@nodii/dev 0.6.172 → 0.6.173

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,830 @@
1
+ // `nodii-dev surface corpus`: the generator's corpus gate (NODII-DEV-CLI-163;
2
+ // docs/generator-plan/README.md, section d).
3
+ //
4
+ // It regenerates every catalog Surface that has a committed tree, in memory,
5
+ // with the generator this CLI carries, and judges what the generator wrote. It
6
+ // never reads Figma and never writes into design-system. It judges fresh output
7
+ // only: the pages committed in design-system are on older generator formats and
8
+ // are not compared.
9
+ //
10
+ // What it counts, per page, and holds to a committed baseline
11
+ // (test/corpus/baseline.json) that only shrinks:
12
+ // fixed samples a literal in a place that holds a record's value, or one
13
+ // that reads like a record's value outside copy
14
+ // suspect copy a literal written as copy that reads like a record's value
15
+ // undecided a literal no rule places as data or as copy
16
+ // unmapped layers the generator's own counted findings (U08-14)
17
+ // shallow input a saved tree with no `treeFormat` 2 (nested slots not kept)
18
+ // What it refuses outright: a Surface that throws, an identifier a page uses but
19
+ // never imports or declares, an import that names nothing its module exports.
20
+ //
21
+ // The scan here is the plan's first draft: it parses each page with the design
22
+ // system's own TypeScript and sorts each literal by what it holds and where it
23
+ // sits. Lane gen-rule replaces it with the generator's own manifest. Prop churn
24
+ // is not checked until lane gen-names commits the names locks.
25
+ //
26
+ // This file reads the generator through its exported entry points only; it
27
+ // changes nothing in surface.js.
28
+ import { execFileSync } from "node:child_process";
29
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
30
+ import { createRequire } from "node:module";
31
+ import { homedir } from "node:os";
32
+ import { dirname, join, relative, resolve } from "node:path";
33
+ import { fileURLToPath } from "node:url";
34
+ import { CliError, VERSION } from "./core.js";
35
+
36
+ export const CORPUS_USAGE = "surface corpus [--ds DIR] [--ref REV] [--module M] [--report FILE] [--baseline FILE] [--update]";
37
+
38
+ /** The counts a page carries in the baseline, in the order they are printed. */
39
+ export const CHECKS = ["fixedSamples", "suspectCopy", "undecided", "unmapped", "shallowInput"];
40
+ const LABEL = { fixedSamples: "fixed samples", suspectCopy: "suspect copy", undecided: "undecided", unmapped: "unmapped layers", shallowInput: "shallow input" };
41
+ /** The saved-tree format that keeps nested slot content (lane gen-tree). */
42
+ const FULL_DEPTH_TREE_FORMAT = 2;
43
+
44
+ const BASELINE_FILE = "../test/corpus/baseline.json";
45
+ const REF_FILE = "design-system.ref";
46
+ const CATALOG_PATH = "packages/blocks/src/product-pages/catalog.ts";
47
+ const SHA = /^[0-9a-f]{40}$/;
48
+
49
+ // ---------------------------------------------------------------------------
50
+ // The scan: every literal a page writes into its JSX, sorted
51
+ // ---------------------------------------------------------------------------
52
+
53
+ // Attributes that never hold text a person reads: layout, tokens, variants, wiring.
54
+ const SKIPPED_ATTR = new Set([
55
+ "className", "id", "key", "htmlFor", "variant", "size", "tone", "kind", "shape", "layout", "density", "orientation", "colAlign", "width", "height", "type", "role",
56
+ "connector", "state", "mode", "side", "direction", "sort", "status", "step", "preset", "align", "part", "icon", "illustration", "href", "src", "alt", "name", "autoComplete",
57
+ "inputMode", "pattern", "target", "rel", "as", "asChild", "slot", "style", "tabIndex", "colSpan", "rowSpan", "columns", "rows", "gap", "padding", "justify", "position",
58
+ "surface",
59
+ ]);
60
+ /** Placeholders drawn while a page loads: never text, never data. */
61
+ const SKIPPED_TAG = /Skeleton/;
62
+ /** A list of choices: each member's `value` is the choice's key, its `label` the text. */
63
+ const CHOICE_LIST = /^(?:items|options|tabs)\[\]\.value$/;
64
+ const SKIPPED_ATTR_PREFIX = /^(?:aria-|data-|on[A-Z])/;
65
+ const SKIPPED_MEMBER = new Set(["id", "key", "tone", "status", "variant", "kind", "icon", "size", "type", "href", "state", "align", "width"]);
66
+ /** A value a program reads, never a person: `pending`, `tab-1`, `leave.approved`. */
67
+ const MACHINE_TOKEN = /^[a-z0-9]+(?:[-_.:/][a-z0-9]+)*$/;
68
+ const VALUE_LEAF = /^(?:value|defaultValue)$/;
69
+
70
+ // Where copy sits: an attribute or a tag that names a thing, never a record's value.
71
+ const LABEL_ATTR = /^(?:label|placeholder|title|hint|description|caption|summary|heading|message|legend|tooltip|emptyMessage)$|(?:Label|Placeholder|Hint|Title|Caption|Description|Message|Heading|Text)$/;
72
+ /** Copy whose digits are a format, never a record: `dd/mm/yyyy`, `e.g. 12`. */
73
+ const FORMAT_ATTR = /^(?:placeholder|hint)$|(?:Placeholder|Hint)$/;
74
+ const LABEL_TAG = /^(?:TabsTrigger|Button\w*|IconButton|TableHead\w*|TableSortHead|DescriptionTerm|Label|Legend|FieldLabel|h[1-6]|SelectItem|SelectLabel|\w*MenuItem|\w*MenuLabel|TooltipContent|RadioGroupItem|Kbd|(?:Dialog|AlertDialog|Sheet|Card|Section|Alert|EmptyState|ErrorStatePage|Popover|Drawer)(?:Title|Description|Action|Cancel|Header|Footer|Trigger|Block)?)$/;
75
+ const CONTAINER_TAG = /^(?:div|span|p|li|strong|em|small|Text|Heading|Field\w*|Form\w*|Tabs\w*)$/;
76
+
77
+ // Where a record's value sits.
78
+ const DATA_ATTR = /^(?:value|defaultValue|count|amount|time|actor|text|initials|subline|secondary|total\w*)$|(?:Count|Total|Amount|Value)$/;
79
+ const DATA_TAG = /^(?:TableCell|TableRichCell|MoneyCell|NameCell|DescriptionItem|DescriptionValue|Metric\w*|Stat\w*|PiiText|PersonName|CopyField|Money\w*|Currency\w*|Badge|StatusPill|PriorityChip|Chip|Avatar\w*|Timeline(?:\.\w+)?|Comment\w*|Progress\w*|Count\w*)$/;
80
+ const DATA_ANCESTOR = /^(?:TableCell|TableRichCell|TableRow|TableBody|MetricCard|DescriptionList|DescriptionItem|PiiText|CopyField|Timeline(?:\.\w+)?|Comment\w*)$/;
81
+
82
+ const MONTH = "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)[a-z]*";
83
+ // What a record's value reads like. The first that matches names the finding.
84
+ const CONTENT = [
85
+ ["email", /[\w.+-]+@[a-z0-9-]+\.[a-z]{2,}/i],
86
+ ["currency", /[₹$€£]\s?\d|\b(?:INR|USD|EUR|GBP|Rs\.?)\s?\d/],
87
+ ["percent", /\d\s?%/],
88
+ ["date", new RegExp(String.raw`\b\d{1,2}(?:st|nd|rd|th)? ${MONTH}\b|\b${MONTH} \d{1,4}\b`)],
89
+ ["date", /\b\d{1,4}[-/]\d{1,2}[-/]\d{1,4}\b|\bFY ?\d{2,4}\b/],
90
+ ["time", /\b\d{1,2}:\d{2}\b/],
91
+ ["relative time", /\b\d+\s?(?:s|secs?|m|mins?|minutes?|h|hrs?|hours?|d|days?|w|wks?|weeks?|mo|months?|y|yrs?|years?)\b/i],
92
+ ["identifier", /\b[A-Z]{2,6}-\d[\w-]*\b|#\d+|[•*·]{3,}|\b[A-Z]{5}\d{4}[A-Z]\b|\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/],
93
+ ["version", /\bv\d+(?:\.\d+)*\b/],
94
+ ["number", /^[+\-−]?\d[\d,]*(?:\.\d+)?$/],
95
+ ["quantity", /^\d[\d,]*(?:\.\d+)?\s\p{L}|\b\d[\d,]*\s(?:of|\/)\s\d/u],
96
+ ["count", /(?:\s|\()\d[\d,]*\)?$/],
97
+ ];
98
+ const contentOf = (text) => CONTENT.find(([, pattern]) => pattern.test(text))?.[0] ?? null;
99
+
100
+ const leafOf = (attr) => attr.split(/\.|\[\]/).filter(Boolean).at(-1);
101
+ const nested = (attr) => /\.|\[\]/.test(attr);
102
+
103
+ /**
104
+ * Where a literal sits: `data` (a record's value), `copy`, or neither. An
105
+ * attribute is read by its own name first, then by its tag; a child by its tag,
106
+ * then by what it sits inside.
107
+ */
108
+ function placeOf({ tag, attr, ancestors }) {
109
+ if (attr !== "child") {
110
+ const leaf = leafOf(attr);
111
+ if (nested(attr)) {
112
+ if (DATA_ATTR.test(leaf)) return ["data", `${attr} holds a record's value`];
113
+ // One object handed to a component is a record: `post={{ title, excerpt }}`.
114
+ if (!attr.includes("[]")) return ["data", `${attr.split(".")[0]} is one record`];
115
+ return [null, "no rule"];
116
+ }
117
+ if (LABEL_ATTR.test(leaf)) return ["copy", `${leaf} names a thing`];
118
+ if (DATA_ATTR.test(leaf)) return ["data", `${leaf} holds a record's value`];
119
+ if (DATA_TAG.test(tag)) return ["data", `${tag} holds a record's values`];
120
+ return [null, "no rule"];
121
+ }
122
+ if (LABEL_TAG.test(tag)) return ["copy", `${tag} names a thing`];
123
+ if (DATA_TAG.test(tag)) return ["data", `${tag} holds a record's values`];
124
+ const inside = ancestors.find((name) => DATA_ANCESTOR.test(name) || LABEL_TAG.test(name));
125
+ if (inside && DATA_ANCESTOR.test(inside)) return ["data", `inside ${inside}`];
126
+ if (CONTAINER_TAG.test(tag)) return ["copy", `text in ${tag}`];
127
+ return [null, "no rule"];
128
+ }
129
+
130
+ /** Which check a literal falls under, or null when it is plain copy. */
131
+ function sort(literal) {
132
+ const [place, where] = placeOf(literal);
133
+ const content = literal.numeric ? "number" : contentOf(literal.text);
134
+ if (place === "data") return { check: "fixedSamples", why: content ? `${content}; ${where}` : where };
135
+ if (place === "copy") {
136
+ if (!content || (literal.attr !== "child" && FORMAT_ATTR.test(leafOf(literal.attr)))) return null;
137
+ return { check: "suspectCopy", why: `${content}; ${where}` };
138
+ }
139
+ return content ? { check: "fixedSamples", why: content } : { check: "undecided", why: where };
140
+ }
141
+
142
+ /** Every literal the page writes into its JSX: text children, literal attributes, and literals inside either. */
143
+ function literalsOf(ts, file) {
144
+ const K = ts.SyntaxKind;
145
+ const found = [];
146
+ const lineOf = (node) => file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1;
147
+ const tagOf = (node) => node.tagName.getText(file);
148
+ const emit = (node, text, ctx, numeric = false) => {
149
+ const clean = String(text).replace(/\s+/g, " ").trim();
150
+ if (!/[\p{L}\p{N}]/u.test(clean)) return;
151
+ const attr = ctx.attr;
152
+ if (SKIPPED_TAG.test(ctx.tag)) return;
153
+ if (attr !== "child") {
154
+ const top = attr.split(/\.|\[\]/)[0];
155
+ const leaf = leafOf(attr);
156
+ if (SKIPPED_ATTR.has(top) || SKIPPED_ATTR_PREFIX.test(top)) return;
157
+ if (nested(attr) && (SKIPPED_MEMBER.has(leaf) || SKIPPED_ATTR.has(leaf) || CHOICE_LIST.test(attr))) return;
158
+ if (numeric && !DATA_ATTR.test(leaf)) return;
159
+ if (!numeric && (VALUE_LEAF.test(leaf) || nested(attr)) && MACHINE_TOKEN.test(clean) && (VALUE_LEAF.test(leaf) || /[-_.:/]/.test(clean))) return;
160
+ // One word on an attribute that is neither copy nor data is a setting, not text.
161
+ const setting = !numeric && !nested(attr) && !LABEL_ATTR.test(leaf) && !DATA_ATTR.test(leaf);
162
+ if (setting && (DATA_TAG.test(ctx.tag) ? MACHINE_TOKEN.test(clean) : /^[\p{L}-]+$/u.test(clean))) return;
163
+ }
164
+ found.push({ text: clean, tag: ctx.tag, attr, ancestors: ctx.ancestors, line: lineOf(node), numeric });
165
+ };
166
+ // The literals an expression can come out as: itself, either branch, a fallback, a member of a list or record.
167
+ const expression = (node, ctx) => {
168
+ if (!node) return;
169
+ switch (node.kind) {
170
+ case K.StringLiteral:
171
+ case K.NoSubstitutionTemplateLiteral:
172
+ return emit(node, node.text, ctx);
173
+ case K.NumericLiteral:
174
+ return emit(node, node.text, ctx, true);
175
+ case K.TemplateExpression:
176
+ return emit(node, [node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join(" … "), ctx);
177
+ case K.PrefixUnaryExpression:
178
+ return node.operand.kind === K.NumericLiteral ? emit(node, node.getText(file), ctx, true) : undefined;
179
+ case K.ParenthesizedExpression:
180
+ case K.AsExpression:
181
+ case K.SatisfiesExpression:
182
+ case K.NonNullExpression:
183
+ return expression(node.expression, ctx);
184
+ case K.ConditionalExpression:
185
+ expression(node.whenTrue, ctx);
186
+ return expression(node.whenFalse, ctx);
187
+ case K.BinaryExpression:
188
+ if (![K.QuestionQuestionToken, K.BarBarToken, K.AmpersandAmpersandToken].includes(node.operatorToken.kind)) return;
189
+ if (node.operatorToken.kind !== K.AmpersandAmpersandToken) expression(node.left, ctx);
190
+ return expression(node.right, ctx);
191
+ case K.CallExpression:
192
+ case K.NewExpression:
193
+ // `Number("12")`, `new Date("2026-10-21")`: a sample a template wrapped.
194
+ if (node.expression.kind === K.Identifier && ["Number", "String", "Date"].includes(node.expression.text)) for (const arg of node.arguments ?? []) expression(arg, ctx);
195
+ return;
196
+ case K.ArrayLiteralExpression:
197
+ if (ctx.attr === "child") return;
198
+ for (const element of node.elements) expression(element, { ...ctx, attr: `${ctx.attr}[]` });
199
+ return;
200
+ case K.ObjectLiteralExpression:
201
+ if (ctx.attr === "child") return;
202
+ for (const member of node.properties) {
203
+ if (member.kind !== K.PropertyAssignment || !member.name) continue;
204
+ const name = member.name.kind === K.ComputedPropertyName ? null : member.name.text;
205
+ if (name) expression(member.initializer, { ...ctx, attr: `${ctx.attr}.${name}` });
206
+ }
207
+ return;
208
+ default:
209
+ }
210
+ };
211
+ const attributes = (node, ancestors) => {
212
+ const tag = tagOf(node);
213
+ for (const attribute of node.attributes.properties) {
214
+ if (attribute.kind !== K.JsxAttribute || !attribute.initializer) continue;
215
+ const ctx = { tag, attr: attribute.name.getText(file), ancestors };
216
+ if (attribute.initializer.kind === K.StringLiteral) emit(attribute.initializer, attribute.initializer.text, ctx);
217
+ else if (attribute.initializer.kind === K.JsxExpression) {
218
+ expression(attribute.initializer.expression, ctx);
219
+ if (attribute.initializer.expression) visit(attribute.initializer.expression, [tag, ...ancestors]);
220
+ } else visit(attribute.initializer, [tag, ...ancestors]);
221
+ }
222
+ };
223
+ const children = (nodes, tag, ancestors) => {
224
+ for (const child of nodes) {
225
+ if (child.kind === K.JsxText) emit(child, child.text, { tag, attr: "child", ancestors });
226
+ else if (child.kind === K.JsxExpression) {
227
+ expression(child.expression, { tag, attr: "child", ancestors });
228
+ if (child.expression) visit(child.expression, [tag, ...ancestors]);
229
+ } else visit(child, [tag, ...ancestors]);
230
+ }
231
+ };
232
+ function visit(node, ancestors) {
233
+ if (node.kind === K.JsxElement) {
234
+ attributes(node.openingElement, ancestors);
235
+ return children(node.children, tagOf(node.openingElement), ancestors);
236
+ }
237
+ if (node.kind === K.JsxSelfClosingElement) return attributes(node, ancestors);
238
+ // A fragment adds no tag: its children sit where it sits.
239
+ if (node.kind === K.JsxFragment) return children(node.children, ancestors[0] ?? "", ancestors.slice(1));
240
+ ts.forEachChild(node, (child) => visit(child, ancestors));
241
+ }
242
+ visit(file, []);
243
+ return found;
244
+ }
245
+
246
+ // Names every page may use without declaring them: the runtime's globals and TypeScript's own types.
247
+ const GLOBAL_NAMES = new Set([
248
+ ...Object.getOwnPropertyNames(globalThis),
249
+ "Record", "Pick", "Exclude", "Extract", "Omit", "Partial", "Required", "Readonly", "NonNullable", "Parameters", "ReturnType", "InstanceType", "Awaited", "PropertyKey",
250
+ "ReadonlyArray", "Iterable", "JSX", "React", "Element", "Node", "Event", "File", "Blob", "FormData", "KeyboardEvent", "MouseEvent", "FocusEvent", "ChangeEvent",
251
+ ]);
252
+ const GLOBAL_PATTERN = /^(?:HTML|SVG)\w*Element$/;
253
+
254
+ /** The identifiers a page uses that it never imports or declares. */
255
+ function undeclaredOf(ts, file) {
256
+ const K = ts.SyntaxKind;
257
+ const declared = new Set();
258
+ const used = new Map();
259
+ const bind = (name) => {
260
+ if (!name) return;
261
+ if (name.kind === K.Identifier) declared.add(name.text);
262
+ else if (name.kind === K.ObjectBindingPattern || name.kind === K.ArrayBindingPattern) for (const element of name.elements) if (element.kind === K.BindingElement) bind(element.name);
263
+ };
264
+ const DECLARES = new Set([
265
+ K.VariableDeclaration, K.Parameter, K.FunctionDeclaration, K.FunctionExpression, K.ClassDeclaration, K.InterfaceDeclaration, K.TypeAliasDeclaration, K.EnumDeclaration,
266
+ K.TypeParameter, K.ImportClause, K.ImportSpecifier, K.NamespaceImport, K.BindingElement, K.ModuleDeclaration,
267
+ ]);
268
+ // An identifier in one of these places names a member or a key, not a thing in scope.
269
+ const isName = (node) => {
270
+ const parent = node.parent;
271
+ switch (parent.kind) {
272
+ case K.PropertyAccessExpression:
273
+ case K.QualifiedName:
274
+ return (parent.name ?? parent.right) === node;
275
+ case K.PropertyAssignment:
276
+ case K.PropertySignature:
277
+ case K.MethodSignature:
278
+ case K.MethodDeclaration:
279
+ case K.PropertyDeclaration:
280
+ case K.EnumMember:
281
+ case K.JsxAttribute:
282
+ case K.JsxNamespacedName:
283
+ case K.LabeledStatement:
284
+ case K.NamedTupleMember:
285
+ return parent.name === node;
286
+ case K.BindingElement:
287
+ return parent.propertyName === node;
288
+ case K.ImportSpecifier:
289
+ case K.ExportSpecifier:
290
+ return true;
291
+ case K.JsxOpeningElement:
292
+ case K.JsxClosingElement:
293
+ case K.JsxSelfClosingElement:
294
+ // A lower-case tag is the platform's own element.
295
+ return parent.tagName === node && /^[a-z]/.test(node.text);
296
+ case K.TypePredicate:
297
+ return parent.parameterName === node;
298
+ default:
299
+ return false;
300
+ }
301
+ };
302
+ const walk = (node) => {
303
+ if (DECLARES.has(node.kind)) bind(node.name);
304
+ if (node.kind === K.Identifier && !isName(node) && !used.has(node.text)) used.set(node.text, node);
305
+ ts.forEachChild(node, walk);
306
+ };
307
+ walk(file);
308
+ return [...used.keys()].filter((name) => !declared.has(name) && !GLOBAL_NAMES.has(name) && !GLOBAL_PATTERN.test(name)).sort();
309
+ }
310
+
311
+ /** The props a page declares, and how many of them are callbacks. */
312
+ function propsOf(ts, file) {
313
+ const K = ts.SyntaxKind;
314
+ const names = [];
315
+ for (const statement of file.statements) {
316
+ if (statement.kind !== K.InterfaceDeclaration || !statement.name.text.endsWith("SurfaceProps")) continue;
317
+ for (const member of statement.members) if (member.name) names.push(member.name.getText(file));
318
+ }
319
+ return { props: names.length, handlers: names.filter((name) => /^(?:on|set|handle)[A-Z]/.test(name)).length };
320
+ }
321
+
322
+ /** What a page imports: [{ module, names }], `default` for a default import; a namespace import names nothing. */
323
+ function importsOf(ts, file) {
324
+ const K = ts.SyntaxKind;
325
+ const imports = [];
326
+ for (const statement of file.statements) {
327
+ if (statement.kind !== K.ImportDeclaration || !statement.importClause) continue;
328
+ const names = [];
329
+ if (statement.importClause.name) names.push("default");
330
+ const bindings = statement.importClause.namedBindings;
331
+ if (bindings?.kind === K.NamedImports) for (const element of bindings.elements) names.push((element.propertyName ?? element.name).text);
332
+ imports.push({ module: statement.moduleSpecifier.text, names });
333
+ }
334
+ return imports;
335
+ }
336
+
337
+ const parse = (ts, code, name = "page.surface.generated.tsx") => ts.createSourceFile(name, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
338
+
339
+ /**
340
+ * Scan one generated page. `findings` lists every literal that is not plain
341
+ * copy, each under its check; `undeclared` lists the identifiers nothing
342
+ * declares. `ts` is the TypeScript module the page is parsed with.
343
+ */
344
+ export function scanPage(ts, code) {
345
+ const file = parse(ts, code);
346
+ const findings = [];
347
+ for (const literal of literalsOf(ts, file)) {
348
+ const sorted = sort(literal);
349
+ if (sorted) findings.push({ check: sorted.check, why: sorted.why, text: literal.text, tag: literal.tag, attr: literal.attr, line: literal.line });
350
+ }
351
+ return { findings, ...propsOf(ts, file), undeclared: undeclaredOf(ts, file), imports: importsOf(ts, file) };
352
+ }
353
+
354
+ /** One page's counts: the scan's findings by check, the generator's counted unmapped layers, and one for a shallow tree. */
355
+ export function pageCounts(scan, { unmapped = 0, treeFormat } = {}) {
356
+ const counts = Object.fromEntries(CHECKS.map((check) => [check, 0]));
357
+ for (const finding of scan.findings) counts[finding.check] += 1;
358
+ counts.unmapped = unmapped;
359
+ counts.shallowInput = Number(treeFormat) >= FULL_DEPTH_TREE_FORMAT ? 0 : 1;
360
+ return counts;
361
+ }
362
+
363
+ /** The counts summed over every page, and per module. */
364
+ export function totals(pages) {
365
+ const blank = () => ({ pages: 0, ...Object.fromEntries(CHECKS.map((check) => [check, 0])) });
366
+ const all = blank();
367
+ const modules = {};
368
+ for (const id of Object.keys(pages).sort()) {
369
+ const page = pages[id];
370
+ for (const sum of [all, (modules[page.module] ??= blank())]) {
371
+ sum.pages += 1;
372
+ for (const check of CHECKS) sum[check] += page[check];
373
+ }
374
+ }
375
+ return { all, modules: Object.fromEntries(Object.entries(modules).sort(([a], [b]) => a.localeCompare(b))) };
376
+ }
377
+
378
+ // ---------------------------------------------------------------------------
379
+ // Imports: does every imported name exist where the page says it does?
380
+ // ---------------------------------------------------------------------------
381
+
382
+ const SOURCE_ENDINGS = ["", ".ts", ".tsx", "/index.ts", "/index.tsx"];
383
+ const sourceFile = (path) => SOURCE_ENDINGS.map((ending) => path + ending).find((candidate) => existsSync(candidate) && !isDirectory(candidate)) ?? null;
384
+ function isDirectory(path) {
385
+ try {
386
+ readdirSync(path);
387
+ return true;
388
+ } catch {
389
+ return false;
390
+ }
391
+ }
392
+
393
+ /**
394
+ * The names a source file exports, read from its syntax and followed through
395
+ * `export * from "./x"`. `open` is true when it re-exports a module this cannot
396
+ * read (another package), so a name missing here may still exist.
397
+ */
398
+ function exportsOf(ts, path, cache, seen = new Set()) {
399
+ if (cache.has(path)) return cache.get(path);
400
+ const result = { names: new Set(), open: false };
401
+ if (seen.has(path)) return result;
402
+ seen.add(path);
403
+ const K = ts.SyntaxKind;
404
+ const file = parse(ts, readFileSync(path, "utf8"), path);
405
+ const follow = (specifier) => {
406
+ const target = specifier.startsWith(".") ? sourceFile(resolve(dirname(path), specifier.replace(/\.js$/, ""))) : null;
407
+ if (!target) {
408
+ result.open = true;
409
+ return null;
410
+ }
411
+ return exportsOf(ts, target, cache, seen);
412
+ };
413
+ const bind = (name) => {
414
+ if (name.kind === K.Identifier) result.names.add(name.text);
415
+ else for (const element of name.elements ?? []) if (element.name) bind(element.name);
416
+ };
417
+ for (const statement of file.statements) {
418
+ if (statement.kind === K.ExportDeclaration) {
419
+ const from = statement.moduleSpecifier?.text;
420
+ if (!statement.exportClause) {
421
+ const inner = from ? follow(from) : null;
422
+ if (inner) {
423
+ for (const name of inner.names) if (name !== "default") result.names.add(name);
424
+ result.open ||= inner.open;
425
+ }
426
+ } else if (statement.exportClause.kind === K.NamedExports) for (const element of statement.exportClause.elements) result.names.add(element.name.text);
427
+ else result.names.add(statement.exportClause.name.text);
428
+ continue;
429
+ }
430
+ if (statement.kind === K.ExportAssignment) {
431
+ result.names.add("default");
432
+ continue;
433
+ }
434
+ const modifiers = statement.modifiers ?? [];
435
+ if (!modifiers.some((m) => m.kind === K.ExportKeyword)) continue;
436
+ if (modifiers.some((m) => m.kind === K.DefaultKeyword)) result.names.add("default");
437
+ else if (statement.kind === K.VariableStatement) for (const declaration of statement.declarationList.declarations) bind(declaration.name);
438
+ else if (statement.name) result.names.add(statement.name.text);
439
+ }
440
+ cache.set(path, result);
441
+ return result;
442
+ }
443
+
444
+ const WORKSPACE_PACKAGE = /^@cognion-nucleus\/nodii-([a-z-]+)$/;
445
+
446
+ /** The imports of one page that name nothing: an unknown module, or a name its module does not export. */
447
+ function unresolvedImports(ts, root, pageFile, imports, cache) {
448
+ const missing = [];
449
+ for (const { module, names } of imports) {
450
+ const workspace = WORKSPACE_PACKAGE.exec(module);
451
+ // Anything else (react) is the platform's, not the design system's.
452
+ if (!workspace && !module.startsWith(".")) continue;
453
+ const entry = workspace ? sourceFile(join(root, "packages", workspace[1], "src", "index")) : sourceFile(resolve(dirname(join(root, pageFile)), module));
454
+ if (!entry) {
455
+ missing.push(`module ${module}`);
456
+ continue;
457
+ }
458
+ const exported = exportsOf(ts, entry, cache);
459
+ if (exported.open) continue;
460
+ for (const name of names) if (!exported.names.has(name)) missing.push(`${name} from ${module}`);
461
+ }
462
+ return missing;
463
+ }
464
+
465
+ // ---------------------------------------------------------------------------
466
+ // The baseline: one count per check per page; it only shrinks
467
+ // ---------------------------------------------------------------------------
468
+
469
+ /** Read and validate a baseline file's text. */
470
+ export function parseBaseline(text) {
471
+ const invalid = (why) => new CliError("CORPUS_BASELINE_INVALID", `The corpus baseline is not valid: ${why}`, 1);
472
+ let value;
473
+ try {
474
+ value = JSON.parse(text);
475
+ } catch (error) {
476
+ throw invalid(`it is not JSON (${error.message})`);
477
+ }
478
+ const isRecord = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
479
+ if (!isRecord(value) || !isRecord(value.pages)) throw invalid('it needs a "pages" object, one entry per page');
480
+ for (const [id, page] of Object.entries(value.pages)) {
481
+ if (!isRecord(page)) throw invalid(`${id} is not an object`);
482
+ if (typeof page.module !== "string" || !page.module) throw invalid(`${id} names no module`);
483
+ for (const check of CHECKS) if (!Number.isInteger(page[check]) || page[check] < 0) throw invalid(`${id}: ${check} must be a whole number of zero or more, got ${JSON.stringify(page[check])}`);
484
+ }
485
+ return value;
486
+ }
487
+
488
+ const BASELINE_COMMENT =
489
+ "The corpus gate's baseline (nodii-dev surface corpus; docs/generator-plan/README.md section d): for each generated page, the count of each check on fresh output. It only shrinks: rewrite it with `nodii-dev surface corpus --update`, which refuses to raise a count. Never edit it by hand.";
490
+
491
+ /** The baseline file's text: one line per page, pages in order, so a change reads as one line. */
492
+ export function baselineText(baseline) {
493
+ const ids = Object.keys(baseline.pages).sort();
494
+ const row = (id) => ` ${JSON.stringify(id)}: { ${["module", ...CHECKS].map((key) => `${JSON.stringify(key)}: ${JSON.stringify(baseline.pages[id][key])}`).join(", ")} }`;
495
+ return `{\n "$comment": ${JSON.stringify(BASELINE_COMMENT)},\n "pages": {\n${ids.map(row).join(",\n")}\n }\n}\n`;
496
+ }
497
+
498
+ /**
499
+ * Hold a run to the baseline. It fails on a Surface that throws, an identifier
500
+ * or import that resolves to nothing, a run with no pages (MW2-17), a baseline
501
+ * page the run did not produce, a page the baseline does not know, and any
502
+ * count that differs: higher is a regression, lower must be written down with
503
+ * --update in the same change, so a later regression cannot hide in the slack.
504
+ */
505
+ export function compareBaseline(baseline, run) {
506
+ const failures = [];
507
+ const threw = new Set();
508
+ for (const error of run.errors ?? []) {
509
+ threw.add(error.page);
510
+ failures.push({ kind: "throws", page: error.page, code: error.code, message: error.message });
511
+ }
512
+ for (const entry of run.undeclared ?? []) failures.push({ kind: "undeclared", page: entry.page, names: entry.names });
513
+ for (const entry of run.unresolved ?? []) failures.push({ kind: "unresolved", page: entry.page, names: entry.names });
514
+ const now = run.pages;
515
+ if (!Object.keys(now).length && !failures.length) return { failures: [{ kind: "empty" }] };
516
+ for (const id of [...new Set([...Object.keys(baseline.pages), ...Object.keys(now)])].sort()) {
517
+ const before = baseline.pages[id];
518
+ const after = now[id];
519
+ if (!after) {
520
+ if (!threw.has(id)) failures.push({ kind: "missing", page: id });
521
+ } else if (!before) failures.push({ kind: "new", page: id });
522
+ else for (const check of CHECKS) if (after[check] !== before[check]) failures.push({ kind: after[check] > before[check] ? "raised" : "lowered", page: id, check, baseline: before[check], now: after[check] });
523
+ }
524
+ return { failures };
525
+ }
526
+
527
+ const SHOWN = 20;
528
+ const shown = (lines) => (lines.length > SHOWN ? [...lines.slice(0, SHOWN), `and ${lines.length - SHOWN} more`] : lines);
529
+
530
+ /**
531
+ * The baseline a run may be written as. Refused when the run failed, when any
532
+ * count would rise, or when a page would be dropped. The one way a count rises
533
+ * or a page goes is a later design-system commit (`refMoved`): the Surfaces
534
+ * changed, the generator did not. That commit is refused outright beside a
535
+ * generator change (`generatorChanged`, MW8-17.15). A page new to the corpus
536
+ * enters with what it has.
537
+ */
538
+ export function nextBaseline(baseline, run, { refMoved = false, generatorChanged = true } = {}) {
539
+ const broken = [...(run.errors ?? []).map((e) => `${e.page}: ${e.code}`), ...(run.undeclared ?? []).map((e) => `${e.page}: undeclared ${e.names.join(", ")}`), ...(run.unresolved ?? []).map((e) => `${e.page}: unresolved ${e.names.join(", ")}`)];
540
+ if (broken.length || !Object.keys(run.pages).length)
541
+ throw new CliError("CORPUS_RUN_FAILED", `--update writes a baseline only from a run that generated every page: ${broken.length ? shown(broken).join("; ") : "this run produced no page"}`, 1);
542
+ if (refMoved && generatorChanged)
543
+ throw new CliError(
544
+ "CORPUS_REF_WITH_GENERATOR_CHANGE",
545
+ "A later design-system commit enters the baseline only in a change that touches no generator source (MW8-17.15): this checkout's generator sources differ from origin/main. Land the generator change first, or take the commit from a clean checkout of main.",
546
+ 1,
547
+ );
548
+ if (!refMoved) {
549
+ const raised = [];
550
+ for (const id of Object.keys(baseline.pages).sort()) {
551
+ const after = run.pages[id];
552
+ if (!after) raised.push(`${id}: no longer generated`);
553
+ else for (const check of CHECKS) if (after[check] > baseline.pages[id][check]) raised.push(`${id}: ${LABEL[check]} ${baseline.pages[id][check]} → ${after[check]}`);
554
+ }
555
+ if (raised.length)
556
+ throw new CliError(
557
+ "CORPUS_BASELINE_RAISED",
558
+ `The baseline only shrinks, so --update refuses this run: ${shown(raised).join("; ")}. Fix the generator, never the baseline.`,
559
+ 1,
560
+ );
561
+ }
562
+ const pages = {};
563
+ for (const id of Object.keys(run.pages).sort()) pages[id] = { module: run.pages[id].module, ...Object.fromEntries(CHECKS.map((check) => [check, run.pages[id][check]])) };
564
+ return { pages };
565
+ }
566
+
567
+ // ---------------------------------------------------------------------------
568
+ // The corpus: a design-system checkout at the pinned commit
569
+ // ---------------------------------------------------------------------------
570
+
571
+ const git = (exec, cwd, args) => String(exec("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 16 * 1024 * 1024 })).trim();
572
+
573
+ /**
574
+ * The design-system repository on this machine, when there is one: the path in
575
+ * NODII_CORPUS_DS, else `design-system` beside this repository's main checkout.
576
+ * It may be a bare repository; it must hold the installed dependencies.
577
+ */
578
+ export function corpusSource({ env = process.env, exec = execFileSync, from = dirname(fileURLToPath(import.meta.url)) } = {}) {
579
+ if (env.NODII_CORPUS_DS) return resolve(env.NODII_CORPUS_DS);
580
+ try {
581
+ const common = git(exec, from, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
582
+ const beside = join(dirname(dirname(common)), "design-system");
583
+ return existsSync(join(beside, "node_modules")) ? beside : null;
584
+ } catch {
585
+ return null;
586
+ }
587
+ }
588
+
589
+ /** The TypeScript a design-system checkout has installed: the scan parses pages with it, so this CLI carries no parser. */
590
+ export function loadTypescript(source) {
591
+ try {
592
+ return createRequire(join(source, "package.json"))("typescript");
593
+ } catch {
594
+ throw new CliError("CORPUS_DEPENDENCIES_MISSING", `No TypeScript under ${source}/node_modules: run pnpm install in the design-system checkout`, 1);
595
+ }
596
+ }
597
+
598
+ const defaultCache = () => join(homedir(), ".cache", "nodii-dev", "surface-corpus");
599
+
600
+ /**
601
+ * A design-system working tree at commit REF, for reading only. When SOURCE is
602
+ * a checkout at that commit with nothing uncommitted it is used as it is. Otherwise the commit
603
+ * is exported once (`git archive`, no worktree, nothing written into SOURCE)
604
+ * into a cache directory named by the commit, with SOURCE's installed
605
+ * dependencies linked in.
606
+ */
607
+ export function corpusCheckout(source, ref, { exec = execFileSync, cacheDir = defaultCache() } = {}) {
608
+ let commit;
609
+ try {
610
+ commit = git(exec, source, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
611
+ } catch {
612
+ throw new CliError("CORPUS_REF_UNKNOWN", `${source} has no commit ${ref}: fetch design-system (git -C ${source} fetch origin) and run again`, 1);
613
+ }
614
+ if (existsSync(join(source, CATALOG_PATH))) {
615
+ let head = null;
616
+ try {
617
+ head = git(exec, source, ["rev-parse", "HEAD"]);
618
+ } catch {
619
+ /* not a working tree: export below */
620
+ }
621
+ // Read as it is only when it is exactly the commit: an uncommitted change there is not the corpus.
622
+ let clean = false;
623
+ try {
624
+ clean = head === commit && git(exec, source, ["status", "--porcelain"]) === "";
625
+ } catch {
626
+ /* unreadable: export below */
627
+ }
628
+ if (clean) return { root: source, commit };
629
+ }
630
+ if (!existsSync(join(source, "node_modules")))
631
+ throw new CliError("CORPUS_DEPENDENCIES_MISSING", `${source} has no node_modules: run pnpm install there (the catalog loads through tsx, the templates through the figma CLI)`, 1);
632
+ const root = join(cacheDir, commit);
633
+ if (existsSync(join(root, ".corpus-complete"))) return { root, commit };
634
+ const staging = `${root}.${process.pid}.tmp`;
635
+ rmSync(staging, { recursive: true, force: true });
636
+ mkdirSync(staging, { recursive: true });
637
+ try {
638
+ exec("sh", ["-c", 'git -C "$1" archive "$2" | tar -x -C "$3"', "corpus-export", source, commit, staging], { stdio: ["ignore", "ignore", "pipe"] });
639
+ symlinkSync(join(source, "node_modules"), join(staging, "node_modules"));
640
+ for (const group of ["packages", "apps"]) {
641
+ if (!existsSync(join(staging, group))) continue;
642
+ for (const name of readdirSync(join(staging, group))) {
643
+ const installed = join(source, group, name, "node_modules");
644
+ if (existsSync(installed) && !existsSync(join(staging, group, name, "node_modules"))) symlinkSync(installed, join(staging, group, name, "node_modules"));
645
+ }
646
+ }
647
+ writeFileSync(join(staging, ".corpus-complete"), `${commit}\n`);
648
+ rmSync(root, { recursive: true, force: true });
649
+ renameSync(staging, root);
650
+ } catch (error) {
651
+ rmSync(staging, { recursive: true, force: true });
652
+ throw new CliError("CORPUS_EXPORT_FAILED", `Could not export design-system ${commit.slice(0, 9)} from ${source}: ${String(error.stderr || error.message).trim().split("\n").slice(-2).join(" ")}`, 1);
653
+ }
654
+ return { root, commit };
655
+ }
656
+
657
+ /**
658
+ * Regenerate every catalog Surface that has a committed tree and scan what the
659
+ * generator wrote. Nothing is written into ROOT. `module` narrows the run.
660
+ */
661
+ export async function runCorpus(root, { exec = execFileSync, module, ts = loadTypescript(root), surface, docs } = {}) {
662
+ const s = surface ?? (await import("./surface.js"));
663
+ const rows = s.loadCatalog(root, { exec });
664
+ const ds = s.loadDesignSystem(root, { exec, docs });
665
+ const targets = s.selectTargets(rows, undefined, { all: true, module });
666
+ const run = { generatorFormat: s.GENERATOR_FORMAT, pages: {}, errors: [], undeclared: [], unresolved: [], noTree: [], findings: {}, props: {}, files: {} };
667
+ const exported = new Map();
668
+ for (const row of targets) {
669
+ const path = s.treePath(root, row);
670
+ if (!existsSync(path)) {
671
+ run.noTree.push(row.id);
672
+ continue;
673
+ }
674
+ let emitted;
675
+ let tree;
676
+ try {
677
+ tree = JSON.parse(readFileSync(path, "utf8"));
678
+ emitted = s.emitSurface(tree, row, ds);
679
+ } catch (error) {
680
+ run.errors.push({ page: row.id, code: error?.code ?? "ERROR", message: String(error?.message ?? error).split("\n")[0] });
681
+ continue;
682
+ }
683
+ const file = relative(root, s.generatedPath(root, row)).split("\\").join("/");
684
+ const scan = scanPage(ts, emitted.code);
685
+ // The generator's own count of layers with no Code Connect mapping, by its own rule of what counts.
686
+ const unmapped = s.surfaceScoreboard([row], [{ row, tree, ...emitted }])[0].unmapped;
687
+ run.pages[row.id] = { module: row.product ?? "no module", ...pageCounts(scan, { unmapped, treeFormat: tree.treeFormat }) };
688
+ run.findings[row.id] = scan.findings;
689
+ run.props[row.id] = { props: scan.props, handlers: scan.handlers };
690
+ run.files[row.id] = file;
691
+ if (scan.undeclared.length) run.undeclared.push({ page: row.id, names: scan.undeclared });
692
+ const missing = unresolvedImports(ts, root, file, scan.imports, exported);
693
+ if (missing.length) run.unresolved.push({ page: row.id, names: missing });
694
+ }
695
+ run.withoutRow = s.generatedWithoutCatalogRow(root, rows, { module }).map((page) => page.file);
696
+ return run;
697
+ }
698
+
699
+ /** The generator's own sources: a change to any of them is a generator change. */
700
+ export const GENERATOR_SOURCES = ["packages/dev/src/surface.js", "packages/dev/src/surface", "packages/dev/src/vendor", "packages/dev/src/surface-corpus.js"];
701
+
702
+ /**
703
+ * True unless DIR is inside a checkout whose generator sources, committed and
704
+ * uncommitted, equal origin/main's. It fails closed: no repository, or no
705
+ * origin/main, counts as changed.
706
+ */
707
+ export function generatorChangedIn(dir, exec = execFileSync) {
708
+ try {
709
+ const top = git(exec, dir, ["rev-parse", "--show-toplevel"]);
710
+ // Unlanded work is what differs from origin/main itself (MW1-30.1), plus what is not committed yet.
711
+ return git(exec, top, ["status", "--porcelain", "--", ...GENERATOR_SOURCES]) !== "" || git(exec, top, ["diff", "--name-only", "origin/main", "HEAD", "--", ...GENERATOR_SOURCES]) !== "";
712
+ } catch {
713
+ return true;
714
+ }
715
+ }
716
+
717
+ // ---------------------------------------------------------------------------
718
+ // The command
719
+ // ---------------------------------------------------------------------------
720
+
721
+ const failureText = (f) => {
722
+ switch (f.kind) {
723
+ case "empty":
724
+ return "the run produced no page: a gate that examined nothing has failed (MW2-17)";
725
+ case "throws":
726
+ return `${f.page}: the generator threw ${f.code}: ${f.message}`;
727
+ case "undeclared":
728
+ return `${f.page}: uses ${f.names.join(", ")} but never imports or declares ${f.names.length === 1 ? "it" : "them"}`;
729
+ case "unresolved":
730
+ return `${f.page}: unresolved import: ${f.names.join(", ")}`;
731
+ case "missing":
732
+ return `${f.page}: in the baseline, not generated by this run`;
733
+ case "new":
734
+ return `${f.page}: generated, not in the baseline (add it with --update)`;
735
+ case "raised":
736
+ return `${f.page}: ${LABEL[f.check]} ${f.baseline} → ${f.now}`;
737
+ default:
738
+ return `${f.page}: ${LABEL[f.check]} ${f.baseline} → ${f.now} (lower: write it down with --update in the same change)`;
739
+ }
740
+ };
741
+
742
+ const countsText = (sum) => [`${sum.pages} page${sum.pages === 1 ? "" : "s"}`, ...CHECKS.map((check) => `${sum[check]} ${LABEL[check]}`)].join("\t");
743
+
744
+ /**
745
+ * surface corpus: regenerate the corpus offline, report the counts against the
746
+ * committed baseline, exit 1 on any difference; --update rewrites the baseline
747
+ * and refuses to raise a count.
748
+ */
749
+ export async function corpusCommand(rest, f, deps = {}) {
750
+ if (rest.length) throw new CliError("USAGE", CORPUS_USAGE, 2);
751
+ for (const flag of ["ds", "ref", "module", "report", "baseline"]) if (f[flag] === true || f[flag] === "") throw new CliError("USAGE", `--${flag} needs a value\n${CORPUS_USAGE}`, 2);
752
+ if (f.update && f.module) throw new CliError("USAGE", "--update rewrites the whole baseline: run it without --module", 2);
753
+ const { exec = execFileSync, cwd = process.cwd(), checkout = corpusCheckout, run = runCorpus, generatorChanged, log = (line) => process.stderr.write(`${line}\n`) } = deps;
754
+
755
+ const baselinePath = f.baseline ? resolve(cwd, String(f.baseline)) : fileURLToPath(new URL(BASELINE_FILE, import.meta.url));
756
+ if (!existsSync(baselinePath))
757
+ throw new CliError("CORPUS_BASELINE_MISSING", `No corpus baseline at ${baselinePath}: run this from a nodii-clis checkout, or name the file with --baseline`, 1);
758
+ const baseline = parseBaseline(readFileSync(baselinePath, "utf8"));
759
+ const refPath = join(dirname(baselinePath), REF_FILE);
760
+ const pinned = existsSync(refPath) ? readFileSync(refPath, "utf8").trim() : null;
761
+ if (!f.ref && !pinned) throw new CliError("CORPUS_REF_MISSING", `No design-system commit is pinned at ${refPath}: name one with --ref`, 1);
762
+ if (pinned && !SHA.test(pinned)) throw new CliError("CORPUS_REF_INVALID", `${refPath} must hold one 40-character commit id, got ${JSON.stringify(pinned.slice(0, 60))}`, 1);
763
+
764
+ const source = f.ds ? resolve(cwd, String(f.ds)) : (deps.source ?? corpusSource({ exec }));
765
+ if (!source) throw new CliError("USAGE", `Name a design-system checkout with --ds DIR (or set NODII_CORPUS_DS)\n${CORPUS_USAGE}`, 2);
766
+ const { root, commit } = checkout(source, String(f.ref ?? pinned), { exec });
767
+ const refMoved = commit !== pinned;
768
+ const module = f.module ? String(f.module) : undefined;
769
+ log(`regenerating the corpus from design-system ${commit.slice(0, 9)} (${root})`);
770
+ const result = await run(root, { exec, module });
771
+
772
+ const inScope = (pages) => (module ? Object.fromEntries(Object.entries(pages).filter(([, page]) => page.module === module)) : pages);
773
+ const held = { pages: inScope(baseline.pages) };
774
+ let { failures } = compareBaseline(held, result);
775
+ let written = null;
776
+ if (f.update) {
777
+ const changed = (generatorChanged ?? (() => generatorChangedIn(dirname(baselinePath), exec)))();
778
+ const next = nextBaseline(baseline, result, { refMoved, generatorChanged: changed });
779
+ writeFileSync(baselinePath, baselineText(next));
780
+ if (refMoved) writeFileSync(refPath, `${commit}\n`);
781
+ written = baselinePath;
782
+ failures = [];
783
+ } else if (refMoved) {
784
+ failures.unshift({ kind: "ref", pinned, commit });
785
+ }
786
+
787
+ const sums = totals(result.pages);
788
+ const before = totals(held.pages);
789
+ if (f.report) {
790
+ const target = resolve(cwd, String(f.report));
791
+ mkdirSync(dirname(target), { recursive: true });
792
+ const pages = Object.keys(result.pages).sort().map((id) => ({ id, file: result.files?.[id] ?? null, ...result.pages[id], ...(result.props?.[id] ?? {}), findings: result.findings?.[id] ?? [] }));
793
+ writeFileSync(target, `${JSON.stringify({ designSystem: commit, generator: VERSION, generatorFormat: result.generatorFormat ?? null, totals: sums, pages }, null, 2)}\n`);
794
+ }
795
+ const text = (failure) => (failure.kind === "ref" ? `this run read design-system ${failure.commit.slice(0, 9)}, the baseline is for ${String(failure.pinned).slice(0, 9)}: take the later commit with --update, in a change that touches no generator source` : failureText(failure));
796
+ const payload = {
797
+ data: {
798
+ designSystem: commit,
799
+ pinned,
800
+ generator: VERSION,
801
+ generatorFormat: result.generatorFormat ?? null,
802
+ module: module ?? null,
803
+ totals: sums,
804
+ baselineTotals: before,
805
+ failures,
806
+ errors: result.errors ?? [],
807
+ coverage: { noTree: result.noTree ?? [], withoutCatalogRow: result.withoutRow ?? [] },
808
+ propChurn: { checked: false, reason: "no names lock yet (lane gen-names)" },
809
+ baselineWritten: written,
810
+ },
811
+ };
812
+ const human = () => {
813
+ const lines = [
814
+ `surface corpus: @nodii/dev ${VERSION}${result.generatorFormat ? `, generator format ${result.generatorFormat}` : ""}, design-system ${commit.slice(0, 9)}${module ? `, module ${module}` : ""}`,
815
+ ...Object.entries(sums.modules).map(([name, sum]) => `${name}\t${countsText(sum)}`),
816
+ `all\t${countsText(sums.all)}`,
817
+ `baseline\t${countsText(before.all)}`,
818
+ `coverage: ${(result.noTree ?? []).length} catalog Surface${(result.noTree ?? []).length === 1 ? "" : "s"} with no committed tree, ${(result.withoutRow ?? []).length} committed page${(result.withoutRow ?? []).length === 1 ? "" : "s"} with no catalog row (reported, not held)`,
819
+ "prop churn: not checked (no names lock yet; lane gen-names turns it on)",
820
+ ];
821
+ if (written) lines.push(`baseline written: ${written}${refMoved ? ` and ${refPath}` : ""}`);
822
+ if (failures.length) {
823
+ lines.push("", ...shown(failures.map(text)));
824
+ const lowered = failures.some((x) => x.kind === "lowered" || x.kind === "new");
825
+ lines.push(`SURFACE_CORPUS_FAILED: ${failures.length} difference${failures.length === 1 ? "" : "s"} from the baseline.${lowered ? " A count that fell is written down with `nodii-dev surface corpus --update`, which refuses to raise one." : ""}`);
826
+ } else if (!written) lines.push("equal to the baseline");
827
+ return lines.join("\n");
828
+ };
829
+ return { payload, human, exitCode: failures.length ? 1 : 0 };
830
+ }