@astryxdesign/cli 0.7.15-canary.gf890983 → 0.7.15

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 (115) hide show
  1. package/CHANGELOG.md +353 -3
  2. package/api/doctor/_adapter.d.mts +2 -1
  3. package/api/doctor/_adapter.mjs +6 -1
  4. package/api/doctor/doctor.mjs +2 -2
  5. package/api/doctor/theme-checks.mjs +56 -21
  6. package/api/integration/add-helpers.mjs +5 -0
  7. package/api/integration/add-theme.mjs +15 -110
  8. package/api/theme/_adapter.d.mts +37 -5
  9. package/api/theme/_adapter.mjs +363 -50
  10. package/api/theme/_fork.d.mts +90 -0
  11. package/api/theme/_fork.mjs +246 -0
  12. package/api/theme/build/build.d.mts +25 -1
  13. package/api/theme/build/build.mjs +352 -41
  14. package/api/theme/eject/eject.mjs +36 -15
  15. package/api/theme/list/list.mjs +3 -6
  16. package/api/theme/palette/generate/generator.d.mts +13 -0
  17. package/api/theme/palette/generate/generator.mjs +32 -2
  18. package/api/theme/targets/targets.mjs +10 -3
  19. package/api/theme/template/template.mjs +48 -2
  20. package/api/theme/theme.type.d.mts +8 -0
  21. package/api/theme/theme.type.mjs +5 -1
  22. package/api/theme/themeBuild.doc.mjs +2 -2
  23. package/api/theme/themeRemove.doc.mjs +5 -2
  24. package/api/theme/themeTemplate.doc.mjs +2 -2
  25. package/api/theme/themeUse.doc.mjs +8 -2
  26. package/api/theme-edit/_adapter.mjs +157 -36
  27. package/api/theme-edit/_catalog.d.mts +1 -6
  28. package/api/theme-edit/_catalog.mjs +5 -268
  29. package/api/theme-edit/_check.d.mts +3 -1
  30. package/api/theme-edit/_check.mjs +733 -308
  31. package/api/theme-edit/_color.d.mts +19 -0
  32. package/api/theme-edit/_color.mjs +277 -33
  33. package/api/theme-edit/_compiler.d.mts +1 -0
  34. package/api/theme-edit/_compiler.mjs +25 -0
  35. package/api/theme-edit/_context.d.mts +2 -0
  36. package/api/theme-edit/_context.mjs +83 -9
  37. package/api/theme-edit/_css.d.mts +84 -0
  38. package/api/theme-edit/_css.mjs +700 -0
  39. package/api/theme-edit/_edit.mjs +370 -85
  40. package/api/theme-edit/_how-commands.d.mts +5 -0
  41. package/api/theme-edit/_how-commands.mjs +20 -13
  42. package/api/theme-edit/_how-question.d.mts +29 -0
  43. package/api/theme-edit/_how-question.mjs +1573 -182
  44. package/api/theme-edit/_how.mjs +306 -22
  45. package/api/theme-edit/_overview.mjs +2 -7
  46. package/api/theme-edit/_palette.d.mts +27 -5
  47. package/api/theme-edit/_palette.mjs +231 -97
  48. package/api/theme-edit/_parts.d.mts +42 -10
  49. package/api/theme-edit/_parts.mjs +224 -69
  50. package/api/theme-edit/_preview-app.d.mts +8 -0
  51. package/api/theme-edit/_preview-app.mjs +549 -96
  52. package/api/theme-edit/_preview.d.mts +7 -16
  53. package/api/theme-edit/_preview.mjs +77 -84
  54. package/api/theme-edit/_project.d.mts +20 -1
  55. package/api/theme-edit/_project.mjs +43 -13
  56. package/api/theme-edit/_settings.d.mts +96 -20
  57. package/api/theme-edit/_settings.mjs +646 -141
  58. package/api/theme-edit/_tables.d.mts +18 -12
  59. package/api/theme-edit/_tables.mjs +144 -147
  60. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  61. package/api/theme-edit/theme-edit.type.mjs +3 -1
  62. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  63. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  64. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  65. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  66. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  67. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  68. package/assets/docs/tree/publishing.doc.mjs +1 -0
  69. package/assets/docs.generated.json +2 -2
  70. package/assets/self-audit.generated.json +1 -1
  71. package/clients/cli/build-id.generated.json +1 -1
  72. package/clients/cli/commands/experimental/index.mjs +10 -10
  73. package/clients/cli/commands/experimental/theme.mjs +22 -3
  74. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  75. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  76. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  77. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  78. package/clients/cli/commands/integration.mjs +8 -0
  79. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  80. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  81. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  82. package/clients/cli/commands/theme.mjs +325 -48
  83. package/clients/cli/index.mjs +18 -3
  84. package/clients/cli/lib/cli-error.mjs +118 -3
  85. package/clients/cli/manifest.generated.json +1 -1
  86. package/foundation/config/project.mjs +34 -8
  87. package/foundation/config/theme-state.d.mts +16 -0
  88. package/foundation/config/theme-state.mjs +84 -13
  89. package/foundation/discovery/template-needs.d.mts +13 -0
  90. package/foundation/discovery/template-needs.mjs +30 -15
  91. package/foundation/discovery/theme-discovery.mjs +14 -2
  92. package/foundation/discovery/theme-imports.d.mts +16 -0
  93. package/foundation/discovery/theme-imports.mjs +30 -2
  94. package/foundation/doc-compiler/import.mjs +10 -4
  95. package/foundation/fs/gather-cache.mjs +82 -23
  96. package/foundation/fs/jiti-cache.d.mts +21 -0
  97. package/foundation/fs/jiti-cache.mjs +66 -0
  98. package/foundation/fs/module-loader.mjs +7 -2
  99. package/foundation/integrations/autolink.d.mts +1 -24
  100. package/foundation/integrations/autolink.mjs +7 -60
  101. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  102. package/foundation/integrations/declared-dependencies.mjs +73 -0
  103. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  104. package/foundation/integrations/may-have-integrations.mjs +47 -0
  105. package/foundation/release/cache.d.mts +21 -2
  106. package/foundation/release/cache.mjs +48 -8
  107. package/foundation/release/folder-lock.d.mts +7 -0
  108. package/foundation/release/folder-lock.mjs +60 -26
  109. package/foundation/release/lock-lease.d.mts +2 -1
  110. package/foundation/release/lock-lease.mjs +7 -2
  111. package/foundation/response/error-codes.doc.mjs +1 -1
  112. package/foundation/response/response-types.doc.mjs +4 -4
  113. package/package.json +6 -6
  114. package/api/theme-edit/_css-properties.d.mts +0 -10
  115. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -23,6 +23,7 @@ import {Project} from '../../foundation/config/project.mjs';
23
23
  import {
24
24
  BUNDLED_THEME_PACKAGE,
25
25
  THEMES_DIR,
26
+ THEME_SLUG_RE,
26
27
  discoverBundledThemes,
27
28
  discoverIntegrationThemes,
28
29
  discoverUnmigratedThemeCopies,
@@ -51,8 +52,13 @@ import {stripCopyrightHeader} from '../../foundation/text/copyright-header.mjs';
51
52
  import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';
52
53
  import {importThemeArtifact} from '../../foundation/fs/module-loader.mjs';
53
54
  import {applyWrites} from '../integration/add-helpers.mjs';
54
- import {formatCliCommand} from '../../foundation/env/package-manager.mjs';
55
+ import {forkFileNames, renamedEntry} from './_fork.mjs';
56
+ import {
57
+ formatCliCommand,
58
+ quoteCommandArgument,
59
+ } from '../../foundation/env/package-manager.mjs';
55
60
  import {fsErrorMessage} from '../../foundation/fs/fs-error.mjs';
61
+ import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
56
62
  import {analyzeTemplateNeeds} from '../../foundation/discovery/template-needs.mjs';
57
63
 
58
64
  export {BUNDLED_THEME_PACKAGE, THEMES_DIR};
@@ -65,6 +71,20 @@ export function themeRecordOwner(theme) {
65
71
  return themeImportPackage(theme);
66
72
  }
67
73
 
74
+ /**
75
+ * Whether `--package <name>` selects a theme. It takes either name the CLI
76
+ * shows for it: the package that provides it (`@astryxdesign/cli` for a
77
+ * bundled theme) or the package the app imports it from, which the record
78
+ * holds (`@astryxdesign/theme-butter`).
79
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
80
+ * @param {string | undefined} name
81
+ */
82
+ export function themeInPackage(theme, name) {
83
+ return (
84
+ name == null || theme.package === name || themeImportPackage(theme) === name
85
+ );
86
+ }
87
+
68
88
  /**
69
89
  * A bundled theme entry kept for the historical public `listThemes()` helper.
70
90
  * @typedef {Pick<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme, 'slug' | 'displayName' | 'description' | 'maintained' | 'entry' | 'exportName' | 'files'>} BundledTheme
@@ -168,11 +188,60 @@ const skippedLocalThemesOf = new WeakMap();
168
188
  function brokenLocalThemeError(broken) {
169
189
  return new AstryxError(
170
190
  `Local theme "${broken.slug}" in ${broken.path} is broken: ${broken.reason}`,
171
- undefined,
191
+ [
192
+ {
193
+ name: formatCliCommand('theme list'),
194
+ reason: 'the themes that load, and the broken folders it skips',
195
+ },
196
+ ],
172
197
  ERROR_CODES.ERR_THEME_INVALID,
173
198
  );
174
199
  }
175
200
 
201
+ /**
202
+ * A slug that is not in the app's record. When a theme by that name is
203
+ * available, the refusal names `theme add`; otherwise `theme list`, since
204
+ * adding it would fail too.
205
+ * @param {string} slug
206
+ * @param {{projectDir: string}} state
207
+ */
208
+ async function notAddedError(slug, state) {
209
+ let match;
210
+ try {
211
+ match = await findTheme(slug, {cwd: state.projectDir});
212
+ } catch (error) {
213
+ // More than one package provides the slug: adding it names one.
214
+ if (
215
+ error instanceof AstryxError &&
216
+ error.code === ERROR_CODES.ERR_AMBIGUOUS_THEME
217
+ ) {
218
+ return new AstryxError(
219
+ `Theme "${slug}" is not added, and more than one package provides it. Add it from one of them with --package first.`,
220
+ error.suggestions,
221
+ ERROR_CODES.ERR_UNKNOWN_THEME,
222
+ );
223
+ }
224
+ throw error;
225
+ }
226
+ const list = {
227
+ name: formatCliCommand('theme list', state.projectDir),
228
+ reason: 'the themes you can add',
229
+ };
230
+ if (!match) {
231
+ return new AstryxError(
232
+ `Theme "${slug}" is not added, and no theme by that name is available. Run \`${list.name}\` for the themes you can add.`,
233
+ [list],
234
+ ERROR_CODES.ERR_UNKNOWN_THEME,
235
+ );
236
+ }
237
+ const add = formatCliCommand(`theme add ${match.slug}`, state.projectDir);
238
+ return new AstryxError(
239
+ `Theme "${slug}" is not added. Run \`${add}\` first.`,
240
+ [{name: add, reason: 'add it to the app'}],
241
+ ERROR_CODES.ERR_UNKNOWN_THEME,
242
+ );
243
+ }
244
+
176
245
  /** @param {unknown} error */
177
246
  function isMissingThemeArtifact(error) {
178
247
  return (
@@ -381,12 +450,14 @@ function scaffoldContents(bytes) {
381
450
  /**
382
451
  * Describe an ejected theme as a new, unmaintained local fork.
383
452
  * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
453
+ * @param {string} [name] the fork's name: the folder it takes in the local
454
+ * themes root, which discovery reads as the theme's name
384
455
  */
385
- function localThemeDescriptor(theme) {
456
+ function localThemeDescriptor(theme, name = theme.slug) {
386
457
  return `/** @type {import('@astryxdesign/cli/authoring').ThemeDoc} */
387
458
  export default {
388
459
  type: 'theme',
389
- name: ${JSON.stringify(theme.slug)},
460
+ name: ${JSON.stringify(name)},
390
461
  displayName: ${JSON.stringify(theme.displayName)},
391
462
  description: ${JSON.stringify(theme.description)},
392
463
  maintained: false,
@@ -404,8 +475,9 @@ export default {
404
475
  * @param {string} dir
405
476
  * @param {string} cwd
406
477
  * @param {string} projectDir the project root the default target is in
478
+ * @param {string[]} [forkNames] the fork's own file names, when they differ
407
479
  */
408
- function assertEjectTargetFree(theme, dir, cwd, projectDir) {
480
+ function assertEjectTargetFree(theme, dir, cwd, projectDir, forkNames = []) {
409
481
  /** @type {string[]} */
410
482
  let entries;
411
483
  try {
@@ -434,7 +506,9 @@ function assertEjectTargetFree(theme, dir, cwd, projectDir) {
434
506
  ERROR_CODES.ERR_FILE_EXISTS,
435
507
  );
436
508
  }
437
- const ownFiles = new Set(theme.files.map(name => path.basename(name)));
509
+ const ownFiles = new Set(
510
+ [...theme.files, ...forkNames].map(name => path.basename(name)),
511
+ );
438
512
  for (const name of entries) {
439
513
  const otherDescriptor =
440
514
  name.endsWith('.doc.mjs') && !ownFiles.has(name)
@@ -442,7 +516,13 @@ function assertEjectTargetFree(theme, dir, cwd, projectDir) {
442
516
  : null;
443
517
  const otherEntry =
444
518
  /Theme\.(?:ts|tsx|mts)$/.test(name) && !ownFiles.has(name);
445
- if ((otherDescriptor && otherDescriptor !== theme.slug) || otherEntry) {
519
+ // A fork in the local themes root carries its folder's name.
520
+ if (
521
+ (otherDescriptor &&
522
+ otherDescriptor !== theme.slug &&
523
+ otherDescriptor !== path.basename(dir)) ||
524
+ otherEntry
525
+ ) {
446
526
  throw new AstryxError(
447
527
  `${rel} holds another theme (${name}). Eject does not mix two themes in one folder, even with --overwrite.`,
448
528
  suggestion,
@@ -452,6 +532,98 @@ function assertEjectTargetFree(theme, dir, cwd, projectDir) {
452
532
  }
453
533
  }
454
534
 
535
+ /**
536
+ * Refuse a fork target that `theme list` and `theme add` would then misread:
537
+ * the local themes folder itself, where every theme has its own folder, or a
538
+ * folder in it named after another theme the project can use.
539
+ * @param {string} slug
540
+ * @param {string} dir absolute target
541
+ * @param {string} projectDir
542
+ * @param {string} cwd
543
+ * @param {Set<string>} takenSlugs the slugs of the themes the project can use
544
+ * @param {boolean} [sameFork] whether the folder holds no fork or a fork of
545
+ * this theme
546
+ */
547
+ function assertEjectTargetPlace(
548
+ slug,
549
+ dir,
550
+ projectDir,
551
+ cwd,
552
+ takenSlugs,
553
+ sameFork = true,
554
+ ) {
555
+ const themesRoot = path.resolve(projectDir, LOCAL_THEME_ROOT);
556
+ const resolved = path.resolve(dir);
557
+ const own = defaultEjectTarget(slug).split(path.sep).join('/');
558
+ const suggestion = [
559
+ {
560
+ name: formatCliCommand(`theme eject ${slug}`, cwd),
561
+ reason: `fork into ${own}`,
562
+ },
563
+ ];
564
+ if (resolved === themesRoot) {
565
+ throw new AstryxError(
566
+ `${path.relative(cwd, dir) || '.'} is the folder that holds the local themes, each in its own folder. Fork ${slug} into ${own}.`,
567
+ suggestion,
568
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
569
+ );
570
+ }
571
+ // A fork may take a new name; only another theme's name is refused.
572
+ const name = path.basename(resolved);
573
+ // The theme of that name may be the one in this very folder (a re-fork,
574
+ // which the folder checks decide).
575
+ const ownFolder = () => {
576
+ try {
577
+ return fs
578
+ .readdirSync(resolved)
579
+ .some(
580
+ file =>
581
+ file.endsWith('.doc.mjs') &&
582
+ themeDescriptorName(path.join(resolved, file)) === name,
583
+ );
584
+ } catch {
585
+ return false;
586
+ }
587
+ };
588
+ if (
589
+ path.dirname(resolved) === themesRoot &&
590
+ name !== slug &&
591
+ takenSlugs.has(name) &&
592
+ !(sameFork && ownFolder())
593
+ ) {
594
+ throw new AstryxError(
595
+ `${path.relative(cwd, dir)} is named after the theme ${name}, and a local theme's folder carries its name. Fork ${slug} into ${own}, or into a folder with a new name.`,
596
+ suggestion,
597
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
598
+ );
599
+ }
600
+ }
601
+
602
+ /**
603
+ * Whether a folder holds no fork, or a fork of `theme`: its descriptor
604
+ * carries the theme's display name, as eject writes it.
605
+ * @param {string} dir
606
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
607
+ */
608
+ function holdsForkOf(dir, theme) {
609
+ let docs;
610
+ try {
611
+ docs = fs.readdirSync(dir).filter(file => file.endsWith('.doc.mjs'));
612
+ } catch {
613
+ return true;
614
+ }
615
+ return docs.every(file => {
616
+ try {
617
+ const text = fs.readFileSync(path.join(dir, file), 'utf-8');
618
+ return (
619
+ /\bdisplayName:\s*(['"])(.*?)\1/.exec(text)?.[2] === theme.displayName
620
+ );
621
+ } catch {
622
+ return false;
623
+ }
624
+ });
625
+ }
626
+
455
627
  /**
456
628
  * The `name` of a theme descriptor, read as text so a broken file cannot run.
457
629
  * @param {string} file
@@ -470,14 +642,23 @@ function themeDescriptorName(file) {
470
642
  /**
471
643
  * Publish one theme's complete source inventory as an atomic local fork.
472
644
  * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
473
- * @param {{cwd: string, targetPath?: string, overwrite?: boolean}} options
474
- * @returns {string} project-relative output directory
645
+ * @param {{cwd: string, targetPath?: string, overwrite?: boolean, takenSlugs?: Set<string>}} options
646
+ * `takenSlugs`: the slugs of the themes the project can use, which a fork's
647
+ * new folder name may not take
648
+ * @returns {{outputDir: string, files: string[]}} the project-relative output
649
+ * directory and the files written, named as the fork names them
475
650
  */
476
- export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
651
+ export function ejectThemeFiles(
652
+ theme,
653
+ {cwd, targetPath: typedPath, overwrite = false, takenSlugs = new Set()},
654
+ ) {
477
655
  // The fork lands in the project, as list and add read it: the default root
478
656
  // is the project's, and a relative [path] is read from the working folder
479
657
  // but must stay inside the project.
480
658
  const projectDir = findPackageRoot(cwd) ?? path.resolve(cwd);
659
+ // A Windows-style path names the same folders on every platform, as
660
+ // compile reads it; a folder name with a backslash in it is never meant.
661
+ const targetPath = typedPath?.replace(/\\/g, '/');
481
662
  const target = !targetPath
482
663
  ? defaultEjectTarget(theme.slug)
483
664
  : path.isAbsolute(targetPath)
@@ -494,20 +675,45 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
494
675
  targetPath
495
676
  ? error.message.replace(`"${target}"`, `"${targetPath}"`)
496
677
  : error.message,
497
- undefined,
678
+ [
679
+ {
680
+ name: formatCliCommand(`theme eject ${theme.slug}`, cwd),
681
+ reason: `fork into ${defaultEjectTarget(theme.slug).split(path.sep).join('/')}`,
682
+ },
683
+ ],
498
684
  ERROR_CODES.ERR_PATH_TRAVERSAL,
499
685
  );
500
686
  }
501
687
  throw error;
502
688
  }
503
689
 
690
+ // A fork in the local themes root is named after its folder, as `theme
691
+ // list` and `theme add` read it; elsewhere it keeps the theme's name.
692
+ const inThemesRoot =
693
+ path.dirname(path.resolve(resolvedDir)) ===
694
+ path.resolve(projectDir, LOCAL_THEME_ROOT);
695
+ const forkName = inThemesRoot ? path.basename(resolvedDir) : theme.slug;
696
+ if (inThemesRoot && !THEME_SLUG_RE.test(forkName)) {
697
+ throw new AstryxError(
698
+ `A local theme's folder is its name, which is lowercase kebab-case starting with a letter; ${forkName} is not.`,
699
+ [
700
+ {
701
+ name: formatCliCommand(`theme eject ${theme.slug}`, cwd),
702
+ reason: `fork into ${defaultEjectTarget(theme.slug).split(path.sep).join('/')}`,
703
+ },
704
+ ],
705
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
706
+ );
707
+ }
708
+
709
+ const names = forkFileNames(theme, forkName);
504
710
  let writes;
505
711
  try {
506
- writes = theme.files.map(name => ({
507
- name,
508
- src: path.join(theme.sourceDir, name),
509
- dest: assertWithin(name, resolvedDir, {
510
- label: `theme destination for ${name}`,
712
+ writes = theme.files.map((src, index) => ({
713
+ name: names[index],
714
+ src: path.join(theme.sourceDir, src),
715
+ dest: assertWithin(names[index], resolvedDir, {
716
+ label: `theme destination for ${names[index]}`,
511
717
  }),
512
718
  }));
513
719
  } catch (error) {
@@ -532,8 +738,24 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
532
738
  }
533
739
  }
534
740
 
535
- assertEjectTargetFree(theme, resolvedDir, cwd, projectDir);
536
-
741
+ // The fork's own names count as its files only in a folder that holds
742
+ // no fork or a fork of this theme.
743
+ const sameFork = holdsForkOf(resolvedDir, theme);
744
+ assertEjectTargetFree(
745
+ theme,
746
+ resolvedDir,
747
+ cwd,
748
+ projectDir,
749
+ sameFork ? names : [],
750
+ );
751
+ assertEjectTargetPlace(
752
+ theme.slug,
753
+ resolvedDir,
754
+ projectDir,
755
+ cwd,
756
+ takenSlugs,
757
+ sameFork,
758
+ );
537
759
  if (!overwrite) {
538
760
  const existing = writes.find(write => fs.existsSync(write.dest));
539
761
  if (existing) {
@@ -541,12 +763,39 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
541
763
  throw new AstryxError(
542
764
  `Refusing to overwrite existing file ${rel}. ` +
543
765
  'Re-run with --overwrite (or -f) to replace it.',
544
- undefined,
766
+ [
767
+ {
768
+ name: formatCliCommand(
769
+ [
770
+ 'theme eject',
771
+ theme.slug,
772
+ ...(targetPath ? [quoteCommandArgument(targetPath)] : []),
773
+ ...(theme.source === 'bundled'
774
+ ? []
775
+ : ['--package', quoteCommandArgument(theme.package)]),
776
+ '--overwrite',
777
+ ].join(' '),
778
+ cwd,
779
+ ),
780
+ reason: 'replace the earlier fork of this theme',
781
+ },
782
+ ],
545
783
  ERROR_CODES.ERR_FILE_EXISTS,
546
784
  );
547
785
  }
548
786
  }
549
787
 
788
+ // A fork under another name renames its entry first, so an entry that
789
+ // names no theme is refused before any folder is made.
790
+ const entrySrc = path.resolve(theme.sourceDir, theme.files[0]);
791
+ const renamed =
792
+ forkName !== theme.slug
793
+ ? renamedEntry(
794
+ String(scaffoldContents(fs.readFileSync(entrySrc))),
795
+ theme,
796
+ forkName,
797
+ )
798
+ : null;
550
799
  try {
551
800
  fs.mkdirSync(resolvedDir, {recursive: true});
552
801
  const plans = writes.map(write => {
@@ -558,8 +807,10 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
558
807
  path: dest,
559
808
  contents:
560
809
  path.resolve(write.src) === path.resolve(theme.docPath)
561
- ? localThemeDescriptor(theme)
562
- : scaffoldContents(fs.readFileSync(write.src)),
810
+ ? localThemeDescriptor(theme, forkName)
811
+ : renamed != null && path.resolve(write.src) === entrySrc
812
+ ? renamed
813
+ : scaffoldContents(fs.readFileSync(write.src)),
563
814
  createOnly: !overwrite,
564
815
  };
565
816
  });
@@ -579,7 +830,7 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
579
830
  throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);
580
831
  }
581
832
 
582
- return path.relative(cwd, resolvedDir) || '.';
833
+ return {outputDir: path.relative(cwd, resolvedDir) || '.', files: names};
583
834
  }
584
835
 
585
836
  /**
@@ -617,7 +868,11 @@ function asThemeError(error) {
617
868
  message.startsWith('Refusing to replace')
618
869
  ? ERROR_CODES.ERR_FILE_EXISTS
619
870
  : ERROR_CODES.ERR_THEME_INVALID;
620
- return new AstryxError(message, undefined, code);
871
+ const suggestions =
872
+ error instanceof ThemeStateError || error instanceof ThemeImportError
873
+ ? error.suggestions
874
+ : undefined;
875
+ return new AstryxError(message, suggestions, code);
621
876
  }
622
877
 
623
878
  /**
@@ -625,7 +880,9 @@ function asThemeError(error) {
625
880
  * Without an explicit package, a local theme shadows package themes that share
626
881
  * its slug. Other duplicate slugs fail closed until the caller selects an owner.
627
882
  * @param {string} [slug]
628
- * @param {{cwd?: string, package?: string, includeLocal?: boolean}} [options]
883
+ * @param {{cwd?: string, package?: string, includeLocal?: boolean, command?: string}} [options]
884
+ * `command`: the command a refusal suggests running with `--package`,
885
+ * `theme add` by default
629
886
  * @returns {Promise<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme | undefined>}
630
887
  */
631
888
  export async function findTheme(slug, options = {}) {
@@ -638,7 +895,7 @@ export async function findTheme(slug, options = {}) {
638
895
  const matches = themes.filter(
639
896
  theme =>
640
897
  theme.slug.toLowerCase() === normalized &&
641
- (options.package == null || theme.package === options.package),
898
+ themeInPackage(theme, options.package),
642
899
  );
643
900
  const broken = skipped.find(entry => entry.slug.toLowerCase() === normalized);
644
901
  if (
@@ -668,7 +925,10 @@ export async function findTheme(slug, options = {}) {
668
925
  throw new AstryxError(
669
926
  `Theme "${slug}" is provided by more than one package. Select one with --package.`,
670
927
  matches.map(theme => ({
671
- name: `${theme.slug} --package ${theme.package}`,
928
+ name: formatCliCommand(
929
+ `${options.command ?? 'theme add'} ${theme.slug} --package ${quoteCommandArgument(theme.package)}`,
930
+ options.cwd ?? process.cwd(),
931
+ ),
672
932
  reason:
673
933
  theme.source === 'bundled'
674
934
  ? 'bundled theme'
@@ -682,6 +942,36 @@ export async function findTheme(slug, options = {}) {
682
942
  return matches[0];
683
943
  }
684
944
 
945
+ /**
946
+ * Runnable `<command> <slug>` suggestions for an unknown slug, closest names
947
+ * first; `--package` is named only where packages share a slug.
948
+ * @param {string} command such as `theme add`
949
+ * @param {string} slug what the person typed
950
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} available
951
+ * @param {string} cwd
952
+ * @returns {Array<{theme: import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme, name: string}>}
953
+ */
954
+ export function themeCommandsFor(command, slug, available, cwd) {
955
+ const needle = String(slug).toLowerCase();
956
+ const shared = (/** @type {string} */ other) =>
957
+ available.filter(theme => theme.slug === other).length > 1;
958
+ return [...available]
959
+ .sort(
960
+ (a, b) =>
961
+ levenshteinDistance(needle, a.slug.toLowerCase()) -
962
+ levenshteinDistance(needle, b.slug.toLowerCase()) ||
963
+ a.slug.localeCompare(b.slug),
964
+ )
965
+ .slice(0, 5)
966
+ .map(theme => ({
967
+ theme,
968
+ name: formatCliCommand(
969
+ `${command} ${theme.slug}${shared(theme.slug) ? ` --package ${quoteCommandArgument(theme.package)}` : ''}`,
970
+ cwd,
971
+ ),
972
+ }));
973
+ }
974
+
685
975
  /**
686
976
  * Read the generated module's app-theme record with stable CLI errors.
687
977
  * @param {string} [cwd]
@@ -741,7 +1031,12 @@ export function resolveRecordedThemes(state, available) {
741
1031
  if (!theme) {
742
1032
  throw new AstryxError(
743
1033
  `Added theme "${slug}" from ${owner} is unavailable. Reinstall the package or restore the local theme, or drop it with \`${formatCliCommand(`theme remove ${slug}`, state.projectDir)}\`.`,
744
- undefined,
1034
+ [
1035
+ {
1036
+ name: formatCliCommand(`theme remove ${slug}`, state.projectDir),
1037
+ reason: 'drop it from the app',
1038
+ },
1039
+ ],
745
1040
  ERROR_CODES.ERR_UNKNOWN_THEME,
746
1041
  );
747
1042
  }
@@ -996,15 +1291,17 @@ async function addThemeToAppLocked(slug, cwd, options) {
996
1291
  const available = await listAvailableThemes(cwd);
997
1292
  throw new AstryxError(
998
1293
  `Unknown theme "${slug}"${options.package ? ` in package "${options.package}"` : ''}.`,
999
- available.map(theme => ({
1000
- name: `${theme.slug} --package ${theme.package}`,
1001
- reason:
1002
- theme.source === 'bundled'
1003
- ? 'bundled theme'
1004
- : theme.source === 'local'
1005
- ? 'local theme'
1006
- : `provided by ${theme.package}`,
1007
- })),
1294
+ themeCommandsFor('theme add', slug, available, cwd).map(
1295
+ ({theme, name}) => ({
1296
+ name,
1297
+ reason:
1298
+ theme.source === 'bundled'
1299
+ ? 'bundled theme'
1300
+ : theme.source === 'local'
1301
+ ? 'local theme'
1302
+ : `provided by ${theme.package}`,
1303
+ }),
1304
+ ),
1008
1305
  ERROR_CODES.ERR_UNKNOWN_THEME,
1009
1306
  );
1010
1307
  }
@@ -1077,16 +1374,28 @@ async function removeThemeFromAppLocked(slug, cwd) {
1077
1374
  const state = readAppThemeState(cwd);
1078
1375
  const recordedSlug = recordedThemeSlug(state, slug);
1079
1376
  if (!state.configured || recordedSlug == null) {
1080
- throw new AstryxError(
1081
- `Theme "${slug}" is not added. Run \`${formatCliCommand(`theme add ${slug}`, state.projectDir)}\` first.`,
1082
- undefined,
1083
- ERROR_CODES.ERR_UNKNOWN_THEME,
1084
- );
1377
+ throw await notAddedError(slug, state);
1085
1378
  }
1086
1379
  if (state.defaultSlug === recordedSlug) {
1380
+ const others = Object.keys(state.themes).filter(
1381
+ other => other !== recordedSlug,
1382
+ );
1383
+ const uses = others.slice(0, 3).map(other => ({
1384
+ name: formatCliCommand(`theme use ${other}`, state.projectDir),
1385
+ reason: `make ${other} the default`,
1386
+ }));
1087
1387
  throw new AstryxError(
1088
- `Theme "${recordedSlug}" is the default. Run \`${formatCliCommand('theme use <other-slug>', state.projectDir)}\` before removing it.`,
1089
- undefined,
1388
+ uses.length > 0
1389
+ ? `Theme "${recordedSlug}" is the default. Run \`${uses[0].name}\` before removing it.`
1390
+ : `Theme "${recordedSlug}" is the default and the only added theme. Add another theme and make it the default before removing it.`,
1391
+ uses.length > 0
1392
+ ? uses
1393
+ : [
1394
+ {
1395
+ name: formatCliCommand('theme list', state.projectDir),
1396
+ reason: 'the themes you can add',
1397
+ },
1398
+ ],
1090
1399
  ERROR_CODES.ERR_THEME_INVALID,
1091
1400
  );
1092
1401
  }
@@ -1094,8 +1403,16 @@ async function removeThemeFromAppLocked(slug, cwd) {
1094
1403
  delete themes[recordedSlug];
1095
1404
  if (state.defaultSlug == null) {
1096
1405
  throw new AstryxError(
1097
- `The generated theme module has no default theme. Run \`${formatCliCommand('theme use <slug>', state.projectDir)}\` first.`,
1098
- undefined,
1406
+ `The generated theme module has no default theme. Run \`${formatCliCommand(`theme use ${Object.keys(themes)[0] ?? recordedSlug}`, state.projectDir)}\` first.`,
1407
+ [
1408
+ {
1409
+ name: formatCliCommand(
1410
+ `theme use ${Object.keys(themes)[0] ?? recordedSlug}`,
1411
+ state.projectDir,
1412
+ ),
1413
+ reason: 'choose a default',
1414
+ },
1415
+ ],
1099
1416
  ERROR_CODES.ERR_THEME_INVALID,
1100
1417
  );
1101
1418
  }
@@ -1127,11 +1444,7 @@ async function useThemeInAppLocked(slug, cwd) {
1127
1444
  const state = readAppThemeState(cwd);
1128
1445
  const recordedSlug = recordedThemeSlug(state, slug);
1129
1446
  if (!state.configured || recordedSlug == null) {
1130
- throw new AstryxError(
1131
- `Theme "${slug}" is not added. Run \`${formatCliCommand(`theme add ${slug}`, state.projectDir)}\` first.`,
1132
- undefined,
1133
- ERROR_CODES.ERR_UNKNOWN_THEME,
1134
- );
1447
+ throw await notAddedError(slug, state);
1135
1448
  }
1136
1449
  const available = await listAvailableThemes(state.projectDir);
1137
1450
  return writeThemeApp(