@astryxdesign/cli 0.7.18-canary.gfacee17 → 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 (363) 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 +5 -5
  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 +2 -2
  16. package/api/icon/_adapter.mjs +6 -2
  17. package/api/icon/_authoring.mjs +22 -13
  18. package/api/icon/_default-look.mjs +15 -15
  19. package/api/icon/add/add.mjs +14 -9
  20. package/api/icon/icon.doc.mjs +7 -7
  21. package/api/icon/icon.type.d.mts +33 -33
  22. package/api/icon/icon.type.mjs +45 -45
  23. package/api/icon/iconAdd.doc.mjs +9 -10
  24. package/api/icon/iconMap.doc.mjs +11 -12
  25. package/api/icon/iconNewDefinition.doc.mjs +8 -8
  26. package/api/icon/iconNewSet.doc.mjs +5 -5
  27. package/api/icon/map/map.mjs +7 -7
  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/integration/validate-integration.type.d.mts +6 -6
  32. package/api/integration/validate-integration.type.mjs +6 -6
  33. package/api/render/_adapter.d.mts +5 -3
  34. package/api/render/_adapter.mjs +64 -4
  35. package/api/render/render.doc.mjs +9 -2
  36. package/api/render/render.mjs +5 -2
  37. package/api/render/render.type.d.mts +17 -0
  38. package/api/render/render.type.mjs +10 -0
  39. package/api/search/ORDERING.md +1 -1
  40. package/api/search/_candidate-score.mjs +20 -0
  41. package/api/search/_words.d.mts +8 -0
  42. package/api/search/_words.mjs +15 -0
  43. package/api/template/template.type.d.mts +2 -2
  44. package/api/template/template.type.mjs +2 -2
  45. package/api/theme/_adapter.mjs +19 -11
  46. package/api/theme/build/build.d.mts +19 -51
  47. package/api/theme/build/build.mjs +195 -189
  48. package/api/theme/build/font-warning.d.mts +19 -2
  49. package/api/theme/build/font-warning.mjs +46 -5
  50. package/api/theme/generateTonalPalette.doc.mjs +1 -1
  51. package/api/theme/palette/generate/derive-look.mjs +108 -37
  52. package/api/theme/palette/generate/mapping.mjs +2 -0
  53. package/api/theme/template/template.d.mts +0 -17
  54. package/api/theme/template/template.mjs +1 -42
  55. package/api/theme/theme.type.d.mts +5 -4
  56. package/api/theme/theme.type.mjs +5 -4
  57. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  58. package/api/theme/themeRemove.doc.mjs +1 -1
  59. package/assets/codemods/transforms/v0.7.0/preserve-bottom-sheet-content-padding.mjs +3 -1
  60. package/assets/component-list.generated.json +1 -1
  61. package/assets/discover/official-packages.json +26 -2
  62. package/assets/docs/author-a-theme.doc.mjs +6 -5
  63. package/assets/docs/browser-support.doc.mjs +1 -0
  64. package/assets/docs/icons.doc.mjs +8 -7
  65. package/assets/docs/motion.doc.mjs +46 -0
  66. package/assets/docs/theme.doc.dense.mjs +6 -17
  67. package/assets/docs/theme.doc.mjs +6 -16
  68. package/assets/docs/theme.doc.zh.mjs +6 -16
  69. package/assets/docs/tree/ci-and-containers.doc.mjs +1 -1
  70. package/assets/docs/tree/data-colors-in-renderers.doc.mjs +400 -0
  71. package/assets/docs/tree/font-setup.doc.mjs +30 -0
  72. package/assets/docs/tree/icon-sets.doc.mjs +2 -2
  73. package/assets/docs/tree/share-a-page.doc.mjs +1 -1
  74. package/assets/docs/tree/template-icons.doc.mjs +3 -3
  75. package/assets/docs/tree/tokens-color.doc.mjs +5 -0
  76. package/assets/docs/tree/tokens.doc.mjs +4 -3
  77. package/assets/docs/tree/updates.doc.mjs +1 -1
  78. package/assets/docs/tree/visualization.doc.mjs +30 -0
  79. package/assets/docs-routes.generated.json +1 -1
  80. package/assets/docs.generated.json +2 -2
  81. package/assets/icons/definitions/drag.doc.mjs +1 -0
  82. package/assets/search-catalog.generated.json +2 -2
  83. package/assets/self-audit.generated.json +1 -1
  84. package/assets/templates/blocks/components/Card/SelectableCardElevated.doc.mjs +1 -1
  85. package/assets/templates/blocks/components/Card/SelectableCardElevated.tsx +20 -10
  86. package/assets/templates/blocks/components/Card/SelectableCardShowcase.doc.mjs +1 -1
  87. package/assets/templates/blocks/components/Card/SelectableCardShowcase.tsx +36 -16
  88. package/assets/templates/blocks/components/ChatComposerInput/ChatComposerInputMentionTrigger.tsx +6 -0
  89. package/assets/templates/blocks/components/ChatComposerInput/ChatComposerInputMultipleTriggers.tsx +6 -0
  90. package/assets/templates/blocks/components/Hooks/useIndicatorFocusRingHookUsage.doc.mjs +14 -0
  91. package/assets/templates/blocks/components/Hooks/useIndicatorFocusRingHookUsage.tsx +63 -0
  92. package/assets/templates/blocks/components/Hooks/useLongPressHookUsage.doc.mjs +29 -0
  93. package/assets/templates/blocks/components/Hooks/useLongPressHookUsage.tsx +237 -0
  94. package/assets/templates/blocks/components/SideNav/SideNavShowcase.tsx +10 -72
  95. package/assets/templates/blocks/components/SideNav/SideNavWithHeaderMenu.doc.mjs +1 -1
  96. package/assets/templates/blocks/components/SideNav/SideNavWithHeaderMenu.tsx +7 -7
  97. package/assets/templates/blocks/components/Table/TableCustomRowTable.doc.mjs +14 -0
  98. package/assets/templates/blocks/components/Table/TableCustomRowTable.tsx +96 -0
  99. package/assets/templates/components.generated.json +1 -1
  100. package/assets/templates/pages/ai-chat-landing/page.tsx +4 -0
  101. package/assets/templates/pages/dashboard-scorecard/page.tsx +26 -7
  102. package/assets/templates/pages/editor/page.tsx +13 -3
  103. package/assets/templates/themes/butter/butterPaletteRefs.generated.ts +2 -2
  104. package/assets/templates/themes/butter/butterTheme.ts +12 -10
  105. package/assets/templates/themes/butter/icons.tsx +2 -0
  106. package/assets/templates/themes/chocolate/chocolateTheme.ts +1 -0
  107. package/assets/templates/themes/chocolate/icons.tsx +2 -0
  108. package/assets/templates/themes/gothic/gothicPaletteRefs.generated.ts +1 -1
  109. package/assets/templates/themes/gothic/gothicTheme.ts +1 -0
  110. package/assets/templates/themes/gothic/icons.tsx +2 -0
  111. package/assets/templates/themes/matcha/icons.tsx +2 -0
  112. package/assets/templates/themes/matcha/matchaPaletteRefs.generated.ts +2 -2
  113. package/assets/templates/themes/matcha/matchaTheme.ts +1 -0
  114. package/assets/templates/themes/neutral/icons.tsx +2 -0
  115. package/assets/templates/themes/neutral/neutralPaletteRefs.generated.ts +2 -2
  116. package/assets/templates/themes/neutral/neutralTheme.ts +1 -0
  117. package/assets/templates/themes/stone/icons.tsx +2 -0
  118. package/assets/templates/themes/stone/stonePaletteRefs.generated.ts +1 -1
  119. package/assets/templates/themes/stone/stoneTheme.ts +1 -0
  120. package/assets/templates/themes/y2k/icons.tsx +2 -0
  121. package/assets/templates/themes/y2k/y2kTheme.ts +1 -0
  122. package/assets/theme.template.ts +9 -5
  123. package/authoring/config/parse.mjs +1 -1
  124. package/authoring/doctypes/base/type.ts +2 -3
  125. package/authoring/doctypes/component/component.doc.mjs +1 -1
  126. package/authoring/doctypes/icon-set/icon-names.mjs +1 -0
  127. package/authoring/integration/integration.doc.mjs +1 -1
  128. package/authoring/integration/type.ts +1 -1
  129. package/clients/cli/build-id.generated.json +1 -1
  130. package/clients/cli/commands/doctor.mjs +2 -2
  131. package/clients/cli/commands/experimental/export.mjs +2 -1
  132. package/clients/cli/commands/experimental/icon.mjs +17 -17
  133. package/clients/cli/commands/experimental/index.mjs +0 -5
  134. package/clients/cli/commands/experimental/render-output.mjs +9 -0
  135. package/clients/cli/commands/experimental-export.doc.mjs +6 -0
  136. package/clients/cli/commands/experimental-icon-add.doc.mjs +8 -8
  137. package/clients/cli/commands/experimental-icon-map.doc.mjs +6 -6
  138. package/clients/cli/commands/experimental-icon-new-definition.doc.mjs +6 -6
  139. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +3 -3
  140. package/clients/cli/commands/experimental-icon-use.doc.mjs +1 -1
  141. package/clients/cli/commands/experimental-icon.doc.mjs +6 -6
  142. package/clients/cli/commands/experimental.doc.mjs +2 -6
  143. package/clients/cli/commands/template.mjs +1 -1
  144. package/clients/cli/commands/theme-build.doc.mjs +8 -1
  145. package/clients/cli/commands/theme-palette-generate.doc.mjs +1 -1
  146. package/clients/cli/commands/theme-remove.doc.mjs +1 -1
  147. package/clients/cli/commands/theme.doc.mjs +1 -11
  148. package/clients/cli/commands/theme.mjs +110 -475
  149. package/clients/cli/commands.generated.json +1 -1
  150. package/clients/cli/index.mjs +4 -34
  151. package/clients/cli/lib/base-gate.mjs +2 -3
  152. package/clients/cli/lib/cli-error.mjs +8 -72
  153. package/clients/cli/lib/define-command.mjs +0 -19
  154. package/clients/cli/lib/json-shim.mjs +11 -633
  155. package/clients/cli/lib/manifest.mjs +0 -4
  156. package/clients/cli/lib/stray-option.mjs +1 -2
  157. package/clients/cli/manifest.generated.json +1 -1
  158. package/foundation/agent-docs/agent-docs.mjs +1 -1
  159. package/foundation/color/css-color.mjs +2 -3
  160. package/foundation/discovery/app-layout.d.mts +13 -0
  161. package/foundation/discovery/app-layout.mjs +35 -0
  162. package/foundation/discovery/cli-self-docs.mjs +4 -4
  163. package/foundation/discovery/fixture-refs.d.mts +51 -0
  164. package/foundation/discovery/fixture-refs.mjs +351 -0
  165. package/foundation/discovery/icon-definition-discovery.mjs +7 -7
  166. package/foundation/discovery/icon-ranking.mjs +2 -2
  167. package/foundation/discovery/icon-set-checks.mjs +6 -6
  168. package/foundation/discovery/icon-set-discovery.mjs +2 -2
  169. package/foundation/discovery/icon-set-writer.d.mts +24 -7
  170. package/foundation/discovery/icon-set-writer.mjs +75 -31
  171. package/foundation/discovery/static-descriptor.d.mts +49 -0
  172. package/foundation/discovery/static-descriptor.mjs +548 -0
  173. package/foundation/discovery/template-adapter.d.mts +0 -47
  174. package/foundation/discovery/template-adapter.mjs +1 -333
  175. package/foundation/discovery/theme-discovery.d.mts +6 -47
  176. package/foundation/discovery/theme-discovery.mjs +15 -537
  177. package/foundation/doc-compiler/bundle.mjs +2 -2
  178. package/foundation/doc-compiler/import.mjs +1 -1
  179. package/foundation/env/user-dirs.d.mts +5 -2
  180. package/foundation/env/user-dirs.mjs +12 -5
  181. package/foundation/fonts/next-font.d.mts +26 -0
  182. package/foundation/fonts/next-font.mjs +149 -0
  183. package/foundation/fs/empty-folder.mjs +2 -2
  184. package/foundation/fs/read-record.mjs +11 -4
  185. package/foundation/pictures/pictures.d.mts +152 -0
  186. package/foundation/pictures/pictures.mjs +565 -0
  187. package/foundation/release/folder-lock.mjs +3 -2
  188. package/foundation/render/cut-short.d.mts +2 -2
  189. package/foundation/render/cut-short.mjs +2 -2
  190. package/foundation/render/drawn-contrast.d.mts +2 -2
  191. package/foundation/render/drawn-contrast.mjs +2 -2
  192. package/foundation/render/font-probe.d.mts +2 -2
  193. package/foundation/render/font-probe.mjs +2 -2
  194. package/foundation/render/layers.mjs +1 -2
  195. package/foundation/render/package-resolve-hooks.d.mts +25 -5
  196. package/foundation/render/package-resolve-hooks.mjs +77 -14
  197. package/foundation/render/page-worker.mjs +24 -12
  198. package/foundation/render/part-boxes.d.mts +2 -3
  199. package/foundation/render/part-boxes.mjs +2 -3
  200. package/foundation/render/picture-chrome.mjs +18 -15
  201. package/foundation/render/picture-playwright.mjs +10 -7
  202. package/foundation/render/picture-window.d.mts +13 -0
  203. package/foundation/render/picture-window.mjs +31 -0
  204. package/foundation/render/render-page.d.mts +1 -1
  205. package/foundation/render/render-page.mjs +4 -5
  206. package/foundation/render/single-copy-hooks.d.mts +2 -0
  207. package/foundation/render/single-copy-hooks.mjs +2 -0
  208. package/foundation/response/error-codes.doc.mjs +14 -14
  209. package/foundation/response/error-codes.mjs +13 -13
  210. package/foundation/response/response-types.doc.mjs +8 -69
  211. package/foundation/runtime/css-tree.mjs +2 -2
  212. package/foundation/runtime/word-table.d.mts +1 -1
  213. package/foundation/runtime/word-table.mjs +1 -1
  214. package/foundation/suggest/other-command.d.mts +52 -15
  215. package/foundation/suggest/other-command.mjs +168 -45
  216. package/foundation/text/suggest-order.d.mts +7 -0
  217. package/foundation/text/suggest-order.mjs +1 -1
  218. package/package.json +7 -8
  219. package/api/theme-edit/_adapter.d.mts +0 -228
  220. package/api/theme-edit/_adapter.mjs +0 -2025
  221. package/api/theme-edit/_catalog.d.mts +0 -172
  222. package/api/theme-edit/_catalog.mjs +0 -806
  223. package/api/theme-edit/_check.d.mts +0 -391
  224. package/api/theme-edit/_check.mjs +0 -9370
  225. package/api/theme-edit/_color.d.mts +0 -135
  226. package/api/theme-edit/_color.mjs +0 -480
  227. package/api/theme-edit/_compiler.d.mts +0 -77
  228. package/api/theme-edit/_compiler.mjs +0 -1053
  229. package/api/theme-edit/_context.d.mts +0 -399
  230. package/api/theme-edit/_context.mjs +0 -1778
  231. package/api/theme-edit/_css.d.mts +0 -169
  232. package/api/theme-edit/_css.mjs +0 -1167
  233. package/api/theme-edit/_edit.d.mts +0 -167
  234. package/api/theme-edit/_edit.mjs +0 -11220
  235. package/api/theme-edit/_how-commands.d.mts +0 -315
  236. package/api/theme-edit/_how-commands.mjs +0 -1664
  237. package/api/theme-edit/_how-question.d.mts +0 -341
  238. package/api/theme-edit/_how-question.mjs +0 -33291
  239. package/api/theme-edit/_how-sides.d.mts +0 -22
  240. package/api/theme-edit/_how-sides.mjs +0 -173
  241. package/api/theme-edit/_how-steps.d.mts +0 -42
  242. package/api/theme-edit/_how-steps.mjs +0 -208
  243. package/api/theme-edit/_how-values.d.mts +0 -29
  244. package/api/theme-edit/_how-values.mjs +0 -111
  245. package/api/theme-edit/_how-words.d.mts +0 -15
  246. package/api/theme-edit/_how-words.mjs +0 -239
  247. package/api/theme-edit/_how.d.mts +0 -55
  248. package/api/theme-edit/_how.mjs +0 -2388
  249. package/api/theme-edit/_importers.d.mts +0 -38
  250. package/api/theme-edit/_importers.mjs +0 -188
  251. package/api/theme-edit/_marks.d.mts +0 -39
  252. package/api/theme-edit/_marks.mjs +0 -67
  253. package/api/theme-edit/_missed.d.mts +0 -56
  254. package/api/theme-edit/_missed.mjs +0 -1128
  255. package/api/theme-edit/_name-rule.d.mts +0 -11
  256. package/api/theme-edit/_name-rule.mjs +0 -12
  257. package/api/theme-edit/_normal.d.mts +0 -365
  258. package/api/theme-edit/_normal.mjs +0 -1978
  259. package/api/theme-edit/_overview.d.mts +0 -9
  260. package/api/theme-edit/_overview.mjs +0 -293
  261. package/api/theme-edit/_palette.d.mts +0 -616
  262. package/api/theme-edit/_palette.mjs +0 -2776
  263. package/api/theme-edit/_part-pieces.d.mts +0 -54
  264. package/api/theme-edit/_part-pieces.mjs +0 -179
  265. package/api/theme-edit/_part-words.d.mts +0 -39
  266. package/api/theme-edit/_part-words.mjs +0 -242
  267. package/api/theme-edit/_parts.d.mts +0 -402
  268. package/api/theme-edit/_parts.mjs +0 -2294
  269. package/api/theme-edit/_picture-traits.d.mts +0 -259
  270. package/api/theme-edit/_picture-traits.mjs +0 -1030
  271. package/api/theme-edit/_png.d.mts +0 -94
  272. package/api/theme-edit/_png.mjs +0 -479
  273. package/api/theme-edit/_preview-app.d.mts +0 -172
  274. package/api/theme-edit/_preview-app.mjs +0 -6430
  275. package/api/theme-edit/_preview.d.mts +0 -549
  276. package/api/theme-edit/_preview.mjs +0 -3264
  277. package/api/theme-edit/_project.d.mts +0 -207
  278. package/api/theme-edit/_project.mjs +0 -643
  279. package/api/theme-edit/_resolved.d.mts +0 -46
  280. package/api/theme-edit/_resolved.mjs +0 -800
  281. package/api/theme-edit/_set-line.d.mts +0 -29
  282. package/api/theme-edit/_set-line.mjs +0 -100
  283. package/api/theme-edit/_settings.d.mts +0 -2426
  284. package/api/theme-edit/_settings.mjs +0 -18435
  285. package/api/theme-edit/_tables.d.mts +0 -227
  286. package/api/theme-edit/_tables.mjs +0 -1128
  287. package/api/theme-edit/_text-looks.d.mts +0 -78
  288. package/api/theme-edit/_text-looks.mjs +0 -376
  289. package/api/theme-edit/_vet.d.mts +0 -50
  290. package/api/theme-edit/_vet.mjs +0 -166
  291. package/api/theme-edit/how/how.d.mts +0 -17
  292. package/api/theme-edit/how/how.mjs +0 -28
  293. package/api/theme-edit/new/new.d.mts +0 -11
  294. package/api/theme-edit/new/new.mjs +0 -22
  295. package/api/theme-edit/preview-add/preview-add.d.mts +0 -14
  296. package/api/theme-edit/preview-add/preview-add.mjs +0 -25
  297. package/api/theme-edit/preview-app/preview-app.d.mts +0 -13
  298. package/api/theme-edit/preview-app/preview-app.mjs +0 -24
  299. package/api/theme-edit/preview-list/preview-list.d.mts +0 -10
  300. package/api/theme-edit/preview-list/preview-list.mjs +0 -21
  301. package/api/theme-edit/preview-remove/preview-remove.d.mts +0 -12
  302. package/api/theme-edit/preview-remove/preview-remove.mjs +0 -23
  303. package/api/theme-edit/set/set.d.mts +0 -13
  304. package/api/theme-edit/set/set.mjs +0 -24
  305. package/api/theme-edit/show/show.d.mts +0 -13
  306. package/api/theme-edit/show/show.mjs +0 -24
  307. package/api/theme-edit/theme-edit.d.mts +0 -12
  308. package/api/theme-edit/theme-edit.mjs +0 -36
  309. package/api/theme-edit/theme-edit.type.d.mts +0 -730
  310. package/api/theme-edit/theme-edit.type.mjs +0 -342
  311. package/api/theme-edit/themeEditHow.doc.d.mts +0 -6
  312. package/api/theme-edit/themeEditHow.doc.mjs +0 -105
  313. package/api/theme-edit/themeEditNew.doc.d.mts +0 -5
  314. package/api/theme-edit/themeEditNew.doc.mjs +0 -112
  315. package/api/theme-edit/themeEditPreviewAdd.doc.d.mts +0 -6
  316. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +0 -121
  317. package/api/theme-edit/themeEditPreviewApp.doc.d.mts +0 -6
  318. package/api/theme-edit/themeEditPreviewApp.doc.mjs +0 -87
  319. package/api/theme-edit/themeEditPreviewList.doc.d.mts +0 -6
  320. package/api/theme-edit/themeEditPreviewList.doc.mjs +0 -62
  321. package/api/theme-edit/themeEditPreviewRemove.doc.d.mts +0 -6
  322. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +0 -96
  323. package/api/theme-edit/themeEditSet.doc.d.mts +0 -6
  324. package/api/theme-edit/themeEditSet.doc.mjs +0 -175
  325. package/api/theme-edit/themeEditShow.doc.d.mts +0 -6
  326. package/api/theme-edit/themeEditShow.doc.mjs +0 -118
  327. package/api/theme-edit/themeEditUndo.doc.d.mts +0 -6
  328. package/api/theme-edit/themeEditUndo.doc.mjs +0 -133
  329. package/api/theme-edit/undo/undo.d.mts +0 -13
  330. package/api/theme-edit/undo/undo.mjs +0 -24
  331. package/assets/preview-app/README.md +0 -6
  332. package/assets/preview-app/css.d.ts +0 -5
  333. package/assets/preview-app/gitignore +0 -4
  334. package/assets/preview-app/next.config.mjs +0 -12
  335. package/assets/preview-app/package.json +0 -24
  336. package/assets/preview-app/src/app/globals.css +0 -6
  337. package/assets/preview-app/src/app/layout.tsx +0 -21
  338. package/assets/preview-app/src/app/page.tsx +0 -94
  339. package/assets/preview-app/src/app/providers.tsx +0 -16
  340. package/assets/preview-app/tsconfig.json +0 -27
  341. package/clients/cli/commands/experimental/theme.mjs +0 -2990
  342. package/clients/cli/commands/experimental-theme-add.doc.mjs +0 -80
  343. package/clients/cli/commands/experimental-theme-compile.doc.mjs +0 -98
  344. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +0 -196
  345. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -174
  346. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +0 -139
  347. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +0 -77
  348. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +0 -105
  349. package/clients/cli/commands/experimental-theme-editor.doc.mjs +0 -49
  350. package/clients/cli/commands/experimental-theme-eject.doc.mjs +0 -72
  351. package/clients/cli/commands/experimental-theme-list.doc.mjs +0 -49
  352. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +0 -88
  353. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +0 -61
  354. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +0 -48
  355. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +0 -59
  356. package/clients/cli/commands/experimental-theme-preview.doc.mjs +0 -41
  357. package/clients/cli/commands/experimental-theme-remove.doc.mjs +0 -57
  358. package/clients/cli/commands/experimental-theme-targets.doc.mjs +0 -62
  359. package/clients/cli/commands/experimental-theme-template.doc.mjs +0 -63
  360. package/clients/cli/commands/experimental-theme-use.doc.mjs +0 -57
  361. package/clients/cli/commands/experimental-theme.doc.mjs +0 -60
  362. package/foundation/fonts/fontsource-families.generated.d.mts +0 -5
  363. package/foundation/fonts/fontsource-families.generated.mjs +0 -2110
@@ -1,2990 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file `astryx experimental theme` — the `editor` group makes and changes a
5
- * theme one checked change at a time; beside it sit experimental copies of
6
- * the theme commands. Experimental (spec:AST-017 FR27): it is registered only
7
- * under the `experimental` group.
8
- *
9
- * The command surface comes from the colocated CommandDocs via
10
- * `defineCommand`; this file reads flags, calls the theme-edit API, and
11
- * prints its receipt.
12
- *
13
- * Usage:
14
- * astryx experimental theme editor new brand --like neutral
15
- * astryx experimental theme editor set brand corners pill
16
- * astryx experimental theme editor how "white text in the banner"
17
- */
18
-
19
- import {getCliInvocation} from '../../../../foundation/env/package-manager.mjs';
20
- import {jsonOut} from '../../../../foundation/response/json.mjs';
21
- import {levenshteinDistance} from '../../../../foundation/text/levenshtein.mjs';
22
- import {NO_RESULT_SET, resultSet} from '../../../../foundation/debug/index.mjs';
23
- import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
24
- import {
25
- emit,
26
- list,
27
- record,
28
- records,
29
- section,
30
- text,
31
- } from '../../formatters/index.mjs';
32
- import {cliError} from '../../lib/cli-error.mjs';
33
- import {
34
- editorMissingArgument,
35
- setFreeArgument,
36
- setEditorThemeList,
37
- setUnknownOptionReader,
38
- } from '../../lib/json-shim.mjs';
39
- import {AstryxError} from '../../../../api/error.mjs';
40
- import {defineCommand} from '../../lib/define-command.mjs';
41
- import {
42
- themeEditHow,
43
- themeEditNew,
44
- themeEditPreviewAdd,
45
- themeEditPreviewApp,
46
- themeEditPreviewList,
47
- themeEditPreviewRemove,
48
- themeEditSet,
49
- themeEditShow,
50
- themeEditUndo,
51
- } from '../../../../api/theme-edit/theme-edit.mjs';
52
- import {
53
- builtInThemes,
54
- dialValueFits,
55
- modeDialValue,
56
- newFlagList,
57
- editorCheckedLine,
58
- editorCheckedNewLines,
59
- editorCheckedShowLines,
60
- splitCommand,
61
- booleanWord,
62
- editorCompileProblem,
63
- editorFollowCompile,
64
- editorThemesAt,
65
- editorFreeName,
66
- editorNameOk,
67
- editorFreeAppFolder,
68
- typoNear,
69
- typoOf,
70
- editorAfterBuild,
71
- editorFontHelp,
72
- editorInstall,
73
- editorSourcePath,
74
- editorBuildExtra,
75
- editorLoadedFonts,
76
- editorColorModes,
77
- editorThemeHold,
78
- editorThemeRefusal,
79
- editorMissingSource,
80
- editorThemeTemplate,
81
- showSections,
82
- describe,
83
- namesSetting,
84
- needsPart,
85
- } from '../../../../api/theme-edit/_adapter.mjs';
86
- import {registerThemeSubcommands} from '../theme.mjs';
87
- import {doc as groupDoc} from '../experimental-theme.doc.mjs';
88
- import {doc as editorDoc} from '../experimental-theme-editor.doc.mjs';
89
- import {doc as newDoc} from '../experimental-theme-editor-new.doc.mjs';
90
- import {doc as setDoc} from '../experimental-theme-editor-set.doc.mjs';
91
- import {doc as showDoc} from '../experimental-theme-editor-show.doc.mjs';
92
- import {doc as undoDoc} from '../experimental-theme-editor-undo.doc.mjs';
93
- import {doc as previewDoc} from '../experimental-theme-preview.doc.mjs';
94
- import {doc as previewAddDoc} from '../experimental-theme-preview-add.doc.mjs';
95
- import {doc as previewAppDoc} from '../experimental-theme-preview-app.doc.mjs';
96
- import {doc as previewListDoc} from '../experimental-theme-preview-list.doc.mjs';
97
- import {doc as previewRemoveDoc} from '../experimental-theme-preview-remove.doc.mjs';
98
- import {doc as howDoc} from '../experimental-theme-editor-how.doc.mjs';
99
- import {doc as compileDoc} from '../experimental-theme-compile.doc.mjs';
100
- import {doc as listDoc} from '../experimental-theme-list.doc.mjs';
101
- import {doc as addDoc} from '../experimental-theme-add.doc.mjs';
102
- import {doc as removeDoc} from '../experimental-theme-remove.doc.mjs';
103
- import {doc as useDoc} from '../experimental-theme-use.doc.mjs';
104
- import {doc as ejectDoc} from '../experimental-theme-eject.doc.mjs';
105
- import {doc as templateDoc} from '../experimental-theme-template.doc.mjs';
106
- import {doc as targetsDoc} from '../experimental-theme-targets.doc.mjs';
107
- import {doc as newFn} from '../../../../api/theme-edit/themeEditNew.doc.mjs';
108
- import {doc as setFn} from '../../../../api/theme-edit/themeEditSet.doc.mjs';
109
- import {doc as showFn} from '../../../../api/theme-edit/themeEditShow.doc.mjs';
110
- import {doc as undoFn} from '../../../../api/theme-edit/themeEditUndo.doc.mjs';
111
- import {doc as previewAddFn} from '../../../../api/theme-edit/themeEditPreviewAdd.doc.mjs';
112
- import {doc as previewAppFn} from '../../../../api/theme-edit/themeEditPreviewApp.doc.mjs';
113
- import {doc as previewListFn} from '../../../../api/theme-edit/themeEditPreviewList.doc.mjs';
114
- import {doc as previewRemoveFn} from '../../../../api/theme-edit/themeEditPreviewRemove.doc.mjs';
115
- import {doc as howFn} from '../../../../api/theme-edit/themeEditHow.doc.mjs';
116
- import {quoteCommandArgument} from '../../../../foundation/env/package-manager.mjs';
117
- import {
118
- commandAvailable,
119
- exampleAvailable,
120
- helpBase,
121
- } from '../../lib/base-gate.mjs';
122
-
123
- const PREFIX = 'astryx experimental theme';
124
- const EDITOR = `${PREFIX} editor`;
125
- /** The lookup command, named once: its CommandDoc's last word. */
126
- const HOW = `${EDITOR} ${howDoc.name.split(' ').pop()}`;
127
-
128
- /**
129
- * Commands in a line, with the run prefix this project uses.
130
- * @param {string} line
131
- */
132
- const cmd = line => {
133
- const stem = `${getCliInvocation()} experimental theme`;
134
- // A line that already starts its commands this way (how's answers do,
135
- // in JSON too) keeps them.
136
- return line
137
- .split(stem)
138
- .map(part => part.split(PREFIX).join(stem))
139
- .join(stem);
140
- };
141
- /** The project's invocation of a command line (cmd, under a name an action's own `cmd` parameter does not hide). */
142
-
143
- /**
144
- * Print blocks, a blank line between them, with this project's run prefix
145
- * in every command.
146
- * @param {Array<string | import('../../formatters/index.mjs').Block>} blocks
147
- */
148
- const print = blocks => emit(...blocks.map(b => text(cmd(String(b)))));
149
-
150
- /** @param {unknown} v */
151
- const isEmptyValue = v =>
152
- v == null || v === '' || (Array.isArray(v) && v.length === 0);
153
-
154
- /**
155
- * One value as record text: an array comma-joined, an object as
156
- * `key: value` pairs, and an empty value as `none`, so every JSON key shows.
157
- * @param {unknown} v
158
- * @returns {string}
159
- */
160
- function shownValue(v) {
161
- if (isEmptyValue(v)) return 'none';
162
- if (Array.isArray(v))
163
- return (
164
- v
165
- .map(x => (x && typeof x === 'object' ? shownValue(x) : String(x)))
166
- .join(', ') || 'none'
167
- );
168
- if (typeof v === 'object')
169
- return Object.entries(/** @type {Record<string, unknown>} */ (v))
170
- .map(([k, x]) => `${k}: ${shownValue(x)}`)
171
- .join('; ');
172
- return String(v);
173
- }
174
-
175
- /**
176
- * One object as record fields: a nested object's own fields join the
177
- * record, so every label is a JSON key.
178
- * @param {Record<string, unknown>} o
179
- * @returns {Record<string, string>}
180
- */
181
- function flatRecord(o) {
182
- /** @type {Record<string, string>} */
183
- const out = {};
184
- for (const [k, v] of Object.entries(o)) {
185
- if (Array.isArray(v) && !v.length) continue;
186
- if (v && typeof v === 'object' && !Array.isArray(v)) {
187
- const inner = Object.entries(/** @type {Record<string, unknown>} */ (v));
188
- // A map of objects keeps one field per entry, so no entry overwrites
189
- // another.
190
- if (
191
- inner.some(([, x]) => x && typeof x === 'object' && !Array.isArray(x))
192
- )
193
- for (const [name, x] of inner) out[name] = shownValue(x);
194
- else
195
- Object.assign(
196
- out,
197
- flatRecord(/** @type {Record<string, unknown>} */ (v)),
198
- );
199
- } else out[k] = shownValue(v);
200
- }
201
- return out;
202
- }
203
-
204
- /**
205
- * The text projection of an envelope's data, with field names that match
206
- * its JSON keys: plain fields in one record; a long list, a list of objects,
207
- * or an object as a section of its own.
208
- * @param {Record<string, unknown>} data
209
- * @returns {Array<string | import('../../formatters/index.mjs').Block>}
210
- */
211
- function project(data) {
212
- /** @type {Record<string, string>} */
213
- const plain = {};
214
- /** @type {Array<string | import('../../formatters/index.mjs').Block>} */
215
- const parts = [];
216
- for (const [k, v] of Object.entries(data)) {
217
- // An empty list has no field in the JSON projection, so none here.
218
- if (Array.isArray(v) && !v.length) continue;
219
- if (isEmptyValue(v) || (v !== null && typeof v !== 'object')) {
220
- plain[k] = shownValue(v);
221
- } else if (Array.isArray(v) && typeof v[0] !== 'object') {
222
- const joined = v.join(', ');
223
- if (v.length <= 3 && joined.length <= 80) plain[k] = joined;
224
- else parts.push(section(`${k}:`), list(v.map(String)));
225
- } else if (Array.isArray(v)) {
226
- const items = /** @type {Record<string, unknown>[]} */ (v).map(
227
- flatRecord,
228
- );
229
- // Short items print one per line; items with prose print as records.
230
- const prose = items.some(o => Object.values(o).some(x => x.length > 100));
231
- parts.push(
232
- section(`${k}:`),
233
- records(items, prose ? {} : {layout: 'inline'}),
234
- );
235
- } else {
236
- const entries = Object.entries(
237
- /** @type {Record<string, unknown>} */ (v),
238
- );
239
- if (
240
- entries.every(
241
- ([, x]) =>
242
- x === null ||
243
- typeof x !== 'object' ||
244
- (Array.isArray(x) && typeof x[0] !== 'object'),
245
- )
246
- )
247
- parts.push(
248
- section(`${k}:`),
249
- record(flatRecord(Object.fromEntries(entries))),
250
- );
251
- else {
252
- // Plain fields of a mixed object print first, as `<key> <field>`.
253
- /** @type {Record<string, string>} */
254
- const head = {};
255
- /** @type {Array<string | import('../../formatters/index.mjs').Block>} */
256
- const nested = [];
257
- for (const [name, x] of entries) {
258
- if (Array.isArray(x) && !x.length) continue;
259
- if (x === null || typeof x !== 'object')
260
- head[`${k} ${name}`] = shownValue(x);
261
- else if (Array.isArray(x) && typeof x[0] !== 'object') {
262
- const joined = x.join(', ');
263
- if (x.length <= 3 && joined.length <= 80)
264
- head[`${k} ${name}`] = joined;
265
- else nested.push(section(`${k} ${name}:`), list(x.map(String)));
266
- } else {
267
- const items = Array.isArray(x) ? x : [x];
268
- nested.push(
269
- section(`${k} ${name}:`),
270
- records(
271
- /** @type {Record<string, unknown>[]} */ (items).map(
272
- flatRecord,
273
- ),
274
- ),
275
- );
276
- }
277
- }
278
- if (Object.keys(head).length) parts.push(record(head));
279
- parts.push(...nested);
280
- }
281
- }
282
- }
283
- return [record(plain), ...parts];
284
- }
285
-
286
- /**
287
- * A result whose change was saved but not checked leads with a warning
288
- * line naming the cause.
289
- * @param {unknown} result
290
- * @returns {string[]}
291
- */
292
- function notCheckedLine(result) {
293
- const n = /** @type {any} */ (result)?.data?.notChecked;
294
- return n ? [`[warn] saved, not checked (${n.code}): ${n.cause}`] : [];
295
- }
296
-
297
- /**
298
- * Text with C0 control characters and DEL shown as escapes (\u001b), so
299
- * text a person typed cannot move the cursor or recolor the terminal.
300
- * @param {string} text
301
- */
302
- const escapeControls = text =>
303
- String(text).replace(
304
- // eslint-disable-next-line no-control-regex
305
- /[\u0000-\u0008\u000b-\u001f\u007f]/g,
306
- c => `\\u${`000${c.charCodeAt(0).toString(16)}`.slice(-4)}`,
307
- );
308
-
309
- /**
310
- * Run one API call: errors become the CLI error envelope, results go to
311
- * JSON or to `render`.
312
- * @template T
313
- * @param {import('commander').Command} program
314
- * @param {() => Promise<T>} call
315
- * @param {(result: T) => Array<string | import('../../formatters/index.mjs').Block>} render
316
- * @param {(result: T) => import('../../../../foundation/debug/command-result.mjs').CommandResult} [answer]
317
- */
318
- async function run(program, call, render, answer) {
319
- const json = program.opts().json || false;
320
- /** @type {T} */
321
- let result;
322
- try {
323
- result = await call();
324
- } catch (e) {
325
- const err = /** @type {import('../../../../api/error.mjs').AstryxError} */ (
326
- e
327
- );
328
- // Suggested commands start the way this project runs the CLI, in JSON
329
- // as in text. Echoed user text never drives the terminal: control
330
- // characters print as escapes.
331
- return cliError(escapeControls(err.message), {
332
- suggestions: err.suggestions?.map(x => ({
333
- ...x,
334
- name: escapeControls(cmd(x.name)),
335
- })),
336
- code: err.code ?? ERROR_CODES.ERR_UNKNOWN,
337
- });
338
- }
339
- const answered = answer
340
- ? answer(result)
341
- : resultSet({count: 1, resultKind: 'mixed', directMatch: true});
342
- if (json) {
343
- jsonOut(/** @type {any} */ (result));
344
- return answered;
345
- }
346
- // --detail compact|brief (and --dense) print a change's status line
347
- // alone; an answer (how, show, list) is the answer, and prints whole.
348
- const o = program.opts();
349
- const change = ['themeEdit.set', 'themeEdit.undo', 'themeEdit.new'].includes(
350
- /** @type {any} */ (result)?.type,
351
- );
352
- const short =
353
- change &&
354
- (o.detail === 'compact' ||
355
- o.detail === 'brief' ||
356
- o.dense ||
357
- o.lang === 'dense');
358
- const lines = [...notCheckedLine(result), ...render(result)];
359
- print(short ? lines.slice(0, notCheckedLine(result).length + 1) : lines);
360
- return answered;
361
- }
362
-
363
- /**
364
- * The flags of a change, from Commander's options.
365
- * @param {any} o
366
- */
367
- const changeOptions = o => ({
368
- cwd: process.cwd(),
369
- on: o.on,
370
- // (--when given for several props, a ghost small button: all at once,
371
- // joined as Core's own keys join them.)
372
- when: flagValues('when').length > 1 ? flagValues('when').join('+') : o.when,
373
- state: o.state,
374
- mode: o.mode,
375
- only: o.only ?? false,
376
- png: o.png ?? false,
377
- });
378
-
379
- /**
380
- * The dial settings `new` takes as flags, by dial name: every option of its
381
- * CommandDoc that `set` would take as a dial.
382
- * @param {any} o
383
- * @returns {Record<string, string | string[]>}
384
- */
385
- function newSettings(o, themeName = '<theme>') {
386
- /** @type {Record<string, string | string[]>} */
387
- const out = {};
388
- // --like given two values is refused like a dial given two.
389
- const likes = flagValues('like');
390
- if (new Set(likes).size > 1) {
391
- // The suggestion keeps the first built-in theme given, or drops --like.
392
- const like = likes
393
- .map(l => l.toLowerCase())
394
- .find(l => builtInThemes().includes(l));
395
- throw new AstryxError(
396
- `--like was given twice (${likes.join(', ')}); give it once. Nothing was changed.`,
397
- [
398
- {
399
- name: cmd(`${EDITOR} new ${themeName}${newFlagLine({...o, like})}`),
400
- reason: like
401
- ? 'do this instead: the first built-in theme given'
402
- : 'do this instead: none of them is a built-in theme',
403
- },
404
- ],
405
- ERROR_CODES.ERR_INVALID_ARGUMENT,
406
- );
407
- }
408
- for (const opt of newDoc.options ?? []) {
409
- if (opt.param !== 'options.settings') continue;
410
- const flag = opt.flag.split(' ')[0].slice(2);
411
- const key = flag.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
412
- const value = o[key];
413
- if (value == null) continue;
414
- // A flag given twice: headings takes one value per axis (a weight and a
415
- // tracking); any other flag given two different values is refused.
416
- const all = flagValues(flag);
417
- if (flag === 'headings' && all.length > 1) out[flag] = all;
418
- else if (new Set(all).size > 1) {
419
- // Each value as the dial reads it (`--mode light` is light-only); a
420
- // light and a dark mode together are both modes, the default.
421
- const read = all.map(v =>
422
- dialValueFits(flag, v) ? v : flag === 'mode' ? modeDialValue(v) : null,
423
- );
424
- const bothModes =
425
- flag === 'mode' &&
426
- read.includes('light-only') &&
427
- read.includes('dark-only');
428
- // The suggestion keeps the first value the dial takes, or drops it.
429
- const fits = bothModes ? undefined : (read.find(Boolean) ?? undefined);
430
- throw new AstryxError(
431
- `--${flag} was given twice (${all.join(', ')}); give it once. Nothing was changed.`,
432
- [
433
- {
434
- name: cmd(
435
- `${EDITOR} new ${themeName}${newFlagLine({...o, [key]: fits})}`,
436
- ),
437
- reason: bothModes
438
- ? 'do this instead: a light and a dark mode together are both modes, the default'
439
- : fits
440
- ? 'do this instead: the first value it takes'
441
- : `do this instead: none of them is a value --${flag} takes`,
442
- },
443
- ],
444
- ERROR_CODES.ERR_INVALID_ARGUMENT,
445
- );
446
- } else out[flag] = String(value);
447
- }
448
- return out;
449
- }
450
-
451
- /**
452
- * The settings flags of options as commander read them (camelCase keys),
453
- * by the flag name `new` takes.
454
- * @param {Record<string, any>} o
455
- * @returns {Record<string, string | string[]>}
456
- */
457
- function newSettingsGiven(o) {
458
- /** @type {Record<string, string | string[]>} */
459
- const settings = {};
460
- for (const opt of newDoc.options ?? []) {
461
- if (opt.param !== 'options.settings') continue;
462
- const flag = opt.flag.split(' ')[0].slice(2);
463
- const value = o[flag.replace(/-([a-z])/g, (_, c) => c.toUpperCase())];
464
- if (value != null) settings[flag] = value;
465
- }
466
- return settings;
467
- }
468
-
469
- /**
470
- * The options a `new` was given, as flags for a suggested command, so a
471
- * corrected command makes the theme that was asked for.
472
- * @param {any} o
473
- * @returns {string}
474
- */
475
- function newFlagLine(o) {
476
- const settings = newSettingsGiven(o);
477
- const parts = newFlagList(
478
- o.like == null ? undefined : String(o.like),
479
- settings,
480
- Boolean(o.png),
481
- );
482
- return parts.length ? ` ${parts.join(' ')}` : '';
483
- }
484
-
485
- /**
486
- * The options of a preview command as the one option reader reads them
487
- * ({@link optionsAsWritten}): a typed dash (`—template`, `−−path`), other
488
- * letters or a typo of an option it takes is that option, refused with
489
- * the command as meant. Commander reads a word that starts with a typed
490
- * dash as a word of the command, so it is read here. Null when every
491
- * option is written as the command takes it.
492
- * @param {string} command `add` or `app` under preview
493
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
494
- * @returns {null}
495
- */
496
- function previewOptionsRead(command, doc) {
497
- const head = `${PREFIX} preview ${command}`;
498
- const read = optionsAsWritten(command, doc, {group: 'preview', head});
499
- if (!read) return null;
500
- throw new AstryxError(
501
- `${read.why}.`,
502
- [
503
- ...(read.line ? [{name: cmd(read.line), reason: 'do this instead'}] : []),
504
- {name: cmd(`${head} --help`), reason: 'every option it takes'},
505
- ],
506
- ERROR_CODES.ERR_INVALID_OPTION,
507
- );
508
- }
509
-
510
- /**
511
- * Refuse a preview flag given twice with different values: the command
512
- * would keep only the last one without a word. Undefined when each is
513
- * given once.
514
- * @param {string} command the preview subcommand, for the suggestion
515
- * @param {string[]} flags
516
- * @returns {undefined}
517
- */
518
- function previewFlagsOnce(command, flags) {
519
- for (const flag of flags) {
520
- const all = flagValues(flag);
521
- if (new Set(all).size > 1)
522
- throw new AstryxError(
523
- `--${flag} was given twice (${all.join(', ')}); give it once. Nothing was changed.`,
524
- [
525
- {
526
- name: cmd(`${PREFIX} preview ${command} --help`),
527
- reason: 'every option it takes',
528
- },
529
- ],
530
- ERROR_CODES.ERR_INVALID_ARGUMENT,
531
- );
532
- }
533
- return undefined;
534
- }
535
-
536
- /**
537
- * Every value one flag was given on the command line, in order.
538
- * @param {string} name
539
- * @returns {string[]}
540
- */
541
- function flagValues(name) {
542
- const argv = process.argv;
543
- /** @type {string[]} */
544
- const out = [];
545
- for (let i = 0; i < argv.length; i++) {
546
- if (argv[i] === '--') break;
547
- if (argv[i] === `--${name}` && i + 1 < argv.length) out.push(argv[++i]);
548
- else if (argv[i].startsWith(`--${name}=`))
549
- out.push(argv[i].slice(name.length + 3));
550
- }
551
- return out;
552
- }
553
-
554
- /**
555
- * The other values an undo removed with the one named, for a setting listed
556
- * more than once by hand (` and red, listed twice`), or nothing.
557
- * @param {import('../../../../api/theme-edit/theme-edit.type.mjs').ThemeEditChangeData} d
558
- */
559
- function alsoRemovedText(d) {
560
- const also = d.alsoRemoved ?? [];
561
- if (!also.length) return '';
562
- return ` and ${also.map(x => JSON.stringify(x.value)).join(', ')} (it was listed ${also.length === 1 ? 'twice' : `${also.length + 1} times`})`;
563
- }
564
-
565
- /**
566
- * The receipt of a change: a status line, then the change data.
567
- * @param {import('../../../../api/theme-edit/theme-edit.type.mjs').ThemeEditChangeResponse} r
568
- */
569
- function changeBlocks(r) {
570
- const d = r.data;
571
- // The status line names the value as saved, with a quote or space mark
572
- // the text output would fold written as its CSS escape (\201C), so the
573
- // text and the JSON name the same value.
574
- // A value saved as no text (none at all) is named by describe as such.
575
- const s = {
576
- ...d.setting,
577
- value:
578
- typeof d.setting.value !== 'string'
579
- ? d.setting.value
580
- : d.setting.value.replace(
581
- /[\u00A0\u00AB\u00BB\u2000-\u200B\u2018-\u201F\u2039\u203A\u202F\u3000\u300C-\u300F]/g,
582
- c => `\\${c.codePointAt(0)?.toString(16).toUpperCase()} `,
583
- ),
584
- };
585
- // A change that leaves the setting as it was says so, never "x -> x".
586
- const unchanged = /** @type {any} */ (d.notes ?? []).some(
587
- (/** @type {string} */ n) => n.startsWith('no change: '),
588
- );
589
- const drawnAlready = /** @type {any} */ (d.notes ?? []).some(
590
- (/** @type {string} */ n) =>
591
- n.startsWith('no change: ') && n.includes(' already draws '),
592
- );
593
- // A dial step on a part (`corners large --on card`) says what it drew
594
- // there, when that is a value or two: a part's own scale can give a step
595
- // another size than the dial's help names for the whole theme.
596
- const stepOn = d.action === 'set' && s.source === 'dial' ? s.on : null;
597
- const drawnOn = stepOn
598
- ? /** @type {string[]} */ (/** @type {any} */ (d).styled ?? [])
599
- .filter(x => x.startsWith(`${stepOn}: `))
600
- .map(x => x.slice(stepOn.length + 2))
601
- : [];
602
- const drawnAs = drawnOn.length <= 2 ? drawnOn : [];
603
- const done =
604
- unchanged && d.action === 'set'
605
- ? drawnAlready
606
- ? `[no change] ${d.theme}: ${describe(s)} already shows; nothing written`
607
- : `[ok] ${d.theme}: ${d.asSides ? `${describe({...s, thing: d.asSides.thing, value: d.asSides.value})} (${d.asSides.sides.map(x => `${x.thing} ${x.value}`).join(', ')})` : describe(s)} was already set; nothing changed`
608
- : d.was != null
609
- ? `[ok] ${d.theme}: ${s.thing} ${d.was} -> ${s.value}`
610
- : `[ok] ${d.theme}: ${d.action === 'set' ? (d.asSides ? `${describe({...s, thing: d.asSides.thing, value: d.asSides.value})} (${d.asSides.sides.map(x => `${x.thing} ${x.value}`).join(', ')})` : `${describe(s)}${drawnAs.length ? ` (drawn as ${drawnAs.join(', ')})` : ''}`) : `removed ${describe(s)}${alsoRemovedText(d)}; now ${/** @type {any} */ (d).now ?? "the base theme's value"} applies`}`;
611
- // A problem the change made leads the result, right under the status
612
- // line, which counts them: a tail-cut or head-cut output still shows it.
613
- // What a whole-theme change leaves out comes next, with the lines that
614
- // reach it, before the rest a head-cut output drops.
615
- const {
616
- newProblems = [],
617
- leftProblems = [],
618
- leftOut = [],
619
- fontNotLoaded = [],
620
- missed: _missed,
621
- missedParts: _missedParts,
622
- missedOn: _missedOn,
623
- missedWhere: _missedWhere,
624
- missedNew: _missedNew,
625
- ...rest
626
- } = /** @type {any} */ (d);
627
- const status = newProblems.length
628
- ? `${done}, but it made ${newProblems.length} new problem${newProblems.length > 1 ? 's' : ''}:`
629
- : done;
630
- // On undo, `setting` and `removed` both name the setting removed, as in
631
- // the JSON; the status line says the base theme's value is back.
632
- return [
633
- status,
634
- ...(newProblems.length ? problemList(newProblems) : []),
635
- // Problems it moved but left failing: said under the new ones.
636
- ...(leftProblems.length
637
- ? [
638
- `still failing after this change (${leftProblems.length}):`,
639
- ...problemList(leftProblems),
640
- ]
641
- : []),
642
- ...(fontNotLoaded.length
643
- ? [
644
- list(
645
- fontNotLoaded.map(
646
- (/** @type {{family: string, run: string[]}} */ x) => [
647
- `${x.family} is not installed, so the pictures and the app draw the next font in the stack until it is`,
648
- ...x.run,
649
- ],
650
- ),
651
- ),
652
- ]
653
- : []),
654
- ...(leftOut.length
655
- ? [
656
- list(
657
- leftOut.map((/** @type {{note: string, run: string[]}} */ x) => [
658
- x.note,
659
- ...x.run,
660
- ]),
661
- ),
662
- ]
663
- : []),
664
- ...missedLine(d),
665
- ...changeFields(rest),
666
- ];
667
- }
668
-
669
- /**
670
- * The parts the theme's own changes still do not reach, counted and
671
- * named, near the top of a change or a new theme, so a head of the
672
- * output keeps it; show names the first ones with their lines, and show
673
- * --json lists each.
674
- * A change says them only when it brought some (`missedNew`): the ones it
675
- * found are show's to list, not every change's to repeat.
676
- * @param {{missed?: number, missedParts?: number, missedOn?: string[], missedWhere?: string[], missedNew?: number}} d
677
- */
678
- function missedLine(d) {
679
- const {
680
- missed = 0,
681
- missedParts = missed,
682
- missedOn = [],
683
- missedWhere = [],
684
- missedNew,
685
- } = d;
686
- const named = missedWhere.length ? missedWhere : missedOn;
687
- if (!missed || missedNew === 0) return [];
688
- return [
689
- record({
690
- missed: `${missedNew ? `this change left ${missedNew} new miss${missedNew > 1 ? 'es' : ''}; ` : ''}${missed} miss${missed > 1 ? 'es' : ''} on ${missedParts} part${missedParts > 1 ? 's' : ''} the theme's changes did not reach${named.length ? ` (${named.slice(0, 6).join(', ')}${named.length > 6 ? `, and ${named.length - 6} more` : ''})` : ''}: each still shows the base theme's own look there. Keep each one, or bring it in line with your changes: show lists the first misses with their lines, and show --json has every one`,
691
- }),
692
- ];
693
- }
694
-
695
- /**
696
- * Problems, one to an item: what is wrong, then the command that fixes it.
697
- * @param {Array<{problem: string, fix: string | null}>} problems
698
- */
699
- function problemList(problems) {
700
- return cappedList(
701
- problems.map(p => (p.fix ? [p.problem, `fix: ${p.fix}`] : p.problem)),
702
- 'every one, each with its fix',
703
- );
704
- }
705
-
706
- /** How many problems the text shows before it counts the rest. */
707
- const PROBLEMS_SHOWN = 8;
708
-
709
- /**
710
- * A list the text cuts after the first few, counting the rest; the JSON has
711
- * every item.
712
- * @param {Array<string | string[]>} items
713
- * @param {string} [jsonHas] What the JSON holds for each item.
714
- */
715
- function cappedList(items, jsonHas = 'every one') {
716
- const rest = items.length - PROBLEMS_SHOWN;
717
- return [
718
- list(items.slice(0, PROBLEMS_SHOWN)),
719
- ...(rest > 0 ? [`and ${rest} more (--json lists ${jsonHas})`] : []),
720
- ];
721
- }
722
-
723
- /**
724
- * The plain fields of a change's data, with its problems as a cut list.
725
- * @param {Record<string, unknown>} data
726
- */
727
- function changeFields(data) {
728
- const {problems, ...rest} = /** @type {any} */ (data);
729
- return [
730
- ...project(rest),
731
- ...(Array.isArray(problems) && problems.length
732
- ? [section('problems:'), ...cappedList(problems)]
733
- : []),
734
- ];
735
- }
736
-
737
- /** How many variant lines the text of `show --on` gives before it counts the rest. */
738
- const VARIANT_LINES = 4;
739
-
740
- /**
741
- * A part value's final value as one short text.
742
- * @param {import('../../../../api/theme-edit/theme-edit.type.mjs').ThemeEditPartValue['value']} v
743
- */
744
- function valueText(v) {
745
- if (v == null) return 'no value';
746
- if (typeof v === 'string') return v;
747
- // (A mode left out is not shown yet; a mode given as null has no value.)
748
- return /** @type {const} */ (['light', 'dark'])
749
- .filter(m => v[m] !== undefined)
750
- .map(m => `${m} ${v[m] ?? 'no value'}`)
751
- .join(', ');
752
- }
753
-
754
- /**
755
- * The text of `show --on`: the part at rest, one line per property, then
756
- * the variants' values that differ from rest, a few, counted; the JSON
757
- * carries every value.
758
- * @param {import('../../../../api/theme-edit/theme-edit.type.mjs').ThemeEditShowPartResponse['data']} d
759
- */
760
- function partValueBlocks(d) {
761
- // (A token a rule sets on the part is in the JSON; the text gives the
762
- // properties the part draws.)
763
- const drawn = d.values.filter(v => !v.property.startsWith('--'));
764
- const rest = drawn.filter(v => v.when == null && v.state == null);
765
- const restOf = new Map(rest.map(v => [v.property, valueText(v.value)]));
766
- const variants = drawn.filter(
767
- v =>
768
- (v.when != null || v.state != null) &&
769
- valueText(v.value) !== restOf.get(v.property),
770
- );
771
- // A combined condition that draws what one of its conditions draws alone
772
- // (`variant:blue+selected:true` as `variant:blue`) says nothing more.
773
- const alone = new Set(
774
- variants.map(
775
- v => `${v.when}|${v.state}|${v.property}|${valueText(v.value)}`,
776
- ),
777
- );
778
- // A condition set cannot name (two variants at once) that draws what
779
- // one of its variants draws alone says nothing more either.
780
- const wordsOf = (/** @type {any} */ v) =>
781
- v.notSettable
782
- ? (v.when ?? '')
783
- .split(' ')
784
- .map((/** @type {string} */ w) => w.replace('=', ':'))
785
- : (v.when ?? '').split('+');
786
- const shown = variants.filter(
787
- v =>
788
- !wordsOf(v).some(
789
- (/** @type {string} */ w) =>
790
- w !== v.when &&
791
- alone.has(`${w}|${v.state}|${v.property}|${valueText(v.value)}`),
792
- ),
793
- );
794
- /** @param {import('../../../../api/theme-edit/theme-edit.type.mjs').ThemeEditPartValue} v */
795
- const row = v => ({
796
- ...(v.when != null || v.state != null
797
- ? {
798
- when:
799
- [v.when, v.state].filter(Boolean).join(' ') +
800
- (v.notSettable ? ' (not settable)' : ''),
801
- }
802
- : {}),
803
- property: v.property,
804
- value: valueText(v.value),
805
- tokens: (Array.isArray(v.tokens)
806
- ? v.tokens
807
- : [...new Set([...(v.tokens.light ?? []), ...(v.tokens.dark ?? [])])]
808
- ).join(' '),
809
- source: v.source,
810
- });
811
- return [
812
- section(
813
- `${d.part} in ${d.theme} (${d.kind} theme), at rest: ${rest.length} value${rest.length === 1 ? '' : 's'}`,
814
- ),
815
- records(rest.map(row), {layout: 'inline'}),
816
- ...(shown.length
817
- ? [
818
- section(
819
- `in variants: ${shown.length} value${shown.length === 1 ? '' : 's'} that differ${shown.length > VARIANT_LINES ? `, the first ${VARIANT_LINES} here (--json lists every value)` : ''}`,
820
- ),
821
- records(shown.slice(0, VARIANT_LINES).map(row), {layout: 'inline'}),
822
- ]
823
- : []),
824
- ];
825
- }
826
-
827
- /**
828
- * The text of `show`: the theme, then each color with its seed and the shade
829
- * each token uses, the notes on moved shades, and the generated files last.
830
- * @param {import('../../../../api/theme-edit/theme-edit.type.mjs').ThemeEditShowResponse['data']} d
831
- */
832
- function showBlocks(d) {
833
- const {
834
- settings,
835
- colors,
836
- colorNotes,
837
- colorFiles,
838
- unreached,
839
- missed = [],
840
- // Every problem is in the open problems at the end, with its fix.
841
- problems: _problems,
842
- openProblems = [],
843
- // The pictures to open: the first line and the last, so a head or a
844
- // tail of the output keeps it.
845
- look,
846
- ...rest
847
- } = d;
848
- const [head, ...others] = project(/** @type {any} */ (rest));
849
- const lookLine = look ? record({look}) : [];
850
- return [
851
- lookLine,
852
- head,
853
- // Each setting as named fields: its whole scope, the parts it reaches,
854
- // and what a stronger setting hides of it.
855
- ...(settings.length
856
- ? [section('settings:'), records(settings.map(s => flatRecord(s)))]
857
- : []),
858
- ...others,
859
- ...(colors.length
860
- ? [
861
- section('colors:'),
862
- ...colors.flatMap(c => [
863
- record({color: c.color, seed: c.seed}),
864
- record(c.tokens),
865
- ]),
866
- ]
867
- : []),
868
- ...(colorNotes.length ? [section('colorNotes:'), list(colorNotes)] : []),
869
- // What the theme's own changes did not reach, counted, six with the
870
- // line that reaches each; the other parts on the base's look are
871
- // counted, and listed in the JSON. Just before the generated files
872
- // (which stay last, before the closing look line), so a tail of the
873
- // output keeps them.
874
- ...(missed.length
875
- ? [
876
- section(
877
- `missed (${missed.length} miss${missed.length > 1 ? 'es' : ''} on ${new Set(missed.map(m => m.part)).size} part${new Set(missed.map(m => m.part)).size > 1 ? 's' : ''} the theme's own changes did not reach; each line reaches one):`,
878
- ),
879
- // Each part and why, then the line that reaches it.
880
- missed
881
- .slice(0, 6)
882
- .map(
883
- m =>
884
- `- ${m.part}${m.state ? ` (${m.state})` : ''}: ${m.why}\n line: ${cmd(m.line)}`,
885
- )
886
- .join('\n'),
887
- ]
888
- : []),
889
- ...(() => {
890
- // The rest, each said for what it is: the misses beyond the six shown
891
- // (a border, a shadow, a pill, a state), and the parts with no miss
892
- // whose fill or text color is still the base's (unreached).
893
- const hidden = missed.slice(6);
894
- const missedNames = new Set(missed.map(m => m.part));
895
- const still = (unreached ?? []).filter(p => !missedNames.has(p)).length;
896
- const hiddenParts = new Set(hidden.map(m => m.part)).size;
897
- const said = [
898
- hidden.length
899
- ? `${hidden.length} more miss${hidden.length > 1 ? 'es' : ''} (on ${hiddenParts} part${hiddenParts > 1 ? 's' : ''})`
900
- : '',
901
- still
902
- ? `${still} more part${still > 1 ? 's' : ''} whose fill or text color is still the base's`
903
- : '',
904
- ].filter(Boolean);
905
- return said.length
906
- ? [
907
- record({
908
- unreached: `${said.join(', and ')} (show --json lists each)`,
909
- }),
910
- ]
911
- : [];
912
- })(),
913
- colorFiles
914
- ? [section('colorFiles:'), record(colorFiles)]
915
- : record({colorFiles: 'none'}),
916
- // Last, so the end of the output names what the theme still gets wrong
917
- // (none, as an empty list in the JSON, prints nothing).
918
- openProblems.length
919
- ? [
920
- section(
921
- `openProblems: ${openProblems.length} the theme has now${(() => {
922
- const fixable = openProblems.filter(
923
- (/** @type {any} */ p) => p.fix,
924
- ).length;
925
- return fixable === openProblems.length
926
- ? '; each fix line fixes one'
927
- : fixable
928
- ? `; ${fixable} with a fix line that fixes it, the rest with none (no one line fixes those alone)`
929
- : '; none has a fix line (no one line fixes these alone)';
930
- })()}`,
931
- ),
932
- ...problemList(openProblems),
933
- ]
934
- : [],
935
- lookLine,
936
- ].flat();
937
- }
938
-
939
- /**
940
- * The text of a lookup answer: the answer data, lists one item per line.
941
- * @param {any} d
942
- */
943
- function lookupBlocks(d) {
944
- // Echoed user text never drives the terminal: control characters print
945
- // as escapes.
946
- const safe = (/** @type {unknown} */ v) =>
947
- typeof v === 'string'
948
- ? v.replace(
949
- /\p{Cc}/gu,
950
- c => `\\x${(c.charCodeAt(0) + 0x100).toString(16).slice(1)}`,
951
- )
952
- : v;
953
- /** @type {Record<string, unknown>} */
954
- const shown = {};
955
- for (const [k, v] of Object.entries(d)) shown[k] = safe(v);
956
- const {
957
- hint,
958
- run: next,
959
- results,
960
- examples,
961
- refused,
962
- points,
963
- items,
964
- ...rest
965
- } = /** @type {any} */ (shown);
966
- // Commands print one to a line and are never wrapped, so a line pasted
967
- // into a shell runs exactly one whole command; a sequence is one line.
968
- /** @param {string[]} cmds @param {boolean} [sequence] */
969
- const commandLines = (cmds, sequence) =>
970
- sequence && cmds.length > 1
971
- ? [cmds.join(' && '), 'sequence: run as one line, in this order']
972
- : cmds;
973
- /** @param {Array<{command: string, why: string}>} refusedList */
974
- const refusedLines = refusedList =>
975
- refusedList.flatMap(r => [`x ${r.command}`, ` not run: ${r.why}`]);
976
- /** @type {Array<string | import('../../formatters/index.mjs').Block>} */
977
- const blocks = [...(hint ? [String(hint)] : []), ...project(rest)];
978
- if (Array.isArray(results) && results.length)
979
- blocks.push(
980
- section('results:'),
981
- list(
982
- results.map((/** @type {any} */ r) => [
983
- String(r.text),
984
- ...commandLines(r.commands ?? [], r.sequence),
985
- ...refusedLines(r.refused ?? []),
986
- ]),
987
- ),
988
- );
989
- if (Array.isArray(examples) && examples.length)
990
- blocks.push(section('examples:'), list(commandLines(examples)));
991
- if (Array.isArray(refused) && refused.length)
992
- blocks.push(
993
- section('refused:'),
994
- list(refused.map((/** @type {any} */ r) => refusedLines([r]))),
995
- );
996
- if (Array.isArray(points) && points.length)
997
- blocks.push(
998
- section('points:'),
999
- records(
1000
- points.map((/** @type {any} */ x) => ({
1001
- at: x.at,
1002
- color: x.color,
1003
- alpha: x.alpha,
1004
- })),
1005
- ),
1006
- );
1007
- if (Array.isArray(items) && items.length) {
1008
- if (items.some((/** @type {any} */ x) => Array.isArray(x.examples)))
1009
- blocks.push(
1010
- section('items:'),
1011
- list(
1012
- items.map((/** @type {any} */ x) => [
1013
- `${x.name} ${x.values}`,
1014
- `help: ${x.help}`,
1015
- ...commandLines(x.examples),
1016
- ]),
1017
- ),
1018
- );
1019
- else blocks.push(...project({items}).slice(1));
1020
- }
1021
- if (Array.isArray(next) && next.length)
1022
- blocks.push(`Tip: ${next.map(String).join(', or ')}`);
1023
- return blocks;
1024
- }
1025
-
1026
- /**
1027
- * Refuse an option the command does not have. Set, undo and how take
1028
- * unknown options so a design token (`--color-accent`) can be the thing
1029
- * they name; a `--` word anywhere else is a mistyped option.
1030
- * @param {string} command the subcommand, for the suggestion
1031
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc the command's doc, which lists its options
1032
- * @param {Array<string | undefined>} rest the operands after the thing
1033
- * @returns {ReturnType<typeof cliError> | null}
1034
- */
1035
- function strayOption(command, doc, rest) {
1036
- // A scope flag given twice would keep only the last one without a word.
1037
- // (--when takes one value per prop: those are joined, all at once.)
1038
- for (const flag of ['on', 'when', 'state', 'mode']) {
1039
- const all = flagValues(flag);
1040
- const props = all.map(w => String(w).split(':')[0].trim().toLowerCase());
1041
- if (flag === 'when' && new Set(props).size === all.length) continue;
1042
- if (new Set(all).size > 1)
1043
- return cliError(
1044
- `--${flag} was given twice (${all.join(', ')}); give it once.`,
1045
- {
1046
- suggestions: [
1047
- {
1048
- name: cmd(`${EDITOR} ${command} --help`),
1049
- reason: 'every option it takes',
1050
- },
1051
- ],
1052
- code: ERROR_CODES.ERR_INVALID_ARGUMENT,
1053
- },
1054
- );
1055
- }
1056
- // A value pasted with a token's label (`'--color-accent: #e11d48'`) is
1057
- // a value, read by the label reader, not an option.
1058
- const word = rest.find(
1059
- w =>
1060
- typeof w === 'string' &&
1061
- w.startsWith('--') &&
1062
- !/^--[a-z0-9-]+\s*:\s*\S/i.test(w),
1063
- );
1064
- if (word == null) return null;
1065
- // An option the command takes, after the POSIX "--": every word after it
1066
- // is a value, so the option was not read. The line without the "--" is
1067
- // the one meant.
1068
- const argv = process.argv;
1069
- const dashes = argv.indexOf('--', argv.indexOf(command) + 1);
1070
- const takes = (doc.options ?? []).flatMap(o =>
1071
- String(o.flag)
1072
- .split(/[\s,]+/)
1073
- .filter(w => w.startsWith('--')),
1074
- );
1075
- if (dashes >= 0 && takes.includes(word) && argv.indexOf(word) > dashes) {
1076
- const words = argv
1077
- .slice(argv.indexOf(command) + 1)
1078
- .filter((w, i) => i !== dashes - argv.indexOf(command) - 1);
1079
- return cliError(
1080
- `every word after "--" is a value, so ${word} after it is not read as the option ${command} takes; write the line without the "--" (a value that starts with a dash, such as -0.5px, needs none). Nothing was changed.`,
1081
- {
1082
- suggestions: [
1083
- {
1084
- name: cmd(
1085
- `${EDITOR} ${command} ${words.map(w => (/^--[a-z]/.test(w) && takes.includes(w) ? w : quoteCommandArgument(w))).join(' ')}`,
1086
- ),
1087
- reason: 'do this instead',
1088
- },
1089
- ],
1090
- code: ERROR_CODES.ERR_INVALID_ARGUMENT,
1091
- },
1092
- );
1093
- }
1094
- return strayRefusal(command, doc, `${EDITOR} ${command}`, {
1095
- option: word,
1096
- note: 'a design token (such as --color-accent) is the thing a change names, before its value',
1097
- });
1098
- }
1099
-
1100
- /**
1101
- * What a theme command answers for an option it does not take, or for
1102
- * words past what it takes: the one stray reader every editor and preview
1103
- * command uses. It names the options the command takes; it offers the same
1104
- * command without the stray words only when that is safe to run
1105
- * (`safeLine`: show reads and changes nothing; a preview remove without its
1106
- * option would remove the whole preview), and always the command's help.
1107
- * @param {string} command the command's words after the group (`set`, `preview remove`)
1108
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc the command's doc, which lists its options
1109
- * @param {string} head the command line's start, as the project runs it
1110
- * @param {{option?: string, extra?: string[], note?: string}} stray an option it does not take, or words past what it takes, and a sentence about them
1111
- * @param {string | null} [safeLine] the command without them, when it is safe to run
1112
- * @returns {{message: string, suggestions: Array<{name: string, reason: string}>, code: string}}
1113
- */
1114
- function strayAnswer(command, doc, head, stray, safeLine = null) {
1115
- const takes = [
1116
- ...(doc.options ?? []).flatMap(o =>
1117
- String(o.flag)
1118
- .split(/[\s,]+/)
1119
- .filter(w => w.startsWith('--')),
1120
- ),
1121
- '--json',
1122
- ].filter((w, i, all) => all.indexOf(w) === i);
1123
- const list =
1124
- takes.length > 1
1125
- ? `${takes.slice(0, -1).join(', ')} and ${takes.at(-1)}`
1126
- : takes.join('');
1127
- const message = stray.option
1128
- ? `unknown option '${stray.option}': ${command} takes ${list}${stray.note ? `; ${stray.note}` : ''}.`
1129
- : `${command} does not take "${(stray.extra ?? []).join(' ')}"${stray.note ? `; ${stray.note}` : ''}.`;
1130
- return {
1131
- message,
1132
- suggestions: [
1133
- ...(safeLine ? [{name: cmd(safeLine), reason: 'do this instead'}] : []),
1134
- {
1135
- name: cmd(`${head} --help`),
1136
- reason: stray.option ? 'every option it takes' : 'what it takes',
1137
- },
1138
- ],
1139
- code: stray.option
1140
- ? ERROR_CODES.ERR_INVALID_OPTION
1141
- : ERROR_CODES.ERR_INVALID_ARGUMENT,
1142
- };
1143
- }
1144
-
1145
- /**
1146
- * {@link strayAnswer} as the refusal the command prints.
1147
- * @param {string} command
1148
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
1149
- * @param {string} head
1150
- * @param {{option?: string, extra?: string[], note?: string}} stray
1151
- * @param {string | null} [safeLine]
1152
- */
1153
- function strayRefusal(command, doc, head, stray, safeLine = null) {
1154
- const a = strayAnswer(command, doc, head, stray, safeLine);
1155
- return cliError(a.message, {suggestions: a.suggestions, code: a.code});
1156
- }
1157
-
1158
- /**
1159
- * Read the options of an editor command as written, the one reading every
1160
- * editor command gives them: an option in other letters, with one dash or
1161
- * a typed dash (`--On`, `-only`, `\u2014only`) or within the one typo limit
1162
- * of an option the command takes (`--olny`) is that option; a boolean
1163
- * option written with a value (`--png=false`, `--only true`) takes none,
1164
- * and its value is read by the one yes/no reader (booleanWord). Null when
1165
- * every option is written as the command takes it; else the reason, and
1166
- * the command as meant (the option as the command takes it; a boolean as
1167
- * itself for yes, left out for no), or no command when a boolean's value
1168
- * reads as neither.
1169
- * @param {string} command the subcommand (`set`, `undo`, `new`, `show`, how's word; `add` under preview)
1170
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc the command's doc, which lists its options
1171
- * @param {{group: string, head: string}} [where] the group word the subcommand follows (`editor`, `preview`) and the command line's start
1172
- * @returns {{why: string, line: string | null} | null}
1173
- */
1174
- function optionsAsWritten(
1175
- command,
1176
- doc,
1177
- where = {group: 'editor', head: `${EDITOR} ${command}`},
1178
- ) {
1179
- const flags = (doc.options ?? []).map(opt => String(opt.flag));
1180
- const names = (/** @type {(f: string) => boolean} */ keep) =>
1181
- flags
1182
- .filter(keep)
1183
- .flatMap(f => f.split(/[\s,]+/).filter(w => w.startsWith('--')));
1184
- const booleans = ['--json', ...names(f => !/[<[]/.test(f))];
1185
- const all = [...booleans, ...names(f => /[<[]/.test(f))];
1186
- // The options that must have a value (`--section <name>`).
1187
- const valued = names(f => /</.test(f));
1188
- /** The option a word names, as the command takes it, or null. @param {string} word */
1189
- const meant = word => {
1190
- const w = word.toLowerCase();
1191
- if (all.includes(`--${w}`)) return `--${w}`;
1192
- const near = all.filter(o => typoNear(w, o.slice(2)));
1193
- return near.length === 1 ? near[0] : null;
1194
- };
1195
- // Any run of up to three hyphens and dash-like characters (an en or em
1196
- // dash, a minus sign, a non-breaking hyphen: `-—on`, `−−on`) is the
1197
- // option's dashes, as normalizeEntry reads a token's.
1198
- const optionShape =
1199
- /^([-\u2010-\u2015\u2212\ufe58\ufe63\uff0d]{1,3})([A-Za-z][A-Za-z-]*)(?:=(.*))?$/;
1200
- const argv = process.argv;
1201
- const at = argv.indexOf(command, argv.indexOf(where.group) + 1);
1202
- if (at < 0) return null;
1203
- /** @type {string[]} */
1204
- const words = [];
1205
- /** @type {string | null} */
1206
- let why = null;
1207
- let unread = false;
1208
- for (let i = at + 1; i < argv.length; i += 1) {
1209
- const a = argv[i];
1210
- if (a === '--') {
1211
- words.push(...argv.slice(i));
1212
- break;
1213
- }
1214
- const m = optionShape.exec(a);
1215
- const flag = m ? meant(m[2]) : null;
1216
- if (!m || !flag) {
1217
- if (a !== '--json') words.push(a);
1218
- continue;
1219
- }
1220
- const written = m[3] == null ? `${m[1]}${m[2]}` : a.split('=')[0];
1221
- if (written !== flag)
1222
- why ??= `unknown option '${written}' (did you mean ${flag}?)`;
1223
- const next = argv[i + 1];
1224
- if (booleans.includes(flag)) {
1225
- // A value after a boolean option, joined by `=` or as the next word
1226
- // when that word is a yes or a no.
1227
- const value = m[3] ?? (booleanWord(next) != null ? String(next) : null);
1228
- if (value != null) {
1229
- if (m[3] == null) i += 1;
1230
- const read = booleanWord(value);
1231
- const shown = m[3] == null ? `${a} ${value}` : a;
1232
- if (read == null) unread = true;
1233
- why ??=
1234
- read == null
1235
- ? `${flag} takes no value ("${shown}"), and "${value}" reads as neither yes nor no: give ${flag} alone for yes, or leave it out`
1236
- : `${flag} takes no value ("${shown}"): give it alone for yes, or leave it out`;
1237
- if (read === true && flag !== '--json' && !words.includes(flag))
1238
- words.push(flag);
1239
- continue;
1240
- }
1241
- // A yes/no option given twice is one option.
1242
- if (flag !== '--json' && !words.includes(flag)) words.push(flag);
1243
- // A word right after a mistyped yes/no option that reads as neither
1244
- // (`--olny dark`) is no value of it: the line leaves it out, and says
1245
- // so, never gluing it onto the setting's value.
1246
- if (written !== flag && next != null && !/^-/.test(next)) {
1247
- i += 1;
1248
- why = `${why}; "${next}" after it is no value of ${flag}, so the line leaves it out`;
1249
- }
1250
- continue;
1251
- }
1252
- // An option that takes a value, given none, is left out of the line. A
1253
- // next word that starts with a dash is its value unless it names an
1254
- // option the command takes (`--font -apple-system`, `--text-size -1`).
1255
- // A word written as a long option (`--path`, `--color-accent`) is never
1256
- // a value either: no value an option takes starts with two dashes.
1257
- const opt = next == null ? null : optionShape.exec(next);
1258
- const nextIsOption =
1259
- next === '--' ||
1260
- /^--[A-Za-z]/.test(next ?? '') ||
1261
- Boolean(opt && meant(opt[2]));
1262
- if (m[3] == null && (next == null || nextIsOption)) {
1263
- if (valued.includes(flag)) {
1264
- why ??= `${flag} was given no value`;
1265
- // Leaving out an option that narrows what the command acts on
1266
- // would widen it: that line is never offered.
1267
- if (NARROWING_OPTIONS.includes(flag.slice(2))) unread = true;
1268
- }
1269
- continue;
1270
- }
1271
- words.push(flag);
1272
- if (m[3] != null) words.push(m[3]);
1273
- else if (/^-/.test(next)) {
1274
- words.push(next);
1275
- i += 1;
1276
- }
1277
- }
1278
- if (!why) return null;
1279
- return {
1280
- why,
1281
- line: unread
1282
- ? null
1283
- : `${where.head} ${words.map(w => (/^--[a-z]/.test(w) && all.includes(w) ? w : quoteCommandArgument(w))).join(' ')}`.trim(),
1284
- };
1285
- }
1286
-
1287
- /**
1288
- * An option a theme command does not take, or one written with no value,
1289
- * as the one option reader reads it (the json shim asks, for the options
1290
- * commander refuses): the option meant, or the command without the empty
1291
- * option, with the command that works, else what the command takes and its
1292
- * help. Undefined for any other command.
1293
- * Each offered command is checked as that command checks it (set and undo
1294
- * by their own checks, new by new's, show's section by show's), so a line
1295
- * offered is one that works; leaving out an option that narrows what the
1296
- * command acts on (--on, --when, --state, --mode, --path, --like, --theme)
1297
- * would widen it, so that line is never offered.
1298
- * @param {any} c the command commander refused
1299
- * @param {string} [code] commander's code for the refusal
1300
- * @returns {Promise<{message: string, suggestions: Array<{name: string, reason: string}>} | undefined> | undefined}
1301
- */
1302
- function unknownThemeOption(c, code = 'commander.unknownOption') {
1303
- const sub = c?.name?.();
1304
- const group = c?.parent?.name?.();
1305
- const doc =
1306
- group === 'preview'
1307
- ? /** @type {Record<string, import('@astryxdesign/cli/authoring').CommandDoc>} */ ({
1308
- add: previewAddDoc,
1309
- app: previewAppDoc,
1310
- list: previewListDoc,
1311
- remove: previewRemoveDoc,
1312
- })[sub]
1313
- : group === 'editor'
1314
- ? /** @type {Record<string, import('@astryxdesign/cli/authoring').CommandDoc>} */ ({
1315
- new: newDoc,
1316
- set: setDoc,
1317
- show: showDoc,
1318
- undo: undoDoc,
1319
- how: howDoc,
1320
- })[sub]
1321
- : undefined;
1322
- if (!doc) return undefined;
1323
- return themeOptionAnswer(c, code, sub, group, doc);
1324
- }
1325
-
1326
- /**
1327
- * The commands that carry out a line the option reader built, each checked
1328
- * as its own command checks it: set and undo by their checks (a repair
1329
- * folded in), new by new's (its own repairs offered), show's --section by
1330
- * show's; none when the command refuses it with no repair.
1331
- * @param {string} group
1332
- * @param {string} sub
1333
- * @param {string} line
1334
- * @returns {Promise<Array<{name: string, reason: string}>>}
1335
- */
1336
- async function checkedOptionLines(group, sub, line) {
1337
- const cwd = process.cwd();
1338
- const offer = (/** @type {string} */ l) => [
1339
- {name: cmd(l), reason: 'do this instead'},
1340
- ];
1341
- if (group === 'editor' && (sub === 'set' || sub === 'undo')) {
1342
- const checked = await editorCheckedLine(sub, line, cwd);
1343
- return checked ? offer(checked) : [];
1344
- }
1345
- if (group === 'editor' && sub === 'new') {
1346
- const words = splitCommand(line.slice(`${EDITOR} new `.length)) ?? [];
1347
- const [name, ...rest] = words;
1348
- /** @type {Record<string, string | string[]>} */
1349
- const settings = {};
1350
- let like;
1351
- let png = false;
1352
- for (let i = 0; i < rest.length; i += 1) {
1353
- const m = /^--([a-z-]+)$/.exec(rest[i]);
1354
- if (!m) continue;
1355
- if (m[1] === 'png') png = true;
1356
- else if (rest[i + 1] != null) {
1357
- const v = rest[(i += 1)];
1358
- if (m[1] === 'like') like = v;
1359
- else
1360
- settings[m[1]] =
1361
- settings[m[1]] == null ? v : [...[settings[m[1]]].flat(), v];
1362
- }
1363
- }
1364
- const lines = await editorCheckedNewLines(line, name, {
1365
- cwd,
1366
- ...(like != null ? {like} : {}),
1367
- settings,
1368
- png,
1369
- });
1370
- return lines.map(x => ({
1371
- name: cmd(x.name),
1372
- reason: x.reason ?? 'do this instead',
1373
- }));
1374
- }
1375
- if (group === 'editor' && sub === 'show') {
1376
- const lines = editorCheckedShowLines(line);
1377
- return lines.map(x => ({
1378
- name: cmd(x.name),
1379
- reason: x.reason ?? 'do this instead',
1380
- }));
1381
- }
1382
- return offer(line);
1383
- }
1384
-
1385
- /** Options whose absence widens what a command acts on, or changes it. */
1386
- const NARROWING_OPTIONS = Object.freeze([
1387
- 'on',
1388
- 'when',
1389
- 'state',
1390
- 'mode',
1391
- 'path',
1392
- 'like',
1393
- 'theme',
1394
- ]);
1395
-
1396
- /**
1397
- * {@link unknownThemeOption}'s answer for a theme command.
1398
- * @param {any} c
1399
- * @param {string} code
1400
- * @param {string} sub
1401
- * @param {string} group
1402
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
1403
- * @returns {Promise<{message: string, suggestions: Array<{name: string, reason: string}>} | undefined>}
1404
- */
1405
- async function themeOptionAnswer(c, code, sub, group, doc) {
1406
- const head = `${group === 'preview' ? `${PREFIX} preview` : EDITOR} ${sub}`;
1407
- const help = {name: cmd(`${head} --help`), reason: 'every option it takes'};
1408
- const read = optionsAsWritten(sub, doc, {group, head});
1409
- // An option given no value is left out of the offered command, unless
1410
- // leaving it out widens what the command acts on (a set without its part
1411
- // styles the whole theme; a preview remove without its page removes the
1412
- // whole preview).
1413
- const valued = (doc.options ?? [])
1414
- .filter(o => /</.test(String(o.flag)))
1415
- .flatMap(o =>
1416
- String(o.flag)
1417
- .split(/[\s,]+/)
1418
- .filter(w => w.startsWith('--'))
1419
- .map(w => w.slice(2)),
1420
- );
1421
- const argv = process.argv;
1422
- const at = argv.indexOf(sub, argv.indexOf(group) + 1);
1423
- const emptied = argv
1424
- .slice(at + 1)
1425
- .filter(
1426
- (w, i, rest) =>
1427
- /^--[a-z-]+$/.test(w) &&
1428
- valued.includes(w.slice(2)) &&
1429
- (rest[i + 1] == null || rest[i + 1].startsWith('-')),
1430
- )
1431
- .map(w => w.slice(2));
1432
- const widens =
1433
- code === 'commander.optionMissingArgument' &&
1434
- (emptied.some(o => NARROWING_OPTIONS.includes(o)) ||
1435
- (group === 'preview' && sub === 'remove'));
1436
- if (read) {
1437
- const lines =
1438
- read.line && !widens
1439
- ? await checkedOptionLines(group, sub, read.line)
1440
- : [];
1441
- return {message: `${read.why}.`, suggestions: [...lines, help]};
1442
- }
1443
- if (code === 'commander.excessArguments' && group === 'preview')
1444
- return previewExtraWords(sub, doc, head);
1445
- if (code !== 'commander.unknownOption' || group !== 'preview')
1446
- return undefined;
1447
- const takes = (doc.options ?? []).flatMap(o =>
1448
- String(o.flag)
1449
- .split(/[\s,]+/)
1450
- .filter(w => w.startsWith('--')),
1451
- );
1452
- const from = argv.indexOf(sub, argv.indexOf('preview') + 1);
1453
- const stray = argv
1454
- .slice(from + 1)
1455
- .find(
1456
- (w, i, rest) =>
1457
- w.startsWith('-') &&
1458
- !rest.slice(0, i).includes('--') &&
1459
- ![...takes, '--json', '--help', '-h'].includes(w.split('=')[0]),
1460
- );
1461
- // A folder name that starts with "-" reads as an option: it goes after
1462
- // --, and that line is the safe one.
1463
- const folder =
1464
- sub === 'app' && stray && /^-[^-]/.test(stray) && stray.length > 2;
1465
- const a = strayAnswer(
1466
- `preview ${sub}`,
1467
- doc,
1468
- head,
1469
- {
1470
- option: stray ?? '',
1471
- ...(folder
1472
- ? {note: 'a folder name that starts with "-" goes after --'}
1473
- : {}),
1474
- },
1475
- folder ? `${head} -- ${stray}` : null,
1476
- );
1477
- return {message: a.message, suggestions: a.suggestions};
1478
- }
1479
-
1480
- /**
1481
- * The refusal of options not written as the command takes them, with the
1482
- * command as meant when there is one.
1483
- * @param {string} command
1484
- * @param {{why: string, line: string | null, lines?: Array<{name: string, reason: string}>}} read
1485
- * `lines`: the commands that carry out the line, checked
1486
- */
1487
- function optionsRefusal(command, read) {
1488
- return cliError(`${read.why}.`, {
1489
- suggestions: [
1490
- ...(read.lines ??
1491
- (read.line ? [{name: cmd(read.line), reason: 'do this instead'}] : [])),
1492
- {
1493
- name: cmd(`${EDITOR} ${command} --help`),
1494
- reason: 'every option it takes',
1495
- },
1496
- ],
1497
- code: ERROR_CODES.ERR_INVALID_OPTION,
1498
- });
1499
- }
1500
-
1501
- /**
1502
- * {@link optionsAsWritten} as a refusal, or null.
1503
- * @param {string} command
1504
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
1505
- */
1506
- function readOptions(command, doc) {
1507
- const read = optionsAsWritten(command, doc);
1508
- return read ? optionsRefusal(command, read) : null;
1509
- }
1510
-
1511
- /**
1512
- * {@link readOptions} with its line checked as every offered line is, by
1513
- * the command's own checks (set and undo with a repair folded in, new with
1514
- * new's repairs, show's section by show's): a line the command refuses with
1515
- * no repair is not offered.
1516
- * @param {string} command
1517
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
1518
- */
1519
- async function readOptionsChecked(command, doc) {
1520
- const read = optionsAsWritten(command, doc);
1521
- if (!read) return null;
1522
- const lines = read.line
1523
- ? await checkedOptionLines('editor', command, read.line)
1524
- : [];
1525
- return optionsRefusal(command, {...read, lines});
1526
- }
1527
-
1528
- /**
1529
- * Words past what a preview command takes (`preview list overview`,
1530
- * `preview remove colors components`, `preview app my app`), through the
1531
- * one stray reader: the same command without them when that is safe to run
1532
- * (list reads only; app with the words as one folder name, which a
1533
- * folder with a space needs quoted, refused when the folder is not free),
1534
- * never for remove, whose first word alone would remove a page not meant;
1535
- * and always the command's help.
1536
- * @param {string} sub `app`, `list` or `remove`
1537
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
1538
- * @param {string} head the command line's start, as the project runs it
1539
- */
1540
- function previewExtraWords(sub, doc, head) {
1541
- const valued = new Set(
1542
- (doc.options ?? [])
1543
- .filter(o => /</.test(String(o.flag)))
1544
- .flatMap(o =>
1545
- String(o.flag)
1546
- .split(/[\s,]+/)
1547
- .filter(w => w.startsWith('-')),
1548
- ),
1549
- );
1550
- const argv = process.argv;
1551
- const from = argv.indexOf(sub, argv.indexOf('preview') + 1);
1552
- /** @type {string[]} */
1553
- const words = [];
1554
- /** @type {string[]} */
1555
- const options = [];
1556
- for (let i = from + 1; from >= 0 && i < argv.length; i++) {
1557
- const w = argv[i];
1558
- if (w === '--') {
1559
- words.push(...argv.slice(i + 1));
1560
- break;
1561
- }
1562
- if (w.startsWith('-')) {
1563
- if (w === '--json') continue;
1564
- options.push(w);
1565
- if (
1566
- valued.has(w.split('=')[0]) &&
1567
- !w.includes('=') &&
1568
- i + 1 < argv.length
1569
- )
1570
- options.push(quoteCommandArgument(argv[++i]));
1571
- continue;
1572
- }
1573
- words.push(w);
1574
- }
1575
- const takes = sub === 'list' ? 0 : 1;
1576
- const extra = words.slice(takes);
1577
- const flags = options.length ? ` ${options.join(' ')}` : '';
1578
- const safe =
1579
- sub === 'list'
1580
- ? `${head}${flags}`
1581
- : sub === 'app' && words.length
1582
- ? `${head} ${quoteCommandArgument(words.join(' '))}${flags}`
1583
- : null;
1584
- const a = strayAnswer(
1585
- `preview ${sub}`,
1586
- doc,
1587
- head,
1588
- {
1589
- extra,
1590
- note:
1591
- sub === 'list'
1592
- ? 'it takes no words'
1593
- : sub === 'app'
1594
- ? 'it takes one folder: a folder name with a space goes in quotes'
1595
- : 'it takes one page; remove pages one at a time',
1596
- },
1597
- safe,
1598
- );
1599
- return {message: a.message, suggestions: a.suggestions};
1600
- }
1601
-
1602
- /**
1603
- * Refuse an option `show` does not take with a show that works: the same
1604
- * show without it, and its help (an option the one reader names, and one
1605
- * written with a value, are read first by {@link readOptions}). Null when
1606
- * there is none.
1607
- * @param {string} name
1608
- * @param {unknown[]} rest the words after the theme
1609
- * @param {{png?: boolean, section?: string, on?: string}} o the options read
1610
- */
1611
- function showStray(name, rest, o) {
1612
- // (Beside --on, the refusal offers no other show: a show without --on
1613
- // writes the pages, and the lookup's own line is not offered yet.)
1614
- const offer = (/** @type {string} */ line) => (o.on ? null : line);
1615
- // The theme typed as an option (`show --theme t`), as set and undo read
1616
- // it: the show on that theme, never its help alone.
1617
- const asOption = /^--?(?:theme|name)$/i.test(String(name));
1618
- if (asOption && rest.length) {
1619
- const theme = String(rest[0]);
1620
- return strayRefusal(
1621
- 'show',
1622
- showDoc,
1623
- `${EDITOR} show`,
1624
- {
1625
- option: String(name),
1626
- note: "the theme is show's first word",
1627
- },
1628
- offer(
1629
- `${EDITOR} show ${quoteCommandArgument(theme)}${o.section ? ` --section ${o.section}` : ''}${o.png ? ' --png' : ''}`,
1630
- ),
1631
- );
1632
- }
1633
- const stray = rest.map(String).find(w => w.startsWith('-'));
1634
- if (stray == null) return null;
1635
- // An option the one reader names never comes here (readOptions reads
1636
- // it first): this one is none show takes, so the show it offers leaves it
1637
- // out and names no guess.
1638
- return strayRefusal(
1639
- 'show',
1640
- showDoc,
1641
- `${EDITOR} show`,
1642
- {option: stray},
1643
- offer(
1644
- `${EDITOR} show ${name}${o.section ? ` --section ${o.section}` : ''}${o.png ? ' --png' : ''}`,
1645
- ),
1646
- );
1647
- }
1648
-
1649
- /**
1650
- * A refusal for words after what a command takes, which would otherwise be
1651
- * dropped without a word (the one stray reader); null when there are none.
1652
- * @param {string} command
1653
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
1654
- * @param {string[]} extra
1655
- */
1656
- function extraWords(command, doc, extra) {
1657
- if (!extra.length) return null;
1658
- return strayRefusal(command, doc, `${EDITOR} ${command}`, {extra});
1659
- }
1660
-
1661
- /**
1662
- * Help that explains exactly what a subcommand does: its whole description
1663
- * under the usage line, while the group's list keeps the one-line summary.
1664
- * Token names start with `--`, so set and unset take unknown options as
1665
- * operands.
1666
- * @param {import('commander').Command} c
1667
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
1668
- * @param {{tokens?: boolean}} [options]
1669
- */
1670
- function explained(c, doc, {tokens = false} = {}) {
1671
- c.summary(c.description());
1672
- c.description(`[experimental] ${doc.description ?? doc.summary ?? ''}`);
1673
- if (tokens) c.allowUnknownOption(true);
1674
- return c;
1675
- }
1676
-
1677
- /** Old and sibling names, and where each now is. */
1678
- const MOVED = /** @type {Record<string, Record<string, string>>} */ ({
1679
- theme: {
1680
- build: 'compile',
1681
- set: 'editor set',
1682
- undo: 'editor undo',
1683
- show: 'editor show',
1684
- new: 'editor new',
1685
- how: 'editor how',
1686
- explain: 'editor how',
1687
- reset: 'editor undo',
1688
- palette: 'editor set',
1689
- help: '--help',
1690
- },
1691
- editor: {explain: 'how', reset: 'undo', help: '--help', palette: 'set'},
1692
- preview: {help: '--help'},
1693
- });
1694
-
1695
- /**
1696
- * A command group: bare, it prints its help (in JSON too, as the root
1697
- * does); with an unknown word, the unknown-subcommand error, leading with
1698
- * where a moved name now is, then the nearest subcommands.
1699
- * @param {import('commander').Command} parent
1700
- * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
1701
- * @returns {import('commander').Command}
1702
- */
1703
- function defineGroup(parent, doc) {
1704
- /** @type {import('commander').Command} */
1705
- const cmd = defineCommand(parent, doc, {
1706
- action: (
1707
- /** @type {unknown} */ _options,
1708
- /** @type {import('commander').Command} */ c,
1709
- ) => {
1710
- const extras = c?.args ?? [];
1711
- const words = [];
1712
- for (let x = cmd; x && x.parent; x = x.parent) words.unshift(x.name());
1713
- const here = `${getCliInvocation()} ${words.join(' ')}`;
1714
- if (extras.length > 0) {
1715
- const word = String(extras[0]).toLowerCase();
1716
- const group = doc.name.split(' ').at(-1) ?? '';
1717
- const ranked = (cmd.commands ?? [])
1718
- .filter(command => commandAvailable(command, helpBase()))
1719
- .map(command => command.name())
1720
- .sort(
1721
- (a, b) =>
1722
- levenshteinDistance(word, a) - levenshteinDistance(word, b),
1723
- );
1724
- // A typo of a subcommand (lst, remve) is that subcommand; any
1725
- // other word after `preview` that names an editor theme here asks
1726
- // for that theme's pages.
1727
- const typo = typoOf(word, ranked[0] ?? '') ? ranked[0] : null;
1728
- const moved =
1729
- MOVED[group]?.[word] ??
1730
- (typo
1731
- ? null
1732
- : group === 'preview' &&
1733
- editorThemesAt(process.cwd()).includes(word)
1734
- ? `add --theme ${word}`
1735
- : null);
1736
- return cliError(
1737
- `unknown subcommand '${doc.name} ${String(extras[0])}'${moved ? `; it is ${here} ${moved}` : ''}`,
1738
- {
1739
- suggestions: [
1740
- ...(moved
1741
- ? [{name: `${here} ${moved}`, reason: 'do this instead'}]
1742
- : []),
1743
- ...ranked.map(name => ({
1744
- name: `${here} ${name}`,
1745
- reason: 'available subcommand',
1746
- })),
1747
- ],
1748
- code: ERROR_CODES.ERR_UNKNOWN_SUBCOMMAND,
1749
- },
1750
- );
1751
- }
1752
- if (c?.optsWithGlobals?.().json) {
1753
- jsonOut(
1754
- /** @type {any} */ ({
1755
- type: 'help',
1756
- data: {
1757
- command: words.join(' '),
1758
- commands: (cmd.commands ?? [])
1759
- .filter(command => commandAvailable(command, helpBase()))
1760
- .map(command => ({
1761
- name: command.name(),
1762
- summary: command.summary() || command.description(),
1763
- })),
1764
- },
1765
- }),
1766
- );
1767
- return NO_RESULT_SET;
1768
- }
1769
- cmd.help();
1770
- return NO_RESULT_SET;
1771
- },
1772
- });
1773
- return cmd;
1774
- }
1775
-
1776
- /**
1777
- * A preview command's result, once it is in: this client owns its process,
1778
- * so a stop that lands while the result is printed is held, and a printed
1779
- * ok never ends with exit 130. The API itself leaves no listener behind.
1780
- * @template T
1781
- * @param {Promise<T>} result
1782
- * @returns {Promise<T>}
1783
- */
1784
- async function resultStands(result) {
1785
- const r = await result;
1786
- for (const sig of /** @type {const} */ (['SIGINT', 'SIGTERM']))
1787
- if (!process.listeners(sig).includes(heldStop)) process.on(sig, heldStop);
1788
- return r;
1789
- }
1790
-
1791
- /** A stop after a preview command finished: its result stands. */
1792
- function heldStop() {}
1793
-
1794
- /**
1795
- * Register `theme` and its subcommands under the `experimental` group.
1796
- * @param {import('commander').Command} group the `experimental` command
1797
- * @param {import('commander').Command} program the root program
1798
- */
1799
- export function registerExperimentalTheme(group, program) {
1800
- // A command run with no theme names the app's only theme.
1801
- setEditorThemeList(editorThemesAt);
1802
- setFreeArgument((cwd, words) =>
1803
- words === 'experimental theme editor new'
1804
- ? {
1805
- word: editorFreeName(cwd, 'my-theme'),
1806
- reason: 'a name for the new theme',
1807
- }
1808
- : words === 'experimental theme preview app'
1809
- ? {
1810
- word: quoteCommandArgument(editorFreeAppFolder(cwd)),
1811
- reason: 'a folder for the new app, free here',
1812
- }
1813
- : null,
1814
- );
1815
- setUnknownOptionReader(unknownThemeOption);
1816
- const theme = defineGroup(group, groupDoc);
1817
- explained(theme, groupDoc);
1818
- // The run's base may not serve a line's command; help then leaves it out.
1819
- const overrides = [
1820
- [
1821
- 'experimental theme targets',
1822
- ` ${getCliInvocation()} experimental theme targets Every themeable class, with its props and states\n`,
1823
- ],
1824
- [
1825
- 'experimental theme editor how',
1826
- ` ${getCliInvocation()} experimental theme editor how <part> What one part reads, and the commands that change it\n`,
1827
- ],
1828
- [
1829
- 'component <Name>',
1830
- ` ${getCliInvocation()} component <Name> One component's theming table\n`,
1831
- ],
1832
- ];
1833
- theme.addHelpText(
1834
- 'after',
1835
- () =>
1836
- `\nComponent style overrides:\n` +
1837
- overrides
1838
- .filter(([cli]) => exampleAvailable(program, cli, helpBase()))
1839
- .map(([, line]) => line)
1840
- .join(''),
1841
- );
1842
-
1843
- const editor = defineGroup(theme, editorDoc);
1844
- explained(editor, editorDoc);
1845
-
1846
- const newCli = explained(
1847
- defineCommand(editor, newDoc, {
1848
- fn: newFn,
1849
- action: async (
1850
- /** @type {string} */ name,
1851
- /** @type {any} */ o,
1852
- /** @type {any} */ cmd,
1853
- ) =>
1854
- // An option given a value is refused before the run, as for every
1855
- // other editor command: a refusal inside run is thrown, never
1856
- // printed there.
1857
- (await readOptionsChecked('new', newDoc)) ??
1858
- run(
1859
- program,
1860
- async () => {
1861
- // An option new does not take (--force, --dry-run, -t) is refused
1862
- // with new's help, as every editor command's unknown option is.
1863
- const takes = new Set(
1864
- (newDoc.options ?? []).flatMap(opt =>
1865
- String(opt.flag)
1866
- .split(/[\s,]+/)
1867
- .filter(w => w.startsWith('-'))
1868
- .map(w => w.replace(/[<[].*$/, '')),
1869
- ),
1870
- );
1871
- const stray = (cmd?.args ?? [])
1872
- .slice(1)
1873
- .map(String)
1874
- .find(
1875
- (/** @type {string} */ w) =>
1876
- /^-/.test(w) && !takes.has(w.split('=')[0]),
1877
- );
1878
- if (stray)
1879
- throw new AstryxError(
1880
- `unknown option '${stray}'.`,
1881
- [
1882
- {
1883
- name: `${EDITOR} new --help`,
1884
- reason: 'every option it takes',
1885
- },
1886
- ],
1887
- ERROR_CODES.ERR_INVALID_OPTION,
1888
- );
1889
- // A word after the name is never dropped without a word.
1890
- const extra = (cmd?.args ?? []).slice(1);
1891
- // The only word given straight after a dial's value (`new --font
1892
- // Open Sans`) is more of that value, and no name was given: the
1893
- // value whole, with a free name, checked as new checks it.
1894
- {
1895
- const argv = process.argv;
1896
- const from = argv.indexOf('new', argv.indexOf('editor') + 1);
1897
- const at = argv.indexOf(String(name), from + 1);
1898
- const before = argv[at - 2];
1899
- const dial = (newDoc.options ?? []).find(
1900
- opt =>
1901
- opt.param === 'options.settings' &&
1902
- String(opt.flag).split(' ')[0] === before,
1903
- );
1904
- const key = String(before ?? '')
1905
- .slice(2)
1906
- .replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1907
- // Read so only when the word cannot be the name, or the value
1908
- // alone is no value of the dial (`--accent dark blue`).
1909
- if (
1910
- !extra.length &&
1911
- from >= 0 &&
1912
- at > from + 2 &&
1913
- dial &&
1914
- !argv.slice(from + 1, at).includes('--') &&
1915
- (!editorNameOk(String(name)) ||
1916
- !dialValueFits(before.slice(2), String(o[key])))
1917
- ) {
1918
- const given = {...o, [key]: `${o[key]} ${name}`};
1919
- const free = editorFreeName(process.cwd(), 'my-theme');
1920
- throw new AstryxError(
1921
- `new takes <theme>, and was given none: "${name}" is more of ${before}'s value. A value of more than one word goes in quotes. Nothing was changed.`,
1922
- await editorCheckedNewLines(
1923
- `${EDITOR} new ${free}${newFlagLine(given)}`,
1924
- free,
1925
- {
1926
- cwd: process.cwd(),
1927
- like: given.like,
1928
- png: given.png ?? false,
1929
- settings: newSettingsGiven(given),
1930
- },
1931
- ),
1932
- ERROR_CODES.ERR_MISSING_ARGUMENT,
1933
- );
1934
- }
1935
- }
1936
- if (extra.length) {
1937
- // Words after `--` that are `--<option> <value>` pairs new
1938
- // takes become options; the other words were most likely
1939
- // part of the name. The options given stay in the suggestion.
1940
- /** @type {Record<string, any>} */
1941
- const given = {...o};
1942
- /** @type {string[]} */
1943
- const words = [];
1944
- // Each word in the order typed: one that follows a dial's
1945
- // value with no option between is more of that value, read as
1946
- // set reads it (`--font Open Sans` is the family Open Sans,
1947
- // `--mode Dark Only` the mode dark-only), while a word is left
1948
- // for the name or the name was typed already; a base name
1949
- // (--like) takes one word, and a word after it is a word of the
1950
- // name.
1951
- const valueFlags = new Set(
1952
- (newDoc.options ?? [])
1953
- .filter(opt => /</.test(String(opt.flag)))
1954
- .map(opt => String(opt.flag).split(' ')[0]),
1955
- );
1956
- const dialFlags = new Set(
1957
- (newDoc.options ?? [])
1958
- .filter(opt => opt.param === 'options.settings')
1959
- .map(opt => String(opt.flag).split(' ')[0]),
1960
- );
1961
- const camel = (/** @type {string} */ f) =>
1962
- f.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1963
- const argv = process.argv;
1964
- const from = argv.indexOf('new', argv.indexOf('editor') + 1);
1965
- /** @type {string | null} */
1966
- let open = null;
1967
- let named = false;
1968
- /** The word typed as the name, where it is not the first. @type {string | null} */
1969
- let nameWord = null;
1970
- /** The words read as more of a value. @type {string[]} */
1971
- const intoValues = [];
1972
- /**
1973
- * Whether a word is left for the name after argv[i]: a later
1974
- * word that is no option's value (`--font Open Sans --like
1975
- * neutral my-theme` leaves my-theme). The last such word is
1976
- * the name.
1977
- * @param {number} i
1978
- */
1979
- const wordLeft = i => {
1980
- for (let j = i + 1; j < argv.length; j++) {
1981
- const x = argv[j];
1982
- if (x === '--') return false;
1983
- if (x.startsWith('-')) {
1984
- if (valueFlags.has(x.split('=')[0]) && !x.includes('='))
1985
- j += 1;
1986
- continue;
1987
- }
1988
- return true;
1989
- }
1990
- return false;
1991
- };
1992
- /** Words typed straight after an option's value, past the name. @type {Set<string>} */
1993
- const afterValue = new Set();
1994
- /** An option's value before words that may be extra. @type {Record<string, string>} */
1995
- const extendedFrom = {};
1996
- /** The option the name was typed with (`--theme`), if any. @type {string | null} */
1997
- let nameOption = null;
1998
- for (let i = from + 1; from >= 0 && i < argv.length; i++) {
1999
- const w = argv[i];
2000
- if (w === '--') {
2001
- // After `--`, `--<option> <value>` pairs new takes.
2002
- for (let j = i + 1; j < argv.length; j++) {
2003
- const x = argv[j];
2004
- if (x.startsWith('--')) {
2005
- if (argv[j + 1] != null && given[camel(x)] == null)
2006
- given[camel(x)] = argv[++j];
2007
- } else words.push(x);
2008
- }
2009
- break;
2010
- }
2011
- if (w.startsWith('-')) {
2012
- const flag = w.split('=')[0];
2013
- // The name typed as an option (`--theme t2`, `--name t2`):
2014
- // new takes it as its first word.
2015
- if (/^--?(theme|name)$/i.test(flag)) {
2016
- nameOption = flag;
2017
- open = null;
2018
- continue;
2019
- }
2020
- if (valueFlags.has(flag) && !w.includes('=')) i += 1;
2021
- open = dialFlags.has(flag) ? camel(flag) : null;
2022
- continue;
2023
- }
2024
- // Words straight after an option's value are more of it
2025
- // while a later word is left for the name; the name ends the
2026
- // value, and a word after the name is never more of it.
2027
- if (open && !named && wordLeft(i)) {
2028
- const had = given[open];
2029
- given[open] = Array.isArray(had)
2030
- ? [...had.slice(0, -1), `${had.at(-1)} ${w}`]
2031
- : `${had} ${w}`;
2032
- intoValues.push(w);
2033
- continue;
2034
- }
2035
- if (!named) {
2036
- named = true;
2037
- if (w !== String(name)) nameWord = w;
2038
- open = null;
2039
- continue;
2040
- }
2041
- // After the name, a word is more of an open value only for a
2042
- // dial whose values are words (a font family, a headings
2043
- // style) or a value not finished yet (`rgb(1,`, `Inter,`); a
2044
- // setting's word starts its own setting (`--accent red
2045
- // corners pill`, `--corners pill padding 8px`), read below,
2046
- // and any other word is extra (`--accent red foo`).
2047
- if (open) {
2048
- const bare = w.toLowerCase().replace(/[:=]+$/, '');
2049
- const had = String(
2050
- Array.isArray(given[open])
2051
- ? given[open].at(-1)
2052
- : given[open],
2053
- );
2054
- const unfinished =
2055
- (had.match(/\(/g) ?? []).length >
2056
- (had.match(/\)/g) ?? []).length || /,\s*$/.test(had);
2057
- if (
2058
- dialFlags.has(`--${bare}`) ||
2059
- /^(like|base)$/.test(bare) ||
2060
- namesSetting(bare)
2061
- ) {
2062
- open = null;
2063
- afterValue.add(w);
2064
- } else if (!(
2065
- unfinished || ['font', 'headings'].includes(open)
2066
- )) {
2067
- // A word that may be more of the value (`dark blue`)
2068
- // or extra (`red foo`): the line with it, and if that
2069
- // line leaves the option out, the value before it.
2070
- const key = /** @type {string} */ (open);
2071
- if (!(key in extendedFrom)) extendedFrom[key] = had;
2072
- afterValue.add(w);
2073
- }
2074
- }
2075
- if (open) {
2076
- const had = given[open];
2077
- given[open] = Array.isArray(had)
2078
- ? [...had.slice(0, -1), `${had.at(-1)} ${w}`]
2079
- : `${had} ${w}`;
2080
- intoValues.push(w);
2081
- continue;
2082
- }
2083
- words.push(w);
2084
- }
2085
- /** Settings set gives after the theme is made. @type {Array<[string, string]>} */
2086
- const later = [];
2087
- // Settings typed after the name, in any form set reads (`accent
2088
- // red`, `red accent`, `corners=pill`, `like: neutral`, `corners:
2089
- // pill; accent: red`, `'accent red, corners pill'`, a pasted
2090
- // JSON object): each is its option (`--accent red`, `--like
2091
- // neutral`), never part of the name. A dial's value runs to the
2092
- // next setting.
2093
- {
2094
- // A dial word as set reads it: with its colon or equals sign
2095
- // apart from the value (`accent:`), in other letters, or
2096
- // with a typo (`cornres`, the one typo limit); `like` and
2097
- // `base` are the base (--like).
2098
- const dialOf = (/** @type {string} */ w) => {
2099
- const word = String(w)
2100
- .trim()
2101
- .toLowerCase()
2102
- .replace(/[:=]+$/, '')
2103
- // A key in quotes (`"like"`, `'accent'`) is that key.
2104
- .replace(/^(["'])(.*)\1$/, '$2');
2105
- if (!/^[a-z][a-z-]*$/.test(word)) return null;
2106
- if (word === 'like' || word === 'base') return 'like';
2107
- if (dialFlags.has(`--${word}`)) return camel(`--${word}`);
2108
- const near = [...dialFlags].filter(f =>
2109
- typoOf(word, f.slice(2)),
2110
- );
2111
- return near.length === 1 ? camel(near[0]) : null;
2112
- };
2113
- /** The flag word a dial word reads as. @param {string} w */
2114
- const dialName = w =>
2115
- String(dialOf(w)).replace(
2116
- /[A-Z]/g,
2117
- c => `-${c.toLowerCase()}`,
2118
- );
2119
- /**
2120
- * A key, a value or a word without the quotes around it
2121
- * (`"accent"`, `'base neutral'`); a text that holds a quote
2122
- * of its own (`"like": "neutral"`) keeps them, since its
2123
- * ends are two quotes, not one pair.
2124
- * @param {string} x
2125
- */
2126
- const unquote = x => {
2127
- const t = String(x).trim();
2128
- const m = /^(["'])([\s\S]*)\1$/.exec(t);
2129
- return m && !m[2].includes(m[1]) ? m[2] : t;
2130
- };
2131
- /**
2132
- * The settings one typed word holds, each `[dial, value]`: a
2133
- * JSON object, `key=value` or `key: value` pairs, or `dial
2134
- * value` items, apart at `;` or `,`; null when it holds none.
2135
- * @param {string} rawWord
2136
- * @returns {Array<[string, string]> | null}
2137
- */
2138
- const pairsIn = (/** @type {string} */ rawWord) => {
2139
- // A word with its own quotes around it (`'base neutral'`,
2140
- // `"accent"`) is that word, as the shell would have given
2141
- // it: the quotes are no part of a name.
2142
- const w = unquote(rawWord);
2143
- /** @type {unknown} */
2144
- let json;
2145
- try {
2146
- json = /^\s*\{/.test(w) ? JSON.parse(w) : undefined;
2147
- } catch {
2148
- json = undefined;
2149
- }
2150
- const entries =
2151
- json && typeof json === 'object' && !Array.isArray(json)
2152
- ? Object.entries(json)
2153
- : [];
2154
- if (entries.length)
2155
- return entries.every(
2156
- ([k]) => dialOf(k) || namesSetting(unquote(k)),
2157
- )
2158
- ? entries.map(([k, v]) => [k, String(v)])
2159
- : null;
2160
- // `key=value`, `key: value`, keys and values in quotes or
2161
- // not (`"like": "neutral"`), in either order (`red=accent`,
2162
- // `stone=like`), as set reads a pair swapped; `like` is
2163
- // never a value (`neutral=like` is the base neutral).
2164
- // Pairs apart at `;`, or at a comma when a key comes next
2165
- // (`like: neutral, corners: pill`); a comma inside a value
2166
- // (`font: Inter, Arial`) is the value's.
2167
- const byColon = w
2168
- .split(/\s*;\s*|\s*,\s*(?=["']?[a-z][a-z-]*["']?\s*[=:])/i)
2169
- .map(x =>
2170
- /^((["'])[a-z-]+\2|[a-z0-9#(][^=:]*?)\s*[=:]\s*(.+)$/i.exec(
2171
- x.trim(),
2172
- ),
2173
- );
2174
- /** @type {Array<[string, string]>} */
2175
- const read = [];
2176
- // (No pair at all: the `dial value` items below.)
2177
- for (const m of byColon.some(Boolean) ? byColon : []) {
2178
- if (!m) return null;
2179
- const [k, v] = [unquote(m[1]), unquote(m[3])];
2180
- if (dialOf(v) === 'like' && !dialOf(k)?.startsWith('like'))
2181
- read.push([v, k]);
2182
- else if (dialOf(k) || namesSetting(k)) read.push([k, v]);
2183
- else if (dialOf(v) && !/\s/.test(v)) read.push([v, k]);
2184
- else return null;
2185
- }
2186
- if (read.length) return read;
2187
- // `'accent red'`, `'accent red, corners pill'`, `'base
2188
- // neutral'`.
2189
- if (!/\s/.test(w.trim())) return null;
2190
- const items = w
2191
- .split(/\s*[;,]\s*/)
2192
- .map(x => x.trim().split(/\s+/))
2193
- .filter(x => x[0]);
2194
- return items.length &&
2195
- items.every(
2196
- x =>
2197
- x.length > 1 &&
2198
- (dialOf(x[0]) || namesSetting(unquote(x[0]))),
2199
- )
2200
- ? items.map(x => [unquote(x[0]), x.slice(1).join(' ')])
2201
- : null;
2202
- };
2203
- /** @type {string[]} */
2204
- const kept = [];
2205
- /** @type {Array<[string, string]>} */
2206
- const pairs = [];
2207
- /** The pasted pair a later word continues, or -1. */
2208
- let pasted = -1;
2209
- for (const w of words) {
2210
- const found = pairsIn(w);
2211
- if (found) {
2212
- pairs.push(...found);
2213
- // A value typed on across words (`font=Inter, Arial`)
2214
- // runs to the next setting, as `font Inter, Arial` does.
2215
- pasted = /^\s*\{/.test(w) ? -1 : pairs.length - 1;
2216
- continue;
2217
- }
2218
- if (pasted >= 0 && !dialOf(w) && !namesSetting(w)) {
2219
- pairs[pasted][1] = `${pairs[pasted][1]} ${w}`;
2220
- continue;
2221
- }
2222
- pasted = -1;
2223
- // A word quoted on its own (`"accent"`) keeps no quotes.
2224
- kept.push(unquote(w));
2225
- }
2226
- // `accent red`: a dial word, and its value up to the next
2227
- // setting; `red accent`: a value, then the dial it is for (as
2228
- // set reads the two swapped); a dial word with no value is
2229
- // never a word of the name.
2230
- /** @type {string[]} */
2231
- const rest = [];
2232
- /** @type {string[]} */
2233
- const bare = [];
2234
- const isSetting = (/** @type {string} */ w) =>
2235
- Boolean(dialOf(w)) ||
2236
- namesSetting(String(w).replace(/[:=]+$/, ''));
2237
- for (let i = 0; i < kept.length; i++) {
2238
- // The base takes the one word after it (`like neutral`,
2239
- // whose base shares its name with a dial).
2240
- if (dialOf(kept[i]) === 'like' && kept[i + 1] != null) {
2241
- pairs.push([kept[i], kept[i + 1]]);
2242
- i += 1;
2243
- continue;
2244
- }
2245
- const builtIn = (/** @type {string} */ w) =>
2246
- builtInThemes().includes(String(w).toLowerCase());
2247
- // A built-in theme's name is the base, whatever word is
2248
- // beside it (`theme neutral`, `neutral stone`): the base
2249
- // reader below takes it, never a dial of the same name.
2250
- if (builtIn(kept[i])) {
2251
- rest.push(kept[i]);
2252
- continue;
2253
- }
2254
- if (dialOf(kept[i])) {
2255
- const value = [];
2256
- let j = i + 1;
2257
- while (
2258
- j < kept.length &&
2259
- !isSetting(kept[j]) &&
2260
- !builtIn(kept[j])
2261
- )
2262
- value.push(kept[j++]);
2263
- if (value.length) pairs.push([kept[i], value.join(' ')]);
2264
- else bare.push(kept[i]);
2265
- i = j - 1;
2266
- continue;
2267
- }
2268
- if (
2269
- !isSetting(kept[i]) &&
2270
- kept[i + 1] != null &&
2271
- dialOf(kept[i + 1]) &&
2272
- !builtIn(kept[i + 1]) &&
2273
- (kept[i + 2] == null || isSetting(kept[i + 2]))
2274
- ) {
2275
- pairs.push([kept[i + 1], kept[i]]);
2276
- i += 1;
2277
- continue;
2278
- }
2279
- rest.push(kept[i]);
2280
- }
2281
- for (const [k, v] of pairs) {
2282
- // A setting new has no option for (`padding: 8px`) is a
2283
- // set after the theme is made, as the space form is.
2284
- if (!dialOf(k)) {
2285
- later.push([unquote(k), v]);
2286
- intoValues.push(`${unquote(k)} ${v}`);
2287
- continue;
2288
- }
2289
- const key = /** @type {string} */ (dialOf(k));
2290
- if (given[key] == null) given[key] = v;
2291
- intoValues.push(`${dialName(k)} ${v}`);
2292
- }
2293
- intoValues.push(...bare);
2294
- // A setting new takes no option for (`padding 8px`): set
2295
- // gives it after the theme is made, never a word of the name.
2296
- const named = [];
2297
- for (let i = 0; i < rest.length; i++) {
2298
- const thing = rest[i].replace(/[:=]+$/, '');
2299
- // (A built-in theme's name is the base, read below.)
2300
- if (
2301
- namesSetting(thing) &&
2302
- !builtInThemes().includes(thing.toLowerCase()) &&
2303
- rest[i + 1] != null
2304
- ) {
2305
- const value = [];
2306
- let j = i + 1;
2307
- while (j < rest.length && !isSetting(rest[j]))
2308
- value.push(rest[j++]);
2309
- later.push([thing, value.join(' ')]);
2310
- intoValues.push(`${thing} ${value.join(' ')}`);
2311
- i = j - 1;
2312
- continue;
2313
- }
2314
- // A word typed after an option's value that no reading
2315
- // takes is extra, never a word of the name.
2316
- if (afterValue.has(rest[i])) {
2317
- intoValues.push(rest[i]);
2318
- continue;
2319
- }
2320
- named.push(rest[i]);
2321
- }
2322
- words.splice(0, words.length, ...named);
2323
- }
2324
- // A built-in theme among the words (after a `like` word, or
2325
- // typed as the name with the real name after it) is the base,
2326
- // as --like; every other word is part of the name.
2327
- const all = [nameWord ?? String(name), ...words];
2328
- const baseAt = all.findIndex(
2329
- (w, i) =>
2330
- builtInThemes().includes(w.toLowerCase()) &&
2331
- (i > 0 || all.length > 1),
2332
- );
2333
- if (baseAt >= 0 && given.like == null)
2334
- given.like = all[baseAt].toLowerCase();
2335
- // (`base stone` and `theme stone` are the base as `like
2336
- // stone` is; a second base typed is no word of the name.)
2337
- const nameWords = all.filter(
2338
- (w, i) =>
2339
- i !== baseAt &&
2340
- !(
2341
- baseAt >= 0 &&
2342
- /^(like|base|theme)[:=]?$/i.test(w) &&
2343
- i === baseAt - 1
2344
- ) &&
2345
- !(
2346
- baseAt >= 0 &&
2347
- i > baseAt &&
2348
- builtInThemes().includes(w.toLowerCase())
2349
- ),
2350
- );
2351
- const fixed = nameWords
2352
- .join('-')
2353
- .toLowerCase()
2354
- .replace(/[^a-z0-9-]+/g, '-');
2355
- // The line is checked as every new line is offered.
2356
- const read = Object.keys(given).some(k => given[k] !== o[k]);
2357
- const linesFor = () =>
2358
- editorCheckedNewLines(
2359
- `${EDITOR} new ${quoteCommandArgument(fixed)}${newFlagLine(given)}`,
2360
- fixed,
2361
- {
2362
- cwd: process.cwd(),
2363
- like: given.like,
2364
- png: given.png ?? false,
2365
- settings: newSettingsGiven(given),
2366
- },
2367
- );
2368
- let lines = await linesFor();
2369
- // A value a later word made one no reading takes (`--accent
2370
- // red foo`): the value before it, the word extra.
2371
- const lost = Object.keys(extendedFrom).filter(
2372
- k =>
2373
- !lines.some(x =>
2374
- x.name.includes(
2375
- ` --${k.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)} `,
2376
- ),
2377
- ),
2378
- );
2379
- if (lost.length) {
2380
- for (const k of lost) given[k] = extendedFrom[k];
2381
- lines = await linesFor();
2382
- }
2383
- throw new AstryxError(
2384
- // (Only the name typed as an option, nothing extra: say that.)
2385
- nameOption &&
2386
- !(nameWord ? [...intoValues, ...words] : extra).join('')
2387
- ? `${nameOption} is no option of new: the theme name is new's first word. Nothing was changed.`
2388
- : `new takes one theme name; "${(nameWord ? [...intoValues, ...words] : extra).join(' ')}" is extra.${read ? ' A value of more than one word goes in quotes.' : ''} For a base theme, use --like. Nothing was changed.`,
2389
- [
2390
- ...lines,
2391
- // A CSS property is written on a part: the ask that
2392
- // names the parts, never a set line set itself refuses.
2393
- ...later.map(([thing, value]) =>
2394
- needsPart(thing)
2395
- ? {
2396
- name: `${HOW} ${quoteCommandArgument(`${value} ${thing}`)}`,
2397
- reason: `then this: new takes no ${thing}, and set writes it on a part (--on)`,
2398
- }
2399
- : {
2400
- name: `${EDITOR} set ${quoteCommandArgument(fixed)} ${quoteCommandArgument(thing)} ${quoteCommandArgument(value)}`,
2401
- reason: `then this: new takes no ${thing}; set gives it`,
2402
- },
2403
- ),
2404
- ],
2405
- ERROR_CODES.ERR_INVALID_ARGUMENT,
2406
- );
2407
- }
2408
- return themeEditNew(name, {
2409
- cwd: process.cwd(),
2410
- like: o.like,
2411
- png: o.png ?? false,
2412
- settings: newSettings(o, name),
2413
- });
2414
- },
2415
- r => [
2416
- `[ok] made theme "${r.data.theme}"${r.data.like ? ` on top of ${r.data.like}` : ''}`,
2417
- ...missedLine(/** @type {any} */ (r.data)),
2418
- ...changeFields(
2419
- /** @type {any} */ (
2420
- (({
2421
- missed: _m,
2422
- missedParts: _p,
2423
- missedOn: _o,
2424
- missedWhere: _w,
2425
- ...x
2426
- }) => x)(/** @type {any} */ (r.data))
2427
- ),
2428
- ),
2429
- `Tip: ${EDITOR} set ${r.data.theme} <thing> <value>, or ${HOW} "<what you want>"`,
2430
- `Look at it after each change (this changes nothing in your app): ${EDITOR} show ${r.data.theme} --png writes themes/${r.data.theme}/preview.png (a sample page), sheet-overlays.png (each control at rest, hovered, focused and pressed at its top, then every menu, tooltip, popover and list, open) and a picture of each family of components the theme sets a part of (sheet-actions.png, the buttons, while it sets none) from real components, and --section <family> --png pictures any other family (actions, inputs, selection, navigation, feedback, data, containers); open the family pictures, preview.png and sheet-overlays.png and check them against the request`,
2431
- ],
2432
- ),
2433
- }),
2434
- newDoc,
2435
- );
2436
- // new refuses an option it does not take itself, naming its help.
2437
- newCli.allowUnknownOption();
2438
-
2439
- explained(
2440
- defineCommand(editor, setDoc, {
2441
- fn: setFn,
2442
- action: (
2443
- /** @type {string} */ name,
2444
- /** @type {string} */ thing,
2445
- /** @type {string[]} */ value,
2446
- /** @type {any} */ o,
2447
- ) => {
2448
- // A declaration pasted as one argument (`--color-accent: #e11d48`,
2449
- // or `--color-accent:#e11d48`) is the token and its value; with no
2450
- // value otherwise, the missing-argument error the parser gives.
2451
- // A pasted JSON object of settings goes to the editor whole, which
2452
- // gives one set line per entry.
2453
- if (!value.length && /^\s*\{/.test(thing)) value = [''];
2454
- // Several pasted lines in one argument, each a declaration or the
2455
- // editor's own printed or change line, go to the editor whole: its
2456
- // entry reader reads each line.
2457
- if (!value.length) {
2458
- const lines = thing.split(/\r?\n/).filter(l => l.trim());
2459
- if (lines.length > 1 && lines.every(l => /[:=]|->|\u2192/.test(l)))
2460
- value = [''];
2461
- }
2462
- if (!value.length) {
2463
- // Any thing, a token or a dial, with `:` or `=` (`accent: red`,
2464
- // `--color-accent=#e11d48`).
2465
- // A thing and its value in one word (`'corners pill'`) are the
2466
- // same as given apart.
2467
- // A declaration goes to the editor whole: its one reader splits
2468
- // it, and reads the scope of the editor's own printed line
2469
- // (`corners = pill (whole theme)`).
2470
- if (/^(\S+?)\s*[:=]\s*(.+?);?\s*$/.test(thing)) value = [''];
2471
- else {
2472
- const pasted = /^\s*(\S+)\s+(.+?)\s*$/.exec(thing);
2473
- if (!pasted)
2474
- return missingSetValue(
2475
- editor.commands.find(c => c.name() === 'set'),
2476
- );
2477
- thing = pasted[1];
2478
- value = [pasted[2]];
2479
- }
2480
- }
2481
- return (async () =>
2482
- (await readOptionsChecked('set', setDoc)) ??
2483
- // A token typed after its value (`set t 4px --radius-element`)
2484
- // is no option: the set reads the two in the other order.
2485
- (value.length === 1 &&
2486
- /^--[a-z0-9-]+$/i.test(value[0]) &&
2487
- !thing.startsWith('-')
2488
- ? null
2489
- : strayOption('set', setDoc, value)) ??
2490
- run(
2491
- program,
2492
- () => themeEditSet(name, thing, value.join(' '), changeOptions(o)),
2493
- changeBlocks,
2494
- ))();
2495
- },
2496
- }),
2497
- setDoc,
2498
- {tokens: true},
2499
- );
2500
-
2501
- explained(
2502
- defineCommand(editor, showDoc, {
2503
- fn: showFn,
2504
- action: async (
2505
- /** @type {string} */ name,
2506
- /** @type {any} */ o,
2507
- /** @type {any} */ c,
2508
- ) =>
2509
- (await readOptionsChecked('show', showDoc)) ??
2510
- showStray(name, (c?.args ?? []).slice(1), o) ??
2511
- extraWords('show', showDoc, (c?.args ?? []).slice(1)) ??
2512
- // The sheet is limited to one section (the docs say so): a second
2513
- // --section is refused, never kept over the first in silence.
2514
- (new Set(flagValues('section')).size > 1
2515
- ? cliError(
2516
- `--section limits the sheet to one section, and was given ${flagValues('section').length} (${flagValues('section').join(', ')}); give one, or none for the whole sheet.`,
2517
- {
2518
- // (Beside --on no other show is offered: a show without
2519
- // --on writes the pages.)
2520
- suggestions: o.on
2521
- ? []
2522
- : [
2523
- {
2524
- // The first section given that `show` takes, else the
2525
- // whole sheet.
2526
- name: cmd(
2527
- `${EDITOR} show ${name}${(sec => (sec ? ` --section ${sec}` : ''))(flagValues('section').find(v => showSections().includes(v)))}`,
2528
- ),
2529
- reason: 'do this instead',
2530
- },
2531
- ],
2532
- code: ERROR_CODES.ERR_INVALID_ARGUMENT,
2533
- },
2534
- )
2535
- : null) ??
2536
- // One part's values: a lookup of one part.
2537
- (new Set(flagValues('on')).size > 1
2538
- ? cliError(
2539
- `--on looks up one part, and was given ${flagValues('on').length} (${flagValues('on').join(', ')}); give one.`,
2540
- {
2541
- suggestions: [
2542
- {
2543
- name: cmd(
2544
- `${EDITOR} show ${name} --on ${flagValues('on')[0]}`,
2545
- ),
2546
- reason: 'do this instead',
2547
- },
2548
- ],
2549
- code: ERROR_CODES.ERR_INVALID_ARGUMENT,
2550
- },
2551
- )
2552
- : null) ??
2553
- run(
2554
- program,
2555
- () =>
2556
- themeEditShow(name, {
2557
- cwd: process.cwd(),
2558
- png: o.png ?? false,
2559
- section: o.section,
2560
- ...(o.on != null ? {on: o.on} : {}),
2561
- }),
2562
- r =>
2563
- r.type === 'themeEdit.showPart'
2564
- ? partValueBlocks(r.data)
2565
- : showBlocks(/** @type {any} */ (r).data),
2566
- ),
2567
- }),
2568
- showDoc,
2569
- // An unknown option reaches the action, which names a show that works.
2570
- {tokens: true},
2571
- );
2572
-
2573
- explained(
2574
- defineCommand(editor, undoDoc, {
2575
- fn: undoFn,
2576
- action: (
2577
- /** @type {string} */ name,
2578
- /** @type {string | undefined} */ thing,
2579
- /** @type {string | undefined} */ which,
2580
- /** @type {any} */ o,
2581
- /** @type {import('commander').Command} */ c,
2582
- ) =>
2583
- (async () => {
2584
- // "undo t accent, corners and spacing" unquoted: the words make one
2585
- // list of settings, read as the quoted list is.
2586
- const words = [thing, which, ...(c?.args ?? []).slice(3)].filter(
2587
- w => typeof w === 'string',
2588
- );
2589
- // Three or more bare words that each name a setting are a list
2590
- // too (`undo t accent corners spacing`); a setting with a value of
2591
- // several words (`font Inter Tight`) is not.
2592
- // Commas or "and" make a list only when each item starts with a
2593
- // setting's name: a value with commas typed unquoted, as set takes
2594
- // it (`border-color rgb(1, 2, 3)`, `font Inter, Arial`), is that
2595
- // setting's value.
2596
- const items = words
2597
- .map(String)
2598
- .join(' ')
2599
- .split(/\s*,\s*|\s+and\s+/)
2600
- .filter(Boolean);
2601
- const listed =
2602
- words.length > 1 &&
2603
- ((words.some(
2604
- (w, i) => /,$/.test(String(w)) || (i > 0 && w === 'and'),
2605
- ) &&
2606
- items.length > 1 &&
2607
- items.every(item => namesSetting(item.split(/\s+/)[0]))) ||
2608
- (words.length > 2 &&
2609
- words.every(w => namesSetting(String(w))))) &&
2610
- !words.some(w => String(w).startsWith('-'));
2611
- const list = listed ? words.join(' ') : null;
2612
- // Otherwise the words after the thing are its value, typed
2613
- // unquoted as set takes it (`undo t padding 4px 8px --on card`).
2614
- const value =
2615
- which == null
2616
- ? undefined
2617
- : [which, ...(c?.args ?? []).slice(3)].map(String).join(' ');
2618
- return (
2619
- (await readOptionsChecked('undo', undoDoc)) ??
2620
- (list
2621
- ? null
2622
- : strayOption('undo', undoDoc, [
2623
- which,
2624
- ...(c?.args ?? []).slice(3),
2625
- ])) ??
2626
- run(
2627
- program,
2628
- () =>
2629
- themeEditUndo(name, {
2630
- ...changeOptions(o),
2631
- ...(list != null
2632
- ? {thing: list}
2633
- : thing == null
2634
- ? {}
2635
- : {thing, value}),
2636
- }),
2637
- r =>
2638
- r.data.action === 'step'
2639
- ? [
2640
- // What was undone is in the headline, so a tail of
2641
- // the output keeps it.
2642
- ...(() => {
2643
- const {newProblems = [], ...rest} = /** @type {any} */ (
2644
- r.data
2645
- );
2646
- return [
2647
- `[ok] ${rest.theme}: undid ${rest.undid ?? 'the last change'}${rest.refusedBefore ? ` (${rest.refusedBefore})` : ''}${newProblems.length ? `, but it made ${newProblems.length} new problem${newProblems.length > 1 ? 's' : ''}:` : ''}`,
2648
- ...(newProblems.length
2649
- ? problemList(newProblems)
2650
- : []),
2651
- ...changeFields(rest),
2652
- ];
2653
- })(),
2654
- ]
2655
- : changeBlocks(
2656
- /** @type {import('../../../../api/theme-edit/theme-edit.type.mjs').ThemeEditChangeResponse} */ (
2657
- r
2658
- ),
2659
- ),
2660
- )
2661
- );
2662
- })(),
2663
- }),
2664
- undoDoc,
2665
- {tokens: true},
2666
- );
2667
-
2668
- const preview = defineGroup(theme, previewDoc);
2669
- explained(preview, previewDoc);
2670
-
2671
- explained(
2672
- defineCommand(preview, previewAddDoc, {
2673
- fn: previewAddFn,
2674
- action: (
2675
- /** @type {string[] | string | undefined} */ words,
2676
- /** @type {any} */ o,
2677
- ) =>
2678
- run(
2679
- program,
2680
- () =>
2681
- previewFlagsOnce('add', ['theme', 'template', 'top', 'path']) ??
2682
- previewOptionsRead('add', previewAddDoc) ??
2683
- resultStands(
2684
- themeEditPreviewAdd([words ?? []].flat().join(' ') || undefined, {
2685
- cwd: process.cwd(),
2686
- theme: o.theme,
2687
- template: o.template,
2688
- top: o.top,
2689
- path: o.path,
2690
- }),
2691
- ),
2692
- r => {
2693
- const {matched, skipped, ...rest} = r.data;
2694
- return [
2695
- `[ok] theme preview in ${r.data.folder}: ${
2696
- [
2697
- ...(r.data.added.length
2698
- ? [`added ${r.data.added.join(', ')}`]
2699
- : []),
2700
- ...(r.data.refreshed.length
2701
- ? [
2702
- `${r.data.refreshed.join(', ')} ${r.data.refreshed.length > 1 ? 'were' : 'was'} there already and ${r.data.refreshed.length > 1 ? 'are' : 'is'} written again`,
2703
- ]
2704
- : []),
2705
- ].join('; ') || 'pages refreshed'
2706
- }`,
2707
- ...project(/** @type {any} */ (rest)),
2708
- ...(matched.length
2709
- ? [section('matched:'), records(matched)]
2710
- : []),
2711
- ...(skipped.length
2712
- ? [
2713
- section('skipped:'),
2714
- records(skipped.map(s => flatRecord(s))),
2715
- ]
2716
- : []),
2717
- ];
2718
- },
2719
- ),
2720
- }),
2721
- previewAddDoc,
2722
- );
2723
-
2724
- explained(
2725
- defineCommand(preview, previewAppDoc, {
2726
- fn: previewAppFn,
2727
- action: (/** @type {string} */ dir, /** @type {any} */ o) =>
2728
- run(
2729
- program,
2730
- () =>
2731
- previewFlagsOnce('app', ['theme']) ??
2732
- previewOptionsRead('app', previewAppDoc) ??
2733
- resultStands(
2734
- themeEditPreviewApp(dir, {
2735
- cwd: process.cwd(),
2736
- theme: o.theme,
2737
- }),
2738
- ),
2739
- r => [
2740
- `[ok] new app in ${r.data.folder} with the theme preview`,
2741
- ...project(/** @type {any} */ (r.data)),
2742
- ],
2743
- ),
2744
- }).allowExcessArguments(false),
2745
- previewAppDoc,
2746
- );
2747
-
2748
- explained(
2749
- defineCommand(preview, previewListDoc, {
2750
- fn: previewListFn,
2751
- action: (/** @type {any} */ o) =>
2752
- run(
2753
- program,
2754
- () =>
2755
- previewFlagsOnce('list', ['path']) ??
2756
- themeEditPreviewList({cwd: process.cwd(), path: o.path}),
2757
- r =>
2758
- r.data.folder
2759
- ? project(
2760
- /** @type {any} */ ({
2761
- ...r.data,
2762
- // A page whose file is gone says so in words.
2763
- pages: r.data.pages.map(({missing, ...p}) =>
2764
- missing ? {...p, file: 'missing'} : p,
2765
- ),
2766
- }),
2767
- )
2768
- : [
2769
- ...project(/** @type {any} */ (r.data)),
2770
- // A folder add refuses has a note that says why instead.
2771
- ...(r.data.notes.some(
2772
- n =>
2773
- n.includes(' refuses this folder') ||
2774
- n.startsWith('no preview here; '),
2775
- )
2776
- ? []
2777
- : [
2778
- `Tip: ${PREFIX} preview add${o.path == null ? '' : ` --path ${quoteCommandArgument(String(o.path))}`}`,
2779
- ]),
2780
- ],
2781
- r =>
2782
- resultSet({
2783
- count: r.data.pages.length,
2784
- resultKind: 'mixed',
2785
- empty: r.data.pages.length === 0,
2786
- }),
2787
- ),
2788
- }).allowExcessArguments(false),
2789
- previewListDoc,
2790
- );
2791
-
2792
- explained(
2793
- defineCommand(preview, previewRemoveDoc, {
2794
- fn: previewRemoveFn,
2795
- action: (/** @type {string | undefined} */ page, /** @type {any} */ o) =>
2796
- run(
2797
- program,
2798
- () =>
2799
- previewFlagsOnce('remove', ['path']) ??
2800
- resultStands(
2801
- themeEditPreviewRemove(page, {cwd: process.cwd(), path: o.path}),
2802
- ),
2803
- r => [
2804
- // The headline says what happened: a page still listed, or a
2805
- // preview nothing was removed from, was not removed.
2806
- r.data.pages.some(
2807
- p => p.toLowerCase() === String(page ?? '').toLowerCase(),
2808
- )
2809
- ? `[ok] nothing was removed: ${page} stays in the theme preview`
2810
- : r.data.pages.length
2811
- ? `[ok] removed ${page} from the theme preview`
2812
- : r.data.removed.length
2813
- ? `[ok] removed the theme preview in ${r.data.folder}`
2814
- : `[ok] nothing was removed: the theme preview in ${r.data.folder} stays`,
2815
- ...project(/** @type {any} */ (r.data)),
2816
- ],
2817
- ),
2818
- }).allowExcessArguments(false),
2819
- previewRemoveDoc,
2820
- );
2821
-
2822
- explained(
2823
- defineCommand(editor, howDoc, {
2824
- fn: howFn,
2825
- action: async (/** @type {string[]} */ words, /** @type {any} */ o) => {
2826
- if (!words.length && !o.list && !(o.at ?? []).length) {
2827
- const c = editor.commands.find(
2828
- x => x.name() === howDoc.name.split(' ').pop(),
2829
- );
2830
- // In JSON mode outputHelp prints the help envelope.
2831
- if (program.opts().json) c?.outputHelp();
2832
- else
2833
- print([
2834
- `Usage: ${HOW} [<part|setting|"question"|picture.png>] [--theme <name>] [--at x,y] [--list dials|tokens|parts|groups|properties [filter]]`,
2835
- '',
2836
- 'Examples:',
2837
- ...(howDoc.examples ?? []).flatMap(e => [
2838
- ` # ${e.label}`,
2839
- ` ${e.cli}`,
2840
- ]),
2841
- ]);
2842
- return NO_RESULT_SET;
2843
- }
2844
- // `--list=tokens` and a second --list are mistakes of form.
2845
- /** @type {string[]} */
2846
- const raw = /** @type {any} */ (program).rawArgs ?? process.argv;
2847
- const listFlags = raw.filter(
2848
- w => w === '--list' || w.startsWith('--list='),
2849
- );
2850
- const themeFlags = raw.filter(
2851
- w => w === '--theme' || w.startsWith('--theme='),
2852
- );
2853
- if (themeFlags.length > 1)
2854
- return cliError('--theme is given twice; give it once.', {
2855
- suggestions: [
2856
- {name: cmd(`${HOW} --help`), reason: 'give --theme once'},
2857
- ],
2858
- code: ERROR_CODES.ERR_INVALID_ARGUMENT,
2859
- });
2860
- if (listFlags.length > 1)
2861
- return cliError('--list is given twice; give it once.', {
2862
- suggestions: [
2863
- {
2864
- name: cmd(`${HOW} --list tokens accent`),
2865
- reason: 'one list, then the filter',
2866
- },
2867
- ],
2868
- code: ERROR_CODES.ERR_INVALID_ARGUMENT,
2869
- });
2870
- let list = o.list;
2871
- let rest = [...words];
2872
- const eq = rest.find(w => w.startsWith('--list='));
2873
- if (eq) {
2874
- list = true;
2875
- rest = [eq.slice('--list='.length), ...rest.filter(w => w !== eq)];
2876
- }
2877
- if (list) {
2878
- // The kind is the first word that names one ("accent --list
2879
- // tokens" too); the other words filter, and may start with --.
2880
- const kinds =
2881
- /^(dials?|tokens?|parts?|groups?|propert(y|ies)|kinds?)$/i;
2882
- const at = rest.findIndex(w => kinds.test(w));
2883
- const kind = at >= 0 ? rest[at] : (rest[0] ?? '');
2884
- const filter = (
2885
- at >= 0 ? rest.filter((_, i) => i !== at) : rest.slice(1)
2886
- )
2887
- .filter(w => w !== '--')
2888
- .join(' ');
2889
- return run(
2890
- program,
2891
- () =>
2892
- themeEditHow(filter, {
2893
- cwd: process.cwd(),
2894
- list: kind,
2895
- at: o.at ?? [],
2896
- theme: o.theme,
2897
- }),
2898
- r => lookupBlocks(/** @type {any} */ (r.data)),
2899
- r => {
2900
- const n = /** @type {any} */ (r.data).items.length;
2901
- return resultSet({count: n, resultKind: 'mixed', empty: n === 0});
2902
- },
2903
- );
2904
- }
2905
- // The API decides what the words are (a picture and a count, or a
2906
- // question); a picture is told by its extension here only to keep
2907
- // option words after it for the count.
2908
- const picture = /\.png$/i.test(rest[0] ?? '');
2909
- const stray = picture
2910
- ? null
2911
- : (readOptions(howDoc.name.split(' ').pop() ?? 'how', howDoc) ??
2912
- strayOption('how', howDoc, rest.slice(1)));
2913
- if (stray) return stray;
2914
- return run(
2915
- program,
2916
- () =>
2917
- themeEditHow(rest.join(' '), {
2918
- cwd: process.cwd(),
2919
- at: o.at ?? [],
2920
- words: rest,
2921
- theme: o.theme,
2922
- }),
2923
- r => lookupBlocks(/** @type {any} */ (r.data)),
2924
- r => {
2925
- const d = /** @type {any} */ (r.data);
2926
- const n =
2927
- d.kind === 'list'
2928
- ? d.items.length
2929
- : d.kind === 'question'
2930
- ? d.results.length
2931
- : 1;
2932
- return resultSet({count: n, resultKind: 'mixed', empty: n === 0});
2933
- },
2934
- );
2935
- },
2936
- }),
2937
- howDoc,
2938
- {tokens: true},
2939
- );
2940
-
2941
- registerThemeSubcommands(
2942
- theme,
2943
- program,
2944
- {
2945
- build: compileDoc,
2946
- list: listDoc,
2947
- add: addDoc,
2948
- remove: removeDoc,
2949
- use: useDoc,
2950
- eject: ejectDoc,
2951
- template: templateDoc,
2952
- targets: targetsDoc,
2953
- },
2954
- {
2955
- group: 'experimental theme',
2956
- build: 'compile',
2957
- explain: editorThemeRefusal,
2958
- preflight: editorCompileProblem,
2959
- follow: editorFollowCompile,
2960
- missingSource: editorMissingSource,
2961
- template: editorThemeTemplate,
2962
- hold: editorThemeHold,
2963
- loadedFonts: editorLoadedFonts,
2964
- extraData: editorBuildExtra,
2965
- afterBuild: editorAfterBuild,
2966
- sourcePath: editorSourcePath,
2967
- fontHelp: editorFontHelp,
2968
- install: editorInstall,
2969
- colorModes: editorColorModes,
2970
- },
2971
- );
2972
- }
2973
-
2974
- /**
2975
- * The error for `set` given a theme and a thing but no value: the parser's
2976
- * missing-argument report, from the one builder it uses.
2977
- * @param {any} cmd the set command
2978
- * @returns {never}
2979
- */
2980
- function missingSetValue(cmd) {
2981
- const {message, suggestions} = editorMissingArgument(
2982
- cmd,
2983
- ['theme', 'thing', 'value'],
2984
- 'value',
2985
- );
2986
- return cliError(message, {
2987
- code: ERROR_CODES.ERR_MISSING_ARGUMENT,
2988
- suggestions,
2989
- });
2990
- }