@astryxdesign/cli 0.7.15 → 0.7.16-canary.g723a112

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +5 -3
  2. package/api/component/_adapter.d.mts +1 -1
  3. package/api/component/_adapter.mjs +28 -1
  4. package/api/doctor/_adapter.d.mts +17 -0
  5. package/api/doctor/_adapter.mjs +35 -0
  6. package/api/doctor/doctor.mjs +18 -4
  7. package/api/integration/validate-integration.mjs +1 -1
  8. package/api/theme/_adapter.d.mts +5 -2
  9. package/api/theme/_adapter.mjs +43 -12
  10. package/api/theme/build/build.d.mts +15 -23
  11. package/api/theme/build/build.mjs +285 -47
  12. package/api/theme/eject/eject.mjs +22 -1
  13. package/api/theme/template/template.d.mts +19 -0
  14. package/api/theme/template/template.mjs +102 -25
  15. package/api/theme/theme.type.d.mts +5 -1
  16. package/api/theme/theme.type.mjs +2 -1
  17. package/api/theme/themeBuild.doc.mjs +3 -3
  18. package/api/theme/themeEject.doc.mjs +1 -1
  19. package/api/theme/themeTemplate.doc.mjs +9 -3
  20. package/api/theme-edit/_adapter.d.mts +33 -0
  21. package/api/theme-edit/_adapter.mjs +208 -31
  22. package/api/theme-edit/_check.d.mts +38 -0
  23. package/api/theme-edit/_check.mjs +1326 -211
  24. package/api/theme-edit/_color.d.mts +2 -8
  25. package/api/theme-edit/_color.mjs +292 -219
  26. package/api/theme-edit/_compiler.d.mts +1 -0
  27. package/api/theme-edit/_compiler.mjs +20 -1
  28. package/api/theme-edit/_context.d.mts +29 -0
  29. package/api/theme-edit/_context.mjs +329 -30
  30. package/api/theme-edit/_css.d.mts +60 -1
  31. package/api/theme-edit/_css.mjs +404 -28
  32. package/api/theme-edit/_edit.d.mts +9 -0
  33. package/api/theme-edit/_edit.mjs +1025 -126
  34. package/api/theme-edit/_how-commands.d.mts +11 -26
  35. package/api/theme-edit/_how-commands.mjs +30 -2
  36. package/api/theme-edit/_how-question.d.mts +7 -0
  37. package/api/theme-edit/_how-question.mjs +1304 -176
  38. package/api/theme-edit/_how.mjs +144 -30
  39. package/api/theme-edit/_overview.mjs +2 -0
  40. package/api/theme-edit/_palette.d.mts +11 -0
  41. package/api/theme-edit/_palette.mjs +194 -65
  42. package/api/theme-edit/_parts.d.mts +16 -0
  43. package/api/theme-edit/_parts.mjs +59 -7
  44. package/api/theme-edit/_png.mjs +19 -14
  45. package/api/theme-edit/_preview-app.d.mts +3 -0
  46. package/api/theme-edit/_preview-app.mjs +843 -45
  47. package/api/theme-edit/_preview.d.mts +15 -2
  48. package/api/theme-edit/_preview.mjs +288 -28
  49. package/api/theme-edit/_project.d.mts +11 -0
  50. package/api/theme-edit/_project.mjs +35 -9
  51. package/api/theme-edit/_settings.d.mts +178 -5
  52. package/api/theme-edit/_settings.mjs +2035 -86
  53. package/api/theme-edit/_tables.d.mts +24 -0
  54. package/api/theme-edit/_tables.mjs +211 -149
  55. package/api/theme-edit/_vet.d.mts +42 -0
  56. package/api/theme-edit/_vet.mjs +144 -0
  57. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  58. package/api/theme-edit/theme-edit.type.mjs +1 -1
  59. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  60. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  61. package/api/upgrade/registry/registry.mjs +6 -1
  62. package/assets/docs/tree/single-component.doc.mjs +11 -2
  63. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  64. package/assets/docs.generated.json +2 -2
  65. package/assets/preview-app/next.config.mjs +7 -1
  66. package/assets/preview-app/package.json +1 -0
  67. package/assets/preview-app/src/app/globals.css +1 -0
  68. package/assets/self-audit.generated.json +1 -1
  69. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  70. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  71. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  72. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  73. package/assets/templates/components.generated.json +1 -1
  74. package/assets/templates/pages/dashboard/page.tsx +1 -1
  75. package/authoring/doctypes/_schema.d.mts +52 -5
  76. package/authoring/doctypes/_schema.mjs +62 -7
  77. package/authoring/doctypes/base/type.ts +10 -0
  78. package/authoring/doctypes/component/component.doc.mjs +1 -1
  79. package/authoring/doctypes/function/function.doc.mjs +6 -0
  80. package/authoring/doctypes/function/type.ts +3 -0
  81. package/authoring/doctypes/legacy.mjs +5 -1
  82. package/authoring/index.d.ts +1 -0
  83. package/clients/cli/build-id.generated.json +1 -1
  84. package/clients/cli/commands/doctor.doc.mjs +2 -2
  85. package/clients/cli/commands/experimental/theme.mjs +190 -37
  86. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  87. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  88. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  89. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  90. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  91. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  92. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  93. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  94. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  95. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  96. package/clients/cli/commands/theme.mjs +153 -37
  97. package/clients/cli/formatters/index.mjs +7 -4
  98. package/clients/cli/lib/cli-error.mjs +9 -3
  99. package/clients/cli/lib/component-format.mjs +27 -9
  100. package/clients/cli/lib/json-shim.mjs +40 -2
  101. package/clients/cli/manifest.generated.json +1 -1
  102. package/clients/cli/run.mjs +49 -0
  103. package/foundation/config/project.mjs +50 -14
  104. package/foundation/discovery/theme-discovery.d.mts +5 -1
  105. package/foundation/discovery/theme-discovery.mjs +24 -3
  106. package/foundation/fs/gather-cache.d.mts +9 -2
  107. package/foundation/fs/gather-cache.mjs +79 -15
  108. package/foundation/fs/paths.d.mts +31 -0
  109. package/foundation/fs/paths.mjs +43 -10
  110. package/foundation/render/host-exit.d.mts +8 -0
  111. package/foundation/render/host-exit.mjs +11 -0
  112. package/foundation/render/page-host.mjs +56 -10
  113. package/foundation/render/page-worker.mjs +14 -0
  114. package/foundation/render/render-page.mjs +37 -2
  115. package/foundation/response/error-codes.d.mts +2 -1
  116. package/foundation/response/error-codes.d.ts +1 -0
  117. package/foundation/response/error-codes.doc.mjs +5 -0
  118. package/foundation/response/error-codes.mjs +3 -0
  119. package/foundation/response/json.d.mts +15 -0
  120. package/foundation/response/json.mjs +52 -1
  121. package/foundation/response/response-types.doc.mjs +1 -1
  122. package/package.json +7 -6
@@ -14,6 +14,17 @@ export function showcaseItems(project: import("./_project.mjs").ThemeProject, gr
14
14
  imports: Record<string, string>;
15
15
  skipped: string[];
16
16
  };
17
+ /**
18
+ * The fonts stylesheet of the theme a theme is built on, when its package
19
+ * ships one (`@astryxdesign/theme-neutral/fonts.css` loads Figtree): naming
20
+ * a family does not load it, and the base theme's families apply until the
21
+ * theme sets its own. Once the theme's build names none of the families the
22
+ * sheet loads, it is left out.
23
+ * @param {import('./_settings.mjs').Ctx} ctx
24
+ * @param {import('./_settings.mjs').ThemeData} data
25
+ * @returns {string[]}
26
+ */
27
+ export function baseFontsCss(ctx: import("./_settings.mjs").Ctx, data: import("./_settings.mjs").ThemeData): string[];
17
28
  /**
18
29
  * How a generated page imports the theme: its built module, its stylesheet,
19
30
  * and the stylesheets of open fonts the project has installed.
@@ -75,11 +86,13 @@ export function componentsPageSource(project: import("./_project.mjs").ThemeProj
75
86
  * boundary, so one part that throws never blanks the page. The preview
76
87
  * route is the app shell, so the page has no shell of its own.
77
88
  * @param {import('./_project.mjs').ThemeProject} project
78
- * @param {{theme?: string | null}} [options]
89
+ * @param {{theme?: string | null, colors?: boolean}} [options] `colors`:
90
+ * the preview has a Colors page, so the header points to it
79
91
  * @returns {string}
80
92
  */
81
- export function overviewPageSource(project: import("./_project.mjs").ThemeProject, { theme }?: {
93
+ export function overviewPageSource(project: import("./_project.mjs").ThemeProject, { theme, colors }?: {
82
94
  theme?: string | null;
95
+ colors?: boolean;
83
96
  }): string;
84
97
  /**
85
98
  * The source of the preview's Colors page: each generated color's shades in
@@ -12,6 +12,7 @@
12
12
  * @position api/theme-edit — previews and pictures
13
13
  */
14
14
 
15
+ import {createHash} from 'node:crypto';
15
16
  import * as fs from 'node:fs';
16
17
  import * as path from 'node:path';
17
18
  import {spawnSync} from 'node:child_process';
@@ -24,15 +25,16 @@ import {
24
25
  } from './_catalog.mjs';
25
26
  import {
26
27
  catalogVariants,
27
- isItemOf,
28
+ needsParent,
28
29
  renderDir,
29
30
  renderGenerated,
30
31
  } from './_parts.mjs';
31
32
  import {OVERVIEW_SECTIONS} from './_overview.mjs';
32
33
  import {camel, fontPackages, modesOf, themeFiles, shown} from './_settings.mjs';
33
34
  import {writeWhole} from './_palette.mjs';
35
+ import {cliVersion} from '../../foundation/release/run-context.mjs';
34
36
  import {importPathOf, installLine} from './_project.mjs';
35
- import {COLOR_PROP_PARTS, DIRECT, P} from './_tables.mjs';
37
+ import {COLOR_PROP_PARTS, DIRECT, P, wordTable} from './_tables.mjs';
36
38
  import {extractImportedPackages} from '../../foundation/discovery/template-needs.mjs';
37
39
  import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
38
40
 
@@ -187,7 +189,7 @@ function inParentOf(project, name) {
187
189
  const wrapper = info.wrapper;
188
190
  // A part its parent does not list as an item, such as a heading of the
189
191
  // text family, renders on its own.
190
- if (!wrapper) return isItemOf(project, name) ? null : tree => tree;
192
+ if (!wrapper) return needsParent(project, name) ? null : tree => tree;
191
193
  if (project.components[wrapper.component]?.wrapper) return null;
192
194
  const props = Object.fromEntries(
193
195
  Object.entries(wrapper.props).filter(([k]) => !OPEN_PROPS.includes(k)),
@@ -214,6 +216,59 @@ function templateFiles(imports) {
214
216
  });
215
217
  }
216
218
 
219
+ /**
220
+ * The fonts stylesheet of the theme a theme is built on, when its package
221
+ * ships one (`@astryxdesign/theme-neutral/fonts.css` loads Figtree): naming
222
+ * a family does not load it, and the base theme's families apply until the
223
+ * theme sets its own. Once the theme's build names none of the families the
224
+ * sheet loads, it is left out.
225
+ * @param {import('./_settings.mjs').Ctx} ctx
226
+ * @param {import('./_settings.mjs').ThemeData} data
227
+ * @returns {string[]}
228
+ */
229
+ export function baseFontsCss(ctx, data) {
230
+ if (!data.like) return [];
231
+ const pkg = `@astryxdesign/theme-${data.like}`;
232
+ const sheet = `${pkg}/fonts.css`;
233
+ // Read off disk: the package must export the sheet for an app to import
234
+ // it.
235
+ const found = findNodeModulesPackage(ctx.project.cwd, pkg);
236
+ /** @type {string} */
237
+ let text;
238
+ try {
239
+ if (!found) return [];
240
+ const exportsMap = JSON.parse(
241
+ fs.readFileSync(path.join(found.packageDir, 'package.json'), 'utf8'),
242
+ ).exports;
243
+ if (
244
+ !exportsMap ||
245
+ typeof exportsMap !== 'object' ||
246
+ !('./fonts.css' in exportsMap)
247
+ )
248
+ return [];
249
+ text = fs.readFileSync(path.join(found.packageDir, 'fonts.css'), 'utf8');
250
+ } catch {
251
+ return [];
252
+ }
253
+ // The families the sheet loads; with the theme's build at hand, the sheet
254
+ // is imported only while the build still names one of them.
255
+ const families = [...text.matchAll(/family=([^:&'")]+)/g)].map(m =>
256
+ decodeURIComponent(m[1].replace(/\+/g, ' ')),
257
+ );
258
+ /** @type {string | null} */
259
+ let built = null;
260
+ try {
261
+ built = fs.readFileSync(themeFiles(ctx.project.cwd, data.name).css, 'utf8');
262
+ } catch {
263
+ // Not built yet: the base families may still apply.
264
+ }
265
+ if (built != null && families.length) {
266
+ const css = built;
267
+ if (!families.some(f => css.includes(f))) return [];
268
+ }
269
+ return [sheet];
270
+ }
271
+
217
272
  /**
218
273
  * How a generated page imports the theme: its built module, its stylesheet,
219
274
  * and the stylesheets of open fonts the project has installed.
@@ -235,13 +290,162 @@ export function themeImports(ctx, slug, data, fromDir) {
235
290
  .map(x => `${x.pkg}/index.css`);
236
291
  return {
237
292
  module: rel(f.js),
238
- css: [rel(f.css), ...fonts],
293
+ css: [rel(f.css), ...baseFontsCss(ctx, data), ...fonts],
239
294
  mode: /** @type {'system' | 'light' | 'dark'} */ (
240
295
  modes.length > 1 ? 'system' : modes[0]
241
296
  ),
242
297
  };
243
298
  }
244
299
 
300
+ /**
301
+ * The inputs a page was rendered from and a hash of the page above it,
302
+ * recorded at the end of the page.
303
+ */
304
+ const RENDER_STAMP = /<!-- astryx: render of ([0-9a-f]{24}) ([0-9a-f]{16}) -->/;
305
+
306
+ /** @type {Map<string, string>} */
307
+ const treeKeys = new Map();
308
+
309
+ /**
310
+ * A cheap fingerprint of the files a package runs from: each file's path,
311
+ * size and modification time under its folder (node_modules left out), so a
312
+ * linked or patched copy with the same version reads as another. Once per
313
+ * process for each folder.
314
+ * @param {string | null | undefined} dir
315
+ * @returns {string}
316
+ */
317
+ function treeKey(dir) {
318
+ if (!dir) return 'none';
319
+ const known = treeKeys.get(dir);
320
+ if (known) return known;
321
+ const h = createHash('sha256');
322
+ /** @param {string} d */
323
+ const walk = d => {
324
+ let entries;
325
+ try {
326
+ entries = fs.readdirSync(d, {withFileTypes: true});
327
+ } catch {
328
+ return;
329
+ }
330
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
331
+ for (const e of entries) {
332
+ if (e.name === 'node_modules' || e.name.startsWith('.')) continue;
333
+ const p = path.join(d, e.name);
334
+ if (e.isDirectory()) walk(p);
335
+ else if (e.isFile()) {
336
+ try {
337
+ const st = fs.statSync(p);
338
+ h.update(`${path.relative(dir, p)}\0${st.size}\0${st.mtimeMs}\0`);
339
+ } catch {
340
+ // Gone meanwhile.
341
+ }
342
+ }
343
+ }
344
+ };
345
+ walk(dir);
346
+ const key = h.digest('hex').slice(0, 16);
347
+ treeKeys.set(dir, key);
348
+ return key;
349
+ }
350
+
351
+ /**
352
+ * The folder of an installed package, resolved from the project, or null.
353
+ * @param {string} cwd
354
+ * @param {string} name
355
+ */
356
+ function packageDirOf(cwd, name) {
357
+ try {
358
+ return findNodeModulesPackage(cwd, name)?.packageDir ?? null;
359
+ } catch {
360
+ return null;
361
+ }
362
+ }
363
+
364
+ /** @param {string} text */
365
+ const bodyHash = text =>
366
+ createHash('sha256').update(text).digest('hex').slice(0, 16);
367
+
368
+ /**
369
+ * A key for everything a page render reads: the CLI, Core (its version and
370
+ * stylesheet, and the files it runs from), the base theme package's files,
371
+ * the generated page source, and the theme's built stylesheet and module.
372
+ * The same key means the same page.
373
+ * @param {import('./_project.mjs').ThemeProject} project
374
+ * @param {string} slug
375
+ * @param {string} source
376
+ * @param {string | null | undefined} [like] the base theme
377
+ * @returns {string}
378
+ */
379
+ function renderKey(project, slug, source, like) {
380
+ const f = themeFiles(project.cwd, slug);
381
+ const h = createHash('sha256')
382
+ .update(cliVersion())
383
+ .update('\0')
384
+ .update(String(project.coreKey ?? ''))
385
+ .update('\0')
386
+ .update(treeKey(path.join(project.coreDir, 'dist')))
387
+ .update('\0')
388
+ .update(
389
+ like
390
+ ? treeKey(packageDirOf(project.cwd, `@astryxdesign/theme-${like}`))
391
+ : 'none',
392
+ )
393
+ .update('\0')
394
+ .update(source);
395
+ for (const file of [f.css, f.js]) {
396
+ h.update('\0');
397
+ try {
398
+ h.update(fs.readFileSync(file));
399
+ } catch {
400
+ h.update('missing');
401
+ }
402
+ }
403
+ return h.digest('hex').slice(0, 24);
404
+ }
405
+
406
+ /**
407
+ * Whether `out` is a page rendered from `key` (a no-op show renders
408
+ * nothing again).
409
+ * @param {string} out
410
+ * @param {string} key
411
+ */
412
+ function renderedFrom(out, key) {
413
+ try {
414
+ const st = fs.lstatSync(out);
415
+ if (!st.isFile()) return false;
416
+ const text = fs.readFileSync(out, 'utf8');
417
+ const m = RENDER_STAMP.exec(text);
418
+ // The page above the comment is the one rendered: an edit by hand, or
419
+ // a comment pasted under another page, is rendered again.
420
+ // Nothing may follow the comment but the sheet's own build stamp
421
+ // (written after it by show): text added after it is rendered over.
422
+ const after = m
423
+ ? text
424
+ .slice(m.index + m[0].length)
425
+ .replace(/<!-- astryx: sheet of build [0-9a-f]{16} -->/, '')
426
+ : '';
427
+ return (
428
+ m != null &&
429
+ m[1] === key &&
430
+ after.trim() === '' &&
431
+ m[2] === bodyHash(text.slice(0, m.index).trimEnd())
432
+ );
433
+ } catch {
434
+ return false;
435
+ }
436
+ }
437
+
438
+ /**
439
+ * The page with its render key recorded at its end (after the closing tag:
440
+ * a comment before the doctype would put it in quirks mode).
441
+ * @param {string} html
442
+ * @param {string} key
443
+ */
444
+ const withRenderKey = (html, key) => {
445
+ const body = html.replace(RENDER_STAMP, '').trimEnd();
446
+ return `${body}\n<!-- astryx: render of ${key} ${bodyHash(body)} -->\n`;
447
+ };
448
+
245
449
  /**
246
450
  * Render the sample app page with the theme to themes/<slug>/preview.html.
247
451
  * @param {import('./_settings.mjs').Ctx} ctx
@@ -263,10 +467,13 @@ export async function renderPreview(ctx, slug, data) {
263
467
  layout: 'page',
264
468
  title: `${slug}: sample page`,
265
469
  });
266
- const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
267
470
  const out = themeFiles(project.cwd, slug).preview;
471
+ // Rendered from the same inputs before: the page is as it would be.
472
+ const key = renderKey(project, slug, source, data.like);
473
+ if (renderedFrom(out, key)) return shown(project.cwd, out);
474
+ const {html} = await renderGenerated(project, `preview-${slug}.mjs`, source);
268
475
  // Written whole and renamed in, never through a link.
269
- writeWhole(out, html);
476
+ writeWhole(out, withRenderKey(html, key));
270
477
  return shown(project.cwd, out);
271
478
  }
272
479
 
@@ -288,12 +495,6 @@ export async function renderSheet(ctx, slug, data, options = {}) {
288
495
  layout: 'sheet',
289
496
  title: `${slug}: every component${options.group ? ` (${options.group})` : ''}`,
290
497
  });
291
- const {html} = await renderGenerated(
292
- project,
293
- `sheet-${slug}.mjs`,
294
- source,
295
- templateFiles(imports),
296
- );
297
498
  // One section goes to its own file, so the full sheet stays whole.
298
499
  const full = themeFiles(project.cwd, slug).sheet;
299
500
  const out =
@@ -301,9 +502,23 @@ export async function renderSheet(ctx, slug, data, options = {}) {
301
502
  (options.group
302
503
  ? path.join(path.dirname(full), `sheet-${options.group}.html`)
303
504
  : full);
505
+ const key = renderKey(project, slug, source, data.like);
506
+ const result = {
507
+ file: shown(project.cwd, out),
508
+ components: new Set(items.map(i => i.name)).size,
509
+ skipped,
510
+ };
511
+ // Rendered from the same inputs before: the sheet is as it would be.
512
+ if (renderedFrom(out, key)) return result;
513
+ const {html} = await renderGenerated(
514
+ project,
515
+ `sheet-${slug}.mjs`,
516
+ source,
517
+ templateFiles(imports),
518
+ );
304
519
  fs.mkdirSync(path.dirname(out), {recursive: true});
305
520
  // Written whole and renamed in, never through a link.
306
- writeWhole(out, html);
521
+ writeWhole(out, withRenderKey(html, key));
307
522
  return {
308
523
  file: shown(project.cwd, out),
309
524
  components: new Set(items.map(i => i.name)).size,
@@ -460,11 +675,11 @@ function componentTable(project, trees) {
460
675
  const SAFE = [
461
676
  '/** Shows a short note for a component that throws, so the rest of the page renders. */',
462
677
  'class Safe extends React.Component<{name: string, children: React.ReactNode}, {failed: boolean}> {',
463
- ' state = {failed: false};',
678
+ ' override state = {failed: false};',
464
679
  ' static getDerivedStateFromError() {',
465
680
  ' return {failed: true};',
466
681
  ' }',
467
- ' render() {',
682
+ ' override render() {',
468
683
  ' return this.state.failed ? <div className="tp-note">{this.props.name} could not render here</div> : this.props.children;',
469
684
  ' }',
470
685
  '}',
@@ -567,10 +782,12 @@ const usesSource = v =>
567
782
  Object.values(/** @type {object} */ (v)).some(usesSource);
568
783
 
569
784
  /** The heading of each group on the components page. */
570
- const GROUP_TITLES = /** @type {Record<string, string>} */ ({
571
- data: 'data display',
572
- overlays: 'overlays (shown open)',
573
- });
785
+ const GROUP_TITLES = wordTable(
786
+ /** @type {Record<string, string>} */ ({
787
+ data: 'data display',
788
+ overlays: 'overlays (shown open)',
789
+ }),
790
+ );
574
791
 
575
792
  /**
576
793
  * A cell with the component's name. A cell whose parts show nothing on
@@ -727,10 +944,14 @@ export function componentsPageSource(project, {theme = null, C} = {}) {
727
944
  * boundary, so one part that throws never blanks the page. The preview
728
945
  * route is the app shell, so the page has no shell of its own.
729
946
  * @param {import('./_project.mjs').ThemeProject} project
730
- * @param {{theme?: string | null}} [options]
947
+ * @param {{theme?: string | null, colors?: boolean}} [options] `colors`:
948
+ * the preview has a Colors page, so the header points to it
731
949
  * @returns {string}
732
950
  */
733
- export function overviewPageSource(project, {theme = null} = {}) {
951
+ export function overviewPageSource(
952
+ project,
953
+ {theme = null, colors = false} = {},
954
+ ) {
734
955
  const sections = OVERVIEW_SECTIONS.map(x => ({
735
956
  title: x.title,
736
957
  tree: /** @type {import('./_catalog.mjs').Tree | undefined} */ (
@@ -786,8 +1007,38 @@ export function overviewPageSource(project, {theme = null} = {}) {
786
1007
  ' React.useEffect(() => {',
787
1008
  ' if (!ref.current) return;',
788
1009
  ' const style = getComputedStyle(ref.current);',
789
- " const first = (token: string) => style.getPropertyValue(token).split(',')[0].replace(/[\"']/g, '').trim() || 'default';",
790
- " setFonts(`Body: ${first('--font-family-body')}. Headings: ${first('--font-family-heading')}.`);",
1010
+ " const first = (token: string) => (style.getPropertyValue(token).split(',')[0] ?? '').replace(/[\"']/g, '').trim() || 'default';",
1011
+ ' // A family the browser does not have measures as its fallback does.',
1012
+ ' const GENERIC = /^(default|serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-[a-z-]+|math|emoji|fangsong)$/i;',
1013
+ ' const missing = (family: string) => {',
1014
+ ' if (GENERIC.test(family)) return false;',
1015
+ " const ctx = document.createElement('canvas').getContext('2d');",
1016
+ ' if (!ctx) return false;',
1017
+ " const sample = 'mmmmmmmmmwwwwwww1234567890';",
1018
+ " return ['monospace', 'serif'].every(fallback => {",
1019
+ ' ctx.font = `48px ${fallback}`;',
1020
+ ' const plain = ctx.measureText(sample).width;',
1021
+ ' ctx.font = `48px "${family}", ${fallback}`;',
1022
+ ' return ctx.measureText(sample).width === plain;',
1023
+ ' });',
1024
+ ' };',
1025
+ ' const shown = (token: string) => { const f = first(token); return missing(f) ? `${f} (not installed here)` : f; };',
1026
+ " const write = () => setFonts(`Body: ${shown('--font-family-body')}. Headings: ${shown('--font-family-heading')}.`);",
1027
+ ' write();',
1028
+ ' // Read again when the theme changes live (a stylesheet or theme',
1029
+ ' // update while the page is open) and when a font finishes loading.',
1030
+ ' document.fonts?.ready.then(write);',
1031
+ " document.fonts?.addEventListener?.('loadingdone', write);",
1032
+ ' let queued = 0;',
1033
+ ' const soon = () => { if (!queued) queued = requestAnimationFrame(() => { queued = 0; write(); }); };',
1034
+ ' const watch = new MutationObserver(soon);',
1035
+ ' watch.observe(document.head, {childList: true, subtree: true, characterData: true});',
1036
+ " watch.observe(document.documentElement, {attributes: true, subtree: true, attributeFilter: ['style', 'class', 'data-theme']});",
1037
+ ' return () => {',
1038
+ ' watch.disconnect();',
1039
+ ' cancelAnimationFrame(queued);',
1040
+ " document.fonts?.removeEventListener?.('loadingdone', write);",
1041
+ ' };',
791
1042
  ' }, []);',
792
1043
  ' return (',
793
1044
  " <div ref={ref} style={{color: 'var(--color-text-secondary)', fontSize: 13}}>",
@@ -812,7 +1063,12 @@ export function overviewPageSource(project, {theme = null} = {}) {
812
1063
  ' {s.name}',
813
1064
  ' </div>',
814
1065
  ' ))}',
815
- ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1066
+ // The Colors page is there only for a theme with generated colors.
1067
+ ...(colors
1068
+ ? [
1069
+ ' <div className="tp-swatch" style={{alignSelf: \'center\'}}>Every shade: the Colors page</div>',
1070
+ ]
1071
+ : []),
816
1072
  ' </div>',
817
1073
  ' </header>',
818
1074
  body,
@@ -839,7 +1095,6 @@ export function colorsPageSource({slug, module, seeds, uses}) {
839
1095
  '// `astryx experimental theme editor set` rewrites it with every change.',
840
1096
  "'use client';",
841
1097
  '',
842
- "import * as React from 'react';",
843
1098
  ];
844
1099
  const text = {color: 'var(--color-text-primary)'};
845
1100
  const page = {
@@ -891,7 +1146,7 @@ export function colorsPageSource({slug, module, seeds, uses}) {
891
1146
  " <h2 style={{margin: 0, fontSize: 20, textTransform: 'capitalize'}}>",
892
1147
  ' {name}',
893
1148
  ' {SEEDS[name] ? (',
894
- " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, color: 'var(--color-text-secondary)'}}>",
1149
+ " <span style={{marginLeft: 8, fontSize: 14, fontWeight: 400, textTransform: 'none', color: 'var(--color-text-secondary)'}}>",
895
1150
  ' from {SEEDS[name]}',
896
1151
  ' </span>',
897
1152
  ' ) : null}',
@@ -984,7 +1239,7 @@ export function previewRouteSource({
984
1239
  ' ))}',
985
1240
  ' </SideNav>',
986
1241
  ' }>',
987
- ' <current.Page />',
1242
+ ' {ready ? <current.Page /> : null}',
988
1243
  ' </AppShell>',
989
1244
  ' </div>',
990
1245
  ];
@@ -1028,6 +1283,10 @@ export function previewRouteSource({
1028
1283
  '',
1029
1284
  'export default function ThemePreviewPage() {',
1030
1285
  ' const [page, setPage] = React.useState(PAGES[0]?.id);',
1286
+ // Pages render only in the browser: some components crash a server
1287
+ // render, and Next prerenders a client page's first state.
1288
+ ' const [ready, setReady] = React.useState(false);',
1289
+ ' React.useEffect(() => setReady(true), []);',
1031
1290
  ...(theme
1032
1291
  ? [
1033
1292
  oneMode
@@ -1035,7 +1294,8 @@ export function previewRouteSource({
1035
1294
  : " const [mode, setMode] = React.useState<Mode>('system');",
1036
1295
  ]
1037
1296
  : []),
1038
- ' const current = PAGES.find(p => p.id === page) ?? PAGES[0];',
1297
+ // The route always has a page; the cast keeps noUncheckedIndexedAccess apps building.
1298
+ ' const current = (PAGES.find(p => p.id === page) ?? PAGES[0]) as (typeof PAGES)[number];',
1039
1299
  ' return (',
1040
1300
  ...(theme
1041
1301
  ? [' <Theme theme={theme} mode={mode}>', ...shell, ' </Theme>']
@@ -32,6 +32,16 @@ export function openProject(cwd: string): Promise<ThemeProject>;
32
32
  * @returns {string | null}
33
33
  */
34
34
  export function importPathOf(project: ThemeProject, name: string): string | null;
35
+ /**
36
+ * The built module of a base's theme package, resolved the way the theme
37
+ * resolves it: from the project (an open project, or its folder, relative
38
+ * or not). Null when it is not installed there. The one base resolution:
39
+ * `new`, `set base`, `how` and every suggestion ask this.
40
+ * @param {ThemeProject | string} from
41
+ * @param {string} like
42
+ * @returns {string | null}
43
+ */
44
+ export function baseModule(from: ThemeProject | string, like: string): string | null;
35
45
  /**
36
46
  * The built-in theme package for a base, or a refusal naming its install line.
37
47
  * @param {ThemeProject} project
@@ -51,6 +61,7 @@ export function baseResolved(project: ThemeProject, like: string | undefined): P
51
61
  components: Record<string, any>;
52
62
  }>;
53
63
  export function literals(type: string): string[];
64
+ export function baseInstalled(from: ThemeProject | string, like: string): boolean;
54
65
  export type ThemeProject = {
55
66
  cwd: string;
56
67
  /**
@@ -321,6 +321,34 @@ export function importPathOf(project, name) {
321
321
  return spec && spec !== '@astryxdesign/core' ? spec : null;
322
322
  }
323
323
 
324
+ /**
325
+ * The built module of a base's theme package, resolved the way the theme
326
+ * resolves it: from the project (an open project, or its folder, relative
327
+ * or not). Null when it is not installed there. The one base resolution:
328
+ * `new`, `set base`, `how` and every suggestion ask this.
329
+ * @param {ThemeProject | string} from
330
+ * @param {string} like
331
+ * @returns {string | null}
332
+ */
333
+ export function baseModule(from, like) {
334
+ const req =
335
+ typeof from === 'string'
336
+ ? createRequire(path.join(path.resolve(from), 'noop.js'))
337
+ : from.req;
338
+ try {
339
+ return req.resolve(`@astryxdesign/theme-${like}/built`);
340
+ } catch {
341
+ return null;
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Whether a base's theme package is installed in the project.
347
+ * @param {ThemeProject | string} from
348
+ * @param {string} like
349
+ */
350
+ export const baseInstalled = (from, like) => baseModule(from, like) != null;
351
+
324
352
  /**
325
353
  * The built-in theme package for a base, or a refusal naming its install line.
326
354
  * @param {ThemeProject} project
@@ -329,15 +357,13 @@ export function importPathOf(project, name) {
329
357
  */
330
358
  export function baseThemeFile(project, like) {
331
359
  const pkg = `@astryxdesign/theme-${like}`;
332
- try {
333
- return project.req.resolve(`${pkg}/built`);
334
- } catch {
335
- throw new AstryxError(
336
- `The ${like} theme is not installed, so a theme cannot build on it. Install ${pkg}, or build on no theme. Nothing was changed.`,
337
- [{name: installLine(project.cwd, [pkg]), reason: 'install it'}],
338
- ERROR_CODES.ERR_UNKNOWN_THEME,
339
- );
340
- }
360
+ const file = baseModule(project, like);
361
+ if (file) return file;
362
+ throw new AstryxError(
363
+ `The ${like} theme is not installed, so a theme cannot build on it. Install ${pkg}, or build on no theme. Nothing was changed.`,
364
+ [{name: installLine(project.cwd, [pkg]), reason: 'install it'}],
365
+ ERROR_CODES.ERR_UNKNOWN_THEME,
366
+ );
341
367
  }
342
368
 
343
369
  /**