@astryxdesign/cli 0.7.15 → 0.7.16-canary.g56680f6

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 (117) 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 +185 -39
  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 +91 -19
  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 +21 -0
  21. package/api/theme-edit/_adapter.mjs +176 -22
  22. package/api/theme-edit/_check.d.mts +7 -0
  23. package/api/theme-edit/_check.mjs +1050 -173
  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 +21 -0
  29. package/api/theme-edit/_context.mjs +235 -12
  30. package/api/theme-edit/_css.d.mts +50 -1
  31. package/api/theme-edit/_css.mjs +310 -28
  32. package/api/theme-edit/_edit.d.mts +9 -0
  33. package/api/theme-edit/_edit.mjs +907 -123
  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/_palette.d.mts +6 -0
  40. package/api/theme-edit/_palette.mjs +164 -62
  41. package/api/theme-edit/_parts.d.mts +16 -0
  42. package/api/theme-edit/_parts.mjs +49 -1
  43. package/api/theme-edit/_png.mjs +19 -14
  44. package/api/theme-edit/_preview-app.mjs +514 -27
  45. package/api/theme-edit/_preview.d.mts +11 -0
  46. package/api/theme-edit/_preview.mjs +245 -24
  47. package/api/theme-edit/_project.d.mts +11 -0
  48. package/api/theme-edit/_project.mjs +35 -9
  49. package/api/theme-edit/_settings.d.mts +122 -5
  50. package/api/theme-edit/_settings.mjs +1363 -71
  51. package/api/theme-edit/_tables.d.mts +19 -0
  52. package/api/theme-edit/_tables.mjs +205 -149
  53. package/api/theme-edit/_vet.d.mts +42 -0
  54. package/api/theme-edit/_vet.mjs +144 -0
  55. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  56. package/api/theme-edit/theme-edit.type.mjs +1 -1
  57. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  58. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  59. package/assets/docs/tree/single-component.doc.mjs +11 -2
  60. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  61. package/assets/docs.generated.json +2 -2
  62. package/assets/preview-app/next.config.mjs +7 -1
  63. package/assets/preview-app/src/app/globals.css +1 -0
  64. package/assets/self-audit.generated.json +1 -1
  65. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  66. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  67. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  68. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  69. package/assets/templates/components.generated.json +1 -1
  70. package/assets/templates/pages/dashboard/page.tsx +1 -1
  71. package/authoring/doctypes/_schema.d.mts +52 -5
  72. package/authoring/doctypes/_schema.mjs +62 -7
  73. package/authoring/doctypes/base/type.ts +10 -0
  74. package/authoring/doctypes/component/component.doc.mjs +1 -1
  75. package/authoring/doctypes/function/function.doc.mjs +6 -0
  76. package/authoring/doctypes/function/type.ts +3 -0
  77. package/authoring/doctypes/legacy.mjs +5 -1
  78. package/authoring/index.d.ts +1 -0
  79. package/clients/cli/build-id.generated.json +1 -1
  80. package/clients/cli/commands/doctor.doc.mjs +2 -2
  81. package/clients/cli/commands/experimental/theme.mjs +188 -37
  82. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  83. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  84. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  85. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  86. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  87. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  88. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  89. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  90. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  91. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  92. package/clients/cli/commands/theme.mjs +93 -10
  93. package/clients/cli/formatters/index.mjs +7 -4
  94. package/clients/cli/lib/cli-error.mjs +9 -3
  95. package/clients/cli/lib/component-format.mjs +27 -9
  96. package/clients/cli/lib/json-shim.mjs +40 -2
  97. package/clients/cli/manifest.generated.json +1 -1
  98. package/foundation/config/project.mjs +50 -14
  99. package/foundation/discovery/theme-discovery.d.mts +5 -1
  100. package/foundation/discovery/theme-discovery.mjs +24 -3
  101. package/foundation/fs/gather-cache.d.mts +9 -2
  102. package/foundation/fs/gather-cache.mjs +36 -10
  103. package/foundation/fs/paths.d.mts +16 -0
  104. package/foundation/fs/paths.mjs +25 -0
  105. package/foundation/render/host-exit.d.mts +8 -0
  106. package/foundation/render/host-exit.mjs +11 -0
  107. package/foundation/render/page-host.mjs +56 -10
  108. package/foundation/render/page-worker.mjs +14 -0
  109. package/foundation/render/render-page.mjs +37 -2
  110. package/foundation/response/error-codes.d.mts +2 -1
  111. package/foundation/response/error-codes.d.ts +1 -0
  112. package/foundation/response/error-codes.doc.mjs +5 -0
  113. package/foundation/response/error-codes.mjs +3 -0
  114. package/foundation/response/json.d.mts +15 -0
  115. package/foundation/response/json.mjs +52 -1
  116. package/foundation/response/response-types.doc.mjs +1 -1
  117. 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,
@@ -36,6 +37,7 @@ import {
36
37
  windowsReserved,
37
38
  } from './_settings.mjs';
38
39
  import {
40
+ baseFontsCss,
39
41
  colorsPageSource,
40
42
  componentsPageSource,
41
43
  overviewPageSource,
@@ -43,6 +45,7 @@ import {
43
45
  themeImports,
44
46
  } from './_preview.mjs';
45
47
  import {
48
+ isEditorTemp,
46
49
  PALETTE_STAND_IN,
47
50
  paletteFiles,
48
51
  paletteMapping,
@@ -204,11 +207,12 @@ function readNextConfig(cwd) {
204
207
  basePath: undefined,
205
208
  distDir: undefined,
206
209
  };
210
+ // The order Next loads them in; it refuses next.config.cjs.
207
211
  for (const name of [
208
- 'next.config.mjs',
209
212
  'next.config.js',
213
+ 'next.config.mjs',
210
214
  'next.config.ts',
211
- 'next.config.cjs',
215
+ 'next.config.mts',
212
216
  ]) {
213
217
  /** @type {string} */
214
218
  let text;
@@ -270,6 +274,11 @@ function readNextConfig(cwd) {
270
274
  let exported = null;
271
275
  for (const st of body) {
272
276
  if (st.type === 'ExportDefaultDeclaration') exported = st.declaration;
277
+ // export {config as default}
278
+ if (st.type === 'ExportNamedDeclaration' && !st.source)
279
+ for (const sp of st.specifiers ?? [])
280
+ if ((sp.exported?.name ?? sp.exported?.value) === 'default')
281
+ exported = sp.local;
273
282
  if (
274
283
  st.type === 'ExpressionStatement' &&
275
284
  st.expression.type === 'AssignmentExpression' &&
@@ -281,6 +290,66 @@ function readNextConfig(cwd) {
281
290
  }
282
291
  const config = exported && configOf(exported);
283
292
  if (!config) return exported ? unknown : none;
293
+ const wrapped = resolve(exported)?.type === 'CallExpression';
294
+ // Changes to the config after it is made: `config.key = value` sets a
295
+ // key (the last one counts), and anything else (Object.assign, a
296
+ // computed key) makes every key unknown.
297
+ const names = new Set(
298
+ [...consts]
299
+ .filter(([, init]) => resolve(init) === config)
300
+ .map(([n]) => n),
301
+ );
302
+ /** @type {Map<string, any>} */
303
+ const later = new Map();
304
+ let changed = false;
305
+ // Only a statement at the top of the file surely runs: a key set inside
306
+ // an `if` or a function, or deleted, is known only by running it.
307
+ const UNSURE = Symbol('unsure');
308
+ const topLevel = new Set(
309
+ body
310
+ .filter(st => st.type === 'ExpressionStatement')
311
+ .map(st => st.expression),
312
+ );
313
+ /** @param {any} n */
314
+ const visit = n => {
315
+ if (!n || typeof n !== 'object') return;
316
+ if (Array.isArray(n)) return n.forEach(visit);
317
+ if (
318
+ n.type === 'AssignmentExpression' &&
319
+ n.left?.type === 'MemberExpression' &&
320
+ names.has(n.left.object?.name)
321
+ ) {
322
+ if (n.left.computed) changed = true;
323
+ else
324
+ later.set(
325
+ n.left.property.name,
326
+ topLevel.has(n) && n.operator === '=' ? n.right : UNSURE,
327
+ );
328
+ }
329
+ if (
330
+ n.type === 'UnaryExpression' &&
331
+ n.operator === 'delete' &&
332
+ n.argument?.type === 'MemberExpression' &&
333
+ names.has(n.argument.object?.name)
334
+ ) {
335
+ if (n.argument.computed) changed = true;
336
+ else later.set(n.argument.property.name, UNSURE);
337
+ }
338
+ if (
339
+ n.type === 'CallExpression' &&
340
+ n.arguments?.some(
341
+ (/** @type {any} */ a) =>
342
+ a.type === 'Identifier' && names.has(a.name),
343
+ ) &&
344
+ n.callee?.type === 'MemberExpression' &&
345
+ n.callee.object?.name === 'Object'
346
+ )
347
+ changed = true;
348
+ for (const [k, v] of Object.entries(n))
349
+ if (k !== 'loc' && k !== 'start' && k !== 'end') visit(v);
350
+ };
351
+ visit(body);
352
+ if (changed) return unknown;
284
353
  // The config's keys in order, with a spread of a constant object read
285
354
  // in place; a spread of anything else may set any key (`null`).
286
355
  /** @type {Array<{key: string, value: any} | null>} */
@@ -302,8 +371,10 @@ function readNextConfig(cwd) {
302
371
  }
303
372
  };
304
373
  flatten(config, 0);
305
- /** The entry that sets a key last; null when an unreadable spread may; undefined when nothing does. @param {string} key */
374
+ /** 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
375
  const prop = key => {
376
+ if (later.has(key))
377
+ return later.get(key) === UNSURE ? null : {key, value: later.get(key)};
307
378
  for (let i = entries.length - 1; i >= 0; i--) {
308
379
  const e = entries[i];
309
380
  if (e === null) return null;
@@ -332,10 +403,13 @@ function readNextConfig(cwd) {
332
403
  const out = n.elements.map((/** @type {any} */ e) => str(e));
333
404
  return out.every((/** @type {any} */ e) => e != null) ? out : null;
334
405
  }),
335
- basePath: value('basePath', n => {
336
- const v = str(n);
337
- return v == null ? null : v.replace(/\/+$/, '');
338
- }),
406
+ // A wrapper such as withX(config) may add a basePath of its own.
407
+ basePath: wrapped
408
+ ? null
409
+ : value('basePath', n => {
410
+ const v = str(n);
411
+ return v == null ? null : v.replace(/\/+$/, '');
412
+ }),
339
413
  distDir: value('distDir', n => {
340
414
  const v = str(n);
341
415
  return v == null
@@ -407,6 +481,134 @@ function reservedFolder(cwd, dir) {
407
481
  return null;
408
482
  }
409
483
 
484
+ /**
485
+ * The app's tsconfig.json compiler options (comments and trailing commas
486
+ * allowed), or null when there is none.
487
+ * @param {string} cwd
488
+ * @returns {Record<string, unknown> | null}
489
+ */
490
+ function appCompilerOptions(cwd) {
491
+ /** @type {string} */
492
+ let text;
493
+ try {
494
+ text = fs.readFileSync(path.join(cwd, 'tsconfig.json'), 'utf8');
495
+ } catch {
496
+ return null;
497
+ }
498
+ try {
499
+ const json = text
500
+ .replace(
501
+ /("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\/|\/\/.*$/gm,
502
+ (m, str) => str ?? '',
503
+ )
504
+ .replace(/,(\s*[}\]])/g, '$1');
505
+ const o = JSON.parse(json)?.compilerOptions;
506
+ return o && typeof o === 'object' ? o : {};
507
+ } catch {
508
+ return {};
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Notes on what the preview's TypeScript files need from the app: an app
514
+ * with no TypeScript gets the install line (Next sets it up on the next
515
+ * build otherwise), and an app whose tsconfig turns on
516
+ * `noUncheckedIndexedAccess` is told which template pages were written as
517
+ * their template ships them, which may not pass it.
518
+ * @param {string} cwd
519
+ * @param {string} dir
520
+ * @param {string[]} added page ids added by this command
521
+ * @returns {string[]}
522
+ */
523
+ function typeScriptNotes(cwd, dir, added) {
524
+ const options = appCompilerOptions(cwd);
525
+ if (!options) {
526
+ const hasTs = (() => {
527
+ try {
528
+ return Boolean(
529
+ createRequire(path.join(cwd, 'package.json')).resolve('typescript'),
530
+ );
531
+ } catch {
532
+ return false;
533
+ }
534
+ })();
535
+ return hasTs
536
+ ? []
537
+ : [
538
+ `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 ')}`,
539
+ ];
540
+ }
541
+ const templates = added.filter(
542
+ id => !['overview', 'components', COLORS_PAGE.id].includes(id),
543
+ );
544
+ if (options.noUncheckedIndexedAccess !== true || !templates.length) return [];
545
+ const files = templates.map(id =>
546
+ shown(cwd, path.join(dir, PAGES_DIR, `${id}.tsx`)),
547
+ );
548
+ return [
549
+ `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]}`,
550
+ ];
551
+ }
552
+
553
+ /**
554
+ * Why a file cannot be read (its error code), or null when it can.
555
+ * @param {string} file
556
+ * @returns {string | null}
557
+ */
558
+ function unreadable(file) {
559
+ try {
560
+ fs.closeSync(fs.openSync(file, 'r'));
561
+ return null;
562
+ } catch (e) {
563
+ const code = /** @type {any} */ (e)?.code;
564
+ return code === 'ENOENT' ? null : (code ?? 'error');
565
+ }
566
+ }
567
+
568
+ /**
569
+ * Whether a folder beside `dir` has its name in another case.
570
+ * @param {string} dir
571
+ */
572
+ function twinBeside(dir) {
573
+ const name = path.basename(dir);
574
+ try {
575
+ return fs
576
+ .readdirSync(path.dirname(dir))
577
+ .some(n => n !== name && n.toLowerCase() === name.toLowerCase());
578
+ } catch {
579
+ return false;
580
+ }
581
+ }
582
+
583
+ /**
584
+ * A folder beside `dir`, or beside one of its parents, whose name differs
585
+ * only in case, or null.
586
+ * @param {string} dir
587
+ * @returns {string | null}
588
+ */
589
+ function sameCaseSibling(dir) {
590
+ for (let at = dir; path.dirname(at) !== at; at = path.dirname(at)) {
591
+ const parent = path.dirname(at);
592
+ const name = path.basename(at);
593
+ /** @type {string[]} */
594
+ let names;
595
+ try {
596
+ names = fs.readdirSync(parent);
597
+ } catch {
598
+ continue;
599
+ }
600
+ const twin = names.find(
601
+ n => n !== name && n.toLowerCase() === name.toLowerCase(),
602
+ );
603
+ if (twin) return path.join(parent, twin);
604
+ if (fs.existsSync(path.join(parent, 'package.json'))) break;
605
+ }
606
+ return null;
607
+ }
608
+
609
+ /** An intercepting route folder: `(.)x`, `(..)x`, `(..)(..)x`, `(...)x`. */
610
+ const INTERCEPT = /^\((\.{1,3})\)/;
611
+
410
612
  /**
411
613
  * Why Next does not serve a folder inside the routes folder at its own
412
614
  * URL, or null: a `_private` folder is never routed, an `@slot` folder is a
@@ -418,7 +620,9 @@ function unroutedSegment(app, dir) {
418
620
  const seg = path
419
621
  .relative(app, dir)
420
622
  .split(path.sep)
421
- .find(x => /^[_@[]/.test(x));
623
+ .find(x => /^[_@[]/.test(x) || INTERCEPT.test(x));
624
+ if (seg && INTERCEPT.test(seg))
625
+ 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
626
  return seg
423
627
  ? `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
628
  : null;
@@ -615,6 +819,75 @@ function checkPlacement(cwd, dir, where, retry) {
615
819
  `${where} is no place for the preview: ${why}.`,
616
820
  {run: [fallback]},
617
821
  );
822
+ // A folder name that is not a plain URL segment (a space, an accent,
823
+ // ?, #, %) is not served at the URL it seems to have. The characters a
824
+ // URL path takes as they are (RFC 3986 unreserved and sub-delims, @, ~)
825
+ // are served.
826
+ const PLAIN = /^[A-Za-z0-9._~!$&'()+,;=@-]+$/;
827
+ const segs = app ? path.relative(app, dir).split(path.sep) : [];
828
+ const odd = segs.filter(
829
+ seg => seg && !/^\(.+\)$|^\[.+\]$/.test(seg) && !PLAIN.test(seg),
830
+ );
831
+ if (app && odd.length) {
832
+ const slug = (/** @type {string} */ seg) =>
833
+ seg
834
+ .normalize('NFD')
835
+ .replace(/[\u0300-\u036f]/g, '')
836
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
837
+ .replace(/^-+|-+$/g, '')
838
+ .toLowerCase() || 'theme-preview';
839
+ // Every odd segment slugged, then the first free folder from it.
840
+ const base = path.join(
841
+ app,
842
+ ...segs.map(seg => (odd.includes(seg) ? slug(seg) : seg)),
843
+ );
844
+ let fixed = base;
845
+ for (
846
+ let n = 2;
847
+ fs.existsSync(fixed) || twinBeside(fixed) || sameUrlPage(cwd, app, fixed);
848
+ n++
849
+ )
850
+ fixed = `${base}-${n}`;
851
+ refuse(
852
+ E.ERR_INVALID_ARGUMENT,
853
+ `${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).`,
854
+ {run: [retry(shown(cwd, fixed))]},
855
+ );
856
+ }
857
+ // A folder whose name differs from a folder beside it only in case is the
858
+ // same folder on macOS and Windows: one of them is lost in a checkout.
859
+ const twin = sameCaseSibling(dir);
860
+ if (twin) {
861
+ // A twin of a folder on the way: the same path through the folder that
862
+ // is there. A twin of the folder itself: the first free name beside it.
863
+ const base = path.dirname(twin);
864
+ const rel = path.relative(base, dir).split(path.sep);
865
+ // Both spellings are folders already: no path through either is free,
866
+ // so the way on is a new folder beside them.
867
+ const bothThere = rel.length > 1 && fs.existsSync(path.join(base, rel[0]));
868
+ let free = path.join(twin, ...rel.slice(1));
869
+ if (rel.length === 1 || bothThere) {
870
+ const start = rel.length === 1 ? dir : path.join(base, 'theme-preview');
871
+ free = start;
872
+ for (let n = 2; fs.existsSync(free) || twinBeside(free); n++)
873
+ free = `${start}-${n}`;
874
+ }
875
+ const existing = fs.existsSync(path.join(dir, PREVIEW_DATA));
876
+ refuse(
877
+ E.ERR_INVALID_ARGUMENT,
878
+ `${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.` : ''}`,
879
+ {
880
+ run: [
881
+ retry(shown(cwd, free)),
882
+ ...(existing
883
+ ? [
884
+ `${PREVIEW} remove --path ${quoteCommandArgument(shownDir(cwd, dir))}`,
885
+ ]
886
+ : []),
887
+ ],
888
+ },
889
+ );
890
+ }
618
891
  if (!app) return;
619
892
  if (served && app !== served)
620
893
  refuse(
@@ -676,8 +949,12 @@ function checkPlacement(cwd, dir, where, retry) {
676
949
  );
677
950
  const clash = sameUrlPage(cwd, app, dir);
678
951
  if (clash) {
679
- let free = `${dir}-2`;
680
- for (let n = 3; fs.existsSync(free); n++) free = `${dir}-${n}`;
952
+ // The first free name from the base name, whose URL no other page
953
+ // serves either.
954
+ const base = dir.replace(/-\d+$/, '');
955
+ let free = `${base}-2`;
956
+ for (let n = 3; fs.existsSync(free) || sameUrlPage(cwd, app, free); n++)
957
+ free = `${base}-${n}`;
681
958
  refuse(
682
959
  E.ERR_FILE_EXISTS,
683
960
  `${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 +1004,52 @@ function previewDir(cwd, where, opts = {}) {
727
1004
  );
728
1005
  throw e;
729
1006
  }
1007
+ // A file on the way, or a path longer than the system takes, would
1008
+ // fail every command on it with a system error.
1009
+ const blocker = (() => {
1010
+ for (
1011
+ let at = path.dirname(dir);
1012
+ at.startsWith(cwd + path.sep);
1013
+ at = path.dirname(at)
1014
+ )
1015
+ try {
1016
+ if (!fs.statSync(at).isDirectory()) return at;
1017
+ } catch {
1018
+ // Not there yet: made with the folder.
1019
+ }
1020
+ return null;
1021
+ })();
1022
+ if (blocker)
1023
+ refuse(
1024
+ E.ERR_INVALID_ARGUMENT,
1025
+ `--path ${where} goes through ${shown(cwd, blocker)}, which is a file, so no folder can be made there.`,
1026
+ {
1027
+ run: [
1028
+ retry(
1029
+ shown(cwd, path.join(path.dirname(blocker), 'theme-preview')),
1030
+ ),
1031
+ ],
1032
+ },
1033
+ );
1034
+ // A folder name is at most 255 bytes on every common file system; the
1035
+ // whole path, with the preview's own files below it, is kept under
1036
+ // 3,500 bytes.
1037
+ const longName = path
1038
+ .relative(cwd, dir)
1039
+ .split(path.sep)
1040
+ .find(seg => Buffer.byteLength(seg) > 255);
1041
+ if (longName)
1042
+ refuse(
1043
+ E.ERR_INVALID_ARGUMENT,
1044
+ `--path ${where} has a folder name longer than 255 bytes, the most a file system takes for one name.`,
1045
+ {run: [retry(null)]},
1046
+ );
1047
+ if (Buffer.byteLength(dir) > 3500)
1048
+ refuse(
1049
+ E.ERR_INVALID_ARGUMENT,
1050
+ `--path ${where} is longer than 3,500 bytes, with the preview's files in it.`,
1051
+ {run: [retry(null)]},
1052
+ );
730
1053
  if (opts.write) checkPlacement(cwd, dir, `--path ${where}`, retry);
731
1054
  return {dir, app: appOf(dir)};
732
1055
  }
@@ -827,9 +1150,11 @@ const STARTER = path.join(CLI_PACKAGE, 'assets', 'preview-app');
827
1150
  * @param {string} file absolute
828
1151
  * @param {string} root absolute
829
1152
  * @param {string} what what the path is, for the refusal
1153
+ * @param {{cwd?: string, pf?: string}} [opts] `cwd`: paths in the refusal
1154
+ * are shown from it; `pf`: the caller's --path flag, for the suggestion
830
1155
  * @returns {string}
831
1156
  */
832
- function confined(file, root, what) {
1157
+ function confined(file, root, what, opts = {}) {
833
1158
  try {
834
1159
  return assertWithin(file, root, {allowAbsolute: true, label: what});
835
1160
  } catch (e) {
@@ -848,12 +1173,14 @@ function confined(file, root, what) {
848
1173
  } catch {
849
1174
  // Not there: look at its folder.
850
1175
  }
1176
+ const at = (/** @type {string} */ f) =>
1177
+ opts.cwd ? shown(opts.cwd, f) || '.' : f;
851
1178
  refuse(
852
1179
  E.ERR_PATH_TRAVERSAL,
853
1180
  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`]},
1181
+ ? `${what} names ${at(file)}, which is outside ${at(root)}.`
1182
+ : `${at(link.at)} is a link to ${link.to}, outside ${at(root)}; the preview never writes through a link.`,
1183
+ {run: [`${PREVIEW} list${opts.pf ?? ''}`]},
857
1184
  );
858
1185
  }
859
1186
  throw e;
@@ -938,7 +1265,11 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
938
1265
  reservedFolder(cwd, root) ??
939
1266
  (routes.some(r => root === r || root.startsWith(r + path.sep))
940
1267
  ? "it is inside this app's routes folder, where Next would serve the new app's files as pages of this one"
941
- : null);
1268
+ : null) ??
1269
+ (t =>
1270
+ t
1271
+ ? `${shownDir(cwd, t)}/ differs from it only in case, and on macOS and Windows they are one folder`
1272
+ : null)(sameCaseSibling(root));
942
1273
  if (why) {
943
1274
  let free = 'theme-app';
944
1275
  for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
@@ -1161,6 +1492,8 @@ function previewProblem(d) {
1161
1492
  f.split('/').some(x => x === '' || x === '.')
1162
1493
  )
1163
1494
  return `"files" holds ${JSON.stringify(f)}, which is not a file path relative to the folder`;
1495
+ else if (f.split('/').includes('..'))
1496
+ return `"files" holds ${JSON.stringify(f)}, which leads outside the folder (${OUTSIDE_FIX})`;
1164
1497
  if (
1165
1498
  d.hashes != null &&
1166
1499
  (typeof d.hashes !== 'object' ||
@@ -1213,15 +1546,21 @@ function holdsApp(cwd, dir) {
1213
1546
  );
1214
1547
  }
1215
1548
 
1549
+ /** What a record entry that leads outside the folder takes. */
1550
+ const OUTSIDE_FIX = `${PREVIEW} remove drops it and deletes nothing outside`;
1551
+
1216
1552
  /**
1217
1553
  * The preview's data, null when the folder has none; a refusal when the
1218
1554
  * file is there but unreadable or of the wrong shape.
1219
1555
  * @param {string} cwd
1220
1556
  * @param {string} dir
1221
1557
  * @param {string} [pf] the caller's --path flag, for the refusal
1558
+ * @param {{dropped?: string[]}} [opts] `dropped`: entries of "files" that
1559
+ * lead outside the folder are taken out and collected here, as `remove`
1560
+ * does
1222
1561
  * @returns {PreviewData | null}
1223
1562
  */
1224
- function readPreview(cwd, dir, pf = '') {
1563
+ function readPreview(cwd, dir, pf = '', opts = {}) {
1225
1564
  /** @type {string} */
1226
1565
  let text;
1227
1566
  try {
@@ -1246,6 +1585,14 @@ function readPreview(cwd, dir, pf = '') {
1246
1585
  pf,
1247
1586
  );
1248
1587
  }
1588
+ // `remove` drops an entry that leads outside the folder, and deletes
1589
+ // nothing there.
1590
+ if (opts.dropped && data && Array.isArray(data.files)) {
1591
+ const outside = (/** @type {unknown} */ f) =>
1592
+ typeof f === 'string' && f.split('/').includes('..');
1593
+ for (const f of data.files) if (outside(f)) opts.dropped.push(f);
1594
+ data.files = data.files.filter((/** @type {unknown} */ f) => !outside(f));
1595
+ }
1249
1596
  const problem = previewProblem(data);
1250
1597
  if (problem) damagedPreview(cwd, dir, problem, pf);
1251
1598
  data.files = [...new Set(data.files)];
@@ -2202,11 +2549,11 @@ async function buildWorn(cwd, theme, options, notes) {
2202
2549
  }
2203
2550
 
2204
2551
  /** The Colors page: its id and file, relative to the route folder. */
2205
- const COLORS_PAGE = {
2552
+ const COLORS_PAGE = wordTable({
2206
2553
  id: 'colors',
2207
2554
  label: 'Colors',
2208
2555
  file: `${PAGES_DIR}/colors`,
2209
- };
2556
+ });
2210
2557
 
2211
2558
  /**
2212
2559
  * The Colors page source of a theme, and whether the theme has generated
@@ -3008,6 +3355,25 @@ async function addPreview(description, options, box) {
3008
3355
  options.theme != null
3009
3356
  ? ` --theme ${quoteCommandArgument(options.theme)}`
3010
3357
  : '';
3358
+ // A default page's id (overview, components, colors), as `remove` takes
3359
+ // it, asks for the default pages back: the same as a bare add.
3360
+ const DEFAULT_IDS = ['overview', 'components', COLORS_PAGE.id];
3361
+ const isDefault = (/** @type {unknown} */ v) =>
3362
+ typeof v === 'string' && DEFAULT_IDS.includes(v.trim().toLowerCase());
3363
+ // Beside another page asked for, it is refused below (drop one).
3364
+ const blank = (/** @type {unknown} */ v) => v == null || !String(v).trim();
3365
+ const askedId = [description, options.template]
3366
+ .find(isDefault)
3367
+ ?.trim()
3368
+ .toLowerCase();
3369
+ const again =
3370
+ askedId != null &&
3371
+ (blank(description) || isDefault(description)) &&
3372
+ (blank(options.template) || isDefault(options.template));
3373
+ if (again) {
3374
+ description = undefined;
3375
+ options = {...options, template: undefined};
3376
+ }
3011
3377
  const said = (description ?? '').trim();
3012
3378
  const named =
3013
3379
  options.template == null ? null : String(options.template).trim();
@@ -3243,7 +3609,13 @@ async function addPreview(description, options, box) {
3243
3609
  writes.set(rel, w);
3244
3610
  if (!data.files.includes(rel)) data.files.push(rel);
3245
3611
  const had = data.pages.find(x => x.id === page.id);
3246
- if (!had) {
3612
+ // A recorded page whose file is gone is added back, not refreshed.
3613
+ if (!had || !fs.existsSync(path.join(at.dir, rel))) {
3614
+ if (had) {
3615
+ had.label = page.label;
3616
+ added.push(page.id);
3617
+ continue;
3618
+ }
3247
3619
  data.pages.push({
3248
3620
  id: page.id,
3249
3621
  label: page.label,
@@ -3305,6 +3677,19 @@ async function addPreview(description, options, box) {
3305
3677
  writes.set(w.rel, w);
3306
3678
  if (!data.files.includes(w.rel)) data.files.push(w.rel);
3307
3679
  }
3680
+ // Every recorded page this command writes again is named, the Colors page
3681
+ // the route writes included.
3682
+ for (const p of data.pages)
3683
+ if (
3684
+ writes.has(`${p.file}.tsx`) &&
3685
+ !added.includes(p.id) &&
3686
+ !refreshed.includes(p.id) &&
3687
+ !rewrote.includes(p.id) &&
3688
+ fs.existsSync(path.join(at.dir, `${p.file}.tsx`)) &&
3689
+ fs.readFileSync(path.join(at.dir, `${p.file}.tsx`), 'utf8') !==
3690
+ writes.get(`${p.file}.tsx`)?.text
3691
+ )
3692
+ refreshed.push(p.id);
3308
3693
  await buildWorn(cwd, theme, options, notes);
3309
3694
  commitPreview(
3310
3695
  cwd,
@@ -3328,6 +3713,20 @@ async function addPreview(description, options, box) {
3328
3713
  const worn = data.theme;
3329
3714
  if (worn)
3330
3715
  await themeLocked(options, worn, () => recordPreview(cwd, worn, at.dir));
3716
+ if (again)
3717
+ notes.push(
3718
+ `a default page's id brings back the default pages that are missing, as ${PREVIEW} add does`,
3719
+ );
3720
+ notes.push(...typeScriptNotes(cwd, at.dir, added));
3721
+ if (
3722
+ askedId === COLORS_PAGE.id &&
3723
+ !data.pages.some(p => p.id === COLORS_PAGE.id)
3724
+ )
3725
+ notes.push(
3726
+ data.theme
3727
+ ? `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>`
3728
+ : `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>`,
3729
+ );
3331
3730
  return {
3332
3731
  type: 'themeEdit.previewAdd',
3333
3732
  data: {
@@ -3434,7 +3833,12 @@ export async function themeEditPreviewApp(dir, options = {}) {
3434
3833
  })) {
3435
3834
  const sub = path.join(rel, entry.name);
3436
3835
  if (entry.isDirectory()) copyDir(sub);
3437
- else if (entry.isFile() && !(rel === '' && skip.has(entry.name)))
3836
+ else if (
3837
+ entry.isFile() &&
3838
+ !(rel === '' && skip.has(entry.name)) &&
3839
+ // A temp file a stopped command left is no part of the theme.
3840
+ !isEditorTemp(entry.name)
3841
+ )
3438
3842
  themeCopy.push({
3439
3843
  rel: path.join(to.dir, sub),
3440
3844
  text: fs.readFileSync(path.join(from.dir, sub)),
@@ -3458,7 +3862,11 @@ export async function themeEditPreviewApp(dir, options = {}) {
3458
3862
  routeTheme = {
3459
3863
  name: slug,
3460
3864
  module: fromRoute(to.js),
3461
- css: [fromRoute(to.css), ...fonts.map(x => `${x.pkg}/index.css`)],
3865
+ css: [
3866
+ fromRoute(to.css),
3867
+ ...baseFontsCss(ctx, theme),
3868
+ ...fonts.map(x => `${x.pkg}/index.css`),
3869
+ ],
3462
3870
  mode: themeImports(ctx, slug, theme, path.join(cwd, routeDir)).mode,
3463
3871
  };
3464
3872
  // The app's theme folder sits where this project's does, so the Colors
@@ -3611,6 +4019,20 @@ export async function themeEditPreviewList(options = {}) {
3611
4019
  const themeMissing = Boolean(
3612
4020
  data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir),
3613
4021
  );
4022
+ if (at && fs.existsSync(path.join(at.dir, PENDING)))
4023
+ notes.push(
4024
+ `a preview change was stopped part way, so this list may be out of date; ${PREVIEW} add${pf} finishes it`,
4025
+ );
4026
+ // A page whose file is gone breaks the route, which still imports it.
4027
+ const missing = new Set(
4028
+ (data?.pages ?? [])
4029
+ .filter(p => at && !fs.existsSync(path.join(at.dir, `${p.file}.tsx`)))
4030
+ .map(p => p.id),
4031
+ );
4032
+ if (at && missing.size)
4033
+ notes.push(
4034
+ `${[...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`,
4035
+ );
3614
4036
  if (data?.theme && themeMissing) {
3615
4037
  const themes = editedThemes(cwd);
3616
4038
  notes.push(
@@ -3623,7 +4045,11 @@ export async function themeEditPreviewList(options = {}) {
3623
4045
  folder: at && data ? shownDir(cwd, at.dir) : null,
3624
4046
  theme: data?.theme ?? null,
3625
4047
  themeMissing,
3626
- pages: (data?.pages ?? []).map(x => ({id: x.id, label: x.label})),
4048
+ pages: (data?.pages ?? []).map(x => ({
4049
+ id: x.id,
4050
+ label: x.label,
4051
+ ...(missing.has(x.id) ? {missing: true} : {}),
4052
+ })),
3627
4053
  notes,
3628
4054
  },
3629
4055
  };
@@ -3658,9 +4084,29 @@ async function removePreview(page, options, box) {
3658
4084
  const retry = (/** @type {string | null} */ p) =>
3659
4085
  `${PREVIEW} remove${page != null ? ` ${quoteCommandArgument(page)}` : ''}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
3660
4086
  const at = previewDir(cwd, options.path, {retry});
4087
+ // The pages a stopped change was removing, read before it is finished.
4088
+ /** @type {string[]} */
4089
+ let removing = [];
4090
+ try {
4091
+ const pend = JSON.parse(
4092
+ fs.readFileSync(path.join(at.dir, PENDING), 'utf8'),
4093
+ );
4094
+ const ids = (/** @type {any} */ r) =>
4095
+ Array.isArray(r?.pages)
4096
+ ? r.pages.map((/** @type {any} */ x) => String(x?.id))
4097
+ : [];
4098
+ const after = ids(pend?.record);
4099
+ removing = ids(pend?.old).filter(
4100
+ (/** @type {string} */ id) => !after.includes(id),
4101
+ );
4102
+ } catch {
4103
+ // No stopped change, or a damaged one.
4104
+ }
3661
4105
  const recovered = recoverPreview(cwd, at.dir);
3662
4106
  box.note = recovered;
3663
- const data = readPreview(cwd, at.dir, pf);
4107
+ /** @type {string[]} */
4108
+ const dropped = [];
4109
+ const data = readPreview(cwd, at.dir, pf, {dropped});
3664
4110
  if (!data) {
3665
4111
  // A folder that holds the app takes no preview: the way on is the
3666
4112
  // preview elsewhere, or a new one in its own folder.
@@ -3692,11 +4138,15 @@ async function removePreview(page, options, box) {
3692
4138
  // theme-preview.json is a file anyone can edit: every path in it must
3693
4139
  // stay in the route folder before anything is removed.
3694
4140
  const inside = (/** @type {string} */ rel) =>
3695
- confined(path.join(at.dir, rel), at.dir, `${PREVIEW_DATA} names`);
4141
+ confined(path.join(at.dir, rel), at.dir, PREVIEW_DATA, {cwd, pf});
3696
4142
  for (const rel of data.files) inside(rel);
3697
4143
  for (const p of data.pages) inside(`${p.file}.tsx`);
3698
4144
  /** @type {string[]} */
3699
4145
  const notes = recovered ? [recovered] : [];
4146
+ if (dropped.length)
4147
+ notes.push(
4148
+ `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`,
4149
+ );
3700
4150
  /** @type {string[]} */
3701
4151
  const kept = [];
3702
4152
  /** @type {string[]} */
@@ -3709,6 +4159,28 @@ async function removePreview(page, options, box) {
3709
4159
  one =
3710
4160
  data.pages.find(x => x.id === key) ??
3711
4161
  data.pages.find(x => x.id.toLowerCase() === key.toLowerCase());
4162
+ // The same remove run again after it was stopped: the change just
4163
+ // finished removed the page.
4164
+ if (
4165
+ !one &&
4166
+ recovered &&
4167
+ removing.some(id => id.toLowerCase() === key.toLowerCase())
4168
+ )
4169
+ return {
4170
+ type: 'themeEdit.previewRemove',
4171
+ data: {
4172
+ folder,
4173
+ removed: [],
4174
+ kept: [],
4175
+ missing: [],
4176
+ rewritten: [],
4177
+ notes: [
4178
+ ...notes,
4179
+ `${key} is no longer in the preview: the change that was stopped removed it`,
4180
+ ],
4181
+ pages: data.pages.map(x => x.id),
4182
+ },
4183
+ };
3712
4184
  if (!one)
3713
4185
  refuse(E.ERR_NOT_FOUND, `The preview has no page "${page}".`, {
3714
4186
  didYouMean: nearest(
@@ -3733,12 +4205,19 @@ async function removePreview(page, options, box) {
3733
4205
  `${name} was not written by the preview, so it is kept; only its nav item is gone`,
3734
4206
  );
3735
4207
  } else if (!fs.existsSync(inside(rel))) missing.push(name);
3736
- else if (verdict !== 'delete') {
4208
+ else if (unreadable(inside(rel))) {
4209
+ kept.push(name);
4210
+ notes.push(
4211
+ `${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`,
4212
+ );
4213
+ } else if (verdict !== 'delete') {
3737
4214
  kept.push(name);
3738
4215
  notes.push(keptNote(name, verdict));
3739
4216
  } else deletes.push(rel);
3740
4217
  data.pages = data.pages.filter(x => x !== target);
3741
- data.files = data.files.filter(f => f !== rel);
4218
+ // A file left in place because it could not be read stays recorded.
4219
+ if (!unreadable(inside(rel)))
4220
+ data.files = data.files.filter(f => f !== rel);
3742
4221
  const wore = data.theme;
3743
4222
  /** @type {string | null} */
3744
4223
  let gone = null;
@@ -3885,6 +4364,14 @@ async function removePreview(page, options, box) {
3885
4364
  );
3886
4365
  continue;
3887
4366
  }
4367
+ const cannot = unreadable(file);
4368
+ if (cannot) {
4369
+ kept.push(shown(cwd, file));
4370
+ notes.push(
4371
+ `${shown(cwd, file)} could not be read (${cannot}), so it is left in place; fix its permissions, then run ${PREVIEW} remove${pf} again`,
4372
+ );
4373
+ continue;
4374
+ }
3888
4375
  plan.push({file, before: fs.readFileSync(file)});
3889
4376
  }
3890
4377
  // theme-preview.json goes last, so an interrupted remove can run again.