@astryxdesign/cli 0.7.18-canary.gfca8508 → 0.7.18

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 (341) hide show
  1. package/CHANGELOG.md +185 -19
  2. package/README.md +19 -19
  3. package/api/component/_adapter.d.mts +2 -1
  4. package/api/component/_adapter.mjs +2 -1
  5. package/api/docs/_adapter.d.mts +6 -5
  6. package/api/docs/_adapter.mjs +36 -5
  7. package/api/doctor/_adapter.d.mts +6 -3
  8. package/api/doctor/_adapter.mjs +13 -5
  9. package/api/doctor/doctor.mjs +2 -2
  10. package/api/doctor/font-packages.d.mts +36 -0
  11. package/api/doctor/font-packages.mjs +124 -0
  12. package/api/doctor/theme-checks.mjs +110 -49
  13. package/api/experimental.d.mts +0 -2
  14. package/api/experimental.mjs +0 -12
  15. package/api/icon/_adapter.d.mts +1 -1
  16. package/api/icon/_adapter.mjs +1 -0
  17. package/api/icon/_authoring.mjs +17 -8
  18. package/api/icon/_default-look.mjs +15 -15
  19. package/api/icon/add/add.mjs +9 -4
  20. package/api/icon/exportIconIndex.doc.mjs +1 -1
  21. package/api/icon/icon.doc.mjs +1 -1
  22. package/api/icon/icon.type.d.mts +33 -33
  23. package/api/icon/icon.type.mjs +45 -45
  24. package/api/icon/iconAdd.doc.mjs +1 -1
  25. package/api/icon/iconNewSet.doc.mjs +3 -3
  26. package/api/icon/iconUse.doc.mjs +5 -5
  27. package/api/icon/rankIconIndex.doc.mjs +1 -1
  28. package/api/icon/use/use.mjs +4 -4
  29. package/api/init/run/run.mjs +0 -1
  30. package/api/integration/add-helpers.mjs +1 -1
  31. package/api/render/_adapter.mjs +7 -1
  32. package/api/search/ORDERING.md +1 -1
  33. package/api/search/_candidate-score.mjs +20 -0
  34. package/api/search/_words.d.mts +8 -0
  35. package/api/search/_words.mjs +15 -0
  36. package/api/template/template.type.d.mts +2 -2
  37. package/api/template/template.type.mjs +2 -2
  38. package/api/theme/_adapter.mjs +19 -11
  39. package/api/theme/build/build.d.mts +19 -51
  40. package/api/theme/build/build.mjs +195 -189
  41. package/api/theme/build/font-warning.d.mts +19 -2
  42. package/api/theme/build/font-warning.mjs +46 -5
  43. package/api/theme/generateTonalPalette.doc.mjs +1 -1
  44. package/api/theme/palette/generate/derive-look.mjs +108 -37
  45. package/api/theme/palette/generate/mapping.mjs +2 -0
  46. package/api/theme/template/template.d.mts +0 -17
  47. package/api/theme/template/template.mjs +1 -42
  48. package/api/theme/theme.type.d.mts +5 -4
  49. package/api/theme/theme.type.mjs +5 -4
  50. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  51. package/api/theme/themeRemove.doc.mjs +1 -1
  52. package/assets/codemods/transforms/v0.7.0/preserve-bottom-sheet-content-padding.mjs +3 -1
  53. package/assets/component-list.generated.json +1 -1
  54. package/assets/discover/official-packages.json +26 -2
  55. package/assets/docs/author-a-theme.doc.mjs +6 -5
  56. package/assets/docs/browser-support.doc.mjs +1 -0
  57. package/assets/docs/icons.doc.mjs +8 -7
  58. package/assets/docs/motion.doc.mjs +46 -0
  59. package/assets/docs/theme.doc.dense.mjs +6 -17
  60. package/assets/docs/theme.doc.mjs +6 -16
  61. package/assets/docs/theme.doc.zh.mjs +6 -16
  62. package/assets/docs/tree/ci-and-containers.doc.mjs +1 -1
  63. package/assets/docs/tree/font-setup.doc.mjs +30 -0
  64. package/assets/docs/tree/icon-sets.doc.mjs +1 -1
  65. package/assets/docs/tree/template-icons.doc.mjs +3 -3
  66. package/assets/docs/tree/tokens-color.doc.mjs +5 -0
  67. package/assets/docs/tree/tokens.doc.mjs +4 -3
  68. package/assets/docs/tree/updates.doc.mjs +1 -1
  69. package/assets/docs-routes.generated.json +1 -1
  70. package/assets/docs.generated.json +2 -2
  71. package/assets/icons/definitions/drag.doc.mjs +1 -0
  72. package/assets/search-catalog.generated.json +2 -2
  73. package/assets/self-audit.generated.json +1 -1
  74. package/assets/templates/blocks/components/Card/SelectableCardElevated.doc.mjs +1 -1
  75. package/assets/templates/blocks/components/Card/SelectableCardElevated.tsx +20 -10
  76. package/assets/templates/blocks/components/Card/SelectableCardShowcase.doc.mjs +1 -1
  77. package/assets/templates/blocks/components/Card/SelectableCardShowcase.tsx +36 -16
  78. package/assets/templates/blocks/components/ChatComposerInput/ChatComposerInputMentionTrigger.tsx +6 -0
  79. package/assets/templates/blocks/components/ChatComposerInput/ChatComposerInputMultipleTriggers.tsx +6 -0
  80. package/assets/templates/blocks/components/Hooks/useIndicatorFocusRingHookUsage.doc.mjs +14 -0
  81. package/assets/templates/blocks/components/Hooks/useIndicatorFocusRingHookUsage.tsx +63 -0
  82. package/assets/templates/blocks/components/Hooks/useLongPressHookUsage.doc.mjs +29 -0
  83. package/assets/templates/blocks/components/Hooks/useLongPressHookUsage.tsx +237 -0
  84. package/assets/templates/blocks/components/SideNav/SideNavShowcase.tsx +10 -72
  85. package/assets/templates/blocks/components/SideNav/SideNavWithHeaderMenu.doc.mjs +1 -1
  86. package/assets/templates/blocks/components/SideNav/SideNavWithHeaderMenu.tsx +7 -7
  87. package/assets/templates/blocks/components/Table/TableCustomRowTable.doc.mjs +14 -0
  88. package/assets/templates/blocks/components/Table/TableCustomRowTable.tsx +96 -0
  89. package/assets/templates/components.generated.json +1 -1
  90. package/assets/templates/pages/ai-chat-landing/page.tsx +4 -0
  91. package/assets/templates/pages/dashboard-scorecard/page.tsx +26 -7
  92. package/assets/templates/pages/editor/page.tsx +13 -3
  93. package/assets/templates/themes/butter/butterPaletteRefs.generated.ts +2 -2
  94. package/assets/templates/themes/butter/butterTheme.ts +12 -10
  95. package/assets/templates/themes/butter/icons.tsx +2 -0
  96. package/assets/templates/themes/chocolate/chocolateTheme.ts +1 -0
  97. package/assets/templates/themes/chocolate/icons.tsx +2 -0
  98. package/assets/templates/themes/gothic/gothicPaletteRefs.generated.ts +1 -1
  99. package/assets/templates/themes/gothic/gothicTheme.ts +1 -0
  100. package/assets/templates/themes/gothic/icons.tsx +2 -0
  101. package/assets/templates/themes/matcha/icons.tsx +2 -0
  102. package/assets/templates/themes/matcha/matchaPaletteRefs.generated.ts +2 -2
  103. package/assets/templates/themes/matcha/matchaTheme.ts +1 -0
  104. package/assets/templates/themes/neutral/icons.tsx +2 -0
  105. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +2 -2
  106. package/assets/templates/themes/neutral/neutralTheme.ts +1 -0
  107. package/assets/templates/themes/stone/icons.tsx +2 -0
  108. package/assets/templates/themes/stone/stonePaletteRefs.generated.ts +1 -1
  109. package/assets/templates/themes/stone/stoneTheme.ts +1 -0
  110. package/assets/templates/themes/y2k/icons.tsx +2 -0
  111. package/assets/templates/themes/y2k/y2kTheme.ts +1 -0
  112. package/assets/theme.template.ts +9 -5
  113. package/authoring/config/parse.mjs +1 -1
  114. package/authoring/doctypes/base/type.ts +2 -3
  115. package/authoring/doctypes/component/component.doc.mjs +1 -1
  116. package/authoring/doctypes/icon-set/icon-names.mjs +1 -0
  117. package/authoring/integration/integration.doc.mjs +1 -1
  118. package/authoring/integration/type.ts +1 -1
  119. package/clients/cli/build-id.generated.json +1 -1
  120. package/clients/cli/commands/experimental/icon.mjs +7 -7
  121. package/clients/cli/commands/experimental/index.mjs +0 -5
  122. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +2 -2
  123. package/clients/cli/commands/experimental-icon-use.doc.mjs +4 -4
  124. package/clients/cli/commands/experimental-icon.doc.mjs +1 -1
  125. package/clients/cli/commands/experimental.doc.mjs +2 -6
  126. package/clients/cli/commands/template.mjs +1 -1
  127. package/clients/cli/commands/theme-build.doc.mjs +8 -1
  128. package/clients/cli/commands/theme-palette-generate.doc.mjs +1 -1
  129. package/clients/cli/commands/theme-remove.doc.mjs +1 -1
  130. package/clients/cli/commands/theme.doc.mjs +1 -11
  131. package/clients/cli/commands/theme.mjs +110 -475
  132. package/clients/cli/commands.generated.json +1 -1
  133. package/clients/cli/index.mjs +4 -34
  134. package/clients/cli/lib/base-gate.mjs +2 -3
  135. package/clients/cli/lib/cli-error.mjs +8 -72
  136. package/clients/cli/lib/define-command.mjs +0 -19
  137. package/clients/cli/lib/json-shim.mjs +11 -633
  138. package/clients/cli/lib/manifest.mjs +0 -4
  139. package/clients/cli/lib/stray-option.mjs +1 -2
  140. package/clients/cli/manifest.generated.json +1 -1
  141. package/foundation/agent-docs/agent-docs.mjs +1 -1
  142. package/foundation/color/css-color.mjs +2 -3
  143. package/foundation/discovery/app-layout.d.mts +13 -0
  144. package/foundation/discovery/app-layout.mjs +35 -0
  145. package/foundation/discovery/fixture-refs.d.mts +51 -0
  146. package/foundation/discovery/fixture-refs.mjs +351 -0
  147. package/foundation/discovery/icon-definition-discovery.mjs +1 -1
  148. package/foundation/discovery/icon-ranking.mjs +2 -2
  149. package/foundation/discovery/icon-set-checks.mjs +1 -1
  150. package/foundation/discovery/icon-set-discovery.mjs +1 -1
  151. package/foundation/discovery/icon-set-writer.d.mts +24 -7
  152. package/foundation/discovery/icon-set-writer.mjs +66 -22
  153. package/foundation/discovery/static-descriptor.d.mts +49 -0
  154. package/foundation/discovery/static-descriptor.mjs +548 -0
  155. package/foundation/discovery/template-adapter.d.mts +0 -47
  156. package/foundation/discovery/template-adapter.mjs +1 -333
  157. package/foundation/discovery/theme-discovery.d.mts +6 -47
  158. package/foundation/discovery/theme-discovery.mjs +15 -537
  159. package/foundation/doc-compiler/import.mjs +1 -1
  160. package/foundation/env/user-dirs.d.mts +5 -2
  161. package/foundation/env/user-dirs.mjs +12 -5
  162. package/foundation/fonts/next-font.d.mts +26 -0
  163. package/foundation/fonts/next-font.mjs +149 -0
  164. package/foundation/fs/empty-folder.mjs +2 -2
  165. package/foundation/fs/read-record.mjs +11 -4
  166. package/foundation/pictures/pictures.d.mts +1 -45
  167. package/foundation/pictures/pictures.mjs +8 -8
  168. package/foundation/release/folder-lock.mjs +3 -2
  169. package/foundation/render/cut-short.d.mts +2 -2
  170. package/foundation/render/cut-short.mjs +2 -2
  171. package/foundation/render/drawn-contrast.d.mts +2 -2
  172. package/foundation/render/drawn-contrast.mjs +2 -2
  173. package/foundation/render/font-probe.d.mts +2 -2
  174. package/foundation/render/font-probe.mjs +2 -2
  175. package/foundation/render/layers.mjs +1 -2
  176. package/foundation/render/package-resolve-hooks.d.mts +25 -5
  177. package/foundation/render/package-resolve-hooks.mjs +77 -14
  178. package/foundation/render/page-worker.mjs +24 -12
  179. package/foundation/render/part-boxes.d.mts +2 -3
  180. package/foundation/render/part-boxes.mjs +2 -3
  181. package/foundation/render/picture-chrome.mjs +5 -0
  182. package/foundation/render/render-page.d.mts +1 -1
  183. package/foundation/render/render-page.mjs +4 -5
  184. package/foundation/render/single-copy-hooks.d.mts +2 -0
  185. package/foundation/render/single-copy-hooks.mjs +2 -0
  186. package/foundation/response/error-codes.doc.mjs +14 -14
  187. package/foundation/response/error-codes.mjs +13 -13
  188. package/foundation/response/response-types.doc.mjs +7 -68
  189. package/foundation/runtime/css-tree.mjs +2 -2
  190. package/foundation/runtime/word-table.d.mts +1 -1
  191. package/foundation/runtime/word-table.mjs +1 -1
  192. package/foundation/suggest/other-command.d.mts +52 -15
  193. package/foundation/suggest/other-command.mjs +168 -45
  194. package/foundation/text/suggest-order.d.mts +7 -0
  195. package/foundation/text/suggest-order.mjs +1 -1
  196. package/package.json +7 -8
  197. package/api/theme-edit/_adapter.d.mts +0 -228
  198. package/api/theme-edit/_adapter.mjs +0 -2025
  199. package/api/theme-edit/_catalog.d.mts +0 -172
  200. package/api/theme-edit/_catalog.mjs +0 -806
  201. package/api/theme-edit/_check.d.mts +0 -391
  202. package/api/theme-edit/_check.mjs +0 -9370
  203. package/api/theme-edit/_color.d.mts +0 -135
  204. package/api/theme-edit/_color.mjs +0 -480
  205. package/api/theme-edit/_compiler.d.mts +0 -77
  206. package/api/theme-edit/_compiler.mjs +0 -1053
  207. package/api/theme-edit/_context.d.mts +0 -399
  208. package/api/theme-edit/_context.mjs +0 -1778
  209. package/api/theme-edit/_css.d.mts +0 -169
  210. package/api/theme-edit/_css.mjs +0 -1167
  211. package/api/theme-edit/_edit.d.mts +0 -167
  212. package/api/theme-edit/_edit.mjs +0 -11220
  213. package/api/theme-edit/_how-commands.d.mts +0 -315
  214. package/api/theme-edit/_how-commands.mjs +0 -1664
  215. package/api/theme-edit/_how-question.d.mts +0 -341
  216. package/api/theme-edit/_how-question.mjs +0 -33339
  217. package/api/theme-edit/_how-sides.d.mts +0 -22
  218. package/api/theme-edit/_how-sides.mjs +0 -173
  219. package/api/theme-edit/_how-steps.d.mts +0 -42
  220. package/api/theme-edit/_how-steps.mjs +0 -208
  221. package/api/theme-edit/_how-values.d.mts +0 -29
  222. package/api/theme-edit/_how-values.mjs +0 -111
  223. package/api/theme-edit/_how-words.d.mts +0 -15
  224. package/api/theme-edit/_how-words.mjs +0 -239
  225. package/api/theme-edit/_how.d.mts +0 -55
  226. package/api/theme-edit/_how.mjs +0 -2388
  227. package/api/theme-edit/_importers.d.mts +0 -38
  228. package/api/theme-edit/_importers.mjs +0 -188
  229. package/api/theme-edit/_marks.d.mts +0 -39
  230. package/api/theme-edit/_marks.mjs +0 -67
  231. package/api/theme-edit/_missed.d.mts +0 -56
  232. package/api/theme-edit/_missed.mjs +0 -1128
  233. package/api/theme-edit/_name-rule.d.mts +0 -11
  234. package/api/theme-edit/_name-rule.mjs +0 -12
  235. package/api/theme-edit/_normal.d.mts +0 -365
  236. package/api/theme-edit/_normal.mjs +0 -1978
  237. package/api/theme-edit/_overview.d.mts +0 -9
  238. package/api/theme-edit/_overview.mjs +0 -293
  239. package/api/theme-edit/_palette.d.mts +0 -616
  240. package/api/theme-edit/_palette.mjs +0 -2776
  241. package/api/theme-edit/_part-pieces.d.mts +0 -54
  242. package/api/theme-edit/_part-pieces.mjs +0 -179
  243. package/api/theme-edit/_part-words.d.mts +0 -39
  244. package/api/theme-edit/_part-words.mjs +0 -242
  245. package/api/theme-edit/_parts.d.mts +0 -402
  246. package/api/theme-edit/_parts.mjs +0 -2322
  247. package/api/theme-edit/_picture-traits.d.mts +0 -259
  248. package/api/theme-edit/_picture-traits.mjs +0 -1030
  249. package/api/theme-edit/_png.d.mts +0 -94
  250. package/api/theme-edit/_png.mjs +0 -479
  251. package/api/theme-edit/_preview-app.d.mts +0 -172
  252. package/api/theme-edit/_preview-app.mjs +0 -6430
  253. package/api/theme-edit/_preview.d.mts +0 -484
  254. package/api/theme-edit/_preview.mjs +0 -2775
  255. package/api/theme-edit/_project.d.mts +0 -207
  256. package/api/theme-edit/_project.mjs +0 -643
  257. package/api/theme-edit/_resolved.d.mts +0 -46
  258. package/api/theme-edit/_resolved.mjs +0 -800
  259. package/api/theme-edit/_set-line.d.mts +0 -29
  260. package/api/theme-edit/_set-line.mjs +0 -100
  261. package/api/theme-edit/_settings.d.mts +0 -2426
  262. package/api/theme-edit/_settings.mjs +0 -18449
  263. package/api/theme-edit/_tables.d.mts +0 -227
  264. package/api/theme-edit/_tables.mjs +0 -1128
  265. package/api/theme-edit/_text-looks.d.mts +0 -78
  266. package/api/theme-edit/_text-looks.mjs +0 -376
  267. package/api/theme-edit/_vet.d.mts +0 -50
  268. package/api/theme-edit/_vet.mjs +0 -166
  269. package/api/theme-edit/how/how.d.mts +0 -17
  270. package/api/theme-edit/how/how.mjs +0 -28
  271. package/api/theme-edit/new/new.d.mts +0 -11
  272. package/api/theme-edit/new/new.mjs +0 -22
  273. package/api/theme-edit/preview-add/preview-add.d.mts +0 -14
  274. package/api/theme-edit/preview-add/preview-add.mjs +0 -25
  275. package/api/theme-edit/preview-app/preview-app.d.mts +0 -13
  276. package/api/theme-edit/preview-app/preview-app.mjs +0 -24
  277. package/api/theme-edit/preview-list/preview-list.d.mts +0 -10
  278. package/api/theme-edit/preview-list/preview-list.mjs +0 -21
  279. package/api/theme-edit/preview-remove/preview-remove.d.mts +0 -12
  280. package/api/theme-edit/preview-remove/preview-remove.mjs +0 -23
  281. package/api/theme-edit/set/set.d.mts +0 -13
  282. package/api/theme-edit/set/set.mjs +0 -24
  283. package/api/theme-edit/show/show.d.mts +0 -13
  284. package/api/theme-edit/show/show.mjs +0 -24
  285. package/api/theme-edit/theme-edit.d.mts +0 -12
  286. package/api/theme-edit/theme-edit.mjs +0 -36
  287. package/api/theme-edit/theme-edit.type.d.mts +0 -730
  288. package/api/theme-edit/theme-edit.type.mjs +0 -342
  289. package/api/theme-edit/themeEditHow.doc.d.mts +0 -6
  290. package/api/theme-edit/themeEditHow.doc.mjs +0 -105
  291. package/api/theme-edit/themeEditNew.doc.d.mts +0 -5
  292. package/api/theme-edit/themeEditNew.doc.mjs +0 -112
  293. package/api/theme-edit/themeEditPreviewAdd.doc.d.mts +0 -6
  294. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +0 -121
  295. package/api/theme-edit/themeEditPreviewApp.doc.d.mts +0 -6
  296. package/api/theme-edit/themeEditPreviewApp.doc.mjs +0 -87
  297. package/api/theme-edit/themeEditPreviewList.doc.d.mts +0 -6
  298. package/api/theme-edit/themeEditPreviewList.doc.mjs +0 -62
  299. package/api/theme-edit/themeEditPreviewRemove.doc.d.mts +0 -6
  300. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +0 -96
  301. package/api/theme-edit/themeEditSet.doc.d.mts +0 -6
  302. package/api/theme-edit/themeEditSet.doc.mjs +0 -175
  303. package/api/theme-edit/themeEditShow.doc.d.mts +0 -6
  304. package/api/theme-edit/themeEditShow.doc.mjs +0 -118
  305. package/api/theme-edit/themeEditUndo.doc.d.mts +0 -6
  306. package/api/theme-edit/themeEditUndo.doc.mjs +0 -133
  307. package/api/theme-edit/undo/undo.d.mts +0 -13
  308. package/api/theme-edit/undo/undo.mjs +0 -24
  309. package/assets/preview-app/README.md +0 -6
  310. package/assets/preview-app/css.d.ts +0 -5
  311. package/assets/preview-app/gitignore +0 -4
  312. package/assets/preview-app/next.config.mjs +0 -12
  313. package/assets/preview-app/package.json +0 -24
  314. package/assets/preview-app/src/app/globals.css +0 -6
  315. package/assets/preview-app/src/app/layout.tsx +0 -21
  316. package/assets/preview-app/src/app/page.tsx +0 -94
  317. package/assets/preview-app/src/app/providers.tsx +0 -16
  318. package/assets/preview-app/tsconfig.json +0 -27
  319. package/clients/cli/commands/experimental/theme.mjs +0 -2990
  320. package/clients/cli/commands/experimental-theme-add.doc.mjs +0 -80
  321. package/clients/cli/commands/experimental-theme-compile.doc.mjs +0 -98
  322. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +0 -196
  323. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -174
  324. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +0 -139
  325. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +0 -77
  326. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +0 -105
  327. package/clients/cli/commands/experimental-theme-editor.doc.mjs +0 -49
  328. package/clients/cli/commands/experimental-theme-eject.doc.mjs +0 -72
  329. package/clients/cli/commands/experimental-theme-list.doc.mjs +0 -49
  330. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +0 -88
  331. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +0 -61
  332. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +0 -48
  333. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +0 -59
  334. package/clients/cli/commands/experimental-theme-preview.doc.mjs +0 -41
  335. package/clients/cli/commands/experimental-theme-remove.doc.mjs +0 -57
  336. package/clients/cli/commands/experimental-theme-targets.doc.mjs +0 -62
  337. package/clients/cli/commands/experimental-theme-template.doc.mjs +0 -63
  338. package/clients/cli/commands/experimental-theme-use.doc.mjs +0 -57
  339. package/clients/cli/commands/experimental-theme.doc.mjs +0 -60
  340. package/foundation/fonts/fontsource-families.generated.d.mts +0 -5
  341. package/foundation/fonts/fontsource-families.generated.mjs +0 -2110
@@ -1,2025 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file The theme-edit subject's adapter: the work behind `astryx experimental
5
- * theme editor` and `theme preview`, and the subject's only access to the
6
- * environment (files, the installed Core, the renderer). Each operation's
7
- * work is in an underscore helper that only this file imports; the leaves
8
- * call it.
9
- *
10
- * themeEditNew('brand', {like: 'neutral'}) themeEdit.new
11
- * themeEditSet('brand', 'corners', 'pill') themeEdit.set
12
- * themeEditUndo('brand') themeEdit.undo (one step)
13
- * themeEditUndo('brand', {thing: 'corners'}) themeEdit.undo (one setting)
14
- * themeEditShow('brand') themeEdit.show
15
- * themeEditPreviewAdd('a sales dashboard') themeEdit.previewAdd
16
- * themeEditPreviewApp('theme-app') themeEdit.previewApp
17
- * themeEditPreviewList() themeEdit.previewList
18
- * themeEditPreviewRemove('components') themeEdit.previewRemove
19
- * themeEditHow('banner') themeEdit.how
20
- * themeEditHow('white text in the banner') themeEdit.how (a question)
21
- * themeEditHow('target.png', {at: ['4,8']}) themeEdit.how (a picture)
22
- * themeEditHow('accent', {list: 'tokens'}) themeEdit.how (a list)
23
- *
24
- * Every change is checked first against what the installed Core's parts
25
- * really read; a change that cannot take effect is refused and nothing is
26
- * written. An accepted change rebuilds the theme with the theme build and
27
- * writes a preview.
28
- *
29
- * @input a theme name and a change, a question, or a picture
30
- * @output themeEdit.* envelopes
31
- * @position api/theme-edit — adapter for api/theme-edit/theme-edit.mjs
32
- */
33
-
34
- import {writeThemeTemplate} from '../theme/template/template.mjs';
35
- import {
36
- blankOptionProblem,
37
- buildInputProblem,
38
- buildSuggestion,
39
- realLocation,
40
- refusedOutput,
41
- } from '../theme/build/build.mjs';
42
- import {createHash} from 'node:crypto';
43
- import * as fs from 'node:fs';
44
- import * as path from 'node:path';
45
- import * as edit from './_edit.mjs';
46
- import {
47
- baseInstalled,
48
- installLine,
49
- packageInstalled,
50
- refusePlugAndPlay,
51
- themeCacheRoot,
52
- } from './_project.mjs';
53
- import * as preview from './_preview-app.mjs';
54
- import {AstryxError} from '../error.mjs';
55
- import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
56
- import {findPackageRoot} from '../../foundation/fs/paths.mjs';
57
- import {
58
- baseWeightNotes,
59
- context,
60
- coreApp,
61
- loneFamilyNotes,
62
- } from './_context.mjs';
63
- import {APP_COPY_MARK} from './_marks.mjs';
64
- import {irregularFileKind} from '../../foundation/fs/regular-file.mjs';
65
- import {
66
- fontKey,
67
- importedFontFamilies,
68
- } from '../../foundation/fonts/font-stylesheet.mjs';
69
- import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
70
- import {withFolderLock} from '../../foundation/release/folder-lock.mjs';
71
- import {
72
- getCliInvocation,
73
- quoteCommandArgument,
74
- } from '../../foundation/env/package-manager.mjs';
75
- import {LIKE, P, knowBuiltInThemes} from './_tables.mjs';
76
- import {discoverBundledThemes} from '../../foundation/discovery/theme-discovery.mjs';
77
-
78
- /** The preview command, as a person runs it. */
79
- const PREVIEW_WORDS = P.replace(/ editor$/, ' preview');
80
- import {setLine} from './_check.mjs';
81
- export {modeDialValue} from './_check.mjs';
82
- import {followLine, splitCommand} from './_vet.mjs';
83
- import {
84
- SHOWCASE_GROUPS,
85
- appCopyBehind,
86
- appCopyStale,
87
- copyFontsCss,
88
- takeFirstAppCopy,
89
- writeAppCopy,
90
- writeAppCopyAt,
91
- } from './_preview.mjs';
92
- import {humanWarn} from '../../foundation/response/json.mjs';
93
- import {
94
- buildColorModes,
95
- camel,
96
- folderIsEmpty,
97
- editorMadeFolder,
98
- loadTheme,
99
- setAfterBuild,
100
- editedThemes,
101
- themeFiles,
102
- fontsourcePackageOf,
103
- fontsourceSuggestion,
104
- themeSourceRefusal,
105
- typedThemeName,
106
- } from './_settings.mjs';
107
-
108
- // Every build of a theme writes its app copy (src/themes/<theme>/).
109
- setAfterBuild(writeAppCopy);
110
- import {LOCAL_THEME_ROOT} from '../../foundation/config/theme-state.mjs';
111
-
112
- export {parsePoints} from './_how.mjs';
113
- export {
114
- newFlagList,
115
- checkedChangeLine as editorCheckedLine,
116
- checkedNewLines as editorCheckedNewLines,
117
- checkedShowLines as editorCheckedShowLines,
118
- } from './_edit.mjs';
119
- export {splitCommand} from './_vet.mjs';
120
- import {themeEditHow as howAt} from './_how.mjs';
121
-
122
- /**
123
- * `how`, run at the project root like the other editor commands, so a
124
- * subfolder finds the app's themes. A picture named from the subfolder
125
- * keeps pointing where it was named.
126
- * @param {string} subject
127
- * @param {import('./theme-edit.type.mjs').ThemeEditHowOptions} [options]
128
- * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditHowResponse>}
129
- */
130
- export async function themeEditHow(subject, options = {}) {
131
- const from = options.cwd ?? process.cwd();
132
- const o = atRoot(options);
133
- /** A file named from the subfolder, as a path from anywhere. @param {unknown} name */
134
- const here = name =>
135
- typeof name === 'string' &&
136
- name !== '' &&
137
- !path.isAbsolute(name) &&
138
- path.resolve(from) !== o.cwd &&
139
- fs.existsSync(path.resolve(from, name)) &&
140
- fs.statSync(path.resolve(from, name)).isFile()
141
- ? path.resolve(from, name)
142
- : name;
143
- // The CLI passes the words as typed: the first may be that picture too.
144
- const words = o.words?.length
145
- ? [String(here(o.words[0])), ...o.words.slice(1)]
146
- : o.words;
147
- return howAt(/** @type {string} */ (here(subject)), {
148
- ...o,
149
- ...(words ? {words} : {}),
150
- });
151
- }
152
-
153
- // The built-in themes come from the installed packages: found here, in the
154
- // adapter, and handed to the editor's tables.
155
- knowBuiltInThemes(discoverBundledThemes().map(t => t.slug));
156
-
157
- /** The built-in themes a theme can build on (`--like`). */
158
- export const builtInThemes = () => [...LIKE];
159
-
160
- /**
161
- * The base the editor can start a theme from in a project: `slug` when it
162
- * is a built-in base installed there (the check `new --like` makes), else
163
- * neutral.
164
- * @param {string | null | undefined} slug
165
- * @param {string} cwd
166
- * @returns {string}
167
- */
168
- export const editorBaseIn = (slug, cwd) =>
169
- slug && LIKE.includes(slug) && baseInstalled(cwd, slug) ? slug : 'neutral';
170
-
171
- /** The sections `show --section` takes. */
172
- export const showSections = () => [...SHOWCASE_GROUPS];
173
-
174
- /**
175
- * A free folder for a new starter app here, the one `preview app`'s own
176
- * refusals offer.
177
- * @param {string} cwd
178
- */
179
- export const editorFreeAppFolder = cwd => preview.freeAppFolder(cwd);
180
-
181
- export {
182
- dialTakesText,
183
- dialValueFits,
184
- slugOk as editorNameOk,
185
- usableNewName as editorFreeName,
186
- } from './_settings.mjs';
187
-
188
- /**
189
- * The project a command acts on: the Astryx project at or above `cwd`, found
190
- * as `upgrade` finds it (the nearest package that declares an Astryx package
191
- * in any dependency list; the search stops at a repository root and never
192
- * counts the home folder or above), else `cwd` itself. A package nearer
193
- * than that project that does not use Astryx is refused with the folder to
194
- * run from, and a nearest package.json that does not parse is never walked
195
- * past.
196
- * @param {string} cwd
197
- */
198
- export function projectRoot(cwd) {
199
- const start = path.resolve(cwd);
200
- // One rule: the nearest folder at or above cwd whose package.json lists
201
- // @astryxdesign/core.
202
- const project = coreApp(start);
203
- const pkg = findPackageRoot(start);
204
- const inReach = (/** @type {string} */ dir) =>
205
- project ? !path.relative(project, dir).startsWith('..') : true;
206
- if (pkg && inReach(pkg) && pkg !== project) {
207
- const file = path.join(pkg, 'package.json');
208
- /** @type {any} */
209
- let json;
210
- try {
211
- json = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
212
- } catch (e) {
213
- // Name the file and what the parser says is wrong, with its place.
214
- const rel = path.relative(start, file) || 'package.json';
215
- const why = String(/** @type {Error} */ (e).message ?? '').replace(
216
- /^Unexpected token.*?, /,
217
- '',
218
- );
219
- throw new AstryxError(
220
- `${rel} is not valid JSON (${why}), so the app it belongs to is unknown. Fix it, then run the command again. Nothing was written.`,
221
- [
222
- {
223
- name: `\${EDITOR:-vi} ${quoteCommandArgument(rel)}`,
224
- reason: 'open the file and fix it',
225
- },
226
- ],
227
- ERROR_CODES.ERR_PROJECT_REQUIRED,
228
- );
229
- }
230
- // A package.json that only sets the module type (no name, no
231
- // dependencies) is a folder setting, not another package.
232
- const trivial =
233
- json?.name == null &&
234
- !['dependencies', 'devDependencies', 'peerDependencies'].some(
235
- k => json?.[k] != null,
236
- );
237
- if (project && !trivial)
238
- throw new AstryxError(
239
- `${path.relative(start, file) || 'package.json'} is a package that does not use Astryx; the app that does is ${path.relative(start, project) || '.'}. Run the command from there, so the theme lands in that app. Nothing was written.`,
240
- [
241
- {
242
- name: `cd ${quoteCommandArgument(path.relative(start, project))}`,
243
- reason: 'do this first',
244
- },
245
- ],
246
- ERROR_CODES.ERR_PROJECT_REQUIRED,
247
- );
248
- }
249
- return project ?? start;
250
- }
251
-
252
- /**
253
- * Where a project's locks are: the `.cache` of the node_modules holding
254
- * the Core the command reads (the project's own, or a workspace root's), shared by
255
- * every shell and user that can change the project, outside the source
256
- * tree. Null outside a project or without Core (nothing can be written
257
- * then, so there is nothing to keep apart). A folder that
258
- * cannot be written is refused, naming it.
259
- * @param {string} root
260
- * @returns {string | null}
261
- */
262
- function lockDir(root) {
263
- // The Core the command reads decides where; outside a project there is
264
- // none, and no lock.
265
- if (isOutsideProject(root)) return null;
266
- const cache = themeCacheRoot(root);
267
- if (!cache) return null;
268
- const dir = path.join(cache, 'locks');
269
- try {
270
- fs.mkdirSync(dir, {recursive: true});
271
- fs.accessSync(dir, fs.constants.W_OK);
272
- return dir;
273
- } catch (e) {
274
- throw new AstryxError(
275
- `Could not write ${path.relative(root, dir)} (${/** @type {any} */ (e).code ?? String(e)}), where the lock that keeps two commands on one theme apart is kept. Fix its permission, then run the command again. Nothing was changed.`,
276
- [
277
- {
278
- name: `ls -ld ${quoteCommandArgument(dir)}`,
279
- reason: 'see who owns the lock folder',
280
- },
281
- ],
282
- ERROR_CODES.ERR_WRITE_FAILED,
283
- );
284
- }
285
- }
286
-
287
- /**
288
- * Run `fn` holding a lock named `name` for the project at `root`, so two
289
- * commands on one theme (or one preview) run one after the other: each one
290
- * reads what the other wrote. The lock is a folder in the project's
291
- * node_modules/.cache; a lock left by a command that is no longer running
292
- * is taken over.
293
- * @template T
294
- * @param {string} root
295
- * @param {string} name
296
- * @param {(locked: boolean) => Promise<T>} fn called with whether the lock
297
- * is held
298
- * @param {boolean} [bestEffort] a command that can run read-only runs
299
- * without the lock when it cannot be taken (a read-only node_modules),
300
- * told so, and then writes nothing
301
- * @param {string | null} [again] the command's own words after the CLI
302
- * name, to suggest running it again (never the host process's argv: an
303
- * API caller is not a CLI run)
304
- * @returns {Promise<T>}
305
- */
306
- async function withLock(root, name, fn, bestEffort = false, again = null) {
307
- // A preview command, which holds the preview lock, suggests the list of
308
- // previews (what the other command may be changing).
309
- again ??= name === 'preview' ? 'experimental theme preview list' : null;
310
- // A Plug'n'Play app has no node_modules to keep the lock in, and the editor
311
- // refuses it: refuse before any lock folder, read-only commands included.
312
- if (!isOutsideProject(root)) refusePlugAndPlay(root);
313
- /** @type {string | null} */
314
- let dir;
315
- try {
316
- dir = lockDir(root);
317
- } catch (e) {
318
- if (bestEffort) return fn(false);
319
- throw e;
320
- }
321
- if (!dir) return fn(true);
322
- // The lock is named for the project as seen from the lock folder (which
323
- // lives in the project's own node_modules), not by the path this command
324
- // was given: one project reached through two paths (a bind mount, a
325
- // devcontainer) has one lock.
326
- /** @param {string} p */
327
- const real = p => {
328
- try {
329
- return fs.realpathSync(p);
330
- } catch {
331
- return path.resolve(p);
332
- }
333
- };
334
- const key = createHash('sha256')
335
- .update(path.relative(real(dir), real(root)).split(path.sep).join('/'))
336
- .digest('hex')
337
- .slice(0, 16);
338
- const lock = path.join(dir, `${key}-${name}.lock`);
339
- // The release cache's lock, held with its lease while the command runs
340
- // (foundation/release/folder-lock.mjs). A lock naming this pid is never
341
- // taken over on that ground alone: two containers on one checkout can
342
- // both be pid 1.
343
- let started = false;
344
- try {
345
- return await withFolderLock(
346
- lock,
347
- async () => {
348
- started = true;
349
- return fn(true);
350
- },
351
- {
352
- onBusy: (o, held) => {
353
- throw new AstryxError(
354
- `Another command has been changing ${name.replace(/^theme-/, '')} for 30 seconds${o ? ` (process ${o.pid} on ${o.host}${held != null ? `, holding it ${held} s` : ''})` : ''}. Nothing was changed; run this command again once the other one ends. If no astryx command is running, the lock is left from one that stopped: remove the folder ${lock}.`,
355
- // Every editor command (show too) takes this lock, so none of
356
- // them works meanwhile: this same command, once the other ends.
357
- again
358
- ? [
359
- {
360
- name: runLine(root, again),
361
- reason: 'run it again once the other command ends',
362
- },
363
- ]
364
- : [],
365
- ERROR_CODES.ERR_THEME_BUSY,
366
- );
367
- },
368
- },
369
- );
370
- } catch (e) {
371
- if (e instanceof AstryxError) throw e;
372
- const code = /** @type {any} */ (e)?.code;
373
- if (!started) {
374
- if (bestEffort) return fn(false);
375
- throw new AstryxError(
376
- `Could not take the lock ${lock} (${code ?? String(e)}). Nothing was changed; fix the folder, then run the command again.`,
377
- [
378
- {
379
- name: `ls -ld ${quoteCommandArgument(path.dirname(lock))}`,
380
- reason: 'see who owns the lock folder',
381
- },
382
- ],
383
- ERROR_CODES.ERR_WRITE_FAILED,
384
- );
385
- }
386
- // A folder that cannot be written (no permission, a full or read-only
387
- // disk) is a documented refusal, not a crash.
388
- if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO'].includes(code))
389
- throw new AstryxError(
390
- `Could not write ${path.relative(root, /** @type {any} */ (e).path ?? '') || 'the theme files'}: ${code === 'ENOSPC' ? 'the disk is full' : code === 'EROFS' ? 'the disk is read-only' : code === 'EIO' ? 'the disk could not be read or written' : 'no permission'}. ${code === 'EROFS' ? 'Make the folder writable' : code === 'EIO' ? 'Check the disk' : 'Free the space or fix the permission'}, then run the command again; a refused change is undone.`,
391
- [
392
- {
393
- name: `ls -ld ${quoteCommandArgument(path.dirname(/** @type {any} */ (e).path ?? path.join(root, 'themes', 'x')))}`,
394
- reason: 'see who owns the folder and whether it is writable',
395
- },
396
- ],
397
- ERROR_CODES.ERR_WRITE_FAILED,
398
- );
399
- throw e;
400
- }
401
- }
402
-
403
- /**
404
- * Options with `cwd` moved to the project root, and a `--path` given from a
405
- * subfolder kept pointing where it was given.
406
- * @template {{cwd?: string, path?: string}} O
407
- * @param {O} options
408
- * @returns {O & {cwd: string}}
409
- */
410
- function atRoot(options) {
411
- const from = options.cwd ?? process.cwd();
412
- const cwd = projectRoot(from);
413
- return {
414
- ...options,
415
- cwd,
416
- ...(options.path != null && options.path !== ''
417
- ? {path: path.relative(cwd, path.resolve(from, options.path)) || '.'}
418
- : {}),
419
- };
420
- }
421
-
422
- /** @param {any} name */
423
- const lockName = name =>
424
- `theme-${String(name ?? '')
425
- .replace(/[^a-z0-9-]/gi, '_')
426
- .slice(0, 80)}`;
427
-
428
- /**
429
- * A result whose theme paths read from the project root, made absolute when
430
- * the command ran in a folder below that root, so a path in the reply
431
- * points at the file wherever the person is.
432
- * @template T
433
- * @param {T} result
434
- * @param {string} root
435
- * @param {string} from
436
- * @returns {T}
437
- */
438
- function absolute(result, root, from) {
439
- if (path.resolve(from) === root) return result;
440
- /**
441
- * Lines that name project files inside them: `see`, a picture note, the
442
- * in-app preview's stale entries. Every project path in them (a theme
443
- * file, an in-app preview folder) is made absolute, one style per line.
444
- */
445
- const PROSE = new Set(['see', 'pictureProblem', 'previewStale', 'wiring']);
446
- /** A project-relative path that names a file or folder there. @param {string} p */
447
- const inRoot = p => {
448
- const bare = p.replace(/\/+$/, '');
449
- return (
450
- Boolean(bare) &&
451
- !path.isAbsolute(bare) &&
452
- !bare.startsWith('.') &&
453
- fs.existsSync(path.join(root, bare))
454
- );
455
- };
456
- /** @param {any} v @param {string} [key] @returns {any} */
457
- const map = (v, key) =>
458
- typeof v === 'string'
459
- ? // A path alone; a line that starts with one is read as prose below.
460
- /^themes\/\S*$/.test(v) && !(key && PROSE.has(key))
461
- ? path.join(root, v)
462
- : key && PROSE.has(key)
463
- ? previewCommandsFrom(v, root, from).replace(
464
- /(^|[\s(,])((?:themes|src|app)\/[^\s,;)]*)/g,
465
- (all, before, file) =>
466
- /^themes\//.test(file) || inRoot(file)
467
- ? `${before}${path.join(root, file)}`
468
- : all,
469
- )
470
- : previewCommandsFrom(v, root, from)
471
- : Array.isArray(v)
472
- ? v.map(x => map(x, key))
473
- : v && typeof v === 'object'
474
- ? Object.fromEntries(
475
- Object.entries(v).map(([k, x]) => [k, map(x, k)]),
476
- )
477
- : v;
478
- return map(result);
479
- }
480
-
481
- /**
482
- * Run an editor command at the project root, holding `lock` when one is
483
- * named, with paths in the reply that work from where it ran.
484
- * @template {{cwd?: string, path?: string}} O
485
- * @template T
486
- * @param {O} options
487
- * @param {string | null} lock
488
- * @param {(o: O & {cwd: string}) => Promise<T>} fn
489
- * @param {boolean} [bestEffort]
490
- * @param {string | null} [again] the command's own words, for a busy lock
491
- * @returns {Promise<T>}
492
- */
493
- async function inProject(options, lock, fn, bestEffort = false, again = null) {
494
- const from = options.cwd ?? process.cwd();
495
- const o = atRoot(options);
496
- try {
497
- // Without the lock (it cannot be taken), a read-only command writes
498
- // nothing.
499
- const r = lock
500
- ? await withLock(
501
- o.cwd,
502
- lock,
503
- locked => fn(locked ? o : {...o, readOnly: true}),
504
- bestEffort,
505
- again,
506
- )
507
- : await fn(o);
508
- return absolute(r, o.cwd, from);
509
- } catch (e) {
510
- throw fromCaller(e, o.cwd, from);
511
- }
512
- }
513
-
514
- /**
515
- * A refusal whose suggested preview commands name folders as the person
516
- * types them where they ran the command: a `--path` and a `preview app`
517
- * folder, read from the project root, are written from the caller's
518
- * folder.
519
- * @param {any} e
520
- * @param {string} root
521
- * @param {string} from
522
- */
523
- function fromCaller(e, root, from) {
524
- if (path.resolve(from) === root || !Array.isArray(e?.suggestions)) return e;
525
- for (const s of e.suggestions)
526
- if (typeof s?.name === 'string')
527
- s.name = previewCommandsFrom(s.name, root, from);
528
- return e;
529
- }
530
-
531
- /**
532
- * The preview commands in a line, rebased from the project root onto the
533
- * folder the command ran in: each `--path` and each `preview app` folder,
534
- * so a pointer works where it is printed (in a refusal, a `see` line, a
535
- * note). A folder that comes out starting with `-` goes after `--`.
536
- * @param {string} line
537
- * @param {string} root
538
- * @param {string} from
539
- */
540
- export function previewCommandsFrom(line, root, from) {
541
- if (path.resolve(from) === root) return line;
542
- const ARG = String.raw`('(?:[^']|'\\'')*'|"[^"]*"|[^\s'"]+)`;
543
- /** @param {string} v */
544
- const unquote = v =>
545
- v.startsWith("'")
546
- ? v.slice(1, -1).replace(/'\\''/g, "'")
547
- : v.startsWith('"')
548
- ? v.slice(1, -1)
549
- : v;
550
- /** @param {string} v */
551
- const rel = v =>
552
- /^<.*>$/.test(v)
553
- ? v
554
- : path.relative(path.resolve(from), path.resolve(root, unquote(v))) ||
555
- '.';
556
- const CMD = 'astryx experimental theme preview ';
557
- const parts = line.split(CMD);
558
- return parts
559
- .map((part, i) => {
560
- // A command after a `cd … &&` runs in the folder it names: as given.
561
- if (i === 0 || /\bcd [^&]*&& (?:npx \S+ )?$/.test(parts[i - 1]))
562
- return part;
563
- let out = part.replace(
564
- new RegExp(`(--path )${ARG}`, 'g'),
565
- (
566
- /** @type {string} */ _m,
567
- /** @type {string} */ flag,
568
- /** @type {string} */ v,
569
- ) => flag + quoteCommandArgument(rel(v)),
570
- );
571
- out = out.replace(
572
- new RegExp(`^app ((?:--theme ${ARG} )?)(-- )?${ARG}`),
573
- (
574
- /** @type {string} */ m,
575
- /** @type {string} */ flags,
576
- /** @type {string} */ _t,
577
- /** @type {string | undefined} */ dash,
578
- /** @type {string} */ v,
579
- ) => {
580
- if (!dash && v.startsWith('-')) return m;
581
- const r = rel(v);
582
- return `app ${flags}${r.startsWith('-') ? '-- ' : ''}${quoteCommandArgument(r)}`;
583
- },
584
- );
585
- return out;
586
- })
587
- .join(CMD);
588
- }
589
-
590
- /**
591
- * Options for a preview command, with a way to hold a theme's lock while
592
- * the preview builds that theme.
593
- * @template {{cwd: string}} O
594
- * @param {O} o
595
- * @returns {any}
596
- */
597
- const withThemeLock = o => ({
598
- ...o,
599
- lockTheme: (
600
- /** @type {string} */ slug,
601
- /** @type {() => Promise<any>} */ fn,
602
- ) => withLock(o.cwd, lockName(slug), fn),
603
- });
604
-
605
- /**
606
- * A command's own words after the CLI name, from what it was called with,
607
- * every option kept: set and undo as `set` writes them (scope flags and
608
- * --only), new with --like and each dial, --png where given.
609
- * @param {string} line a command as the editor writes one (`astryx …`)
610
- * @param {{png?: boolean}} [o]
611
- */
612
- const words = (line, o = {}) =>
613
- `${line.replace(/^astryx /, '').trimEnd()}${o.png ? ' --png' : ''}`;
614
-
615
- /** @type {typeof edit.themeEditNew} */
616
- export const themeEditNew = (name, options = {}) =>
617
- inProject(
618
- options,
619
- lockName(name),
620
- o => edit.themeEditNew(name, o),
621
- false,
622
- words(
623
- `${P} new ${quoteCommandArgument(name)} ${edit
624
- .newFlagList(
625
- options.like,
626
- options.settings ?? {},
627
- /** @type {boolean} */ (options.png),
628
- )
629
- .join(' ')}`,
630
- ),
631
- );
632
- /** @type {typeof edit.themeEditSet} */
633
- export const themeEditSet = (theme, thing, value, options = {}) =>
634
- inProject(
635
- options,
636
- lockName(theme),
637
- o => edit.themeEditSet(theme, thing, value, o),
638
- false,
639
- words(setLine(theme, thing, value, options), options),
640
- );
641
- /** @type {typeof edit.themeEditUndo} */
642
- export const themeEditUndo = (theme, options = {}) =>
643
- inProject(
644
- options,
645
- lockName(theme),
646
- o => edit.themeEditUndo(theme, o),
647
- false,
648
- words(
649
- options.thing
650
- ? setLine(
651
- theme,
652
- options.thing,
653
- /** @type {string} */ (options.value ?? ''),
654
- options,
655
- true,
656
- )
657
- : `${P} undo ${theme}`,
658
- options,
659
- ),
660
- );
661
- /** @type {typeof edit.themeEditShow} */
662
- export const themeEditShow = (theme, options = {}) =>
663
- inProject(
664
- options,
665
- // A lookup of one part writes nothing, and may name a theme that is not
666
- // the editor's: it takes no theme lock.
667
- options.on != null ? null : lockName(theme),
668
- o => edit.themeEditShow(theme, o),
669
- true,
670
- words(
671
- `${P} show ${theme}${options.section ? ` --section ${quoteCommandArgument(String(options.section))}` : ''}`,
672
- options,
673
- ),
674
- );
675
- /** @type {typeof preview.themeEditPreviewAdd} */
676
- export const themeEditPreviewAdd = (description, options = {}) =>
677
- stopTold(
678
- `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)`,
679
- () =>
680
- inProject(options, 'preview', o =>
681
- preview.themeEditPreviewAdd(description, withThemeLock(o)),
682
- ),
683
- );
684
-
685
- /**
686
- * Run a preview command with a stop (Ctrl-C, SIGTERM) heard for its whole
687
- * run, and after it: the stop ends the process as stopped, with one line
688
- * saying where the change stands (a change stopped part way is finished by
689
- * the next preview command), never an ok with exit 0.
690
- * @template T
691
- * @param {string | (() => string)} where where the change stands, and what
692
- * finishes it; a function is asked when the stop lands, so it can look
693
- * @param {() => Promise<T>} fn
694
- * @returns {Promise<T>}
695
- */
696
- async function stopTold(where, fn) {
697
- const on = (/** @type {NodeJS.Signals} */ sig) => {
698
- process.removeListener('SIGINT', on);
699
- process.removeListener('SIGTERM', on);
700
- process.stderr.write(
701
- `Stopped: ${typeof where === 'function' ? where() : where}.\n`,
702
- );
703
- // With no other listener (a lock's, which ends the process itself),
704
- // the stop ends it here.
705
- if (process.listenerCount(sig) === 0) process.kill(process.pid, sig);
706
- };
707
- process.on('SIGINT', on);
708
- process.on('SIGTERM', on);
709
- try {
710
- const r = await fn();
711
- // A turn of the event loop, so a stop that came while the work ran
712
- // without a pause is heard now, before the result is printed.
713
- await new Promise(resolve => setImmediate(resolve));
714
- // Every listener added here is removed on return: the caller's process
715
- // keeps its own stop handling. The CLI client, which owns its process,
716
- // holds a stop that lands while it prints the result.
717
- return r;
718
- } finally {
719
- process.removeListener('SIGINT', on);
720
- process.removeListener('SIGTERM', on);
721
- }
722
- }
723
- /**
724
- * `preview app` runs from the project root, with `dir` kept pointing where
725
- * it was given. With a theme it holds that theme's lock, since it may build
726
- * the theme and copies its files: a `set` beside it waits.
727
- * @type {typeof preview.themeEditPreviewApp}
728
- */
729
- export const themeEditPreviewApp = async (dir, options = {}) => {
730
- const from = options.cwd ?? process.cwd();
731
- // The app is written into a temp folder and moved into place in one step,
732
- // with no pause on the way: when a stop lands, the folder holds the whole
733
- // app or is as it was. Which one is told.
734
- const target =
735
- typeof dir === 'string' && dir.trim() ? path.resolve(from, dir) : null;
736
- /** @param {string} d */
737
- const holdsApp = d => fs.existsSync(path.join(d, 'package.json'));
738
- const hadApp = target != null && holdsApp(target);
739
- const shownTarget = target
740
- ? path.relative(from, target).split(path.sep).join('/') || '.'
741
- : null;
742
- return fromHere(
743
- await stopTold(
744
- () =>
745
- target && !hadApp && holdsApp(target)
746
- ? `the new app in ${shownTarget}/ is written whole (it is moved into place in one step); cd ${quoteCommandArgument(shownTarget?.startsWith('-') ? `./${shownTarget}` : (shownTarget ?? '.'))} && npm install && npm run dev opens it`
747
- : `nothing was written${shownTarget ? ` (${shownTarget}/ is as it was)` : ''}; run the same command again`,
748
- () =>
749
- inProject(
750
- options,
751
- options.theme == null ? null : lockName(options.theme),
752
- o =>
753
- preview.themeEditPreviewApp(
754
- typeof dir === 'string' && dir.trim() && dir === dir.trim()
755
- ? path.relative(o.cwd, path.resolve(from, dir)) || '.'
756
- : dir,
757
- o,
758
- ),
759
- true,
760
- ),
761
- ),
762
- from,
763
- );
764
- };
765
- /**
766
- * A new app's folder and its open line, as they work from where the command
767
- * ran (`cd ../../theme-app` from src/app), not from the project root.
768
- * @template T
769
- * @param {T} r
770
- * @param {string} from
771
- * @returns {T}
772
- */
773
- function fromHere(r, from) {
774
- const d = /** @type {any} */ (r)?.data;
775
- if (!d || typeof d.folder !== 'string') return r;
776
- const root = projectRoot(from);
777
- if (!root || path.resolve(from) === root) return r;
778
- const here = path.relative(from, path.join(root, d.folder)) || '.';
779
- const shown = here.split(path.sep).join('/');
780
- const cdArg = quoteCommandArgument(
781
- shown.startsWith('-') ? `./${shown}` : shown,
782
- );
783
- return /** @type {T} */ ({
784
- ...r,
785
- data: {
786
- ...d,
787
- folder: shown,
788
- ...(typeof d.open === 'string'
789
- ? {open: d.open.replace(/^cd \S+ &&/, `cd ${cdArg} &&`)}
790
- : {}),
791
- },
792
- });
793
- }
794
- /** @type {typeof preview.themeEditPreviewList} */
795
- export const themeEditPreviewList = (options = {}) =>
796
- inProject(options, null, async o => preview.themeEditPreviewList(o));
797
- /** @type {typeof preview.themeEditPreviewRemove} */
798
- export const themeEditPreviewRemove = (page, options = {}) =>
799
- stopTold(
800
- `a removal stopped part way is finished by the next ${PREVIEW_WORDS} remove, and one made in full stands (${PREVIEW_WORDS} list says which)`,
801
- () =>
802
- inProject(options, 'preview', o =>
803
- preview.themeEditPreviewRemove(page, withThemeLock(o)),
804
- ),
805
- );
806
-
807
- /**
808
- * The editor theme a path or a name names, with its project, or null: a
809
- * name is a theme in `root`'s themes/ folder; a path is one in the themes/
810
- * folder of the project the file belongs to (found from the file, so a
811
- * path from another folder still names it, and a `src/themes/<slug>` fork
812
- * does not).
813
- * @param {string} root
814
- * @param {string} word a path or a name
815
- * @param {{made?: boolean}} [options] `made`: a folder the editor made that
816
- * lost its settings counts too (the editor commands refuse it, and so
817
- * does compile)
818
- * @returns {{root: string, slug: string} | null}
819
- */
820
- function editorThemeAt(root, word, {made = false} = {}) {
821
- const has = (/** @type {string} */ r, /** @type {string} */ slug) =>
822
- fs.existsSync(path.join(r, 'themes', slug, `${slug}.settings.json`)) ||
823
- (made && editorMadeFolder(r, slug));
824
- if (/^[a-z][a-z0-9-]*$/.test(word))
825
- return has(root, word) ? {root, slug: word} : null;
826
- // Through a link, the real path decides (a linked theme folder is the
827
- // same folder).
828
- /** @type {string} */
829
- let abs = path.resolve(root, word);
830
- try {
831
- abs = fs.realpathSync(abs);
832
- } catch {
833
- try {
834
- abs = path.join(fs.realpathSync(path.dirname(abs)), path.basename(abs));
835
- } catch {
836
- // Not there: the path as given.
837
- }
838
- }
839
- // The folder above the last themes/<slug>/ in the path, when that folder
840
- // is a project's root (src/themes/<slug> is not: its project is above).
841
- const m = /^(.*)[\\/]themes[\\/]([a-z][a-z0-9-]*)(?:[\\/]|$)/.exec(abs);
842
- if (!m || !has(m[1], m[2])) return null;
843
- /** @type {string} */
844
- let top;
845
- try {
846
- top = projectRoot(m[1]);
847
- } catch {
848
- top = m[1];
849
- }
850
- return path.resolve(top) === path.resolve(m[1])
851
- ? {root: m[1], slug: m[2]}
852
- : null;
853
- }
854
-
855
- /**
856
- * Whether a file in an editor theme's folder is one of the editor's own
857
- * (its theme source or settings), which the editor guards; another file
858
- * there (a template written into the folder) is compiled as any file.
859
- * @param {string} slug
860
- * @param {string} file
861
- */
862
- function editorOwnFile(slug, file) {
863
- return [
864
- `${slug}.theme.ts`,
865
- `${slug}.settings.ts`,
866
- `${slug}.settings.json`,
867
- ].includes(path.basename(file));
868
- }
869
-
870
- /**
871
- * The editor theme a path or name names in `root`, or null.
872
- * @param {string} root
873
- * @param {string} word
874
- */
875
- function editorThemeOf(root, word) {
876
- return editorThemeAt(root, word)?.slug ?? null;
877
- }
878
-
879
- /**
880
- * A suggested command, started the way this project runs the CLI.
881
- * @param {string} cwd
882
- * @param {string} rest the words after `astryx`
883
- */
884
- function runLine(cwd, rest) {
885
- return `${getCliInvocation(cwd)} ${rest}`;
886
- }
887
-
888
- /**
889
- * A clearer refusal for a theme the editor made, named to list, add, use,
890
- * remove or eject: those commands work on package themes, and the editor
891
- * theme is used by importing its module. Null for any other refusal.
892
- * @param {AstryxError} err
893
- * @param {string} cwd
894
- * @returns {AstryxError | null}
895
- */
896
- export function editorThemeRefusal(err, cwd) {
897
- // A refused compile ends here: its theme locks go now, not at exit, and
898
- // it writes no app copy (from build files it refused).
899
- void releaseCompileHold?.(true);
900
- if (
901
- err.code !== ERROR_CODES.ERR_UNKNOWN_THEME &&
902
- !/unknown theme|is not added|not a theme package/i.test(err.message)
903
- )
904
- return null;
905
- const root = projectRoot(cwd);
906
- // The name as typed, read the way the editor reads a theme name: a path
907
- // to its folder or a file in it, in any case, names the theme.
908
- const named = /"([^"]+)"|'([^']+)'/.exec(err.message);
909
- const word = named ? typedThemeName(named[1] ?? named[2]) : '';
910
- const slug = word ? editorThemeOf(root, word) : null;
911
- if (!slug) return null;
912
- // The command that refused: list, add, use, remove or eject.
913
- const verb =
914
- process.argv
915
- .slice(2)
916
- .find(a => ['list', 'add', 'use', 'remove', 'eject'].includes(a)) ?? null;
917
- // eject copies a theme package's source into the app; an editor theme's
918
- // source is the app's already.
919
- if (verb === 'eject')
920
- return new AstryxError(
921
- `${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}.`,
922
- [
923
- {
924
- name: runLine(cwd, `experimental theme editor show ${slug}`),
925
- reason: 'the theme as it is now',
926
- },
927
- ],
928
- ERROR_CODES.ERR_UNKNOWN_THEME,
929
- );
930
- const copyThere = !folderIsEmpty(path.join(root, LOCAL_THEME_ROOT, slug));
931
- // A path to the theme ("themes/d", "src/themes/d"): the commands take its
932
- // name.
933
- const typed = named ? (named[1] ?? named[2]) : '';
934
- if (copyThere && verb && typed !== slug)
935
- return new AstryxError(
936
- `"${typed}" is ${/[\\/]|\.[a-z]+$/i.test(typed) ? 'a path' : "not the theme's name"}; the theme commands take the theme's name: ${slug}.`,
937
- [
938
- {
939
- name: runLine(cwd, `theme ${verb} ${slug}`),
940
- reason: 'the same, by name',
941
- },
942
- ],
943
- ERROR_CODES.ERR_UNKNOWN_THEME,
944
- );
945
- // A local theme of that name (a fork in the app's own themes folder) is
946
- // one the stable commands take: their own message stands.
947
- // A folder of only system files (or empty) holds no theme: as absent.
948
- if (copyThere) return null;
949
- // No app copy yet (a theme made before the editor wrote one, or the
950
- // copy removed): the next build writes it, then the same steps every
951
- // place gives (`wiring` of new and show).
952
- // A one-mode theme's mode is a step too, as in `wiring`.
953
- /** @type {'light' | 'dark' | 'system'} */
954
- let mode = 'system';
955
- try {
956
- const m = JSON.parse(
957
- fs.readFileSync(
958
- path.join(root, 'themes', slug, `${slug}.settings.json`),
959
- 'utf8',
960
- ),
961
- ).mode;
962
- if (m === 'light-only') mode = 'light';
963
- else if (m === 'dark-only') mode = 'dark';
964
- } catch {
965
- // Settings that do not read: both modes.
966
- }
967
- const steps = preview.addWiring(root, slug, mode);
968
- return new AstryxError(
969
- `${slug} is a theme the editor made (themes/${slug}/), and it has no app copy yet: list, add, use, remove and eject take the copy every build of it writes in src/themes/${slug}/, a standard local theme. Build it once, then: ${steps.join('; ')}.`,
970
- [
971
- {
972
- name: runLine(cwd, `experimental theme editor show ${slug}`),
973
- reason: `builds it and writes its app copy, src/themes/${slug}/`,
974
- },
975
- {
976
- name: runLine(cwd, `theme add ${slug}`),
977
- reason: 'then adds it to the app',
978
- },
979
- ],
980
- ERROR_CODES.ERR_UNKNOWN_THEME,
981
- );
982
- }
983
-
984
- /** The shared typo rule, for a typed subcommand. */
985
- export {booleanWord, typoNear, typoOf} from './_normal.mjs';
986
- // How a setting is named in a result: one wording for the API and the CLI.
987
- export {describe, namesSetting, needsPart} from './_settings.mjs';
988
-
989
- /**
990
- * The editor themes of the app the folder `cwd` is in, by name; none when
991
- * the folder is in no app or its themes cannot be read.
992
- * @param {string} cwd
993
- * @returns {string[]}
994
- */
995
- export function editorThemesAt(cwd) {
996
- try {
997
- return editedThemes(projectRoot(cwd));
998
- } catch {
999
- return [];
1000
- }
1001
- }
1002
-
1003
- /**
1004
- * A refused compile whose first suggestion is another compile: that compile
1005
- * is run through compile's own checks before it is offered (in memory,
1006
- * nothing built), and each repair a refusal of it offers is folded into the
1007
- * one line. An --out outside the working folder is dropped, and the reason
1008
- * says why; when the rest cannot be repaired, the reason says so. A line
1009
- * that starts with `cd` runs elsewhere, so it is not checked from here.
1010
- * @param {AstryxError} err
1011
- * @param {string} cwd
1012
- * @returns {Promise<AstryxError>}
1013
- */
1014
- export async function editorFollowCompile(err, cwd) {
1015
- const list = err.suggestions ?? [];
1016
- const first = list[0];
1017
- // The build's own refusals name `theme build`; the group's words replace
1018
- // those words when the refusal is shown.
1019
- const wordsIn = (/** @type {string} */ line) =>
1020
- [' experimental theme compile ', ' theme build '].find(w =>
1021
- line.includes(w),
1022
- );
1023
- const isCompile = (/** @type {string} */ line) =>
1024
- /^cd /.test(line) || Boolean(wordsIn(line));
1025
- if (!first || /^cd /.test(first.name) || !wordsIn(first.name)) return err;
1026
- /** @param {string} line */
1027
- const read = line => {
1028
- const words = wordsIn(line);
1029
- if (!words) return null;
1030
- const args = splitCommand(line.slice(line.indexOf(words) + words.length));
1031
- if (!args) return null;
1032
- /** @type {{source?: string, out?: string, iconsSpecifier?: string, check?: boolean}} */
1033
- const r = {};
1034
- for (let i = 0; i < args.length; i += 1) {
1035
- const a = args[i];
1036
- if (a === '--check') r.check = true;
1037
- else if (a === '--out') r.out = args[(i += 1)];
1038
- else if (a === '--icons-specifier') r.iconsSpecifier = args[(i += 1)];
1039
- else if (a.startsWith('-') || r.source) return null;
1040
- else r.source = a;
1041
- }
1042
- return r.source ? r : null;
1043
- };
1044
- const COMPILE = {group: 'experimental theme', build: 'compile'};
1045
- /** @type {string | null} */
1046
- let outDropped = null;
1047
- const followed = await followLine(
1048
- first.name,
1049
- async line => {
1050
- // A line that runs elsewhere is not checked from here.
1051
- if (/^cd /.test(line)) return null;
1052
- const r = read(line);
1053
- if (!r?.source) return null;
1054
- const refused =
1055
- (await editorCompileProblem([r.source], {cwd, ...r})) ??
1056
- buildInputProblem(r.source, r, cwd);
1057
- if (refused) return refused;
1058
- // A build writes only inside the working folder: the same build
1059
- // without --out writes beside the source.
1060
- if (r.out && refusedOutput(path.resolve(cwd, r.out), cwd)) {
1061
- outDropped = r.out;
1062
- return new AstryxError(`--out ${r.out} is outside the working folder`, [
1063
- {
1064
- name: buildSuggestion(
1065
- r.source,
1066
- {check: r.check, iconsSpecifier: r.iconsSpecifier},
1067
- cwd,
1068
- COMPILE,
1069
- ),
1070
- reason: 'do this instead',
1071
- },
1072
- ]);
1073
- }
1074
- return null;
1075
- },
1076
- isCompile,
1077
- );
1078
- if (followed.line === first.name) return err;
1079
- const reason = [
1080
- outDropped && !/ --out /.test(followed.line)
1081
- ? `do this instead, without --out: ${outDropped} is outside the working folder, where a build may not write, so the outputs go beside the source`
1082
- : first.reason,
1083
- ...(followed.why ? [`it is still refused: ${followed.why}`] : []),
1084
- ].join('; ');
1085
- err.suggestions = [
1086
- {...first, name: followed.line, reason},
1087
- ...list.slice(1).filter(x => x.name !== followed.line),
1088
- ];
1089
- return err;
1090
- }
1091
-
1092
- /**
1093
- * A refusal before `compile` runs on an editor theme's files, or null: the
1094
- * editor's generated settings are not a theme source, `--family` does not
1095
- * take an editor theme, and `--check` checks an editor theme by the editor's
1096
- * own rules (waiting for a change in progress).
1097
- * @param {string[]} files
1098
- * @param {{cwd: string, check?: boolean, family?: boolean, iconsSpecifier?: string, out?: string}} options
1099
- * `check`, `out` and `iconsSpecifier` are kept in every compile a refusal
1100
- * suggests
1101
- * @returns {Promise<AstryxError | null>}
1102
- */
1103
- export async function editorCompileProblem(
1104
- files,
1105
- {cwd, check, family, iconsSpecifier, out},
1106
- ) {
1107
- const cwdRoot = projectRoot(cwd);
1108
- const COMPILE = {group: 'experimental theme', build: 'compile'};
1109
- // An empty or blank --out or --icons-specifier names nothing: refused
1110
- // before anything is built, with the compile without it.
1111
- const blank =
1112
- blankOptionProblem(
1113
- '--out',
1114
- out,
1115
- 'name a file or folder, or leave out --out to write beside the source',
1116
- buildSuggestion(
1117
- files.length === 1 ? files[0] : files,
1118
- {check, iconsSpecifier},
1119
- cwd,
1120
- COMPILE,
1121
- ),
1122
- ) ??
1123
- blankOptionProblem(
1124
- '--icons-specifier',
1125
- iconsSpecifier,
1126
- "name the registry module, or leave out --icons-specifier to keep the theme source's own import",
1127
- buildSuggestion(
1128
- files.length === 1 ? files[0] : files,
1129
- {check, out},
1130
- cwd,
1131
- COMPILE,
1132
- ),
1133
- );
1134
- if (blank) return blank;
1135
- /**
1136
- * The compile of `source` (from `from`) with the caller's mode: a check
1137
- * stays a check, and --out names the same file from there.
1138
- * @param {string} source @param {string} from
1139
- */
1140
- const compileLine = (source, from) =>
1141
- buildSuggestion(
1142
- source,
1143
- {
1144
- check,
1145
- iconsSpecifier,
1146
- out: out
1147
- ? path.relative(from, path.resolve(cwd, out)) || out
1148
- : undefined,
1149
- },
1150
- from,
1151
- COMPILE,
1152
- );
1153
- /**
1154
- * The compile of `source` from the app root, after a cd there: --out
1155
- * names the same file from the root while it stays inside it (a build
1156
- * writes only inside its working folder); one outside is left off, and
1157
- * `why` says so.
1158
- * @param {string} source @param {string} root
1159
- */
1160
- const fromRootLine = (source, root) => {
1161
- const rebased = out
1162
- ? path.relative(root, path.resolve(cwd, slashed(out)))
1163
- : '';
1164
- const escapes =
1165
- !check &&
1166
- !!rebased &&
1167
- (rebased.startsWith('..') || path.isAbsolute(rebased));
1168
- return {
1169
- name: `cd ${quoteCommandArgument(path.relative(cwd, root) || '.')} && ${
1170
- escapes
1171
- ? buildSuggestion(source, {check, iconsSpecifier}, root, COMPILE)
1172
- : compileLine(source, root)
1173
- }`,
1174
- why: escapes
1175
- ? ` --out ${out} is outside the app root, where a build may not write, so the compile below writes beside the source.`
1176
- : '',
1177
- };
1178
- };
1179
- // An --out into an editor theme's app copy folder: the copy refresh would
1180
- // write the theme's own build over it. One into the theme's own editor
1181
- // folder that is not its default output would leave that folder half
1182
- // built (the module rewritten, the stylesheet not) and the copy made from
1183
- // it.
1184
- if (out) {
1185
- // Any --out in the copy folder, the folder itself too, written with
1186
- // backslashes, through a link or (on a case-insensitive disk) in
1187
- // another case, as the build reads it: real paths name the folder as
1188
- // the disk does.
1189
- const rel = path
1190
- .relative(
1191
- realLocation(cwdRoot),
1192
- realLocation(path.resolve(cwd, slashed(out))),
1193
- )
1194
- .split(path.sep)
1195
- .filter(Boolean);
1196
- const inCopy =
1197
- rel[0] === 'src' &&
1198
- rel[1] === 'themes' &&
1199
- rel.length >= 3 &&
1200
- fs.existsSync(themeFiles(cwdRoot, rel[2]).settings);
1201
- // Only for a compile of that theme: another source written there is
1202
- // the build's own case (it warns).
1203
- const inEditor =
1204
- rel[0] === 'themes' &&
1205
- rel.length >= 3 &&
1206
- fs.existsSync(themeFiles(cwdRoot, rel[1]).settings) &&
1207
- files.some(
1208
- file =>
1209
- editorThemeAt(cwdRoot, path.resolve(cwd, file))?.slug === rel[1],
1210
- ) &&
1211
- !outIsDefault(cwdRoot, rel[1], cwd, out);
1212
- if (inCopy || inEditor) {
1213
- const t = inCopy ? rel[2] : rel[1];
1214
- return new AstryxError(
1215
- inCopy
1216
- ? `--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.`
1217
- : `--out ${out} is in ${t}'s own folder (themes/${t}/), where the theme's build writes its module and stylesheet together; compile without --out to build there, or write the build outside themes/${t}/.`,
1218
- [
1219
- {
1220
- // The same compile without --out: it builds into themes/<t>/,
1221
- // and the copy follows.
1222
- // From a subfolder, with the cd to the app root, where an
1223
- // editor theme compiles.
1224
- name:
1225
- path.resolve(cwd) === path.resolve(cwdRoot)
1226
- ? buildSuggestion(
1227
- files.length === 1 ? files[0] : `themes/${t}/${t}.theme.ts`,
1228
- {check, iconsSpecifier},
1229
- cwd,
1230
- COMPILE,
1231
- )
1232
- : `cd ${quoteCommandArgument(path.relative(cwd, cwdRoot) || '.')} && ${buildSuggestion(
1233
- files.length === 1
1234
- ? path.relative(cwdRoot, path.resolve(cwd, files[0])) ||
1235
- files[0]
1236
- : `themes/${t}/${t}.theme.ts`,
1237
- {check, iconsSpecifier},
1238
- cwdRoot,
1239
- COMPILE,
1240
- )}`,
1241
- reason: 'do this instead',
1242
- },
1243
- ],
1244
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1245
- );
1246
- }
1247
- }
1248
- for (const file of files) {
1249
- const abs = path.resolve(cwd, file);
1250
- const relParts = path
1251
- .relative(
1252
- realLocation(cwdRoot),
1253
- realLocation(path.resolve(cwd, slashed(file))),
1254
- )
1255
- .split(path.sep);
1256
- // The app's theme module `theme add` writes: not a theme source.
1257
- if (relParts.join('/') === 'src/astryx-themes.ts')
1258
- return new AstryxError(
1259
- `${file} is the app's theme module (\`theme add\` writes it), not a theme source; compile the editor theme instead.`,
1260
- editedThemes(cwdRoot)
1261
- .slice(0, 3)
1262
- .map(t => ({
1263
- name: compileLine(`themes/${t}/${t}.theme.ts`, cwdRoot),
1264
- reason: 'do this instead',
1265
- })),
1266
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1267
- );
1268
- // A file of an editor theme's app copy (src/themes/<t>/): the copy
1269
- // is written from themes/<t>/, so that is what compiles.
1270
- if (
1271
- relParts[0] === 'src' &&
1272
- relParts[1] === 'themes' &&
1273
- (relParts.length === 3 || relParts.length === 4) &&
1274
- fs.existsSync(themeFiles(cwdRoot, relParts[2]).settings) &&
1275
- // A file of yours there (no editor mark, no build header) compiles
1276
- // like any theme source.
1277
- (relParts.length === 3 ||
1278
- isCopyFile(path.join(cwdRoot, ...relParts)) ||
1279
- relParts[3] === `${camel(relParts[2])}Theme.ts`)
1280
- ) {
1281
- const t = relParts[2];
1282
- const own = `themes/${t}/${t}.theme.ts`;
1283
- if (path.resolve(cwd) !== path.resolve(cwdRoot)) {
1284
- const line = fromRootLine(own, cwdRoot);
1285
- return new AstryxError(
1286
- `${t} is a theme the editor made; compile it from the app root (${path.relative(cwd, cwdRoot) || '.'}), where the editor builds it.${line.why}`,
1287
- [{name: line.name, reason: 'do this instead'}],
1288
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1289
- );
1290
- }
1291
- // Its source too: a compile of the copy builds neither the theme
1292
- // nor a current copy. The compile offered is the one this check
1293
- // takes (an --out in the theme's own folder is refused there, and its
1294
- // refusal's line is offered instead).
1295
- const ownRefused = await editorCompileProblem([own], {
1296
- cwd,
1297
- check,
1298
- family,
1299
- iconsSpecifier,
1300
- out,
1301
- });
1302
- return new AstryxError(
1303
- `${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.`,
1304
- [
1305
- ...(ownRefused?.suggestions?.length
1306
- ? ownRefused.suggestions
1307
- : [{name: compileLine(own, cwd), reason: 'do this instead'}]),
1308
- {
1309
- name: runLine(cwdRoot, `experimental theme editor show ${t}`),
1310
- reason: 'writes the app copy again from the theme',
1311
- },
1312
- ],
1313
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1314
- );
1315
- }
1316
- const at = editorThemeAt(cwdRoot, abs, {made: true});
1317
- if (!at || !editorOwnFile(at.slug, file)) continue;
1318
- const {root, slug} = at;
1319
- // An editor theme that lost its settings is refused as every editor
1320
- // command refuses it, with the line that makes it again: a plain build
1321
- // of it would drop the editor's settings and app copy.
1322
- if (
1323
- !fs.existsSync(path.join(root, 'themes', slug, `${slug}.settings.json`))
1324
- )
1325
- try {
1326
- loadTheme(root, slug);
1327
- } catch (e) {
1328
- if (e instanceof AstryxError) return e;
1329
- throw e;
1330
- }
1331
- const source = `themes/${slug}/${slug}.theme.ts`;
1332
- // An editor theme is built from its project's root, as every editor
1333
- // command runs there: from a subfolder the build would write outside
1334
- // its working folder. The run names the root.
1335
- if (path.resolve(cwd) !== path.resolve(root)) {
1336
- const line = fromRootLine(source, root);
1337
- return new AstryxError(
1338
- `${slug} is a theme the editor made; compile it from the app root (${path.relative(cwd, root) || '.'}), where the editor builds it.${line.why}`,
1339
- [{name: line.name, reason: 'do this instead'}],
1340
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1341
- );
1342
- }
1343
- if (/\.settings\.(ts|json)$/.test(file))
1344
- return new AstryxError(
1345
- `${file} is the editor's own settings for ${slug}, not a theme source; compile the theme source.`,
1346
- [
1347
- {
1348
- name: compileLine(
1349
- path.relative(cwd, path.join(root, source)) || source,
1350
- cwd,
1351
- ),
1352
- reason: 'do this instead',
1353
- },
1354
- ],
1355
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1356
- );
1357
- // A source that no longer carries the settings (another theme's name,
1358
- // or no extends of them) is refused as set refuses it: a build would
1359
- // write another theme's files, or drop every setting.
1360
- {
1361
- const refusal = await themeSourceRefusal(root, slug);
1362
- if (refusal) return refusal;
1363
- }
1364
- if (family)
1365
- return new AstryxError(
1366
- `${slug} is a theme the editor made; --family builds package theme families, not editor themes. Compile it on its own.`,
1367
- [
1368
- {
1369
- name: compileLine(
1370
- path.relative(cwd, path.join(root, source)) || source,
1371
- cwd,
1372
- ),
1373
- reason: 'do this instead',
1374
- },
1375
- ],
1376
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1377
- );
1378
- {
1379
- // A check waits for a change in progress, so it never reads one half
1380
- // written. A plain compile builds the theme source, which reads the
1381
- // generated settings: when those no longer match the settings, it
1382
- // would report ok without them.
1383
- // `compile` holds the lock already while it runs (editorThemeHold).
1384
- /** @type {string | null} */
1385
- let why;
1386
- try {
1387
- why = COMPILE_HELD.has(`${root}\0${slug}`)
1388
- ? await edit.editorStale(root, slug)
1389
- : await withLock(root, lockName(slug), () =>
1390
- edit.editorStale(root, slug),
1391
- );
1392
- } catch (e) {
1393
- // A settings file damaged by hand is refused like any refusal,
1394
- // never as a raw error, with the lines every command gives it.
1395
- if (e instanceof AstryxError)
1396
- return edit.editorSavedRefusal(e, root, slug);
1397
- throw e;
1398
- }
1399
- // An own change to the theme source is what compile builds (and what
1400
- // --check compares): never a reason to refuse it.
1401
- if (
1402
- why &&
1403
- /\.theme\.ts (or a module it imports )?changed since the last build$/.test(
1404
- why,
1405
- )
1406
- )
1407
- why = null;
1408
- // A missing built output is one compile writes itself, and one a
1409
- // check names in its own result (the stale outputs, upToDate false):
1410
- // never a reason to refuse either.
1411
- if (why && /^[^/]+\.(css|js|d\.ts|css\.d\.ts) was missing$/.test(why))
1412
- why = null;
1413
- // Saved settings the editor no longer accepts: show refuses them too,
1414
- // so the refusal names the undo that removes each.
1415
- if (why) {
1416
- const stored = await edit.editorStoredRefusal(root, slug);
1417
- if (stored) return stored;
1418
- }
1419
- if (why && !check)
1420
- return new AstryxError(
1421
- `${slug}'s generated settings do not match its settings (${why}), so compile would build the old ones. The editor builds it from its settings.`,
1422
- [
1423
- {
1424
- name: runLine(cwd, `experimental theme editor show ${slug}`),
1425
- reason: 'do this instead',
1426
- },
1427
- ],
1428
- ERROR_CODES.ERR_THEME_INVALID,
1429
- );
1430
- if (why)
1431
- return new AstryxError(
1432
- `${slug} is not up to date: ${why}. The editor builds it again from its settings.`,
1433
- [
1434
- {
1435
- name: runLine(cwd, `experimental theme editor show ${slug}`),
1436
- reason: 'build it again',
1437
- },
1438
- ],
1439
- ERROR_CODES.ERR_THEME_INVALID,
1440
- );
1441
- // The file's own token values, judged as a build of it writes them
1442
- // (never written beside it), by the check the editor's build runs.
1443
- if (path.basename(file) === `${slug}.theme.ts`) {
1444
- const values = await edit.editorOwnTokenRefusal(root, slug);
1445
- if (values) return values;
1446
- }
1447
- }
1448
- }
1449
- return null;
1450
- }
1451
-
1452
- /** The editor themes a running `compile` holds the lock of, by project and name. */
1453
- const COMPILE_HELD = new Set();
1454
-
1455
- /** @type {((refused?: boolean) => Promise<void>) | null} The release of the running compile's hold; `refused`: it wrote nothing, so no app copy either. */
1456
- let releaseCompileHold = null;
1457
-
1458
- /** @type {Array<{root: string, slug: string, copy: (refused: boolean) => boolean, report: () => Record<string, unknown> | null}>} The running compile's held themes. */
1459
- let compileHoldItems = [];
1460
-
1461
- /**
1462
- * For `compile`, once its outputs are written: write each held editor
1463
- * theme's app copy now, and say per file what the write did (`appCopy` on
1464
- * a first write, `appCopyStale` when something keeps the copy behind), so
1465
- * the JSON result carries what the text says.
1466
- * @param {string[]} files
1467
- * @param {string} cwd
1468
- * @returns {Promise<Record<string, Record<string, unknown>>>}
1469
- */
1470
- export async function editorAfterBuild(files, cwd) {
1471
- const root = projectRoot(cwd);
1472
- /** @type {Record<string, Record<string, unknown>>} */
1473
- const out = {};
1474
- for (const item of compileHoldItems) {
1475
- item.copy(false);
1476
- const report = item.report();
1477
- if (!report) continue;
1478
- for (const file of files) {
1479
- const abs = path.resolve(cwd, file);
1480
- const own = editorThemeAt(root, abs);
1481
- if (own?.slug === item.slug && editorOwnFile(own.slug, file))
1482
- out[file] = report;
1483
- }
1484
- }
1485
- return out;
1486
- }
1487
-
1488
- /**
1489
- * Hold the theme lock of every editor theme among the files while
1490
- * `compile` builds or checks them, so it never reads a change half
1491
- * written. Resolves to the release.
1492
- * @param {string[]} files
1493
- * @param {{cwd: string, check?: boolean, out?: string}} options
1494
- * @returns {Promise<() => Promise<void>>}
1495
- */
1496
- export async function editorThemeHold(files, {cwd, check = false, out}) {
1497
- // Two compiles of one theme in one process: the second waits for the
1498
- // lock like any other command.
1499
- const cwdRoot = projectRoot(cwd);
1500
- const found = new Map();
1501
- for (const f of files) {
1502
- const at = editorThemeAt(cwdRoot, path.resolve(cwd, f));
1503
- if (at && editorOwnFile(at.slug, f))
1504
- found.set(`${at.root}\0${at.slug}`, at);
1505
- // The app copy's source (src/themes/<t>/<t>Theme.ts) of an editor
1506
- // theme: built under the theme's lock, so it never lands between a
1507
- // change's two writes.
1508
- const copy = appCopyTheme(cwdRoot, path.resolve(cwd, f));
1509
- if (copy) found.set(`${copy.root}\0${copy.slug}`, copy);
1510
- }
1511
- const themes = [...found.keys()].sort().map(k => found.get(k));
1512
- /** @type {Array<{root: string, slug: string, copy: (refused: boolean) => boolean, report: () => Record<string, unknown> | null, finish: (later: boolean) => Promise<void>}>} */
1513
- const releases = [];
1514
- compileHoldItems = releases;
1515
- // Every theme's copy is written first, at once (a refusal ends the run
1516
- // without waiting), then each lock goes.
1517
- const releaseAll = async (refused = false) => {
1518
- if (releaseCompileHold === releaseAll) releaseCompileHold = null;
1519
- const items = releases.splice(0);
1520
- const later = items.map(x => x.copy(refused));
1521
- for (const [i, x] of [...items.entries()].reverse())
1522
- await x.finish(later[i]);
1523
- };
1524
- releaseCompileHold = releaseAll;
1525
- for (const {
1526
- root,
1527
- slug,
1528
- } of /** @type {Array<{root: string, slug: string}>} */ (themes)) {
1529
- /** @type {() => void} */
1530
- let release = () => {};
1531
- const held = new Promise(r => {
1532
- release = () => r(undefined);
1533
- });
1534
- /** @type {(e?: unknown) => void} */
1535
- let ready = () => {};
1536
- const got = new Promise(r => {
1537
- ready = r;
1538
- });
1539
- const key = `${root}\0${slug}`;
1540
- // When the lock was taken, and the context a copy write needs (its
1541
- // font stylesheets), ready before the build so the copy is written at
1542
- // once when the run ends.
1543
- const heldAt = Date.now() - 1;
1544
- // An --out elsewhere builds neither themes/<theme>/ nor its copy.
1545
- const skipped = outSkipsCopy(root, slug, cwd, {check, out});
1546
- let ran = false;
1547
- let copied = false;
1548
- /** @type {string[] | null} */
1549
- let firstWrite = null;
1550
- /** @type {string | null} */
1551
- let keptBack = null;
1552
- /** @type {any} */
1553
- let copyCtx = null;
1554
- try {
1555
- copyCtx = await context(root);
1556
- } catch {
1557
- copyCtx = null;
1558
- }
1559
- const done = withLock(root, lockName(slug), async () => {
1560
- COMPILE_HELD.add(key);
1561
- ready();
1562
- try {
1563
- await held;
1564
- } finally {
1565
- COMPILE_HELD.delete(key);
1566
- }
1567
- }).catch(e => ready(e));
1568
- const err = await got;
1569
- if (err) {
1570
- await releaseAll();
1571
- throw err;
1572
- }
1573
- releases.push({
1574
- // A compile that wrote the build refreshes the app's copy too
1575
- // (src/themes/<theme>/), under the same lock; a check writes
1576
- // nothing. Each theme's copy follows its own build: a theme this run
1577
- // built (its build now matches its settings) gets its copy, whatever
1578
- // a later theme did; one that was refused or failed keeps its copy.
1579
- // True when the copy still needs its font stylesheet from the
1580
- // theme's settings (written in finish).
1581
- root,
1582
- slug,
1583
- copy: (/** @type {boolean} */ refused) => {
1584
- // Once per run: after the build's writes when the command asks
1585
- // (its result then says what the copy write did), else at release.
1586
- if (copied) return false;
1587
- copied = true;
1588
- ran = !refused && (process.exitCode ?? 0) === 0;
1589
- if (check || skipped) return false;
1590
- // This run built the theme: its module and stylesheet, one unit,
1591
- // were written since the lock was taken, or the run ended well. A
1592
- // refused or failed compile writes no copy.
1593
- const f = themeFiles(root, slug);
1594
- const written = [f.css, f.js].every(x => {
1595
- try {
1596
- return fs.statSync(x).mtimeMs >= heldAt;
1597
- } catch {
1598
- return false;
1599
- }
1600
- });
1601
- if (!written && (refused || (process.exitCode ?? 0) !== 0))
1602
- return false;
1603
- try {
1604
- // From what was just built, its font stylesheets from the fonts
1605
- // the theme loads now.
1606
- if (copyCtx) writeAppCopy(copyCtx, slug, loadTheme(root, slug));
1607
- else writeAppCopyAt(root, slug, null);
1608
- } catch {
1609
- try {
1610
- writeAppCopyAt(root, slug, null);
1611
- } catch {
1612
- // A theme that does not load keeps its copy as it was.
1613
- }
1614
- }
1615
- // What the write did, for the result and the text alike: the
1616
- // files of a first write, or what keeps the copy behind.
1617
- firstWrite = takeFirstAppCopy(root, slug);
1618
- keptBack = appCopyStale(root, slug).appCopyStale ?? null;
1619
- return false;
1620
- },
1621
- report: () =>
1622
- firstWrite || keptBack
1623
- ? {
1624
- ...(firstWrite ? {appCopy: {wrote: firstWrite}} : {}),
1625
- ...(keptBack ? {appCopyStale: keptBack} : {}),
1626
- }
1627
- : null,
1628
- finish: async () => {
1629
- // Said only after a build or check that ran: a refused one wrote
1630
- // and checked nothing.
1631
- if (skipped) {
1632
- if (ran) humanWarn(skipped);
1633
- } else if (!check) {
1634
- // The first write of the app copy is named once.
1635
- if (firstWrite)
1636
- humanWarn(
1637
- `wrote ${slug}'s app copy, a local theme \`theme add ${slug}\` takes, written again after every build: ${firstWrite.join(', ')}`,
1638
- );
1639
- // A copy a file or a link keeps behind, or one that could not be
1640
- // written, is said, as set and show say it.
1641
- if (keptBack) humanWarn(keptBack);
1642
- }
1643
- release();
1644
- await done;
1645
- },
1646
- });
1647
- }
1648
- return releaseAll;
1649
- }
1650
-
1651
- /**
1652
- * For `compile` of an editor theme's own source: how the app takes the
1653
- * theme, in place of importing the build's own outputs. The app takes its
1654
- * app copy (src/themes/<t>/, written after every build, with the font
1655
- * stylesheet that loads the theme's fonts), which `theme add` wires in.
1656
- * Null for any other file.
1657
- * @param {string} file the path as given
1658
- * @param {string} cwd
1659
- * @returns {string | null}
1660
- */
1661
- export function editorInstall(file, cwd) {
1662
- const root = projectRoot(cwd);
1663
- const at = editorThemeAt(root, path.resolve(cwd, file));
1664
- if (!at || path.basename(file) !== `${at.slug}.theme.ts`) return null;
1665
- return `Install in your app: the editor writes ${at.slug}'s app copy in src/themes/${at.slug}/ after every build (its module, stylesheet and font stylesheet), and the app takes that copy, not themes/${at.slug}/. Wire it in once:
1666
-
1667
- ${runLine(root, `theme add ${at.slug}`)}`;
1668
- }
1669
-
1670
- /**
1671
- * For `compile` of an editor theme's own source: how to load a family the
1672
- * build names, as the editor says it (the app copy imports a family's
1673
- * installed Fontsource package); null for any other file.
1674
- * @param {string} file the path as given
1675
- * @param {string} cwd
1676
- * @returns {import('../theme/build/build.mjs').FontHelp | null}
1677
- */
1678
- export function editorFontHelp(file, cwd) {
1679
- const root = projectRoot(cwd);
1680
- const at = editorThemeAt(root, path.resolve(cwd, file));
1681
- if (!at || path.basename(file) !== `${at.slug}.theme.ts`) return null;
1682
- const copy = `src/themes/${at.slug}/${at.slug}.fonts.css`;
1683
- /** @param {string} family */
1684
- const notice = family => {
1685
- const s = fontsourceSuggestion(family);
1686
- return s
1687
- ? `Font "${family}" is named by this theme but not loaded; ${s.known ? '' : 'if Fontsource publishes it, '}${installLine(root, [s.pkg])} installs its package, which ${copy} then imports`
1688
- : `Font "${family}" is named by this theme but not loaded, and no font package is named for it: the app must load it, or it falls back`;
1689
- };
1690
- return {
1691
- notice,
1692
- recipe: families => {
1693
- const all = families.map(fontsourceSuggestion).filter(s => s !== null);
1694
- // Packages the editor knows Fontsource publishes go on one install
1695
- // line; a name it cannot vouch for gets its own, so one that does
1696
- // not exist never stops the others installing.
1697
- const known = all.filter(s => s.known).map(s => s.pkg);
1698
- const guessed = all.filter(s => !s.known).map(s => s.pkg);
1699
- const lines = [
1700
- ...(known.length ? [installLine(root, known)] : []),
1701
- ...guessed.map(
1702
- pkg => `${installLine(root, [pkg])} (if Fontsource publishes it)`,
1703
- ),
1704
- ];
1705
- return ` The built CSS only sets font-family. ${at.slug}'s app copy loads a family
1706
- once its package is installed, importing it in ${copy} on the next
1707
- compile, set or show:
1708
- ${lines.length ? `\n${lines.map(l => ` ${l}`).join('\n')}\n` : '\n (no Fontsource package is named for these families: load them in your app)\n'}
1709
- Recipe and fallback-stack guidance: ${runLine(root, 'docs typography')}
1710
- `;
1711
- },
1712
- };
1713
- }
1714
-
1715
- /**
1716
- * For `compile`: the path an editor theme's own file builds under when it
1717
- * was named through a link (its real path, which every output's header
1718
- * names and `--check` compares); null for any other file.
1719
- * @param {string} file the path as given
1720
- * @param {string} cwd
1721
- * @returns {string | null}
1722
- */
1723
- export function editorSourcePath(file, cwd) {
1724
- const abs = path.resolve(cwd, slashed(file));
1725
- const realCwd = realLocation(cwd);
1726
- const real = realLocation(abs);
1727
- if (real === path.join(realCwd, path.relative(cwd, abs))) return null;
1728
- const at = editorThemeAt(projectRoot(cwd), real);
1729
- if (!at || !editorOwnFile(at.slug, real)) return null;
1730
- return path.relative(realCwd, real) || null;
1731
- }
1732
-
1733
- /** @param {string} p a path as typed, with Windows separators read as `/` */
1734
- const slashed = p => String(p).replace(/\\/g, '/');
1735
-
1736
- /**
1737
- * Whether --out names an editor theme's default output, where the build
1738
- * writes without --out: its folder, or its stylesheet file there (the same
1739
- * file, as the file system tells files apart: a name that differs only in
1740
- * case is another file on a case-sensitive disk). A folder form (a
1741
- * trailing slash) names a folder, so it is the default only as the theme's
1742
- * folder. No --out counts.
1743
- * @param {string} root the app root
1744
- * @param {string} slug
1745
- * @param {string} cwd
1746
- * @param {string | undefined} out
1747
- */
1748
- function outIsDefault(root, slug, cwd, out) {
1749
- if (!out) return true;
1750
- const typed = slashed(out);
1751
- const at = path.resolve(cwd, typed);
1752
- const f = themeFiles(root, slug);
1753
- if (sameFile(at, f.dir)) return true;
1754
- return !typed.endsWith('/') && sameFile(at, f.css);
1755
- }
1756
-
1757
- /**
1758
- * Whether two paths name one file: the same file on disk when both are
1759
- * there, else the same real path.
1760
- * @param {string} a
1761
- * @param {string} b
1762
- */
1763
- function sameFile(a, b) {
1764
- try {
1765
- const x = fs.statSync(a);
1766
- const y = fs.statSync(b);
1767
- return x.dev === y.dev && x.ino === y.ino;
1768
- } catch {
1769
- return realLocation(a) === realLocation(b);
1770
- }
1771
- }
1772
-
1773
- /**
1774
- * Why an editor theme's app copy was not written, or checked, by a build
1775
- * with --out elsewhere; null without one.
1776
- * @param {string} root
1777
- * @param {string} slug
1778
- * @param {string} cwd
1779
- * @param {{check?: boolean, out?: string}} opts
1780
- */
1781
- function outSkipsCopy(root, slug, cwd, {check, out}) {
1782
- if (outIsDefault(root, slug, cwd, out)) return null;
1783
- return check
1784
- ? `--check with --out checks only the files --out names: themes/${slug}/ and ${slug}'s app copy in src/themes/${slug}/ are not checked. Check without --out to check them.`
1785
- : `--out builds only the files it names: themes/${slug}/ and ${slug}'s app copy in src/themes/${slug}/ were not written. Compile without --out to write them.`;
1786
- }
1787
-
1788
- /**
1789
- * Whether a file in an app copy folder is the editor's: its mark, or the
1790
- * header the build writes. A missing file counts (it would be the copy's).
1791
- * @param {string} file
1792
- */
1793
- function isCopyFile(file) {
1794
- // A pipe or a device there is never opened: it stands where the copy's
1795
- // file goes.
1796
- if (irregularFileKind(file)) return true;
1797
- try {
1798
- const head = fs.readFileSync(file, 'utf8').slice(0, 600);
1799
- return (
1800
- head.includes(APP_COPY_MARK) ||
1801
- /@generated by `astryx theme build`/.test(head)
1802
- );
1803
- } catch {
1804
- return true;
1805
- }
1806
- }
1807
-
1808
- /**
1809
- * The editor theme whose app copy source a file is
1810
- * (`src/themes/<t>/<t>Theme.ts`, with themes/<t>/ an editor theme), or
1811
- * null.
1812
- * @param {string} root the project root
1813
- * @param {string} file absolute
1814
- * @returns {{root: string, slug: string} | null}
1815
- */
1816
- function appCopyTheme(root, file) {
1817
- const rel = path.relative(root, file).split(path.sep);
1818
- if (rel.length !== 4 || rel[0] !== 'src' || rel[1] !== 'themes') return null;
1819
- const slug = rel[2];
1820
- if (rel[3] !== `${camel(slug)}Theme.ts`) return null;
1821
- return fs.existsSync(themeFiles(root, slug).settings) ? {root, slug} : null;
1822
- }
1823
-
1824
- /**
1825
- * For `compile` of an editor theme: `appCopyStale` for its result data when
1826
- * the app copy is behind (the same line set and show give), or
1827
- * `appCopySkipped` when --out builds elsewhere (neither themes/<theme>/ nor
1828
- * the copy is written or checked); null for any other file or a current
1829
- * copy.
1830
- * @param {string} file the path as given
1831
- * @param {string} cwd
1832
- * @param {{check: boolean, upToDate?: boolean, out?: string, iconsSpecifier?: string}} opts
1833
- * `upToDate`: the check's own verdict on the theme's outputs
1834
- * @returns {Promise<Record<string, unknown> | null>}
1835
- */
1836
- export async function editorBuildExtra(file, cwd, opts) {
1837
- const root = projectRoot(cwd);
1838
- const abs = path.resolve(cwd, file);
1839
- const own = editorThemeAt(root, abs);
1840
- const slug =
1841
- appCopyTheme(root, abs)?.slug ??
1842
- (own && editorOwnFile(own.slug, file) ? own.slug : null);
1843
- if (!slug) return null;
1844
- {
1845
- const skipped = outSkipsCopy(root, slug, cwd, opts);
1846
- if (skipped) return {appCopySkipped: skipped};
1847
- }
1848
- if (!opts.check) {
1849
- // Every set and show builds the theme again from its source, without
1850
- // --icons-specifier: said, with the change that keeps it.
1851
- const warnings = opts.iconsSpecifier
1852
- ? [
1853
- `${slug} is a theme the editor made: every set and show builds it again from themes/${slug}/${slug}.theme.ts without --icons-specifier, which puts the theme's own import of the registry back. To keep this one, import the registry from its package in ${slug}.theme.ts.`,
1854
- ]
1855
- : [];
1856
- // What show says of the source's own type on phones, said by the
1857
- // compile that builds the app copy from it too.
1858
- /** @type {string[]} */
1859
- let notices;
1860
- try {
1861
- const data = loadTheme(root, slug);
1862
- notices = [
1863
- ...edit.ownPhoneNotes(root, slug, data),
1864
- // A weight the base theme's font stylesheet does not load.
1865
- ...baseWeightNotes(await context(root), data),
1866
- // A font role built as one family with no fallback.
1867
- ...loneFamilyNotes(await context(root), data),
1868
- ];
1869
- } catch {
1870
- notices = [];
1871
- }
1872
- if (warnings.length || notices.length)
1873
- return {
1874
- ...(warnings.length ? {warnings} : {}),
1875
- ...(notices.length ? {notices} : {}),
1876
- };
1877
- }
1878
- if (opts.check) {
1879
- // A theme output that is stale is the check's own finding (it names
1880
- // the file); the copy is compared only with a current build.
1881
- if (opts.upToDate === false) return null;
1882
- /** @type {string[] | null} */
1883
- let fonts;
1884
- try {
1885
- fonts = copyFontsCss(await context(root), slug, loadTheme(root, slug));
1886
- } catch {
1887
- fonts = null;
1888
- }
1889
- const behind = appCopyBehind(root, slug, fonts);
1890
- return behind
1891
- ? {
1892
- upToDate: false,
1893
- code: 'ERR_THEME_STALE',
1894
- // Something of yours in the way: its own line says what to move;
1895
- // no editor command writes over it.
1896
- appCopyStale: appCopyStale(root, slug).appCopyStale
1897
- ? `${slug}'s app copy in src/themes/${slug}/ is not up to date: ${behind}`
1898
- : `${slug}'s app copy in src/themes/${slug}/ is not up to date: ${behind}. ${runLine(root, `experimental theme editor show ${slug}`)} writes it again`,
1899
- }
1900
- : null;
1901
- }
1902
- // A build's copy write is reported once it has run (editorAfterBuild).
1903
- return null;
1904
- }
1905
-
1906
- /**
1907
- * For `compile` of an editor theme's own source (themes/<t>/<t>.theme.ts):
1908
- * the one color mode a light-only or dark-only theme has, which its source
1909
- * cannot say, for the build to write into the built module. Null for any
1910
- * other file (the app copy's source re-exports it from its build).
1911
- * @param {string} file the path as given
1912
- * @param {string} cwd
1913
- * @returns {['light'] | ['dark'] | null}
1914
- */
1915
- export function editorColorModes(file, cwd) {
1916
- const root = projectRoot(cwd);
1917
- const at = editorThemeAt(root, path.resolve(cwd, file));
1918
- if (!at || path.basename(file) !== `${at.slug}.theme.ts`) return null;
1919
- return buildColorModes(at.root, at.slug);
1920
- }
1921
-
1922
- /**
1923
- * For `compile` of an editor theme (themes/<t>/ or its app copy's source):
1924
- * whether a font family is loaded by the app copy's font stylesheet as
1925
- * this compile writes it (src/themes/<t>/<t>.fonts.css, from the fonts the
1926
- * theme loads now: an @fontsource package by its name, a stylesheet by the
1927
- * `family=` it requests), so the build's "named but not loaded" notice
1928
- * leaves it out. Null for any other file.
1929
- * @param {string} file the path as given
1930
- * @param {string} cwd
1931
- * @returns {Promise<((family: string) => boolean) | null>}
1932
- */
1933
- export async function editorLoadedFonts(file, cwd) {
1934
- const root = projectRoot(cwd);
1935
- const abs = path.resolve(cwd, file);
1936
- const slug =
1937
- appCopyTheme(root, abs)?.slug ??
1938
- (editorThemeAt(root, abs) &&
1939
- editorOwnFile(editorThemeAt(root, abs)?.slug ?? '', file)
1940
- ? editorThemeAt(root, abs)?.slug
1941
- : null);
1942
- if (!slug) return null;
1943
- // The stylesheets the copy's font file imports once this compile has
1944
- // written it: from the fonts the theme loads now, as the copy write
1945
- // computes them.
1946
- /** @type {string[]} */
1947
- let specs;
1948
- try {
1949
- specs = copyFontsCss(await context(root), slug, loadTheme(root, slug));
1950
- } catch {
1951
- return null;
1952
- }
1953
- const copyDir = path.join(root, 'src', 'themes', slug);
1954
- const from = fs.existsSync(copyDir) ? copyDir : root;
1955
- /** @type {Set<string>} */
1956
- const loaded = new Set();
1957
- for (const spec of specs)
1958
- for (const f of importedFontFamilies(spec, from)) loaded.add(f);
1959
- // A family the build names whose @fontsource package is installed: the
1960
- // copy written after this build imports that package (copyFontsCss).
1961
- /** @param {string} family */
1962
- const installed = family => {
1963
- const pkg = fontsourcePackageOf(family);
1964
- return pkg !== null && packageInstalled(root, pkg);
1965
- };
1966
- return family => loaded.has(fontKey(family)) || installed(family);
1967
- }
1968
-
1969
- /**
1970
- * For `compile` of a file that is not there: when it is an editor theme's
1971
- * own source (`themes/<t>/<t>.theme.ts` beside its settings), the command
1972
- * that writes it again; null otherwise.
1973
- * @param {string} file the path as given
1974
- * @param {string} cwd
1975
- * @returns {{name: string, reason: string} | null}
1976
- */
1977
- export function editorMissingSource(file, cwd) {
1978
- // The app copy's source of an editor theme, its folder gone: the editor
1979
- // writes it again.
1980
- const copy = appCopyTheme(projectRoot(cwd), path.resolve(cwd, slashed(file)));
1981
- if (copy)
1982
- // A copy file named with Windows separators: the theme is what
1983
- // compiles (the copy follows); with the copy gone, show writes it.
1984
- return fs.existsSync(path.join(copy.root, 'src', 'themes', copy.slug))
1985
- ? {
1986
- name: runLine(
1987
- cwd,
1988
- `experimental theme compile ${
1989
- path
1990
- .relative(
1991
- cwd,
1992
- path.join(
1993
- copy.root,
1994
- 'themes',
1995
- copy.slug,
1996
- `${copy.slug}.theme.ts`,
1997
- ),
1998
- )
1999
- .split(path.sep)
2000
- .join('/') || `themes/${copy.slug}/${copy.slug}.theme.ts`
2001
- }`,
2002
- ),
2003
- reason: `${copy.slug}'s app copy follows every compile of the theme`,
2004
- }
2005
- : {
2006
- name: runLine(cwd, `experimental theme editor show ${copy.slug}`),
2007
- reason: `the editor writes ${copy.slug}'s app copy in src/themes/${copy.slug}/ again`,
2008
- };
2009
- const at = editorThemeAt(projectRoot(cwd), path.resolve(cwd, file));
2010
- if (!at || path.basename(file) !== `${at.slug}.theme.ts`) return null;
2011
- return {
2012
- name: runLine(cwd, `experimental theme editor show ${at.slug}`),
2013
- reason: `the editor writes ${at.slug}.theme.ts again from its settings`,
2014
- };
2015
- }
2016
-
2017
- /**
2018
- * `theme template` for the experimental command: in a folder the theme
2019
- * editor made, only the editor's own files are protected.
2020
- * @param {{targetPath?: string, overwrite?: boolean, cwd?: string}} options
2021
- * @returns {import('../theme/theme.type.mjs').ThemeTemplateResponse}
2022
- */
2023
- export function editorThemeTemplate(options) {
2024
- return writeThemeTemplate(options, true);
2025
- }