@astryxdesign/cli 0.7.16 → 0.7.17-canary.gb36275e

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 (239) hide show
  1. package/README.md +13 -23
  2. package/api/build/_adapter.d.mts +5 -0
  3. package/api/build/_adapter.mjs +49 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/build.doc.mjs +2 -1
  7. package/api/build/kit/rank.mjs +59 -12
  8. package/api/build/kit/weights.d.mts +16 -3
  9. package/api/build/kit/weights.json +1 -1
  10. package/api/build/kit/weights.mjs +238 -31
  11. package/api/build/kit/word-model.d.mts +23 -0
  12. package/api/build/kit/word-model.mjs +46 -0
  13. package/api/build/kit/words.d.mts +42 -0
  14. package/api/build/kit/words.mjs +82 -1
  15. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  16. package/api/component/list/list.d.mts +1 -1
  17. package/api/component/list/list.mjs +46 -5
  18. package/api/discover/_adapter.d.mts +1 -1
  19. package/api/docs/_adapter.d.mts +26 -2
  20. package/api/docs/_adapter.mjs +217 -5
  21. package/api/docs/docs.d.mts +3 -0
  22. package/api/docs/docs.doc.mjs +7 -1
  23. package/api/docs/docs.mjs +12 -0
  24. package/api/docs/docs.type.d.mts +5 -0
  25. package/api/docs/docs.type.mjs +2 -0
  26. package/api/docs/node/node.mjs +1 -1
  27. package/api/doctor/_adapter.d.mts +27 -5
  28. package/api/doctor/_adapter.mjs +77 -6
  29. package/api/doctor/built-checks.mjs +38 -13
  30. package/api/doctor/doctor.d.mts +4 -3
  31. package/api/doctor/doctor.mjs +14 -7
  32. package/api/doctor/theme-checks.mjs +121 -17
  33. package/api/render/_adapter.mjs +531 -192
  34. package/api/render/render.doc.mjs +11 -3
  35. package/api/render/render.type.d.mts +30 -0
  36. package/api/render/render.type.mjs +19 -0
  37. package/api/search/ORDERING.md +1 -1
  38. package/api/search/_candidate-score.mjs +51 -32
  39. package/api/search/_fit-order.mjs +3 -3
  40. package/api/search/_result.d.mts +5 -5
  41. package/api/search/_score.d.mts +6 -1
  42. package/api/search/_score.mjs +15 -3
  43. package/api/search/search.d.mts +1 -1
  44. package/api/theme/_adapter.mjs +10 -0
  45. package/api/theme/build/build.d.mts +47 -0
  46. package/api/theme/build/build.mjs +147 -25
  47. package/api/theme/theme.type.d.mts +10 -0
  48. package/api/theme/theme.type.mjs +7 -1
  49. package/api/theme-edit/_adapter.d.mts +48 -0
  50. package/api/theme-edit/_adapter.mjs +675 -42
  51. package/api/theme-edit/_check.d.mts +28 -22
  52. package/api/theme-edit/_check.mjs +1481 -252
  53. package/api/theme-edit/_color.d.mts +9 -0
  54. package/api/theme-edit/_color.mjs +41 -1
  55. package/api/theme-edit/_compiler.mjs +9 -0
  56. package/api/theme-edit/_context.mjs +60 -3
  57. package/api/theme-edit/_css.mjs +21 -1
  58. package/api/theme-edit/_edit.d.mts +22 -0
  59. package/api/theme-edit/_edit.mjs +1196 -88
  60. package/api/theme-edit/_how-commands.d.mts +57 -0
  61. package/api/theme-edit/_how-commands.mjs +536 -1
  62. package/api/theme-edit/_how-question.d.mts +65 -0
  63. package/api/theme-edit/_how-question.mjs +4401 -225
  64. package/api/theme-edit/_how.mjs +104 -4
  65. package/api/theme-edit/_marks.d.mts +31 -5
  66. package/api/theme-edit/_marks.mjs +57 -5
  67. package/api/theme-edit/_normal.d.mts +153 -0
  68. package/api/theme-edit/_normal.mjs +661 -0
  69. package/api/theme-edit/_palette.mjs +10 -4
  70. package/api/theme-edit/_parts.d.mts +8 -0
  71. package/api/theme-edit/_parts.mjs +103 -2
  72. package/api/theme-edit/_preview-app.d.mts +7 -1
  73. package/api/theme-edit/_preview-app.mjs +205 -17
  74. package/api/theme-edit/_preview.d.mts +64 -8
  75. package/api/theme-edit/_preview.mjs +447 -89
  76. package/api/theme-edit/_settings.d.mts +176 -5
  77. package/api/theme-edit/_settings.mjs +1936 -128
  78. package/api/theme-edit/_tables.d.mts +6 -0
  79. package/api/theme-edit/_tables.mjs +32 -1
  80. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  81. package/api/theme-edit/theme-edit.type.mjs +4 -1
  82. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  83. package/assets/codemods/run-codemod.mjs +73 -6
  84. package/assets/codemods/transforms/next/index.mjs +11 -1
  85. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  86. package/assets/docs/author-a-theme.doc.mjs +1 -0
  87. package/assets/docs/theme.doc.dense.mjs +2 -2
  88. package/assets/docs/theme.doc.mjs +1 -1
  89. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  90. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  91. package/assets/docs/tree/render-pages.doc.mjs +43 -2
  92. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  93. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  94. package/assets/docs/use-a-theme.doc.mjs +1 -1
  95. package/assets/docs.generated.json +2 -2
  96. package/assets/self-audit.generated.json +1 -1
  97. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  98. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  99. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  100. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  101. package/assets/templates/components.generated.json +1 -1
  102. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  103. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  104. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  105. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  106. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  107. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  108. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  109. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  110. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  111. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  112. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  113. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  114. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  115. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  116. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  117. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  118. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  119. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  120. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  121. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  122. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  123. package/assets/templates/pages/ide/page.tsx +24 -2
  124. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  125. package/assets/templates/pages/library/template.doc.mjs +4 -1
  126. package/assets/templates/pages/login/template.doc.mjs +2 -1
  127. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  128. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  129. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  130. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  131. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  132. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  133. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  134. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  135. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  136. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  137. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  138. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  139. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  140. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  141. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  142. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  143. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  144. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  145. package/authoring/debug/parse.d.mts +3 -3
  146. package/authoring/doctypes/_schema.d.mts +3 -3
  147. package/authoring/doctypes/command/command.doc.mjs +1 -1
  148. package/authoring/doctypes/template/template.doc.mjs +1 -1
  149. package/authoring/doctypes/template/type.ts +9 -0
  150. package/clients/cli/bin/astryx.mjs +6 -9
  151. package/clients/cli/build-id.generated.json +1 -1
  152. package/clients/cli/commands/component.doc.mjs +1 -1
  153. package/clients/cli/commands/component.mjs +20 -2
  154. package/clients/cli/commands/docs.doc.mjs +7 -1
  155. package/clients/cli/commands/docs.mjs +3 -1
  156. package/clients/cli/commands/doctor.mjs +22 -14
  157. package/clients/cli/commands/experimental/render.mjs +32 -1
  158. package/clients/cli/commands/experimental/theme.mjs +65 -14
  159. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  160. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  161. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  162. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  163. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  164. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  165. package/clients/cli/commands/search.doc.mjs +2 -1
  166. package/clients/cli/commands/search.mjs +6 -1
  167. package/clients/cli/commands/template.mjs +4 -2
  168. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  169. package/clients/cli/commands/theme.doc.mjs +1 -1
  170. package/clients/cli/commands/theme.mjs +153 -5
  171. package/clients/cli/commands/upgrade.mjs +42 -7
  172. package/clients/cli/index.mjs +1 -1
  173. package/clients/cli/lib/component-format.mjs +205 -98
  174. package/clients/cli/lib/hook-format.mjs +9 -19
  175. package/clients/cli/manifest.generated.json +1 -1
  176. package/foundation/agent-docs/agent-docs.mjs +1 -1
  177. package/foundation/config/theme-state.d.mts +13 -1
  178. package/foundation/config/theme-state.mjs +47 -7
  179. package/foundation/discovery/component-discovery.d.mts +11 -0
  180. package/foundation/discovery/component-discovery.mjs +27 -2
  181. package/foundation/discovery/component-replacement.mjs +130 -1
  182. package/foundation/discovery/entry-name-files.d.mts +43 -0
  183. package/foundation/discovery/entry-name-files.mjs +264 -0
  184. package/foundation/discovery/hook-discovery.d.mts +8 -2
  185. package/foundation/discovery/hook-discovery.mjs +20 -7
  186. package/foundation/discovery/package-exports.d.mts +10 -0
  187. package/foundation/discovery/package-exports.mjs +56 -3
  188. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  189. package/foundation/discovery/runner-allowlist.mjs +2 -0
  190. package/foundation/discovery/template-adapter.d.mts +52 -0
  191. package/foundation/discovery/template-adapter.mjs +173 -10
  192. package/foundation/discovery/theme-imports.d.mts +14 -0
  193. package/foundation/discovery/theme-imports.mjs +43 -1
  194. package/foundation/doc-compiler/import.mjs +7 -1
  195. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  196. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  197. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  198. package/foundation/fs/cache-eviction.d.mts +21 -0
  199. package/foundation/fs/cache-eviction.mjs +73 -0
  200. package/foundation/fs/gather-cache.d.mts +25 -4
  201. package/foundation/fs/gather-cache.mjs +163 -53
  202. package/foundation/fs/jiti-cache.d.mts +19 -1
  203. package/foundation/fs/jiti-cache.mjs +130 -6
  204. package/foundation/fs/kept-tree.d.mts +60 -0
  205. package/foundation/fs/kept-tree.mjs +154 -0
  206. package/foundation/fs/module-loader.d.mts +18 -2
  207. package/foundation/fs/module-loader.mjs +92 -20
  208. package/foundation/identity/provider-identity.d.mts +6 -0
  209. package/foundation/identity/provider-identity.mjs +10 -1
  210. package/foundation/render/embedded-imports.d.mts +5 -4
  211. package/foundation/render/embedded-imports.mjs +7 -16
  212. package/foundation/render/file-header.d.mts +66 -0
  213. package/foundation/render/file-header.mjs +118 -0
  214. package/foundation/render/host-answer.d.mts +18 -0
  215. package/foundation/render/host-answer.mjs +46 -0
  216. package/foundation/render/host-exit.d.mts +1 -0
  217. package/foundation/render/host-exit.mjs +6 -1
  218. package/foundation/render/html-reader.d.mts +55 -2
  219. package/foundation/render/html-reader.mjs +145 -26
  220. package/foundation/render/markup-edits.d.mts +57 -0
  221. package/foundation/render/markup-edits.mjs +182 -0
  222. package/foundation/render/page-host.mjs +29 -12
  223. package/foundation/render/page-worker.mjs +83 -13
  224. package/foundation/render/render-page.d.mts +34 -2
  225. package/foundation/render/render-page.mjs +210 -29
  226. package/foundation/render/source-block.d.mts +73 -6
  227. package/foundation/render/source-block.mjs +170 -19
  228. package/foundation/render/ts-paths.d.mts +53 -6
  229. package/foundation/render/ts-paths.mjs +286 -41
  230. package/foundation/response/error-codes.d.mts +3 -1
  231. package/foundation/response/error-codes.d.ts +1 -0
  232. package/foundation/response/error-codes.doc.mjs +12 -1
  233. package/foundation/response/error-codes.mjs +10 -0
  234. package/foundation/text/string-utils.d.mts +3 -2
  235. package/foundation/text/string-utils.mjs +16 -3
  236. package/foundation/text/suggest-order.d.mts +9 -0
  237. package/foundation/text/suggest-order.mjs +13 -0
  238. package/host/index.mjs +8 -6
  239. package/package.json +6 -6
@@ -32,9 +32,10 @@
32
32
  */
33
33
 
34
34
  import {writeThemeTemplate} from '../theme/template/template.mjs';
35
- import {buildSuggestion} from '../theme/build/build.mjs';
35
+ import {buildSuggestion, realLocation} from '../theme/build/build.mjs';
36
36
  import {createHash} from 'node:crypto';
37
37
  import * as fs from 'node:fs';
38
+ import {createRequire} from 'node:module';
38
39
  import * as path from 'node:path';
39
40
  import * as edit from './_edit.mjs';
40
41
  import {baseInstalled, themeCacheRoot} from './_project.mjs';
@@ -42,7 +43,8 @@ import * as preview from './_preview-app.mjs';
42
43
  import {AstryxError} from '../error.mjs';
43
44
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
44
45
  import {findPackageRoot} from '../../foundation/fs/paths.mjs';
45
- import {coreApp} from './_context.mjs';
46
+ import {context, coreApp} from './_context.mjs';
47
+ import {APP_COPY_MARK} from './_marks.mjs';
46
48
  import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
47
49
  import {withFolderLock} from '../../foundation/release/folder-lock.mjs';
48
50
  import {
@@ -50,15 +52,31 @@ import {
50
52
  quoteCommandArgument,
51
53
  } from '../../foundation/env/package-manager.mjs';
52
54
  import {LIKE, P} from './_tables.mjs';
55
+
56
+ /** The preview command, as a person runs it. */
57
+ const PREVIEW_WORDS = P.replace(/ editor$/, ' preview');
53
58
  import {setLine} from './_check.mjs';
59
+ import {splitCommand} from './_vet.mjs';
54
60
  import {
55
61
  SHOWCASE_GROUPS,
62
+ appCopyBehind,
63
+ appCopyStale,
64
+ copyFontsCss,
56
65
  takeFirstAppCopy,
57
66
  writeAppCopy,
58
67
  writeAppCopyAt,
59
68
  } from './_preview.mjs';
60
69
  import {humanWarn} from '../../foundation/response/json.mjs';
61
- import {folderIsEmpty, setAfterBuild, typedThemeName} from './_settings.mjs';
70
+ import {
71
+ buildColorModes,
72
+ camel,
73
+ folderIsEmpty,
74
+ loadTheme,
75
+ setAfterBuild,
76
+ editedThemes,
77
+ themeFiles,
78
+ typedThemeName,
79
+ } from './_settings.mjs';
62
80
 
63
81
  // Every build of a theme writes its app copy (src/themes/<theme>/).
64
82
  setAfterBuild(writeAppCopy);
@@ -367,16 +385,43 @@ const lockName = name =>
367
385
  */
368
386
  function absolute(result, root, from) {
369
387
  if (path.resolve(from) === root) return result;
370
- /** @param {any} v @returns {any} */
371
- const map = v =>
388
+ /**
389
+ * Lines that name project files inside them: `see`, a picture note, the
390
+ * in-app preview's stale entries. Every project path in them (a theme
391
+ * file, an in-app preview folder) is made absolute, one style per line.
392
+ */
393
+ const PROSE = new Set(['see', 'pictureProblem', 'previewStale']);
394
+ /** A project-relative path that names a file or folder there. @param {string} p */
395
+ const inRoot = p => {
396
+ const bare = p.replace(/\/+$/, '');
397
+ return (
398
+ Boolean(bare) &&
399
+ !path.isAbsolute(bare) &&
400
+ !bare.startsWith('.') &&
401
+ fs.existsSync(path.join(root, bare))
402
+ );
403
+ };
404
+ /** @param {any} v @param {string} [key] @returns {any} */
405
+ const map = (v, key) =>
372
406
  typeof v === 'string'
373
- ? /^themes\//.test(v)
407
+ ? // A path alone; a line that starts with one is read as prose below.
408
+ /^themes\/\S*$/.test(v) && !(key && PROSE.has(key))
374
409
  ? path.join(root, v)
375
- : v
410
+ : key && PROSE.has(key)
411
+ ? v.replace(
412
+ /(^|[\s(,])((?:themes|src|app)\/[^\s,;)]*)/g,
413
+ (all, before, file) =>
414
+ /^themes\//.test(file) || inRoot(file)
415
+ ? `${before}${path.join(root, file)}`
416
+ : all,
417
+ )
418
+ : v
376
419
  : Array.isArray(v)
377
- ? v.map(map)
420
+ ? v.map(x => map(x, key))
378
421
  : v && typeof v === 'object'
379
- ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, map(x)]))
422
+ ? Object.fromEntries(
423
+ Object.entries(v).map(([k, x]) => [k, map(x, k)]),
424
+ )
380
425
  : v;
381
426
  return map(result);
382
427
  }
@@ -550,37 +595,117 @@ export const themeEditShow = (theme, options = {}) =>
550
595
  );
551
596
  /** @type {typeof preview.themeEditPreviewAdd} */
552
597
  export const themeEditPreviewAdd = (description, options = {}) =>
553
- inProject(options, 'preview', o =>
554
- preview.themeEditPreviewAdd(description, withThemeLock(o)),
598
+ stopTold(
599
+ `a preview change stopped part way is finished by the next ${PREVIEW_WORDS} add, and one written in full stands (${PREVIEW_WORDS} list says which)`,
600
+ () =>
601
+ inProject(options, 'preview', o =>
602
+ preview.themeEditPreviewAdd(description, withThemeLock(o)),
603
+ ),
555
604
  );
605
+
606
+ /**
607
+ * Run a preview command with a stop (Ctrl-C, SIGTERM) heard for its whole
608
+ * run, and after it: the stop ends the process as stopped, with one line
609
+ * saying where the change stands (a change stopped part way is finished by
610
+ * the next preview command), never an ok with exit 0.
611
+ * @template T
612
+ * @param {string} where where the change stands, and what finishes it
613
+ * @param {() => Promise<T>} fn
614
+ * @returns {Promise<T>}
615
+ */
616
+ async function stopTold(where, fn) {
617
+ const on = (/** @type {NodeJS.Signals} */ sig) => {
618
+ process.removeListener('SIGINT', on);
619
+ process.removeListener('SIGTERM', on);
620
+ process.stderr.write(`Stopped: ${where}.\n`);
621
+ // With no other listener (a lock's, which ends the process itself),
622
+ // the stop ends it here.
623
+ if (process.listenerCount(sig) === 0) process.kill(process.pid, sig);
624
+ };
625
+ process.on('SIGINT', on);
626
+ process.on('SIGTERM', on);
627
+ try {
628
+ const r = await fn();
629
+ // A turn of the event loop, so a stop that came while the work ran
630
+ // without a pause is heard now, before the result is printed.
631
+ await new Promise(resolve => setImmediate(resolve));
632
+ // Every listener added here is removed on return: the caller's process
633
+ // keeps its own stop handling. The CLI client, which owns its process,
634
+ // holds a stop that lands while it prints the result.
635
+ return r;
636
+ } finally {
637
+ process.removeListener('SIGINT', on);
638
+ process.removeListener('SIGTERM', on);
639
+ }
640
+ }
556
641
  /**
557
642
  * `preview app` runs from the project root, with `dir` kept pointing where
558
643
  * it was given. With a theme it holds that theme's lock, since it may build
559
644
  * the theme and copies its files: a `set` beside it waits.
560
645
  * @type {typeof preview.themeEditPreviewApp}
561
646
  */
562
- export const themeEditPreviewApp = (dir, options = {}) => {
647
+ export const themeEditPreviewApp = async (dir, options = {}) => {
563
648
  const from = options.cwd ?? process.cwd();
564
- return inProject(
565
- options,
566
- options.theme == null ? null : lockName(options.theme),
567
- o =>
568
- preview.themeEditPreviewApp(
569
- typeof dir === 'string' && dir.trim() && dir === dir.trim()
570
- ? path.relative(o.cwd, path.resolve(from, dir)) || '.'
571
- : dir,
572
- o,
573
- ),
574
- true,
649
+ return fromHere(
650
+ await stopTold(
651
+ `the new app may be part made; ${PREVIEW_WORDS} app with a new folder name makes a whole one`,
652
+ () =>
653
+ inProject(
654
+ options,
655
+ options.theme == null ? null : lockName(options.theme),
656
+ o =>
657
+ preview.themeEditPreviewApp(
658
+ typeof dir === 'string' && dir.trim() && dir === dir.trim()
659
+ ? path.relative(o.cwd, path.resolve(from, dir)) || '.'
660
+ : dir,
661
+ o,
662
+ ),
663
+ true,
664
+ ),
665
+ ),
666
+ from,
575
667
  );
576
668
  };
669
+ /**
670
+ * A new app's folder and its open line, as they work from where the command
671
+ * ran (`cd ../../theme-app` from src/app), not from the project root.
672
+ * @template T
673
+ * @param {T} r
674
+ * @param {string} from
675
+ * @returns {T}
676
+ */
677
+ function fromHere(r, from) {
678
+ const d = /** @type {any} */ (r)?.data;
679
+ if (!d || typeof d.folder !== 'string') return r;
680
+ const root = projectRoot(from);
681
+ if (!root || path.resolve(from) === root) return r;
682
+ const here = path.relative(from, path.join(root, d.folder)) || '.';
683
+ const shown = here.split(path.sep).join('/');
684
+ const cdArg = quoteCommandArgument(
685
+ shown.startsWith('-') ? `./${shown}` : shown,
686
+ );
687
+ return /** @type {T} */ ({
688
+ ...r,
689
+ data: {
690
+ ...d,
691
+ folder: shown,
692
+ ...(typeof d.open === 'string'
693
+ ? {open: d.open.replace(/^cd \S+ &&/, `cd ${cdArg} &&`)}
694
+ : {}),
695
+ },
696
+ });
697
+ }
577
698
  /** @type {typeof preview.themeEditPreviewList} */
578
699
  export const themeEditPreviewList = (options = {}) =>
579
700
  inProject(options, null, async o => preview.themeEditPreviewList(o));
580
701
  /** @type {typeof preview.themeEditPreviewRemove} */
581
702
  export const themeEditPreviewRemove = (page, options = {}) =>
582
- inProject(options, 'preview', o =>
583
- preview.themeEditPreviewRemove(page, withThemeLock(o)),
703
+ stopTold(
704
+ `a removal stopped part way is finished by the next ${PREVIEW_WORDS} remove, and one made in full stands (${PREVIEW_WORDS} list says which)`,
705
+ () =>
706
+ inProject(options, 'preview', o =>
707
+ preview.themeEditPreviewRemove(page, withThemeLock(o)),
708
+ ),
584
709
  );
585
710
 
586
711
  /**
@@ -669,8 +794,9 @@ function runLine(cwd, rest) {
669
794
  * @returns {AstryxError | null}
670
795
  */
671
796
  export function editorThemeRefusal(err, cwd) {
672
- // A refused compile ends here: its theme locks go now, not at exit.
673
- void releaseCompileHold?.();
797
+ // A refused compile ends here: its theme locks go now, not at exit, and
798
+ // it writes no app copy (from build files it refused).
799
+ void releaseCompileHold?.(true);
674
800
  if (
675
801
  err.code !== ERROR_CODES.ERR_UNKNOWN_THEME &&
676
802
  !/unknown theme|is not added|not a theme package/i.test(err.message)
@@ -683,10 +809,43 @@ export function editorThemeRefusal(err, cwd) {
683
809
  const word = named ? typedThemeName(named[1] ?? named[2]) : '';
684
810
  const slug = word ? editorThemeOf(root, word) : null;
685
811
  if (!slug) return null;
812
+ // The command that refused: list, add, use, remove or eject.
813
+ const verb =
814
+ process.argv
815
+ .slice(2)
816
+ .find(a => ['list', 'add', 'use', 'remove', 'eject'].includes(a)) ?? null;
817
+ // eject copies a theme package's source into the app; an editor theme's
818
+ // source is the app's already.
819
+ if (verb === 'eject')
820
+ return new AstryxError(
821
+ `${slug} is a theme the editor made: its source is yours already, themes/${slug}/${slug}.theme.ts (your edits there survive every change), and the editor changes the rest. eject copies a theme package's source into the app, so it has nothing to do for ${slug}.`,
822
+ [
823
+ {
824
+ name: runLine(cwd, `experimental theme editor show ${slug}`),
825
+ reason: 'the theme as it is now',
826
+ },
827
+ ],
828
+ ERROR_CODES.ERR_UNKNOWN_THEME,
829
+ );
830
+ const copyThere = !folderIsEmpty(path.join(root, LOCAL_THEME_ROOT, slug));
831
+ // A path to the theme ("themes/d", "src/themes/d"): the commands take its
832
+ // name.
833
+ const typed = named ? (named[1] ?? named[2]) : '';
834
+ if (copyThere && verb && typed !== slug)
835
+ return new AstryxError(
836
+ `"${typed}" is ${/[\\/]|\.[a-z]+$/i.test(typed) ? 'a path' : "not the theme's name"}; the theme commands take the theme's name: ${slug}.`,
837
+ [
838
+ {
839
+ name: runLine(cwd, `theme ${verb} ${slug}`),
840
+ reason: 'the same, by name',
841
+ },
842
+ ],
843
+ ERROR_CODES.ERR_UNKNOWN_THEME,
844
+ );
686
845
  // A local theme of that name (a fork in the app's own themes folder) is
687
846
  // one the stable commands take: their own message stands.
688
847
  // A folder of only system files (or empty) holds no theme: as absent.
689
- if (!folderIsEmpty(path.join(root, LOCAL_THEME_ROOT, slug))) return null;
848
+ if (copyThere) return null;
690
849
  // No app copy yet (a theme made before the editor wrote one, or the
691
850
  // copy removed): the next build writes it, then the same steps every
692
851
  // place gives (`wiring` of new and show).
@@ -722,6 +881,113 @@ export function editorThemeRefusal(err, cwd) {
722
881
  );
723
882
  }
724
883
 
884
+ /**
885
+ * A refused compile whose first suggestion is another compile: that compile
886
+ * is run through compile's own checks before it is offered (in memory,
887
+ * nothing built), and each repair a refusal of it offers is folded into the
888
+ * one line. An --out outside the working folder is dropped, and the reason
889
+ * says why; when the rest cannot be repaired, the reason says so. A line
890
+ * that starts with `cd` runs elsewhere, so it is not checked from here.
891
+ * @param {AstryxError} err
892
+ * @param {string} cwd
893
+ * @returns {Promise<AstryxError>}
894
+ */
895
+ export async function editorFollowCompile(err, cwd) {
896
+ const list = err.suggestions ?? [];
897
+ const first = list[0];
898
+ // The build's own refusals name `theme build`; the group's words replace
899
+ // those words when the refusal is shown.
900
+ const wordsIn = (/** @type {string} */ line) =>
901
+ [' experimental theme compile ', ' theme build '].find(w =>
902
+ line.includes(w),
903
+ );
904
+ if (!first || /^cd /.test(first.name) || !wordsIn(first.name)) return err;
905
+ /** @param {string} line */
906
+ const read = line => {
907
+ const words = wordsIn(line);
908
+ if (!words) return null;
909
+ const args = splitCommand(line.slice(line.indexOf(words) + words.length));
910
+ if (!args) return null;
911
+ /** @type {{source?: string, out?: string, iconsSpecifier?: string, check?: boolean}} */
912
+ const r = {};
913
+ for (let i = 0; i < args.length; i += 1) {
914
+ const a = args[i];
915
+ if (a === '--check') r.check = true;
916
+ else if (a === '--out') r.out = args[(i += 1)];
917
+ else if (a === '--icons-specifier') r.iconsSpecifier = args[(i += 1)];
918
+ else if (a.startsWith('-') || r.source) return null;
919
+ else r.source = a;
920
+ }
921
+ return r.source ? r : null;
922
+ };
923
+ const COMPILE = {group: 'experimental theme', build: 'compile'};
924
+ const inside = (/** @type {string} */ p) => {
925
+ const rel = path.relative(
926
+ realLocation(path.resolve(cwd)),
927
+ realLocation(path.resolve(p)),
928
+ );
929
+ return !rel.startsWith('..') && !path.isAbsolute(rel);
930
+ };
931
+ let line = first.name;
932
+ let reason = first.reason;
933
+ for (let i = 0; i < 6; i += 1) {
934
+ const r = read(line);
935
+ if (!r || !r.source) break;
936
+ const source = r.source;
937
+ const abs = path.resolve(cwd, source);
938
+ if (r.out && !inside(path.resolve(cwd, r.out))) {
939
+ line = buildSuggestion(
940
+ source,
941
+ {check: r.check, iconsSpecifier: r.iconsSpecifier},
942
+ cwd,
943
+ COMPILE,
944
+ );
945
+ reason = `do this instead, without --out: ${r.out} is outside the working folder, where a build may not write, so the outputs go beside the source`;
946
+ continue;
947
+ }
948
+ /** @type {{message: string, next?: string} | null} */
949
+ let problem = null;
950
+ if (!fs.existsSync(abs)) problem = {message: `${source} is not there`};
951
+ else if (fs.statSync(abs).isDirectory()) {
952
+ const own = `${path.basename(abs)}.theme.ts`;
953
+ problem = {
954
+ message: `${source} is a folder`,
955
+ next: fs.existsSync(path.join(abs, own))
956
+ ? buildSuggestion(
957
+ path.posix.join(source.replace(/\/+$/, ''), own),
958
+ r,
959
+ cwd,
960
+ COMPILE,
961
+ )
962
+ : undefined,
963
+ };
964
+ } else if (!r.out && !inside(path.dirname(abs)))
965
+ problem = {message: `${source} is outside the working folder`};
966
+ else {
967
+ const refused = await editorCompileProblem([source], {cwd, ...r});
968
+ if (refused)
969
+ problem = {
970
+ message: refused.message,
971
+ next: refused.suggestions?.[0]?.name,
972
+ };
973
+ }
974
+ if (!problem) break;
975
+ if (problem.next && problem.next !== line) {
976
+ line = problem.next;
977
+ if (/^cd /.test(line)) break;
978
+ continue;
979
+ }
980
+ reason = `${reason}; it is still refused: ${problem.message}`;
981
+ break;
982
+ }
983
+ if (line === first.name && reason === first.reason) return err;
984
+ err.suggestions = [
985
+ {...first, name: line, reason},
986
+ ...list.slice(1).filter(x => x.name !== line),
987
+ ];
988
+ return err;
989
+ }
990
+
725
991
  /**
726
992
  * A refusal before `compile` runs on an editor theme's files, or null: the
727
993
  * editor's generated settings are not a theme source, `--family` does not
@@ -757,8 +1023,119 @@ export async function editorCompileProblem(
757
1023
  from,
758
1024
  COMPILE,
759
1025
  );
1026
+ // An --out into an editor theme's app copy folder: the copy refresh would
1027
+ // write the theme's own build over it.
1028
+ if (out) {
1029
+ // Any --out in the copy folder, the folder itself too, in any case,
1030
+ // written with backslashes or through a link, as the build reads it.
1031
+ const rel = path
1032
+ .relative(
1033
+ realLocation(cwdRoot),
1034
+ realLocation(path.resolve(cwd, slashed(out))),
1035
+ )
1036
+ .split(path.sep)
1037
+ .filter(Boolean)
1038
+ .map(x => x.toLowerCase());
1039
+ if (
1040
+ rel[0] === 'src' &&
1041
+ rel[1] === 'themes' &&
1042
+ rel.length >= 3 &&
1043
+ fs.existsSync(themeFiles(cwdRoot, rel[2]).settings)
1044
+ ) {
1045
+ const t = rel[2];
1046
+ return new AstryxError(
1047
+ `--out ${out} is in ${t}'s app copy (src/themes/${t}/), which the editor writes after every build of themes/${t}/; write the build somewhere else.`,
1048
+ [
1049
+ {
1050
+ // The same compile without --out: it builds into themes/<t>/,
1051
+ // and the copy follows.
1052
+ // From a subfolder, with the cd to the app root, where an
1053
+ // editor theme compiles.
1054
+ name:
1055
+ path.resolve(cwd) === path.resolve(cwdRoot)
1056
+ ? buildSuggestion(
1057
+ files.length === 1 ? files[0] : `themes/${t}/${t}.theme.ts`,
1058
+ {check, iconsSpecifier},
1059
+ cwd,
1060
+ COMPILE,
1061
+ )
1062
+ : `cd ${quoteCommandArgument(path.relative(cwd, cwdRoot) || '.')} && ${buildSuggestion(
1063
+ files.length === 1
1064
+ ? path.relative(cwdRoot, path.resolve(cwd, files[0])) ||
1065
+ files[0]
1066
+ : `themes/${t}/${t}.theme.ts`,
1067
+ {check, iconsSpecifier},
1068
+ cwdRoot,
1069
+ COMPILE,
1070
+ )}`,
1071
+ reason: 'do this instead',
1072
+ },
1073
+ ],
1074
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
1075
+ );
1076
+ }
1077
+ }
760
1078
  for (const file of files) {
761
- const at = editorThemeAt(cwdRoot, path.resolve(cwd, file));
1079
+ const abs = path.resolve(cwd, file);
1080
+ const relParts = path
1081
+ .relative(
1082
+ realLocation(cwdRoot),
1083
+ realLocation(path.resolve(cwd, slashed(file))),
1084
+ )
1085
+ .split(path.sep);
1086
+ // The app's theme module `theme add` writes: not a theme source.
1087
+ if (relParts.join('/') === 'src/astryx-themes.ts')
1088
+ return new AstryxError(
1089
+ `${file} is the app's theme module (\`theme add\` writes it), not a theme source; compile the editor theme instead.`,
1090
+ editedThemes(cwdRoot)
1091
+ .slice(0, 3)
1092
+ .map(t => ({
1093
+ name: compileLine(`themes/${t}/${t}.theme.ts`, cwdRoot),
1094
+ reason: 'do this instead',
1095
+ })),
1096
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
1097
+ );
1098
+ // A file of an editor theme's app copy (src/themes/<t>/): the copy
1099
+ // is written from themes/<t>/, so that is what compiles.
1100
+ if (
1101
+ relParts[0] === 'src' &&
1102
+ relParts[1] === 'themes' &&
1103
+ (relParts.length === 3 || relParts.length === 4) &&
1104
+ fs.existsSync(themeFiles(cwdRoot, relParts[2]).settings) &&
1105
+ // A file of yours there (no editor mark, no build header) compiles
1106
+ // like any theme source.
1107
+ (relParts.length === 3 ||
1108
+ isCopyFile(path.join(cwdRoot, ...relParts)) ||
1109
+ relParts[3] === `${camel(relParts[2])}Theme.ts`)
1110
+ ) {
1111
+ const t = relParts[2];
1112
+ const own = `themes/${t}/${t}.theme.ts`;
1113
+ if (path.resolve(cwd) !== path.resolve(cwdRoot))
1114
+ return new AstryxError(
1115
+ `${t} is a theme the editor made; compile it from the app root (${path.relative(cwd, cwdRoot) || '.'}), where the editor builds it.`,
1116
+ [
1117
+ {
1118
+ name: `cd ${quoteCommandArgument(path.relative(cwd, cwdRoot) || '.')} && ${compileLine(own, cwdRoot)}`,
1119
+ reason: 'do this instead',
1120
+ },
1121
+ ],
1122
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
1123
+ );
1124
+ // Its source too: a compile of the copy builds neither the theme
1125
+ // nor a current copy.
1126
+ return new AstryxError(
1127
+ `${file} is ${relParts.length === 3 ? '' : 'part of '}${t}'s app copy, which the editor writes from themes/${t}/ after every build; compile the theme itself.`,
1128
+ [
1129
+ {name: compileLine(own, cwd), reason: 'do this instead'},
1130
+ {
1131
+ name: runLine(cwdRoot, `experimental theme editor show ${t}`),
1132
+ reason: 'writes the app copy again from the theme',
1133
+ },
1134
+ ],
1135
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
1136
+ );
1137
+ }
1138
+ const at = editorThemeAt(cwdRoot, abs);
762
1139
  if (!at || !editorOwnFile(at.slug, file)) continue;
763
1140
  const {root, slug} = at;
764
1141
  const source = `themes/${slug}/${slug}.theme.ts`;
@@ -874,6 +1251,9 @@ export async function editorCompileProblem(
874
1251
  if (path.basename(file) === `${slug}.theme.ts`) {
875
1252
  const pairs = await edit.editorPairRefusal(root, slug);
876
1253
  if (pairs) return pairs;
1254
+ // A token value the file gives that set refuses ships as it is.
1255
+ const values = await edit.editorOwnTokenRefusal(root, slug);
1256
+ if (values) return values;
877
1257
  }
878
1258
  }
879
1259
  }
@@ -883,7 +1263,7 @@ export async function editorCompileProblem(
883
1263
  /** The editor themes a running `compile` holds the lock of, by project and name. */
884
1264
  const COMPILE_HELD = new Set();
885
1265
 
886
- /** @type {(() => Promise<void>) | null} The release of the running compile's hold. */
1266
+ /** @type {((refused?: boolean) => Promise<void>) | null} The release of the running compile's hold; `refused`: it wrote nothing, so no app copy either. */
887
1267
  let releaseCompileHold = null;
888
1268
 
889
1269
  /**
@@ -903,13 +1283,23 @@ export async function editorThemeHold(files, {cwd}) {
903
1283
  const at = editorThemeAt(cwdRoot, path.resolve(cwd, f));
904
1284
  if (at && editorOwnFile(at.slug, f))
905
1285
  found.set(`${at.root}\0${at.slug}`, at);
1286
+ // The app copy's source (src/themes/<t>/<t>Theme.ts) of an editor
1287
+ // theme: built under the theme's lock, so it never lands between a
1288
+ // change's two writes.
1289
+ const copy = appCopyTheme(cwdRoot, path.resolve(cwd, f));
1290
+ if (copy) found.set(`${copy.root}\0${copy.slug}`, copy);
906
1291
  }
907
1292
  const themes = [...found.keys()].sort().map(k => found.get(k));
908
- /** @type {Array<() => Promise<void>>} */
1293
+ /** @type {Array<{copy: (refused: boolean) => boolean, finish: (later: boolean) => Promise<void>}>} */
909
1294
  const releases = [];
910
- const releaseAll = async () => {
1295
+ // Every theme's copy is written first, at once (a refusal ends the run
1296
+ // without waiting), then each lock goes.
1297
+ const releaseAll = async (refused = false) => {
911
1298
  if (releaseCompileHold === releaseAll) releaseCompileHold = null;
912
- for (const r of releases.splice(0).reverse()) await r();
1299
+ const items = releases.splice(0);
1300
+ const later = items.map(x => x.copy(refused));
1301
+ for (const [i, x] of [...items.entries()].reverse())
1302
+ await x.finish(later[i]);
913
1303
  };
914
1304
  releaseCompileHold = releaseAll;
915
1305
  for (const {
@@ -927,6 +1317,17 @@ export async function editorThemeHold(files, {cwd}) {
927
1317
  ready = r;
928
1318
  });
929
1319
  const key = `${root}\0${slug}`;
1320
+ // When the lock was taken, and the context a copy write needs (its
1321
+ // font stylesheets), ready before the build so the copy is written at
1322
+ // once when the run ends.
1323
+ const heldAt = Date.now() - 1;
1324
+ /** @type {any} */
1325
+ let copyCtx = null;
1326
+ try {
1327
+ copyCtx = await context(root);
1328
+ } catch {
1329
+ copyCtx = null;
1330
+ }
930
1331
  const done = withLock(root, lockName(slug), async () => {
931
1332
  COMPILE_HELD.add(key);
932
1333
  ready();
@@ -941,12 +1342,45 @@ export async function editorThemeHold(files, {cwd}) {
941
1342
  await releaseAll();
942
1343
  throw err;
943
1344
  }
944
- releases.push(async () => {
1345
+ releases.push({
945
1346
  // A compile that wrote the build refreshes the app's copy too
946
- // (src/themes/<theme>/), under the same lock; a check writes nothing.
947
- if (!process.argv.includes('--check')) {
1347
+ // (src/themes/<theme>/), under the same lock; a check writes
1348
+ // nothing. Each theme's copy follows its own build: a theme this run
1349
+ // built (its build now matches its settings) gets its copy, whatever
1350
+ // a later theme did; one that was refused or failed keeps its copy.
1351
+ // True when the copy still needs its font stylesheet from the
1352
+ // theme's settings (written in finish).
1353
+ copy: (/** @type {boolean} */ refused) => {
1354
+ if (process.argv.includes('--check')) return false;
1355
+ // This run built the theme: its outputs were written since the
1356
+ // lock was taken, or the run ended well. A refused or failed
1357
+ // compile writes no copy.
1358
+ const f = themeFiles(root, slug);
1359
+ const written = [f.css, f.js].some(x => {
1360
+ try {
1361
+ return fs.statSync(x).mtimeMs >= heldAt;
1362
+ } catch {
1363
+ return false;
1364
+ }
1365
+ });
1366
+ if (!written && (refused || (process.exitCode ?? 0) !== 0))
1367
+ return false;
948
1368
  try {
949
- writeAppCopyAt(root, slug, null);
1369
+ // From what was just built, its font stylesheets from the fonts
1370
+ // the theme loads now.
1371
+ if (copyCtx) writeAppCopy(copyCtx, slug, loadTheme(root, slug));
1372
+ else writeAppCopyAt(root, slug, null);
1373
+ } catch {
1374
+ try {
1375
+ writeAppCopyAt(root, slug, null);
1376
+ } catch {
1377
+ // A theme that does not load keeps its copy as it was.
1378
+ }
1379
+ }
1380
+ return false;
1381
+ },
1382
+ finish: async () => {
1383
+ if (!process.argv.includes('--check')) {
950
1384
  // The first write of the app copy is named once (the compile's
951
1385
  // own JSON envelope is the stable command's).
952
1386
  const wrote = takeFirstAppCopy(root, slug);
@@ -954,17 +1388,185 @@ export async function editorThemeHold(files, {cwd}) {
954
1388
  humanWarn(
955
1389
  `wrote ${slug}'s app copy, a local theme \`theme add ${slug}\` takes, written again after every build: ${wrote.join(', ')}`,
956
1390
  );
957
- } catch {
958
- // A theme that does not load keeps its copy as it was.
1391
+ // A copy a file or a link keeps behind, or one that could not be
1392
+ // written, is said, as set and show say it.
1393
+ const stale = appCopyStale(root, slug).appCopyStale;
1394
+ if (stale) humanWarn(stale);
959
1395
  }
960
- }
961
- release();
962
- await done;
1396
+ release();
1397
+ await done;
1398
+ },
963
1399
  });
964
1400
  }
965
1401
  return releaseAll;
966
1402
  }
967
1403
 
1404
+ /** @param {string} p a path as typed, with Windows separators read as `/` */
1405
+ const slashed = p => String(p).replace(/\\/g, '/');
1406
+
1407
+ /**
1408
+ * Whether a file in an app copy folder is the editor's: its mark, or the
1409
+ * header the build writes. A missing file counts (it would be the copy's).
1410
+ * @param {string} file
1411
+ */
1412
+ function isCopyFile(file) {
1413
+ try {
1414
+ const head = fs.readFileSync(file, 'utf8').slice(0, 600);
1415
+ return (
1416
+ head.includes(APP_COPY_MARK) ||
1417
+ /@generated by `astryx theme build`/.test(head)
1418
+ );
1419
+ } catch {
1420
+ return true;
1421
+ }
1422
+ }
1423
+
1424
+ /**
1425
+ * The editor theme whose app copy source a file is
1426
+ * (`src/themes/<t>/<t>Theme.ts`, with themes/<t>/ an editor theme), or
1427
+ * null.
1428
+ * @param {string} root the project root
1429
+ * @param {string} file absolute
1430
+ * @returns {{root: string, slug: string} | null}
1431
+ */
1432
+ function appCopyTheme(root, file) {
1433
+ const rel = path.relative(root, file).split(path.sep);
1434
+ if (rel.length !== 4 || rel[0] !== 'src' || rel[1] !== 'themes') return null;
1435
+ const slug = rel[2];
1436
+ if (rel[3] !== `${camel(slug)}Theme.ts`) return null;
1437
+ return fs.existsSync(themeFiles(root, slug).settings) ? {root, slug} : null;
1438
+ }
1439
+
1440
+ /**
1441
+ * For `compile` of an editor theme: `appCopyStale` for its result data when
1442
+ * the app copy is behind (the same line set and show give); null for any
1443
+ * other file or a current copy.
1444
+ * @param {string} file the path as given
1445
+ * @param {string} cwd
1446
+ * @param {{check: boolean, upToDate?: boolean}} opts `upToDate`: the
1447
+ * check's own verdict on the theme's outputs
1448
+ * @returns {Promise<Record<string, unknown> | null>}
1449
+ */
1450
+ export async function editorBuildExtra(file, cwd, opts) {
1451
+ const root = projectRoot(cwd);
1452
+ const abs = path.resolve(cwd, file);
1453
+ const own = editorThemeAt(root, abs);
1454
+ const slug =
1455
+ appCopyTheme(root, abs)?.slug ??
1456
+ (own && editorOwnFile(own.slug, file) ? own.slug : null);
1457
+ if (!slug) return null;
1458
+ if (opts.check) {
1459
+ // A theme output that is stale is the check's own finding (it names
1460
+ // the file); the copy is compared only with a current build.
1461
+ if (opts.upToDate === false) return null;
1462
+ /** @type {string[] | null} */
1463
+ let fonts;
1464
+ try {
1465
+ fonts = copyFontsCss(await context(root), slug, loadTheme(root, slug));
1466
+ } catch {
1467
+ fonts = null;
1468
+ }
1469
+ const behind = appCopyBehind(root, slug, fonts);
1470
+ return behind
1471
+ ? {
1472
+ upToDate: false,
1473
+ code: 'ERR_THEME_STALE',
1474
+ // Something of yours in the way: its own line says what to move;
1475
+ // no editor command writes over it.
1476
+ appCopyStale: appCopyStale(root, slug).appCopyStale
1477
+ ? `${slug}'s app copy in src/themes/${slug}/ is not up to date: ${behind}`
1478
+ : `${slug}'s app copy in src/themes/${slug}/ is not up to date: ${behind}. ${runLine(root, `experimental theme editor show ${slug}`)} writes it again`,
1479
+ }
1480
+ : null;
1481
+ }
1482
+ const stale = appCopyStale(root, slug).appCopyStale;
1483
+ return stale ? {appCopyStale: stale} : null;
1484
+ }
1485
+
1486
+ /**
1487
+ * For `compile` of an editor theme's own source (themes/<t>/<t>.theme.ts):
1488
+ * the one color mode a light-only or dark-only theme has, which its source
1489
+ * cannot say, for the build to write into the built module. Null for any
1490
+ * other file (the app copy's source re-exports it from its build).
1491
+ * @param {string} file the path as given
1492
+ * @param {string} cwd
1493
+ * @returns {['light'] | ['dark'] | null}
1494
+ */
1495
+ export function editorColorModes(file, cwd) {
1496
+ const root = projectRoot(cwd);
1497
+ const at = editorThemeAt(root, path.resolve(cwd, file));
1498
+ if (!at || path.basename(file) !== `${at.slug}.theme.ts`) return null;
1499
+ return buildColorModes(at.root, at.slug);
1500
+ }
1501
+
1502
+ /**
1503
+ * For `compile` of an editor theme (themes/<t>/ or its app copy's source):
1504
+ * whether a font family is loaded by the app copy's font stylesheet as
1505
+ * this compile writes it (src/themes/<t>/<t>.fonts.css, from the fonts the
1506
+ * theme loads now: an @fontsource package by its name, a stylesheet by the
1507
+ * `family=` it requests), so the build's "named but not loaded" notice
1508
+ * leaves it out. Null for any other file.
1509
+ * @param {string} file the path as given
1510
+ * @param {string} cwd
1511
+ * @returns {Promise<((family: string) => boolean) | null>}
1512
+ */
1513
+ export async function editorLoadedFonts(file, cwd) {
1514
+ const root = projectRoot(cwd);
1515
+ const abs = path.resolve(cwd, file);
1516
+ const slug =
1517
+ appCopyTheme(root, abs)?.slug ??
1518
+ (editorThemeAt(root, abs) &&
1519
+ editorOwnFile(editorThemeAt(root, abs)?.slug ?? '', file)
1520
+ ? editorThemeAt(root, abs)?.slug
1521
+ : null);
1522
+ if (!slug) return null;
1523
+ /** @param {string} s */
1524
+ const key = s =>
1525
+ String(s)
1526
+ .replace(/["']/g, '')
1527
+ .toLowerCase()
1528
+ .replace(/[^a-z0-9]/g, '');
1529
+ /** @type {Set<string>} */
1530
+ const loaded = new Set();
1531
+ // The stylesheets the copy's font file imports once this compile has
1532
+ // written it: from the fonts the theme loads now (a package installed or
1533
+ // removed since the last write), as the copy write computes them.
1534
+ /** @type {string[]} */
1535
+ let specs;
1536
+ try {
1537
+ specs = copyFontsCss(await context(root), slug, loadTheme(root, slug));
1538
+ } catch {
1539
+ try {
1540
+ specs = [
1541
+ ...fs
1542
+ .readFileSync(
1543
+ path.join(root, 'src', 'themes', slug, `${slug}.fonts.css`),
1544
+ 'utf8',
1545
+ )
1546
+ .matchAll(/@import\s+"([^"]+)"/g),
1547
+ ].map(m => m[1]);
1548
+ } catch {
1549
+ return null;
1550
+ }
1551
+ }
1552
+ const req = createRequire(path.join(root, 'package.json'));
1553
+ for (const spec of specs) {
1554
+ const pkg = /^@fontsource(?:-variable)?\/([^/]+)/.exec(spec);
1555
+ if (pkg) {
1556
+ loaded.add(key(pkg[1]));
1557
+ continue;
1558
+ }
1559
+ try {
1560
+ const css = fs.readFileSync(req.resolve(spec), 'utf8');
1561
+ for (const f of css.matchAll(/family=([^:&'")]+)/g))
1562
+ loaded.add(key(decodeURIComponent(f[1].replace(/\+/g, ' '))));
1563
+ } catch {
1564
+ // A stylesheet that cannot be read loads nothing known here.
1565
+ }
1566
+ }
1567
+ return family => loaded.has(key(family));
1568
+ }
1569
+
968
1570
  /**
969
1571
  * For `compile` of a file that is not there: when it is an editor theme's
970
1572
  * own source (`themes/<t>/<t>.theme.ts` beside its settings), the command
@@ -974,6 +1576,37 @@ export async function editorThemeHold(files, {cwd}) {
974
1576
  * @returns {{name: string, reason: string} | null}
975
1577
  */
976
1578
  export function editorMissingSource(file, cwd) {
1579
+ // The app copy's source of an editor theme, its folder gone: the editor
1580
+ // writes it again.
1581
+ const copy = appCopyTheme(projectRoot(cwd), path.resolve(cwd, slashed(file)));
1582
+ if (copy)
1583
+ // A copy file named with Windows separators: the theme is what
1584
+ // compiles (the copy follows); with the copy gone, show writes it.
1585
+ return fs.existsSync(path.join(copy.root, 'src', 'themes', copy.slug))
1586
+ ? {
1587
+ name: runLine(
1588
+ cwd,
1589
+ `experimental theme compile ${
1590
+ path
1591
+ .relative(
1592
+ cwd,
1593
+ path.join(
1594
+ copy.root,
1595
+ 'themes',
1596
+ copy.slug,
1597
+ `${copy.slug}.theme.ts`,
1598
+ ),
1599
+ )
1600
+ .split(path.sep)
1601
+ .join('/') || `themes/${copy.slug}/${copy.slug}.theme.ts`
1602
+ }`,
1603
+ ),
1604
+ reason: `${copy.slug}'s app copy follows every compile of the theme`,
1605
+ }
1606
+ : {
1607
+ name: runLine(cwd, `experimental theme editor show ${copy.slug}`),
1608
+ reason: `the editor writes ${copy.slug}'s app copy in src/themes/${copy.slug}/ again`,
1609
+ };
977
1610
  const at = editorThemeAt(projectRoot(cwd), path.resolve(cwd, file));
978
1611
  if (!at || path.basename(file) !== `${at.slug}.theme.ts`) return null;
979
1612
  return {