toolcrib 0.9.0 → 0.11.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.
@@ -0,0 +1,582 @@
1
+ import { structuredPatch } from 'diff';
2
+ import { normalize, buildPatch } from './patches.js';
3
+ import { stripComments, extractImports, resolveRelativeImport } from './importScan.js';
4
+
5
+ /**
6
+ * Pure analysis for `toolcrib export-patches`: given the installed release's
7
+ * files and the consumer's local copy of the vendored tree (both as in-memory
8
+ * Maps of forward-slash relPath -> text, relative to the toolkit root), decide
9
+ * what can go upstream, group it into contributions, split the shared
10
+ * registry files by hunk, and run a static readiness checklist. No fs, no
11
+ * network, so every rule here is unit-testable with plain fixtures.
12
+ */
13
+
14
+ /** Top-level vendored source directories eligible for export. */
15
+ export const ALLOWLIST = ['components', 'theme', 'eventBus', 'observer'];
16
+
17
+ /**
18
+ * Files every contribution edits (event channels, slice registry, editor
19
+ * controls). Import-following can't reach them, and exporting one whole would
20
+ * drag along other contributions' and the app's own edits, so they are split
21
+ * by hunk instead.
22
+ */
23
+ export const SHARED_FILES = [
24
+ 'eventBus/eventBus.ts',
25
+ 'theme/registerThemeSlices.ts',
26
+ 'components/ThemeEditor/sliceEditorControls.tsx',
27
+ ];
28
+
29
+ export const VALID_CATEGORIES = ['Layout Primitives', 'Containers', 'Overlays', 'Data Display', 'Form Controls'];
30
+
31
+ const INFRA_DIRS = ['theme', 'eventBus', 'observer'];
32
+ const CODE_FILE = /\.[cm]?[jt]sx?$/;
33
+ const MANIFEST_BLOCK_RE = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*export\s+(?:const|function)\s+(\w+)/g;
34
+ const EXPORT_DECL_RE = /\bexport\s+(?:declare\s+)?(?:abstract\s+)?(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;
35
+ /** Raw React prop types that carry style/className, as an extends, intersection or alias. */
36
+ const RAW_PROP_TYPE_RE = /(?:extends|&|=)\s*(?:React\.)?(?:\w*HTMLAttributes|ComponentProps(?:WithoutRef|WithRef)?|HTMLProps)</;
37
+ /** `style?:` / `className?:` only exists in type declarations, so it counts anywhere on a line. */
38
+ const DECLARED_STYLE_OPTIONAL_RE = /\b(?:readonly\s+)?(?:style|className)\?\s*:/;
39
+ /** A required style/className member with a type annotation (not an object literal value). */
40
+ const DECLARED_STYLE_TYPED_RE = /\b(?:style|className)\s*:\s*(?:string|React\.CSSProperties|CSSProperties)\b/;
41
+ const USE_CLIENT_TRIGGER_RE =
42
+ /\buse[A-Z]\w*\s*\(|\bcreateContext\s*\(|\b(?:document|window)\.|extends\s+(?:React\.)?(?:Pure)?Component\b/;
43
+
44
+ /**
45
+ * Local content is diffed to produce patches for the UPSTREAM repo, which is
46
+ * LF with no BOM. This is the opposite of project.js's readTextIfExists,
47
+ * which must keep a BOM because its output becomes the "before" side of a
48
+ * patch that git apply matches byte-for-byte against the consumer's own file.
49
+ */
50
+ function toUpstreamText(content) {
51
+ const noBom = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;
52
+ return normalize(noBom);
53
+ }
54
+
55
+ function toNormalizedMap(files) {
56
+ const out = new Map();
57
+ for (const [relPath, content] of files) out.set(relPath, toUpstreamText(content));
58
+ return out;
59
+ }
60
+
61
+ function topSegment(relPath) {
62
+ return relPath.includes('/') ? relPath.split('/')[0] : null;
63
+ }
64
+
65
+ function baseName(relPath) {
66
+ return relPath.split('/').pop().replace(/\.[^.]+$/, '');
67
+ }
68
+
69
+ /** Component unit a path belongs to: components/<Folder>/... or components/<File>.ext. */
70
+ function unitKeyOf(relPath) {
71
+ const parts = relPath.split('/');
72
+ if (parts[0] !== 'components' || parts.length < 2) return null;
73
+ if (parts.length >= 3) return parts[1];
74
+ return parts[1].replace(/\.[^.]+$/, '');
75
+ }
76
+
77
+ /** `@manifest`-tagged exported components: [{ name, body }] (body = JSDoc text). */
78
+ function manifestComponents(content) {
79
+ const out = [];
80
+ for (const m of content.matchAll(MANIFEST_BLOCK_RE)) {
81
+ if (/@manifest(?=\s)/.test(m[1])) out.push({ name: m[2], body: m[1] });
82
+ }
83
+ return out;
84
+ }
85
+
86
+ function exportedNames(content) {
87
+ const code = stripComments(content);
88
+ return [...code.matchAll(EXPORT_DECL_RE)].map((m) => m[1]);
89
+ }
90
+
91
+ function sliceIds(content) {
92
+ const code = stripComments(content);
93
+ if (!/:\s*ThemeSlice</.test(code)) return [];
94
+ return [...code.matchAll(/\bid:\s*(['"])([^'"]+)\1/g)].map((m) => m[2]);
95
+ }
96
+
97
+ function hunkHeaderText(h) {
98
+ return `@@ -${h.oldStart},${h.oldLines} +${h.newStart},${h.newLines} @@\n${h.lines.join('\n')}`;
99
+ }
100
+
101
+ /** A quoted event channel key, e.g. `'gauge:changed'` or `"widget:changed"`. Groups: quote, full name, prefix. */
102
+ const CHANNEL_KEY_RE = /(['"])(([a-z0-9]+):[A-Za-z0-9_:-]+)\1\s*[:?]/g;
103
+ /** A hunk line's object key: a bare identifier or a quoted, possibly hyphenated, key. Groups: bare, quote, quoted. */
104
+ const HUNK_KEY_RE = /^\s*(?:([a-z][a-z0-9]*)|(['"])([a-z][a-z0-9-]*)\2)\s*:/;
105
+
106
+ /** Tokens a hunk's added AND removed lines expose for attribution. */
107
+ function hunkTokens(hunk, sharedRelPath, localHas) {
108
+ const changed = hunk.lines.filter((l) => l[0] === '+' || l[0] === '-').map((l) => l.slice(1));
109
+ const text = changed.join('\n');
110
+
111
+ const channels = [];
112
+ for (const m of text.matchAll(CHANNEL_KEY_RE)) {
113
+ channels.push({ full: m[2], prefix: m[3] });
114
+ }
115
+
116
+ const specifiers = new Set(extractImports(text));
117
+ // A multi-line import's `} from './x'` tail has no import keyword in the hunk.
118
+ for (const m of text.matchAll(/\bfrom\s+['"]([^'"]+)['"]/g)) specifiers.add(m[1]);
119
+ const imports = new Set();
120
+ for (const spec of specifiers) {
121
+ const resolved = resolveRelativeImport(sharedRelPath, spec, localHas);
122
+ if (resolved) imports.add(resolved);
123
+ }
124
+
125
+ const identifiers = new Set(text.match(/\b[A-Z][A-Za-z0-9_]{3,}\b/g) ?? []);
126
+ const keys = new Set();
127
+ for (const line of changed) {
128
+ const m = HUNK_KEY_RE.exec(line);
129
+ if (m) keys.add(m[1] ?? m[3]);
130
+ }
131
+ const addedChannelPrefixes = [];
132
+ for (const l of hunk.lines) {
133
+ if (l[0] !== '+') continue;
134
+ for (const m of l.matchAll(CHANNEL_KEY_RE)) addedChannelPrefixes.push(m[3]);
135
+ }
136
+ return { channels, imports, identifiers, keys, addedChannelPrefixes };
137
+ }
138
+
139
+ /**
140
+ * Apply only the selected zero-context hunks to `original`. structuredPatch
141
+ * (diff v9) reports oldStart as the 1-based line the hunk starts at, and for
142
+ * a pure insertion (oldLines 0) the 1-based line it goes BEFORE, so
143
+ * `oldStart - 1` is the 0-based splice index in both cases.
144
+ */
145
+ function applyHunks(original, hunks) {
146
+ let lines = original.split('\n');
147
+ const endsWithNewline = lines[lines.length - 1] === '';
148
+ if (endsWithNewline) lines = lines.slice(0, -1);
149
+
150
+ const sorted = [...hunks].sort((a, b) => a.oldStart - b.oldStart);
151
+ const out = [];
152
+ let cursor = 0;
153
+ for (const h of sorted) {
154
+ const start = h.oldStart - 1;
155
+ for (; cursor < start; cursor++) out.push(lines[cursor]);
156
+ for (const l of h.lines) {
157
+ if (l[0] === '+') out.push(l.slice(1));
158
+ }
159
+ cursor = start + h.oldLines;
160
+ }
161
+ for (; cursor < lines.length; cursor++) out.push(lines[cursor]);
162
+ return out.join('\n') + (endsWithNewline ? '\n' : '');
163
+ }
164
+
165
+ class UnionFind {
166
+ constructor(items) {
167
+ this.parent = new Map(items.map((i) => [i, i]));
168
+ }
169
+ find(x) {
170
+ let root = x;
171
+ while (this.parent.get(root) !== root) root = this.parent.get(root);
172
+ this.parent.set(x, root);
173
+ return root;
174
+ }
175
+ union(a, b) {
176
+ const ra = this.find(a);
177
+ const rb = this.find(b);
178
+ if (ra !== rb) this.parent.set(rb, ra);
179
+ }
180
+ }
181
+
182
+ /**
183
+ * @param {{ releaseFiles: Map<string,string>, localFiles: Map<string,string> }} input
184
+ * relPaths are relative to the toolkit root (`components/Card/Card.tsx`).
185
+ */
186
+ export function analyzeExport({ releaseFiles, localFiles }) {
187
+ const rel = toNormalizedMap(releaseFiles);
188
+ const loc = toNormalizedMap(localFiles);
189
+ const localHas = (p) => loc.has(p);
190
+
191
+ // ---- classify every differing file ----
192
+ const notExported = [];
193
+ const regeneratedUpstream = [];
194
+ const changed = new Map(); // allowlisted, non-shared: relPath -> 'added'|'modified'|'deleted'
195
+ const sharedModified = [];
196
+ let anyDifference = false;
197
+
198
+ const allPaths = [...new Set([...rel.keys(), ...loc.keys()])].sort();
199
+ for (const relPath of allPaths) {
200
+ const inRel = rel.has(relPath);
201
+ const inLoc = loc.has(relPath);
202
+ if (inRel && inLoc && rel.get(relPath) === loc.get(relPath)) continue;
203
+ anyDifference = true;
204
+ const change = inRel && inLoc ? 'modified' : inLoc ? 'added' : 'deleted';
205
+
206
+ if (relPath === 'index.ts') {
207
+ regeneratedUpstream.push(relPath);
208
+ continue;
209
+ }
210
+ const seg = topSegment(relPath);
211
+ if (!seg || !ALLOWLIST.includes(seg)) {
212
+ notExported.push({ relPath, change });
213
+ continue;
214
+ }
215
+ if (SHARED_FILES.includes(relPath)) {
216
+ if (change === 'modified') sharedModified.push(relPath);
217
+ else notExported.push({ relPath, change });
218
+ continue;
219
+ }
220
+ changed.set(relPath, change);
221
+ }
222
+
223
+ if (!anyDifference) {
224
+ return { hasChanges: false, contributions: [], notExported, regeneratedUpstream, appSpecific: [], ambiguous: [] };
225
+ }
226
+
227
+ // ---- import graph over the consumer's whole tree ----
228
+ const depCache = new Map();
229
+ const deps = (relPath) => {
230
+ if (depCache.has(relPath)) return depCache.get(relPath);
231
+ const out = new Set();
232
+ const content = loc.get(relPath);
233
+ if (content !== undefined && CODE_FILE.test(relPath)) {
234
+ for (const spec of extractImports(content)) {
235
+ const resolved = resolveRelativeImport(relPath, spec, localHas);
236
+ if (resolved) out.add(resolved);
237
+ }
238
+ }
239
+ depCache.set(relPath, out);
240
+ return out;
241
+ };
242
+
243
+ // ---- 1. component units ----
244
+ const releaseUnitKeys = new Set([...rel.keys()].map(unitKeyOf).filter(Boolean));
245
+ const units = new Map(); // key -> contribution
246
+ const unitOf = new Map(); // relPath -> unit key
247
+ for (const [relPath] of changed) {
248
+ const key = unitKeyOf(relPath);
249
+ if (!key) continue;
250
+ if (!units.has(key)) {
251
+ units.set(key, {
252
+ name: key,
253
+ type: releaseUnitKeys.has(key) ? 'change' : 'new-component',
254
+ isUnit: true,
255
+ paths: [],
256
+ dependsOn: [],
257
+ missingDependencies: [],
258
+ });
259
+ }
260
+ units.get(key).paths.push(relPath);
261
+ unitOf.set(relPath, key);
262
+ }
263
+
264
+ // ---- 2. import following ----
265
+ const isInfraCandidate = (p) => changed.has(p) && INFRA_DIRS.includes(topSegment(p)) && !unitOf.has(p);
266
+ const reachedBy = new Map(); // candidate relPath -> Set(unit key)
267
+ const reachedPerUnit = new Map();
268
+ for (const [key, unit] of units) {
269
+ const seen = new Set(unit.paths);
270
+ const stack = [...unit.paths];
271
+ const reached = new Set();
272
+ const missing = new Set();
273
+ while (stack.length) {
274
+ const f = stack.pop();
275
+ for (const d of deps(f)) {
276
+ if (seen.has(d)) continue;
277
+ seen.add(d);
278
+ if (SHARED_FILES.includes(d)) continue;
279
+ const owner = unitOf.get(d);
280
+ if (owner !== undefined && owner !== key) continue; // another unit's own files
281
+ if (isInfraCandidate(d)) reached.add(d);
282
+ else if (changed.has(d) === false && loc.has(d) && rel.get(d) !== loc.get(d) && d !== 'index.ts') {
283
+ if (!ALLOWLIST.includes(topSegment(d) ?? '')) missing.add(d);
284
+ }
285
+ stack.push(d);
286
+ }
287
+ }
288
+ reachedPerUnit.set(key, reached);
289
+ unit.missingDependencies = [...missing].sort();
290
+ for (const d of reached) {
291
+ if (!reachedBy.has(d)) reachedBy.set(d, new Set());
292
+ reachedBy.get(d).add(key);
293
+ }
294
+ }
295
+ for (const [d, owners] of reachedBy) {
296
+ if (owners.size === 1) {
297
+ const key = [...owners][0];
298
+ units.get(key).paths.push(d);
299
+ unitOf.set(d, key);
300
+ }
301
+ }
302
+
303
+ // ---- 3. infrastructure contributions ----
304
+ const pool = [...changed.keys()].filter((p) => !unitOf.has(p) && INFRA_DIRS.includes(topSegment(p))).sort();
305
+ const uf = new UnionFind(pool);
306
+ const poolSet = new Set(pool);
307
+ for (const f of pool) {
308
+ for (const d of deps(f)) if (poolSet.has(d)) uf.union(f, d);
309
+ }
310
+ const groups = new Map();
311
+ for (const f of pool) {
312
+ const root = uf.find(f);
313
+ if (!groups.has(root)) groups.set(root, []);
314
+ groups.get(root).push(f);
315
+ }
316
+ const usedNames = new Set(units.keys());
317
+ const infra = [];
318
+ const infraOfFile = new Map();
319
+ for (const members of groups.values()) {
320
+ members.sort();
321
+ let name = baseName(members[0]);
322
+ while (usedNames.has(name)) name += '-infra';
323
+ usedNames.add(name);
324
+ const contribution = {
325
+ name,
326
+ type: members.some((m) => changed.get(m) === 'added') ? 'infrastructure' : 'change',
327
+ isUnit: false,
328
+ paths: members,
329
+ dependsOn: [],
330
+ missingDependencies: [],
331
+ };
332
+ infra.push(contribution);
333
+ for (const m of members) infraOfFile.set(m, contribution);
334
+ }
335
+ infra.sort((a, b) => a.name.localeCompare(b.name));
336
+ for (const [key, unit] of units) {
337
+ const names = new Set();
338
+ for (const d of reachedPerUnit.get(key)) {
339
+ if (infraOfFile.has(d)) names.add(infraOfFile.get(d).name);
340
+ }
341
+ unit.dependsOn = [...names].sort();
342
+ }
343
+
344
+ const contributions = [...[...units.values()].sort((a, b) => a.name.localeCompare(b.name)), ...infra];
345
+
346
+ // ---- per-contribution facts used for hunk attribution ----
347
+ for (const c of contributions) {
348
+ c.paths.sort();
349
+ const live = c.paths.filter((p) => loc.has(p));
350
+ const text = live.map((p) => loc.get(p)).join('\n');
351
+ c.manifest = [];
352
+ c.exports = new Set();
353
+ c.prefixes = new Set();
354
+ c.sliceIds = [];
355
+ for (const p of live) {
356
+ for (const m of manifestComponents(loc.get(p))) {
357
+ c.manifest.push(m);
358
+ c.prefixes.add(m.name.toLowerCase());
359
+ }
360
+ for (const n of exportedNames(loc.get(p))) c.exports.add(n);
361
+ for (const id of sliceIds(loc.get(p))) {
362
+ c.sliceIds.push(id);
363
+ c.prefixes.add(id);
364
+ }
365
+ }
366
+ if (c.isUnit) c.prefixes.add(c.name.toLowerCase());
367
+ c.text = text;
368
+ c.fileSet = new Set(c.paths);
369
+ c.hunksByFile = new Map(); // shared relPath -> [{ hunk, tokens }]
370
+ }
371
+
372
+ // ---- shared files: split by hunk ----
373
+ const appSpecific = [];
374
+ const ambiguous = [];
375
+ for (const relPath of sharedModified) {
376
+ const patch = structuredPatch(relPath, relPath, rel.get(relPath), loc.get(relPath), '', '', { context: 0 });
377
+ for (const hunk of patch.hunks) {
378
+ const tokens = hunkTokens(hunk, relPath, localHas);
379
+ const matches = contributions.filter((c) => {
380
+ for (const ch of tokens.channels) {
381
+ if (c.prefixes.has(ch.prefix)) return true;
382
+ if (c.text.includes(`'${ch.full}'`) || c.text.includes(`"${ch.full}"`)) return true;
383
+ }
384
+ for (const i of tokens.imports) if (c.fileSet.has(i)) return true;
385
+ for (const id of tokens.identifiers) if (c.exports.has(id)) return true;
386
+ for (const k of tokens.keys) if (c.prefixes.has(k)) return true;
387
+ return false;
388
+ });
389
+ if (matches.length === 1) {
390
+ const c = matches[0];
391
+ if (!c.hunksByFile.has(relPath)) c.hunksByFile.set(relPath, []);
392
+ c.hunksByFile.get(relPath).push({ hunk, tokens });
393
+ } else if (matches.length === 0) {
394
+ appSpecific.push({ relPath, hunkText: hunkHeaderText(hunk) });
395
+ } else {
396
+ ambiguous.push({ relPath, hunkText: hunkHeaderText(hunk), candidates: matches.map((c) => c.name) });
397
+ }
398
+ }
399
+ }
400
+
401
+ // ---- build file records + patches ----
402
+ for (const c of contributions) {
403
+ const files = [];
404
+ for (const p of c.paths) {
405
+ const change = changed.get(p);
406
+ const upstream = `src/${p}`;
407
+ files.push({
408
+ relPath: p,
409
+ upstreamPath: upstream,
410
+ change,
411
+ patch: buildPatch(upstream, rel.get(p) ?? '', loc.get(p) ?? ''),
412
+ });
413
+ }
414
+ for (const [p, entries] of c.hunksByFile) {
415
+ const original = rel.get(p);
416
+ const partial = applyHunks(original, entries.map((e) => e.hunk));
417
+ files.push({
418
+ relPath: p,
419
+ upstreamPath: `src/${p}`,
420
+ change: 'modified',
421
+ hunks: entries.length,
422
+ patch: buildPatch(`src/${p}`, original, partial),
423
+ });
424
+ }
425
+ files.sort((a, b) => a.relPath.localeCompare(b.relPath));
426
+ c.files = files;
427
+ }
428
+
429
+ // ---- readiness checklist ----
430
+ const changedTestFiles = notExported.map((n) => n.relPath).filter((p) => p.startsWith('__tests__/'));
431
+ for (const c of contributions) {
432
+ c.checklist = buildChecklist(c, loc, changedTestFiles);
433
+ }
434
+
435
+ const outContributions = contributions.map((c) => ({
436
+ name: c.name,
437
+ type: c.type,
438
+ files: c.files,
439
+ dependsOn: c.dependsOn,
440
+ missingDependencies: c.missingDependencies,
441
+ checklist: c.checklist,
442
+ }));
443
+
444
+ notExported.sort((a, b) => a.relPath.localeCompare(b.relPath));
445
+ return { hasChanges: true, contributions: outContributions, notExported, regeneratedUpstream, appSpecific, ambiguous };
446
+ }
447
+
448
+ // ---------------------------------------------------------------------------
449
+ // Readiness checklist
450
+ // ---------------------------------------------------------------------------
451
+
452
+ const result = (status, details = []) => ({ status, details });
453
+
454
+ function buildChecklist(c, loc, changedTestFiles) {
455
+ const live = c.paths.filter((p) => loc.has(p));
456
+ const codeFiles = live.filter((p) => CODE_FILE.test(p));
457
+ const checks = {};
458
+
459
+ const useClient = () => {
460
+ const offenders = [];
461
+ for (const p of codeFiles) {
462
+ const content = loc.get(p);
463
+ // A hook *declaration* is not a hook call.
464
+ const code = stripComments(content).replace(/\bfunction\s+use[A-Z]\w*/g, 'function _');
465
+ if (!USE_CLIENT_TRIGGER_RE.test(code)) continue;
466
+ if (!/^\s*(['"])use client\1/.test(stripComments(content))) offenders.push(p);
467
+ }
468
+ return result(offenders.length ? 'fail' : 'pass', offenders);
469
+ };
470
+ const selfImport = () => {
471
+ const offenders = live.filter((p) =>
472
+ CODE_FILE.test(p) && extractImports(loc.get(p)).some((s) => s === '#toolcrib' || s.startsWith('#toolcrib/'))
473
+ );
474
+ return result(offenders.length ? 'fail' : 'pass', offenders);
475
+ };
476
+ const processEnv = () => {
477
+ const offenders = live.filter((p) => CODE_FILE.test(p) && /\bprocess\.env\b/.test(stripComments(loc.get(p))));
478
+ return result(offenders.length ? 'fail' : 'pass', offenders.map((p) => `${p} (use isDevBuild())`));
479
+ };
480
+
481
+ // Channels this contribution adds must use one of its own prefixes,
482
+ // whether the component is new or an existing one gaining an event.
483
+ const eventPrefix = () => {
484
+ const badPrefix = [];
485
+ let sawChannel = false;
486
+ for (const entries of c.hunksByFile.values()) {
487
+ for (const { tokens } of entries) {
488
+ for (const prefix of tokens.addedChannelPrefixes) {
489
+ sawChannel = true;
490
+ if (!c.prefixes.has(prefix)) badPrefix.push(`channel prefix "${prefix}:" is not one of ${[...c.prefixes].join(', ')}`);
491
+ }
492
+ }
493
+ }
494
+ return !sawChannel ? result('n/a') : result(badPrefix.length ? 'fail' : 'pass', badPrefix);
495
+ };
496
+
497
+ if (c.type === 'new-component') {
498
+ checks.manifest = c.manifest.length
499
+ ? result('pass', c.manifest.map((m) => m.name))
500
+ : result('fail', ['no exported component carries a @manifest tag']);
501
+
502
+ if (c.manifest.length === 0) {
503
+ checks.manifest_category = result('n/a');
504
+ } else {
505
+ const bad = [];
506
+ for (const m of c.manifest) {
507
+ const cat = /@manifestCategory[ \t]+([^\r\n]*)/.exec(m.body)?.[1].trim();
508
+ if (!cat) bad.push(`${m.name}: missing @manifestCategory`);
509
+ else if (!VALID_CATEGORIES.includes(cat)) bad.push(`${m.name}: invalid category "${cat}"`);
510
+ }
511
+ checks.manifest_category = result(bad.length ? 'fail' : 'pass', bad);
512
+ }
513
+
514
+ const styleBad = [];
515
+ let sawStyleFree = false;
516
+ for (const p of codeFiles) {
517
+ const code = stripComments(loc.get(p));
518
+ if (RAW_PROP_TYPE_RE.test(code)) styleBad.push(`${p}: uses a raw React prop type (brings style/className)`);
519
+ if (DECLARED_STYLE_OPTIONAL_RE.test(code) || DECLARED_STYLE_TYPED_RE.test(code)) {
520
+ styleBad.push(`${p}: declares style/className`);
521
+ }
522
+ if (/StyleFree/.test(code)) sawStyleFree = true;
523
+ }
524
+ checks.style_free = styleBad.length ? result('fail', styleBad) : sawStyleFree ? result('pass') : result('n/a');
525
+
526
+ checks.use_client = useClient();
527
+ checks.toolcrib_self_import = selfImport();
528
+ checks.process_env = processEnv();
529
+
530
+ checks.event_prefix = eventPrefix();
531
+
532
+ if (c.sliceIds.length === 0) {
533
+ checks.theme_slice = result('n/a');
534
+ } else {
535
+ const missing = [];
536
+ if (!c.hunksByFile.has('theme/registerThemeSlices.ts')) missing.push('no hunk in theme/registerThemeSlices.ts');
537
+ if (!c.hunksByFile.has('components/ThemeEditor/sliceEditorControls.tsx')) {
538
+ missing.push('no hunk in components/ThemeEditor/sliceEditorControls.tsx');
539
+ }
540
+ checks.theme_slice = result(missing.length ? 'fail' : 'pass', missing);
541
+ }
542
+
543
+ const formControls = c.manifest.filter((m) => /@manifestCategory[ \t]+Form Controls\b/.test(m.body));
544
+ if (formControls.length === 0) {
545
+ checks.form_controls = result('n/a');
546
+ } else {
547
+ const noStates = formControls.filter((m) => !/@manifestStates\b/.test(m.body)).map((m) => `${m.name}: missing @manifestStates`);
548
+ checks.form_controls = result(noStates.length ? 'fail' : 'pass', [
549
+ ...noStates,
550
+ 'add to src/__tests__/formControlContract.test.tsx CONTROLS upstream',
551
+ ]);
552
+ }
553
+
554
+ checks.tests = testsCheck(c.manifest.map((m) => m.name), changedTestFiles);
555
+ } else if (c.type === 'infrastructure') {
556
+ const added = c.files.filter((f) => f.change === 'added');
557
+ if (added.length === 0) {
558
+ checks.barrel_export = result('n/a');
559
+ } else {
560
+ const tagged = added.some((f) => /@barrelExport\b/.test(loc.get(f.relPath) ?? ''));
561
+ checks.barrel_export = tagged ? result('pass') : result('fail', ['no added file carries a @barrelExport tag, so it would not be reachable via #toolcrib']);
562
+ }
563
+ checks.use_client = useClient();
564
+ checks.toolcrib_self_import = selfImport();
565
+ checks.process_env = processEnv();
566
+ checks.tests = testsCheck(c.paths.map(baseName), changedTestFiles);
567
+ } else {
568
+ checks.use_client = useClient();
569
+ checks.toolcrib_self_import = selfImport();
570
+ checks.process_env = processEnv();
571
+ checks.event_prefix = eventPrefix();
572
+ }
573
+ return checks;
574
+ }
575
+
576
+ function testsCheck(names, testFiles) {
577
+ const found = testFiles.filter((t) => {
578
+ const file = t.split('/').pop();
579
+ return names.some((n) => file.includes(n));
580
+ });
581
+ return found.length ? result('pass', found) : result('fail', ['no tests found']);
582
+ }