@astryxdesign/cli 0.7.14-canary.gfdb9213 → 0.7.14

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 (95) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/theme/_adapter.d.mts +33 -0
  3. package/api/theme/_adapter.mjs +352 -16
  4. package/api/theme/build/build.mjs +261 -10
  5. package/api/theme/eject/eject.mjs +13 -1
  6. package/api/theme/list/list.mjs +11 -2
  7. package/api/theme/template/template.mjs +139 -6
  8. package/api/theme/theme.type.d.mts +15 -1
  9. package/api/theme/theme.type.mjs +9 -3
  10. package/api/theme/themeAdd.doc.mjs +1 -1
  11. package/api/theme/themeBuild.doc.mjs +10 -2
  12. package/api/theme/themeEject.doc.mjs +2 -2
  13. package/api/theme/themeListAvailable.doc.mjs +1 -1
  14. package/api/theme/themeRemove.doc.mjs +1 -1
  15. package/api/theme/themeTemplate.doc.mjs +8 -0
  16. package/api/theme/themeUse.doc.mjs +1 -1
  17. package/api/theme-edit/_adapter.d.mts +10 -2
  18. package/api/theme-edit/_adapter.mjs +52 -31
  19. package/api/theme-edit/_check.d.mts +28 -25
  20. package/api/theme-edit/_check.mjs +586 -548
  21. package/api/theme-edit/_color.d.mts +28 -2
  22. package/api/theme-edit/_color.mjs +306 -68
  23. package/api/theme-edit/_compiler.d.mts +8 -4
  24. package/api/theme-edit/_compiler.mjs +30 -27
  25. package/api/theme-edit/_context.d.mts +10 -4
  26. package/api/theme-edit/_context.mjs +21 -4
  27. package/api/theme-edit/_edit.mjs +300 -43
  28. package/api/theme-edit/_how-commands.d.mts +91 -0
  29. package/api/theme-edit/_how-commands.mjs +269 -0
  30. package/api/theme-edit/_how-question.d.mts +57 -0
  31. package/api/theme-edit/_how-question.mjs +2574 -0
  32. package/api/theme-edit/_how.d.mts +25 -17
  33. package/api/theme-edit/_how.mjs +727 -305
  34. package/api/theme-edit/_palette.d.mts +127 -19
  35. package/api/theme-edit/_palette.mjs +1313 -399
  36. package/api/theme-edit/_parts.mjs +36 -3
  37. package/api/theme-edit/_png.d.mts +18 -6
  38. package/api/theme-edit/_png.mjs +135 -25
  39. package/api/theme-edit/_preview-app.d.mts +26 -7
  40. package/api/theme-edit/_preview-app.mjs +1611 -280
  41. package/api/theme-edit/_preview.d.mts +4 -2
  42. package/api/theme-edit/_preview.mjs +18 -7
  43. package/api/theme-edit/_settings.d.mts +56 -5
  44. package/api/theme-edit/_settings.mjs +197 -49
  45. package/api/theme-edit/_tables.d.mts +0 -12
  46. package/api/theme-edit/_tables.mjs +24 -97
  47. package/api/theme-edit/theme-edit.type.d.mts +22 -5
  48. package/api/theme-edit/theme-edit.type.mjs +17 -6
  49. package/api/theme-edit/themeEditHow.doc.mjs +13 -3
  50. package/api/theme-edit/themeEditNew.doc.mjs +2 -1
  51. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +16 -4
  52. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -4
  53. package/api/theme-edit/themeEditPreviewList.doc.mjs +9 -1
  54. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +27 -2
  55. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  56. package/assets/docs.generated.json +1 -0
  57. package/assets/preview-app/gitignore +3 -0
  58. package/assets/templates/components.generated.json +1 -0
  59. package/clients/cli/bin/astryx.mjs +37 -5
  60. package/clients/cli/commands/experimental/theme.mjs +231 -31
  61. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +14 -5
  62. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -1
  63. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  64. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  65. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -2
  66. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  67. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  68. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  69. package/clients/cli/commands/experimental-theme.doc.mjs +2 -2
  70. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  71. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  72. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  73. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  74. package/clients/cli/commands/theme.mjs +104 -40
  75. package/clients/cli/commands.generated.json +1 -0
  76. package/clients/cli/index.mjs +96 -4
  77. package/clients/cli/lib/json-shim.mjs +29 -1
  78. package/foundation/config/project.d.mts +16 -2
  79. package/foundation/config/project.mjs +40 -6
  80. package/foundation/config/theme-state.d.mts +9 -0
  81. package/foundation/config/theme-state.mjs +20 -1
  82. package/foundation/discovery/template-adapter.d.mts +12 -1
  83. package/foundation/discovery/template-adapter.mjs +24 -1
  84. package/foundation/discovery/template-needs.d.mts +7 -0
  85. package/foundation/discovery/template-needs.mjs +117 -8
  86. package/foundation/discovery/template-source-tree.d.mts +5 -1
  87. package/foundation/discovery/template-source-tree.mjs +6 -4
  88. package/foundation/discovery/theme-discovery.d.mts +14 -3
  89. package/foundation/discovery/theme-discovery.mjs +45 -12
  90. package/foundation/doc-compiler/import.mjs +68 -3
  91. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  92. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  93. package/foundation/fs/fs-error.d.mts +17 -0
  94. package/foundation/fs/fs-error.mjs +34 -0
  95. package/package.json +6 -6
@@ -775,6 +775,167 @@ function outsideCheckRemedy(writes, sources, root, args) {
775
775
  ];
776
776
  }
777
777
 
778
+ /** The first words of every file a build writes. */
779
+ const GENERATED_MARKER = '@generated by `astryx theme build`';
780
+
781
+ /** @param {string} file @returns {boolean} */
782
+ function isDirectorySync(file) {
783
+ try {
784
+ return fs.statSync(file).isDirectory();
785
+ } catch {
786
+ return false;
787
+ }
788
+ }
789
+
790
+ /** @param {string} file @returns {string} the start of a file, or '' when it cannot be read */
791
+ function fileHead(file) {
792
+ try {
793
+ const fd = fs.openSync(file, 'r');
794
+ try {
795
+ const head = Buffer.alloc(600);
796
+ const n = fs.readSync(fd, head, 0, head.length, 0);
797
+ return head.subarray(0, n).toString('utf-8');
798
+ } finally {
799
+ fs.closeSync(fd);
800
+ }
801
+ } catch {
802
+ return '';
803
+ }
804
+ }
805
+
806
+ /** @param {string} file @returns {string} one key per real location, whatever the spelling */
807
+ function outputKey(file) {
808
+ const resolved = realLocation(path.resolve(file));
809
+ return process.platform === 'win32' || process.platform === 'darwin'
810
+ ? resolved.toLowerCase()
811
+ : resolved;
812
+ }
813
+
814
+ /**
815
+ * Theme sources a folder holds, for a hint when a folder is passed.
816
+ * @param {string} dir
817
+ * @returns {string[]}
818
+ */
819
+ function themeFilesIn(dir) {
820
+ try {
821
+ return fs
822
+ .readdirSync(dir)
823
+ .filter(name => /(?:\.theme|Theme)\.(?:[cm]?[jt]sx?)$/.test(name))
824
+ .sort()
825
+ .slice(0, 3);
826
+ } catch {
827
+ return [];
828
+ }
829
+ }
830
+
831
+ /**
832
+ * Refuse a build that would replace a file it does not own. A build never
833
+ * writes over its input, two of its own outputs at one path, or an output
834
+ * another theme in the same run already wrote. With `refuseUnmarked`, it also
835
+ * replaces only its own earlier outputs (they carry the `@generated` header)
836
+ * and empty files, never another file such as `package.json` or app source.
837
+ * @param {Array<{dest: string}>} writes
838
+ * @param {string} filePath the theme source
839
+ * @param {string} cwd
840
+ * @param {{claimed?: Map<string, string>, rerun?: string, refuseUnmarked?: boolean, elsewhere?: string}} [options]
841
+ * `claimed`: outputs written earlier in this run, by the source that wrote
842
+ * them; `rerun`: this build's command, to run again once the file is gone;
843
+ * `elsewhere`: the option that moves the outputs
844
+ */
845
+ function assertOutputsReplaceable(
846
+ writes,
847
+ filePath,
848
+ cwd,
849
+ {claimed, rerun, refuseUnmarked = false, elsewhere = '--out'} = {},
850
+ ) {
851
+ const rel = (/** @type {string} */ file) => path.relative(cwd, file);
852
+ const sourceKey = outputKey(filePath);
853
+ const sourceHead = fileHead(filePath);
854
+ if (sourceHead.includes(GENERATED_MARKER)) {
855
+ const from = /Source: (.+)/.exec(sourceHead)?.[1]?.trim();
856
+ throw new AstryxError(
857
+ `${rel(filePath)} is an output of \`theme build\`, not a theme source.${from ? ` It was built from ${from}.` : ''}`,
858
+ from
859
+ ? [
860
+ {
861
+ name: formatCliCommand(`theme build ${shellWord(from)}`, cwd),
862
+ reason: 'build the theme source',
863
+ },
864
+ ]
865
+ : undefined,
866
+ ERROR_CODES.ERR_THEME_INVALID,
867
+ );
868
+ }
869
+ const seen = new Set();
870
+ for (const write of writes) {
871
+ const key = outputKey(write.dest);
872
+ if (key === sourceKey) {
873
+ throw new AstryxError(
874
+ `The output ${rel(write.dest)} is the theme source itself. Pick another --out.`,
875
+ [
876
+ {
877
+ name: formatCliCommand(
878
+ `theme build ${shellWord(rel(filePath))}`,
879
+ cwd,
880
+ ),
881
+ reason: 'write the outputs beside the source',
882
+ },
883
+ ],
884
+ ERROR_CODES.ERR_THEME_INVALID,
885
+ );
886
+ }
887
+ if (seen.has(key)) {
888
+ throw new AstryxError(
889
+ `Two outputs of this build have the same path, ${rel(write.dest)}. --out must name the .css file, not the theme's .js or .d.ts.`,
890
+ undefined,
891
+ ERROR_CODES.ERR_THEME_INVALID,
892
+ );
893
+ }
894
+ seen.add(key);
895
+ const earlier = claimed?.get(key);
896
+ if (earlier !== undefined) {
897
+ throw new AstryxError(
898
+ `${earlier} already wrote ${rel(write.dest)} in this run. Two themes build the same outputs; give each theme its own name.`,
899
+ undefined,
900
+ ERROR_CODES.ERR_THEME_INVALID,
901
+ );
902
+ }
903
+ let stat;
904
+ try {
905
+ stat = fs.statSync(write.dest);
906
+ } catch {
907
+ continue;
908
+ }
909
+ if (stat.isDirectory()) {
910
+ throw new AstryxError(
911
+ `The output ${rel(write.dest)} is a folder. Move the folder, or pick another ${elsewhere}.`,
912
+ undefined,
913
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
914
+ );
915
+ }
916
+ // Outputs from CLIs before 0.6.7 have no header, so they read as files
917
+ // the build did not write; only the user can say they may go.
918
+ if (
919
+ refuseUnmarked &&
920
+ stat.size > 0 &&
921
+ !fileHead(write.dest).includes(GENERATED_MARKER)
922
+ ) {
923
+ throw new AstryxError(
924
+ `${rel(write.dest)} was written by an older CLI (before 0.6.7) or by hand, so the build does not replace it. Delete that file and run the same build again, or pick another ${elsewhere}.`,
925
+ rerun
926
+ ? [
927
+ {
928
+ name: rerun,
929
+ reason: 'run the same build again once the file is deleted',
930
+ },
931
+ ]
932
+ : undefined,
933
+ ERROR_CODES.ERR_FILE_EXISTS,
934
+ );
935
+ }
936
+ }
937
+ }
938
+
778
939
  /** @param {Array<{dest: string, content: string}>} writes */
779
940
  function writeBuildOutputs(writes) {
780
941
  if (writes.length === 0) return;
@@ -1970,6 +2131,9 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
1970
2131
  loader ??
1971
2132
  createJiti(import.meta.url, {
1972
2133
  moduleCache: false,
2134
+ // No transpile cache: it is written to the system temp folder, named
2135
+ // for the theme, and never removed, so every edit added files there.
2136
+ fsCache: false,
1973
2137
  jsx: true,
1974
2138
  extensions: THEME_MODULE_EXTENSIONS,
1975
2139
  ...(interception ? {virtualModules: interception.modules} : {}),
@@ -2030,6 +2194,20 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
2030
2194
  if (isThemeObject(value)) return {theme: value, exportName, degraded};
2031
2195
  }
2032
2196
  }
2197
+ // The loader's interop answers a null default with the module itself, so
2198
+ // read the export as the module wrote it.
2199
+ const ownDefault = hasDefault
2200
+ ? Object.getOwnPropertyDescriptor(mod, 'default')?.value
2201
+ : undefined;
2202
+ if (
2203
+ hasDefault &&
2204
+ (ownDefault === null ||
2205
+ (typeof ownDefault !== 'object' && typeof ownDefault !== 'function'))
2206
+ ) {
2207
+ throw new ThemeShapeError(
2208
+ `The default export is ${ownDefault === null ? 'null' : `a ${typeof ownDefault}`}, not a theme object.`,
2209
+ );
2210
+ }
2033
2211
  // A plain-object default export is the module's theme even when it has
2034
2212
  // no tokens of its own (local tokens, typography or component styles may
2035
2213
  // be all it defines), or no name: the build's validation says what it
@@ -2048,9 +2226,8 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
2048
2226
  }
2049
2227
  }
2050
2228
 
2051
- throw new Error(
2052
- `Could not find a defineTheme() result in ${filePath}.\n` +
2053
- `Expected an export like: export const myTheme = defineTheme({ name: '...', tokens: {...} })`,
2229
+ throw new ThemeShapeError(
2230
+ `Could not find a defineTheme() result in ${filePath}.`,
2054
2231
  );
2055
2232
  }
2056
2233
 
@@ -2123,13 +2300,47 @@ async function extractThemeDefinition(filePath, interception, /** @type {any} */
2123
2300
  } catch (jitiError) {
2124
2301
  const je = /** @type {Error} */ (jitiError);
2125
2302
  throw new Error(
2126
- `Failed to load theme from ${filePath}: ${je.message}\n` +
2127
- `Make sure all imports in the theme file are resolvable.`,
2303
+ `Failed to load theme from ${filePath}: ${themeLoadReason(je)}`,
2128
2304
  {cause: jitiError},
2129
2305
  );
2130
2306
  }
2131
2307
  }
2132
2308
 
2309
+ /** Names a theme module's exports must take; ends a shape failure. */
2310
+ const THEME_EXPORT_FIX =
2311
+ "Export the theme object: `export default defineTheme({name: 'my-theme', tokens: {...}})`, or a plain `export default {name: 'my-theme', tokens: {...}}`.";
2312
+
2313
+ /**
2314
+ * Why a theme module did not load, with the step that fixes it. A module
2315
+ * whose default export is null or a primitive trips the loader's interop
2316
+ * before the build reads it; that is a theme shape failure, not an import one.
2317
+ * @param {Error} error
2318
+ * @returns {string}
2319
+ */
2320
+ function themeLoadReason(error) {
2321
+ const message = error.message;
2322
+ if (error instanceof ThemeShapeError)
2323
+ return `${message}\n${THEME_EXPORT_FIX}`;
2324
+ if (
2325
+ error instanceof TypeError &&
2326
+ /^Cannot read properties of (?:null|undefined)/.test(message) &&
2327
+ /jiti/.test(String(error.stack).split('\n')[1] ?? '')
2328
+ ) {
2329
+ return `its default export is null or not an object.\n${THEME_EXPORT_FIX}`;
2330
+ }
2331
+ const missing =
2332
+ /Cannot find (?:module|package) '((?:@[^/']+\/)?[^/'.][^/']*)/.exec(
2333
+ message,
2334
+ )?.[1];
2335
+ if (missing) {
2336
+ return `${message}\nThe theme imports ${missing}, which is not installed. Install it (for example \`npm install ${missing}\`), then build again.`;
2337
+ }
2338
+ return `${message}\nMake sure all imports in the theme file are resolvable.`;
2339
+ }
2340
+
2341
+ /** A theme module that loaded but exports no theme object. */
2342
+ class ThemeShapeError extends Error {}
2343
+
2133
2344
  /**
2134
2345
  * Load one theme through the build's real module loader and validate the raw
2135
2346
  * input captured from its defineTheme lineage. Used by doctor so it applies the
@@ -2945,9 +3156,10 @@ function validateHeadingTypeAugmentationSupport(themeDef) {
2945
3156
  * `logger` (silent by default).
2946
3157
  *
2947
3158
  * @param {string} file - Theme file path, resolved against `cwd`.
2948
- * @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any, __onPrivateVarError?: () => void, __writeRoot?: string}} [options] -
2949
- * `out` overrides the output CSS path; `check` compares against on-disk outputs
2950
- * instead of writing. `__writeRoot` replaces `cwd` as the directory every
3159
+ * @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any, __onPrivateVarError?: () => void, __writeRoot?: string, __claimedOutputs?: Map<string, string>}} [options] -
3160
+ * `out` overrides the output CSS path, or names the folder for it; `check` compares against on-disk outputs
3161
+ * instead of writing. `__claimedOutputs` records the outputs earlier builds
3162
+ * in one run wrote, so a later theme cannot replace them. `__writeRoot` replaces `cwd` as the directory every
2951
3163
  * output must stay inside, for a CLI-internal scratch build. `iconsSpecifier` overrides the icon registry import
2952
3164
  * specifier in the generated module (e.g. `./icons.mjs`); when omitted, the
2953
3165
  * direct registry specifiers from the theme source are emitted unchanged.
@@ -2971,6 +3183,20 @@ async function themeBuildInternal(
2971
3183
  );
2972
3184
  }
2973
3185
 
3186
+ if (fs.statSync(filePath).isDirectory()) {
3187
+ throw new AstryxError(
3188
+ `${path.relative(cwd, filePath) || '.'} is a folder. Pass the theme file inside it.`,
3189
+ themeFilesIn(filePath).map(name => ({
3190
+ name: formatCliCommand(
3191
+ `theme build ${shellWord(path.relative(cwd, path.join(filePath, name)).split(path.sep).join('/'))}`,
3192
+ cwd,
3193
+ ),
3194
+ reason: 'a theme source in that folder',
3195
+ })),
3196
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
3197
+ );
3198
+ }
3199
+
2974
3200
  if (!report.compact) {
2975
3201
  logger.log(`\nBuilding theme from ${path.relative(cwd, filePath)}...`);
2976
3202
  }
@@ -3488,6 +3714,11 @@ async function themeBuildInternal(
3488
3714
  let outPath;
3489
3715
  if (options.out) {
3490
3716
  outPath = path.resolve(cwd, options.out);
3717
+ // A folder, or a path that ends in a separator, names where the outputs
3718
+ // go: write `<folder>/<name>.css`, never a file named like the folder.
3719
+ if (/[\\/]$/.test(options.out) || isDirectorySync(outPath)) {
3720
+ outPath = path.join(outPath, `${baseName}.css`);
3721
+ }
3491
3722
  // A build keeps the explicit output inside the write root, relative or
3492
3723
  // absolute. Check mode writes nothing, so it refuses only a relative path
3493
3724
  // that escapes cwd.
@@ -3599,6 +3830,16 @@ async function themeBuildInternal(
3599
3830
  // outside cwd read-only.
3600
3831
  if (!options.check) {
3601
3832
  confineOutputs(writes, writeRoot, options.out ? OUT_REMEDY : SOURCE_REMEDY);
3833
+ // prettier-ignore
3834
+ const rerun = formatCliCommand(['theme', 'build', path.relative(cwd, filePath), ...(options.out ? ['--out', options.out] : []), ...(options.iconsSpecifier ? ['--icons-specifier', options.iconsSpecifier] : [])].map(shellWord).join(' '), cwd);
3835
+ // A header-less file at the default paths beside the source is an output
3836
+ // of a CLI before 0.6.7, which the build has always replaced. A path that
3837
+ // --out names may hold anything, so there only build outputs are replaced.
3838
+ assertOutputsReplaceable(writes, filePath, cwd, {
3839
+ claimed: options.__claimedOutputs,
3840
+ rerun,
3841
+ refuseUnmarked: Boolean(options.out),
3842
+ });
3602
3843
  }
3603
3844
 
3604
3845
  // Check mode: compare generated content against what's on disk instead of
@@ -3636,6 +3877,9 @@ async function themeBuildInternal(
3636
3877
  }
3637
3878
 
3638
3879
  writeBuildOutputs(writes);
3880
+ for (const write of writes) {
3881
+ options.__claimedOutputs?.set(outputKey(write.dest), sourceRelative);
3882
+ }
3639
3883
 
3640
3884
  if (!report.compact) {
3641
3885
  logger.log(`\n[ok] ${path.relative(cwd, outPath)}`);
@@ -4039,7 +4283,7 @@ export async function themeBuildFamily(
4039
4283
  await selectCore(cwd);
4040
4284
  const familyInterception = interceptCore(_coreThemeModule, _coreRootModule);
4041
4285
  // prettier-ignore
4042
- const familyLoader = createJiti(import.meta.url, {moduleCache: true, interopDefault: false, jsx: true, extensions: THEME_MODULE_EXTENSIONS, virtualModules: familyInterception.modules});
4286
+ const familyLoader = createJiti(import.meta.url, {moduleCache: true, fsCache: false, interopDefault: false, jsx: true, extensions: THEME_MODULE_EXTENSIONS, virtualModules: familyInterception.modules});
4043
4287
  /** @type {any[]} */
4044
4288
  const prepared = [];
4045
4289
  for (const source of planFamilySources(files, cwd)) {
@@ -4247,7 +4491,14 @@ export async function themeBuildFamily(
4247
4491
  dts: path.relative(cwd, dtsPath),
4248
4492
  };
4249
4493
  // A family build's outputs stay inside cwd too; check mode only reads them.
4250
- if (!options.check) confineOutputs(writes, cwd, FAMILY_REMEDY);
4494
+ if (!options.check) {
4495
+ confineOutputs(writes, cwd, FAMILY_REMEDY);
4496
+ // Family outputs always go to the family's default paths, where a
4497
+ // header-less file is an output of a CLI before 0.6.7: it is replaced.
4498
+ assertOutputsReplaceable(writes, root.filePath, cwd, {
4499
+ elsewhere: '--family-key',
4500
+ });
4501
+ }
4251
4502
  if (options.check) {
4252
4503
  const stale = staleBuildOutputs(writes, cwd);
4253
4504
  const upToDate = stale.length === 0;
@@ -7,7 +7,12 @@
7
7
 
8
8
  import {AstryxError} from '../../error.mjs';
9
9
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
10
- import {ejectThemeFiles, findTheme, listAvailableThemes} from '../_adapter.mjs';
10
+ import {
11
+ ejectThemeFiles,
12
+ findTheme,
13
+ forkNeeds,
14
+ listAvailableThemes,
15
+ } from '../_adapter.mjs';
11
16
 
12
17
  /**
13
18
  * Copy a bundled or installed theme's complete source inventory into the
@@ -49,6 +54,11 @@ export async function themeEject(slug, options = {}) {
49
54
  targetPath,
50
55
  overwrite,
51
56
  });
57
+ const {missingPackages, installCommand} = forkNeeds(
58
+ outputDir,
59
+ match.files,
60
+ cwd,
61
+ );
52
62
  return {
53
63
  type: 'theme.eject',
54
64
  data: {
@@ -60,6 +70,8 @@ export async function themeEject(slug, options = {}) {
60
70
  entry: match.entry,
61
71
  exportName: match.exportName,
62
72
  files: match.files,
73
+ missingPackages,
74
+ installCommand,
63
75
  },
64
76
  };
65
77
  }
@@ -11,6 +11,7 @@ import * as path from 'node:path';
11
11
 
12
12
  import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
13
13
  import {
14
+ listAvailableThemeState,
14
15
  listAvailableThemes,
15
16
  listThemes,
16
17
  listUnmigratedThemeCopies,
@@ -72,7 +73,7 @@ export async function themeListCopySources(options = {}) {
72
73
  export async function themeListAvailable(options = {}) {
73
74
  const cwd = options.cwd ?? process.cwd();
74
75
  const state = readThemeListState(cwd);
75
- const themes = await listAvailableThemes(cwd);
76
+ const {themes, skipped} = await listAvailableThemeState(cwd);
76
77
  const data = themes
77
78
  .filter(
78
79
  theme => options.package == null || theme.package === options.package,
@@ -106,9 +107,17 @@ export async function themeListAvailable(options = {}) {
106
107
  ),
107
108
  upgradeCommand,
108
109
  }));
110
+ const skippedThemes = options.package == null ? skipped : [];
109
111
  return {
110
112
  type: 'theme.list',
111
113
  data,
112
- ...(unmigratedCopies.length > 0 ? {meta: {unmigratedCopies}} : {}),
114
+ ...(unmigratedCopies.length > 0 || skippedThemes.length > 0
115
+ ? {
116
+ meta: {
117
+ unmigratedCopies,
118
+ ...(skippedThemes.length > 0 ? {skippedThemes} : {}),
119
+ },
120
+ }
121
+ : {}),
113
122
  };
114
123
  }
@@ -18,6 +18,9 @@ import * as path from 'node:path';
18
18
  import {CLI_ROOT} from '../../../foundation/fs/paths.mjs';
19
19
  import {assertWithin, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
20
20
  import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';
21
+ import {formatCliCommand} from '../../../foundation/env/package-manager.mjs';
22
+ import {fsErrorMessage} from '../../../foundation/fs/fs-error.mjs';
23
+ import {editorThemeRecord} from '../../../foundation/config/theme-state.mjs';
21
24
  import {AstryxError} from '../../error.mjs';
22
25
  import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
23
26
 
@@ -27,6 +30,38 @@ export const THEME_TEMPLATE_SRC = path.join(CLI_ROOT, 'assets', 'theme.template.
27
30
  /** Where it lands when the caller does not say. */
28
31
  export const THEME_TEMPLATE_DEFAULT_PATH = 'theme.template.ts';
29
32
 
33
+ /** The first words of the template; a file that holds them is a copy of it. */
34
+ const TEMPLATE_MARKER = 'Astryx theme template';
35
+
36
+ /** The template is TypeScript; any other extension gives a broken file. */
37
+ const TEMPLATE_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts']);
38
+
39
+ /** Names that theme sources use: `x.template.ts`, `x.theme.ts`, `xTheme.ts`. */
40
+ const THEME_SOURCE_NAME = /(?:\.template|\.theme|Theme)\.(?:ts|tsx|mts|cts)$/;
41
+
42
+ /**
43
+ * May `--overwrite` replace this existing file? Only a copy of the template,
44
+ * or a file named like a theme source. Anything else, such as `package.json`
45
+ * or an app route, is the user's work and is never replaced.
46
+ * @param {string} file
47
+ * @returns {boolean}
48
+ */
49
+ function isReplaceableThemeFile(file) {
50
+ if (THEME_SOURCE_NAME.test(path.basename(file))) return true;
51
+ try {
52
+ const fd = fs.openSync(file, 'r');
53
+ try {
54
+ const head = Buffer.alloc(512);
55
+ const n = fs.readSync(fd, head, 0, head.length, 0);
56
+ return head.subarray(0, n).toString('utf-8').includes(TEMPLATE_MARKER);
57
+ } finally {
58
+ fs.closeSync(fd);
59
+ }
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
30
65
  /**
31
66
  * Write the annotated theme template into a project.
32
67
  *
@@ -43,6 +78,28 @@ export function themeTemplate(options = {}) {
43
78
  cwd = process.cwd(),
44
79
  } = options;
45
80
 
81
+ const suggested = path.posix.join(
82
+ String(targetPath)
83
+ .trim()
84
+ .replace(/[\\/]+$/, '') || '.',
85
+ THEME_TEMPLATE_DEFAULT_PATH,
86
+ );
87
+ if (String(targetPath).trim() === '') {
88
+ throw new AstryxError(
89
+ 'The theme template path is blank. Give a file path, or leave it out for theme.template.ts.',
90
+ [
91
+ {
92
+ name: formatCliCommand(
93
+ `theme template ${THEME_TEMPLATE_DEFAULT_PATH}`,
94
+ cwd,
95
+ ),
96
+ reason: 'the default path',
97
+ },
98
+ ],
99
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
100
+ );
101
+ }
102
+
46
103
  let resolved;
47
104
  try {
48
105
  resolved = assertWithin(targetPath, cwd, {label: 'theme template path'});
@@ -55,6 +112,75 @@ export function themeTemplate(options = {}) {
55
112
 
56
113
  const relative = path.relative(cwd, resolved) || targetPath;
57
114
 
115
+ const namesFolder = /[\\/]$/.test(targetPath) || isDirectory(resolved);
116
+ if (namesFolder) {
117
+ throw new AstryxError(
118
+ `${relative || '.'} is a folder. The theme template is one file; give its path.`,
119
+ [
120
+ {
121
+ name: formatCliCommand(`theme template ${suggested}`, cwd),
122
+ reason: 'write the template into that folder',
123
+ },
124
+ ],
125
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
126
+ );
127
+ }
128
+ if (!TEMPLATE_EXTENSIONS.has(path.extname(resolved).toLowerCase())) {
129
+ throw new AstryxError(
130
+ `${relative} is not a TypeScript file. The theme template is TypeScript; give a .ts path.`,
131
+ [
132
+ {
133
+ name: formatCliCommand(
134
+ `theme template ${path.posix.join(path.dirname(targetPath).replace(/\\/g, '/'), THEME_TEMPLATE_DEFAULT_PATH)}`,
135
+ cwd,
136
+ ),
137
+ reason: 'a .ts path in the same folder',
138
+ },
139
+ ],
140
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
141
+ );
142
+ }
143
+
144
+ const editorRecord =
145
+ fs.existsSync(resolved) && overwrite
146
+ ? editorThemeRecord(path.dirname(resolved))
147
+ : null;
148
+ if (editorRecord) {
149
+ throw new AstryxError(
150
+ `${relative} belongs to a theme the theme editor made (${editorRecord} is beside it). Replacing it would cut the theme off from its settings, so --overwrite does not replace it.`,
151
+ [
152
+ {
153
+ name: formatCliCommand(
154
+ `theme template ${THEME_TEMPLATE_DEFAULT_PATH}`,
155
+ cwd,
156
+ ),
157
+ reason: 'write the template to a new file',
158
+ },
159
+ ],
160
+ ERROR_CODES.ERR_FILE_EXISTS,
161
+ );
162
+ }
163
+
164
+ if (
165
+ fs.existsSync(resolved) &&
166
+ overwrite &&
167
+ !isReplaceableThemeFile(resolved)
168
+ ) {
169
+ throw new AstryxError(
170
+ `${relative} is not a theme template or theme source, so --overwrite does not replace it.`,
171
+ [
172
+ {
173
+ name: formatCliCommand(
174
+ `theme template ${THEME_TEMPLATE_DEFAULT_PATH}`,
175
+ cwd,
176
+ ),
177
+ reason: 'write the template to a new file',
178
+ },
179
+ ],
180
+ ERROR_CODES.ERR_FILE_EXISTS,
181
+ );
182
+ }
183
+
58
184
  if (fs.existsSync(resolved) && !overwrite) {
59
185
  return {type: 'theme.template', data: {path: relative, written: false, reason: 'exists'}};
60
186
  }
@@ -65,13 +191,20 @@ export function themeTemplate(options = {}) {
65
191
  fs.mkdirSync(path.dirname(resolved), {recursive: true});
66
192
  fs.writeFileSync(resolved, contents);
67
193
  } catch (err) {
68
- const message = err instanceof Error ? err.message : String(err);
69
- throw new AstryxError(
70
- `Failed to write the theme template to ${relative}: ${message}`,
71
- undefined,
72
- ERROR_CODES.ERR_WRITE_FAILED,
73
- );
194
+ const message =
195
+ fsErrorMessage(err, relative) ??
196
+ `Failed to write the theme template to ${relative}: ${err instanceof Error ? err.message : String(err)}`;
197
+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);
74
198
  }
75
199
 
76
200
  return {type: 'theme.template', data: {path: relative, written: true, reason: null}};
77
201
  }
202
+
203
+ /** @param {string} file */
204
+ function isDirectory(file) {
205
+ try {
206
+ return fs.statSync(file).isDirectory();
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
@@ -100,10 +100,15 @@ export type ThemeListResponse = {
100
100
  type: "theme.list";
101
101
  data: ThemeListEntry[];
102
102
  /**
103
- * descriptor-less released copies that are not listed as themes
103
+ * descriptor-less released copies that are not listed as themes; local theme folders left out because they are broken
104
104
  */
105
105
  meta?: {
106
106
  unmigratedCopies: ThemeUnmigratedCopy[];
107
+ skippedThemes?: Array<{
108
+ slug: string;
109
+ path: string;
110
+ reason: string;
111
+ }>;
107
112
  } | undefined;
108
113
  };
109
114
  /**
@@ -137,6 +142,9 @@ export type ThemeAppResponse = {
137
142
  /**
138
143
  * npm package that owns the theme `theme add`
139
144
  * added. Omitted for a local theme, and for remove and use.
145
+ * `notes` is present only when the command did more than its change says:
146
+ * it chose between a local and a package theme with one slug, replaced a
147
+ * recorded owner, or dropped a recorded theme whose source is gone.
140
148
  */
141
149
  package?: string | undefined;
142
150
  data: {
@@ -149,6 +157,7 @@ export type ThemeAppResponse = {
149
157
  changed: boolean;
150
158
  firstAdd: boolean;
151
159
  };
160
+ notes?: string[];
152
161
  };
153
162
  };
154
163
  /**
@@ -159,6 +168,9 @@ export type ThemeEjectResponse = {
159
168
  * `maintained` describes the selected source theme. The ejected descriptor is
160
169
  * always written with `maintained: false` because the app owns the fork.
161
170
  * `package` is the source selector; bundled themes retain `@astryxdesign/cli`.
171
+ * `missingPackages` names the packages the fork imports that the app does not
172
+ * declare (empty when none); `installCommand` installs them, and is null when
173
+ * none are missing or the package manager is undetermined.
162
174
  */
163
175
  type: "theme.eject";
164
176
  data: {
@@ -170,6 +182,8 @@ export type ThemeEjectResponse = {
170
182
  entry: string;
171
183
  exportName: string;
172
184
  files: string[];
185
+ missingPackages: string[];
186
+ installCommand: string | null;
173
187
  };
174
188
  };
175
189
  /**
@@ -79,7 +79,7 @@
79
79
  * @typedef {object} ThemeListResponse
80
80
  * @property {'theme.list'} type
81
81
  * @property {ThemeListEntry[]} data
82
- * @property {{unmigratedCopies: ThemeUnmigratedCopy[]}} [meta] descriptor-less released copies that are not listed as themes
82
+ * @property {{unmigratedCopies: ThemeUnmigratedCopy[], skippedThemes?: Array<{slug: string, path: string, reason: string}>}} [meta] descriptor-less released copies that are not listed as themes; local theme folders left out because they are broken
83
83
  */
84
84
 
85
85
  /**
@@ -99,7 +99,10 @@
99
99
  * @property {'theme.app'} type
100
100
  * @property {string} [package] npm package that owns the theme `theme add`
101
101
  * added. Omitted for a local theme, and for remove and use.
102
- * @property {{themes: ThemeAppEntry[], default: string, modulePath: string, change: {action: 'add'|'remove'|'use', slug: string, changed: boolean, firstAdd: boolean}}} data
102
+ * `notes` is present only when the command did more than its change says:
103
+ * it chose between a local and a package theme with one slug, replaced a
104
+ * recorded owner, or dropped a recorded theme whose source is gone.
105
+ * @property {{themes: ThemeAppEntry[], default: string, modulePath: string, change: {action: 'add'|'remove'|'use', slug: string, changed: boolean, firstAdd: boolean}, notes?: string[]}} data
103
106
  */
104
107
 
105
108
  /**
@@ -109,7 +112,10 @@
109
112
  * `maintained` describes the selected source theme. The ejected descriptor is
110
113
  * always written with `maintained: false` because the app owns the fork.
111
114
  * `package` is the source selector; bundled themes retain `@astryxdesign/cli`.
112
- * @property {{slug: string, displayName: string, maintained: boolean, package: string, outputDir: string, entry: string, exportName: string, files: string[]}} data
115
+ * `missingPackages` names the packages the fork imports that the app does not
116
+ * declare (empty when none); `installCommand` installs them, and is null when
117
+ * none are missing or the package manager is undetermined.
118
+ * @property {{slug: string, displayName: string, maintained: boolean, package: string, outputDir: string, entry: string, exportName: string, files: string[], missingPackages: string[], installCommand: string | null}} data
113
119
  */
114
120
 
115
121
  /**