@magmonium/cli 0.8.29 → 0.10.1

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,780 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { execFileSync } = require('child_process');
4
+ const { stringify } = require('yaml');
5
+ const pkg = require('../../package.json');
6
+ const { readDesignFiles, isNewer } = require('./gen-code');
7
+
8
+ const DESIGN_ROOT = '.magmonium';
9
+ const THEME_FOLDER = 'theme';
10
+ const THEME_INVARIANT = 'theme-selection-resolves';
11
+
12
+ /**
13
+ * The editor's codegen, its Invariant catalogue and its `swagger.json` reader,
14
+ * bundled side by side at build time (ADR 0181). The last two reach codegen as
15
+ * the sibling bundle, so all three read one copy of every helper.
16
+ */
17
+ function loadBundles() {
18
+ const dir = path.join(__dirname, '..', '..', 'codegen');
19
+ const names = {
20
+ codegen: 'index.js',
21
+ invariants: 'invariant-catalog.js',
22
+ gestures: 'gesture-catalog.js',
23
+ inspections: 'inspect-catalog.js',
24
+ swagger: 'swagger-helper.js',
25
+ };
26
+ const missing = Object.values(names).filter(
27
+ (name) => !fs.existsSync(path.join(dir, name))
28
+ );
29
+ if (missing.length) {
30
+ throw new Error(
31
+ `codegen bundle not found in ${dir} (${missing.join(', ')}) — run \`npx nx build cli\` and use dist/libs/cli`
32
+ );
33
+ }
34
+ return Object.fromEntries(
35
+ Object.entries(names).map(([key, name]) => [
36
+ key,
37
+ require(path.join(dir, name)),
38
+ ])
39
+ );
40
+ }
41
+
42
+ /**
43
+ * The AppTarget's `swagger.json` read the way the editor reads it — a URL, a
44
+ * file, or by default the one the Environment's backend serves (GLOSSARY.md
45
+ * ApiOperation). Never persisted; what outlives the read is the operations
46
+ * snapshot `--write` stores for the StoreMethods drawn from it (ADR 0181).
47
+ */
48
+ async function readApiSpec(bundles, spec, appTarget) {
49
+ const where =
50
+ spec ||
51
+ (appTarget &&
52
+ bundles.codegen.swaggerUrlFromBackend(
53
+ appTarget.environment.hosts.backendUrl
54
+ ));
55
+ if (!where)
56
+ throw new Error('no --spec and no backend URL to read swagger.json from');
57
+ let raw;
58
+ if (/^https?:\/\//i.test(where)) {
59
+ const response = await fetch(where);
60
+ if (!response.ok) throw new Error(`${where} answered ${response.status}`);
61
+ raw = await response.json();
62
+ } else {
63
+ raw = JSON.parse(fs.readFileSync(path.resolve(where), 'utf8'));
64
+ }
65
+ return { where, spec: bundles.swagger.readSpec(raw) };
66
+ }
67
+
68
+ // Every API StoreMethod — a Feature's own and its SubStores' — with where it
69
+ // sits, so one that resolves to no ApiOperation is named rather than emitted
70
+ // wrong. A StorageMethod and a CacheMethod call no endpoint and resolve to none.
71
+ function unresolvedMethods(codegen, features, operationOf) {
72
+ const callsApi = (method) =>
73
+ !codegen.isStorageMethod(method) && !codegen.isCacheMethod(method);
74
+ return Object.values(features).flatMap((feature) =>
75
+ [
76
+ ['', feature.methods],
77
+ ...Object.entries(feature.subStores || {}).map(([id, sub]) => [
78
+ id,
79
+ sub.methods,
80
+ ]),
81
+ ].flatMap(([subStoreId, methods]) =>
82
+ Object.values(methods || {})
83
+ .filter((method) => callsApi(method) && !operationOf(method))
84
+ .map((method) => ({
85
+ id: `method-operation-resolves::${feature.id}:${method.id}`,
86
+ invariant: 'method-operation-resolves',
87
+ message: 'invariant-method-operation-unresolved',
88
+ subject: `${feature.name}.${method.name} → ${method.verb} ${method.path}`,
89
+ severity: 'blocking',
90
+ target: {
91
+ kind: 'panel',
92
+ panel: 'store',
93
+ featureId: feature.id,
94
+ ...(subStoreId ? { subStoreId } : {}),
95
+ memberId: method.id,
96
+ },
97
+ }))
98
+ )
99
+ );
100
+ }
101
+
102
+ /**
103
+ * What the editor's gestures refuse and so never wrote as an Invariant
104
+ * (ADR 0041): a Control the ControlRelationship whitelist would not have let
105
+ * land where it sits, a type no ControlType names, a child id with no Control,
106
+ * a `parentId` disagreeing with the `childrens` that list it. A design drawn in
107
+ * the editor cannot hold one; a design written by hand can.
108
+ */
109
+ function placementBreaches(codegen, screens) {
110
+ const known = new Set(Object.values(codegen.ControlType));
111
+ const breach = (screen, controlId, subject) => ({
112
+ id: `control-placement::${screen.meta.id}:${controlId}`,
113
+ invariant: 'control-placement',
114
+ message: 'invariant-control-placement',
115
+ subject: `${screen.meta.name} → ${subject}`,
116
+ severity: 'blocking',
117
+ target: { kind: 'control', screenId: screen.meta.id, controlId },
118
+ });
119
+ return screens.flatMap((screen) => {
120
+ const map = screen.state.controlMap || {};
121
+ const found = [];
122
+ (screen.state.rootControlIds || []).forEach((id) => {
123
+ if (!map[id]) found.push(breach(screen, id, `root ${id} has no Control`));
124
+ });
125
+ Object.values(map).forEach((control) => {
126
+ if (!known.has(control.type)) {
127
+ found.push(
128
+ breach(screen, control.id, `unknown type "${control.type}"`)
129
+ );
130
+ return;
131
+ }
132
+ (control.childrens || []).forEach((childId) => {
133
+ const child = map[childId];
134
+ if (!child) {
135
+ found.push(
136
+ breach(screen, control.id, `child ${childId} has no Control`)
137
+ );
138
+ } else if (child.parentId !== control.id) {
139
+ found.push(
140
+ breach(
141
+ screen,
142
+ childId,
143
+ `parentId is not ${control.type} ${control.id}`
144
+ )
145
+ );
146
+ }
147
+ });
148
+ const parent = control.parentId ? map[control.parentId] : undefined;
149
+ if (control.parentId && !parent) {
150
+ found.push(
151
+ breach(
152
+ screen,
153
+ control.id,
154
+ `parent ${control.parentId} has no Control`
155
+ )
156
+ );
157
+ return;
158
+ }
159
+ if (
160
+ !parent &&
161
+ !(screen.state.rootControlIds || []).includes(control.id)
162
+ ) {
163
+ found.push(breach(screen, control.id, 'no parent and not a root'));
164
+ return;
165
+ }
166
+ // Asked as the drop would have been: the parent without this child, so
167
+ // a cardinality cap counts the siblings and not the Control itself.
168
+ const without = parent
169
+ ? {
170
+ ...map,
171
+ [parent.id]: {
172
+ ...parent,
173
+ childrens: (parent.childrens || []).filter(
174
+ (id) => id !== control.id
175
+ ),
176
+ },
177
+ }
178
+ : map;
179
+ if (
180
+ !codegen.canPlaceChild(
181
+ parent ? without[parent.id] : undefined,
182
+ control.type,
183
+ without
184
+ )
185
+ ) {
186
+ found.push(
187
+ breach(
188
+ screen,
189
+ control.id,
190
+ `${control.type} may not sit under ${parent ? parent.type : 'the Screen root'}`
191
+ )
192
+ );
193
+ }
194
+ });
195
+ return found;
196
+ });
197
+ }
198
+
199
+ /**
200
+ * What the Nav tree's gestures refuse and so never wrote as an Invariant
201
+ * (ADR 0041): a child id with no Nav, an App Nav no parent lists or two
202
+ * parents list, a child whose navId does not extend its parent's, two Default
203
+ * Navs in one sibling set, a `pageId` naming no routed Screen, a
204
+ * `componentKey` naming a Screen that is not an App Widget.
205
+ */
206
+ function navBreaches(source, navMap = source.navMap || {}) {
207
+ const screens = new Map(source.screens.map(({ meta }) => [meta.id, meta]));
208
+ const breach = (navId, subject) => ({
209
+ id: `nav-structure::${navId}:${subject}`,
210
+ invariant: 'nav-structure',
211
+ message: 'invariant-nav-structure',
212
+ subject: `${navId} → ${subject}`,
213
+ severity: 'blocking',
214
+ target: { kind: 'nav', navId },
215
+ });
216
+ const found = [];
217
+ const parentsOf = new Map();
218
+ Object.values(navMap).forEach((nav) => {
219
+ (nav.children || []).forEach((childId) => {
220
+ if (!navMap[childId]) {
221
+ found.push(breach(nav.navId, `child ${childId} has no Nav`));
222
+ return;
223
+ }
224
+ parentsOf.set(childId, [...(parentsOf.get(childId) || []), nav.navId]);
225
+ if (!childId.startsWith(`${nav.navId}_`)) {
226
+ found.push(
227
+ breach(childId, `navId does not extend its parent ${nav.navId}`)
228
+ );
229
+ }
230
+ });
231
+ const defaults = (nav.children || []).filter(
232
+ (childId) => navMap[childId] && navMap[childId].isDefault
233
+ );
234
+ if (defaults.length > 1) {
235
+ found.push(
236
+ breach(
237
+ nav.navId,
238
+ `${defaults.length} Default Navs: ${defaults.join(', ')}`
239
+ )
240
+ );
241
+ }
242
+ if (nav.pageId) {
243
+ const screen = screens.get(nav.pageId);
244
+ if (!screen)
245
+ found.push(breach(nav.navId, `pageId ${nav.pageId} names no Screen`));
246
+ else if (screen.kind !== 'page' && screen.kind !== 'feature') {
247
+ found.push(
248
+ breach(
249
+ nav.navId,
250
+ `pageId names ${screen.kind} ${screen.name}, not a page or feature Screen`
251
+ )
252
+ );
253
+ }
254
+ }
255
+ const widget = nav.componentKey && screens.get(nav.componentKey);
256
+ if (widget && widget.kind !== 'app_widget') {
257
+ found.push(
258
+ breach(
259
+ nav.navId,
260
+ `componentKey names ${widget.kind} ${widget.name}, not an App Widget`
261
+ )
262
+ );
263
+ }
264
+ });
265
+ Object.values(navMap).forEach((nav) => {
266
+ if (nav.navId === 'root') return;
267
+ const parents = parentsOf.get(nav.navId) || [];
268
+ if (!parents.length) found.push(breach(nav.navId, 'no parent lists it'));
269
+ if (parents.length > 1)
270
+ found.push(breach(nav.navId, `listed by ${parents.join(', ')}`));
271
+ });
272
+ return found;
273
+ }
274
+
275
+ // The same questions of `nav.json` as written, before the codec reads it. The
276
+ // codec repairs an orphaned Nav and a second Default Nav on read, and does so
277
+ // silently — keeping the old default drops the claim that was just written —
278
+ // so a hand-written tree is judged as it stands on disk.
279
+ function rawNavBreaches(source, files) {
280
+ let raw;
281
+ try {
282
+ raw = JSON.parse(files[`${DESIGN_ROOT}/nav.json`] || 'null');
283
+ } catch {
284
+ return [];
285
+ }
286
+ if (!raw || !raw.navMap) return [];
287
+ const seen = new Set(navBreaches(source).map((one) => one.id));
288
+ return navBreaches(source, raw.navMap).filter((one) => !seen.has(one.id));
289
+ }
290
+
291
+ // Theme names off the two tiers the editor's catalogue reads beside the
292
+ // authored ones: the app's `mag_assets/theme/` and the library's. Undefined
293
+ // when neither folder is on disk, so the caller skips the one Invariant that
294
+ // reads it rather than reporting every library theme as missing.
295
+ function themeCatalogOf(root) {
296
+ const dirs = [
297
+ path.join(root, 'mag_assets', THEME_FOLDER),
298
+ path.join(
299
+ root,
300
+ 'node_modules',
301
+ '@magmonium',
302
+ 'one',
303
+ 'mag_assets',
304
+ THEME_FOLDER
305
+ ),
306
+ ].filter((dir) => fs.existsSync(dir));
307
+ if (!dirs.length) return undefined;
308
+ const names = dirs.flatMap((dir) =>
309
+ fs
310
+ .readdirSync(dir)
311
+ .filter((name) => !name.startsWith('.'))
312
+ .map((name) => name.replace(/\.[^.]+$/, ''))
313
+ );
314
+ return [...new Set(names)].sort();
315
+ }
316
+
317
+ // Rewrites `.magmonium/` as the editor would Save it: canonical key order,
318
+ // compacted ControlMaps, a fresh WriteId. Removes only files inside
319
+ // `.magmonium/` the rewrite no longer produces.
320
+ function writeCanonical(root, codegen, ws, operations, before) {
321
+ const files = codegen.buildDesignSource(ws, operations);
322
+ for (const [rel, contents] of Object.entries(files)) {
323
+ const target = path.join(root, rel);
324
+ fs.mkdirSync(path.dirname(target), { recursive: true });
325
+ fs.writeFileSync(target, contents);
326
+ }
327
+ const removed = Object.keys(before).filter((rel) => !(rel in files));
328
+ removed.forEach((rel) => fs.rmSync(path.join(root, rel), { force: true }));
329
+ return { written: Object.keys(files).length, removed: removed.length };
330
+ }
331
+
332
+ // `.magmonium/` as it stood at a git ref, in the shape `readDesignFiles`
333
+ // answers — the design before this change, for `--baseline`.
334
+ function readDesignFilesAt(root, ref) {
335
+ const git = (...args) =>
336
+ execFileSync('git', args, {
337
+ cwd: root,
338
+ encoding: 'utf8',
339
+ maxBuffer: 1 << 28,
340
+ });
341
+ const files = {};
342
+ git('ls-tree', '-r', '--name-only', ref, '--', DESIGN_ROOT)
343
+ .split('\n')
344
+ .filter(Boolean)
345
+ .forEach((rel) => {
346
+ files[rel] = git('show', `${ref}:${rel}`);
347
+ });
348
+ return files;
349
+ }
350
+
351
+ /**
352
+ * The AppRepo's own `typescript`, which the PureFunction body check runs on
353
+ * (0128_12) — not a dependency of the cli, so a repo without one skips the
354
+ * check and says so rather than failing.
355
+ */
356
+ function appTypeScript(root) {
357
+ try {
358
+ return require(require.resolve('typescript', { paths: [root] }));
359
+ } catch {
360
+ return undefined;
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Every PureFunction body checked the way the editor checks it: against its
366
+ * signature and the curated pure lib, so a body that does not compile or
367
+ * reaches past its parameters is blocking here as it is in the function
368
+ * editor (ADR 0046).
369
+ */
370
+ function bodyBreaches(bundles, source, ts) {
371
+ if (!ts) return [];
372
+ const check = bundles.gestures.functionBodyCheckFor(ts);
373
+ const owned = [
374
+ ...Object.values(source.functions || {}).map((fn) => [fn, undefined]),
375
+ ...Object.values(source.features || {}).flatMap((feature) =>
376
+ Object.values(feature.functions || {}).map((fn) => [fn, feature])
377
+ ),
378
+ ];
379
+ return owned.flatMap(([fn, feature]) => {
380
+ const problems = check(source, fn, feature && feature.id);
381
+ if (!problems.length) return [];
382
+ const first = problems[0];
383
+ return [
384
+ {
385
+ id: `function-body-invalid::${fn.id}`,
386
+ invariant: 'function-body-invalid',
387
+ message: 'invariant-function-body-invalid',
388
+ subject: `${feature ? feature.name : 'shared'} · ${fn.name} (${first.line}: ${first.message})`,
389
+ severity: 'blocking',
390
+ target: {
391
+ kind: 'function',
392
+ ...(feature ? { featureId: feature.id } : {}),
393
+ functionId: fn.id,
394
+ },
395
+ problems,
396
+ },
397
+ ];
398
+ });
399
+ }
400
+
401
+ /**
402
+ * What the emit would leave out (GLOSSARY.md EmitGap), the Repair Register's
403
+ * list: advisory, as the editor holds it — a design skill refuses any one new
404
+ * against its baseline (0128_05).
405
+ */
406
+ function emitGapAdvisories(bundles, source, operationOf) {
407
+ return bundles.invariants
408
+ .collectEmitGaps({
409
+ screens: source.screens,
410
+ features: source.features,
411
+ navMap: source.navMap,
412
+ functions: source.functions,
413
+ enums: source.enums,
414
+ operationOf,
415
+ })
416
+ .map((gap) => ({
417
+ id: `emit-gap-${gap.kind}::${gap.screenId}::${gap.subject}`,
418
+ invariant: `emit-gap-${gap.kind}`,
419
+ message: gap.message,
420
+ subject: `${gap.screenName} → ${gap.subject}${gap.detail ? ` (${gap.detail})` : ''}`,
421
+ severity: 'advisory',
422
+ target: gap.screenId
423
+ ? { kind: 'screen', screenId: gap.screenId }
424
+ : { kind: 'panel', panel: 'config' },
425
+ }));
426
+ }
427
+
428
+ // Config keys a Control carries that its inspector form does not list,
429
+ // because a side panel or the gesture itself writes them: the born name, the
430
+ // TextSource's label and `noTranslate`, a link's URLs, a table's columns, a
431
+ // menu's options, a button's key, a SubmitTarget, a pick, and a remote's or a
432
+ // doc's mount wiring (0128_12, measured on the store and invest designs).
433
+ const SIDE_PANEL_KEYS = new Set([
434
+ 'name', 'label', 'noTranslate', 'url', 'murl', 'img_sizes', 'columns',
435
+ 'options', 'buttonKey', 'submitTarget', 'selection', 'mountName', 'outFn',
436
+ 'urlMode', 'remote', 'remoteName', 'designSrc',
437
+ ]);
438
+
439
+ /**
440
+ * The English text of each message key (`message-text.json`, compiled from
441
+ * the m-one-ui i18n assets, 0129_03), so a report says what the editor says
442
+ * rather than only its key. A key with no text reads as itself.
443
+ */
444
+ let messageTexts;
445
+ // The checks only the cli makes — the editor's gestures refuse what they catch,
446
+ // so no editor panel ever says them and no i18n asset holds their text.
447
+ const CLI_MESSAGE_TEXT = {
448
+ 'invariant-codec-dropped':
449
+ 'The editor would drop this row on read — a reserved or duplicate name, a clashing Screen name, an unknown Control type',
450
+ 'invariant-control-configs':
451
+ "This Control's configs hold a key or value its inspector does not offer",
452
+ 'invariant-control-placement':
453
+ 'This Control sits where the editor would not let it land — the ControlRelationship whitelist, an unknown type, or a child or parent link that disagrees',
454
+ 'invariant-function-body-invalid': 'This PureFunction body does not compile',
455
+ 'invariant-method-operation-unresolved':
456
+ 'This StoreMethod resolves to no ApiOperation — neither the stored operations nor the spec has its verb and path',
457
+ 'invariant-nav-structure':
458
+ 'The Nav tree is malformed — a missing or doubly-listed child, a navId off its parent, two Default Navs, or a pageId or componentKey naming the wrong Screen',
459
+ };
460
+ function messageText(key) {
461
+ if (!messageTexts) {
462
+ const file = path.join(__dirname, '..', '..', 'codegen', 'message-text.json');
463
+ messageTexts = {
464
+ ...CLI_MESSAGE_TEXT,
465
+ ...(fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {}),
466
+ };
467
+ }
468
+ return messageTexts[key] ?? key;
469
+ }
470
+
471
+ function controlConfigsCatalog() {
472
+ const file = path.join(__dirname, '..', '..', 'codegen', 'control-configs.json');
473
+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : undefined;
474
+ }
475
+
476
+ /**
477
+ * A Control's `configs` read against what its inspector offers
478
+ * (`control-configs.json`, compiled from the m-form `<type>_controls.yml`):
479
+ * a key no form lists and no side panel writes, or a dropdown value the
480
+ * field does not offer. Advisory — the editor accepts both on read, and a
481
+ * form-less ControlType is not judged at all; a design skill refuses any new
482
+ * one against its baseline (0128_05).
483
+ */
484
+ function configsAdvisories(catalog, source) {
485
+ if (!catalog) return [];
486
+ // A layout key some form offers for some type (margin, padding, …) is one a
487
+ // shared mixin writes, not a typo.
488
+ const anyForm = new Set(Object.values(catalog).flatMap((keys) => Object.keys(keys)));
489
+ return source.screens.flatMap(({ meta, state }) =>
490
+ Object.values(state.controlMap || {}).flatMap((control) => {
491
+ const known = catalog[control.type];
492
+ if (!known) return [];
493
+ return Object.entries(control.configs || {}).flatMap(([key, value]) => {
494
+ const at = `${meta.name} → ${control.configs && control.configs.name ? control.configs.name : control.id}`;
495
+ const finding = (problem) => ({
496
+ id: `control-configs::${meta.id}:${control.id}:${key}`,
497
+ invariant: 'control-configs',
498
+ message: 'invariant-control-configs',
499
+ subject: `${at}: ${problem}`,
500
+ severity: 'advisory',
501
+ target: { kind: 'control', screenId: meta.id, controlId: control.id },
502
+ });
503
+ if (!(key in known)) {
504
+ return SIDE_PANEL_KEYS.has(key) || anyForm.has(key)
505
+ ? []
506
+ : [finding(`\`${key}\` is not a ${control.type} config`)];
507
+ }
508
+ const allowed = known[key];
509
+ // `''` is a dropdown's unset row; objects are bound or authored values.
510
+ if (!allowed || value === undefined || value === null || value === '' || typeof value === 'object')
511
+ return [];
512
+ return allowed.includes(String(value))
513
+ ? []
514
+ : [finding(`\`${key}: ${value}\` is not one of ${allowed.filter(Boolean).join(', ')}`)];
515
+ });
516
+ })
517
+ );
518
+ }
519
+
520
+ // Every Violation a read design holds: the editor's Invariants, plus what its
521
+ // gestures would have refused, what resolves to no ApiOperation, the rows the
522
+ // codec dropped on read, every body that does not compile, and the EmitGaps.
523
+ function findViolations(
524
+ bundles,
525
+ source,
526
+ catalog,
527
+ operationOf,
528
+ files = {},
529
+ ts = undefined
530
+ ) {
531
+ const { codegen, invariants } = bundles;
532
+ return [
533
+ ...invariants.codecDrops(files, source, DESIGN_ROOT),
534
+ ...placementBreaches(codegen, source.screens),
535
+ ...navBreaches(source),
536
+ ...rawNavBreaches(source, files),
537
+ ...unresolvedMethods(codegen, source.features, operationOf),
538
+ ...bodyBreaches(bundles, source, ts),
539
+ ...emitGapAdvisories(bundles, source, operationOf),
540
+ ...configsAdvisories(controlConfigsCatalog(), source),
541
+ ...invariants
542
+ .runInvariants(invariants.invariantScopeOf(source, catalog || []))
543
+ .filter((one) => catalog || one.invariant !== THEME_INVARIANT),
544
+ ]
545
+ .map((one) => ({ ...one, text: messageText(one.message) }))
546
+ .sort((a, b) =>
547
+ a.severity === b.severity ? 0 : a.severity === 'blocking' ? -1 : 1
548
+ );
549
+ }
550
+
551
+ /**
552
+ * Asks of `.magmonium/` what the editor asks of an open design (GLOSSARY.md
553
+ * Invariant, ADR 0041): read it through the DesignSource codec, run every
554
+ * Invariant against it, and emit it in memory. A design that passes opens in
555
+ * the editor as written and generates without throwing.
556
+ *
557
+ * `status`: `unreadable` (the codec refused), `blocking` (a blocking
558
+ * Violation, or the emit threw), `ok` (advisory Violations at most).
559
+ */
560
+ async function validate({
561
+ root = process.cwd(),
562
+ write = false,
563
+ spec,
564
+ baseline,
565
+ } = {}) {
566
+ const report = {
567
+ status: 'ok',
568
+ rewritten: false,
569
+ violations: [],
570
+ skipped: [],
571
+ emitError: undefined,
572
+ written: undefined,
573
+ };
574
+ if (!fs.existsSync(path.join(root, DESIGN_ROOT, 'index.json'))) {
575
+ return {
576
+ ...report,
577
+ status: 'unreadable',
578
+ refusal: { reason: 'absent', path: `${DESIGN_ROOT}/index.json` },
579
+ };
580
+ }
581
+
582
+ const bundles = loadBundles();
583
+ const { codegen } = bundles;
584
+ const files = readDesignFiles(root);
585
+ const read = codegen.readDesignSource(files);
586
+ if (!read.ok || !read.source) {
587
+ return {
588
+ ...report,
589
+ status: 'unreadable',
590
+ refusal: read.refusal || { reason: 'unreadable' },
591
+ };
592
+ }
593
+ const source = read.source;
594
+ if (source.codegen && isNewer(source.codegen, pkg.version)) {
595
+ return {
596
+ ...report,
597
+ status: 'unreadable',
598
+ refusal: { reason: 'newer', version: source.codegen },
599
+ };
600
+ }
601
+ // A migration or a repaired row: the editor would report this on its next
602
+ // read, and its next Save would write the change.
603
+ report.rewritten = Boolean(read.rewritten);
604
+
605
+ const catalog = themeCatalogOf(root);
606
+ if (!catalog) report.skipped.push(THEME_INVARIANT);
607
+ const ts = appTypeScript(root);
608
+ if (!ts) report.skipped.push('function-body-invalid');
609
+
610
+ // With a spec, StoreMethods resolve against it and `--write` refreshes the
611
+ // snapshot from what they draw; without one, against the snapshot as stored.
612
+ let operations = source.operations;
613
+ if (spec !== undefined) {
614
+ const fetched = await readApiSpec(bundles, spec, source.appTarget);
615
+ report.spec = fetched.where;
616
+ operations = fetched.spec.operations;
617
+ }
618
+ const ws = {
619
+ ...source,
620
+ operationOf: codegen.operationResolverOf(operations),
621
+ };
622
+ report.violations = findViolations(
623
+ bundles,
624
+ source,
625
+ catalog,
626
+ ws.operationOf,
627
+ files,
628
+ ts
629
+ );
630
+
631
+ // What the design already held at the baseline is not this change's to fix:
632
+ // marked, listed, and left out of the status.
633
+ if (baseline) {
634
+ const beforeFiles = readDesignFilesAt(root, baseline);
635
+ const before = codegen.readDesignSource(beforeFiles);
636
+ const held = new Set(
637
+ before.ok && before.source
638
+ ? findViolations(
639
+ bundles,
640
+ before.source,
641
+ catalog,
642
+ codegen.operationResolverOf(
643
+ spec === undefined ? before.source.operations : operations
644
+ ),
645
+ beforeFiles,
646
+ ts
647
+ ).map((one) => one.id)
648
+ : []
649
+ );
650
+ report.baseline = baseline;
651
+ report.violations = report.violations.map((one) =>
652
+ held.has(one.id) ? { ...one, preexisting: true } : one
653
+ );
654
+ }
655
+ try {
656
+ codegen.emitGeneratedFiles(ws, stringify, false);
657
+ } catch (error) {
658
+ report.emitError = error && error.message ? error.message : String(error);
659
+ }
660
+
661
+ if (
662
+ report.emitError ||
663
+ report.violations.some(
664
+ (one) => one.severity === 'blocking' && !one.preexisting
665
+ )
666
+ ) {
667
+ report.status = 'blocking';
668
+ }
669
+ if (write && report.status !== 'blocking') {
670
+ report.written = writeCanonical(
671
+ root,
672
+ codegen,
673
+ ws,
674
+ spec === undefined ? source.operations : codegen.drawnOperations(ws),
675
+ files
676
+ );
677
+ }
678
+ return report;
679
+ }
680
+
681
+ const EXIT = { ok: 0, blocking: 1, unreadable: 2 };
682
+
683
+ function printReport(report) {
684
+ if (report.status === 'unreadable') {
685
+ const r = report.refusal || {};
686
+ console.error(
687
+ `❌ validate: cannot read ${DESIGN_ROOT}/ (${r.reason || 'unreadable'}${
688
+ r.path ? `: ${r.path}` : ''
689
+ }${r.version ? `, v${r.version}` : ''})`
690
+ );
691
+ return;
692
+ }
693
+ if (report.rewritten) {
694
+ console.warn(
695
+ `⚠️ validate: the codec migrated or repaired a row — run with --write to store it`
696
+ );
697
+ }
698
+ report.violations.forEach((one) => {
699
+ const mark = one.preexisting
700
+ ? '· '
701
+ : one.severity === 'blocking'
702
+ ? '❌'
703
+ : '⚠️ ';
704
+ console.log(
705
+ `${mark} ${one.invariant} — ${one.subject} (${JSON.stringify(one.target)})`
706
+ );
707
+ if (one.text !== one.message) console.log(` ${one.text}`);
708
+ });
709
+ report.skipped.forEach((name) =>
710
+ console.log(`⏭️ ${name} skipped — no theme folder on disk`)
711
+ );
712
+ if (report.emitError) console.error(`❌ emit: ${report.emitError}`);
713
+ if (report.written) {
714
+ console.log(
715
+ `📝 ${DESIGN_ROOT}/ rewritten: ${report.written.written} file(s), ${report.written.removed} removed`
716
+ );
717
+ }
718
+ const fresh = report.violations.filter((one) => !one.preexisting);
719
+ const blocking = fresh.filter((one) => one.severity === 'blocking');
720
+ const held = report.violations.length - fresh.length;
721
+ const tail = held ? `, ${held} already at ${report.baseline}` : '';
722
+ console.log(
723
+ report.status === 'ok'
724
+ ? `✅ validate: ${fresh.length} advisory${tail}`
725
+ : `❌ validate: ${blocking.length} blocking, ${
726
+ fresh.length - blocking.length
727
+ } advisory${tail}${report.emitError ? ', emit failed' : ''}`
728
+ );
729
+ }
730
+
731
+ function validateCommand(program) {
732
+ program
733
+ .command('validate')
734
+ .description(
735
+ 'Check .magmonium/ the way the editor does: DesignSource codec, every Invariant, an in-memory emit'
736
+ )
737
+ .option('--root <path>', 'App root (default: cwd)')
738
+ .option('--json', 'Print the report as JSON')
739
+ .option(
740
+ '--spec [urlOrFile]',
741
+ "Resolve StoreMethods against swagger.json (default: the Environment backend's) instead of the stored operations snapshot"
742
+ )
743
+ .option(
744
+ '--baseline <ref>',
745
+ 'Mark Violations the design already held at this git ref as preexisting; only new ones decide the status'
746
+ )
747
+ .option(
748
+ '--write',
749
+ 'When nothing blocks, rewrite .magmonium/ in the form the editor saves it (canonical order, fresh write-id)'
750
+ )
751
+ .action(async (options) => {
752
+ let report;
753
+ try {
754
+ report = await validate({
755
+ root: options.root || process.cwd(),
756
+ write: Boolean(options.write),
757
+ spec: options.spec === true ? '' : options.spec,
758
+ baseline: options.baseline,
759
+ });
760
+ } catch (error) {
761
+ console.error(`❌ validate: ${error.message}`);
762
+ process.exit(2);
763
+ }
764
+ if (options.json) console.log(JSON.stringify(report, null, 2));
765
+ else printReport(report);
766
+ process.exit(EXIT[report.status]);
767
+ });
768
+ }
769
+
770
+ module.exports = validateCommand;
771
+ module.exports.validate = validate;
772
+ module.exports.loadBundles = loadBundles;
773
+ module.exports.readApiSpec = readApiSpec;
774
+ module.exports.findViolations = findViolations;
775
+ module.exports.writeCanonical = writeCanonical;
776
+ module.exports.themeCatalogOf = themeCatalogOf;
777
+ module.exports.appTypeScript = appTypeScript;
778
+ module.exports.readDesignFilesAt = readDesignFilesAt;
779
+ module.exports.messageText = messageText;
780
+ module.exports.DESIGN_ROOT = DESIGN_ROOT;