@behavioral-agentic-design-system/core 0.36.0 → 0.38.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.
@@ -12,22 +12,47 @@
12
12
  * Storybook globs node_modules/@.../core/src/stories/*.stories.tsx and gets
13
13
  * every upstream story automatically on the next @core bump.
14
14
  *
15
+ * A second scan root covers the repo-root components/ directory, the same
16
+ * one `.storybook/main.*` globs (`../components/*.stories.tsx`) in both
17
+ * upstream and every fork. A component at components/<name>.tsx expects a
18
+ * co-located story at components/<PascalCase>.stories.tsx (matching upstream
19
+ * pairs like components/activity-feed.tsx + components/ActivityFeed.stories.tsx),
20
+ * and this also covers exactly one level of subdirectory, the depth at
21
+ * which a fork vendors its own components (components/closedloop/*.tsx),
22
+ * accepting a story at either the co-located subdirectory path or the
23
+ * top-level components/<PascalCase>.stories.tsx path, since only the
24
+ * top-level location is guaranteed to actually render in Storybook today.
25
+ * Content that sits two or more levels deep (components/examples/cards/*.tsx
26
+ * and friends) is out of scope: it backs /preview demo routes, not
27
+ * documented components, and is naturally excluded by the one-level rule
28
+ * rather than by name.
29
+ *
30
+ * A file whose entire body is a re-export (`export { X } from "..."` or
31
+ * `export * from "..."`) is a passthrough shim, not a component definition;
32
+ * there is nothing of its own to write a story about, so it is not counted
33
+ * as a component needing one.
34
+ *
15
35
  * Modes:
16
36
  * pnpm check:stories → precommit mode (staged-only, used by hook)
17
- * pnpm check:stories --all → audit every component (used by CI)
37
+ * pnpm check:stories --all → audit every component (pnpm audit:stories;
38
+ * not currently run by any CI workflow --
39
+ * invoke by hand or wire it into a workflow)
18
40
  *
19
- * On failure, prints violations + the fix command.
41
+ * On failure, prints violations + the fix command. A run that scans every
42
+ * root and finds zero components is itself a failure: a coverage gate that
43
+ * cannot see the code it guards must not report success.
20
44
  */
21
45
 
22
46
  import { execSync } from "node:child_process";
23
- import { existsSync, readdirSync } from "node:fs";
47
+ import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
24
48
  import { join, basename } from "node:path";
25
49
 
26
- const ROOT = process.cwd();
27
- const COMPONENTS_DIR = join(ROOT, "packages/core/src/components/ui");
28
- const STORIES_DIR = join(ROOT, "packages/core/src/stories");
50
+ const UI_REL = "packages/core/src/components/ui";
51
+ const UI_STORIES_REL = "packages/core/src/stories";
52
+ const COMPONENTS_REL = "components";
53
+ const SCAN_DESCRIPTION = `${UI_REL}/ and ${COMPONENTS_REL}/ (top level + one level of subdirectory)`;
29
54
 
30
- const ALL = process.argv.includes("--all");
55
+ const REEXPORT_LINE = /^export\s+(?:\*|\{[^}]*\})\s+from\s+["'][^"']+["'];?$/;
31
56
 
32
57
  function pascal(kebab) {
33
58
  return kebab
@@ -37,80 +62,268 @@ function pascal(kebab) {
37
62
  .join("");
38
63
  }
39
64
 
40
- function componentToStoryPath(componentRel) {
65
+ // A file whose entire non-blank, non-comment content is one or more
66
+ // re-export statements is a passthrough shim (e.g. components/customize-tab.tsx,
67
+ // components/customize/*.tsx), nothing of its own to story-test. The real
68
+ // implementation, and its story obligation, lives wherever it's re-exported
69
+ // from.
70
+ function isBarrelReexport(absPath) {
71
+ let content;
72
+ try {
73
+ content = readFileSync(absPath, "utf8");
74
+ } catch {
75
+ return false;
76
+ }
77
+ const lines = content
78
+ .split("\n")
79
+ .map((l) => l.trim())
80
+ .filter((l) => l.length > 0 && !l.startsWith("//"));
81
+ if (lines.length === 0) return false;
82
+ return lines.every((l) => REEXPORT_LINE.test(l));
83
+ }
84
+
85
+ function uiComponentToStoryPath(componentRel) {
41
86
  // packages/core/src/components/ui/dropdown-menu.tsx
42
87
  // → packages/core/src/stories/DropdownMenu.stories.tsx
43
- return `packages/core/src/stories/${pascal(basename(componentRel))}.stories.tsx`;
88
+ return `${UI_STORIES_REL}/${pascal(basename(componentRel))}.stories.tsx`;
44
89
  }
45
90
 
46
- function listAllComponents() {
47
- if (!existsSync(COMPONENTS_DIR)) return [];
48
- return readdirSync(COMPONENTS_DIR)
91
+ function listUiComponents(root) {
92
+ const dir = join(root, UI_REL);
93
+ if (!existsSync(dir)) return [];
94
+ return readdirSync(dir)
49
95
  .filter((f) => f.endsWith(".tsx"))
50
- .map((f) => `packages/core/src/components/ui/${f}`);
96
+ .map((f) => `${UI_REL}/${f}`);
97
+ }
98
+
99
+ // Top-level components/*.tsx, plus exactly one level of subdirectory
100
+ // (components/<dir>/*.tsx). Deliberately does not recurse further; see the
101
+ // header comment for why that's the right depth.
102
+ function listComponentsRootEntries(root) {
103
+ const dir = join(root, COMPONENTS_REL);
104
+ if (!existsSync(dir)) return [];
105
+ const out = [];
106
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
107
+ if (entry.name.startsWith(".")) continue;
108
+ const entryPath = join(dir, entry.name);
109
+ if (entry.isFile()) {
110
+ if (!entry.name.endsWith(".tsx") || entry.name.endsWith(".stories.tsx")) continue;
111
+ if (isBarrelReexport(entryPath)) continue;
112
+ out.push(`${COMPONENTS_REL}/${entry.name}`);
113
+ continue;
114
+ }
115
+ if (!entry.isDirectory()) continue;
116
+ let subEntries;
117
+ try {
118
+ subEntries = readdirSync(entryPath, { withFileTypes: true });
119
+ } catch {
120
+ continue;
121
+ }
122
+ for (const sub of subEntries) {
123
+ if (!sub.isFile()) continue;
124
+ if (!sub.name.endsWith(".tsx") || sub.name.endsWith(".stories.tsx")) continue;
125
+ const subPath = join(entryPath, sub.name);
126
+ if (isBarrelReexport(subPath)) continue;
127
+ out.push(`${COMPONENTS_REL}/${entry.name}/${sub.name}`);
128
+ }
129
+ }
130
+ return out;
131
+ }
132
+
133
+ // componentRel is "components/<name>.tsx" or "components/<subdir>/<name>.tsx".
134
+ // `primary` is the co-located expected path; `alternate` (subdir case only)
135
+ // is the top-level path that Storybook's own glob actually renders.
136
+ function componentsRootStoryPaths(componentRel) {
137
+ const parts = componentRel.split("/");
138
+ const fileName = parts[parts.length - 1];
139
+ const pascalName = pascal(fileName);
140
+ if (parts.length === 2) {
141
+ return { primary: `${COMPONENTS_REL}/${pascalName}.stories.tsx`, alternate: null };
142
+ }
143
+ const subdir = parts[1];
144
+ return {
145
+ primary: `${COMPONENTS_REL}/${subdir}/${pascalName}.stories.tsx`,
146
+ alternate: `${COMPONENTS_REL}/${pascalName}.stories.tsx`,
147
+ };
148
+ }
149
+
150
+ function listAllComponents(root) {
151
+ const out = [];
152
+ for (const rel of listUiComponents(root)) {
153
+ out.push({ component: rel, primary: uiComponentToStoryPath(rel), alternate: null });
154
+ }
155
+ for (const rel of listComponentsRootEntries(root)) {
156
+ const { primary, alternate } = componentsRootStoryPaths(rel);
157
+ out.push({ component: rel, primary, alternate });
158
+ }
159
+ return out;
160
+ }
161
+
162
+ function hasStory(root, entry) {
163
+ const primaryExists = existsSync(join(root, entry.primary));
164
+ const altExists = Boolean(entry.alternate) && existsSync(join(root, entry.alternate));
165
+ return { primaryExists, altExists, covered: primaryExists || altExists };
166
+ }
167
+
168
+ function runAudit(root) {
169
+ const scanned = listAllComponents(root);
170
+ const violations = [];
171
+ for (const c of scanned) {
172
+ const { covered } = hasStory(root, c);
173
+ if (!covered) {
174
+ violations.push({ kind: "missing-story", component: c.component, expected: c.primary, alternate: c.alternate });
175
+ }
176
+ }
177
+ return { scanned, violations };
51
178
  }
52
179
 
53
- function stagedFiles() {
180
+ function stagedFiles(root) {
54
181
  const out = execSync("git diff --cached --name-only --diff-filter=ACMR", {
55
182
  encoding: "utf8",
183
+ cwd: root,
56
184
  });
57
185
  return out.split("\n").filter(Boolean);
58
186
  }
59
187
 
60
- function runAudit() {
61
- const violations = [];
62
- for (const c of listAllComponents()) {
63
- const expected = componentToStoryPath(c);
64
- if (!existsSync(join(ROOT, expected))) {
65
- violations.push({ kind: "missing-story", component: c, expected });
66
- }
188
+ function classifyStagedFile(root, file) {
189
+ if (file.startsWith(`${UI_REL}/`)) {
190
+ if (!file.endsWith(".tsx")) return null;
191
+ return { component: file, primary: uiComponentToStoryPath(file), alternate: null };
192
+ }
193
+ if (file.startsWith(`${COMPONENTS_REL}/`)) {
194
+ if (!file.endsWith(".tsx") || file.endsWith(".stories.tsx")) return null;
195
+ const parts = file.split("/");
196
+ if (parts.length > 3) return null; // deeper than one level of subdirectory, out of scope
197
+ const absPath = join(root, file);
198
+ if (!existsSync(absPath) || isBarrelReexport(absPath)) return null;
199
+ const { primary, alternate } = componentsRootStoryPaths(file);
200
+ return { component: file, primary, alternate };
67
201
  }
68
- return violations;
202
+ return null;
69
203
  }
70
204
 
71
- function runStaged() {
72
- const staged = stagedFiles();
205
+ function runStaged(root) {
206
+ const staged = stagedFiles(root);
73
207
  const stagedSet = new Set(staged);
74
208
  const violations = [];
209
+ let matched = 0;
75
210
 
76
211
  for (const file of staged) {
77
- if (!file.startsWith("packages/core/src/components/ui/")) continue;
78
- if (!file.endsWith(".tsx")) continue;
79
- const expected = componentToStoryPath(file);
80
- if (!existsSync(join(ROOT, expected))) {
81
- violations.push({ kind: "missing-story", component: file, expected });
212
+ const info = classifyStagedFile(root, file);
213
+ if (!info) continue;
214
+ matched++;
215
+ const { primaryExists, covered } = hasStory(root, info);
216
+ if (!covered) {
217
+ violations.push({ kind: "missing-story", component: info.component, expected: info.primary, alternate: info.alternate });
82
218
  continue;
83
219
  }
84
- if (!stagedSet.has(expected)) {
85
- violations.push({ kind: "stale-story", component: file, expected });
220
+ const canonicalExisting = primaryExists ? info.primary : info.alternate;
221
+ if (!stagedSet.has(canonicalExisting)) {
222
+ violations.push({ kind: "stale-story", component: info.component, expected: info.primary, alternate: info.alternate });
86
223
  }
87
224
  }
88
225
 
89
- return violations;
226
+ return { staged, matched, violations };
90
227
  }
91
228
 
92
- const violations = ALL ? runAudit() : runStaged();
229
+ function printViolations(violations) {
230
+ console.error("");
231
+ console.error("✗ Storybook coverage violations:");
232
+ console.error("");
233
+ let anyAlternate = false;
234
+ for (const v of violations) {
235
+ if (v.kind === "missing-story") {
236
+ console.error(` MISSING ${v.component}`);
237
+ if (v.alternate) {
238
+ anyAlternate = true;
239
+ console.error(` → expected story at ${v.expected} (co-located) or ${v.alternate} (top-level)`);
240
+ } else {
241
+ console.error(` → expected story at ${v.expected}`);
242
+ }
243
+ } else if (v.alternate) {
244
+ anyAlternate = true;
245
+ console.error(` STALE ${v.component} was changed but neither ${v.expected} nor ${v.alternate} was`);
246
+ } else {
247
+ console.error(` STALE ${v.component} was changed but ${v.expected} was not`);
248
+ }
249
+ }
250
+ if (anyAlternate) {
251
+ console.error("");
252
+ console.error(" Note: a co-located story under a components/<subdir>/ only renders in");
253
+ console.error(" Storybook if this fork's .storybook/main.* glob covers that path. The");
254
+ console.error(" top-level components/<Name>.stories.tsx location already matches the");
255
+ console.error(" existing glob in both upstream and every fork.");
256
+ }
257
+ console.error("");
258
+ console.error("Fix options:");
259
+ console.error(" • Auto-generate baseline stories: pnpm fix:stories");
260
+ console.error(" • Or in Claude Code, just say: 'fix the stories'");
261
+ console.error(" (Claude follows STORYBOOK_RULE.md to write full-matrix coverage)");
262
+ console.error("");
263
+ }
264
+
265
+ function main() {
266
+ const root = process.cwd();
267
+ const all = process.argv.includes("--all");
268
+
269
+ if (all) {
270
+ const { scanned, violations } = runAudit(root);
271
+ console.log(`Storybook coverage: scanned ${SCAN_DESCRIPTION}, ${scanned.length} component(s) found.`);
272
+ if (scanned.length === 0) {
273
+ console.error(
274
+ "Storybook coverage: FAILED, every scan root came up empty. A coverage gate that cannot see any code it is supposed to guard is not a pass."
275
+ );
276
+ process.exitCode = 1;
277
+ return;
278
+ }
279
+ if (violations.length === 0) {
280
+ console.log(`Storybook coverage: OK (${scanned.length} component(s) checked, every one has a story).`);
281
+ process.exitCode = 0;
282
+ return;
283
+ }
284
+ printViolations(violations);
285
+ process.exitCode = 1;
286
+ return;
287
+ }
93
288
 
94
- if (violations.length === 0) {
95
- if (ALL) console.log("Storybook coverage: OK (every component has a story).");
96
- process.exit(0);
289
+ const { staged, matched, violations } = runStaged(root);
290
+ console.log(`Storybook coverage: scanned ${staged.length} staged file(s), ${matched} touching tracked component roots (${SCAN_DESCRIPTION}).`);
291
+ if (violations.length === 0) {
292
+ process.exitCode = 0;
293
+ return;
294
+ }
295
+ printViolations(violations);
296
+ process.exitCode = 1;
97
297
  }
98
298
 
99
- console.error("");
100
- console.error("✗ Storybook coverage violations:");
101
- console.error("");
102
- for (const v of violations) {
103
- if (v.kind === "missing-story") {
104
- console.error(` MISSING ${v.component}`);
105
- console.error(` → expected story at ${v.expected}`);
106
- } else {
107
- console.error(` STALE ${v.component} was changed but ${v.expected} was not`);
299
+ // Node resolves import.meta.url through any symlink in the module's own
300
+ // path, but process.argv[1] is left exactly as invoked. The shipped bin
301
+ // (bads-check-stories) is a symlink into node_modules/.bin, so a naive
302
+ // `import.meta.url === file://${process.argv[1]}` check never matches
303
+ // there and main() silently never runs. Resolve both sides to the same
304
+ // real, absolute path before comparing.
305
+ function isMainModule() {
306
+ if (!process.argv[1]) return false;
307
+ try {
308
+ return import.meta.url === `file://${realpathSync(process.argv[1])}`;
309
+ } catch {
310
+ return false;
108
311
  }
109
312
  }
110
- console.error("");
111
- console.error("Fix options:");
112
- console.error(" • Auto-generate baseline stories: pnpm fix:stories");
113
- console.error(" • Or in Claude Code, just say: 'fix the stories'");
114
- console.error(" (Claude follows STORYBOOK_RULE.md to write full-matrix coverage)");
115
- console.error("");
116
- process.exit(1);
313
+
314
+ if (isMainModule()) main();
315
+
316
+ export {
317
+ pascal,
318
+ isBarrelReexport,
319
+ uiComponentToStoryPath,
320
+ listUiComponents,
321
+ listComponentsRootEntries,
322
+ componentsRootStoryPaths,
323
+ listAllComponents,
324
+ runAudit,
325
+ classifyStagedFile,
326
+ runStaged,
327
+ isMainModule,
328
+ main,
329
+ };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * sRGB contrast math for already-resolved hex colors.
3
+ *
4
+ * Deliberately does NOT parse oklch. Upstream's wcag-audit.cjs owns token
5
+ * resolution and emits resolved hex in its --json output; this module only
6
+ * computes ratios for pairs that audit does not itself check (a bare accent
7
+ * token used as text on a card, for instance).
8
+ */
9
+
10
+ const HEX_RE = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
11
+
12
+ /** Hex string to an [r, g, b] triplet, each 0 to 255. */
13
+ export function parseHex(hex) {
14
+ if (typeof hex !== "string") {
15
+ throw new TypeError(`parseHex expected a string, got ${typeof hex}`);
16
+ }
17
+ const match = hex.trim().match(HEX_RE);
18
+ if (!match) throw new TypeError(`parseHex could not parse ${JSON.stringify(hex)}`);
19
+ let body = match[1];
20
+ if (body.length === 3) body = body.split("").map((c) => c + c).join("");
21
+ return [
22
+ parseInt(body.slice(0, 2), 16),
23
+ parseInt(body.slice(2, 4), 16),
24
+ parseInt(body.slice(4, 6), 16),
25
+ ];
26
+ }
27
+
28
+ /** WCAG 2.x relative luminance. Returns 0 for black, 1 for white. */
29
+ export function relativeLuminance([r, g, b]) {
30
+ const channel = (v) => {
31
+ const s = v / 255;
32
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
33
+ };
34
+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
35
+ }
36
+
37
+ /** WCAG contrast ratio between two hex colors, rounded to 2 decimals. */
38
+ export function contrastFromHex(hexA, hexB) {
39
+ const lA = relativeLuminance(parseHex(hexA));
40
+ const lB = relativeLuminance(parseHex(hexB));
41
+ const lighter = Math.max(lA, lB);
42
+ const darker = Math.min(lA, lB);
43
+ return Math.round(((lighter + 0.05) / (darker + 0.05)) * 100) / 100;
44
+ }