@behavioral-agentic-design-system/core 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/package.json +17 -3
  2. package/scripts/a11y-lint.cjs +78 -15
  3. package/scripts/bads-sync.mjs +1 -1
  4. package/scripts/build-tokens.cjs +122 -7
  5. package/scripts/check-dark-contrast.mjs +204 -0
  6. package/scripts/check-flush-edges.mjs +245 -0
  7. package/scripts/design-system-advisory/README.md +239 -0
  8. package/scripts/design-system-advisory/check-copy-punctuation.mjs +44 -0
  9. package/scripts/design-system-advisory/check-even-padding.mjs +35 -0
  10. package/scripts/design-system-advisory/check-hand-built-button.mjs +46 -0
  11. package/scripts/design-system-advisory/check-html-nesting.mjs +51 -0
  12. package/scripts/design-system-advisory/check-icon-sizing.mjs +79 -0
  13. package/scripts/design-system-advisory/check-label-case.mjs +92 -0
  14. package/scripts/design-system-advisory/check-native-form-controls.mjs +53 -0
  15. package/scripts/design-system-advisory/check-radius.mjs +56 -0
  16. package/scripts/design-system-advisory/check-raw-values.mjs +61 -0
  17. package/scripts/design-system-advisory/check-small-text.mjs +72 -0
  18. package/scripts/design-system-advisory/check-tap-target.mjs +70 -0
  19. package/scripts/design-system-advisory/defaults.mjs +90 -0
  20. package/scripts/design-system-advisory/fixtures/clean.tsx.fixture +12 -0
  21. package/scripts/design-system-advisory/fixtures/violations.tsx.fixture +19 -0
  22. package/scripts/design-system-advisory/lib.mjs +255 -0
  23. package/scripts/design-system-advisory/run.mjs +189 -0
  24. package/scripts/design-system-advisory/workflow.yml +82 -0
  25. package/scripts/lib/copy-strings.mjs +146 -0
  26. package/scripts/lib/dark-contrast.mjs +120 -0
  27. package/scripts/lib/flush-edges.mjs +294 -0
  28. package/scripts/lib/lab-lint.mjs +62 -0
  29. package/scripts/lib/mount-page.mjs +25 -0
  30. package/scripts/lib/source-scan.mjs +173 -0
  31. package/scripts/lib/tells.mjs +240 -2
  32. package/scripts/lint-arbitrary-tokens.mjs +47 -0
  33. package/scripts/lint-component-token-refs.mjs +63 -0
  34. package/scripts/lint-content-hierarchy.mjs +114 -0
  35. package/scripts/lint-control-baseline.mjs +72 -0
  36. package/scripts/lint-copy-punctuation.mjs +60 -0
  37. package/scripts/lint-even-padding.mjs +58 -0
  38. package/scripts/lint-label-case.mjs +219 -0
  39. package/scripts/lint-microanimation.mjs +2 -2
  40. package/scripts/lint-proximity.mjs +181 -0
  41. package/scripts/lint-slop.mjs +1 -1
  42. package/scripts/lint-spacing-scale.mjs +78 -0
  43. package/scripts/lint-target-size.cjs +132 -0
  44. package/scripts/lint-token-primitives.mjs +307 -0
  45. package/scripts/size-audit.cjs +2 -2
  46. package/scripts/ux-tells.mjs +8 -6
  47. package/scripts/wcag-audit.cjs +25 -4
  48. package/src/api/layers/file.ts +2 -0
  49. package/src/api/site-auth.ts +14 -2
  50. package/src/app/preview/components/page.tsx +94 -14
  51. package/src/app/preview/sticker-sheet/page.tsx +329 -0
  52. package/src/app/preview/sticker-sheet/specimens.tsx +296 -0
  53. package/src/app/shell.tsx +4 -3
  54. package/src/components/Foundations/Colors.stories.tsx +119 -8
  55. package/src/components/home-tab.tsx +6 -1
  56. package/src/components/onboarding-wizard.tsx +1 -1
  57. package/src/components/ui/avatar.tsx +4 -0
  58. package/src/components/ui/chart.tsx +134 -42
  59. package/src/components/ui/checkbox-group.tsx +1 -1
  60. package/src/components/ui/checkbox.tsx +1 -1
  61. package/src/components/ui/combobox.tsx +1 -0
  62. package/src/components/ui/command.tsx +1 -1
  63. package/src/components/ui/date-picker.tsx +2 -0
  64. package/src/components/ui/date-range-picker.tsx +4 -0
  65. package/src/components/ui/file-upload.tsx +21 -2
  66. package/src/components/ui/heatmap.tsx +3 -1
  67. package/src/components/ui/input-group.tsx +5 -2
  68. package/src/components/ui/multi-select.tsx +1 -0
  69. package/src/components/ui/radio-group.tsx +2 -2
  70. package/src/components/ui/sparkline.tsx +33 -4
  71. package/src/components/ui/spinner.tsx +23 -4
  72. package/src/components/ui/table.tsx +9 -0
  73. package/src/components/ui/week-picker.tsx +0 -12
  74. package/src/data/component-added.json +8 -0
  75. package/src/data/docs-index.ts +22 -1
  76. package/src/data/history.json +161 -161
  77. package/src/data/sticker-sheet.json +9244 -0
  78. package/src/docs-trace-globs.json +1 -0
  79. package/src/lib/chart-motion.ts +41 -0
  80. package/src/lib/get-icon-color.ts +1 -1
  81. package/src/stories/Accordion.stories.tsx +7 -0
  82. package/src/stories/ActionBar.stories.tsx +5 -0
  83. package/src/stories/Affix.stories.tsx +4 -0
  84. package/src/stories/AiBadge.stories.tsx +9 -7
  85. package/src/stories/Alert.stories.tsx +13 -0
  86. package/src/stories/AlertDialog.stories.tsx +4 -0
  87. package/src/stories/Anchor.stories.tsx +5 -0
  88. package/src/stories/AngleSlider.stories.tsx +6 -3
  89. package/src/stories/AspectRatio.stories.tsx +4 -0
  90. package/src/stories/Autocomplete.stories.tsx +6 -0
  91. package/src/stories/Avatar.stories.tsx +10 -0
  92. package/src/stories/Badge.stories.tsx +14 -6
  93. package/src/stories/Blockquote.stories.tsx +6 -0
  94. package/src/stories/BottomNavigation.stories.tsx +4 -0
  95. package/src/stories/Breadcrumb.stories.tsx +3 -0
  96. package/src/stories/Burger.stories.tsx +1 -0
  97. package/src/stories/Button.stories.tsx +24 -0
  98. package/src/stories/ButtonGroup.stories.tsx +9 -0
  99. package/src/stories/Calendar.stories.tsx +3 -0
  100. package/src/stories/Card.stories.tsx +4 -0
  101. package/src/stories/Carousel.stories.tsx +6 -0
  102. package/src/stories/Cascader.stories.tsx +4 -0
  103. package/src/stories/Chart.stories.tsx +46 -1
  104. package/src/stories/ChatBubble.stories.tsx +8 -2
  105. package/src/stories/ChatMarker.stories.tsx +1 -0
  106. package/src/stories/Checkbox.stories.tsx +40 -0
  107. package/src/stories/CheckboxCard.stories.tsx +8 -0
  108. package/src/stories/CheckboxGroup.stories.tsx +19 -0
  109. package/src/stories/Chip.stories.tsx +10 -19
  110. package/src/stories/CircularProgress.stories.tsx +13 -27
  111. package/src/stories/Clipboard.stories.tsx +6 -0
  112. package/src/stories/CloseButton.stories.tsx +6 -4
  113. package/src/stories/Code.stories.tsx +8 -1
  114. package/src/stories/Collapsible.stories.tsx +2 -0
  115. package/src/stories/ColorPicker.stories.tsx +6 -0
  116. package/src/stories/ColorSwatch.stories.tsx +1 -0
  117. package/src/stories/Combobox.stories.tsx +9 -0
  118. package/src/stories/Command.stories.tsx +2 -0
  119. package/src/stories/Container.stories.tsx +8 -0
  120. package/src/stories/ContextMenu.stories.tsx +9 -0
  121. package/src/stories/CopyButton.stories.tsx +12 -36
  122. package/src/stories/DataList.stories.tsx +8 -0
  123. package/src/stories/DataTable.stories.tsx +9 -0
  124. package/src/stories/DateField.stories.tsx +7 -0
  125. package/src/stories/DatePicker.stories.tsx +34 -0
  126. package/src/stories/DateRangePicker.stories.tsx +32 -0
  127. package/src/stories/Dialog.stories.tsx +8 -0
  128. package/src/stories/Drawer.stories.tsx +6 -0
  129. package/src/stories/DropdownMenu.stories.tsx +2 -0
  130. package/src/stories/Editable.stories.tsx +10 -0
  131. package/src/stories/EmptyState.stories.tsx +9 -0
  132. package/src/stories/Field.stories.tsx +7 -0
  133. package/src/stories/Fieldset.stories.tsx +8 -0
  134. package/src/stories/FileButton.stories.tsx +4 -0
  135. package/src/stories/FileUpload.stories.tsx +16 -17
  136. package/src/stories/FloatLabel.stories.tsx +3 -8
  137. package/src/stories/FloatingActionButton.stories.tsx +10 -0
  138. package/src/stories/FloatingIndicator.stories.tsx +4 -0
  139. package/src/stories/FloatingPanel.stories.tsx +6 -0
  140. package/src/stories/FocusTrap.stories.tsx +5 -0
  141. package/src/stories/FormatByte.stories.tsx +6 -0
  142. package/src/stories/FormatDate.stories.tsx +8 -0
  143. package/src/stories/FormatNumber.stories.tsx +9 -0
  144. package/src/stories/Heatmap.stories.tsx +11 -0
  145. package/src/stories/Highlight.stories.tsx +6 -0
  146. package/src/stories/HoverCard.stories.tsx +4 -0
  147. package/src/stories/Image.stories.tsx +9 -0
  148. package/src/stories/Indicator.stories.tsx +19 -0
  149. package/src/stories/Input.stories.tsx +7 -0
  150. package/src/stories/InputClearButton.stories.tsx +3 -0
  151. package/src/stories/InputGroup.stories.tsx +40 -0
  152. package/src/stories/Kbd.stories.tsx +7 -1
  153. package/src/stories/KeyboardShortcut.stories.tsx +2 -0
  154. package/src/stories/Label.stories.tsx +2 -0
  155. package/src/stories/Link.stories.tsx +9 -0
  156. package/src/stories/List.stories.tsx +8 -0
  157. package/src/stories/Listbox.stories.tsx +1 -0
  158. package/src/stories/LoadingDots.stories.tsx +5 -3
  159. package/src/stories/LoadingOverlay.stories.tsx +5 -1
  160. package/src/stories/Mark.stories.tsx +5 -0
  161. package/src/stories/Marquee.stories.tsx +4 -0
  162. package/src/stories/Masonry.stories.tsx +5 -0
  163. package/src/stories/Menubar.stories.tsx +3 -0
  164. package/src/stories/Meter.stories.tsx +11 -17
  165. package/src/stories/MonthPicker.stories.tsx +5 -1
  166. package/src/stories/MotionToggle.stories.tsx +1 -0
  167. package/src/stories/MultiSelect.stories.tsx +9 -0
  168. package/src/stories/NativeSelect.stories.tsx +1 -0
  169. package/src/stories/NavLink.stories.tsx +7 -0
  170. package/src/stories/NavigationMenu.stories.tsx +5 -0
  171. package/src/stories/NavigationRail.stories.tsx +10 -0
  172. package/src/stories/Notification.stories.tsx +13 -34
  173. package/src/stories/NumberInput.stories.tsx +8 -1
  174. package/src/stories/Overlay.stories.tsx +5 -1
  175. package/src/stories/Pagination.stories.tsx +8 -0
  176. package/src/stories/PasswordInput.stories.tsx +2 -0
  177. package/src/stories/PinInput.stories.tsx +9 -2
  178. package/src/stories/Popover.stories.tsx +2 -0
  179. package/src/stories/Progress.stories.tsx +6 -1
  180. package/src/stories/Prose.stories.tsx +8 -0
  181. package/src/stories/QrCode.stories.tsx +2 -0
  182. package/src/stories/Questionnaire.stories.tsx +7 -0
  183. package/src/stories/RadioGroup.stories.tsx +40 -0
  184. package/src/stories/RatingGroup.stories.tsx +8 -4
  185. package/src/stories/Resizable.stories.tsx +4 -2
  186. package/src/stories/Result.stories.tsx +3 -0
  187. package/src/stories/Reveal.stories.tsx +2 -0
  188. package/src/stories/RollingNumber.stories.tsx +5 -0
  189. package/src/stories/ScrollArea.stories.tsx +3 -1
  190. package/src/stories/SearchInput.stories.tsx +8 -6
  191. package/src/stories/SegmentedControl.stories.tsx +11 -0
  192. package/src/stories/Select.stories.tsx +7 -0
  193. package/src/stories/Separator.stories.tsx +6 -0
  194. package/src/stories/Sheet.stories.tsx +5 -0
  195. package/src/stories/Sidebar.stories.tsx +40 -1
  196. package/src/stories/SimpleGrid.stories.tsx +5 -0
  197. package/src/stories/Skeleton.stories.tsx +8 -0
  198. package/src/stories/SkeletonTable.stories.tsx +6 -5
  199. package/src/stories/SkipLink.stories.tsx +3 -0
  200. package/src/stories/Slider.stories.tsx +2 -1
  201. package/src/stories/Sonner.stories.tsx +7 -0
  202. package/src/stories/Sparkline.stories.tsx +14 -1
  203. package/src/stories/Spinner.stories.tsx +20 -10
  204. package/src/stories/Spoiler.stories.tsx +5 -0
  205. package/src/stories/Squircle.stories.tsx +7 -0
  206. package/src/stories/Stack.stories.tsx +7 -0
  207. package/src/stories/StatusBadge.stories.tsx +12 -6
  208. package/src/stories/Stepper.stories.tsx +5 -0
  209. package/src/stories/Switch.stories.tsx +4 -0
  210. package/src/stories/Table.stories.tsx +10 -1
  211. package/src/stories/Tabs.stories.tsx +8 -0
  212. package/src/stories/Tag.stories.tsx +13 -5
  213. package/src/stories/TagsInput.stories.tsx +13 -0
  214. package/src/stories/Text.stories.tsx +12 -0
  215. package/src/stories/Textarea.stories.tsx +9 -0
  216. package/src/stories/ThemeIcon.stories.tsx +6 -3
  217. package/src/stories/TimePicker.stories.tsx +2 -0
  218. package/src/stories/Timeline.stories.tsx +12 -0
  219. package/src/stories/Timer.stories.tsx +4 -0
  220. package/src/stories/Toggle.stories.tsx +7 -5
  221. package/src/stories/ToggleGroup.stories.tsx +5 -0
  222. package/src/stories/ToggleTip.stories.tsx +4 -0
  223. package/src/stories/Toolbar.stories.tsx +6 -0
  224. package/src/stories/Tooltip.stories.tsx +3 -0
  225. package/src/stories/Tour.stories.tsx +3 -0
  226. package/src/stories/TransferList.stories.tsx +3 -0
  227. package/src/stories/TreeSelect.stories.tsx +4 -0
  228. package/src/stories/TreeView.stories.tsx +5 -0
  229. package/src/stories/TypingIndicator.stories.tsx +4 -0
  230. package/src/stories/VisuallyHidden.stories.tsx +3 -0
  231. package/src/stories/Watermark.stories.tsx +6 -0
  232. package/src/stories/WeekPicker.stories.tsx +4 -1
  233. package/src/stories/WordRotate.stories.tsx +5 -0
  234. package/src/stories/YearPicker.stories.tsx +5 -11
  235. package/src/styles.css +50 -2
  236. package/src/tokens.json +4 -4
  237. package/LICENSE +0 -21
@@ -0,0 +1,255 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readdirSync, readFileSync } from "node:fs";
3
+ import { basename, join, relative, resolve } from "node:path";
4
+ import { DEFAULT_MIN_TARGET_PX, DEFAULTS } from "./defaults.mjs";
5
+
6
+ const isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
7
+
8
+ /** Merge `over` onto `base`. Objects merge key by key, arrays and other values replace, `undefined` is skipped. */
9
+ export function mergeSettings(base, over) {
10
+ if (!isPlainObject(over)) return over === undefined ? base : over;
11
+ const out = isPlainObject(base) ? { ...base } : {};
12
+ for (const [key, value] of Object.entries(over)) {
13
+ if (value === undefined) continue;
14
+ out[key] = isPlainObject(value) && isPlainObject(out[key]) ? mergeSettings(out[key], value) : value;
15
+ }
16
+ return out;
17
+ }
18
+
19
+ /**
20
+ * The settings a run uses: the defaults, then each layer in turn (the file, then the flags).
21
+ * `minTargetPx` is the top-level floor in `.bads-lint.json` that lint-target-size also reads. It
22
+ * sets the tap-target floor when the check's own `minPx` is not set.
23
+ */
24
+ export function resolveSettings(...layers) {
25
+ let settings = DEFAULTS;
26
+ for (const layer of layers) settings = mergeSettings(settings, layer ?? {});
27
+ const tap = settings.checks?.["tap-target"];
28
+ if (isPlainObject(tap) && tap.minPx === undefined) {
29
+ settings = mergeSettings(settings, {
30
+ checks: { "tap-target": { minPx: settings.minTargetPx ?? DEFAULT_MIN_TARGET_PX } },
31
+ });
32
+ }
33
+ return settings;
34
+ }
35
+
36
+ export const DEFAULT_SETTINGS = resolveSettings();
37
+
38
+ /**
39
+ * Read the settings file. By default this is `.bads-lint.json` in `root`. Its `designSystemAdvisory`
40
+ * key holds the settings, and its top-level `minTargetPx` is carried along. A missing default file
41
+ * is not an error; a missing `--config` file is.
42
+ */
43
+ export function readSettingsFile({ root = ".", configPath } = {}) {
44
+ const path = configPath ?? join(root, ".bads-lint.json");
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(readFileSync(path, "utf8"));
48
+ } catch (error) {
49
+ if (!configPath && error.code === "ENOENT") return {};
50
+ throw new Error(`design-system-advisory: cannot read settings from ${path}: ${error.message}`);
51
+ }
52
+ const own = isPlainObject(parsed.designSystemAdvisory) ? parsed.designSystemAdvisory : {};
53
+ return Number.isFinite(parsed.minTargetPx) ? { minTargetPx: parsed.minTargetPx, ...own } : own;
54
+ }
55
+
56
+ /** Settings for one check, or `null` when the check is switched off. */
57
+ export function checkSettings(settings, id) {
58
+ const own = settings?.checks?.[id];
59
+ if (own === false) return null;
60
+ return mergeSettings(DEFAULTS.checks[id] ?? {}, own ?? {});
61
+ }
62
+
63
+ /**
64
+ * What a check's `scanLine` or `scanFile` reads: its own settings, with the whole run's settings
65
+ * under `$all`. A check called with none gets the defaults.
66
+ */
67
+ export function settingsFor(own, id) {
68
+ return own ?? { ...checkSettings(DEFAULT_SETTINGS, id), $all: DEFAULT_SETTINGS };
69
+ }
70
+
71
+ const asList =(v) => (v === undefined || v === null ? [] : Array.isArray(v) ? v : [v]);
72
+
73
+ export function isInScope(file, settings = DEFAULT_SETTINGS) {
74
+ const include = asList(settings.include).map((s) => new RegExp(s));
75
+ const exclude = asList(settings.exclude).map((s) => new RegExp(s));
76
+ return include.some((re) => re.test(file)) && !exclude.some((re) => re.test(file));
77
+ }
78
+
79
+ /** Added lines per file, from `git diff -U0` output. */
80
+ export function parseDiff(diffText) {
81
+ const files = [];
82
+ let current = null;
83
+ let lineNo = 0;
84
+ for (const raw of diffText.split("\n")) {
85
+ if (raw.startsWith("+++ ")) {
86
+ const path = raw.slice(4);
87
+ current = path === "/dev/null" ? null : { file: path.replace(/^b\//, ""), lines: [] };
88
+ if (current) files.push(current);
89
+ continue;
90
+ }
91
+ const hunk = raw.match(/^@@ -\S+ \+(\d+)(?:,\d+)? @@/);
92
+ if (hunk) {
93
+ lineNo = Number(hunk[1]);
94
+ continue;
95
+ }
96
+ if (!current || raw.startsWith("---")) continue;
97
+ if (raw.startsWith("+")) {
98
+ current.lines.push({ n: lineNo, text: raw.slice(1) });
99
+ lineNo += 1;
100
+ }
101
+ }
102
+ return files;
103
+ }
104
+
105
+ export function readAllLines(path) {
106
+ const lines = readFileSync(path, "utf8")
107
+ .split("\n")
108
+ .map((text, i) => ({ n: i + 1, text }));
109
+ return { file: path, lines };
110
+ }
111
+
112
+ export function gitDiff(base, head) {
113
+ return execFileSync(
114
+ "git",
115
+ ["diff", "-U0", "--no-color", "--no-ext-diff", "--diff-filter=AM", `${base}...${head}`],
116
+ { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 },
117
+ );
118
+ }
119
+
120
+ const COMMENT_LINE = /^\s*(\/\/|\/\*|\*|\{\s*\/\*)/;
121
+
122
+ export function isCommentLine(text) {
123
+ return COMMENT_LINE.test(text);
124
+ }
125
+
126
+ /**
127
+ * Does this text carry the marker WITH a reason? `type-scale-ok: hint under a field` does;
128
+ * a bare `type-scale-ok` does not, so an exemption always says why.
129
+ */
130
+ export function carriesMarker(text, marker) {
131
+ /* A marker may be declared with or without its colon. */
132
+ const name = marker.replace(/:$/, "");
133
+ const at = text.indexOf(name);
134
+ if (at === -1) return false;
135
+ return /^\s*:\s*[^\s*/}]/.test(text.slice(at + name.length));
136
+ }
137
+
138
+ /** A marker comment, with a reason, on the same line or on the line above exempts the line. */
139
+ export function hasMarker(lines, index, marker) {
140
+ return (
141
+ carriesMarker(lines[index].text, marker) ||
142
+ (index > 0 &&
143
+ lines[index - 1].n === lines[index].n - 1 &&
144
+ carriesMarker(lines[index - 1].text, marker))
145
+ );
146
+ }
147
+
148
+ const fullTextCache = new Map();
149
+
150
+ /** The whole file, read once per run however many checks ask for it. `null` if it cannot be read. */
151
+ export function readFullText(file) {
152
+ if (fullTextCache.has(file)) return fullTextCache.get(file);
153
+ let text = null;
154
+ try {
155
+ text = readFileSync(file, "utf8");
156
+ } catch {
157
+ text = null;
158
+ }
159
+ fullTextCache.set(file, text);
160
+ return text;
161
+ }
162
+
163
+ /**
164
+ * Run each check over each file's added lines.
165
+ *
166
+ * A check is an object with `id`, `title`, `marker` and one or both of:
167
+ * scanLine(text, settings) -> hits for a single added line
168
+ * scanFile({ file, lines, text, settings }) -> hits for checks that need more than one line
169
+ * (a JSX element, a block). `lines` are the added
170
+ * lines, `text` is the whole file or null when it
171
+ * cannot be read. Each hit carries `line`. Hits on
172
+ * lines the PR did not add are dropped.
173
+ * `settings` is the check's own settings (see `checkSettings`). A check switched off with
174
+ * `checks: { "<id>": false }` does not run. A hit is `{ found, message, fix }`.
175
+ */
176
+ export function scanFiles(files, checks, settings = DEFAULT_SETTINGS) {
177
+ const findings = [];
178
+ const active = checks
179
+ .map((check) => ({ check, own: checkSettings(settings, check.id) }))
180
+ .filter(({ own }) => own !== null)
181
+ .map(({ check, own }) => ({ check, own: settingsFor({ ...own, $all: settings }, check.id) }));
182
+ const lineChecks = active.filter(({ check }) => typeof check.scanLine === "function");
183
+ const fileChecks = active.filter(({ check }) => typeof check.scanFile === "function");
184
+ for (const { file, lines } of files) {
185
+ lines.forEach((line, index) => {
186
+ if (isCommentLine(line.text)) return;
187
+ for (const { check, own } of lineChecks) {
188
+ if (hasMarker(lines, index, check.marker)) continue;
189
+ for (const hit of check.scanLine(line.text, own)) {
190
+ findings.push({ check: check.id, file, line: line.n, ...hit });
191
+ }
192
+ }
193
+ });
194
+ if (fileChecks.length === 0) continue;
195
+ const text = readFullText(file);
196
+ const added = new Set(lines.map((l) => l.n));
197
+ const all = text === null ? null : text.split("\n");
198
+ const marked = (n, marker) =>
199
+ all
200
+ ? carriesMarker(all[n - 1] ?? "", marker) || carriesMarker(all[n - 2] ?? "", marker)
201
+ : lines.some((l) => (l.n === n || l.n === n - 1) && carriesMarker(l.text, marker));
202
+ for (const { check, own } of fileChecks) {
203
+ for (const hit of check.scanFile({ file, lines, text, settings: own })) {
204
+ if (!added.has(hit.line) || marked(hit.line, check.marker)) continue;
205
+ findings.push({ check: check.id, file, ...hit });
206
+ }
207
+ }
208
+ }
209
+ return findings;
210
+ }
211
+
212
+ const NOT_A_COMPONENT = /(\.stories\.|\.test\.|\.spec\.|\.d\.ts$|\/__tests__\/|\/__mocks__\/|\.css$)/;
213
+
214
+ function walk(dir) {
215
+ const out = [];
216
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
217
+ const path = join(dir, entry.name);
218
+ if (entry.isDirectory()) out.push(...walk(path));
219
+ else out.push(path);
220
+ }
221
+ return out;
222
+ }
223
+
224
+ /**
225
+ * Every component file under the given roots: `{ name, layer, file, importPath }`.
226
+ * A root is `{ dir, importPrefix, layer? }`; `layer` defaults to the folder name. `name` is the file
227
+ * name without extension and without a `.shadcn` suffix (`button`, `avatar`); an `index.tsx` takes
228
+ * its folder's name. For checks that need to know what already exists.
229
+ */
230
+ export function listComponents(roots = DEFAULT_SETTINGS.componentRoots, root = ".") {
231
+ const components = [];
232
+ for (const { dir, importPrefix, layer = basename(dir) } of roots) {
233
+ let files;
234
+ try {
235
+ files = walk(resolve(root, dir));
236
+ } catch {
237
+ continue;
238
+ }
239
+ for (const abs of files.sort()) {
240
+ if (!/\.tsx$/.test(abs) || NOT_A_COMPONENT.test(abs)) continue;
241
+ const rel = relative(resolve(root, dir), abs).replace(/\\/g, "/");
242
+ const noExt = rel.replace(/\.tsx$/, "");
243
+ const parts = noExt.split("/");
244
+ const last = parts[parts.length - 1];
245
+ const base = last === "index" ? (parts[parts.length - 2] ?? basename(dir)) : last;
246
+ components.push({
247
+ name: base.replace(/\.shadcn$/, ""),
248
+ layer,
249
+ file: `${dir}/${rel}`,
250
+ importPath: `${importPrefix}/${noExt}`,
251
+ });
252
+ }
253
+ }
254
+ return components;
255
+ }
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Advisory design system checks. Reports findings on lines a PR adds. Exits 0 unless --strict is
4
+ * passed, so it never blocks a merge. Imports only Node built-ins, so CI needs no install to run it.
5
+ *
6
+ * bads-ds-advisory PR-style: merge-base with origin/main..HEAD
7
+ * bads-ds-advisory --base=<sha> --head=<sha>
8
+ * bads-ds-advisory --file=<path> [--file=<path>] scan whole files (testing)
9
+ * --format=text|markdown|github default text
10
+ * --out=<file> write the report to a file
11
+ * --strict exit 1 on findings (for when a check graduates to blocking)
12
+ *
13
+ * Settings come from the `designSystemAdvisory` key of `.bads-lint.json` at the repo root, or from
14
+ * `--config=<file>`. Flags win over the file:
15
+ * --include=<regex> --exclude=<regex> replace the scope (repeatable)
16
+ * --off=<check-id> switch a check off (repeatable)
17
+ * --base-ref=<ref> the branch to compare with, default origin/main
18
+ * --set=<dotted.path>=<value> any setting; the value is read as JSON, or as text
19
+ *
20
+ * See README.md in this folder.
21
+ */
22
+ import { execFileSync } from "node:child_process";
23
+ import { readdirSync, realpathSync, writeFileSync } from "node:fs";
24
+ import { dirname, join } from "node:path";
25
+ import process from "node:process";
26
+ import { fileURLToPath, pathToFileURL } from "node:url";
27
+ import {
28
+ DEFAULT_SETTINGS,
29
+ gitDiff,
30
+ isInScope,
31
+ parseDiff,
32
+ readAllLines,
33
+ readSettingsFile,
34
+ resolveSettings,
35
+ scanFiles,
36
+ } from "./lib.mjs";
37
+
38
+ /**
39
+ * Every `check-*.mjs` in this folder is a check. A file may export one or more check objects;
40
+ * anything without an `id` and a `scanLine` or `scanFile` is ignored. Adding a check means adding
41
+ * a file here, with nothing to register. Reports list checks by `order`, then by `id`.
42
+ */
43
+ async function loadChecks() {
44
+ const dir = dirname(fileURLToPath(import.meta.url));
45
+ const checks = [];
46
+ for (const name of readdirSync(dir).filter((f) => /^check-.+\.mjs$/.test(f)).sort()) {
47
+ const mod = await import(pathToFileURL(join(dir, name)).href);
48
+ for (const value of Object.values(mod)) {
49
+ if (
50
+ value &&
51
+ typeof value === "object" &&
52
+ typeof value.id === "string" &&
53
+ (typeof value.scanLine === "function" || typeof value.scanFile === "function")
54
+ ) {
55
+ checks.push(value);
56
+ }
57
+ }
58
+ }
59
+ return checks.sort((a, b) => (a.order ?? 100) - (b.order ?? 100) || a.id.localeCompare(b.id));
60
+ }
61
+
62
+ export const CHECKS = await loadChecks();
63
+ export const COMMENT_MARKER = "<!-- design-system-advisory -->";
64
+
65
+ const clean = (s) => String(s).replace(/`/g, "'").replace(/\|/g, "\\|").slice(0, 160);
66
+
67
+ export function render(findings, format, scannedFiles, settings = DEFAULT_SETTINGS) {
68
+ if (format === "github") {
69
+ return findings
70
+ .map((f) =>
71
+ `::warning file=${f.file},line=${f.line},title=Design system (${f.check})::${f.message} ${f.fix}`.replace(
72
+ /\r?\n/g,
73
+ " ",
74
+ ),
75
+ )
76
+ .join("\n");
77
+ }
78
+ if (format === "markdown") {
79
+ if (findings.length === 0) {
80
+ return `${COMMENT_MARKER}\n**Design system checks (advisory):** no findings in ${scannedFiles} scanned file(s).`;
81
+ }
82
+ const byCheck = new Map();
83
+ for (const f of findings) byCheck.set(f.check, [...(byCheck.get(f.check) ?? []), f]);
84
+ const rules = settings.rulesDoc ? ` Rules: \`${settings.rulesDoc}\`.` : "";
85
+ const readme = settings.readmePath ? ` How to reproduce locally: \`${settings.readmePath}\`.` : "";
86
+ const out = [
87
+ COMMENT_MARKER,
88
+ `**Design system checks (advisory):** ${findings.length} finding(s). These do not block the merge.${rules}${readme}`,
89
+ ];
90
+ for (const check of CHECKS) {
91
+ const hits = byCheck.get(check.id);
92
+ if (!hits) continue;
93
+ out.push("", `### ${check.title} (${hits.length})`, "", "| File | Line | Found | Fix |", "| --- | --- | --- | --- |");
94
+ for (const f of hits.slice(0, 50)) {
95
+ out.push(`| \`${clean(f.file)}\` | ${f.line} | \`${clean(f.found)}\` | ${clean(f.fix)} |`);
96
+ }
97
+ if (hits.length > 50) out.push("", `...and ${hits.length - 50} more. Run the check locally for the full list.`);
98
+ }
99
+ out.push(
100
+ "",
101
+ "Intentional? Add the marker comment named in the fix (`type-scale-ok: who chose it and why` or `raw-value-ok: why`).",
102
+ );
103
+ return out.join("\n");
104
+ }
105
+ if (findings.length === 0) return `No findings in ${scannedFiles} scanned file(s).`;
106
+ const out = [];
107
+ for (const f of findings) {
108
+ out.push(`${f.file}:${f.line} [${f.check}] ${f.found}`, ` ${f.message}`, ` Fix: ${f.fix}`);
109
+ }
110
+ out.push("", `${findings.length} finding(s) in ${scannedFiles} scanned file(s). Advisory: exit code is 0.`);
111
+ return out.join("\n");
112
+ }
113
+
114
+ /** Read a `--set=a.b.c=value` into `{ a: { b: { c: value } } }`. The value is JSON when it parses. */
115
+ function setFlag(spec) {
116
+ const eq = spec.indexOf("=");
117
+ if (eq < 1) throw new Error(`design-system-advisory: --set needs <path>=<value>, got "${spec}"`);
118
+ const raw = spec.slice(eq + 1);
119
+ let value;
120
+ try {
121
+ value = JSON.parse(raw);
122
+ } catch {
123
+ value = raw;
124
+ }
125
+ const keys = spec.slice(0, eq).split(".");
126
+ const out = {};
127
+ let at = out;
128
+ keys.forEach((k, i) => {
129
+ at[k] = i === keys.length - 1 ? value : {};
130
+ at = at[k];
131
+ });
132
+ return out;
133
+ }
134
+
135
+ /** Turn the command-line flags into settings layers, in the order they apply. */
136
+ export function flagSettings(args) {
137
+ const all = (name) => args.filter((a) => a.startsWith(`--${name}=`)).map((a) => a.slice(name.length + 3));
138
+ const layers = [];
139
+ const include = all("include");
140
+ const exclude = all("exclude");
141
+ const off = all("off");
142
+ const baseRef = all("base-ref").at(-1);
143
+ if (include.length) layers.push({ include });
144
+ if (exclude.length) layers.push({ exclude });
145
+ if (off.length) layers.push({ checks: Object.fromEntries(off.map((id) => [id, false])) });
146
+ if (baseRef) layers.push({ baseRef });
147
+ for (const spec of all("set")) layers.push(setFlag(spec));
148
+ return layers;
149
+ }
150
+
151
+ /** The settings a run uses: defaults, then `.bads-lint.json` (or `--config`), then the flags. */
152
+ export function loadSettings(args, root = process.cwd()) {
153
+ const configPath = args.find((a) => a.startsWith("--config="))?.slice("--config=".length);
154
+ return resolveSettings(readSettingsFile({ root, configPath }), ...flagSettings(args));
155
+ }
156
+
157
+ function main(args) {
158
+ const flag = (name) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3);
159
+ const settings = loadSettings(args);
160
+ const format = flag("format") ?? "text";
161
+ const fileArgs = args.filter((a) => a.startsWith("--file=")).map((a) => a.slice("--file=".length));
162
+ let files;
163
+ if (fileArgs.length > 0) {
164
+ files = fileArgs.map(readAllLines);
165
+ } else {
166
+ const head = flag("head") ?? "HEAD";
167
+ const base =
168
+ flag("base") ?? execFileSync("git", ["merge-base", settings.baseRef, head], { encoding: "utf8" }).trim();
169
+ files = parseDiff(gitDiff(base, head)).filter((f) => isInScope(f.file, settings));
170
+ }
171
+ const findings = scanFiles(files, CHECKS, settings);
172
+ const report = render(findings, format, files.length, settings);
173
+ if (flag("out")) writeFileSync(flag("out"), `${report}\n`);
174
+ else console.log(report);
175
+ if (process.env.GITHUB_OUTPUT) {
176
+ writeFileSync(process.env.GITHUB_OUTPUT, `count=${findings.length}\n`, { flag: "a" });
177
+ }
178
+ process.exit(args.includes("--strict") && findings.length > 0 ? 1 : 0);
179
+ }
180
+
181
+ /* Compare real paths: started through a symlink (/tmp is one on a Mac, and npm's .bin is one) the two spellings differ and nothing would run. */
182
+ const isMain = (() => {
183
+ try {
184
+ return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
185
+ } catch {
186
+ return false;
187
+ }
188
+ })();
189
+ if (isMain) main(process.argv.slice(2));
@@ -0,0 +1,82 @@
1
+ name: Design system checks (advisory)
2
+
3
+ # Copy this file to .github/workflows/design-system-advisory.yml in your repo.
4
+ #
5
+ # It reports design system findings on the lines a PR adds. Advisory: the job is
6
+ # continue-on-error and the script exits 0, so it never blocks a merge.
7
+ #
8
+ # Needs @behavioral-agentic-design-system/core as a dependency of the repo root, so that
9
+ # `npx bads-ds-advisory` finds the installed bin. Settings: the designSystemAdvisory key in
10
+ # .bads-lint.json at your repo root. Full guide:
11
+ # node_modules/@behavioral-agentic-design-system/core/scripts/design-system-advisory/README.md
12
+
13
+ on:
14
+ pull_request:
15
+ types:
16
+ - opened
17
+ - reopened
18
+ - synchronize
19
+
20
+ permissions:
21
+ contents: read
22
+ pull-requests: write
23
+
24
+ concurrency:
25
+ group: design-system-advisory-${{ github.event.pull_request.number || github.ref }}
26
+ cancel-in-progress: true
27
+
28
+ jobs:
29
+ advisory:
30
+ runs-on: ubuntu-latest
31
+ timeout-minutes: 15
32
+ continue-on-error: true
33
+ env:
34
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
35
+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}
36
+ PR_NUMBER: ${{ github.event.pull_request.number }}
37
+ GH_TOKEN: ${{ github.token }}
38
+ REPO: ${{ github.repository }}
39
+ steps:
40
+ - uses: actions/checkout@v7
41
+ with:
42
+ fetch-depth: 0
43
+
44
+ - uses: actions/setup-node@v7
45
+ with:
46
+ node-version: 22
47
+
48
+ # Replace this step with your repo's own install command if it has one.
49
+ - name: Install dependencies
50
+ run: |
51
+ if [ -f pnpm-lock.yaml ]; then corepack enable && pnpm install --frozen-lockfile
52
+ elif [ -f yarn.lock ]; then corepack enable && yarn install --immutable
53
+ else npm ci
54
+ fi
55
+
56
+ - name: Annotate findings on the diff
57
+ run: npx bads-ds-advisory --base="$BASE_SHA" --head="$HEAD_SHA" --format=github
58
+
59
+ - name: Build the report
60
+ id: report
61
+ run: |
62
+ npx bads-ds-advisory --base="$BASE_SHA" --head="$HEAD_SHA" --format=markdown --out="$RUNNER_TEMP/report.md"
63
+ cat "$RUNNER_TEMP/report.md" >> "$GITHUB_STEP_SUMMARY"
64
+
65
+ - name: Update the PR comment
66
+ # Fork PRs get a read-only token. The annotations and the job summary
67
+ # still show the findings, so a failed comment is fine.
68
+ continue-on-error: true
69
+ run: |
70
+ MARKER='<!-- design-system-advisory -->'
71
+ EXISTING=$(gh api "repos/$REPO/issues/$PR_NUMBER/comments" --paginate \
72
+ --jq ".[] | select(.body | contains(\"$MARKER\")) | .id" | head -1)
73
+ if [ "${{ steps.report.outputs.count }}" = "0" ]; then
74
+ # No findings. Only touch the comment if an earlier run left one.
75
+ if [ -n "$EXISTING" ]; then
76
+ gh api -X PATCH "repos/$REPO/issues/comments/$EXISTING" -F body=@"$RUNNER_TEMP/report.md"
77
+ fi
78
+ elif [ -n "$EXISTING" ]; then
79
+ gh api -X PATCH "repos/$REPO/issues/comments/$EXISTING" -F body=@"$RUNNER_TEMP/report.md"
80
+ else
81
+ gh api -X POST "repos/$REPO/issues/$PR_NUMBER/comments" -F body=@"$RUNNER_TEMP/report.md"
82
+ fi
@@ -0,0 +1,146 @@
1
+ /**
2
+ * copy-strings: what counts as user-facing copy, shared by every lint that reads it.
3
+ *
4
+ * WHY ONE MODULE. Two lints that enforce different rules about the same thing (the words a person
5
+ * actually sees) must agree on where those words live. If each carried its own idea, they would drift,
6
+ * and the day one learned about a new place copy hides (a `.ts` copy file, a bullet list) the other
7
+ * would still be blind to it.
8
+ *
9
+ * WHAT COUNTS AS COPY
10
+ * 1. JSX text nodes: words between tags.
11
+ * 2. String values of copy-carrying props and object keys: `title="..."`, `title: "..."`. The key
12
+ * list is COPY_NAMES.
13
+ * 3. Items of a string list under a copy-carrying name: `bullets: ["..."]`, and a SCREAMING_CASE
14
+ * constant whose name says it holds copy, `MODE_BULLETS = { a: ["..."] }`. Only direct items of
15
+ * an array count; a string inside an object inside the array (`options: [{ value: "x" }]`) is
16
+ * data, not copy.
17
+ *
18
+ * NOT comments: the prose written for whoever reads the source next. Blanking them first,
19
+ * length-preserving so offsets still line up, is what makes any of these rules enforceable at all.
20
+ */
21
+ export const COPY_NAMES = [
22
+ "title", "label", "body", "done", "cta", "ctaLabel", "ctaText",
23
+ "description", "placeholder", "alt", "heading", "subheading", "message", "detail",
24
+ "text", "caption", "helperText", "tooltip", "eyebrow",
25
+ "question", "answer", "hint", "meta", "short", "result", "callout",
26
+ ];
27
+
28
+ /** Names whose value is a LIST of copy strings rather than one string. */
29
+ export const LIST_NAMES = ["bullets", "options", "checks"];
30
+
31
+ const NAMES = COPY_NAMES.join("|");
32
+ const AS_PROP = new RegExp(`(?<![\\w-])(?:${NAMES})\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "g");
33
+ const AS_KEY = new RegExp(`(?<![\\w-])(?:${NAMES})\\s*:\\s*(?:"([^"]*)"|'([^']*)'|\`([^\`]*)\`)`, "g");
34
+ /**
35
+ * The head of a copy list: a copy name, a list name, or a SCREAMING_CASE
36
+ * constant ending in BULLETS / LINES / OPTIONS, followed by `:` or `=` and an
37
+ * opening `[` or `{`. The block itself is read by `listItems`.
38
+ */
39
+ const LIST_HEAD = new RegExp(
40
+ `(?<![\\w-])(${NAMES}|${LIST_NAMES.join("|")}|[A-Z][A-Z0-9_]*?(?:BULLETS|LINES|OPTIONS))\\s*[:=]\\s*(?=[\\[{])`,
41
+ "g",
42
+ );
43
+ /** Text between tags, with no braces or tags inside, containing real words. */
44
+ const JSX_TEXT = />\s*([^<>{}\n][^<>{}\n]*?[A-Za-z]{2,}[^<>{}\n]*?)\s*</g;
45
+
46
+ /**
47
+ * Blank comments, keeping length so offsets still line up.
48
+ *
49
+ * A `//` preceded by `:` is left alone, so `https://` inside a string survives.
50
+ */
51
+ export function blankComments(src) {
52
+ const out = src.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "));
53
+ return out.replace(/(^|[^:])\/\/[^\n]*/g, (m, p) => p + " ".repeat(m.length - p.length));
54
+ }
55
+
56
+ /**
57
+ * What a string literal actually RENDERS.
58
+ *
59
+ * `"a — b"` in the source is an em dash by the time anyone reads it, the
60
+ * compiler resolves the escape, so testing the raw source would report it as a
61
+ * literal escape and miss the em dash. Exactly backwards. A DOUBLE backslash is
62
+ * the real literal escape: `"a \\u2014 b"` renders the six characters. So those
63
+ * are protected first, then the genuine escapes decoded, then the protection
64
+ * undone.
65
+ */
66
+ export function rendered(text) {
67
+ const MARK = "\u0000";
68
+ return text
69
+ .replace(/\\\\u([0-9a-fA-F]{4})/g, `${MARK}$1`)
70
+ .replace(/\\u([0-9a-fA-F]{4})/g, (_, h) => String.fromCharCode(parseInt(h, 16)))
71
+ .replace(new RegExp(`${MARK}([0-9a-fA-F]{4})`, "g"), "\\u$1");
72
+ }
73
+
74
+ /**
75
+ * Read a balanced `[…]` or `{…}` block starting at `from` and return the string
76
+ * literals that are DIRECT items of an array inside it, with their offsets.
77
+ *
78
+ * A tiny tokenizer rather than a regex, because the thing that matters is
79
+ * nesting: `["a", "b"]` is two copy strings, `[{ value: "a" }]` is none, and
80
+ * `{ guided: ["a"], diy: ["b"] }` is two. Strings are consumed as tokens so a
81
+ * bracket inside one cannot unbalance the walk.
82
+ */
83
+ export function listItems(src, from) {
84
+ const open = src[from];
85
+ if (open !== "[" && open !== "{") return [];
86
+ const stack = [];
87
+ const out = [];
88
+ for (let i = from; i < src.length; i++) {
89
+ const c = src[i];
90
+ if (c === "[" || c === "{") {
91
+ stack.push(c);
92
+ continue;
93
+ }
94
+ if (c === "]" || c === "}") {
95
+ stack.pop();
96
+ if (!stack.length) break;
97
+ continue;
98
+ }
99
+ if (c === '"' || c === "'" || c === "`") {
100
+ const start = i + 1;
101
+ let j = start;
102
+ while (j < src.length && src[j] !== c) {
103
+ if (src[j] === "\\") j++;
104
+ j++;
105
+ }
106
+ if (stack[stack.length - 1] === "[") {
107
+ const val = src.slice(start, j);
108
+ if (val) out.push({ text: rendered(val), index: start });
109
+ }
110
+ i = j;
111
+ }
112
+ }
113
+ return out;
114
+ }
115
+
116
+ /**
117
+ * Every copy string in a comment-blanked source, as `{ text, index }`, where
118
+ * `index` is the offset of the string's first character in `src`.
119
+ */
120
+ export function copyStrings(src) {
121
+ const out = [];
122
+ for (const re of [AS_PROP, AS_KEY]) {
123
+ re.lastIndex = 0;
124
+ let m;
125
+ while ((m = re.exec(src))) {
126
+ const val = m[1] ?? m[2] ?? m[3];
127
+ if (val) out.push({ text: rendered(val), index: m.index });
128
+ }
129
+ }
130
+ LIST_HEAD.lastIndex = 0;
131
+ let m;
132
+ while ((m = LIST_HEAD.exec(src))) {
133
+ const at = m.index + m[0].length;
134
+ const name = m[1];
135
+ /* A `{` block is only read for a SCREAMING_CASE constant, whose name says
136
+ the whole object is copy. `options: { … }` is configuration. */
137
+ if (src[at] === "{" && !/^[A-Z][A-Z0-9_]*$/.test(name)) continue;
138
+ out.push(...listItems(src, at));
139
+ }
140
+ JSX_TEXT.lastIndex = 0;
141
+ while ((m = JSX_TEXT.exec(src))) {
142
+ out.push({ text: m[1], index: m.index + m[0].indexOf(m[1]) });
143
+ }
144
+ return out;
145
+ }
146
+