@astryxdesign/cli 0.7.15 → 0.7.16-canary.g54dd64e

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 (123) 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/pack-check.mjs +13 -7
  8. package/api/integration/validate-integration.mjs +1 -1
  9. package/api/theme/_adapter.d.mts +5 -2
  10. package/api/theme/_adapter.mjs +43 -12
  11. package/api/theme/build/build.d.mts +64 -27
  12. package/api/theme/build/build.mjs +341 -69
  13. package/api/theme/eject/eject.mjs +22 -1
  14. package/api/theme/template/template.d.mts +19 -0
  15. package/api/theme/template/template.mjs +102 -25
  16. package/api/theme/theme.type.d.mts +5 -1
  17. package/api/theme/theme.type.mjs +2 -1
  18. package/api/theme/themeBuild.doc.mjs +3 -3
  19. package/api/theme/themeEject.doc.mjs +1 -1
  20. package/api/theme/themeTemplate.doc.mjs +9 -3
  21. package/api/theme-edit/_adapter.d.mts +33 -0
  22. package/api/theme-edit/_adapter.mjs +208 -31
  23. package/api/theme-edit/_check.d.mts +38 -0
  24. package/api/theme-edit/_check.mjs +1326 -211
  25. package/api/theme-edit/_color.d.mts +2 -8
  26. package/api/theme-edit/_color.mjs +292 -219
  27. package/api/theme-edit/_compiler.d.mts +1 -0
  28. package/api/theme-edit/_compiler.mjs +20 -1
  29. package/api/theme-edit/_context.d.mts +29 -0
  30. package/api/theme-edit/_context.mjs +329 -30
  31. package/api/theme-edit/_css.d.mts +60 -1
  32. package/api/theme-edit/_css.mjs +404 -28
  33. package/api/theme-edit/_edit.d.mts +9 -0
  34. package/api/theme-edit/_edit.mjs +1025 -126
  35. package/api/theme-edit/_how-commands.d.mts +11 -26
  36. package/api/theme-edit/_how-commands.mjs +30 -2
  37. package/api/theme-edit/_how-question.d.mts +7 -0
  38. package/api/theme-edit/_how-question.mjs +1304 -176
  39. package/api/theme-edit/_how.mjs +144 -30
  40. package/api/theme-edit/_overview.mjs +2 -0
  41. package/api/theme-edit/_palette.d.mts +11 -0
  42. package/api/theme-edit/_palette.mjs +194 -65
  43. package/api/theme-edit/_parts.d.mts +16 -0
  44. package/api/theme-edit/_parts.mjs +59 -7
  45. package/api/theme-edit/_png.mjs +19 -14
  46. package/api/theme-edit/_preview-app.d.mts +3 -0
  47. package/api/theme-edit/_preview-app.mjs +843 -45
  48. package/api/theme-edit/_preview.d.mts +16 -3
  49. package/api/theme-edit/_preview.mjs +310 -29
  50. package/api/theme-edit/_project.d.mts +11 -0
  51. package/api/theme-edit/_project.mjs +46 -12
  52. package/api/theme-edit/_settings.d.mts +178 -5
  53. package/api/theme-edit/_settings.mjs +2035 -86
  54. package/api/theme-edit/_tables.d.mts +24 -0
  55. package/api/theme-edit/_tables.mjs +211 -149
  56. package/api/theme-edit/_vet.d.mts +42 -0
  57. package/api/theme-edit/_vet.mjs +144 -0
  58. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  59. package/api/theme-edit/theme-edit.type.mjs +1 -1
  60. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  61. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  62. package/api/upgrade/registry/registry.mjs +6 -1
  63. package/assets/docs/tree/single-component.doc.mjs +11 -2
  64. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  65. package/assets/docs.generated.json +2 -2
  66. package/assets/preview-app/next.config.mjs +7 -1
  67. package/assets/preview-app/package.json +1 -0
  68. package/assets/preview-app/src/app/globals.css +1 -0
  69. package/assets/self-audit.generated.json +1 -1
  70. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  71. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  72. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  73. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  74. package/assets/templates/components.generated.json +1 -1
  75. package/assets/templates/pages/dashboard/page.tsx +1 -1
  76. package/authoring/doctypes/_schema.d.mts +52 -5
  77. package/authoring/doctypes/_schema.mjs +62 -7
  78. package/authoring/doctypes/base/type.ts +10 -0
  79. package/authoring/doctypes/component/component.doc.mjs +1 -1
  80. package/authoring/doctypes/function/function.doc.mjs +6 -0
  81. package/authoring/doctypes/function/type.ts +3 -0
  82. package/authoring/doctypes/legacy.mjs +5 -1
  83. package/authoring/index.d.ts +1 -0
  84. package/clients/cli/build-id.generated.json +1 -1
  85. package/clients/cli/commands/doctor.doc.mjs +2 -2
  86. package/clients/cli/commands/experimental/theme.mjs +190 -37
  87. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  88. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  89. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  90. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  91. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  92. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  93. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  94. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  95. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  96. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  97. package/clients/cli/commands/theme.mjs +168 -45
  98. package/clients/cli/formatters/index.mjs +7 -4
  99. package/clients/cli/lib/cli-error.mjs +9 -3
  100. package/clients/cli/lib/component-format.mjs +27 -9
  101. package/clients/cli/lib/json-shim.mjs +40 -2
  102. package/clients/cli/manifest.generated.json +1 -1
  103. package/clients/cli/run.mjs +49 -0
  104. package/foundation/config/project.mjs +50 -14
  105. package/foundation/discovery/theme-discovery.d.mts +5 -1
  106. package/foundation/discovery/theme-discovery.mjs +24 -3
  107. package/foundation/fs/gather-cache.d.mts +9 -2
  108. package/foundation/fs/gather-cache.mjs +79 -15
  109. package/foundation/fs/paths.d.mts +31 -0
  110. package/foundation/fs/paths.mjs +43 -10
  111. package/foundation/render/host-exit.d.mts +8 -0
  112. package/foundation/render/host-exit.mjs +11 -0
  113. package/foundation/render/page-host.mjs +56 -10
  114. package/foundation/render/page-worker.mjs +14 -0
  115. package/foundation/render/render-page.mjs +37 -2
  116. package/foundation/response/error-codes.d.mts +2 -1
  117. package/foundation/response/error-codes.d.ts +1 -0
  118. package/foundation/response/error-codes.doc.mjs +5 -0
  119. package/foundation/response/error-codes.mjs +3 -0
  120. package/foundation/response/json.d.mts +15 -0
  121. package/foundation/response/json.mjs +52 -1
  122. package/foundation/response/response-types.doc.mjs +1 -1
  123. package/package.json +7 -6
@@ -13,6 +13,7 @@
13
13
  import {parse as parseModule} from '@babel/parser';
14
14
  import * as fs from 'node:fs';
15
15
  import * as path from 'node:path';
16
+ import {createRequire} from 'node:module';
16
17
  import {fileURLToPath} from 'node:url';
17
18
  import {cliVersion} from '../../foundation/release/run-context.mjs';
18
19
  import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
@@ -21,7 +22,7 @@ import {
21
22
  PathSafetyError,
22
23
  } from '../../foundation/fs/path-safety.mjs';
23
24
  import {baseResolved, installLine, openProject} from './_project.mjs';
24
- import {P} from './_tables.mjs';
25
+ import {P, wordTable} from './_tables.mjs';
25
26
  import {
26
27
  buildTheme,
27
28
  editedThemes,
@@ -33,9 +34,11 @@ import {
33
34
  shown,
34
35
  staleBuild,
35
36
  themeFiles,
37
+ usableNewName,
36
38
  windowsReserved,
37
39
  } from './_settings.mjs';
38
40
  import {
41
+ baseFontsCss,
39
42
  colorsPageSource,
40
43
  componentsPageSource,
41
44
  overviewPageSource,
@@ -43,6 +46,7 @@ import {
43
46
  themeImports,
44
47
  } from './_preview.mjs';
45
48
  import {
49
+ isEditorTemp,
46
50
  PALETTE_STAND_IN,
47
51
  paletteFiles,
48
52
  paletteMapping,
@@ -84,7 +88,9 @@ const MAX_WORDS = 40;
84
88
 
85
89
  /**
86
90
  * @typedef {{id: string, label: string, file: string}} PreviewPage
87
- * @typedef {{version: 1, theme: string | null, pages: PreviewPage[], files: string[], hashes?: Record<string, string>}} PreviewData
91
+ * @typedef {{version: 1, theme: string | null, pages: PreviewPage[], files: string[], hashes?: Record<string, string>, parents?: number}} PreviewData
92
+ * `parents`: how many folders over the preview folder its first add made,
93
+ * which remove takes away again when they are empty.
88
94
  * `hashes`: a short hash of each file as the preview wrote it, so a file
89
95
  * changed by hand is never replaced or deleted
90
96
  * @typedef {(path: string | null) => string} Retry the command again, with
@@ -134,6 +140,97 @@ function checkFolderName(where, what, retry) {
134
140
  );
135
141
  }
136
142
 
143
+ /**
144
+ * Whether a stylesheet comes in through the files the root layout imports,
145
+ * followed through relative and `@/` imports (a root `styles/globals.css`,
146
+ * as create-next-app writes it), a few levels deep.
147
+ * @param {string} cwd
148
+ * @param {string} app the routes folder
149
+ * @param {RegExp} sheet
150
+ */
151
+ function layoutImportsSheet(cwd, app, sheet, dir = app) {
152
+ // Every layout over the preview: the routes folder's, and one in a route
153
+ // group or [param] folder on the way.
154
+ /** @type {string[]} */
155
+ const starts = [];
156
+ for (let at = dir; ; at = path.dirname(at)) {
157
+ for (const x of ['tsx', 'ts', 'jsx', 'js'])
158
+ if (fs.existsSync(path.join(at, `layout.${x}`)))
159
+ starts.push(path.join(at, `layout.${x}`));
160
+ if (at === app || !at.startsWith(app + path.sep)) break;
161
+ }
162
+ if (!starts.length) return false;
163
+ const aliases = tsconfigAliases(cwd);
164
+ const seen = new Set();
165
+ /** @param {string} file @param {number} depth @returns {boolean} */
166
+ const reads = (file, depth) => {
167
+ if (seen.has(file) || depth > 4) return false;
168
+ seen.add(file);
169
+ /** @type {string} */
170
+ let text;
171
+ try {
172
+ text = fs.readFileSync(file, 'utf8');
173
+ } catch {
174
+ return false;
175
+ }
176
+ if (sheet.test(text)) return true;
177
+ for (const m of text.matchAll(
178
+ /(?:import|@import)\s*(?:[^'"]*from\s*)?(?:url\()?['"]([^'"]+)['"]/g,
179
+ )) {
180
+ const spec = m[1];
181
+ // An alias the tsconfig sets; else `@/` is the src folder or the
182
+ // project root.
183
+ const alias = aliases.find(a => spec.startsWith(a.prefix));
184
+ const bases = alias
185
+ ? alias.to.map(t => path.join(t, spec.slice(alias.prefix.length)))
186
+ : spec.startsWith('@/')
187
+ ? [
188
+ path.join(cwd, 'src', spec.slice(2)),
189
+ path.join(cwd, spec.slice(2)),
190
+ ]
191
+ : spec.startsWith('.')
192
+ ? [path.resolve(path.dirname(file), spec)]
193
+ : [];
194
+ const hit = bases
195
+ .flatMap(b =>
196
+ ['', '.css', '.scss', '.ts', '.tsx', '.js', '.jsx'].map(x => b + x),
197
+ )
198
+ .find(f => fs.existsSync(f) && fs.statSync(f).isFile());
199
+ if (hit && reads(hit, depth + 1)) return true;
200
+ }
201
+ return false;
202
+ };
203
+ return starts.some(start => reads(start, 0));
204
+ }
205
+
206
+ /**
207
+ * The import aliases the app's tsconfig `paths` set (`~/*`, `#app/*`), each
208
+ * with the folders it stands for.
209
+ * @param {string} cwd
210
+ * @returns {Array<{prefix: string, to: string[]}>}
211
+ */
212
+ function tsconfigAliases(cwd) {
213
+ const o = appCompilerOptions(cwd);
214
+ const paths = o && typeof o.paths === 'object' && o.paths ? o.paths : {};
215
+ const baseUrl = path.resolve(
216
+ cwd,
217
+ typeof o?.baseUrl === 'string' ? o.baseUrl : '.',
218
+ );
219
+ return Object.entries(/** @type {Record<string, unknown>} */ (paths)).flatMap(
220
+ ([key, targets]) =>
221
+ key.endsWith('/*') && Array.isArray(targets)
222
+ ? [
223
+ {
224
+ prefix: key.slice(0, -1),
225
+ to: targets
226
+ .filter(t => typeof t === 'string' && t.endsWith('/*'))
227
+ .map(t => path.resolve(baseUrl, String(t).slice(0, -2))),
228
+ },
229
+ ]
230
+ : [],
231
+ );
232
+ }
233
+
137
234
  /**
138
235
  * A note when the app never imports Core's stylesheet, or null: without
139
236
  * it, components render unstyled, and some show nothing. Read from the
@@ -180,7 +277,8 @@ function coreStylesheetMissing(cwd, at) {
180
277
  const src = path.join(cwd, 'src');
181
278
  if (
182
279
  imports(at.app) ||
183
- (at.app.startsWith(src + path.sep) ? false : imports(src))
280
+ (at.app.startsWith(src + path.sep) ? false : imports(src)) ||
281
+ layoutImportsSheet(cwd, at.app, SHEET, at.dir)
184
282
  )
185
283
  return null;
186
284
  const layout = ['tsx', 'ts', 'jsx', 'js']
@@ -204,11 +302,12 @@ function readNextConfig(cwd) {
204
302
  basePath: undefined,
205
303
  distDir: undefined,
206
304
  };
305
+ // The order Next loads them in; it refuses next.config.cjs.
207
306
  for (const name of [
208
- 'next.config.mjs',
209
307
  'next.config.js',
308
+ 'next.config.mjs',
210
309
  'next.config.ts',
211
- 'next.config.cjs',
310
+ 'next.config.mts',
212
311
  ]) {
213
312
  /** @type {string} */
214
313
  let text;
@@ -270,6 +369,11 @@ function readNextConfig(cwd) {
270
369
  let exported = null;
271
370
  for (const st of body) {
272
371
  if (st.type === 'ExportDefaultDeclaration') exported = st.declaration;
372
+ // export {config as default}
373
+ if (st.type === 'ExportNamedDeclaration' && !st.source)
374
+ for (const sp of st.specifiers ?? [])
375
+ if ((sp.exported?.name ?? sp.exported?.value) === 'default')
376
+ exported = sp.local;
273
377
  if (
274
378
  st.type === 'ExpressionStatement' &&
275
379
  st.expression.type === 'AssignmentExpression' &&
@@ -281,6 +385,66 @@ function readNextConfig(cwd) {
281
385
  }
282
386
  const config = exported && configOf(exported);
283
387
  if (!config) return exported ? unknown : none;
388
+ const wrapped = resolve(exported)?.type === 'CallExpression';
389
+ // Changes to the config after it is made: `config.key = value` sets a
390
+ // key (the last one counts), and anything else (Object.assign, a
391
+ // computed key) makes every key unknown.
392
+ const names = new Set(
393
+ [...consts]
394
+ .filter(([, init]) => resolve(init) === config)
395
+ .map(([n]) => n),
396
+ );
397
+ /** @type {Map<string, any>} */
398
+ const later = new Map();
399
+ let changed = false;
400
+ // Only a statement at the top of the file surely runs: a key set inside
401
+ // an `if` or a function, or deleted, is known only by running it.
402
+ const UNSURE = Symbol('unsure');
403
+ const topLevel = new Set(
404
+ body
405
+ .filter(st => st.type === 'ExpressionStatement')
406
+ .map(st => st.expression),
407
+ );
408
+ /** @param {any} n */
409
+ const visit = n => {
410
+ if (!n || typeof n !== 'object') return;
411
+ if (Array.isArray(n)) return n.forEach(visit);
412
+ if (
413
+ n.type === 'AssignmentExpression' &&
414
+ n.left?.type === 'MemberExpression' &&
415
+ names.has(n.left.object?.name)
416
+ ) {
417
+ if (n.left.computed) changed = true;
418
+ else
419
+ later.set(
420
+ n.left.property.name,
421
+ topLevel.has(n) && n.operator === '=' ? n.right : UNSURE,
422
+ );
423
+ }
424
+ if (
425
+ n.type === 'UnaryExpression' &&
426
+ n.operator === 'delete' &&
427
+ n.argument?.type === 'MemberExpression' &&
428
+ names.has(n.argument.object?.name)
429
+ ) {
430
+ if (n.argument.computed) changed = true;
431
+ else later.set(n.argument.property.name, UNSURE);
432
+ }
433
+ if (
434
+ n.type === 'CallExpression' &&
435
+ n.arguments?.some(
436
+ (/** @type {any} */ a) =>
437
+ a.type === 'Identifier' && names.has(a.name),
438
+ ) &&
439
+ n.callee?.type === 'MemberExpression' &&
440
+ n.callee.object?.name === 'Object'
441
+ )
442
+ changed = true;
443
+ for (const [k, v] of Object.entries(n))
444
+ if (k !== 'loc' && k !== 'start' && k !== 'end') visit(v);
445
+ };
446
+ visit(body);
447
+ if (changed) return unknown;
284
448
  // The config's keys in order, with a spread of a constant object read
285
449
  // in place; a spread of anything else may set any key (`null`).
286
450
  /** @type {Array<{key: string, value: any} | null>} */
@@ -302,8 +466,10 @@ function readNextConfig(cwd) {
302
466
  }
303
467
  };
304
468
  flatten(config, 0);
305
- /** The entry that sets a key last; null when an unreadable spread may; undefined when nothing does. @param {string} key */
469
+ /** The entry that sets a key last: a later assignment, else the last key; null when an unreadable spread may; undefined when nothing does. @param {string} key */
306
470
  const prop = key => {
471
+ if (later.has(key))
472
+ return later.get(key) === UNSURE ? null : {key, value: later.get(key)};
307
473
  for (let i = entries.length - 1; i >= 0; i--) {
308
474
  const e = entries[i];
309
475
  if (e === null) return null;
@@ -332,10 +498,13 @@ function readNextConfig(cwd) {
332
498
  const out = n.elements.map((/** @type {any} */ e) => str(e));
333
499
  return out.every((/** @type {any} */ e) => e != null) ? out : null;
334
500
  }),
335
- basePath: value('basePath', n => {
336
- const v = str(n);
337
- return v == null ? null : v.replace(/\/+$/, '');
338
- }),
501
+ // A wrapper such as withX(config) may add a basePath of its own.
502
+ basePath: wrapped
503
+ ? null
504
+ : value('basePath', n => {
505
+ const v = str(n);
506
+ return v == null ? null : v.replace(/\/+$/, '');
507
+ }),
339
508
  distDir: value('distDir', n => {
340
509
  const v = str(n);
341
510
  return v == null
@@ -407,6 +576,134 @@ function reservedFolder(cwd, dir) {
407
576
  return null;
408
577
  }
409
578
 
579
+ /**
580
+ * The app's tsconfig.json compiler options (comments and trailing commas
581
+ * allowed), or null when there is none.
582
+ * @param {string} cwd
583
+ * @returns {Record<string, unknown> | null}
584
+ */
585
+ function appCompilerOptions(cwd) {
586
+ /** @type {string} */
587
+ let text;
588
+ try {
589
+ text = fs.readFileSync(path.join(cwd, 'tsconfig.json'), 'utf8');
590
+ } catch {
591
+ return null;
592
+ }
593
+ try {
594
+ const json = text
595
+ .replace(
596
+ /("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\/|\/\/.*$/gm,
597
+ (m, str) => str ?? '',
598
+ )
599
+ .replace(/,(\s*[}\]])/g, '$1');
600
+ const o = JSON.parse(json)?.compilerOptions;
601
+ return o && typeof o === 'object' ? o : {};
602
+ } catch {
603
+ return {};
604
+ }
605
+ }
606
+
607
+ /**
608
+ * Notes on what the preview's TypeScript files need from the app: an app
609
+ * with no TypeScript gets the install line (Next sets it up on the next
610
+ * build otherwise), and an app whose tsconfig turns on
611
+ * `noUncheckedIndexedAccess` is told which template pages were written as
612
+ * their template ships them, which may not pass it.
613
+ * @param {string} cwd
614
+ * @param {string} dir
615
+ * @param {string[]} added page ids added by this command
616
+ * @returns {string[]}
617
+ */
618
+ function typeScriptNotes(cwd, dir, added) {
619
+ const options = appCompilerOptions(cwd);
620
+ if (!options) {
621
+ const hasTs = (() => {
622
+ try {
623
+ return Boolean(
624
+ createRequire(path.join(cwd, 'package.json')).resolve('typescript'),
625
+ );
626
+ } catch {
627
+ return false;
628
+ }
629
+ })();
630
+ return hasTs
631
+ ? []
632
+ : [
633
+ `the app has no TypeScript, and the preview's files are .tsx, so the next build sets it up; to do it now: ${installLine(cwd, ['typescript', '@types/react', '@types/node']).replace(/ (add|install) /, ' $1 -D ')}`,
634
+ ];
635
+ }
636
+ const templates = added.filter(
637
+ id => !['overview', 'components', COLORS_PAGE.id].includes(id),
638
+ );
639
+ if (options.noUncheckedIndexedAccess !== true || !templates.length) return [];
640
+ const files = templates.map(id =>
641
+ shown(cwd, path.join(dir, PAGES_DIR, `${id}.tsx`)),
642
+ );
643
+ return [
644
+ `the app's tsconfig.json turns on noUncheckedIndexedAccess, and ${files.join(', ')} ${files.length > 1 ? 'are' : 'is'} written as the page template ships, which may not pass it; if the build stops there, fix the reported lines or remove the page with ${PREVIEW} remove ${templates[0]}`,
645
+ ];
646
+ }
647
+
648
+ /**
649
+ * Why a file cannot be read (its error code), or null when it can.
650
+ * @param {string} file
651
+ * @returns {string | null}
652
+ */
653
+ function unreadable(file) {
654
+ try {
655
+ fs.closeSync(fs.openSync(file, 'r'));
656
+ return null;
657
+ } catch (e) {
658
+ const code = /** @type {any} */ (e)?.code;
659
+ return code === 'ENOENT' ? null : (code ?? 'error');
660
+ }
661
+ }
662
+
663
+ /**
664
+ * Whether a folder beside `dir` has its name in another case.
665
+ * @param {string} dir
666
+ */
667
+ function twinBeside(dir) {
668
+ const name = path.basename(dir);
669
+ try {
670
+ return fs
671
+ .readdirSync(path.dirname(dir))
672
+ .some(n => n !== name && n.toLowerCase() === name.toLowerCase());
673
+ } catch {
674
+ return false;
675
+ }
676
+ }
677
+
678
+ /**
679
+ * A folder beside `dir`, or beside one of its parents, whose name differs
680
+ * only in case, or null.
681
+ * @param {string} dir
682
+ * @returns {string | null}
683
+ */
684
+ function sameCaseSibling(dir) {
685
+ for (let at = dir; path.dirname(at) !== at; at = path.dirname(at)) {
686
+ const parent = path.dirname(at);
687
+ const name = path.basename(at);
688
+ /** @type {string[]} */
689
+ let names;
690
+ try {
691
+ names = fs.readdirSync(parent);
692
+ } catch {
693
+ continue;
694
+ }
695
+ const twin = names.find(
696
+ n => n !== name && n.toLowerCase() === name.toLowerCase(),
697
+ );
698
+ if (twin) return path.join(parent, twin);
699
+ if (fs.existsSync(path.join(parent, 'package.json'))) break;
700
+ }
701
+ return null;
702
+ }
703
+
704
+ /** An intercepting route folder: `(.)x`, `(..)x`, `(..)(..)x`, `(...)x`. */
705
+ const INTERCEPT = /^\((\.{1,3})\)/;
706
+
410
707
  /**
411
708
  * Why Next does not serve a folder inside the routes folder at its own
412
709
  * URL, or null: a `_private` folder is never routed, an `@slot` folder is a
@@ -418,7 +715,9 @@ function unroutedSegment(app, dir) {
418
715
  const seg = path
419
716
  .relative(app, dir)
420
717
  .split(path.sep)
421
- .find(x => /^[_@[]/.test(x));
718
+ .find(x => /^[_@[]/.test(x) || INTERCEPT.test(x));
719
+ if (seg && INTERCEPT.test(seg))
720
+ return `Next reads the folder ${seg} as an intercepting route ((.), (..) and (...) folders show another route's page), not a URL of its own, and a page there breaks the app`;
422
721
  return seg
423
722
  ? `Next does not serve the folder ${seg} at a URL of its own (_private folders are never routed, @slot and [param] folders are not plain URL segments)`
424
723
  : null;
@@ -615,6 +914,75 @@ function checkPlacement(cwd, dir, where, retry) {
615
914
  `${where} is no place for the preview: ${why}.`,
616
915
  {run: [fallback]},
617
916
  );
917
+ // A folder name that is not a plain URL segment (a space, an accent,
918
+ // ?, #, %) is not served at the URL it seems to have. The characters a
919
+ // URL path takes as they are (RFC 3986 unreserved and sub-delims, @, ~)
920
+ // are served.
921
+ const PLAIN = /^[A-Za-z0-9._~!$&'()+,;=@-]+$/;
922
+ const segs = app ? path.relative(app, dir).split(path.sep) : [];
923
+ const odd = segs.filter(
924
+ seg => seg && !/^\(.+\)$|^\[.+\]$/.test(seg) && !PLAIN.test(seg),
925
+ );
926
+ if (app && odd.length) {
927
+ const slug = (/** @type {string} */ seg) =>
928
+ seg
929
+ .normalize('NFD')
930
+ .replace(/[\u0300-\u036f]/g, '')
931
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
932
+ .replace(/^-+|-+$/g, '')
933
+ .toLowerCase() || 'theme-preview';
934
+ // Every odd segment slugged, then the first free folder from it.
935
+ const base = path.join(
936
+ app,
937
+ ...segs.map(seg => (odd.includes(seg) ? slug(seg) : seg)),
938
+ );
939
+ let fixed = base;
940
+ for (
941
+ let n = 2;
942
+ fs.existsSync(fixed) || twinBeside(fixed) || sameUrlPage(cwd, app, fixed);
943
+ n++
944
+ )
945
+ fixed = `${base}-${n}`;
946
+ refuse(
947
+ E.ERR_INVALID_ARGUMENT,
948
+ `${where} is no place for the preview: Next does not serve the folder "${odd[0]}" at the URL its name seems to give (a space, a letter outside A-Z, %, # or ? are no plain URL segment).`,
949
+ {run: [retry(shown(cwd, fixed))]},
950
+ );
951
+ }
952
+ // A folder whose name differs from a folder beside it only in case is the
953
+ // same folder on macOS and Windows: one of them is lost in a checkout.
954
+ const twin = sameCaseSibling(dir);
955
+ if (twin) {
956
+ // A twin of a folder on the way: the same path through the folder that
957
+ // is there. A twin of the folder itself: the first free name beside it.
958
+ const base = path.dirname(twin);
959
+ const rel = path.relative(base, dir).split(path.sep);
960
+ // Both spellings are folders already: no path through either is free,
961
+ // so the way on is a new folder beside them.
962
+ const bothThere = rel.length > 1 && fs.existsSync(path.join(base, rel[0]));
963
+ let free = path.join(twin, ...rel.slice(1));
964
+ if (rel.length === 1 || bothThere) {
965
+ const start = rel.length === 1 ? dir : path.join(base, 'theme-preview');
966
+ free = start;
967
+ for (let n = 2; fs.existsSync(free) || twinBeside(free); n++)
968
+ free = `${start}-${n}`;
969
+ }
970
+ const existing = fs.existsSync(path.join(dir, PREVIEW_DATA));
971
+ refuse(
972
+ E.ERR_INVALID_ARGUMENT,
973
+ `${where} is no place for the preview: ${shownDir(cwd, twin)}/ differs from it only in case, and on macOS and Windows they are one folder, so the project could not be checked out there.${existing ? ` The preview already there can still be removed.` : ''}`,
974
+ {
975
+ run: [
976
+ retry(shown(cwd, free)),
977
+ ...(existing
978
+ ? [
979
+ `${PREVIEW} remove --path ${quoteCommandArgument(shownDir(cwd, dir))}`,
980
+ ]
981
+ : []),
982
+ ],
983
+ },
984
+ );
985
+ }
618
986
  if (!app) return;
619
987
  if (served && app !== served)
620
988
  refuse(
@@ -646,18 +1014,19 @@ function checkPlacement(cwd, dir, where, retry) {
646
1014
  );
647
1015
  }
648
1016
  if (
649
- served &&
650
- !rootLayouts.length &&
651
- !fs.readdirSync(served).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f))
1017
+ (app && !served) ||
1018
+ (served &&
1019
+ !rootLayouts.length &&
1020
+ !fs.readdirSync(served).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f)))
652
1021
  ) {
653
1022
  let free = 'theme-app';
654
1023
  for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
655
1024
  free = `theme-app-${n}`;
656
1025
  refuse(
657
1026
  E.ERR_INVALID_ARGUMENT,
658
- `${shown(cwd, served)}/ has no root layout (no layout.tsx in it or in a route group), so Next cannot build a page in ${where}.`,
1027
+ `${shown(cwd, served ?? app)}/ has no root layout (no layout.tsx in it or in a route group)${served ? '' : ' and is not there yet'}, so Next cannot build a page in ${where}.`,
659
1028
  {
660
- fix: `add a root layout to ${shown(cwd, served)}/ to use the preview in this app`,
1029
+ fix: `add a root layout to ${shown(cwd, served ?? app)}/ to use the preview in this app`,
661
1030
  run: [
662
1031
  `${PREVIEW} app ${free} # a new app with its own root layout and the preview`,
663
1032
  ],
@@ -676,8 +1045,12 @@ function checkPlacement(cwd, dir, where, retry) {
676
1045
  );
677
1046
  const clash = sameUrlPage(cwd, app, dir);
678
1047
  if (clash) {
679
- let free = `${dir}-2`;
680
- for (let n = 3; fs.existsSync(free); n++) free = `${dir}-${n}`;
1048
+ // The first free name from the base name, whose URL no other page
1049
+ // serves either.
1050
+ const base = dir.replace(/-\d+$/, '');
1051
+ let free = `${base}-2`;
1052
+ for (let n = 3; fs.existsSync(free) || sameUrlPage(cwd, app, free); n++)
1053
+ free = `${base}-${n}`;
681
1054
  refuse(
682
1055
  E.ERR_FILE_EXISTS,
683
1056
  `${shown(cwd, clash)} already serves /${urlSegments(app, dir).join('/')} or the URLs under it, so a preview in ${where} would stop the app from building, or take that URL from it.`,
@@ -727,6 +1100,52 @@ function previewDir(cwd, where, opts = {}) {
727
1100
  );
728
1101
  throw e;
729
1102
  }
1103
+ // A file on the way, or a path longer than the system takes, would
1104
+ // fail every command on it with a system error.
1105
+ const blocker = (() => {
1106
+ for (
1107
+ let at = path.dirname(dir);
1108
+ at.startsWith(cwd + path.sep);
1109
+ at = path.dirname(at)
1110
+ )
1111
+ try {
1112
+ if (!fs.statSync(at).isDirectory()) return at;
1113
+ } catch {
1114
+ // Not there yet: made with the folder.
1115
+ }
1116
+ return null;
1117
+ })();
1118
+ if (blocker)
1119
+ refuse(
1120
+ E.ERR_INVALID_ARGUMENT,
1121
+ `--path ${where} goes through ${shown(cwd, blocker)}, which is a file, so no folder can be made there.`,
1122
+ {
1123
+ run: [
1124
+ retry(
1125
+ shown(cwd, path.join(path.dirname(blocker), 'theme-preview')),
1126
+ ),
1127
+ ],
1128
+ },
1129
+ );
1130
+ // A folder name is at most 255 bytes on every common file system; the
1131
+ // whole path, with the preview's own files below it, is kept under
1132
+ // 3,500 bytes.
1133
+ const longName = path
1134
+ .relative(cwd, dir)
1135
+ .split(path.sep)
1136
+ .find(seg => Buffer.byteLength(seg) > 255);
1137
+ if (longName)
1138
+ refuse(
1139
+ E.ERR_INVALID_ARGUMENT,
1140
+ `--path ${where} has a folder name longer than 255 bytes, the most a file system takes for one name.`,
1141
+ {run: [retry(null)]},
1142
+ );
1143
+ if (Buffer.byteLength(dir) > 3500)
1144
+ refuse(
1145
+ E.ERR_INVALID_ARGUMENT,
1146
+ `--path ${where} is longer than 3,500 bytes, with the preview's files in it.`,
1147
+ {run: [retry(null)]},
1148
+ );
730
1149
  if (opts.write) checkPlacement(cwd, dir, `--path ${where}`, retry);
731
1150
  return {dir, app: appOf(dir)};
732
1151
  }
@@ -766,22 +1185,95 @@ function previewDir(cwd, where, opts = {}) {
766
1185
  served && !known ? (nestedRootLayouts(served)[0] ?? null) : null;
767
1186
  const dir = known ?? (served && path.join(nested ?? served, 'theme-preview'));
768
1187
  if (!dir && opts.optional) return /** @type {any} */ (null);
769
- if (!dir)
1188
+ if (!dir) {
1189
+ // A workspace root: the Next apps below it, each with a --path into
1190
+ // its routes folder.
1191
+ const apps = nextAppsUnder(cwd);
770
1192
  refuse(
771
1193
  E.ERR_NOT_FOUND,
772
- 'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
1194
+ apps.length
1195
+ ? `No app routes folder here (app/ or src/app/); the Next ${apps.length > 1 ? 'apps' : 'app'} below ${apps.length > 1 ? 'are' : 'is'} ${apps.map(a => `${shown(cwd, a.root)}/`).join(', ')}.`
1196
+ : 'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
773
1197
  {
774
1198
  run: [
775
- `${PREVIEW} add --path app/theme-preview # an app routes folder beside the app's own`,
1199
+ ...apps
1200
+ .slice(0, 3)
1201
+ .map(
1202
+ a =>
1203
+ `${PREVIEW} add --path ${quoteCommandArgument(shown(cwd, path.join(a.routes, 'theme-preview')))}`,
1204
+ ),
776
1205
  `${PREVIEW} app theme-app # a new starter app with the preview in it`,
777
1206
  ],
778
1207
  },
779
1208
  );
1209
+ }
780
1210
  inProjectOrRefuse(cwd, dir, retry);
781
1211
  if (opts.write) checkPlacement(cwd, dir, `${shownDir(cwd, dir)}/`, retry);
782
1212
  return {dir, app: appOf(dir)};
783
1213
  }
784
1214
 
1215
+ /**
1216
+ * The Next apps in folders below `cwd` (a few levels, node_modules left
1217
+ * out): each folder with a package.json that depends on `next` and a routes
1218
+ * folder with a root layout.
1219
+ * @param {string} cwd
1220
+ * @returns {Array<{root: string, routes: string}>}
1221
+ */
1222
+ function nextAppsUnder(cwd) {
1223
+ /** @type {Array<{root: string, routes: string}>} */
1224
+ const out = [];
1225
+ /** @param {string} dir @param {number} depth */
1226
+ const walk = (dir, depth) => {
1227
+ if (depth > 3 || out.length >= 10) return;
1228
+ /** @type {fs.Dirent[]} */
1229
+ let entries;
1230
+ try {
1231
+ entries = fs.readdirSync(dir, {withFileTypes: true});
1232
+ } catch {
1233
+ return;
1234
+ }
1235
+ for (const e of entries) {
1236
+ if (
1237
+ !e.isDirectory() ||
1238
+ e.name === 'node_modules' ||
1239
+ e.name.startsWith('.')
1240
+ )
1241
+ continue;
1242
+ const sub = path.join(dir, e.name);
1243
+ const routes = nextRoutesOf(sub);
1244
+ if (routes) out.push({root: sub, routes});
1245
+ else walk(sub, depth + 1);
1246
+ }
1247
+ };
1248
+ walk(cwd, 1);
1249
+ return out.sort((a, b) => a.root.localeCompare(b.root));
1250
+ }
1251
+
1252
+ /**
1253
+ * The routes folder of a Next app in `dir` (app/, else src/app/, with a
1254
+ * root layout), when its package.json depends on `next`; else null.
1255
+ * @param {string} dir
1256
+ * @returns {string | null}
1257
+ */
1258
+ function nextRoutesOf(dir) {
1259
+ try {
1260
+ const pkg = JSON.parse(
1261
+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),
1262
+ );
1263
+ if (!['dependencies', 'devDependencies'].some(k => pkg?.[k]?.next))
1264
+ return null;
1265
+ } catch {
1266
+ return null;
1267
+ }
1268
+ return (
1269
+ [path.join(dir, 'app'), path.join(dir, 'src', 'app')].find(
1270
+ r =>
1271
+ fs.existsSync(r) &&
1272
+ fs.readdirSync(r).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f)),
1273
+ ) ?? null
1274
+ );
1275
+ }
1276
+
785
1277
  /**
786
1278
  * Refuse a preview folder that reaches outside the project through a link,
787
1279
  * as `--path` refuses one: every file the preview writes would land there.
@@ -827,9 +1319,11 @@ const STARTER = path.join(CLI_PACKAGE, 'assets', 'preview-app');
827
1319
  * @param {string} file absolute
828
1320
  * @param {string} root absolute
829
1321
  * @param {string} what what the path is, for the refusal
1322
+ * @param {{cwd?: string, pf?: string}} [opts] `cwd`: paths in the refusal
1323
+ * are shown from it; `pf`: the caller's --path flag, for the suggestion
830
1324
  * @returns {string}
831
1325
  */
832
- function confined(file, root, what) {
1326
+ function confined(file, root, what, opts = {}) {
833
1327
  try {
834
1328
  return assertWithin(file, root, {allowAbsolute: true, label: what});
835
1329
  } catch (e) {
@@ -848,12 +1342,14 @@ function confined(file, root, what) {
848
1342
  } catch {
849
1343
  // Not there: look at its folder.
850
1344
  }
1345
+ const at = (/** @type {string} */ f) =>
1346
+ opts.cwd ? shown(opts.cwd, f) || '.' : f;
851
1347
  refuse(
852
1348
  E.ERR_PATH_TRAVERSAL,
853
1349
  link == null
854
- ? `${what} names ${file}, which is outside ${root}.`
855
- : `${link.at} is a link to ${link.to}, outside ${root}; the preview never writes through a link.`,
856
- {run: [`${PREVIEW} list`]},
1350
+ ? `${what} names ${at(file)}, which is outside ${at(root)}.`
1351
+ : `${at(link.at)} is a link to ${link.to}, outside ${at(root)}; the preview never writes through a link.`,
1352
+ {run: [`${PREVIEW} list${opts.pf ?? ''}`]},
857
1353
  );
858
1354
  }
859
1355
  throw e;
@@ -938,7 +1434,11 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
938
1434
  reservedFolder(cwd, root) ??
939
1435
  (routes.some(r => root === r || root.startsWith(r + path.sep))
940
1436
  ? "it is inside this app's routes folder, where Next would serve the new app's files as pages of this one"
941
- : null);
1437
+ : null) ??
1438
+ (t =>
1439
+ t
1440
+ ? `${shownDir(cwd, t)}/ differs from it only in case, and on macOS and Windows they are one folder`
1441
+ : null)(sameCaseSibling(root));
942
1442
  if (why) {
943
1443
  let free = 'theme-app';
944
1444
  for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
@@ -1135,6 +1635,11 @@ function previewProblem(d) {
1135
1635
  return '"theme" is not a theme name or null';
1136
1636
  if (!Array.isArray(d.pages)) return '"pages" is not a list';
1137
1637
  if (!Array.isArray(d.files)) return '"files" is not a list';
1638
+ if (
1639
+ d.parents !== undefined &&
1640
+ !(Number.isInteger(d.parents) && d.parents >= 0 && d.parents <= 20)
1641
+ )
1642
+ return '"parents" is not a small whole number';
1138
1643
  const ids = new Set();
1139
1644
  for (const p of d.pages) {
1140
1645
  if (!p || typeof p !== 'object' || Array.isArray(p))
@@ -1161,6 +1666,8 @@ function previewProblem(d) {
1161
1666
  f.split('/').some(x => x === '' || x === '.')
1162
1667
  )
1163
1668
  return `"files" holds ${JSON.stringify(f)}, which is not a file path relative to the folder`;
1669
+ else if (f.split('/').includes('..'))
1670
+ return `"files" holds ${JSON.stringify(f)}, which leads outside the folder (${OUTSIDE_FIX})`;
1164
1671
  if (
1165
1672
  d.hashes != null &&
1166
1673
  (typeof d.hashes !== 'object' ||
@@ -1213,15 +1720,21 @@ function holdsApp(cwd, dir) {
1213
1720
  );
1214
1721
  }
1215
1722
 
1723
+ /** What a record entry that leads outside the folder takes. */
1724
+ const OUTSIDE_FIX = `${PREVIEW} remove drops it and deletes nothing outside`;
1725
+
1216
1726
  /**
1217
1727
  * The preview's data, null when the folder has none; a refusal when the
1218
1728
  * file is there but unreadable or of the wrong shape.
1219
1729
  * @param {string} cwd
1220
1730
  * @param {string} dir
1221
1731
  * @param {string} [pf] the caller's --path flag, for the refusal
1732
+ * @param {{dropped?: string[]}} [opts] `dropped`: entries of "files" that
1733
+ * lead outside the folder are taken out and collected here, as `remove`
1734
+ * does
1222
1735
  * @returns {PreviewData | null}
1223
1736
  */
1224
- function readPreview(cwd, dir, pf = '') {
1737
+ function readPreview(cwd, dir, pf = '', opts = {}) {
1225
1738
  /** @type {string} */
1226
1739
  let text;
1227
1740
  try {
@@ -1246,6 +1759,14 @@ function readPreview(cwd, dir, pf = '') {
1246
1759
  pf,
1247
1760
  );
1248
1761
  }
1762
+ // `remove` drops an entry that leads outside the folder, and deletes
1763
+ // nothing there.
1764
+ if (opts.dropped && data && Array.isArray(data.files)) {
1765
+ const outside = (/** @type {unknown} */ f) =>
1766
+ typeof f === 'string' && f.split('/').includes('..');
1767
+ for (const f of data.files) if (outside(f)) opts.dropped.push(f);
1768
+ data.files = data.files.filter((/** @type {unknown} */ f) => !outside(f));
1769
+ }
1249
1770
  const problem = previewProblem(data);
1250
1771
  if (problem) damagedPreview(cwd, dir, problem, pf);
1251
1772
  data.files = [...new Set(data.files)];
@@ -2202,11 +2723,11 @@ async function buildWorn(cwd, theme, options, notes) {
2202
2723
  }
2203
2724
 
2204
2725
  /** The Colors page: its id and file, relative to the route folder. */
2205
- const COLORS_PAGE = {
2726
+ const COLORS_PAGE = wordTable({
2206
2727
  id: 'colors',
2207
2728
  label: 'Colors',
2208
2729
  file: `${PAGES_DIR}/colors`,
2209
- };
2730
+ });
2210
2731
 
2211
2732
  /**
2212
2733
  * The Colors page source of a theme, and whether the theme has generated
@@ -2332,6 +2853,19 @@ function paletteStandIn(cwd, slug) {
2332
2853
  return shown(cwd, file);
2333
2854
  }
2334
2855
 
2856
+ /**
2857
+ * The --path a preview command needs for a preview folder: none for the
2858
+ * default one.
2859
+ * @param {string} cwd
2860
+ * @param {string} dir
2861
+ */
2862
+ function dirFlag(cwd, dir) {
2863
+ const fallback = previewDir(cwd, undefined, {optional: true})?.dir;
2864
+ return fallback === dir
2865
+ ? ''
2866
+ : ` --path ${quoteCommandArgument(shownDir(cwd, dir))}`;
2867
+ }
2868
+
2335
2869
  /**
2336
2870
  * Rewrite the in-app preview routes of a theme when their imports changed, so
2337
2871
  * a font package installed after `set` loads on the next change or `show`,
@@ -2392,6 +2926,15 @@ export async function refreshPreviewRoute(cwd, slug) {
2392
2926
  }
2393
2927
  return true;
2394
2928
  });
2929
+ // A theme that has generated colors now, under a preview with no
2930
+ // Colors page: the next add adds it.
2931
+ if (
2932
+ !data.pages.some(p => p.id === COLORS_PAGE.id) &&
2933
+ (await colorsPage(cwd, dir, slug)).colors
2934
+ )
2935
+ stale.push(
2936
+ `${shownDir(cwd, dir)}/ (${slug} has generated colors now; ${PREVIEW} add${dirFlag(cwd, dir)} adds its Colors page)`,
2937
+ );
2395
2938
  if (!writes.length) continue;
2396
2939
  commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
2397
2940
  changed = true;
@@ -2536,7 +3079,61 @@ async function rankedPages(words, cwd, notes, flags) {
2536
3079
  String(r.reason ?? '').replace(/^matches \d+\/\d+ terms: /, ''),
2537
3080
  ]),
2538
3081
  );
3082
+ // A description that is a template's id or display name names it.
3083
+ const plain = (/** @type {string} */ x) =>
3084
+ x
3085
+ .toLowerCase()
3086
+ .replace(/[^a-z0-9]+/g, ' ')
3087
+ .trim();
3088
+ const exact = listed.find(
3089
+ t => plain(t.id) === plain(words) || plain(t.name ?? '') === plain(words),
3090
+ )?.id;
3091
+ if (exact && frames.has(exact))
3092
+ refuse(
3093
+ E.ERR_INVALID_ARGUMENT,
3094
+ `${exact} is an app frame, not a page, so a description does not add it; name it with --template to add it as a page anyway.`,
3095
+ {run: [`${PREVIEW} add --template ${exact}${flags}`]},
3096
+ );
3097
+ // Build's page ranking, when build picked no page itself (it fell back to
3098
+ // a frame): its pages the description names (by name, keyword or docs,
3099
+ // or a word of it in the page's id), best score first; on a tie, a page whose id holds a word of the
3100
+ // description goes first.
3101
+ const said = plain(words)
3102
+ .split(' ')
3103
+ .filter(w => w.length > 2);
3104
+ const byId = (/** @type {string} */ id) =>
3105
+ said.some(w => id.split('-').includes(w)) ? 1 : 0;
3106
+ const fellBack =
3107
+ !start || (start.basis === 'fallback' && frames.has(start.name));
3108
+ const ranked = (fellBack ? [...(kit.data.pages ?? [])] : [])
3109
+ .map((r, i) => ({
3110
+ name: r.name,
3111
+ score: Number(r.score) || 0,
3112
+ reason: String(r.reason ?? ''),
3113
+ i,
3114
+ }))
3115
+ .filter(
3116
+ r =>
3117
+ listed.some(t => t.id === r.name) &&
3118
+ (/^(exact name|name|keyword|docs mention|description mentions)\b/.test(
3119
+ r.reason,
3120
+ ) ||
3121
+ r.score >= 100 ||
3122
+ byId(r.name)),
3123
+ )
3124
+ .sort(
3125
+ (a, b) => b.score - a.score || byId(b.name) - byId(a.name) || a.i - b.i,
3126
+ )
3127
+ .map(r => r.name);
3128
+ for (const r of kit.data.pages ?? [])
3129
+ if (!matchedWords.has(r.name))
3130
+ matchedWords.set(
3131
+ r.name,
3132
+ String(r.reason ?? '').replace(/^matches \d+\/\d+ terms: /, ''),
3133
+ );
2539
3134
  const names = [
3135
+ ...(exact ? [exact] : []),
3136
+ ...ranked,
2540
3137
  ...(start ? [start.name, ...start.alternatives.map(a => a.name)] : []),
2541
3138
  ...found.map((/** @type {any} */ r) => r.name),
2542
3139
  ].filter((n, i, a) => a.indexOf(n) === i);
@@ -2569,6 +3166,8 @@ async function rankedPages(words, cwd, notes, flags) {
2569
3166
  const named = APP_PAGES.some(([re]) => re.test(words.toLowerCase()));
2570
3167
  const unrelated =
2571
3168
  !named &&
3169
+ !exact &&
3170
+ !ranked.some(n => !frames.has(n)) &&
2572
3171
  (!pages.length ||
2573
3172
  (start &&
2574
3173
  start.basis === 'fallback' &&
@@ -2654,7 +3253,7 @@ async function rankedPages(words, cwd, notes, flags) {
2654
3253
  displayName: label(name),
2655
3254
  why: reason
2656
3255
  ? `${reason}${words ? `; it covers ${words}` : ''}. ${shape}`
2657
- : i === 0 && closest
3256
+ : i === 0 && closest && name !== exact
2658
3257
  ? `the closest page, not exactly the one described${words ? `: it covers ${words}` : ''}; the rest of the description is not on it. ${shape}`
2659
3258
  : `${i === 0 ? 'the best match' : 'the next match'}${words ? `: it covers ${words}` : ''}. ${shape}`,
2660
3259
  };
@@ -2722,6 +3321,17 @@ function installed(cwd, pkg) {
2722
3321
  return findNodeModulesPackage(cwd, pkg) != null;
2723
3322
  }
2724
3323
 
3324
+ /**
3325
+ * The folder of the nearest package.json over `dir`, up to `cwd`.
3326
+ * @param {string} cwd
3327
+ * @param {string} dir
3328
+ */
3329
+ function appRootOf(cwd, dir) {
3330
+ for (let at = dir; at.startsWith(cwd + path.sep); at = path.dirname(at))
3331
+ if (fs.existsSync(path.join(at, 'package.json'))) return at;
3332
+ return cwd;
3333
+ }
3334
+
2725
3335
  /**
2726
3336
  * What a template page needs that the app lacks, from its real imports:
2727
3337
  * packages the app's package.json does not name (with the command that
@@ -2820,7 +3430,7 @@ function wornTheme(cwd, slug, again, without) {
2820
3430
  `${installLine(cwd, [`@astryxdesign/theme-${name}`])} # then a theme of your own can start from it`,
2821
3431
  ]
2822
3432
  : []),
2823
- `${EDITOR} new my-${name} --like ${name} # a theme of your own that starts from it`,
3433
+ `${EDITOR} new ${usableNewName(cwd, `my-${name}`)} --like ${name} # a theme of your own that starts from it`,
2824
3434
  ],
2825
3435
  },
2826
3436
  );
@@ -3008,6 +3618,25 @@ async function addPreview(description, options, box) {
3008
3618
  options.theme != null
3009
3619
  ? ` --theme ${quoteCommandArgument(options.theme)}`
3010
3620
  : '';
3621
+ // A default page's id (overview, components, colors), as `remove` takes
3622
+ // it, asks for the default pages back: the same as a bare add.
3623
+ const DEFAULT_IDS = ['overview', 'components', COLORS_PAGE.id];
3624
+ const isDefault = (/** @type {unknown} */ v) =>
3625
+ typeof v === 'string' && DEFAULT_IDS.includes(v.trim().toLowerCase());
3626
+ // Beside another page asked for, it is refused below (drop one).
3627
+ const blank = (/** @type {unknown} */ v) => v == null || !String(v).trim();
3628
+ const askedId = [description, options.template]
3629
+ .find(isDefault)
3630
+ ?.trim()
3631
+ .toLowerCase();
3632
+ const again =
3633
+ askedId != null &&
3634
+ (blank(description) || isDefault(description)) &&
3635
+ (blank(options.template) || isDefault(options.template));
3636
+ if (again) {
3637
+ description = undefined;
3638
+ options = {...options, template: undefined};
3639
+ }
3011
3640
  const said = (description ?? '').trim();
3012
3641
  const named =
3013
3642
  options.template == null ? null : String(options.template).trim();
@@ -3085,6 +3714,18 @@ async function addPreview(description, options, box) {
3085
3714
  const existing = readPreview(cwd, at.dir, pf);
3086
3715
  /** @type {PreviewData} */
3087
3716
  const data = existing ?? {version: 1, theme: null, pages: [], files: []};
3717
+ // The folders over a new preview folder that are not there yet: the first
3718
+ // add makes them, and remove takes them away again when they are empty.
3719
+ if (!existing) {
3720
+ let made = 0;
3721
+ for (
3722
+ let up = path.dirname(at.dir);
3723
+ up.startsWith((at.app ?? cwd) + path.sep) && !fs.existsSync(up);
3724
+ up = path.dirname(up)
3725
+ )
3726
+ made++;
3727
+ if (made) data.parents = made;
3728
+ }
3088
3729
  const wore = data.theme;
3089
3730
  const againWith = (/** @type {string | null} */ t) =>
3090
3731
  `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${t == null ? '' : ` --theme ${t}`}${pf}`;
@@ -3117,13 +3758,22 @@ async function addPreview(description, options, box) {
3117
3758
  `the preview now wears ${data.theme ?? "the app's own theme"} (was ${wore ?? "the app's own theme"}), so its pages are written again`,
3118
3759
  );
3119
3760
  const project = await openProject(cwd);
3761
+ // Whether the preview has, or gets with a bare add, a Colors page.
3762
+ const hasColors = async () =>
3763
+ data.pages.some(p => p.id === COLORS_PAGE.id) ||
3764
+ (data.theme != null &&
3765
+ fs.existsSync(themeFiles(cwd, data.theme).dir) &&
3766
+ (await colorsPage(cwd, at.dir, data.theme)).colors);
3120
3767
  /** @param {string} id */
3121
3768
  const defaultPage = async id =>
3122
3769
  id === 'overview'
3123
3770
  ? {
3124
3771
  id,
3125
3772
  label: 'Overview',
3126
- text: overviewPageSource(project, {theme: data.theme}),
3773
+ text: overviewPageSource(project, {
3774
+ theme: data.theme,
3775
+ colors: await hasColors(),
3776
+ }),
3127
3777
  }
3128
3778
  : {
3129
3779
  id,
@@ -3167,7 +3817,9 @@ async function addPreview(description, options, box) {
3167
3817
  await template(pick.name, {cwd, type: 'page'})
3168
3818
  );
3169
3819
  const source = shownTemplate.data.source;
3170
- const needs = pageNeeds(cwd, source);
3820
+ // Packages are the app's: the nearest package.json over the preview
3821
+ // (in a workspace, the app's own, not the root's).
3822
+ const needs = pageNeeds(appRootOf(cwd, at.dir), source);
3171
3823
  // A StyleX page calls stylex.create when its module loads, so without
3172
3824
  // a StyleX compiler it breaks the whole route.
3173
3825
  const needsCompiler = needs.stylexCompiler;
@@ -3243,7 +3895,13 @@ async function addPreview(description, options, box) {
3243
3895
  writes.set(rel, w);
3244
3896
  if (!data.files.includes(rel)) data.files.push(rel);
3245
3897
  const had = data.pages.find(x => x.id === page.id);
3246
- if (!had) {
3898
+ // A recorded page whose file is gone is added back, not refreshed.
3899
+ if (!had || !fs.existsSync(path.join(at.dir, rel))) {
3900
+ if (had) {
3901
+ had.label = page.label;
3902
+ added.push(page.id);
3903
+ continue;
3904
+ }
3247
3905
  data.pages.push({
3248
3906
  id: page.id,
3249
3907
  label: page.label,
@@ -3305,6 +3963,19 @@ async function addPreview(description, options, box) {
3305
3963
  writes.set(w.rel, w);
3306
3964
  if (!data.files.includes(w.rel)) data.files.push(w.rel);
3307
3965
  }
3966
+ // Every recorded page this command writes again is named, the Colors page
3967
+ // the route writes included.
3968
+ for (const p of data.pages)
3969
+ if (
3970
+ writes.has(`${p.file}.tsx`) &&
3971
+ !added.includes(p.id) &&
3972
+ !refreshed.includes(p.id) &&
3973
+ !rewrote.includes(p.id) &&
3974
+ fs.existsSync(path.join(at.dir, `${p.file}.tsx`)) &&
3975
+ fs.readFileSync(path.join(at.dir, `${p.file}.tsx`), 'utf8') !==
3976
+ writes.get(`${p.file}.tsx`)?.text
3977
+ )
3978
+ refreshed.push(p.id);
3308
3979
  await buildWorn(cwd, theme, options, notes);
3309
3980
  commitPreview(
3310
3981
  cwd,
@@ -3328,6 +3999,33 @@ async function addPreview(description, options, box) {
3328
3999
  const worn = data.theme;
3329
4000
  if (worn)
3330
4001
  await themeLocked(options, worn, () => recordPreview(cwd, worn, at.dir));
4002
+ // A font the theme names whose package the app lacks shows as the next
4003
+ // font in the stack.
4004
+ if (data.theme && fs.existsSync(themeFiles(cwd, data.theme).dir))
4005
+ try {
4006
+ const ctx = await context(cwd);
4007
+ for (const f of fontPackages(ctx, loadTheme(cwd, data.theme)))
4008
+ if (!f.installed)
4009
+ notes.push(
4010
+ `${f.family} is not installed, so the preview shows the next font in the stack in its place; install it: ${installLine(cwd, [f.pkg])}`,
4011
+ );
4012
+ } catch {
4013
+ // A theme that does not load is reported where it is used.
4014
+ }
4015
+ if (again)
4016
+ notes.push(
4017
+ `a default page's id brings back the default pages that are missing, as ${PREVIEW} add does`,
4018
+ );
4019
+ notes.push(...typeScriptNotes(cwd, at.dir, added));
4020
+ if (
4021
+ askedId === COLORS_PAGE.id &&
4022
+ !data.pages.some(p => p.id === COLORS_PAGE.id)
4023
+ )
4024
+ notes.push(
4025
+ data.theme
4026
+ ? `the Colors page shows a theme's generated colors, and ${data.theme} has none yet; it appears once it does: ${EDITOR} set ${data.theme} accent <color>`
4027
+ : `the Colors page shows a theme's generated colors, and the preview wears the app's own theme; it appears with an editor theme that has colors: ${PREVIEW} add --theme <theme>`,
4028
+ );
3331
4029
  return {
3332
4030
  type: 'themeEdit.previewAdd',
3333
4031
  data: {
@@ -3434,7 +4132,12 @@ export async function themeEditPreviewApp(dir, options = {}) {
3434
4132
  })) {
3435
4133
  const sub = path.join(rel, entry.name);
3436
4134
  if (entry.isDirectory()) copyDir(sub);
3437
- else if (entry.isFile() && !(rel === '' && skip.has(entry.name)))
4135
+ else if (
4136
+ entry.isFile() &&
4137
+ !(rel === '' && skip.has(entry.name)) &&
4138
+ // A temp file a stopped command left is no part of the theme.
4139
+ !isEditorTemp(entry.name)
4140
+ )
3438
4141
  themeCopy.push({
3439
4142
  rel: path.join(to.dir, sub),
3440
4143
  text: fs.readFileSync(path.join(from.dir, sub)),
@@ -3458,7 +4161,11 @@ export async function themeEditPreviewApp(dir, options = {}) {
3458
4161
  routeTheme = {
3459
4162
  name: slug,
3460
4163
  module: fromRoute(to.js),
3461
- css: [fromRoute(to.css), ...fonts.map(x => `${x.pkg}/index.css`)],
4164
+ css: [
4165
+ fromRoute(to.css),
4166
+ ...baseFontsCss(ctx, theme),
4167
+ ...fonts.map(x => `${x.pkg}/index.css`),
4168
+ ],
3462
4169
  mode: themeImports(ctx, slug, theme, path.join(cwd, routeDir)).mode,
3463
4170
  };
3464
4171
  // The app's theme folder sits where this project's does, so the Colors
@@ -3472,7 +4179,14 @@ export async function themeEditPreviewApp(dir, options = {}) {
3472
4179
  const preview = [];
3473
4180
  /** @type {Array<[string, string, string]>} */
3474
4181
  const pages = [
3475
- ['overview', 'Overview', overviewPageSource(project, {theme: slug})],
4182
+ [
4183
+ 'overview',
4184
+ 'Overview',
4185
+ overviewPageSource(project, {
4186
+ theme: slug,
4187
+ colors: colorsSource != null,
4188
+ }),
4189
+ ],
3476
4190
  [
3477
4191
  'components',
3478
4192
  'Components',
@@ -3611,6 +4325,20 @@ export async function themeEditPreviewList(options = {}) {
3611
4325
  const themeMissing = Boolean(
3612
4326
  data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir),
3613
4327
  );
4328
+ if (at && fs.existsSync(path.join(at.dir, PENDING)))
4329
+ notes.push(
4330
+ `a preview change was stopped part way, so this list may be out of date; ${PREVIEW} add${pf} finishes it`,
4331
+ );
4332
+ // A page whose file is gone breaks the route, which still imports it.
4333
+ const missing = new Set(
4334
+ (data?.pages ?? [])
4335
+ .filter(p => at && !fs.existsSync(path.join(at.dir, `${p.file}.tsx`)))
4336
+ .map(p => p.id),
4337
+ );
4338
+ if (at && missing.size)
4339
+ notes.push(
4340
+ `${[...missing].join(', ')} ${missing.size > 1 ? 'are' : 'is'} listed, but ${missing.size > 1 ? 'their files are' : 'its file is'} gone, so the route does not build; ${PREVIEW} add${pf} writes ${missing.size > 1 ? 'them' : 'it'} again`,
4341
+ );
3614
4342
  if (data?.theme && themeMissing) {
3615
4343
  const themes = editedThemes(cwd);
3616
4344
  notes.push(
@@ -3623,7 +4351,11 @@ export async function themeEditPreviewList(options = {}) {
3623
4351
  folder: at && data ? shownDir(cwd, at.dir) : null,
3624
4352
  theme: data?.theme ?? null,
3625
4353
  themeMissing,
3626
- pages: (data?.pages ?? []).map(x => ({id: x.id, label: x.label})),
4354
+ pages: (data?.pages ?? []).map(x => ({
4355
+ id: x.id,
4356
+ label: x.label,
4357
+ ...(missing.has(x.id) ? {missing: true} : {}),
4358
+ })),
3627
4359
  notes,
3628
4360
  },
3629
4361
  };
@@ -3658,9 +4390,29 @@ async function removePreview(page, options, box) {
3658
4390
  const retry = (/** @type {string | null} */ p) =>
3659
4391
  `${PREVIEW} remove${page != null ? ` ${quoteCommandArgument(page)}` : ''}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
3660
4392
  const at = previewDir(cwd, options.path, {retry});
4393
+ // The pages a stopped change was removing, read before it is finished.
4394
+ /** @type {string[]} */
4395
+ let removing = [];
4396
+ try {
4397
+ const pend = JSON.parse(
4398
+ fs.readFileSync(path.join(at.dir, PENDING), 'utf8'),
4399
+ );
4400
+ const ids = (/** @type {any} */ r) =>
4401
+ Array.isArray(r?.pages)
4402
+ ? r.pages.map((/** @type {any} */ x) => String(x?.id))
4403
+ : [];
4404
+ const after = ids(pend?.record);
4405
+ removing = ids(pend?.old).filter(
4406
+ (/** @type {string} */ id) => !after.includes(id),
4407
+ );
4408
+ } catch {
4409
+ // No stopped change, or a damaged one.
4410
+ }
3661
4411
  const recovered = recoverPreview(cwd, at.dir);
3662
4412
  box.note = recovered;
3663
- const data = readPreview(cwd, at.dir, pf);
4413
+ /** @type {string[]} */
4414
+ const dropped = [];
4415
+ const data = readPreview(cwd, at.dir, pf, {dropped});
3664
4416
  if (!data) {
3665
4417
  // A folder that holds the app takes no preview: the way on is the
3666
4418
  // preview elsewhere, or a new one in its own folder.
@@ -3692,11 +4444,15 @@ async function removePreview(page, options, box) {
3692
4444
  // theme-preview.json is a file anyone can edit: every path in it must
3693
4445
  // stay in the route folder before anything is removed.
3694
4446
  const inside = (/** @type {string} */ rel) =>
3695
- confined(path.join(at.dir, rel), at.dir, `${PREVIEW_DATA} names`);
4447
+ confined(path.join(at.dir, rel), at.dir, PREVIEW_DATA, {cwd, pf});
3696
4448
  for (const rel of data.files) inside(rel);
3697
4449
  for (const p of data.pages) inside(`${p.file}.tsx`);
3698
4450
  /** @type {string[]} */
3699
4451
  const notes = recovered ? [recovered] : [];
4452
+ if (dropped.length)
4453
+ notes.push(
4454
+ `dropped ${dropped.map(f => JSON.stringify(f)).join(', ')} from ${PREVIEW_DATA}: ${dropped.length > 1 ? 'they lead' : 'it leads'} outside the folder, so nothing there was deleted`,
4455
+ );
3700
4456
  /** @type {string[]} */
3701
4457
  const kept = [];
3702
4458
  /** @type {string[]} */
@@ -3709,6 +4465,28 @@ async function removePreview(page, options, box) {
3709
4465
  one =
3710
4466
  data.pages.find(x => x.id === key) ??
3711
4467
  data.pages.find(x => x.id.toLowerCase() === key.toLowerCase());
4468
+ // The same remove run again after it was stopped: the change just
4469
+ // finished removed the page.
4470
+ if (
4471
+ !one &&
4472
+ recovered &&
4473
+ removing.some(id => id.toLowerCase() === key.toLowerCase())
4474
+ )
4475
+ return {
4476
+ type: 'themeEdit.previewRemove',
4477
+ data: {
4478
+ folder,
4479
+ removed: [],
4480
+ kept: [],
4481
+ missing: [],
4482
+ rewritten: [],
4483
+ notes: [
4484
+ ...notes,
4485
+ `${key} is no longer in the preview: the change that was stopped removed it`,
4486
+ ],
4487
+ pages: data.pages.map(x => x.id),
4488
+ },
4489
+ };
3712
4490
  if (!one)
3713
4491
  refuse(E.ERR_NOT_FOUND, `The preview has no page "${page}".`, {
3714
4492
  didYouMean: nearest(
@@ -3733,12 +4511,19 @@ async function removePreview(page, options, box) {
3733
4511
  `${name} was not written by the preview, so it is kept; only its nav item is gone`,
3734
4512
  );
3735
4513
  } else if (!fs.existsSync(inside(rel))) missing.push(name);
3736
- else if (verdict !== 'delete') {
4514
+ else if (unreadable(inside(rel))) {
4515
+ kept.push(name);
4516
+ notes.push(
4517
+ `${name} could not be read (${unreadable(inside(rel))}), so it is left in place and stays in ${PREVIEW_DATA}; fix its permissions, then run ${PREVIEW} remove${pf} again`,
4518
+ );
4519
+ } else if (verdict !== 'delete') {
3737
4520
  kept.push(name);
3738
4521
  notes.push(keptNote(name, verdict));
3739
4522
  } else deletes.push(rel);
3740
4523
  data.pages = data.pages.filter(x => x !== target);
3741
- data.files = data.files.filter(f => f !== rel);
4524
+ // A file left in place because it could not be read stays recorded.
4525
+ if (!unreadable(inside(rel)))
4526
+ data.files = data.files.filter(f => f !== rel);
3742
4527
  const wore = data.theme;
3743
4528
  /** @type {string | null} */
3744
4529
  let gone = null;
@@ -3885,6 +4670,14 @@ async function removePreview(page, options, box) {
3885
4670
  );
3886
4671
  continue;
3887
4672
  }
4673
+ const cannot = unreadable(file);
4674
+ if (cannot) {
4675
+ kept.push(shown(cwd, file));
4676
+ notes.push(
4677
+ `${shown(cwd, file)} could not be read (${cannot}), so it is left in place; fix its permissions, then run ${PREVIEW} remove${pf} again`,
4678
+ );
4679
+ continue;
4680
+ }
3888
4681
  plan.push({file, before: fs.readFileSync(file)});
3889
4682
  }
3890
4683
  // theme-preview.json goes last, so an interrupted remove can run again.
@@ -3926,11 +4719,16 @@ async function removePreview(page, options, box) {
3926
4719
  }
3927
4720
  try {
3928
4721
  fs.rmdirSync(at.dir);
3929
- // Route group folders, such as (tools)/, that only held the preview.
4722
+ // The folders the first add made over it, and route group folders,
4723
+ // such as (tools)/, that only held the preview; never one with
4724
+ // anything else in it.
4725
+ let made = data.parents ?? 0;
3930
4726
  for (
3931
4727
  let up = path.dirname(at.dir);
3932
- /^\(.+\)$/.test(path.basename(up)) && at.app && up.startsWith(at.app);
3933
- up = path.dirname(up)
4728
+ (made > 0 || /^\(.+\)$/.test(path.basename(up))) &&
4729
+ at.app &&
4730
+ up.startsWith(at.app + path.sep);
4731
+ up = path.dirname(up), made--
3934
4732
  )
3935
4733
  fs.rmdirSync(up);
3936
4734
  } catch {