@astryxdesign/cli 0.7.16 → 0.7.17-canary.g0135e03

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 (369) hide show
  1. package/README.md +76 -86
  2. package/api/build/_adapter.d.mts +12 -0
  3. package/api/build/_adapter.mjs +51 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/build.doc.mjs +4 -3
  7. package/api/build/build.type.d.mts +2 -2
  8. package/api/build/build.type.mjs +3 -3
  9. package/api/build/kit/kind.d.mts +2 -1
  10. package/api/build/kit/kind.mjs +199 -10
  11. package/api/build/kit/kit.mjs +6 -4
  12. package/api/build/kit/rank.d.mts +4 -2
  13. package/api/build/kit/rank.mjs +125 -24
  14. package/api/build/kit/start.d.mts +5 -4
  15. package/api/build/kit/start.mjs +12 -8
  16. package/api/build/kit/weights.d.mts +39 -3
  17. package/api/build/kit/weights.json +1 -1
  18. package/api/build/kit/weights.mjs +340 -43
  19. package/api/build/kit/word-model.d.mts +23 -0
  20. package/api/build/kit/word-model.mjs +46 -0
  21. package/api/build/kit/words.d.mts +48 -0
  22. package/api/build/kit/words.mjs +90 -1
  23. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  24. package/api/component/list/list.d.mts +1 -1
  25. package/api/component/list/list.mjs +48 -6
  26. package/api/discover/_adapter.d.mts +1 -1
  27. package/api/discover/search/search.mjs +3 -2
  28. package/api/docs/_adapter.d.mts +26 -2
  29. package/api/docs/_adapter.mjs +219 -6
  30. package/api/docs/docs.d.mts +3 -0
  31. package/api/docs/docs.doc.mjs +7 -1
  32. package/api/docs/docs.mjs +12 -0
  33. package/api/docs/docs.type.d.mts +5 -0
  34. package/api/docs/docs.type.mjs +2 -0
  35. package/api/docs/node/node.mjs +1 -1
  36. package/api/doctor/_adapter.d.mts +27 -5
  37. package/api/doctor/_adapter.mjs +83 -10
  38. package/api/doctor/built-checks.mjs +40 -14
  39. package/api/doctor/doctor.d.mts +4 -3
  40. package/api/doctor/doctor.mjs +14 -7
  41. package/api/doctor/theme-checks.mjs +121 -17
  42. package/api/icon/_records.mjs +2 -1
  43. package/api/index.d.mts +2 -0
  44. package/api/index.mjs +2 -0
  45. package/api/integration/_adapter.d.mts +44 -0
  46. package/api/integration/_adapter.mjs +77 -1
  47. package/api/integration/authoring-checks.mjs +6 -6
  48. package/api/integration/example-scope.d.mts +14 -0
  49. package/api/integration/example-scope.mjs +44 -0
  50. package/api/integration/example-scope.type.d.mts +29 -0
  51. package/api/integration/example-scope.type.mjs +25 -0
  52. package/api/integration/integrationExampleScope.doc.d.mts +11 -0
  53. package/api/integration/integrationExampleScope.doc.mjs +59 -0
  54. package/api/integration/validate-integration.mjs +19 -1
  55. package/api/integration/validate-integration.type.d.mts +9 -0
  56. package/api/integration/validate-integration.type.mjs +1 -1
  57. package/api/integration/validateIntegration.doc.mjs +1 -1
  58. package/api/render/_adapter.mjs +591 -195
  59. package/api/render/render.doc.mjs +11 -3
  60. package/api/render/render.type.d.mts +52 -0
  61. package/api/render/render.type.mjs +31 -1
  62. package/api/search/ORDERING.md +1 -1
  63. package/api/search/_adapter.d.mts +9 -0
  64. package/api/search/_adapter.mjs +85 -0
  65. package/api/search/_candidate-score.mjs +51 -32
  66. package/api/search/_fit-order.mjs +3 -3
  67. package/api/search/_gather-components.d.mts +3 -2
  68. package/api/search/_gather-components.mjs +12 -3
  69. package/api/search/_lexical.d.mts +5 -0
  70. package/api/search/_lexical.mjs +8 -2
  71. package/api/search/_result.d.mts +11 -9
  72. package/api/search/_result.mjs +4 -4
  73. package/api/search/_score.d.mts +6 -1
  74. package/api/search/_score.mjs +15 -3
  75. package/api/search/search-index.mjs +7 -1
  76. package/api/search/search.d.mts +1 -1
  77. package/api/theme/_adapter.mjs +12 -1
  78. package/api/theme/build/build.d.mts +122 -1
  79. package/api/theme/build/build.mjs +412 -84
  80. package/api/theme/build/core-interception.d.mts +10 -0
  81. package/api/theme/build/core-interception.mjs +10 -0
  82. package/api/theme/build/font-warning.d.mts +23 -3
  83. package/api/theme/build/font-warning.mjs +54 -5
  84. package/api/theme/build/icon-imports.mjs +25 -2
  85. package/api/theme/theme.type.d.mts +10 -0
  86. package/api/theme/theme.type.mjs +7 -1
  87. package/api/theme-edit/_adapter.d.mts +103 -3
  88. package/api/theme-edit/_adapter.mjs +961 -82
  89. package/api/theme-edit/_catalog.mjs +19 -4
  90. package/api/theme-edit/_check.d.mts +63 -24
  91. package/api/theme-edit/_check.mjs +2467 -362
  92. package/api/theme-edit/_color.d.mts +10 -0
  93. package/api/theme-edit/_color.mjs +49 -1
  94. package/api/theme-edit/_compiler.mjs +89 -6
  95. package/api/theme-edit/_context.d.mts +3 -3
  96. package/api/theme-edit/_context.mjs +165 -54
  97. package/api/theme-edit/_css.d.mts +14 -0
  98. package/api/theme-edit/_css.mjs +46 -1
  99. package/api/theme-edit/_edit.d.mts +31 -4
  100. package/api/theme-edit/_edit.mjs +2433 -204
  101. package/api/theme-edit/_how-commands.d.mts +72 -1
  102. package/api/theme-edit/_how-commands.mjs +759 -9
  103. package/api/theme-edit/_how-question.d.mts +82 -5
  104. package/api/theme-edit/_how-question.mjs +6473 -553
  105. package/api/theme-edit/_how.d.mts +2 -1
  106. package/api/theme-edit/_how.mjs +237 -41
  107. package/api/theme-edit/_marks.d.mts +31 -5
  108. package/api/theme-edit/_marks.mjs +57 -5
  109. package/api/theme-edit/_name-rule.d.mts +11 -0
  110. package/api/theme-edit/_name-rule.mjs +12 -0
  111. package/api/theme-edit/_normal.d.mts +292 -0
  112. package/api/theme-edit/_normal.mjs +1454 -0
  113. package/api/theme-edit/_palette.mjs +10 -4
  114. package/api/theme-edit/_part-words.d.mts +31 -0
  115. package/api/theme-edit/_part-words.mjs +126 -0
  116. package/api/theme-edit/_parts.d.mts +18 -1
  117. package/api/theme-edit/_parts.mjs +246 -23
  118. package/api/theme-edit/_preview-app.d.mts +7 -1
  119. package/api/theme-edit/_preview-app.mjs +776 -187
  120. package/api/theme-edit/_preview.d.mts +100 -14
  121. package/api/theme-edit/_preview.mjs +582 -139
  122. package/api/theme-edit/_project.d.mts +4 -0
  123. package/api/theme-edit/_project.mjs +3 -1
  124. package/api/theme-edit/_settings.d.mts +417 -42
  125. package/api/theme-edit/_settings.mjs +3262 -424
  126. package/api/theme-edit/_tables.d.mts +15 -0
  127. package/api/theme-edit/_tables.mjs +63 -1
  128. package/api/theme-edit/_vet.d.mts +20 -0
  129. package/api/theme-edit/_vet.mjs +47 -2
  130. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  131. package/api/theme-edit/theme-edit.type.mjs +4 -1
  132. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  133. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  134. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  135. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  136. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  137. package/api/upgrade/run/run.mjs +4 -3
  138. package/assets/codemods/integration-discovery.mjs +2 -1
  139. package/assets/codemods/run-codemod.mjs +87 -7
  140. package/assets/codemods/transforms/next/index.mjs +11 -1
  141. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  142. package/assets/component-list.generated.json +1 -0
  143. package/assets/docs/author-a-theme.doc.mjs +1 -0
  144. package/assets/docs/theme.doc.dense.mjs +2 -2
  145. package/assets/docs/theme.doc.mjs +1 -1
  146. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  147. package/assets/docs/tree/checks.doc.mjs +1 -1
  148. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  149. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  150. package/assets/docs/tree/single-component.doc.mjs +4 -0
  151. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  152. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  153. package/assets/docs/use-a-theme.doc.mjs +1 -1
  154. package/assets/docs.generated.json +2 -2
  155. package/assets/search-catalog.generated.json +2 -0
  156. package/assets/self-audit.generated.json +1 -1
  157. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  158. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  159. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  160. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  161. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  162. package/assets/templates/components.generated.json +1 -1
  163. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  164. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +5 -1
  165. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  166. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  167. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  168. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  169. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  170. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  171. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  172. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  173. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  174. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  175. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  176. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  177. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  178. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  179. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  180. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  181. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  182. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  183. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  184. package/assets/templates/pages/ide/page.tsx +24 -2
  185. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  186. package/assets/templates/pages/library/template.doc.mjs +4 -1
  187. package/assets/templates/pages/login/template.doc.mjs +2 -1
  188. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  189. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  190. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  191. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  192. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  193. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  194. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  195. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  196. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  197. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  198. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  199. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  200. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  201. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  202. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  203. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  204. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  205. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  206. package/assets/theme.template.ts +6 -0
  207. package/authoring/debug/parse.d.mts +3 -3
  208. package/authoring/doctypes/_schema.d.mts +3 -3
  209. package/authoring/doctypes/command/command.doc.mjs +1 -1
  210. package/authoring/doctypes/component/categories.d.mts +37 -0
  211. package/authoring/doctypes/component/categories.mjs +54 -0
  212. package/authoring/doctypes/template/template.doc.mjs +1 -1
  213. package/authoring/doctypes/template/type.ts +9 -0
  214. package/authoring/example/example.doc.d.mts +12 -0
  215. package/authoring/example/example.doc.mjs +69 -0
  216. package/authoring/example/preview.d.mts +92 -0
  217. package/authoring/example/preview.mjs +994 -0
  218. package/authoring/example/type.ts +102 -0
  219. package/authoring/index.d.mts +1 -0
  220. package/authoring/index.d.ts +12 -0
  221. package/authoring/index.mjs +3 -1
  222. package/clients/cli/bin/astryx.mjs +6 -9
  223. package/clients/cli/build-id.generated.json +1 -1
  224. package/clients/cli/commands/component.doc.mjs +1 -1
  225. package/clients/cli/commands/component.mjs +22 -3
  226. package/clients/cli/commands/docs.doc.mjs +7 -1
  227. package/clients/cli/commands/docs.mjs +3 -1
  228. package/clients/cli/commands/doctor.mjs +32 -14
  229. package/clients/cli/commands/experimental/render.mjs +42 -1
  230. package/clients/cli/commands/experimental/theme.mjs +358 -63
  231. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  232. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  233. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  234. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  235. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  236. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  237. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  238. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  239. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  240. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  241. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  242. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  243. package/clients/cli/commands/search.doc.mjs +2 -1
  244. package/clients/cli/commands/search.mjs +6 -1
  245. package/clients/cli/commands/template.mjs +4 -2
  246. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  247. package/clients/cli/commands/theme.doc.mjs +1 -1
  248. package/clients/cli/commands/theme.mjs +317 -47
  249. package/clients/cli/commands/upgrade.mjs +42 -7
  250. package/clients/cli/index.mjs +1 -1
  251. package/clients/cli/lib/cli-error.mjs +2 -1
  252. package/clients/cli/lib/component-format.mjs +205 -98
  253. package/clients/cli/lib/hook-format.mjs +9 -19
  254. package/clients/cli/lib/json-shim.mjs +92 -21
  255. package/clients/cli/lib/manifest.mjs +3 -2
  256. package/clients/cli/manifest.generated.json +1 -1
  257. package/foundation/agent-docs/agent-docs.mjs +1 -1
  258. package/foundation/config/theme-state.d.mts +13 -1
  259. package/foundation/config/theme-state.mjs +47 -7
  260. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  261. package/foundation/discovery/component-discovery.d.mts +11 -0
  262. package/foundation/discovery/component-discovery.mjs +56 -8
  263. package/foundation/discovery/component-replacement.mjs +130 -1
  264. package/foundation/discovery/copied-passages.mjs +2 -1
  265. package/foundation/discovery/doc-types.mjs +4 -3
  266. package/foundation/discovery/entry-name-files.d.mts +43 -0
  267. package/foundation/discovery/entry-name-files.mjs +264 -0
  268. package/foundation/discovery/hook-discovery.d.mts +8 -2
  269. package/foundation/discovery/hook-discovery.mjs +22 -8
  270. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  271. package/foundation/discovery/icon-set-checks.mjs +2 -1
  272. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  273. package/foundation/discovery/integration-doc-files.mjs +2 -1
  274. package/foundation/discovery/package-exports.d.mts +10 -0
  275. package/foundation/discovery/package-exports.mjs +56 -3
  276. package/foundation/discovery/prop-drift.mjs +9 -9
  277. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  278. package/foundation/discovery/runner-allowlist.mjs +2 -0
  279. package/foundation/discovery/stored-component-list.d.mts +43 -0
  280. package/foundation/discovery/stored-component-list.mjs +90 -0
  281. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  282. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  283. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  284. package/foundation/discovery/stored-self-audit.mjs +38 -18
  285. package/foundation/discovery/template-adapter.d.mts +53 -1
  286. package/foundation/discovery/template-adapter.mjs +176 -12
  287. package/foundation/discovery/template-icons.mjs +2 -1
  288. package/foundation/discovery/theme-discovery.mjs +31 -4
  289. package/foundation/discovery/theme-imports.d.mts +14 -0
  290. package/foundation/discovery/theme-imports.mjs +43 -1
  291. package/foundation/discovery/theming-targets.mjs +3 -2
  292. package/foundation/doc-compiler/import.mjs +7 -1
  293. package/foundation/doc-compiler/inputs.mjs +3 -2
  294. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  295. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  296. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  297. package/foundation/env/semver.mjs +3 -1
  298. package/foundation/fonts/font-stylesheet.d.mts +31 -0
  299. package/foundation/fonts/font-stylesheet.mjs +115 -0
  300. package/foundation/fs/cache-eviction.d.mts +21 -0
  301. package/foundation/fs/cache-eviction.mjs +73 -0
  302. package/foundation/fs/exact-codec.d.mts +12 -2
  303. package/foundation/fs/exact-codec.mjs +23 -6
  304. package/foundation/fs/file-protection.mjs +4 -3
  305. package/foundation/fs/gather-cache.d.mts +62 -4
  306. package/foundation/fs/gather-cache.mjs +512 -91
  307. package/foundation/fs/jiti-cache.d.mts +19 -1
  308. package/foundation/fs/jiti-cache.mjs +130 -6
  309. package/foundation/fs/kept-tree.d.mts +60 -0
  310. package/foundation/fs/kept-tree.mjs +154 -0
  311. package/foundation/fs/listing-cache.d.mts +7 -0
  312. package/foundation/fs/listing-cache.mjs +10 -0
  313. package/foundation/fs/module-loader.d.mts +24 -2
  314. package/foundation/fs/module-loader.mjs +94 -21
  315. package/foundation/fs/paths.d.mts +18 -0
  316. package/foundation/fs/paths.mjs +15 -2
  317. package/foundation/fs/read-record.d.mts +9 -0
  318. package/foundation/fs/read-record.mjs +19 -11
  319. package/foundation/fs/stop-cleanup.d.mts +12 -0
  320. package/foundation/fs/stop-cleanup.mjs +66 -0
  321. package/foundation/identity/provider-identity.d.mts +6 -0
  322. package/foundation/identity/provider-identity.mjs +10 -1
  323. package/foundation/integrations/contribution-inventory.mjs +4 -3
  324. package/foundation/integrations/example-code.d.mts +63 -0
  325. package/foundation/integrations/example-code.mjs +416 -0
  326. package/foundation/integrations/public-imports.d.mts +9 -0
  327. package/foundation/integrations/public-imports.mjs +3 -2
  328. package/foundation/integrations/validate-contributions.mjs +17 -45
  329. package/foundation/render/embedded-files.d.mts +6 -0
  330. package/foundation/render/embedded-files.mjs +25 -5
  331. package/foundation/render/embedded-imports.d.mts +39 -7
  332. package/foundation/render/embedded-imports.mjs +66 -27
  333. package/foundation/render/file-header.d.mts +66 -0
  334. package/foundation/render/file-header.mjs +118 -0
  335. package/foundation/render/host-answer.d.mts +18 -0
  336. package/foundation/render/host-answer.mjs +46 -0
  337. package/foundation/render/host-exit.d.mts +1 -0
  338. package/foundation/render/host-exit.mjs +6 -1
  339. package/foundation/render/html-reader.d.mts +55 -2
  340. package/foundation/render/html-reader.mjs +145 -26
  341. package/foundation/render/markup-edits.d.mts +57 -0
  342. package/foundation/render/markup-edits.mjs +182 -0
  343. package/foundation/render/page-host.mjs +29 -12
  344. package/foundation/render/page-worker.mjs +121 -13
  345. package/foundation/render/picture-chrome.d.mts +4 -0
  346. package/foundation/render/picture-chrome.mjs +185 -0
  347. package/foundation/render/picture-playwright.d.mts +4 -0
  348. package/foundation/render/picture-playwright.mjs +34 -0
  349. package/foundation/render/rebuild.mjs +2 -1
  350. package/foundation/render/render-page.d.mts +35 -3
  351. package/foundation/render/render-page.mjs +641 -96
  352. package/foundation/render/source-block.d.mts +85 -6
  353. package/foundation/render/source-block.mjs +211 -20
  354. package/foundation/render/ts-paths.d.mts +69 -6
  355. package/foundation/render/ts-paths.mjs +326 -40
  356. package/foundation/response/error-codes.d.mts +3 -1
  357. package/foundation/response/error-codes.d.ts +1 -0
  358. package/foundation/response/error-codes.doc.mjs +12 -1
  359. package/foundation/response/error-codes.mjs +11 -1
  360. package/foundation/response/response-types.doc.mjs +2 -2
  361. package/foundation/text/compare-text.d.mts +14 -0
  362. package/foundation/text/compare-text.mjs +68 -0
  363. package/foundation/text/string-utils.d.mts +3 -2
  364. package/foundation/text/string-utils.mjs +18 -4
  365. package/foundation/text/suggest-order.d.mts +9 -0
  366. package/foundation/text/suggest-order.mjs +15 -1
  367. package/foundation/xle/expand.mjs +2 -1
  368. package/host/index.mjs +8 -6
  369. package/package.json +7 -6
@@ -9,11 +9,24 @@
9
9
  * @position api/theme-edit — imported only by _adapter.mjs
10
10
  */
11
11
 
12
+ import {THEME_SLUG_RE} from '../../foundation/discovery/theme-discovery.mjs';
12
13
  import * as fs from 'node:fs';
13
- import {coversProperty} from './_css.mjs';
14
+ import {coversProperty, cssProperties, matchValue} from './_css.mjs';
14
15
  import * as path from 'node:path';
15
16
  import {AstryxError} from '../error.mjs';
16
- import {vetSuggestions} from './_vet.mjs';
17
+ import {
18
+ followLine,
19
+ readSetLine,
20
+ splitCommand,
21
+ vetSuggestions,
22
+ } from './_vet.mjs';
23
+ import {
24
+ allowedLine,
25
+ colorPair,
26
+ coversTyped,
27
+ readsTyped,
28
+ withoutCopyDebris,
29
+ } from './_normal.mjs';
17
30
  import {
18
31
  AUTO_SPREAD,
19
32
  CORNERS,
@@ -38,6 +51,8 @@ import {
38
51
  radiusTokenOf,
39
52
  contrastProblems,
40
53
  describe,
54
+ entryDamage,
55
+ entryNotes,
41
56
  keyOf,
42
57
  loadTheme,
43
58
  maskedSettings,
@@ -59,40 +74,50 @@ import {
59
74
  buildTheme,
60
75
  staleBuild,
61
76
  EDITOR_SUFFIXES,
62
- madeByEditor,
63
77
  outputsDrift,
64
78
  kebab,
65
79
  camel,
66
80
  NEW_MARKER,
67
81
  clearNewMarker,
68
82
  refuseThemeSource,
69
- settingsShapeOk,
83
+ settingsEntriesOk,
84
+ entriesReadable,
85
+ readAsMeant,
86
+ editorMadeFolder,
87
+ builtOnBase,
88
+ dialWordOf,
89
+ onBuiltIn,
90
+ readFields,
91
+ settingsJson,
70
92
  slugFor,
93
+ typedThemeName,
94
+ themeNameReadings,
71
95
  themeSource,
72
96
  themeSourceProblem,
73
97
  refuseThemeParse,
74
98
  ownSourceTokens,
75
99
  ownSourceTokenValues,
100
+ ownTokenEntries,
101
+ ownThemeInput,
102
+ describeValue,
103
+ nonTextMessage,
76
104
  ownPartTokens,
77
105
  PHONE_TYPE,
78
106
  refreshSourceStamp,
79
107
  sourceChangedReason,
80
- builtPairs,
81
- ownPairMessage,
108
+ setOwnTokenCheck,
82
109
  freeThemeName,
83
110
  refuseLinks,
84
111
  usableNewName,
85
112
  FOLDER_JUNK,
113
+ folderIsEmpty,
86
114
  dialValueFits,
87
115
  holdAfterBuild,
116
+ setArgs,
88
117
  } from './_settings.mjs';
89
- import {
90
- checkSetting,
91
- exampleOf,
92
- normalizeEntry,
93
- storedProblems,
94
- } from './_check.mjs';
95
- import {MODAL} from './_compiler.mjs';
118
+ import {checkSetting, normalizeEntry, storedProblems} from './_check.mjs';
119
+ import {MODAL, isColorToken} from './_compiler.mjs';
120
+ import {colorProblem} from './_color.mjs';
96
121
  import {
97
122
  PALETTE_DIALS,
98
123
  VIBRANCY_DEFAULT,
@@ -105,15 +130,21 @@ import {
105
130
  writeWhole,
106
131
  isGraySeed,
107
132
  seedOf,
133
+ isEditorTemp,
108
134
  } from './_palette.mjs';
109
135
  import {
110
136
  renderPreview,
111
137
  renderSheet,
112
138
  previewIsCurrent,
113
139
  takeFirstAppCopy,
140
+ appCopyBehind,
141
+ appCopyStale,
142
+ copyFontsCss,
114
143
  writeAppCopy,
115
144
  } from './_preview.mjs';
116
145
  import {appWiring, refreshPreviewRoute, seeLine} from './_preview-app.mjs';
146
+ /** The preview command, as a person runs it. */
147
+ const PREVIEW_CMD = `${P.replace(/ editor$/, '')} preview`;
117
148
  import {baseInstalled, baseResolved, installLine} from './_project.mjs';
118
149
  import {reactMissing} from './_parts.mjs';
119
150
  import {
@@ -128,7 +159,9 @@ import {
128
159
  stampSheet,
129
160
  } from './_context.mjs';
130
161
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
162
+ import {readThemeState} from '../../foundation/config/theme-state.mjs';
131
163
  import {
164
+ formatCliCommand,
132
165
  getCliInvocation,
133
166
  quoteCommandArgument,
134
167
  } from '../../foundation/env/package-manager.mjs';
@@ -147,23 +180,18 @@ const E = ERROR_CODES;
147
180
  * for that name, the source only exactly as it writes it); `keep` is every
148
181
  * other file, which is never touched. Null when the editor did not make
149
182
  * the folder. System files (.DS_Store) are in neither.
183
+ * @param {string} cwd
150
184
  * @param {string} dir
151
185
  * @param {string} slug
152
186
  * @param {boolean} [damaged] its settings are there but not valid JSON
153
187
  * @returns {{clear: string[], keep: string[]} | null}
154
188
  */
155
- function editorLeftovers(dir, slug, damaged = false) {
189
+ function editorLeftovers(cwd, dir, slug, damaged = false) {
156
190
  // The editor made this folder: a stopped `new` left its marker, the
157
191
  // generated settings module (which carries the editor's header) is there
158
192
  // without its settings, or its settings are there but damaged (kept
159
193
  // aside by `new`, so neither cleared nor kept here).
160
- const marked = fs.existsSync(path.join(dir, NEW_MARKER));
161
- if (
162
- !marked &&
163
- !damaged &&
164
- !madeByEditor(path.join(dir, `${slug}.settings.ts`))
165
- )
166
- return null;
194
+ if (!damaged && !editorMadeFolder(cwd, slug)) return null;
167
195
  /** @type {string[]} */
168
196
  const clear = [];
169
197
  /** @type {string[]} */
@@ -171,12 +199,11 @@ function editorLeftovers(dir, slug, damaged = false) {
171
199
  const named = (/** @type {string} */ n) =>
172
200
  n === NEW_MARKER ||
173
201
  EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
174
- /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config\.json)$/.test(
202
+ /^(preview(-dark)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config\.json)$/.test(
175
203
  n,
176
204
  ) ||
177
- // The editor's temp names: `.<name>.astryx-<pid>-<rand>.tmp`, and the
178
- // build's `.<name>.tmp-<id>`.
179
- /^\..+\.(astryx-\d+-[a-z0-9]+\.tmp|tmp-[\w-]+)$/.test(n);
205
+ // The editor's temp names (writes, builds, pictures).
206
+ isEditorTemp(n);
180
207
  for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
181
208
  const p = path.join(dir, e.name);
182
209
  if (FOLDER_JUNK.has(e.name)) continue;
@@ -209,9 +236,9 @@ function editorLeftovers(dir, slug, damaged = false) {
209
236
  /** Whether a settings file parses, in the shape the editor reads. @param {string} file */
210
237
  function readableJson(file) {
211
238
  try {
212
- return settingsShapeOk(
213
- JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')),
214
- );
239
+ // An entry with no thing or no source is damage too: `new` keeps the
240
+ // file aside, as the refusal for it says.
241
+ return settingsEntriesOk(settingsJson(fs.readFileSync(file, 'utf8')));
215
242
  } catch {
216
243
  return false;
217
244
  }
@@ -262,9 +289,200 @@ function putBack(kept, tokensDir) {
262
289
  */
263
290
 
264
291
  export async function themeEditNew(name, options = {}) {
292
+ try {
293
+ return await newTheme(name, options);
294
+ } catch (e) {
295
+ throw await vetNewLines(
296
+ e,
297
+ options.cwd ?? process.cwd(),
298
+ options.settings ?? {},
299
+ );
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Every `new` a refusal offers, checked as `new` checks its options (in
305
+ * memory, nothing written) before it is offered: a dial value the line
306
+ * gives in place of one typed passes only as an exact reading of what was
307
+ * typed (never a stock value); a flag `new` refuses is left out, and the
308
+ * reason names it; a line that is still refused is not offered. The one
309
+ * gate for `new` lines, as set's lines have theirs.
310
+ * @param {unknown} e
311
+ * @param {string} cwd
312
+ * @param {Record<string, string | string[] | undefined>} typed the dial options given
313
+ * @returns {Promise<unknown>}
314
+ */
315
+ async function vetNewLines(e, cwd, typed) {
316
+ if (!(e instanceof AstryxError) || !(e.suggestions ?? []).length) return e;
317
+ const prefix = `${P} new `;
318
+ /** @type {import('./_settings.mjs').Ctx | null} */
319
+ let ctx = null;
320
+ try {
321
+ ctx = /** @type {import('./_settings.mjs').Ctx} */ (await context(cwd));
322
+ } catch {
323
+ return e;
324
+ }
325
+ /** @param {string} line */
326
+ const read = line => {
327
+ const args = splitCommand(line.slice(prefix.length));
328
+ if (!args || !args.length || args[0].startsWith('-')) return null;
329
+ const [slug, ...rest] = args;
330
+ /** @type {Array<[string, string]>} */
331
+ const flags = [];
332
+ let like = /** @type {string | undefined} */ (undefined);
333
+ let png = false;
334
+ for (let j = 0; j < rest.length; j += 1) {
335
+ const m = /^--([a-z-]+)$/.exec(rest[j]);
336
+ if (m?.[1] === 'png') png = true;
337
+ else if (m && rest[j + 1] != null) {
338
+ const v = rest[(j += 1)];
339
+ if (m[1] === 'like') like = v;
340
+ else flags.push([m[1], v]);
341
+ } else return null;
342
+ }
343
+ return {slug, like, png, flags};
344
+ };
345
+ /**
346
+ * The refusal `new` gives these flags, or null.
347
+ * @param {string} slug @param {string | undefined} like
348
+ * @param {Array<[string, string]>} flags @param {boolean} png
349
+ */
350
+ const problem = async (slug, like, flags, png) => {
351
+ /** @type {Record<string, string | string[]>} */
352
+ const settings = {};
353
+ for (const [k, v] of flags) {
354
+ const had = settings[k];
355
+ settings[k] = had == null ? v : [...[had].flat(), v];
356
+ }
357
+ const base = like && like !== 'none' ? like : undefined;
358
+ try {
359
+ /** @type {any} */ (ctx).base = await baseResolved(
360
+ /** @type {any} */ (ctx).project,
361
+ base,
362
+ );
363
+ } catch {
364
+ /** @type {any} */ (ctx).base = await baseResolved(
365
+ /** @type {any} */ (ctx).project,
366
+ undefined,
367
+ );
368
+ }
369
+ try {
370
+ applyNewSettings(
371
+ /** @type {any} */ (ctx),
372
+ slug,
373
+ {name: slug, ...(base ? {like: base} : {}), mode: 'both', settings: []},
374
+ settings,
375
+ png,
376
+ like,
377
+ );
378
+ return null;
379
+ } catch (err) {
380
+ if (err instanceof AstryxError) return err;
381
+ throw err;
382
+ }
383
+ };
384
+ // A light and a dark color typed as one value is read as that pair.
385
+ const typedValues = (/** @type {string} */ k) =>
386
+ [typed[k]]
387
+ .flat()
388
+ .filter(v => v != null)
389
+ .map(String)
390
+ .map(v => {
391
+ const pair = colorPair(v) ?? modeColorsOf(v);
392
+ return pair.light && pair.dark
393
+ ? `light-dark(${pair.light}, ${pair.dark})`
394
+ : v;
395
+ });
396
+ /** @type {Array<{name: string, reason?: string}>} */
397
+ const out = [];
398
+ for (const x of e.suggestions ?? []) {
399
+ const line = x.name.startsWith(prefix) ? read(x.name) : null;
400
+ if (!line) {
401
+ out.push(x);
402
+ continue;
403
+ }
404
+ /** @type {string[]} */
405
+ const untyped = [];
406
+ /** @type {string[]} */
407
+ const refused = [];
408
+ const shown = (/** @type {[string, string]} */ [k, v]) =>
409
+ `--${k} ${quoteCommandArgument(v)}`;
410
+ // A value in place of one typed is offered only as an exact reading of
411
+ // what was typed.
412
+ const lineMode = line.flags.find(([k]) => k === 'mode')?.[1];
413
+ const typedOnly = line.flags.filter(f => {
414
+ const was = typedValues(f[0]);
415
+ const ok =
416
+ !was.length ||
417
+ was.includes(f[1]) ||
418
+ was.some(t =>
419
+ allowedLine({
420
+ offered: f[1],
421
+ typed: t,
422
+ thing: f[0],
423
+ ...(lineMode ? {saved: new Map([['mode', [lineMode]]])} : {}),
424
+ }),
425
+ );
426
+ if (!ok) untyped.push(shown(f));
427
+ return ok;
428
+ });
429
+ // Each flag in turn is kept when new still takes the line with it, so a
430
+ // flag new refuses (alone, or beside one kept before it) is left out.
431
+ /** @type {Array<[string, string]>} */
432
+ const flags = [];
433
+ for (const f of typedOnly)
434
+ if (await problem(line.slug, line.like, [...flags, f], false))
435
+ refused.push(shown(f));
436
+ else flags.push(f);
437
+ if (await problem(line.slug, line.like, flags, line.png)) continue;
438
+ const dropped = [
439
+ ...(untyped.length
440
+ ? [`${untyped.join(' and ')} (not what was typed)`]
441
+ : []),
442
+ ...(refused.length
443
+ ? [`${refused.join(' and ')}, which new refuses`]
444
+ : []),
445
+ ];
446
+ const name = `${prefix}${line.slug}${newFlags(
447
+ line.like,
448
+ Object.fromEntries(
449
+ flags.reduce((/** @type {Map<string, string[]>} */ m, [k, v]) => {
450
+ m.set(k, [...(m.get(k) ?? []), v]);
451
+ return m;
452
+ }, new Map()),
453
+ ),
454
+ line.png,
455
+ )}`;
456
+ if (out.some(y => y.name === name)) continue;
457
+ out.push(
458
+ dropped.length
459
+ ? {
460
+ name,
461
+ reason: `do this instead, without ${dropped.join('; and without ')}`,
462
+ }
463
+ : {...x, name},
464
+ );
465
+ }
466
+ e.suggestions = out;
467
+ return e;
468
+ }
469
+
470
+ /**
471
+ * {@link themeEditNew}'s work.
472
+ * @param {string} name
473
+ * @param {import('./theme-edit.type.mjs').ThemeEditNewOptions} options
474
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditNewResponse>}
475
+ */
476
+ async function newTheme(name, options) {
265
477
  const {cwd = process.cwd(), png = false, settings = {}} = options;
266
- // `--like none` builds on no base, as `set <theme> base none` does.
267
- const like = options.like === 'none' ? undefined : options.like;
478
+ // --like reads a base in any case, by the one case rule of every dial
479
+ // (`set <theme> base Neutral` is neutral); `--like none` builds on no
480
+ // base, as `set <theme> base none` does.
481
+ const likeWord =
482
+ typeof options.like === 'string'
483
+ ? (dialWordOf('base', options.like) ?? options.like)
484
+ : options.like;
485
+ const like = likeWord === 'none' ? undefined : likeWord;
268
486
  requireProject(cwd);
269
487
  // A corrected `new` keeps every option given, fixing only the bad one.
270
488
  // A --like in another case is the built-in theme it names.
@@ -284,7 +502,7 @@ export async function themeEditNew(name, options = {}) {
284
502
  .replace(/^theme-/, '');
285
503
  const likeFixed =
286
504
  like == null
287
- ? options.like === 'none'
505
+ ? likeWord === 'none'
288
506
  ? 'none'
289
507
  : undefined
290
508
  : LIKE.includes(baseName(like))
@@ -345,21 +563,50 @@ export async function themeEditNew(name, options = {}) {
345
563
  /** @type {string} */ newName,
346
564
  /** @type {string | null | undefined} */ likeValue = likeFixed,
347
565
  ) => `${P} new ${newName}${newFlags(likeValue, fitSettings, png)}`;
566
+ // The same new as lines that run here: a built-in base the project has
567
+ // not installed is installed first.
568
+ const againLines = (
569
+ /** @type {string} */ newName,
570
+ /** @type {string | null | undefined} */ likeValue = likeFixed,
571
+ ) =>
572
+ likeValue && LIKE.includes(likeValue)
573
+ ? onBuiltIn(cwd, likeValue, again(newName, likeValue))
574
+ : [again(newName, likeValue)];
348
575
  if (!slugOk(name)) {
349
- const fixed = slugFor(name);
350
- // Only a name typed in another case is the theme here already.
351
- const sameName = String(name ?? '').toLowerCase() === fixed;
352
- const exists = sameName && fs.existsSync(themeFiles(cwd, fixed).settings);
576
+ // A path typed for the name (themes/brand, ./t, t/) names the theme the
577
+ // path ends in.
578
+ // A file name, the app copy's export (tTheme), camelCase or spaces
579
+ // (BrandDark, "Brand Dark") name the theme they read as: when it is
580
+ // here already, that is said, never a numbered second copy offered.
581
+ const typed = String(name ?? '');
582
+ const path_ = /[\\/]/.test(typed);
583
+ const readings = themeNameReadings(typed);
584
+ const present = readings.find(n =>
585
+ fs.existsSync(themeFiles(cwd, n).settings),
586
+ );
587
+ const fixed =
588
+ present ?? readings[0] ?? slugFor(path_ ? typedThemeName(typed) : typed);
589
+ const exists = Boolean(present);
353
590
  refuse(
354
591
  E.ERR_INVALID_ARGUMENT,
355
592
  `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE})${exists ? `; ${fixed} is a theme here already` : ''}.${dropped}`,
356
593
  {
357
594
  run: exists
358
595
  ? [`${P} show ${fixed}`]
359
- : [again(usableNewName(cwd, fixed))],
596
+ : againLines(usableNewName(cwd, fixed)),
360
597
  },
361
598
  );
362
599
  }
600
+ // A name the theme commands' own discovery skips ("a--b", "b-") would
601
+ // make an app copy no `theme add`, `theme list` or doctor takes.
602
+ if (!THEME_SLUG_RE.test(name)) {
603
+ const cleaned = name.replace(/-{2,}/g, '-').replace(/-+$/, '');
604
+ refuse(
605
+ E.ERR_INVALID_ARGUMENT,
606
+ `"${name}" is not a theme name the theme commands take: a dash only between letters or digits (no two in a row, none at the end), so its app copy in src/themes/ would be skipped by theme add, theme list and doctor.${dropped}`,
607
+ {run: againLines(usableNewName(cwd, cleaned))},
608
+ );
609
+ }
363
610
  // A built-in theme's name would collide with the theme of that name the
364
611
  // app may also use.
365
612
  if (LIKE.includes(name))
@@ -367,16 +614,19 @@ export async function themeEditNew(name, options = {}) {
367
614
  E.ERR_FILE_EXISTS,
368
615
  `${name} is a built-in theme; an editor theme needs a name of its own. To start from ${name}, build on it.${dropped}`,
369
616
  {
370
- run: [
371
- again(
372
- fs.existsSync(themeFiles(cwd, `my-${name}`).dir)
373
- ? freeThemeName(cwd, `my-${name}`)
374
- : `my-${name}`,
375
- // Built on the theme named when it is installed, unless another
376
- // base (or none) was given.
377
- likeFixed ?? name,
378
- ),
379
- ],
617
+ run: (() => {
618
+ const mine = fs.existsSync(themeFiles(cwd, `my-${name}`).dir)
619
+ ? freeThemeName(cwd, `my-${name}`)
620
+ : `my-${name}`;
621
+ // Built on the theme named (installed first when it is not),
622
+ // unless another base (or none) was given; or on no base.
623
+ return likeFixed !== undefined
624
+ ? againLines(mine, likeFixed)
625
+ : [
626
+ ...againLines(mine, name),
627
+ ...(baseInstalled(cwd, name) ? [] : [again(mine, null)]),
628
+ ];
629
+ })(),
380
630
  },
381
631
  );
382
632
  const f = themeFiles(cwd, name);
@@ -400,7 +650,7 @@ export async function themeEditNew(name, options = {}) {
400
650
  refuse(
401
651
  E.ERR_FILE_EXISTS,
402
652
  `themes/${name} is ${dirSt.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.${dropped}`,
403
- {run: [again(freeThemeName(cwd, name))]},
653
+ {run: againLines(freeThemeName(cwd, name))},
404
654
  );
405
655
  // Settings that are not valid JSON are kept aside, and the theme is
406
656
  // made again beside them.
@@ -408,12 +658,15 @@ export async function themeEditNew(name, options = {}) {
408
658
  if (fs.existsSync(f.settings) && !damaged)
409
659
  refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.${dropped}`, {
410
660
  // What the command asked for, on the theme that exists or as a new one.
661
+ // A base's install line, when one is needed, is given once.
411
662
  run: [
412
- `${P} show ${name}`,
413
- ...(likeFixed && LIKE.includes(likeFixed)
414
- ? [`${P} set ${name} base ${likeFixed}`]
415
- : []),
416
- again(freeThemeName(cwd, name)),
663
+ ...new Set([
664
+ `${P} show ${name}`,
665
+ ...(likeFixed && LIKE.includes(likeFixed)
666
+ ? onBuiltIn(cwd, likeFixed, `${P} set ${name} base ${likeFixed}`)
667
+ : []),
668
+ ...againLines(freeThemeName(cwd, name)),
669
+ ]),
417
670
  ],
418
671
  });
419
672
  // A `new` stopped part way (killed, out of memory) leaves its own marker
@@ -421,17 +674,18 @@ export async function themeEditNew(name, options = {}) {
421
674
  // after every argument is checked. Anything else in the folder, or a
422
675
  // folder without the marker, is never touched.
423
676
  const left = fs.existsSync(f.dir)
424
- ? editorLeftovers(f.dir, name, damaged)
677
+ ? editorLeftovers(cwd, f.dir, name, damaged)
425
678
  : null;
426
679
  const holdsOther =
427
680
  fs.existsSync(f.dir) &&
428
681
  !left &&
429
- fs.readdirSync(f.dir).some(n => !FOLDER_JUNK.has(n));
682
+ // Empty folders (an empty tokens/) hold nothing of anyone's.
683
+ !folderIsEmpty(f.dir);
430
684
  if (holdsOther)
431
685
  refuse(
432
686
  E.ERR_FILE_EXISTS,
433
687
  `themes/${name}/ already holds files this command did not make; choose another name.${dropped}`,
434
- {run: [again(freeThemeName(cwd, name))]},
688
+ {run: againLines(freeThemeName(cwd, name))},
435
689
  );
436
690
  if (like != null && !LIKE.includes(like))
437
691
  refuse(
@@ -469,9 +723,21 @@ export async function themeEditNew(name, options = {}) {
469
723
  // Every check comes before the first change to the folder: the settings,
470
724
  // and a source of the user's own kept from before (it must still extend
471
725
  // the settings, or the build fails after the folder was cleared).
726
+ try {
727
+ applyNewSettings(
728
+ ctx,
729
+ name,
730
+ structuredClone(data),
731
+ settings,
732
+ png,
733
+ likeFixed ?? undefined,
734
+ );
735
+ } catch (e) {
736
+ throw await followNewLine(e, ctx, name, data);
737
+ }
472
738
  applyNewSettings(ctx, name, data, settings, png, likeFixed ?? undefined);
473
739
  if (left?.keep.some(p => path.basename(p) === `${name}.theme.ts`))
474
- refuseThemeSource(cwd, name);
740
+ await refuseThemeSource(cwd, name);
475
741
  /** @type {string[]} */
476
742
  const keptNotes = [];
477
743
  /** @type {string[]} */
@@ -576,7 +842,7 @@ export async function themeEditNew(name, options = {}) {
576
842
  }
577
843
  refuseIfLockLost();
578
844
  fs.rmSync(marker, {force: true});
579
- const p = await previewAndRoute(ctx, name, data, png);
845
+ const p = await previewAndRoute(ctx, name, data, png, 'overview', 'new');
580
846
  /** @type {string[]} */
581
847
  const notes = [
582
848
  ...keptNotes,
@@ -610,6 +876,78 @@ export async function themeEditNew(name, options = {}) {
610
876
  };
611
877
  }
612
878
 
879
+ /**
880
+ * A refused `new` whose suggestions include another `new` of the theme:
881
+ * that line is checked as `new` checks its dial flags (in memory, nothing
882
+ * written), and each repair a refusal of it offers is folded in, so the one
883
+ * line fixes or drops every bad flag. It comes first.
884
+ * @param {unknown} e
885
+ * @param {import('./_settings.mjs').Ctx} ctx
886
+ * @param {string} slug
887
+ * @param {import('./_settings.mjs').ThemeData} data the theme before any dial
888
+ * @returns {Promise<unknown>}
889
+ */
890
+ async function followNewLine(e, ctx, slug, data) {
891
+ if (!(e instanceof AstryxError)) return e;
892
+ const prefix = `${P} new ${slug}`;
893
+ const isNew = (/** @type {string} */ n) =>
894
+ n === prefix || n.startsWith(`${prefix} `);
895
+ const first = (e.suggestions ?? []).find(x => isNew(x.name));
896
+ if (!first) return e;
897
+ const followed = await followLine(
898
+ first.name,
899
+ line => {
900
+ const args = splitCommand(line.slice(prefix.length));
901
+ if (!args) return null;
902
+ /** @type {Record<string, string | string[]>} */
903
+ const settings = {};
904
+ /** @type {string | undefined} */
905
+ let like;
906
+ let png = false;
907
+ for (let j = 0; j < args.length; j += 1) {
908
+ const m = /^--([a-z-]+)$/.exec(args[j]);
909
+ if (m?.[1] === 'png') png = true;
910
+ else if (m && args[j + 1] != null) {
911
+ const v = args[(j += 1)];
912
+ if (m[1] === 'like') like = v;
913
+ else {
914
+ const had = settings[m[1]];
915
+ settings[m[1]] = had == null ? v : [...[had].flat(), v];
916
+ }
917
+ } else return null;
918
+ }
919
+ try {
920
+ applyNewSettings(
921
+ ctx,
922
+ slug,
923
+ structuredClone(data),
924
+ settings,
925
+ png,
926
+ like ?? data.like,
927
+ );
928
+ return null;
929
+ } catch (again) {
930
+ if (again instanceof AstryxError) return again;
931
+ throw again;
932
+ }
933
+ },
934
+ isNew,
935
+ );
936
+ // A line that is still refused is never offered as the fix.
937
+ if (followed.line === first.name || followed.why) return e;
938
+ e.suggestions = [
939
+ {
940
+ ...first,
941
+ name: followed.line,
942
+ reason: 'do this instead: every flag fixed',
943
+ },
944
+ ...(e.suggestions ?? []).filter(
945
+ x => x !== first && x.name !== followed.line,
946
+ ),
947
+ ];
948
+ return e;
949
+ }
950
+
613
951
  /**
614
952
  * The dial settings of `new`, checked one at a time in dial order (mode
615
953
  * first; a color before vibrancy, which needs one) into `data`.
@@ -655,15 +993,34 @@ function applyNewSettings(
655
993
  /** @type {import('./_settings.mjs').Setting} */
656
994
  let s;
657
995
  try {
658
- s = checkSetting(ctx, slug, data, thing, String(value), {}, false);
996
+ // The same input cleanup set gives a typed value (quotes of any
997
+ // kind around a font, invisible spaces, a pasted `name: value`).
998
+ const typed = normalizeEntry(thing, String(value)).value;
999
+ s = checkSetting(
1000
+ ctx,
1001
+ slug,
1002
+ data,
1003
+ thing,
1004
+ typed ?? String(value),
1005
+ {},
1006
+ false,
1007
+ );
659
1008
  } catch (e) {
660
- throw asNewRefusal(
661
- vetSuggestions(e, ctx, slug, data),
1009
+ throw newColorPair(
1010
+ asNewRefusal(
1011
+ vetSuggestions(e, ctx, slug, data),
1012
+ slug,
1013
+ settings,
1014
+ likeFlag,
1015
+ png,
1016
+ {thing, index},
1017
+ ),
662
1018
  slug,
663
1019
  settings,
664
1020
  likeFlag,
665
1021
  png,
666
- {thing, index},
1022
+ thing,
1023
+ String(value),
667
1024
  );
668
1025
  }
669
1026
  if (thing === 'mode')
@@ -737,11 +1094,22 @@ function newFlags(like, settings, png) {
737
1094
  function asNewRefusal(e, slug, settings, like, png = false, at = null) {
738
1095
  if (!(e instanceof AstryxError)) return e;
739
1096
  const setPrefix = `${P} set ${slug} `;
740
- e.suggestions = (e.suggestions ?? []).map(s => {
1097
+ /** @type {string[]} */
1098
+ const after = [];
1099
+ /** @type {Array<import('../../foundation/response/base').Suggestion | null>} */
1100
+ const mapped = (e.suggestions ?? []).map(s => {
741
1101
  if (s.name === `${P} set --help`) return {...s, name: `${P} new --help`};
742
1102
  if (!s.name.startsWith(setPrefix)) return s;
1103
+ const words = splitCommand(s.name.slice(setPrefix.length)) ?? [];
743
1104
  const [thing, ...rest] = s.name.slice(setPrefix.length).split(' ');
744
1105
  if (thing.startsWith('--') || !DIALS[thing]) return s;
1106
+ // A set with its own scope (`corners pill --on button`) is no option of
1107
+ // new: it is a change to make once the theme is made (said in the
1108
+ // message below).
1109
+ if (words.length !== 2) {
1110
+ after.push(s.name);
1111
+ return null;
1112
+ }
745
1113
  const fixed = unquoteWord(rest.join(' '));
746
1114
  // Only the refused value changes: a dial given several values
747
1115
  // (--headings tight --headings BOLD) keeps the others, in order.
@@ -756,6 +1124,12 @@ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
756
1124
  name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: next}, png)}`,
757
1125
  };
758
1126
  });
1127
+ e.suggestions = mapped.filter(x => x != null);
1128
+ if (after.length)
1129
+ e.message = e.message.replace(
1130
+ /( Nothing was changed\.)?$/,
1131
+ ` Once ${slug} is made, ${after.slice(0, 2).join(' or ')} does that.$1`,
1132
+ );
759
1133
  // A refused value with nothing to put in its place: the same new
760
1134
  // without it, every other option kept.
761
1135
  if (at && !e.suggestions.some(x => x.name.startsWith(`${P} new `))) {
@@ -771,6 +1145,93 @@ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
771
1145
  return e;
772
1146
  }
773
1147
 
1148
+ /**
1149
+ * The color for each mode a value names in words (`light #111111 dark
1150
+ * #eeeeee`, `dark: navy`): the one reading of a light and a dark color
1151
+ * typed for a color dial on `new`.
1152
+ * @param {string} typed
1153
+ * @returns {Record<string, string>}
1154
+ */
1155
+ function modeColorsOf(typed) {
1156
+ /** @type {Record<string, string>} */
1157
+ const pair = {};
1158
+ for (const m of typed.matchAll(
1159
+ /\b(light|dark)\b\s*(?:mode\s*)?[:=]?\s*(#[0-9a-f]{3,8}\b|[a-z]+\([^)]*\)|[a-z]+)/gi,
1160
+ ))
1161
+ pair[m[1].toLowerCase()] = m[2];
1162
+ return pair;
1163
+ }
1164
+
1165
+ /**
1166
+ * A color dial on `new` given a light and a dark color ("light #111111 dark
1167
+ * #eeeeee"): the refusal offers the user's own colors, per mode, as set
1168
+ * does, never a stock color they did not type.
1169
+ * @param {unknown} e
1170
+ * @param {string} slug
1171
+ * @param {Record<string, any>} settings
1172
+ * @param {string | undefined} like
1173
+ * @param {boolean} png
1174
+ * @param {string} thing
1175
+ * @param {string} typed
1176
+ */
1177
+ function newColorPair(e, slug, settings, like, png, thing, typed) {
1178
+ if (!(e instanceof AstryxError) || !PALETTE_DIALS.includes(thing)) return e;
1179
+ const typedLower = typed.toLowerCase();
1180
+ // A color in a line the user did not type (a stock example) goes.
1181
+ e.suggestions = (e.suggestions ?? []).filter(x => {
1182
+ if (!x.name.startsWith(`${P} new `)) return true;
1183
+ const m = new RegExp(`--${thing} '?(#[0-9a-f]{3,8})'?`, 'i').exec(x.name);
1184
+ return !m || typedLower.includes(m[1].toLowerCase());
1185
+ });
1186
+ // With every color line gone, the same new without that color, every
1187
+ // other option kept.
1188
+ if (!e.suggestions.some(x => x.name.startsWith(`${P} new `)))
1189
+ e.suggestions.push({
1190
+ name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: undefined}, png)}`,
1191
+ reason: `without --${thing} ${quoteCommandArgument(typed)}`,
1192
+ });
1193
+ const pair = modeColorsOf(typed);
1194
+ if (!pair.light && !pair.dark) return e;
1195
+ const mode = String(
1196
+ Array.isArray(settings.mode) ? settings.mode[0] : (settings.mode ?? 'both'),
1197
+ );
1198
+ /** @type {Array<{name: string, reason: string}>} */
1199
+ const lines = [];
1200
+ /** @param {string} color @param {string} reason @param {Record<string, any>} [extra] */
1201
+ const line = (color, reason, extra = {}) =>
1202
+ lines.push({
1203
+ name: `${P} new ${slug}${newFlags(like, {...settings, ...extra, [thing]: color}, png)}`,
1204
+ reason,
1205
+ });
1206
+ if (mode === 'dark-only' && pair.dark)
1207
+ line(pair.dark, 'do this instead: the dark color you gave');
1208
+ else if (mode === 'light-only' && pair.light)
1209
+ line(pair.light, 'do this instead: the light color you gave');
1210
+ else if (mode === 'both') {
1211
+ if (pair.light)
1212
+ line(
1213
+ pair.light,
1214
+ `the light color you gave; then set ${slug} --color-${thing} ${pair.dark ?? '…'} --mode dark for the dark one`,
1215
+ );
1216
+ if (pair.dark)
1217
+ line(pair.dark, 'or a dark-only theme with the dark color you gave', {
1218
+ mode: 'dark-only',
1219
+ });
1220
+ }
1221
+ // No color for the mode the theme has: how the dial works, and the
1222
+ // same new without it, never a color made up.
1223
+ if (!lines.length)
1224
+ lines.push({
1225
+ name: `${P} how ${thing}`,
1226
+ reason: `no ${mode === 'light-only' ? 'light' : 'dark'} color was given for this ${mode} theme`,
1227
+ });
1228
+ e.suggestions = [
1229
+ ...lines,
1230
+ ...(e.suggestions ?? []).filter(x => !lines.some(l => l.name === x.name)),
1231
+ ];
1232
+ return e;
1233
+ }
1234
+
774
1235
  /**
775
1236
  * Headings values with every later value for an axis already given left
776
1237
  * out (the first weight and the first tracking stay); a word of neither
@@ -822,6 +1283,39 @@ function changeFocus(s) {
822
1283
  return 'overview';
823
1284
  }
824
1285
 
1286
+ /**
1287
+ * A signal handler for the checks and pictures after a change is saved: it
1288
+ * says what is saved (in the words of the command that ran) and how to run
1289
+ * what did not, with the project's own CLI invocation, then lets the
1290
+ * signal end the process (the render's own handler re-raises it; with none,
1291
+ * this one does).
1292
+ * @param {string} slug
1293
+ * @param {'set' | 'undo' | 'new'} [kind] the command that saved
1294
+ * @param {string} [cwd] the project, for the CLI invocation
1295
+ * @param {boolean} [png] pictures were asked for: the command named takes
1296
+ * them too
1297
+ * @returns {(sig: NodeJS.Signals) => void}
1298
+ */
1299
+ export function stoppedAfterSave(
1300
+ slug,
1301
+ kind = 'set',
1302
+ cwd = process.cwd(),
1303
+ png = false,
1304
+ ) {
1305
+ const done =
1306
+ kind === 'undo'
1307
+ ? `the undo is done: ${slug} is saved and built as it was before that change`
1308
+ : kind === 'new'
1309
+ ? `${slug} is made and built`
1310
+ : `the change to ${slug} is saved and built (and its undo step kept)`;
1311
+ return sig => {
1312
+ process.stderr.write(
1313
+ `Stopped: ${done}; its checks and pictures did not run. ${formatCliCommand(`${P} show ${slug}${png ? ' --png' : ''}`, cwd)} runs them.\n`,
1314
+ );
1315
+ if (process.listenerCount(sig) === 0) process.kill(process.pid, sig);
1316
+ };
1317
+ }
1318
+
825
1319
  /**
826
1320
  * The preview after a change, with the in-app preview route kept in step:
827
1321
  * its imports follow the theme, such as the stylesheet of a font package
@@ -832,13 +1326,34 @@ function changeFocus(s) {
832
1326
  * @param {boolean} png
833
1327
  * @param {'colors' | 'components' | 'overview'} [focus] the preview page
834
1328
  * most about the change: Colors for a color, Components for a part
1329
+ * @param {'set' | 'undo' | 'new'} [kind] the command that saved
835
1330
  */
836
- async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
837
- const p = await previewAfter(ctx, slug, data, png);
1331
+ async function previewAndRoute(
1332
+ ctx,
1333
+ slug,
1334
+ data,
1335
+ png,
1336
+ focus = 'overview',
1337
+ kind = /** @type {'set' | 'undo' | 'new'} */ ('set'),
1338
+ ) {
1339
+ // Stopped (Ctrl-C) while the checks and pictures run: the change is saved
1340
+ // and built already, which one line says before the process ends.
1341
+ const stopped = stoppedAfterSave(slug, kind, ctx.project.cwd, png);
1342
+ process.once('SIGINT', stopped);
1343
+ process.once('SIGTERM', stopped);
1344
+ /** @type {Awaited<ReturnType<typeof previewAfter>>} */
1345
+ let p;
1346
+ try {
1347
+ p = await previewAfter(ctx, slug, data, png);
1348
+ } finally {
1349
+ process.removeListener('SIGINT', stopped);
1350
+ process.removeListener('SIGTERM', stopped);
1351
+ }
838
1352
  const wrote = takeFirstAppCopy(ctx.project.cwd, slug);
1353
+ const previewStale = await keepPreviewRoute(ctx, slug);
839
1354
  return {
840
1355
  ...p,
841
- previewStale: await keepPreviewRoute(ctx, slug),
1356
+ previewStale,
842
1357
  // How to see the change: the page about it, at its own URL.
843
1358
  // A page not written this time (preview null) still shows the theme
844
1359
  // as it was; checks that failed with the page written do not.
@@ -852,9 +1367,18 @@ async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
852
1367
  cause: 'no preview was rendered',
853
1368
  })
854
1369
  : null,
1370
+ {
1371
+ // Only a run that took no picture failed: a note on pictures that
1372
+ // were taken (why an earlier browser did not) is not a failure.
1373
+ pictureProblem:
1374
+ png && !(p.pictures ?? []).length ? p.pictureProblem : null,
1375
+ stale: previewStale,
1376
+ },
855
1377
  ),
856
1378
  // The first time the theme's app copy is written, its files are named.
857
1379
  ...(wrote ? {appCopy: {wrote}} : {}),
1380
+ // A copy a file of yours kept from being written: said, never a quiet ok.
1381
+ ...appCopyStale(ctx.project.cwd, slug),
858
1382
  };
859
1383
  }
860
1384
 
@@ -870,12 +1394,93 @@ async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
870
1394
  async function keepPreviewRoute(ctx, slug) {
871
1395
  try {
872
1396
  return (await refreshPreviewRoute(ctx.project.cwd, slug)).stale;
873
- } catch {
874
- // A damaged or moved preview.
1397
+ } catch (e) {
1398
+ // A route that could not be written (its permissions, a folder in its
1399
+ // place) does not follow this change: said, never a quiet ok. A
1400
+ // damaged preview record is named by the preview commands themselves.
1401
+ const code = /** @type {any} */ (e)?.code;
1402
+ if (code && /^E[A-Z]+$/.test(code)) {
1403
+ const where = /** @type {any} */ (e)?.path;
1404
+ return [
1405
+ `${where ? path.relative(ctx.project.cwd, where) : 'the in-app preview route'} could not be written (${code}), so the in-app preview does not follow this change; fix its permissions, then ${PREVIEW_CMD} add writes it again`,
1406
+ ];
1407
+ }
875
1408
  return [];
876
1409
  }
877
1410
  }
878
1411
 
1412
+ /**
1413
+ * The app's theme state (the themes `theme add` put into its theme
1414
+ * module), or null when it cannot be read.
1415
+ * @param {string} cwd
1416
+ */
1417
+ function appThemeState(cwd) {
1418
+ try {
1419
+ return readThemeState(cwd);
1420
+ } catch {
1421
+ return null;
1422
+ }
1423
+ }
1424
+
1425
+ /**
1426
+ * Whether the app lists the theme (`theme add` put it into its module).
1427
+ * @param {string} cwd
1428
+ * @param {string} slug
1429
+ */
1430
+ const appListsTheme = (cwd, slug) =>
1431
+ Object.hasOwn(appThemeState(cwd)?.themes ?? {}, slug);
1432
+
1433
+ /**
1434
+ * For a theme `theme add` put into the app: the app's theme module gives
1435
+ * the app each theme's one color mode, written when the theme was added,
1436
+ * so a change of mode needs `theme add` again. Null for a theme the app
1437
+ * does not list (its mode is the app's own <Theme mode>).
1438
+ * @param {string} cwd
1439
+ * @param {string} slug
1440
+ * @param {'light' | 'dark' | null} now the one mode it has now
1441
+ * @returns {string | null}
1442
+ */
1443
+ function addedModeNote(cwd, slug, now) {
1444
+ const state = appThemeState(cwd);
1445
+ if (!state || !Object.hasOwn(state.themes, slug)) return null;
1446
+ const module = path
1447
+ .relative(cwd, state.module.path)
1448
+ .split(path.sep)
1449
+ .join('/');
1450
+ return `${module}, the app's theme module, gives the app ${slug}'s mode as it was when ${slug} was added; run \`theme add ${slug}\` to write it again, and the app ${now ? `shows ${slug} in ${now} mode` : 'follows the system again'}`;
1451
+ }
1452
+
1453
+ /**
1454
+ * What a change of mode asks of the app's wiring: a one-mode theme is
1455
+ * given its mode by the app's <Theme>, and one back to both modes no longer.
1456
+ * @param {string} cwd
1457
+ * @param {string} slug
1458
+ * @param {string | undefined} before
1459
+ * @param {string | undefined} after
1460
+ * @returns {string[]}
1461
+ */
1462
+ function modeWiringNotes(cwd, slug, before, after) {
1463
+ /** @param {string | undefined} m @returns {'light' | 'dark' | null} */
1464
+ const one = m =>
1465
+ m === 'light-only' ? 'light' : m === 'dark-only' ? 'dark' : null;
1466
+ const [was, now] = [one(before), one(after)];
1467
+ if (was === now) return [];
1468
+ const added = addedModeNote(cwd, slug, now);
1469
+ if (added) return [added];
1470
+ return [
1471
+ ...(was
1472
+ ? [
1473
+ `if the app's <Theme> was given mode="${was}" for ${slug}, take it out${now ? ` (or make it mode="${now}")` : ''}: with it the app stays ${was}, whatever the system asks for`,
1474
+ ]
1475
+ : []),
1476
+ ...(now && !was
1477
+ ? [
1478
+ `the app shows ${slug} in ${now} mode when its <Theme> is given mode="${now}" (<Theme theme={…} mode="${now}">), as the preview does; the theme keeps both halves of its colors, so a toast or a lightbox Core draws in the other mode stays readable`,
1479
+ ]
1480
+ : []),
1481
+ ];
1482
+ }
1483
+
879
1484
  /**
880
1485
  * Change one thing in a theme: checked, built, previewed.
881
1486
  * @experimental
@@ -886,7 +1491,227 @@ async function keepPreviewRoute(ctx, slug) {
886
1491
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
887
1492
  */
888
1493
  export async function themeEditSet(theme, thing, value, options = {}) {
889
- return change('set', theme, thing, value, options);
1494
+ try {
1495
+ return await change('set', theme, thing, value, options);
1496
+ } catch (e) {
1497
+ throw await swappedThingValue(
1498
+ await swappedOrder(e, 'set', [theme, thing, value], options),
1499
+ theme,
1500
+ thing,
1501
+ value,
1502
+ options,
1503
+ );
1504
+ }
1505
+ }
1506
+
1507
+ /**
1508
+ * A refused set whose thing is no setting, with a value that names one
1509
+ * (`set t round corners`): the same set with the two in the other order,
1510
+ * checked by set, leads when it works.
1511
+ * @param {unknown} e
1512
+ * @param {string} slug
1513
+ * @param {string} thing
1514
+ * @param {string | undefined} value
1515
+ * @param {{cwd?: string, on?: string, when?: string, state?: string, mode?: string, only?: boolean}} options
1516
+ * @returns {Promise<unknown>}
1517
+ */
1518
+ async function swappedThingValue(e, slug, thing, value, options) {
1519
+ // The thing named no setting, or the value names one itself (`neutral
1520
+ // base`: a color dial given the base dial's name).
1521
+ if (
1522
+ !(e instanceof AstryxError) ||
1523
+ !value ||
1524
+ !slugOk(slug) ||
1525
+ !(
1526
+ e.code === E.ERR_THEME_UNKNOWN_THING ||
1527
+ (DIALS[value.trim().toLowerCase()] && e.code === E.ERR_THEME_BAD_VALUE)
1528
+ )
1529
+ )
1530
+ return e;
1531
+ const line = `${P} set ${slug} ${[
1532
+ value,
1533
+ thing,
1534
+ ...(options.on ? ['--on', options.on] : []),
1535
+ ...(options.when ? ['--when', options.when] : []),
1536
+ ...(options.state ? ['--state', options.state] : []),
1537
+ ...(options.mode ? ['--mode', options.mode] : []),
1538
+ ]
1539
+ .map(w => quoteCommandArgument(String(w)))
1540
+ .join(' ')}${options.only ? ' --only' : ''}`;
1541
+ const followed = await followChangeLine(
1542
+ 'set',
1543
+ slug,
1544
+ line,
1545
+ options.cwd ?? process.cwd(),
1546
+ );
1547
+ // The swapped reading holds only when set takes the value typed as the
1548
+ // setting, with the scope typed, and the line carries the thing typed
1549
+ // as its value (the one gate): never a sample command from a refusal of
1550
+ // the swapped line (`bold` is no setting, and no part was named). A line
1551
+ // that works once a step is done (an install) is offered after that step.
1552
+ const read = readSetLine(followed.line, slug);
1553
+ if (
1554
+ !read ||
1555
+ read.thing.toLowerCase() !== String(value).trim().toLowerCase() ||
1556
+ (read.flags?.on ?? undefined) !== (options.on ?? undefined) ||
1557
+ !allowedLine({offered: read.value, typed: String(thing), thing: read.thing})
1558
+ )
1559
+ return e;
1560
+ const why = `do this instead: ${value} is the setting and ${thing} its value`;
1561
+ if (!readyLines(followed, why).length) return e;
1562
+ e.suggestions = [
1563
+ ...readyLines(followed, why),
1564
+ ...(e.suggestions ?? []).filter(x => x.name !== followed.line),
1565
+ ];
1566
+ return e;
1567
+ }
1568
+
1569
+ /**
1570
+ * A refusal of a saved entry whose value the editor no longer accepts,
1571
+ * with the repair `set` offers for that value as typed (a typo, a unit, a
1572
+ * label read as set reads them) beside the undo: the line is followed as
1573
+ * set takes it, with the saved entry not checked while the theme is read,
1574
+ * and offered only when it carries the saved value (the one gate).
1575
+ * @param {unknown} e
1576
+ * @param {string} slug
1577
+ * @param {string} cwd
1578
+ */
1579
+ async function withSavedRepair(e, slug, cwd) {
1580
+ const bad = /** @type {any} */ (e)?.damaged;
1581
+ if (
1582
+ !(e instanceof AstryxError) ||
1583
+ !bad ||
1584
+ typeof bad.value !== 'string' ||
1585
+ ['mode', 'base'].includes(bad.thing)
1586
+ )
1587
+ return e;
1588
+ const line = `${P} set ${slug} ${setArgs(bad, bad.value)}`;
1589
+ const followed = await followChangeLine('set', slug, line, cwd, bad);
1590
+ if (followed.why || followed.line === line) return e;
1591
+ const read = readSetLine(followed.line, slug);
1592
+ if (
1593
+ !read ||
1594
+ read.thing !== bad.thing ||
1595
+ !allowedLine({offered: read.value, typed: bad.value, thing: read.thing})
1596
+ )
1597
+ return e;
1598
+ const list = e.suggestions ?? [];
1599
+ // A set line the refusal already offers (the value cleaned) stands.
1600
+ if (list.some(x => x.name.startsWith(`${P} set ${slug} `))) return e;
1601
+ const at = list.findIndex(x => x.name.startsWith(`${P} undo ${slug} `));
1602
+ e.suggestions = [
1603
+ ...list.slice(0, at + 1),
1604
+ {name: followed.line, reason: 'or set the value it holds, as set reads it'},
1605
+ ...list.slice(at + 1),
1606
+ ];
1607
+ return e;
1608
+ }
1609
+
1610
+ /**
1611
+ * A `set` or `undo` command line as set or undo takes it (a repair either
1612
+ * offers folded in, see followChangeLine), or null when it is refused with
1613
+ * no repair: the check every offered line passes, for lines the CLI builds
1614
+ * (a flag written with a value).
1615
+ * @param {'set' | 'undo'} sub
1616
+ * @param {string} line the whole command, `astryx experimental theme editor set <theme> …`
1617
+ * @param {string} cwd
1618
+ * @returns {Promise<string | null>}
1619
+ */
1620
+ export async function checkedChangeLine(sub, line, cwd) {
1621
+ const slug = splitCommand(line.slice(`${P} ${sub} `.length))?.[0];
1622
+ if (!line.startsWith(`${P} ${sub} `) || !slug) return null;
1623
+ const followed = await followChangeLine(sub, slug, line, cwd);
1624
+ return followed.why ? null : followed.line;
1625
+ }
1626
+
1627
+ /**
1628
+ * The lines that carry out a followed line: itself when it works; when its
1629
+ * own refusal offers it after a step (an install), that step and then the
1630
+ * line; else nothing.
1631
+ * @param {{line: string, why: string | null, next?: import('../../foundation/response/base').Suggestion[]}} followed
1632
+ * @param {string} reason
1633
+ * @returns {import('../../foundation/response/base').Suggestion[]}
1634
+ */
1635
+ function readyLines(followed, reason) {
1636
+ if (!followed.why) return [{name: followed.line, reason}];
1637
+ const at = (followed.next ?? []).findIndex(x => x.name === followed.line);
1638
+ return at > 0
1639
+ ? [
1640
+ ...(followed.next ?? []).slice(0, at),
1641
+ {
1642
+ name: followed.line,
1643
+ reason: `then ${reason.replace(/^do this instead: /, '')}`,
1644
+ },
1645
+ ]
1646
+ : [];
1647
+ }
1648
+
1649
+ /**
1650
+ * A refused theme name when the theme was typed after the setting (`set
1651
+ * --color-accent '#123457' t`): the same command with the theme first,
1652
+ * checked by that command, comes first, and no `new` of the setting's name
1653
+ * is offered.
1654
+ * @param {unknown} e
1655
+ * @param {'set' | 'undo'} sub
1656
+ * @param {Array<string | undefined>} words the positionals as typed
1657
+ * @param {{cwd?: string, on?: string, when?: string, state?: string, mode?: string, only?: boolean}} options
1658
+ * @returns {Promise<unknown>}
1659
+ */
1660
+ async function swappedOrder(e, sub, words, options) {
1661
+ if (
1662
+ !(e instanceof AstryxError) ||
1663
+ (e.code !== E.ERR_INVALID_ARGUMENT && e.code !== E.ERR_UNKNOWN_THEME)
1664
+ )
1665
+ return e;
1666
+ const cwd = options.cwd ?? process.cwd();
1667
+ const [first, ...rest] = words.map(w => (w == null ? '' : String(w)));
1668
+ if (slugOk(first) && fs.existsSync(themeFiles(cwd, first).settings)) return e;
1669
+ const at = rest.findIndex(
1670
+ w => slugOk(w) && fs.existsSync(themeFiles(cwd, w).settings),
1671
+ );
1672
+ if (at < 0) return e;
1673
+ const theme = rest[at];
1674
+ const moved = [first, ...rest.filter((_, i) => i !== at)].filter(
1675
+ w => w !== '',
1676
+ );
1677
+ const flags = [
1678
+ ...(options.on ? ['--on', options.on] : []),
1679
+ ...(options.when ? ['--when', options.when] : []),
1680
+ ...(options.state ? ['--state', options.state] : []),
1681
+ ...(options.mode ? ['--mode', options.mode] : []),
1682
+ ];
1683
+ // The line with the theme first, as set or undo checks it; for a set
1684
+ // whose other two words are also in the other order, the line with those
1685
+ // swapped too. Only a line that works is offered.
1686
+ const lineOf = (/** @type {string[]} */ ws) =>
1687
+ `${P} ${sub} ${theme} ${[...ws, ...flags]
1688
+ .map(w => quoteCommandArgument(w))
1689
+ .join(' ')}${options.only ? ' --only' : ''}`;
1690
+ let followed = await followChangeLine(sub, theme, lineOf(moved), cwd);
1691
+ if (followed.why && sub === 'set' && moved.length === 2)
1692
+ followed = await followChangeLine(
1693
+ sub,
1694
+ theme,
1695
+ lineOf([moved[1], moved[0]]),
1696
+ cwd,
1697
+ );
1698
+ const ready = readyLines(
1699
+ followed,
1700
+ `do this instead: ${theme} is the theme, so it comes first`,
1701
+ );
1702
+ // With the theme first and still refused, that refusal's reason and its
1703
+ // own next commands: never a `new` of the setting's name.
1704
+ if (!ready.length && followed.why)
1705
+ e.message = `${e.message.replace(/\s*Nothing was changed\.$/, '')} With ${theme} first: ${followed.why}. Nothing was changed.`;
1706
+ e.suggestions = [
1707
+ ...(ready.length
1708
+ ? ready
1709
+ : (followed.next ?? []).filter(x => !x.name.startsWith(`${P} new `))),
1710
+ ...(e.suggestions ?? []).filter(
1711
+ x => x.name !== followed.line && !x.name.startsWith(`${P} new `),
1712
+ ),
1713
+ ];
1714
+ return e;
890
1715
  }
891
1716
 
892
1717
  /**
@@ -900,9 +1725,47 @@ export async function themeEditSet(theme, thing, value, options = {}) {
900
1725
  function refuseStoredTokens(ctx, slug, data, skip) {
901
1726
  const bad = storedProblems(ctx, slug, data, skip);
902
1727
  if (!bad.length) return;
1728
+ // A repair offers only the value it holds, cleaned: never a stock value
1729
+ // the saved setting did not hold.
1730
+ for (const b of bad) {
1731
+ if (
1732
+ b.fix &&
1733
+ !allowedLine({
1734
+ offered: String(b.fix),
1735
+ typed: String(b.setting.value),
1736
+ thing: b.setting.thing,
1737
+ mode: b.setting.mode ?? '',
1738
+ })
1739
+ )
1740
+ delete b.fix;
1741
+ // A light and a dark color saved as one (`red / blue`) is that pair.
1742
+ const pair =
1743
+ !b.fix && isColorToken(b.setting.thing)
1744
+ ? colorPair(String(b.setting.value))
1745
+ : null;
1746
+ if (pair && !colorProblem(pair.light) && !colorProblem(pair.dark))
1747
+ b.fix = `light-dark(${pair.light}, ${pair.dark})`;
1748
+ }
903
1749
  const found = bad.length === 1 ? bad[0] : null;
904
1750
  // A clean value is offered only when set takes it, so the line works.
905
1751
  const takes = (/** @type {typeof found} */ b) => {
1752
+ if (!b?.fix) return true;
1753
+ // A value whose only fault was curly quotes around it: without them,
1754
+ // when set takes that (`“#e11d48”` is #e11d48).
1755
+ const bare = /^(["'])(.*)\1$/.exec(b.fix)?.[2];
1756
+ if (
1757
+ bare &&
1758
+ b.setting.source === 'token' &&
1759
+ !/font|content/.test(b.setting.thing)
1760
+ ) {
1761
+ const was = b.fix;
1762
+ b.fix = bare;
1763
+ if (takesOne(b)) return true;
1764
+ b.fix = was;
1765
+ }
1766
+ return takesOne(b);
1767
+ };
1768
+ const takesOne = (/** @type {typeof found} */ b) => {
906
1769
  if (!b?.fix) return true;
907
1770
  try {
908
1771
  checkSetting(
@@ -941,13 +1804,14 @@ function refuseStoredTokens(ctx, slug, data, skip) {
941
1804
  // A value to set only for a token whose stored value has the wrong
942
1805
  // type; any other thing `set` would refuse, or read as a dial.
943
1806
  ...(one &&
1807
+ one.fix &&
944
1808
  !one.scope &&
945
1809
  one.setting.source === 'token' &&
946
1810
  ctx.C.isToken(one.setting.thing)
947
1811
  ? [
948
1812
  // The value the check suggests for this value, else a stock
949
1813
  // one of the token's type.
950
- `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(one.fix ?? exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
1814
+ `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(String(one.fix))}${one.setting.mode ? ` --mode ${one.setting.mode}` : ''}`,
951
1815
  ]
952
1816
  : one && one.fix && one.setting.source === 'dial'
953
1817
  ? [
@@ -978,49 +1842,804 @@ export async function editorStoredRefusal(root, slug) {
978
1842
  }
979
1843
 
980
1844
  /**
981
- * For `compile`: the refusal of [light, dark] pairs on tokens that are not
982
- * colors in what the theme builds now, or null.
983
- * @param {string} root
1845
+ * The token values the theme's own source gives that `set` refuses (a
1846
+ * radius of `banana`, a color of `12px`), each with why and the line of
1847
+ * the file that sets it; checked with the very rules `set` uses.
1848
+ * @param {import('./_settings.mjs').Ctx} ctx
1849
+ * @param {string} slug
1850
+ * @param {import('./_settings.mjs').ThemeData} data
1851
+ * @returns {Promise<Array<{token: string, value: string, why: string, line: number | null, file?: string | null}>>}
1852
+ */
1853
+ async function ownTokenProblems(ctx, slug, data) {
1854
+ const {cwd} = ctx.project;
1855
+ /** @type {Array<{token: string, value: string, why: string, line: number | null, file?: string | null}>} */
1856
+ const out = [];
1857
+ const known = ctx.project.core.tokenDefaults;
1858
+ /**
1859
+ * @param {string} token
1860
+ * @param {string} value
1861
+ * @param {ReadonlySet<string>} [reads] custom properties the theme sets where the value is read
1862
+ * @returns {string | null}
1863
+ */
1864
+ const refused = (token, value, reads) => {
1865
+ try {
1866
+ checkSetting(
1867
+ ctx,
1868
+ slug,
1869
+ {...data, settings: []},
1870
+ token,
1871
+ value,
1872
+ {},
1873
+ false,
1874
+ {
1875
+ reads,
1876
+ },
1877
+ );
1878
+ return null;
1879
+ } catch (e) {
1880
+ if (!(e instanceof AstryxError)) throw e;
1881
+ return e.message.replace(/ Nothing was changed\.$/, '');
1882
+ }
1883
+ };
1884
+ /** The file an entry is in, as the project names it; null for the theme file. @param {{file?: string}} e */
1885
+ const fileOf = e => (e.file ? path.relative(cwd, e.file) : null);
1886
+ /** @param {{line: number | null, file?: string}} e */
1887
+ const atOf = e => ({line: e.line, file: fileOf(e)});
1888
+ // Every value is judged as the source gives it to defineTheme(), the
1889
+ // module evaluated as a build evaluates it (an import, an expression, a
1890
+ // spread or a computed key is its value), in every place a build writes
1891
+ // tokens from: the page's tokens, a part's blocks, onDark and onLight,
1892
+ // adaptation rules, and the typography. The source's syntax is read to
1893
+ // name the file and line that hold each value, and for what evaluation
1894
+ // erases: a `tokens` key given twice (JavaScript keeps the last) and a
1895
+ // [light, dark] pair with other than two values written in the file.
1896
+ const entries = ownTokenEntries(cwd, slug).filter(e => !e.overridden);
1897
+ const tokensLine = entries.find(e => e.kind === 'unresolved')?.line ?? null;
1898
+ /** Where a page token's value comes from. @param {string} token */
1899
+ const whereOf = token => {
1900
+ const e = entries.find(x => x.token === token && x.kind !== 'scoped');
1901
+ return e ? atOf(e) : {line: tokensLine, file: null};
1902
+ };
1903
+ /** Where a scoped token's value comes from. @param {string} scope @param {string} token */
1904
+ const whereIn = (scope, token) => {
1905
+ const e =
1906
+ entries.find(
1907
+ x => x.kind === 'scoped' && x.scope === scope && x.token === token,
1908
+ ) ??
1909
+ entries.find(x => x.kind === 'scope' && x.key === scope.split('.')[0]);
1910
+ return e ? atOf(e) : {line: null, file: null};
1911
+ };
1912
+ for (const e of entries) {
1913
+ if (e.kind === 'duplicate')
1914
+ out.push({
1915
+ token: 'tokens',
1916
+ value: '',
1917
+ why: `defineTheme is given tokens twice (lines ${(e.lines ?? []).join(' and ')}); the build keeps only the last, so the first does nothing: merge them into one`,
1918
+ ...atOf(e),
1919
+ });
1920
+ else if (e.notToken) {
1921
+ const key = e.key.replace(/^(["'`])(.*)\1$/, '$2');
1922
+ out.push({
1923
+ token: key,
1924
+ value: '',
1925
+ why: `${key} is no token: a token name starts with -- (such as --color-accent), and the build writes any other key as a CSS declaration on the theme's root, which styles every element; for one part, set it as a property on that part (\`${P} set ${slug} ${key} <value> --on <part>\`)`,
1926
+ ...atOf(e),
1927
+ });
1928
+ } else if (e.token?.startsWith('--_') && e.kind !== 'scoped')
1929
+ out.push({
1930
+ token: e.token,
1931
+ value: '',
1932
+ why: `${e.token} is a private variable (--_*), which Core sets itself, so the build refuses a theme that sets one: remove it`,
1933
+ ...atOf(e),
1934
+ });
1935
+ else if (
1936
+ e.kind === 'pair' &&
1937
+ e.token &&
1938
+ e.token in known &&
1939
+ (e.halves ?? []).length !== 2
1940
+ ) {
1941
+ const halves = e.halves ?? [];
1942
+ out.push({
1943
+ token: e.token,
1944
+ value: `[${halves.map(h => (h === undefined ? '…' : JSON.stringify(h))).join(', ')}]`,
1945
+ why: `a [light, dark] pair holds exactly two values in quotes, and this holds ${halves.length}; the build would write ${halves.length < 2 ? 'light-dark() with an undefined half' : 'the first two and drop the rest'}`,
1946
+ ...atOf(e),
1947
+ });
1948
+ }
1949
+ }
1950
+ // A private variable stops the build itself: nothing more to judge.
1951
+ if (out.some(b => b.token.startsWith('--_'))) return out;
1952
+ const loaded = await ownThemeInput(ctx, slug, data.like ?? null);
1953
+ const input = loaded?.input;
1954
+ if (!input || typeof input !== 'object') return out;
1955
+ const named = new Set(out.map(b => b.token));
1956
+ /**
1957
+ * Why a token's value is refused, or null. An undefined value is not set
1958
+ * (the build writes nothing for it). Any token, a design token or the
1959
+ * theme's own, takes text or a pair of two texts; any other value (null,
1960
+ * a boolean, a number, a BigInt, a symbol, an object) is no text. A design
1961
+ * token's text is checked as `set` checks it, and only a color takes a
1962
+ * pair.
1963
+ * @param {string} token
1964
+ * @param {unknown} value
1965
+ * @param {string} file the file named in a pair's refusal
1966
+ * @param {ReadonlySet<string>} reads custom properties the theme sets where the value is read
1967
+ * @returns {string | null}
1968
+ */
1969
+ const judge = (token, value, file, reads) => {
1970
+ if (value === undefined) return null;
1971
+ const custom = !(token in known);
1972
+ if (Array.isArray(value)) {
1973
+ if (value.length !== 2 || value.some(h => typeof h !== 'string'))
1974
+ return nonTextMessage(ctx, slug, [token, value]);
1975
+ if (custom) return null;
1976
+ if (!isColorToken(token)) {
1977
+ const unitless =
1978
+ ctx.C.typeOf(token) === 'size' &&
1979
+ value.every(h => /^\d*\.?\d+$/.test(String(h).trim()));
1980
+ return unitless
1981
+ ? nonTextMessage(ctx, slug, [token, value.map(Number), 'unit'])
1982
+ : `${file} gives ${token} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors; give it one value`;
1983
+ }
1984
+ for (const [i, h] of value.entries()) {
1985
+ const why = refused(token, String(h), reads);
1986
+ if (why) return `its ${i === 0 ? 'light' : 'dark'} half: ${why}`;
1987
+ }
1988
+ return null;
1989
+ }
1990
+ if (typeof value !== 'string')
1991
+ return nonTextMessage(
1992
+ ctx,
1993
+ slug,
1994
+ value && typeof value === 'object'
1995
+ ? [token, value, 'object']
1996
+ : [token, value],
1997
+ );
1998
+ if (custom) return null;
1999
+ if (/^light-dark\(/i.test(value) && !isColorToken(token))
2000
+ return `${file} gives ${token} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors; give it one value`;
2001
+ return refused(token, value, reads);
2002
+ };
2003
+ /**
2004
+ * Why a part's CSS property value is refused, or null: an undefined
2005
+ * value is not set; text is the property's own check; a number is
2006
+ * written as it is, so it stands only where the property takes a bare
2007
+ * number; any other value is no text.
2008
+ * @param {string} prop the property, as CSS names it
2009
+ * @param {unknown} value
2010
+ * @param {string} file
2011
+ * @returns {string | null}
2012
+ */
2013
+ const judgeProperty = (prop, value, file) => {
2014
+ if (value === undefined || typeof value === 'string') return null;
2015
+ if (typeof value === 'number')
2016
+ return matchValue(prop, String(value))
2017
+ ? null
2018
+ : `${file} gives ${prop} the number ${value}, which the build writes as it is (${prop}: ${value}) and ${prop} does not take, so the browser drops it; write it with a unit, such as '${value}px'`;
2019
+ return `${file} gives ${prop} the value ${describeValue(value)}, which is not text: a part's property is a CSS value in quotes, such as '4px'`;
2020
+ };
2021
+ /** @param {{line: number | null, file: string | null}} at */
2022
+ const fileName = at => at.file ?? `${slug}.theme.ts`;
2023
+ /** A value as the build writes it, when it is text. @param {unknown} v */
2024
+ const asWritten = v =>
2025
+ typeof v === 'string'
2026
+ ? v
2027
+ : Array.isArray(v) &&
2028
+ v.length === 2 &&
2029
+ v.every(h => typeof h === 'string')
2030
+ ? `light-dark(${v.join(', ')})`
2031
+ : '';
2032
+ /** The custom properties a block of tokens sets. @param {any} node */
2033
+ const varsIn = node =>
2034
+ node && typeof node === 'object'
2035
+ ? Object.keys(node).filter(k => k.startsWith('--'))
2036
+ : [];
2037
+ const pageVars = new Set(varsIn(input.tokens));
2038
+ // The page's own tokens, a design token or the theme's own.
2039
+ for (const [token, value] of Object.entries(input.tokens ?? {})) {
2040
+ if (named.has(token) || token.startsWith('--_')) continue;
2041
+ const at = whereOf(token);
2042
+ const why = judge(token, value, fileName(at), pageVars);
2043
+ if (why)
2044
+ out.push({
2045
+ token,
2046
+ value: asWritten(value),
2047
+ why,
2048
+ ...at,
2049
+ });
2050
+ }
2051
+ // The tokens and part properties each scope sets, wherever in it; a
2052
+ // var() there reads the page's custom properties and the block's own.
2053
+ /** @param {any} node @param {string[]} path @param {number} depth */
2054
+ const scoped = (node, path, depth) => {
2055
+ if (!node || typeof node !== 'object' || depth > 12) return;
2056
+ const reads = new Set([...pageVars, ...varsIn(node)]);
2057
+ const scope = path.join('.');
2058
+ for (const [k, v] of Object.entries(node)) {
2059
+ // In a scope the build writes an undefined value as the text
2060
+ // `undefined` (the page's tokens drop it), which no browser reads.
2061
+ if (
2062
+ v === undefined &&
2063
+ (k.startsWith('--') ||
2064
+ cssProperties().has(k.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)))
2065
+ ) {
2066
+ const at = whereIn(scope, k);
2067
+ out.push({
2068
+ token: `${scope} ${k}`,
2069
+ value: '',
2070
+ why: `${fileName(at)} gives ${k} the value undefined here, which the build writes as the text undefined in this rule, where the browser drops it: remove the key to leave it unset`,
2071
+ ...at,
2072
+ });
2073
+ continue;
2074
+ }
2075
+ if (k.startsWith('--')) {
2076
+ if (k.startsWith('--_')) continue;
2077
+ const at = whereIn(scope, k);
2078
+ const why = judge(k, v, fileName(at), reads);
2079
+ if (why)
2080
+ out.push({
2081
+ token: `${scope} ${k}`,
2082
+ value: asWritten(v),
2083
+ why,
2084
+ ...at,
2085
+ });
2086
+ continue;
2087
+ }
2088
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
2089
+ scoped(v, [...path, k], depth + 1);
2090
+ continue;
2091
+ }
2092
+ const prop = k.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
2093
+ if (!cssProperties().has(prop)) continue;
2094
+ const at = whereIn(scope, k);
2095
+ const why = judgeProperty(prop, v, fileName(at));
2096
+ if (why) out.push({token: `${scope} ${prop}`, value: '', why, ...at});
2097
+ }
2098
+ };
2099
+ for (const scope of ['components', 'onDark', 'onLight', 'adaptations'])
2100
+ scoped(input[scope], [scope], 0);
2101
+ // Typography: each field the source gives, as given, then each token
2102
+ // Core builds from it, named by the field that gives it.
2103
+ const typo = entries.filter(e => e.kind === 'typography');
2104
+ /** @type {Set<string>} */
2105
+ const flagged = new Set();
2106
+ /** @param {any} node @param {string[]} path */
2107
+ const fields = (node, path) => {
2108
+ if (!node || typeof node !== 'object') return;
2109
+ for (const [k, v] of Object.entries(node)) {
2110
+ const key = [...path, k].join('.');
2111
+ if (v === undefined) continue;
2112
+ if (v && typeof v === 'object' && !Array.isArray(v))
2113
+ fields(v, [...path, k]);
2114
+ else {
2115
+ const why = typographyProblem(key, v);
2116
+ if (!why) continue;
2117
+ const e = typo.find(x => x.key === key) ?? typo[0];
2118
+ flagged.add(key.split('.')[0]);
2119
+ out.push({
2120
+ token: `typography.${key}`,
2121
+ value: typeof v === 'string' ? v : '',
2122
+ why,
2123
+ ...(e ? atOf(e) : {line: null, file: null}),
2124
+ });
2125
+ }
2126
+ }
2127
+ };
2128
+ fields(input.typography, []);
2129
+ const scale = input.typography?.scale;
2130
+ if (
2131
+ scale &&
2132
+ typeof scale === 'object' &&
2133
+ scale.base === undefined &&
2134
+ !flagged.has('scale')
2135
+ ) {
2136
+ flagged.add('scale');
2137
+ const e = typo.find(x => x.key.startsWith('scale.')) ?? typo[0];
2138
+ out.push({
2139
+ token: 'typography.scale',
2140
+ value: '',
2141
+ why: 'the type scale is given no base, and Core reads the sizes from the base and the ratio together: add the body size in pixels, such as scale: {base: 16, ratio: …}',
2142
+ ...(e ? atOf(e) : {line: null, file: null}),
2143
+ });
2144
+ }
2145
+ const tokens = loaded?.theme?.tokens;
2146
+ if (input.typography && tokens && typeof tokens === 'object') {
2147
+ /** @param {string} role */
2148
+ const roleEntry = role =>
2149
+ typo.find(e => e.key.startsWith(`${role}.`)) ??
2150
+ (role === 'heading'
2151
+ ? typo.find(e => e.key.startsWith('body.'))
2152
+ : undefined);
2153
+ /** The typography field that gives a token Core builds. @param {string} token */
2154
+ const typographyOf = token => {
2155
+ const family = /^--font-family-([a-z]+)$/.exec(token)?.[1];
2156
+ if (family) return roleEntry(family) ?? null;
2157
+ if (!/^--(font-size|text|heading)-/.test(token)) return null;
2158
+ if (/-weight$/.test(token))
2159
+ return (
2160
+ roleEntry(
2161
+ /heading/.test(token)
2162
+ ? 'heading'
2163
+ : /code/.test(token)
2164
+ ? 'code'
2165
+ : 'body',
2166
+ ) ??
2167
+ typo.find(e => /weight/.test(e.key)) ??
2168
+ typo[0] ??
2169
+ null
2170
+ );
2171
+ return typo.find(e => e.key.startsWith('scale.')) ?? typo[0] ?? null;
2172
+ };
2173
+ /** @type {Set<any>} */
2174
+ const reported = new Set();
2175
+ for (const [token, value] of Object.entries(tokens)) {
2176
+ if (!(token in known) || token in (input.tokens ?? {})) continue;
2177
+ const owner = typographyOf(token);
2178
+ if (!owner || reported.has(owner) || flagged.has(owner.key.split('.')[0]))
2179
+ continue;
2180
+ // A token Core leaves as the base theme writes it is the base's.
2181
+ if (loaded?.base.get(token) === value) continue;
2182
+ const at = atOf(owner);
2183
+ const why = judge(token, value, fileName(at), pageVars);
2184
+ if (why) {
2185
+ reported.add(owner);
2186
+ out.push({
2187
+ token: `typography.${owner.key} (builds ${token})`,
2188
+ value: asWritten(value),
2189
+ why,
2190
+ ...at,
2191
+ });
2192
+ }
2193
+ }
2194
+ }
2195
+ return out;
2196
+ }
2197
+
2198
+ /**
2199
+ * What is wrong with one typography field of a theme's own source, or
2200
+ * null: a family is one family name without quotes (Core quotes it whole)
2201
+ * and with nothing CSS would read as the end of the value; the scale's
2202
+ * ratio is above 1 and at most 4, its base a positive number of pixels.
2203
+ * @param {string} key the dotted field (`body.family`, `scale.ratio`)
2204
+ * @param {unknown} value
2205
+ * @returns {string | null}
2206
+ */
2207
+ function typographyProblem(key, value) {
2208
+ const field = key.split('.').pop();
2209
+ // A weight is a CSS value Core writes as it is: text, never a number.
2210
+ if (
2211
+ (field === 'weight' || key.split('.').includes('weights')) &&
2212
+ typeof value !== 'string'
2213
+ )
2214
+ return `a typography weight is a CSS value in quotes, which Core writes as it is; ${JSON.stringify(value)} is not text: write ${typeof value === 'number' ? `'${value}'` : "'600'"} (or a weight token, such as 'var(--font-weight-bold)')`;
2215
+ if (field === 'family') {
2216
+ if (typeof value !== 'string')
2217
+ return 'a typography family is a family name in quotes, such as "Inter"';
2218
+ const v = value.trim();
2219
+ if (/[;{}<>]/.test(v))
2220
+ return `"${v}" holds a ; { } < or >, so the CSS writer drops the whole declaration; give the family name alone, such as "Inter"`;
2221
+ const quoted = /^(["'])(.*)\1$/.exec(v);
2222
+ if (quoted)
2223
+ return `the family is written in quotes, and Core adds its own, so it builds ${JSON.stringify(`"${v}"`)}, a name no font has; write it without them: family: '${quoted[2]}'`;
2224
+ // Core quotes a family with a space whole, so a list here is one
2225
+ // family by that whole name, which exists nowhere.
2226
+ if (v.includes(','))
2227
+ return `a typography family is one family name, which Core quotes whole ("${v}" is one family that exists nowhere); give the first as family and the rest as fallbacks, such as family: '${v
2228
+ .split(',')[0]
2229
+ .trim()
2230
+ .replace(
2231
+ /^["']|["']$/g,
2232
+ '',
2233
+ )}', fallbacks: '${v.split(',').slice(1).join(',').trim()}'`;
2234
+ if (!v || /^[-+]?\d/.test(v) || /^(inherit|initial|unset|revert)$/i.test(v))
2235
+ return `"${v}" is no font family name; give one such as "Inter"`;
2236
+ return null;
2237
+ }
2238
+ if (field === 'ratio') {
2239
+ const n = Number(value);
2240
+ if (!Number.isFinite(n) || n <= 1 || n > 4)
2241
+ return `the type scale's ratio is how much each size grows over the last, a number above 1 and at most 4 (such as 1.2); ${JSON.stringify(value)} makes ${n <= 0 ? 'sizes that are not numbers' : n <= 1 ? 'every size the same or smaller' : 'sizes no page can use'}`;
2242
+ return null;
2243
+ }
2244
+ if (field === 'base') {
2245
+ const n = Number(value);
2246
+ if (!Number.isFinite(n) || n <= 0) {
2247
+ // A size with a unit builds NaNrem: the number of pixels it means.
2248
+ const m = /^\s*([0-9.]+)\s*(px|rem|em)\s*$/i.exec(String(value));
2249
+ const px = m ? Number(m[1]) * (/^r?em$/i.test(m[2]) ? 16 : 1) : null;
2250
+ return `the type scale's base is the body size, a positive number of pixels${px ? `, so ${JSON.stringify(value)} is base: ${px}` : ' (such as 16)'}; ${JSON.stringify(value)} builds sizes no page can use${m ? ' (NaNrem)' : ''}`;
2251
+ }
2252
+ return null;
2253
+ }
2254
+ return null;
2255
+ }
2256
+
2257
+ /**
2258
+ * Refuse a theme whose own source gives a token a value `set` refuses: the
2259
+ * build would write it as it is (a browser drops it), so it is named, with
2260
+ * the line of the file, before anything is written.
2261
+ * @param {import('./_settings.mjs').Ctx} ctx
2262
+ * @param {string} slug
2263
+ * @param {import('./_settings.mjs').ThemeData} data
2264
+ */
2265
+ async function refuseOwnTokenValues(ctx, slug, data) {
2266
+ const err = await ownTokenRefusal(ctx, slug, data);
2267
+ if (err) throw err;
2268
+ }
2269
+ setOwnTokenCheck(refuseOwnTokenValues);
2270
+
2271
+ /**
2272
+ * The refusal for own-source token values `set` refuses, or null.
2273
+ * @param {import('./_settings.mjs').Ctx} ctx
2274
+ * @param {string} slug
2275
+ * @param {import('./_settings.mjs').ThemeData} data
2276
+ * @returns {Promise<AstryxError | null>}
2277
+ */
2278
+ async function ownTokenRefusal(ctx, slug, data) {
2279
+ const bad = await ownTokenProblems(ctx, slug, data);
2280
+ if (!bad.length) return null;
2281
+ const own = `themes/${slug}/${slug}.theme.ts`;
2282
+ const file = bad[0].file ?? own;
2283
+ return new AstryxError(
2284
+ `${own} gives ${bad.length === 1 ? 'a token a value' : `${bad.length} tokens values`} the editor refuses, which the build would write as it is: ${bad
2285
+ .slice(0, 3)
2286
+ .map(
2287
+ b =>
2288
+ `${b.token}${b.value ? `: "${b.value}"` : ''}${b.file ? ` (in ${b.file}${b.line ? `, line ${b.line}` : ''})` : b.line ? ` (line ${b.line})` : ''}: ${b.why.replace(/\.+$/, '')}`,
2289
+ )
2290
+ .join(
2291
+ '; ',
2292
+ )}${bad.length > 3 ? `; and ${bad.length - 3} more` : ''}. Change it in ${file}. Nothing was changed.`,
2293
+ [
2294
+ bad[0].line
2295
+ ? {
2296
+ name: `sed -n ${bad[0].line}p ${quoteCommandArgument(file)}`,
2297
+ reason: 'see the line that sets it',
2298
+ }
2299
+ : {
2300
+ name: `grep -n -- ${quoteCommandArgument(bad[0].token)} ${quoteCommandArgument(file)}`,
2301
+ reason: 'see the line',
2302
+ },
2303
+ ],
2304
+ ERROR_CODES.ERR_THEME_INVALID,
2305
+ );
2306
+ }
2307
+
2308
+ /**
2309
+ * The refusal `compile` gives an editor theme whose own source gives a
2310
+ * token a value `set` refuses, or null.
2311
+ * @param {string} root
2312
+ * @param {string} slug
2313
+ * @returns {Promise<AstryxError | null>}
2314
+ */
2315
+ export async function editorOwnTokenRefusal(root, slug) {
2316
+ const ctx = await context(root);
2317
+ /** @type {import('./_settings.mjs').ThemeData} */
2318
+ let data;
2319
+ try {
2320
+ data = loadTheme(root, slug);
2321
+ } catch {
2322
+ return null;
2323
+ }
2324
+ return ownTokenRefusal(ctx, slug, data);
2325
+ }
2326
+
2327
+ /**
2328
+ * A note for type scale steps that land outside 9 to 200 pixels.
2329
+ * @param {Record<string, string>} res resolved light tokens
2330
+ * @returns {string[]}
2331
+ */
2332
+ function extremeSteps(res) {
2333
+ const out = Object.entries(res)
2334
+ .filter(([k]) => /^--font-size-/.test(k))
2335
+ .map(([k, v]) => {
2336
+ const n = Number.parseFloat(v);
2337
+ return /** @type {[string, number]} */ ([k, /rem$/.test(v) ? n * 16 : n]);
2338
+ })
2339
+ .filter(([, px]) => Number.isFinite(px) && (px < 9 || px > 200))
2340
+ .map(([k, px]) => `${k} ${Math.round(px)}px`);
2341
+ return out.length
2342
+ ? [
2343
+ `some scale steps are outside reading sizes (9 to 200px): ${out.slice(0, 4).join(', ')}`,
2344
+ ]
2345
+ : [];
2346
+ }
2347
+
2348
+ export {carriesTyped, offersTyped} from './_normal.mjs';
2349
+
2350
+ /**
2351
+ * An object of settings written as JSON, with single quotes, or as its
2352
+ * entries with no braces (`"accent": "#e11d48", "corners": "pill"`).
2353
+ * Throws when it is none of these.
2354
+ * @param {string} text
2355
+ * @returns {any}
2356
+ */
2357
+ function looseObject(text) {
2358
+ const t = text.trim();
2359
+ const braced = t.startsWith('{') ? t : `{${t}}`;
2360
+ try {
2361
+ return JSON.parse(braced);
2362
+ } catch {
2363
+ return JSON.parse(
2364
+ braced.replace(/'((?:[^'\\]|\\.)*)'/g, (_, x) =>
2365
+ JSON.stringify(x.replace(/\\'/g, "'")),
2366
+ ),
2367
+ );
2368
+ }
2369
+ }
2370
+
2371
+ /**
2372
+ * A refusal with each line that sets the typed setting again kept only
2373
+ * when it carries the value typed; with none left, `how` for the setting.
2374
+ * Another setting's line, an undo or a look stays.
2375
+ * @param {any} e
2376
+ * @param {'set' | 'undo'} sub
2377
+ * @param {string} slug
2378
+ * @param {string} thing
2379
+ * @param {unknown} typed
2380
+ * @param {import('./_settings.mjs').ThemeData} [data] the theme, whose saved
2381
+ * values a keep line may carry
2382
+ */
2383
+ function carryTyped(e, sub, slug, thing, typed, data, cwd = process.cwd()) {
2384
+ if (
2385
+ sub !== 'set' ||
2386
+ !(e instanceof AstryxError) ||
2387
+ // A refusal about what the settings file holds: its lines carry the
2388
+ // saved value (checked where they are made), not the typed one.
2389
+ /** @type {any} */ (e).aboutSaved ||
2390
+ typeof typed !== 'string' ||
2391
+ !e.suggestions?.length
2392
+ )
2393
+ return e;
2394
+ const head = new RegExp(
2395
+ `^.* set \\S+ (?:'([^']+)'|(\\S+)) (?:'((?:[^']|'\\\\'')*)'|(\\S+))`,
2396
+ );
2397
+ // Every set line, of this setting or another (a dial's other name, a
2398
+ // label, a theme-wide equivalent), offers a value only through the gate's
2399
+ // declared sources (readsTyped): never a stock, reset or nearest value.
2400
+ // A line that carries only part of the value is offered only when the
2401
+ // refusal's lines together carry all of it (a family and its weight).
2402
+ // With no value typed, the thing held it (`accent: red`).
2403
+ const typedText = typed.trim() ? typed : String(thing);
2404
+ /** @type {Map<string, string[]>} */
2405
+ const saved = new Map();
2406
+ for (const x of data?.settings ?? [])
2407
+ saved.set(x.thing, [...(saved.get(x.thing) ?? []), String(x.value ?? '')]);
2408
+ // The base the theme was built on is a saved value of its base too (the
2409
+ // module's header holds it when the file's base is damaged).
2410
+ const builtOn = builtOnBase(cwd, slug);
2411
+ saved.set(
2412
+ 'base',
2413
+ /** @type {string[]} */ (
2414
+ [data?.like, builtOn].filter(b => typeof b === 'string' && b !== '')
2415
+ ),
2416
+ );
2417
+ if (data?.mode) saved.set('mode', [data.mode]);
2418
+ const reads = e.suggestions.map(x => {
2419
+ const m = head.exec(x.name);
2420
+ if (!m) return /** @type {true | number[] | false} */ (true);
2421
+ return readsTyped({
2422
+ offered: m[3] ?? m[4],
2423
+ typed: typedText,
2424
+ thing: (m[1] ?? m[2]).replace(/^'(.*)'$/, '$1'),
2425
+ typedThing: String(thing),
2426
+ saved,
2427
+ mode: / --mode (light|dark)\b/.exec(x.name)?.[1] ?? '',
2428
+ });
2429
+ });
2430
+ const covered = coversTyped(reads, typedText, String(thing));
2431
+ /** @type {Set<string>} */
2432
+ const dropped = new Set();
2433
+ const lines = e.suggestions.filter((x, i) => {
2434
+ const read = reads[i];
2435
+ if (read === true || (read && typeof read === 'object' && covered))
2436
+ return true;
2437
+ const m = head.exec(x.name);
2438
+ if (m) dropped.add(String(m[3] ?? m[4]).toLowerCase());
2439
+ return false;
2440
+ });
2441
+ // A value named as a did-you-mean goes with its line.
2442
+ const kept = lines.filter(
2443
+ x => !(x.reason === 'did you mean' && dropped.has(x.name.toLowerCase())),
2444
+ );
2445
+ // A refusal always names a command that works: with no set, undo, new or
2446
+ // how line left, how for the setting.
2447
+ const runnable = kept.some(
2448
+ x => x.reason !== 'did you mean' && !/ --help$/.test(x.name),
2449
+ );
2450
+ if (kept.length === e.suggestions.length && runnable) return e;
2451
+ e.suggestions = runnable
2452
+ ? kept
2453
+ : [
2454
+ ...kept.filter(x => !/ --help$/.test(x.name)),
2455
+ {
2456
+ name: `${P} how ${quoteCommandArgument(String(thing))}`,
2457
+ reason: 'what it takes',
2458
+ },
2459
+ ];
2460
+ return e;
2461
+ }
2462
+
2463
+ /**
2464
+ * A theme's settings file as written, for the values a keep line may carry
2465
+ * when the theme does not load (a damaged entry); null when it cannot be
2466
+ * read.
2467
+ * @param {string} cwd
2468
+ * @param {string} slug
2469
+ * @returns {import('./_settings.mjs').ThemeData | undefined}
2470
+ */
2471
+ function savedAsWritten(cwd, slug) {
2472
+ try {
2473
+ const data = settingsJson(
2474
+ fs.readFileSync(themeFiles(cwd, slug).settings, 'utf8'),
2475
+ );
2476
+ return entriesReadable(data) ? data : undefined;
2477
+ } catch {
2478
+ return undefined;
2479
+ }
2480
+ }
2481
+
2482
+ /**
2483
+ * A refusal of the settings file (a setting listed twice, a damaged
2484
+ * entry) with every `set` it suggests checked as set checks it, against
2485
+ * the file as written: a keep line whose value set refuses is dropped.
2486
+ * @param {unknown} e
2487
+ * @param {string} cwd
2488
+ * @param {string} slug
2489
+ * @returns {Promise<unknown>}
2490
+ */
2491
+ async function vetLoadRefusal(e, cwd, slug) {
2492
+ if (!(e instanceof AstryxError) || e.code !== E.ERR_THEME_INVALID) return e;
2493
+ const data = savedAsWritten(cwd, slug);
2494
+ if (!data) return e;
2495
+ try {
2496
+ const ctx = /** @type {import('./_settings.mjs').Ctx} */ (
2497
+ await context(cwd)
2498
+ );
2499
+ ctx.base = await baseResolved(ctx.project, data.like ?? undefined);
2500
+ return vetSuggestions(e, ctx, slug, data);
2501
+ } catch {
2502
+ return e;
2503
+ }
2504
+ }
2505
+
2506
+ /**
2507
+ * The lines of a repair that work: each run through set's own check (in
2508
+ * memory) and offered only when set takes it as offered and its value
2509
+ * passes the allowlist of exact readings of what was typed. A line left
2510
+ * out that names its own setting points to how for it; with no line left,
2511
+ * how for the thing (or the command's help when there is no one thing).
2512
+ * @param {'set' | 'undo'} sub
2513
+ * @param {string} slug
2514
+ * @param {Array<string | [string, string] | [string, string, string]>} lines
2515
+ * each line, or each line with the typed text it carries (and, for an
2516
+ * entry of a pasted object, its setting)
2517
+ * @param {string} cwd
2518
+ * @param {string} typed
2519
+ * @param {string} thing
2520
+ * @returns {Promise<string[]>}
2521
+ */
2522
+ async function workingLines(sub, slug, lines, cwd, typed, thing) {
2523
+ /** @type {string[]} */
2524
+ const out = [];
2525
+ for (const item of lines) {
2526
+ const [line, own, subject] = Array.isArray(item)
2527
+ ? item
2528
+ : [item, typed, undefined];
2529
+ // A line left out points to how for its own setting, when it names one
2530
+ // (an entry of a pasted object).
2531
+ const left = () => {
2532
+ if (subject) out.push(`${P} how ${quoteCommandArgument(subject)}`);
2533
+ };
2534
+ // The line as set takes it (a repair set offers for it folded in).
2535
+ const followed = await followChangeLine(sub, slug, line, cwd);
2536
+ if (followed.why) {
2537
+ left();
2538
+ continue;
2539
+ }
2540
+ const read = readSetLine(followed.line, slug);
2541
+ if (
2542
+ sub === 'set' &&
2543
+ read &&
2544
+ !allowedLine({
2545
+ offered: read.value,
2546
+ typed: own,
2547
+ thing: read.thing,
2548
+ mode: String(read.flags?.mode ?? ''),
2549
+ })
2550
+ ) {
2551
+ left();
2552
+ continue;
2553
+ }
2554
+ out.push(followed.line);
2555
+ }
2556
+ return out.length
2557
+ ? [...new Set(out)]
2558
+ : [
2559
+ thing
2560
+ ? `${P} how ${quoteCommandArgument(thing)}`
2561
+ : `${P} ${sub} --help`,
2562
+ ];
2563
+ }
2564
+
2565
+ /**
2566
+ * A `set` or `undo` line for the theme a path or other letters named, run
2567
+ * through that command's own check (in memory, nothing written). Each
2568
+ * repair a refusal of it offers is folded into the one line, so the line
2569
+ * runs as offered; `why` names what is still refused when no repair is
2570
+ * offered.
2571
+ * @param {'set' | 'undo'} sub
984
2572
  * @param {string} slug
985
- * @returns {Promise<import('../error.mjs').AstryxError | null>}
2573
+ * @param {string} line
2574
+ * @param {string} cwd
2575
+ * @param {Partial<import('./_settings.mjs').Setting>} [skip] a saved entry
2576
+ * the line replaces, whose value is not checked when the theme is read
2577
+ * @returns {Promise<{line: string, why: string | null, next?: import("../../foundation/response/base").Suggestion[]}>}
986
2578
  */
987
- export async function editorPairRefusal(root, slug) {
988
- const ctx = await context(root);
989
- const names = await builtPairs(ctx, slug);
990
- if (!names.length) return null;
991
- return new AstryxError(
992
- ownPairMessage(slug, names),
993
- [
994
- {
995
- name: `grep -n -- ${quoteCommandArgument(names[0])} ${quoteCommandArgument(`themes/${slug}/${slug}.theme.ts`)}`,
996
- reason: 'see where the file sets it',
997
- },
998
- ],
999
- ERROR_CODES.ERR_THEME_INVALID,
2579
+ async function followChangeLine(sub, slug, line, cwd, skip) {
2580
+ /** @type {import('./_settings.mjs').ThemeData} */
2581
+ let data;
2582
+ /** @type {import('./_settings.mjs').Ctx} */
2583
+ let ctx;
2584
+ try {
2585
+ data = loadTheme(cwd, slug, skip);
2586
+ ctx = /** @type {import('./_settings.mjs').Ctx} */ (await context(cwd));
2587
+ ctx.base = await baseResolved(ctx.project, data.like);
2588
+ } catch {
2589
+ return {line, why: null};
2590
+ }
2591
+ const prefix = `${P} ${sub} ${slug} `;
2592
+ return followLine(
2593
+ line,
2594
+ now => {
2595
+ const read = readSetLine(
2596
+ sub === 'undo' ? now.replace(`${P} undo `, `${P} set `) : now,
2597
+ slug,
2598
+ );
2599
+ if (!read) return null;
2600
+ try {
2601
+ const s = checkSetting(
2602
+ ctx,
2603
+ slug,
2604
+ structuredClone(data),
2605
+ read.thing,
2606
+ read.value,
2607
+ read.flags,
2608
+ sub === 'undo',
2609
+ );
2610
+ return sub === 'undo' && !data.settings.some(x => keyOf(x) === keyOf(s))
2611
+ ? new AstryxError(
2612
+ `${slug} does not set ${describe({...s, value: '?'}).replace(' = ?', '')}`,
2613
+ [{name: `${P} show ${slug}`, reason: 'see what it sets'}],
2614
+ )
2615
+ : null;
2616
+ } catch (e) {
2617
+ if (e instanceof AstryxError) return e;
2618
+ throw e;
2619
+ }
2620
+ },
2621
+ name => {
2622
+ if (!name.startsWith(prefix)) return false;
2623
+ // A repair passes the one input gate: it adds no scope that was not
2624
+ // typed (never a stock part), and a value in place of the one typed
2625
+ // is an exact reading of it.
2626
+ const toSet = (/** @type {string} */ l) =>
2627
+ sub === 'undo' ? l.replace(`${P} undo `, `${P} set `) : l;
2628
+ const was = readSetLine(toSet(line), slug);
2629
+ const next = readSetLine(toSet(name), slug);
2630
+ if (!was || !next) return true;
2631
+ const scopes = /** @type {const} */ (['on', 'when', 'state', 'mode']);
2632
+ if (scopes.some(k => next.flags[k] != null && was.flags[k] == null))
2633
+ return false;
2634
+ return (
2635
+ sub === 'undo' ||
2636
+ next.value === was.value ||
2637
+ allowedLine({offered: next.value, typed: was.value, thing: next.thing})
2638
+ );
2639
+ },
1000
2640
  );
1001
2641
  }
1002
2642
 
1003
- /**
1004
- * A note for type scale steps that land outside 9 to 200 pixels.
1005
- * @param {Record<string, string>} res resolved light tokens
1006
- * @returns {string[]}
1007
- */
1008
- function extremeSteps(res) {
1009
- const out = Object.entries(res)
1010
- .filter(([k]) => /^--font-size-/.test(k))
1011
- .map(([k, v]) => {
1012
- const n = Number.parseFloat(v);
1013
- return /** @type {[string, number]} */ ([k, /rem$/.test(v) ? n * 16 : n]);
1014
- })
1015
- .filter(([, px]) => Number.isFinite(px) && (px < 9 || px > 200))
1016
- .map(([k, px]) => `${k} ${Math.round(px)}px`);
1017
- return out.length
1018
- ? [
1019
- `some scale steps are outside reading sizes (9 to 200px): ${out.slice(0, 4).join(', ')}`,
1020
- ]
1021
- : [];
1022
- }
1023
-
1024
2643
  /**
1025
2644
  * @param {'set' | 'undo'} sub
1026
2645
  * @param {string} slug
@@ -1033,21 +2652,201 @@ async function change(sub, slug, thing, value, options) {
1033
2652
  // As typed: an undo of a saved entry written in a form the cleanup below
1034
2653
  // repairs (`Corners`, `var(--radius-page)`) removes that exact entry.
1035
2654
  const typedThing = thing;
2655
+ const typedValue = value;
2656
+ // An object of several settings pasted as one (JSON, single quotes, or
2657
+ // its entries with no braces, split at the first colon on the way): one
2658
+ // set line each.
2659
+ const objectText =
2660
+ typeof thing !== 'string'
2661
+ ? null
2662
+ : value == null || value === ''
2663
+ ? /^\s*\{[\s\S]*\}\s*$/.test(thing)
2664
+ ? thing
2665
+ : null
2666
+ : /^\s*\{?\s*["']/.test(thing) && /["']\s*:/.test(String(value))
2667
+ ? `${thing}:${value}`
2668
+ : null;
2669
+ // A pasted object of one entry is that entry, as read below: its repair
2670
+ // carries the entry's value, and how names its setting.
2671
+ let oneEntry = false;
2672
+ if (objectText != null) {
2673
+ /** @type {any} */
2674
+ let obj = null;
2675
+ try {
2676
+ obj = looseObject(objectText);
2677
+ } catch {
2678
+ // Not an object: read as typed.
2679
+ }
2680
+ oneEntry = Boolean(
2681
+ obj && typeof obj === 'object' && Object.keys(obj).length === 1,
2682
+ );
2683
+ if (obj && typeof obj === 'object' && Object.keys(obj).length > 1)
2684
+ refuse(
2685
+ E.ERR_INVALID_ARGUMENT,
2686
+ `This holds ${Object.keys(obj).length} settings; ${sub} changes one at a time.`,
2687
+ {
2688
+ // Each entry as its own line, a nested value (`{"$value": …}`, a
2689
+ // light and dark pair) written back as typed; each line checked,
2690
+ // and one set refuses is left out.
2691
+ run: await workingLines(
2692
+ sub,
2693
+ slug,
2694
+ Object.entries(obj)
2695
+ .slice(0, 6)
2696
+ .map(([k, x]) => {
2697
+ const entry =
2698
+ x != null && typeof x === 'object'
2699
+ ? JSON.stringify(x)
2700
+ : String(x);
2701
+ const read = String(normalizeEntry(k, entry).value ?? '');
2702
+ // Each line with the entry it carries, as typed.
2703
+ return /** @type {[string, string, string]} */ ([
2704
+ `${P} ${sub} ${slug} ${quoteCommandArgument(k)}${sub === 'set' ? ` ${quoteCommandArgument(read)}` : ''}`,
2705
+ read,
2706
+ k,
2707
+ ]);
2708
+ }),
2709
+ options.cwd ?? process.cwd(),
2710
+ objectText,
2711
+ // No one setting: each entry left out points to how for its
2712
+ // own (above), else set's help.
2713
+ '',
2714
+ ),
2715
+ },
2716
+ );
2717
+ }
2718
+ // A flag typed inside the value (`'red --mode dark'`, `'4px --state
2719
+ // hover'`, `'pill --on button'`): the same command with the flag lifted
2720
+ // out, never the value alone, which would change another scope.
2721
+ if (typeof value === 'string' && /\s--(mode|state|on|when)\b/.test(value)) {
2722
+ /** @type {Record<string, string>} */
2723
+ const lifted = {};
2724
+ // The rest is cleaned as any value is (a trailing `;`, `!important`,
2725
+ // a comment).
2726
+ const bare = withoutCopyDebris(
2727
+ value.replace(
2728
+ /\s+--(mode|state|on|when)(?:\s*=\s*|\s+)("[^"]*"|'[^']*'|\S+)/g,
2729
+ (_, f, x) => {
2730
+ lifted[f] = x.replace(/^(["'])(.*)\1$/, '$2');
2731
+ return '';
2732
+ },
2733
+ ),
2734
+ );
2735
+ if (bare && Object.keys(lifted).length) {
2736
+ const opts = /** @type {Record<string, unknown>} */ ({
2737
+ ...options,
2738
+ ...lifted,
2739
+ });
2740
+ const flagText = ['on', 'when', 'state', 'mode']
2741
+ .filter(f => opts[f])
2742
+ .map(f => ` --${f} ${quoteCommandArgument(String(opts[f]))}`)
2743
+ .join('');
2744
+ refuse(
2745
+ E.ERR_INVALID_ARGUMENT,
2746
+ `"${value}" holds ${Object.keys(lifted)
2747
+ .map(f => `--${f}`)
2748
+ .join(' and ')} inside the value; a flag goes outside the quotes.`,
2749
+ {
2750
+ // The line is checked as set checks it; one set refuses is left
2751
+ // out, and how is named instead.
2752
+ run: await workingLines(
2753
+ sub,
2754
+ slug,
2755
+ [
2756
+ `${P} ${sub} ${slug} ${quoteCommandArgument(String(thing))}${sub === 'set' ? ` ${quoteCommandArgument(bare)}` : ''}${flagText}${options.only ? ' --only' : ''}`,
2757
+ ],
2758
+ options.cwd ?? process.cwd(),
2759
+ value,
2760
+ String(thing),
2761
+ ),
2762
+ },
2763
+ );
2764
+ }
2765
+ }
1036
2766
  // How it was typed, put right before anything reads it (a pasted
1037
2767
  // declaration, a dash, a var(), invisible spaces).
2768
+ /** @type {string | undefined} */
2769
+ let dropped;
1038
2770
  if (typeof thing === 'string') {
1039
2771
  const entry = normalizeEntry(thing, value);
1040
2772
  thing = entry.thing;
1041
2773
  value = entry.value;
2774
+ dropped = entry.dropped;
1042
2775
  }
1043
2776
  /** @type {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} */
1044
2777
  const seen = {};
1045
2778
  try {
1046
- return await changeOnce(sub, slug, thing, value, options, seen, typedThing);
2779
+ const r = await changeOnce(
2780
+ sub,
2781
+ slug,
2782
+ thing,
2783
+ value,
2784
+ options,
2785
+ seen,
2786
+ typedThing,
2787
+ );
2788
+ // A second declaration pasted after the first is not set: said, with
2789
+ // its own set line.
2790
+ if (dropped && sub === 'set') {
2791
+ const m = /^([^:]+):\s*(.*?);?\s*$/.exec(dropped);
2792
+ const flags = [
2793
+ ...(options.on ? [`--on ${options.on}`] : []),
2794
+ ...(options.when ? [`--when ${options.when}`] : []),
2795
+ ...(options.state ? [`--state ${options.state}`] : []),
2796
+ ].join(' ');
2797
+ // Its line goes through the one gate as a repair does: checked as set
2798
+ // checks it (a repair set offers for it folded in) and carrying what
2799
+ // was pasted; else no line is named.
2800
+ const [line] = m
2801
+ ? await workingLines(
2802
+ 'set',
2803
+ slug,
2804
+ [
2805
+ `${P} set ${slug} ${quoteCommandArgument(m[1].trim())} ${quoteCommandArgument(m[2].trim())}${flags ? ` ${flags}` : ''}`,
2806
+ ],
2807
+ options.cwd ?? process.cwd(),
2808
+ m[2].trim(),
2809
+ m[1].trim(),
2810
+ )
2811
+ : [];
2812
+ /** @type {any} */ (r.data).notes = [
2813
+ ...(r.data.notes ?? []),
2814
+ `the pasted text also held "${dropped}", which this did not set${line && / set /.test(line) ? `: ${line} sets it` : ''}`,
2815
+ ];
2816
+ }
2817
+ // A mode or base entry in the settings list does nothing: said after
2818
+ // every change, with the undo that removes it.
2819
+ if (seen.ctx && r.data.theme) {
2820
+ /** @type {import('./_settings.mjs').ThemeData | null} */
2821
+ let now = null;
2822
+ try {
2823
+ now = loadTheme(seen.ctx.project.cwd, r.data.theme);
2824
+ } catch {
2825
+ now = null;
2826
+ }
2827
+ const left = now ? misplacedNotes(r.data.theme, now) : [];
2828
+ if (left.length)
2829
+ /** @type {any} */ (r.data).notes = [...left, ...(r.data.notes ?? [])];
2830
+ }
2831
+ return r;
1047
2832
  } catch (e) {
1048
- // A theme name one letter off an existing theme: the same command with
1049
- // that name comes first, before making a theme of the typo.
1050
- if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME) {
2833
+ // A theme name one letter off an existing theme, or typed in other
2834
+ // letters or as a path (T, ./t, themes/t): the same command with that
2835
+ // name comes first, never a bare look at the theme that drops the change.
2836
+ const named =
2837
+ e instanceof AstryxError &&
2838
+ (e.code === E.ERR_UNKNOWN_THEME ||
2839
+ (e.code === E.ERR_INVALID_ARGUMENT &&
2840
+ (e.suggestions ?? []).some(
2841
+ x =>
2842
+ x.reason === 'did you mean' &&
2843
+ slugOk(x.name) &&
2844
+ x.name !== slug &&
2845
+ fs.existsSync(
2846
+ themeFiles(options.cwd ?? process.cwd(), x.name).settings,
2847
+ ),
2848
+ )));
2849
+ if (named) {
1051
2850
  const near = (e.suggestions ?? []).find(x => x.reason === 'did you mean');
1052
2851
  if (near && slugOk(near.name)) {
1053
2852
  const flags = [
@@ -1062,18 +2861,41 @@ async function change(sub, slug, thing, value, options) {
1062
2861
  .map(w =>
1063
2862
  String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
1064
2863
  );
2864
+ const followed = await followChangeLine(
2865
+ sub,
2866
+ near.name,
2867
+ `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
2868
+ options.cwd ?? process.cwd(),
2869
+ );
1065
2870
  e.suggestions = [
1066
2871
  {
1067
- name: `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
1068
- reason: `do this instead: ${near.name} is a theme here`,
2872
+ name: followed.line,
2873
+ reason: `do this instead: ${near.name} is a theme here${followed.why ? `, but this still needs a fix: ${followed.why}` : ''}`,
1069
2874
  },
1070
- ...(e.suggestions ?? []).filter(x => x !== near),
2875
+ ...(e.suggestions ?? []).filter(
2876
+ x => x !== near && x.name !== `${P} show ${near.name}`,
2877
+ ),
1071
2878
  ];
1072
2879
  }
1073
2880
  throw e;
1074
2881
  }
1075
- // Every `set` the refusal suggests is checked as `set` checks it.
1076
- throw vetSuggestions(e, seen.ctx, slug, seen.data);
2882
+ // Every `set` the refusal suggests is checked as `set` checks it, and
2883
+ // carries the value typed (cleaned), never a stock value.
2884
+ throw misplacedFirst(
2885
+ carryTyped(
2886
+ seen.ctx
2887
+ ? vetSuggestions(e, seen.ctx, slug, seen.data)
2888
+ : await vetLoadRefusal(e, options.cwd ?? process.cwd(), slug),
2889
+ sub,
2890
+ slug,
2891
+ oneEntry ? thing : typedThing,
2892
+ oneEntry ? value : typedValue,
2893
+ seen.data ?? savedAsWritten(options.cwd ?? process.cwd(), slug),
2894
+ options.cwd ?? process.cwd(),
2895
+ ),
2896
+ seen.data?.name ?? slug,
2897
+ seen.data,
2898
+ );
1077
2899
  }
1078
2900
  }
1079
2901
 
@@ -1107,29 +2929,33 @@ async function changeOnce(
1107
2929
  when: options.when,
1108
2930
  state: options.state,
1109
2931
  mode: options.mode,
2932
+ // An undo removes the entry it names even when that entry's mode or
2933
+ // source means nothing.
2934
+ ...(sub === 'undo' ? {removing: true} : {}),
1110
2935
  });
1111
- const data = loadTheme(cwd, slug, target);
1112
- /** @type {string[]} */
1113
- const fieldNotes = [];
1114
- if (sub === 'set' && (thing === 'base' || thing === 'mode')) {
1115
- // The other field, when it is damaged too, goes back to its default,
1116
- // so the theme loads again.
1117
- if (
1118
- thing !== 'mode' &&
1119
- !['both', 'light-only', 'dark-only'].includes(data.mode)
1120
- ) {
1121
- data.mode = 'both';
1122
- fieldNotes.push('mode was missing or damaged, so it is both again');
1123
- }
1124
- if (thing !== 'base' && data.like != null && !LIKE.includes(data.like)) {
1125
- delete data.like;
1126
- fieldNotes.push('base was not a built-in theme, so it is none again');
1127
- }
2936
+ /** @type {import('./_settings.mjs').ThemeData} */
2937
+ let data;
2938
+ try {
2939
+ data = loadTheme(cwd, slug, target);
2940
+ } catch (e) {
2941
+ throw await withSavedRepair(e, slug, cwd);
1128
2942
  }
2943
+ /** @type {string[]} */
2944
+ // A damaged mode or base the command does not set itself is read as
2945
+ // meant, or goes back to its default, so the theme loads again.
2946
+ const fieldNotes = [
2947
+ ...entryNotes(data),
2948
+ ...readFields(
2949
+ data,
2950
+ cwd,
2951
+ thing === 'mode' || thing === 'base' ? thing : undefined,
2952
+ slug,
2953
+ ),
2954
+ ];
1129
2955
  const ctx = await context(cwd);
1130
2956
  // An undo of one setting only removes it, so it never waits on the
1131
2957
  // others being fixed.
1132
- if (sub !== 'undo')
2958
+ if (sub !== 'undo') {
1133
2959
  refuseStoredTokens(ctx, slug, data, {
1134
2960
  thing,
1135
2961
  on: options.on,
@@ -1137,6 +2963,7 @@ async function changeOnce(
1137
2963
  state: options.state,
1138
2964
  mode: options.mode,
1139
2965
  });
2966
+ }
1140
2967
  const flags = {
1141
2968
  on: options.on,
1142
2969
  when: options.when,
@@ -1175,8 +3002,25 @@ async function changeOnce(
1175
3002
  Boolean(x.only) === Boolean(flags.only),
1176
3003
  )
1177
3004
  : -1;
1178
- let rawIdx = -1;
1179
- if (exactIdx >= 0) {
3005
+ // An entry of this name whose mode or source means nothing is the one an
3006
+ // undo removes: only that entry, never a valid one beside it.
3007
+ const damagedIdx =
3008
+ sub === 'undo'
3009
+ ? data.settings.findIndex(
3010
+ x =>
3011
+ (x.thing === typedThing || x.thing === thing) &&
3012
+ (x.on ?? null) === (flags.on ?? null) &&
3013
+ (x.when ?? null) === (flags.when ?? null) &&
3014
+ (x.state ?? null) === (flags.state ?? null) &&
3015
+ (entryDamage(x) === 'only' ||
3016
+ Boolean(x.only) === Boolean(flags.only)) &&
3017
+ (entryDamage(x) === 'source' || entryDamage(x) === 'only'
3018
+ ? (x.mode ?? null) === (flags.mode ?? null)
3019
+ : entryDamage(x) === 'mode' && !flags.mode),
3020
+ )
3021
+ : -1;
3022
+ let rawIdx = damagedIdx;
3023
+ if (exactIdx >= 0 && rawIdx < 0) {
1180
3024
  // Only an entry the editor would not save as written: one it refuses,
1181
3025
  // or reads as another name, part or state.
1182
3026
  const entry = data.settings[exactIdx];
@@ -1282,12 +3126,29 @@ async function changeOnce(
1282
3126
  ...data.settings.map(x => x.thing.toLowerCase()),
1283
3127
  ]).length > 0;
1284
3128
  const steps = readHistory(themeFiles(cwd, slug).history).steps.length;
3129
+ // The setting whose scope is the one typed (no --on: the whole
3130
+ // theme's) leads; with none of that scope, the message says so and
3131
+ // the others are listed after it.
3132
+ const sameScope = (/** @type {any} */ x) =>
3133
+ (x.on ?? null) === (flags.on ?? null) &&
3134
+ (x.when ?? null) === (flags.when ?? null) &&
3135
+ (x.state ?? null) === (flags.state ?? null) &&
3136
+ (x.mode ?? null) === (flags.mode ?? null);
3137
+ const ordered = [
3138
+ ...matches.filter(sameScope),
3139
+ ...matches.filter(x => !sameScope(x)),
3140
+ ];
3141
+ const scoped = flags.on || flags.when || flags.state || flags.mode;
1285
3142
  throw new AstryxError(
1286
- e.message,
3143
+ matches.length && !matches.some(sameScope) && scoped
3144
+ ? `${e.message.replace(/\s*Nothing was changed\.$/, '')} ${slug} sets ${matches[0].thing} only where these lines name. Nothing was changed.`
3145
+ : e.message,
1287
3146
  matches.length
1288
- ? matches.slice(0, 5).map(x => ({
3147
+ ? ordered.slice(0, 5).map(x => ({
1289
3148
  name: `${P} undo ${slug} ${undoArgs(x)}`,
1290
- reason: 'do this instead',
3149
+ reason: sameScope(x)
3150
+ ? 'do this instead'
3151
+ : `do this instead: ${describe({...x, value: '?'}).replace(' = ?', '')}`,
1291
3152
  }))
1292
3153
  : [
1293
3154
  steps && !nearSetting
@@ -1341,6 +3202,9 @@ async function changeOnce(
1341
3202
  );
1342
3203
  }
1343
3204
  const compiledBefore = compileTheme(ctx, data, base);
3205
+ // The build notes the theme had before this change: only new ones are
3206
+ // this change's to report.
3207
+ const notesBefore = new Set(buildNotes(ctx));
1344
3208
  if (sub === 'set' && (s.thing === 'base' || s.thing === 'mode')) {
1345
3209
  const before = s.thing === 'base' ? (data.like ?? 'none') : data.mode;
1346
3210
  if (s.thing === 'base') {
@@ -1349,7 +3213,7 @@ async function changeOnce(
1349
3213
  } else
1350
3214
  data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (s.value);
1351
3215
  const r = await commitTheme(ctx, slug, data, {history: true});
1352
- const p = await previewAndRoute(ctx, slug, data, png);
3216
+ const p = await previewAndRoute(ctx, slug, data, png, 'overview', sub);
1353
3217
  const after = await baseResolved(ctx.project, data.like).catch(() => base);
1354
3218
  return {
1355
3219
  type: 'themeEdit.set',
@@ -1377,8 +3241,34 @@ async function changeOnce(
1377
3241
  ]
1378
3242
  : []),
1379
3243
  ...otherModeNotes(data),
3244
+ // A theme the app lists takes its mode from the app's theme
3245
+ // module: `theme add` writes it again.
3246
+ ...(s.thing === 'mode' && before !== data.mode
3247
+ ? [
3248
+ addedModeNote(
3249
+ cwd,
3250
+ slug,
3251
+ data.mode === 'light-only'
3252
+ ? 'light'
3253
+ : data.mode === 'dark-only'
3254
+ ? 'dark'
3255
+ : null,
3256
+ ),
3257
+ ].filter(x => x !== null)
3258
+ : []),
3259
+ // Back to both modes: a mode the app's <Theme> was given for the
3260
+ // one-mode theme pins it still.
3261
+ ...(s.thing === 'mode' &&
3262
+ !appListsTheme(cwd, slug) &&
3263
+ data.mode === 'both' &&
3264
+ (before === 'light-only' || before === 'dark-only')
3265
+ ? [
3266
+ `if the app's <Theme> was given mode="${before === 'light-only' ? 'light' : 'dark'}" for ${slug}, take it out: with it the app stays ${before === 'light-only' ? 'light' : 'dark'}, whatever the system asks for`,
3267
+ ]
3268
+ : []),
1380
3269
  // Core has no mode inside a theme: the app's <Theme> is given it.
1381
3270
  ...(s.thing === 'mode' &&
3271
+ !appListsTheme(cwd, slug) &&
1382
3272
  (data.mode === 'light-only' || data.mode === 'dark-only')
1383
3273
  ? [
1384
3274
  `the app shows ${slug} in ${data.mode === 'light-only' ? 'light' : 'dark'} mode when its <Theme> is given mode="${data.mode === 'light-only' ? 'light' : 'dark'}" (<Theme theme={…} mode="${data.mode === 'light-only' ? 'light' : 'dark'}">), as the preview does; the theme keeps both halves of its colors, so a toast or a lightbox Core draws in the other mode stays readable`,
@@ -1411,13 +3301,53 @@ async function changeOnce(
1411
3301
  }
1412
3302
  const k = keyOf(s);
1413
3303
  const prevIdx =
1414
- rawIdx >= 0 ? rawIdx : data.settings.findIndex(x => keyOf(x) === k);
3304
+ rawIdx >= 0
3305
+ ? rawIdx
3306
+ : // A setting listed twice by hand: the last entry is the one the
3307
+ // build reads, so it is the one this command changes.
3308
+ data.settings.map(x => keyOf(x)).lastIndexOf(k);
1415
3309
  /** @type {string | null} */
1416
3310
  let vibrancyGone = null;
1417
3311
  const prev = prevIdx >= 0 ? data.settings[prevIdx] : null;
3312
+ /** The other entries of a setting listed twice by hand that this command replaces or removes. @type {import('./_settings.mjs').Setting[]} */
3313
+ let alsoReplaced = [];
1418
3314
  if (sub === 'undo') {
1419
3315
  if (!prev) {
1420
- const near = data.settings.filter(x => x.thing === s.thing).map(describe);
3316
+ // A padding set in the other form (a side for the shorthand, or the
3317
+ // shorthand for a side) on the same part is a near one too.
3318
+ const PAD = /^padding(?:-(?:inline|block|top|right|bottom|left))?$/;
3319
+ const nearOnes = data.settings.filter(
3320
+ x =>
3321
+ x.thing === s.thing ||
3322
+ (PAD.test(s.thing) &&
3323
+ PAD.test(x.thing) &&
3324
+ (x.on ?? null) === (s.on ?? null)),
3325
+ );
3326
+ const near = nearOnes.map(describe);
3327
+ // A token the theme's own source sets: that file is where it is
3328
+ // changed, never the settings.
3329
+ const ownEntry =
3330
+ s.thing.startsWith('--') && !s.on && !s.when && !s.state
3331
+ ? ownTokenEntries(cwd, slug).find(
3332
+ x => x.token === s.thing && !x.overridden && x.kind !== 'scoped',
3333
+ )
3334
+ : undefined;
3335
+ if (ownEntry) {
3336
+ const file = ownEntry.file
3337
+ ? path.relative(cwd, ownEntry.file)
3338
+ : `themes/${slug}/${slug}.theme.ts`;
3339
+ refuse(
3340
+ E.ERR_THEME_NOT_SET,
3341
+ `The settings do not set ${s.thing}: ${file} sets it itself${ownEntry.line ? ` (line ${ownEntry.line})` : ''}, so undo has nothing to remove; change or remove it in ${file}.`,
3342
+ {
3343
+ run: [
3344
+ ownEntry.line
3345
+ ? `sed -n ${ownEntry.line}p ${quoteCommandArgument(file)}`
3346
+ : `grep -n -- ${quoteCommandArgument(s.thing)} ${quoteCommandArgument(file)}`,
3347
+ ],
3348
+ },
3349
+ );
3350
+ }
1421
3351
  // headings has two halves: name the one that is set.
1422
3352
  const otherHalf =
1423
3353
  s.thing === 'headings'
@@ -1430,11 +3360,12 @@ async function changeOnce(
1430
3360
  : `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
1431
3361
  {
1432
3362
  also: near.length
1433
- ? [`settings for ${s.thing}: ${near.join('; ')}`]
3363
+ ? [
3364
+ `settings for ${s.thing}: ${near.join('; ')}${nearOnes.some(x => x.thing === 'padding' && s.thing !== 'padding') ? ' (undoing padding removes all four sides)' : ''}`,
3365
+ ]
1434
3366
  : [],
1435
3367
  run: [
1436
- ...data.settings
1437
- .filter(x => x.thing === s.thing)
3368
+ ...nearOnes
1438
3369
  .slice(0, 3)
1439
3370
  .map(x => `${P} undo ${slug} ${undoArgs(x)}`),
1440
3371
  `${P} show ${slug}`,
@@ -1443,7 +3374,9 @@ async function changeOnce(
1443
3374
  );
1444
3375
  }
1445
3376
  data.settings.splice(prevIdx, 1);
1446
- // A setting listed twice by hand goes in full.
3377
+ // A setting listed twice by hand goes in full, and each entry removed
3378
+ // is named.
3379
+ alsoReplaced = data.settings.filter(x => keyOf(x) === k);
1447
3380
  data.settings = data.settings.filter(x => keyOf(x) !== k);
1448
3381
  // Vibrancy needs a color: undoing the last one takes it along, so the
1449
3382
  // theme never holds a state `set` refuses.
@@ -1480,9 +3413,11 @@ async function changeOnce(
1480
3413
  if (prev) data.settings.splice(prevIdx, 1);
1481
3414
  data.settings.push(s);
1482
3415
  }
1483
- // A setting listed twice by hand keeps only the entry this command left.
3416
+ // A setting listed twice by hand keeps only the entry this command left;
3417
+ // every other entry it replaces is named in the notes.
1484
3418
  if (sub === 'set') {
1485
3419
  const last = data.settings.map(x => keyOf(x)).lastIndexOf(k);
3420
+ alsoReplaced = data.settings.filter((x, i) => keyOf(x) === k && i !== last);
1486
3421
  data.settings = data.settings.filter(
1487
3422
  (x, i) => keyOf(x) !== k || i === last,
1488
3423
  );
@@ -1493,7 +3428,21 @@ async function changeOnce(
1493
3428
  const covered =
1494
3429
  sub === 'set' && !s.mode && s.source !== 'dial'
1495
3430
  ? data.settings.filter(
1496
- x => x !== s && x.mode && keyOf({...x, mode: undefined}) === k,
3431
+ x =>
3432
+ x !== s &&
3433
+ x.mode &&
3434
+ (keyOf({...x, mode: undefined}) === k ||
3435
+ // The background shorthand and its color are one property
3436
+ // here: a one-mode one is replaced by either for both modes.
3437
+ (s.source === 'property' &&
3438
+ x.source === 'property' &&
3439
+ x.on === s.on &&
3440
+ x.when === s.when &&
3441
+ x.state === s.state &&
3442
+ [x.thing, s.thing].every(t =>
3443
+ /^background(-color)?$/.test(kebab(t)),
3444
+ ) &&
3445
+ !/gradient\(|url\(/i.test(String(s.value)))),
1497
3446
  )
1498
3447
  : [];
1499
3448
  data.settings = data.settings.filter(x => !covered.includes(x));
@@ -1513,6 +3462,9 @@ async function changeOnce(
1513
3462
  ))) &&
1514
3463
  x.when === s.when &&
1515
3464
  x.state === s.state &&
3465
+ // A shorthand for one mode replaces longhands of that mode or of
3466
+ // both, never the other mode's.
3467
+ (!s.mode || !x.mode || x.mode === s.mode) &&
1516
3468
  // A longhand the shorthand really sets (MDN's data), never a
1517
3469
  // property that only shares its name (overflow-wrap).
1518
3470
  (coversProperty(s.thing, x.thing) ||
@@ -1537,6 +3489,12 @@ async function changeOnce(
1537
3489
  : [];
1538
3490
  const r = await commitTheme(ctx, slug, data, {history: true});
1539
3491
  const compiledAfter = compileTheme(ctx, data, base);
3492
+ // What the spacing dial said of the sizes it could not keep apart.
3493
+ // What the build said of settings it could not write as they are.
3494
+ const compileNotes = buildNotes(ctx).filter(n => !notesBefore.has(n));
3495
+ const sizeNotes =
3496
+ /** @type {{sizeNotes?: string[]}} */ (/** @type {unknown} */ (ctx))
3497
+ .sizeNotes ?? [];
1540
3498
  const styled = styledChanges(compiledBefore, compiledAfter, base);
1541
3499
  const parts = partsOf(ctx, s);
1542
3500
  // Exact whole-theme tokens that win over what this dial writes: the dial
@@ -1562,6 +3520,29 @@ async function changeOnce(
1562
3520
  !x.when &&
1563
3521
  x.thing === `--font-family-${s.on}`,
1564
3522
  );
3523
+ // A whole-theme spacing dial keeps a part's own exact control size too,
3524
+ // on that part.
3525
+ if (sub === 'set' && s.source === 'dial' && s.thing === 'spacing' && !s.on)
3526
+ exactWins.push(
3527
+ ...data.settings.filter(
3528
+ x =>
3529
+ x.source === 'token' &&
3530
+ !!x.on &&
3531
+ !x.state &&
3532
+ /^--size-element-/.test(x.thing),
3533
+ ),
3534
+ );
3535
+ // A spacing dial on a part keeps the exact spacing and sizes there too:
3536
+ // the whole theme's, and the part's own.
3537
+ if (sub === 'set' && s.source === 'dial' && s.thing === 'spacing' && s.on)
3538
+ exactWins = data.settings.filter(
3539
+ x =>
3540
+ x.source === 'token' &&
3541
+ !x.when &&
3542
+ !x.state &&
3543
+ /^--(size-element|spacing)-/.test(x.thing) &&
3544
+ (!x.on || x.on === s.on),
3545
+ );
1565
3546
  // The theme's own source wins over an exact setting, as the exact
1566
3547
  // setting does over a dial: an exact token the file also sets is named
1567
3548
  // as the file's below, never as the one that shows after an undo.
@@ -1762,6 +3743,12 @@ async function changeOnce(
1762
3743
  : null;
1763
3744
  /** @type {string[]} */
1764
3745
  const notes = [
3746
+ ...fieldNotes,
3747
+ ...(alsoReplaced.length && prev
3748
+ ? [
3749
+ `${describe({...prev, value: '?'}).replace(' = ?', '')} was listed ${alsoReplaced.length === 1 ? 'twice' : `${alsoReplaced.length + 1} times`} (${[...alsoReplaced, prev].map(x => x.value).join(', ')}); each is ${sub === 'set' ? 'replaced' : 'removed'}`,
3750
+ ]
3751
+ : []),
1765
3752
  ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
1766
3753
  ...(ownPartHits.length
1767
3754
  ? [
@@ -1773,7 +3760,7 @@ async function changeOnce(
1773
3760
  )
1774
3761
  .join(
1775
3762
  ', ',
1776
- )}${ownPartHits.length > 3 ? ` and ${ownPartHits.length - 3} more` : ''}, and your own source wins over the settings, so this does not show there; change it in ${slug}.theme.ts${ownHitDirect ? `, or take this back with \`${P} undo ${slug} ${undoArgs(s)}\`` : ''}`,
3763
+ )}${ownPartHits.length > 3 ? ` and ${ownPartHits.length - 3} more` : ''}, and your own source wins over the settings, so this does not show ${/^padding(-|$)/.test(s.thing) && ownPartHits.every(h => /^padding-/.test(h.prop)) ? 'on the sides that sets; its other sides take this setting' : 'there'}; change it in ${slug}.theme.ts${ownHitDirect ? `, or take this back with \`${P} undo ${slug} ${undoArgs(s)}\`` : ''}`,
1777
3764
  ]
1778
3765
  : []),
1779
3766
  ...(ownOverToken
@@ -1786,6 +3773,8 @@ async function changeOnce(
1786
3773
  `keeps your exact ${exactWins.map(describe).join(', ')}: an exact setting wins over a dial, so ${exactWins.length > 1 ? 'those do' : 'that does'} not change; this shows after \`${P} undo ${slug} ${exactWins.map(x => undoArgs(x)).join(`\` and \`${P} undo ${slug} `)}\``,
1787
3774
  ]
1788
3775
  : []),
3776
+ ...(sub === 'set' && s.thing === 'spacing' ? sizeNotes : []),
3777
+ ...(sub === 'set' ? compileNotes : []),
1789
3778
  ...(covers.length
1790
3779
  ? [
1791
3780
  `comes after ${covers.map(describe).join(', ')}, so ${covers.length > 1 ? 'those parts show' : `${covers[0].on} shows`} this value now; set ${covers.length > 1 ? 'one' : 'it'} again to make it win`,
@@ -1831,9 +3820,18 @@ async function changeOnce(
1831
3820
  // An exact property on the same part wins over a dial there.
1832
3821
  ...(exactOver
1833
3822
  ? [
1834
- ownPartHits.length
1835
- ? `${describe(exactOver)} is an exact property and wins over ${s.thing} there too; undoing it does not make ${s.thing} show on ${[...new Set(ownPartHits.map(h => h.target))].join(', ')}, where ${slug}.theme.ts wins`
1836
- : `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
3823
+ // The own source holding only some sides or corners there leaves
3824
+ // the dial the others once the exact property is undone.
3825
+ ownPartHits.length &&
3826
+ ownPartHits.every(h =>
3827
+ /(Top|Bottom|Left|Right|Start|End|Block|Inline)/.test(
3828
+ camel(String(h.prop)),
3829
+ ),
3830
+ )
3831
+ ? `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\`, and then not on the ${[...new Set(ownPartHits.map(h => kebab(String(h.prop))))].join(', ')} ${slug}.theme.ts sets itself`
3832
+ : ownPartHits.length
3833
+ ? `${describe(exactOver)} is an exact property and wins over ${s.thing} there too; undoing it does not make ${s.thing} show on ${[...new Set(ownPartHits.map(h => h.target))].join(', ')}, where ${slug}.theme.ts wins`
3834
+ : `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1837
3835
  ]
1838
3836
  : []),
1839
3837
  // A whole-theme font under fonts set for each role shows only where no
@@ -1900,6 +3898,21 @@ async function changeOnce(
1900
3898
  : null
1901
3899
  : null;
1902
3900
  if (s.note) notes.push(s.note);
3901
+ // A group kept alike (inputs share one height) loses that when one member
3902
+ // changes its height alone.
3903
+ const family = s.on && s.only ? familyOf(s.on) : null;
3904
+ if (
3905
+ family &&
3906
+ AUTO_SPREAD.includes(family) &&
3907
+ (s.thing === 'spacing' ||
3908
+ /^--size-element-/.test(s.thing) ||
3909
+ /^(min-|max-)?(height|block-size)$|^padding(-block(-start|-end)?|-top|-bottom)?$/.test(
3910
+ s.thing,
3911
+ ))
3912
+ )
3913
+ notes.push(
3914
+ `${s.on} alone now differs in height from the rest of ${family}, which are kept alike; --on ${family} changes them together`,
3915
+ );
1903
3916
  // A token the theme's own source sets itself wins over what this dial
1904
3917
  // writes, as an exact setting does.
1905
3918
  const ownWins = ownSourceTokens(cwd, slug).filter(
@@ -2000,7 +4013,14 @@ async function changeOnce(
2000
4013
  );
2001
4014
  notes.push(...unsetColorNotes(data, base, slug));
2002
4015
  }
2003
- if (s.thing === 'font' && sub === 'set')
4016
+ // A font set (the dial, a part's own font-family, a font token): how
4017
+ // it loads.
4018
+ if (
4019
+ (s.thing === 'font' ||
4020
+ s.thing === 'font-family' ||
4021
+ /^--font-family-/.test(s.thing)) &&
4022
+ sub === 'set'
4023
+ )
2004
4024
  notes.unshift(...fontNotes(ctx, {...data, settings: [s]}));
2005
4025
  if (s.thing === 'type' || s.thing === 'headings')
2006
4026
  for (const [m, why] of maskedSettings(data, ctx))
@@ -2018,6 +4038,12 @@ async function changeOnce(
2018
4038
  // once preview.html was rendered from the theme as it is now (a retry
2019
4039
  // after a render that failed renders it).
2020
4040
  const f0 = themeFiles(cwd, slug);
4041
+ // A change that changed nothing still writes back an app copy file that
4042
+ // is gone or not the current build.
4043
+ // Its font stylesheet follows the fonts the theme loads now (a font
4044
+ // package installed or removed since).
4045
+ if (r.unchanged && appCopyBehind(cwd, slug, copyFontsCss(ctx, slug, data)))
4046
+ writeAppCopy(ctx, slug, data);
2021
4047
  const p =
2022
4048
  r.unchanged &&
2023
4049
  !png &&
@@ -2030,8 +4056,10 @@ async function changeOnce(
2030
4056
  notChecked: null,
2031
4057
  previewStale: [],
2032
4058
  see: seeLine(cwd, slug, changeFocus(s)),
4059
+ // A copy something keeps behind is said here too.
4060
+ ...appCopyStale(cwd, slug),
2033
4061
  }
2034
- : await previewAndRoute(ctx, slug, data, png, changeFocus(s));
4062
+ : await previewAndRoute(ctx, slug, data, png, changeFocus(s), sub);
2035
4063
  return {
2036
4064
  type: sub === 'set' ? 'themeEdit.set' : 'themeEdit.undo',
2037
4065
  data: {
@@ -2105,6 +4133,50 @@ function unsetColorNotes(data, base, slug) {
2105
4133
  ];
2106
4134
  }
2107
4135
 
4136
+ /**
4137
+ * Whether a settings entry is a mode or base a hand edit put in the list:
4138
+ * it does nothing there (the theme's mode and base are its own fields).
4139
+ * @param {{thing: string}} s
4140
+ */
4141
+ const misplaced = s => s.thing === 'mode' || s.thing === 'base';
4142
+
4143
+ /**
4144
+ * The note for each misplaced entry: listed here only, never as a
4145
+ * setting, with the undo that removes it first.
4146
+ * @param {string} slug
4147
+ * @param {import('./_settings.mjs').ThemeData} data
4148
+ * @returns {string[]}
4149
+ */
4150
+ function misplacedNotes(slug, data) {
4151
+ return data.settings
4152
+ .filter(misplaced)
4153
+ .map(
4154
+ x =>
4155
+ `misplaced: the settings list holds ${x.thing} = ${x.value}, which does nothing there (the theme's ${x.thing} is ${x.thing === 'mode' ? data.mode : (data.like ?? 'none')}); \`${P} undo ${slug} ${x.thing}\` removes it, and \`${P} set ${slug} ${x.thing} <value>\` sets the theme's ${x.thing}`,
4156
+ );
4157
+ }
4158
+
4159
+ /**
4160
+ * A refusal for a theme with misplaced entries, its suggestions led by the
4161
+ * undo that removes each.
4162
+ * @param {unknown} e
4163
+ * @param {string} slug
4164
+ * @param {import('./_settings.mjs').ThemeData | undefined} data
4165
+ */
4166
+ function misplacedFirst(e, slug, data) {
4167
+ if (!(e instanceof AstryxError) || !data) return e;
4168
+ const undos = data.settings.filter(misplaced).map(x => ({
4169
+ name: `${P} undo ${slug} ${x.thing}`,
4170
+ reason: `removes the ${x.thing} entry that does nothing in the settings list`,
4171
+ }));
4172
+ if (!undos.length) return e;
4173
+ e.suggestions = [
4174
+ ...undos,
4175
+ ...(e.suggestions ?? []).filter(x => !undos.some(u => u.name === x.name)),
4176
+ ];
4177
+ return e;
4178
+ }
4179
+
2108
4180
  /**
2109
4181
  * Every setting of a theme, key resolved values, problems it caused, the
2110
4182
  * sample page and the theme-building page with every component.
@@ -2120,12 +4192,19 @@ export async function themeEditShow(theme, options = {}) {
2120
4192
  const readOnly = Boolean(/** @type {any} */ (options).readOnly);
2121
4193
  requireProject(cwd);
2122
4194
  const section = checkSection(options.section, theme);
2123
- const data = loadTheme(cwd, theme);
4195
+ /** @type {import('./_settings.mjs').ThemeData} */
4196
+ let data;
4197
+ try {
4198
+ data = loadTheme(cwd, theme);
4199
+ } catch (e) {
4200
+ throw await vetLoadRefusal(e, cwd, theme);
4201
+ }
2124
4202
  const ctx = await context(cwd);
2125
4203
  // The app copy is written once show succeeds (at its end), never by a
2126
4204
  // build a later refusal puts back.
2127
4205
  holdAfterBuild(ctx);
2128
4206
  refuseStoredTokens(ctx, theme, data);
4207
+ await refuseOwnTokenValues(ctx, theme, data);
2129
4208
  // Without React, show still lists the settings and builds the theme, as
2130
4209
  // set does; only the pages, pictures and the checks that render are
2131
4210
  // skipped, and the result says how to fix it.
@@ -2157,7 +4236,7 @@ export async function themeEditShow(theme, options = {}) {
2157
4236
  // An own source that does not parse is refused before anything is
2158
4237
  // built, written or removed (the build would fail part way).
2159
4238
  if (!readOnly) refuseThemeParse(cwd, theme);
2160
- const brokenSource = themeSourceProblem(cwd, theme);
4239
+ const brokenSource = await themeSourceProblem(cwd, theme);
2161
4240
  // Every output, as `compile --check` reads them: one missing or edited by
2162
4241
  // hand is built again too.
2163
4242
  let stale = staleBuild(cwd, theme, data);
@@ -2256,7 +4335,7 @@ export async function themeEditShow(theme, options = {}) {
2256
4335
  if (brokenSource)
2257
4336
  refuse(
2258
4337
  E.ERR_THEME_INVALID,
2259
- `${theme}.js could not be read, and it cannot be built again: ${brokenSource}. Put back the import of ${camel(theme)}Settings from './${theme}.settings', extends: ${camel(theme)}Settings and name: '${theme}' in ${shown(cwd, f.ts)}, then run show again.`,
4338
+ `${theme}.js could not be read, and it cannot be built again: ${brokenSource.problem}. ${brokenSource.fix} Then run show again.`,
2260
4339
  {
2261
4340
  run: [`cat ${quoteCommandArgument(shown(cwd, f.ts))}`],
2262
4341
  },
@@ -2287,6 +4366,16 @@ export async function themeEditShow(theme, options = {}) {
2287
4366
  if (!(e instanceof Error)) throw e;
2288
4367
  if (e instanceof AstryxError && e.code !== E.ERR_RENDER_FAILED) throw e;
2289
4368
  putBack(kept, tokensDir);
4369
+ // A folder it cannot write is no render failure: the folder is named.
4370
+ const code = /** @type {any} */ (e).code;
4371
+ if (['EACCES', 'EPERM', 'EROFS'].includes(code)) {
4372
+ const where = /** @type {any} */ (e).path;
4373
+ return refuse(
4374
+ E.ERR_WRITE_FAILED,
4375
+ `${theme} cannot be shown: ${where ? `${shown(cwd, path.dirname(where))}/` : 'its theme folder'} cannot be written (${code}). Fix its permissions, then run the command again. Nothing was written.`,
4376
+ {run: [`${P} show ${theme}`]},
4377
+ );
4378
+ }
2290
4379
  return refuse(
2291
4380
  E.ERR_RENDER_FAILED,
2292
4381
  `${theme} cannot be shown: ${renderCause(ctx.project, e.message)} ${[...kept.values()].some(Boolean) ? 'The build this show made again was put back as it was. ' : ''}Nothing was written.`,
@@ -2328,7 +4417,15 @@ export async function themeEditShow(theme, options = {}) {
2328
4417
  ],
2329
4418
  modes,
2330
4419
  )
2331
- : {files: [], problem: null};
4420
+ : // Pictures asked for but not taken: said, never a quiet none.
4421
+ {
4422
+ files: [],
4423
+ problem: png
4424
+ ? readOnly
4425
+ ? 'no picture was taken: show ran read-only (the project or its install cannot be written, so it could not hold the theme lock), and the pages the pictures are taken of were not made; run show --png where the project can be written'
4426
+ : 'no picture was taken: React is not installed here, so the pages the pictures are taken of could not be made; install react and react-dom, then run show --png again'
4427
+ : null,
4428
+ };
2332
4429
  // The app copy follows the build there now, also when the build was
2333
4430
  // current and only the copy is missing (a theme made before it existed).
2334
4431
  if (!readOnly)
@@ -2347,29 +4444,32 @@ export async function themeEditShow(theme, options = {}) {
2347
4444
  const looksBase = await baseResolved(ctx.project, data.like).catch(
2348
4445
  () => null,
2349
4446
  );
2350
- return data.settings.map(s => {
2351
- let masked = maskedSettings(data, ctx).get(s);
2352
- // A look dial (buttons, surfaces) under an exact property on a
2353
- // part it writes: named, as corners under border-radius is.
2354
- if (!masked && looksBase && s.source === 'dial' && !s.on) {
2355
- const writes = dialWrites(ctx, data, s, looksBase);
2356
- const exact = writes.size
2357
- ? data.settings.find(
2358
- x =>
2359
- x.source === 'property' &&
2360
- x.on &&
2361
- !x.when &&
2362
- !x.state &&
2363
- partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
2364
- )
2365
- : undefined;
2366
- if (exact)
2367
- masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
2368
- }
2369
- return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
2370
- });
4447
+ return data.settings
4448
+ .filter(s => !misplaced(s))
4449
+ .map(s => {
4450
+ let masked = maskedSettings(data, ctx).get(s);
4451
+ // A look dial (buttons, surfaces) under an exact property on a
4452
+ // part it writes: named, as corners under border-radius is.
4453
+ if (!masked && looksBase && s.source === 'dial' && !s.on) {
4454
+ const writes = dialWrites(ctx, data, s, looksBase);
4455
+ const exact = writes.size
4456
+ ? data.settings.find(
4457
+ x =>
4458
+ x.source === 'property' &&
4459
+ x.on &&
4460
+ !x.when &&
4461
+ !x.state &&
4462
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
4463
+ )
4464
+ : undefined;
4465
+ if (exact)
4466
+ masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
4467
+ }
4468
+ return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
4469
+ });
2371
4470
  })(),
2372
4471
  notes: [
4472
+ ...misplacedNotes(theme, data),
2373
4473
  ...(noReact
2374
4474
  ? [
2375
4475
  `react and react-dom cannot be found from this app, so the pages and pictures were not made again and the checks that render components were skipped; install them (${installLine(cwd, ['react', 'react-dom'])}), then run show again`,
@@ -2391,7 +4491,7 @@ export async function themeEditShow(theme, options = {}) {
2391
4491
  ...(unreadable ? [unreadable] : []),
2392
4492
  ...(brokenSource
2393
4493
  ? [
2394
- `${brokenSource}, so settings cannot take effect; put back the import, extends and name lines in ${theme}.theme.ts${/no longer names the theme/.test(brokenSource) ? ` (a copy of another theme's source still names that theme: change its name to '${theme}')` : ''}`,
4494
+ `${brokenSource.problem}, so settings cannot take effect. ${brokenSource.fix}`,
2395
4495
  ]
2396
4496
  : []),
2397
4497
  // A setting the theme file wins over is not live: no contrast
@@ -2443,6 +4543,7 @@ export async function themeEditShow(theme, options = {}) {
2443
4543
  const wrote = takeFirstAppCopy(cwd, theme);
2444
4544
  return wrote ? {appCopy: {wrote}} : {};
2445
4545
  })(),
4546
+ ...appCopyStale(cwd, theme),
2446
4547
  colorFiles: pal ? colorFiles(theme) : null,
2447
4548
  },
2448
4549
  };
@@ -2492,6 +4593,10 @@ function dialWrites(ctx, data, dial, base) {
2492
4593
  * @returns {string}
2493
4594
  */
2494
4595
  function nowApplies(ctx, data, removed, base) {
4596
+ // Vibrancy has no base theme value: the colors are made again at the
4597
+ // default.
4598
+ if (removed.source === 'dial' && removed.thing === 'vibrancy')
4599
+ return `the default vibrancy, ${VIBRANCY_DEFAULT}`;
2495
4600
  // A token the theme's own source sets shows its value, whatever else
2496
4601
  // the settings give it.
2497
4602
  if (removed.source === 'token' && !removed.on && !removed.when) {
@@ -2726,8 +4831,30 @@ function ownPhoneNotes(cwd, slug, data) {
2726
4831
  .filter(x => x.source === 'token' && !x.on && !x.when && !x.state)
2727
4832
  .map(x => x.thing),
2728
4833
  );
4834
+ // A family or size the theme's typography sets is kept on phones (the
4835
+ // base theme's rule for those screens keeps the theme's typography); only
4836
+ // one the tokens map sets is lost there.
4837
+ const entries = ownTokenEntries(cwd, slug);
4838
+ const roles = new Set(
4839
+ entries.filter(e => e.kind === 'typography').map(e => e.key.split('.')[0]),
4840
+ );
4841
+ const inMap = new Set(
4842
+ entries
4843
+ .filter(e => e.token && !e.overridden && e.kind !== 'scoped')
4844
+ .map(e => e.token),
4845
+ );
4846
+ /** @param {string} k */
4847
+ const fromTypography = k => {
4848
+ const role = /^--font-family-([a-z]+)$/.exec(k)?.[1];
4849
+ if (role)
4850
+ return roles.has(role) || (role === 'heading' && roles.has('body'));
4851
+ return roles.has('scale') && !/^--font-family-/.test(k);
4852
+ };
2729
4853
  const lost = ownSourceTokens(cwd, slug).filter(
2730
- k => PHONE_TYPE.test(k) && !exact.has(k),
4854
+ k =>
4855
+ PHONE_TYPE.test(k) &&
4856
+ !exact.has(k) &&
4857
+ (!fromTypography(k) || inMap.has(k)),
2731
4858
  );
2732
4859
  if (!lost.length) return [];
2733
4860
  const families = lost.filter(k => /^--font-family-/.test(k));
@@ -3038,10 +5165,98 @@ function colorFiles(slug) {
3038
5165
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditUndoResponse | import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
3039
5166
  */
3040
5167
  export async function themeEditUndo(theme, options = {}) {
5168
+ try {
5169
+ return await undoTheme(theme, options);
5170
+ } catch (e) {
5171
+ // A theme name typed in another form (tTheme, T, brand_dark, themes/t):
5172
+ // the same undo with the theme's name comes first, never a look at the
5173
+ // theme that drops the undo.
5174
+ if (
5175
+ e instanceof AstryxError &&
5176
+ (e.code === E.ERR_INVALID_ARGUMENT || e.code === E.ERR_UNKNOWN_THEME)
5177
+ ) {
5178
+ const cwd = options.cwd ?? process.cwd();
5179
+ const showOf = (/** @type {{name: string}} */ x) => {
5180
+ const rest = x.name.startsWith(`${P} show `)
5181
+ ? x.name.slice(`${P} show `.length)
5182
+ : null;
5183
+ return rest && !/\s/.test(rest) ? rest : null;
5184
+ };
5185
+ // A list of themes (t,u) stays a look at each: one theme at a time.
5186
+ const shows = (e.suggestions ?? []).filter(x => showOf(x) != null);
5187
+ const near = (shows.length === 1 ? shows : []).find(x => {
5188
+ const n = showOf(x);
5189
+ return (
5190
+ n != null &&
5191
+ n !== theme &&
5192
+ slugOk(n) &&
5193
+ fs.existsSync(themeFiles(cwd, n).settings)
5194
+ );
5195
+ });
5196
+ const name = near ? showOf(near) : null;
5197
+ if (near && name) {
5198
+ const words = [
5199
+ ...(options.thing ? [options.thing] : []),
5200
+ ...(options.value ? [options.value] : []),
5201
+ ...(options.on ? ['--on', options.on] : []),
5202
+ ...(options.when ? ['--when', options.when] : []),
5203
+ ...(options.state ? ['--state', options.state] : []),
5204
+ ...(options.mode ? ['--mode', options.mode] : []),
5205
+ ].map(w =>
5206
+ String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
5207
+ );
5208
+ const followed = await followChangeLine(
5209
+ 'undo',
5210
+ name,
5211
+ `${P} undo ${name}${words.length ? ` ${words.join(' ')}` : ''}`,
5212
+ cwd,
5213
+ );
5214
+ e.suggestions = [
5215
+ {
5216
+ name: followed.line,
5217
+ reason: `do this instead: ${name} is a theme here${followed.why ? `, but this still needs a fix: ${followed.why}` : ''}`,
5218
+ },
5219
+ ...(e.suggestions ?? []).filter(x => x !== near),
5220
+ ];
5221
+ }
5222
+ }
5223
+ // Then the theme typed after the setting (`undo corners t`).
5224
+ throw await swappedOrder(
5225
+ e,
5226
+ 'undo',
5227
+ [theme, options.thing, options.value],
5228
+ options,
5229
+ );
5230
+ }
5231
+ }
5232
+
5233
+ /**
5234
+ * {@link themeEditUndo}'s work.
5235
+ * @param {string} theme
5236
+ * @param {import('./theme-edit.type.mjs').ThemeEditUndoOptions} options
5237
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditUndoResponse | import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
5238
+ */
5239
+ async function undoTheme(theme, options) {
3041
5240
  const {cwd = process.cwd(), png = false, thing} = options;
3042
5241
  // base and mode are not settings in the list: undoing one goes back to
3043
5242
  // what the theme was made with (the oldest step the history keeps).
3044
- if (thing === 'base' || thing === 'mode') {
5243
+ // A `base` or `mode` entry a hand edit put in the settings list is a
5244
+ // setting like any other there: undo removes it.
5245
+ const listed =
5246
+ (thing === 'base' || thing === 'mode') &&
5247
+ slugOk(theme) &&
5248
+ (() => {
5249
+ try {
5250
+ return JSON.parse(
5251
+ fs
5252
+ .readFileSync(themeFiles(cwd, theme).settings, 'utf8')
5253
+ .replace(/^\uFEFF/, ''),
5254
+ ).settings.some((/** @type {any} */ x) => x?.thing === thing);
5255
+ } catch {
5256
+ return false;
5257
+ }
5258
+ })();
5259
+ if ((thing === 'base' || thing === 'mode') && !listed) {
3045
5260
  requireProject(cwd);
3046
5261
  const now = loadTheme(cwd, theme, thing);
3047
5262
  const historyFile = themeFiles(cwd, theme).history;
@@ -3128,10 +5343,18 @@ export async function themeEditUndo(theme, options = {}) {
3128
5343
  // A link in the theme is refused as set refuses it, never read as an
3129
5344
  // empty history.
3130
5345
  if (slugOk(theme)) refuseLinks(cwd, theme);
5346
+ /** The command that works when the settings cannot be read. @type {string[] | null} */
5347
+ let repair = null;
3131
5348
  try {
3132
5349
  current = loadTheme(cwd, theme);
3133
5350
  } catch (e) {
3134
5351
  if (!(e instanceof AstryxError && e.code === E.ERR_THEME_INVALID)) throw e;
5352
+ // What the refusal itself names (make the theme again, keeping the
5353
+ // damaged file), never `show`, which fails the same way.
5354
+ repair = (e.suggestions ?? [])
5355
+ .map(x => x.name)
5356
+ .filter(n => !/ show /.test(` ${n} `) && !/ undo /.test(` ${n} `));
5357
+ if (!repair.length) repair = [`${P} new ${theme}`];
3135
5358
  }
3136
5359
  const f = themeFiles(cwd, theme);
3137
5360
  const {steps: history, dropped} = readHistory(f.history);
@@ -3141,35 +5364,26 @@ export async function themeEditUndo(theme, options = {}) {
3141
5364
  `${theme}.history.json is damaged, so there is no step to go back to.`,
3142
5365
  {
3143
5366
  fix: `move ${shown(cwd, f.history)} out of the theme folder (it is kept as it is): the next change starts a new history, and your settings stay as they are`,
3144
- run: [`${P} show ${theme}`],
5367
+ run: repair ?? [`${P} show ${theme}`],
3145
5368
  },
3146
5369
  );
3147
5370
  if (!history.length)
3148
5371
  refuse(
3149
5372
  E.ERR_THEME_NOTHING_TO_UNDO,
3150
- `Nothing to undo: ${theme} has no earlier change.`,
3151
- {run: [`${P} show ${theme}`]},
5373
+ `Nothing to undo: ${theme} has no earlier change${repair ? `, and ${theme}.settings.json cannot be read` : ''}.`,
5374
+ {run: repair ?? [`${P} show ${theme}`]},
3152
5375
  );
3153
5376
  // A top step equal to the settings now (left by an undo stopped between
3154
5377
  // its two writes) changes nothing: skip it.
3155
5378
  const nowText = fs.readFileSync(f.settings, 'utf8');
3156
5379
  const same = (/** @type {string} */ a, /** @type {string} */ b) => {
3157
- try {
3158
- return (
3159
- JSON.stringify({
3160
- ...JSON.parse(a.replace(/^\uFEFF/, '')),
3161
- lifted: 0,
3162
- built: 0,
3163
- }) ===
3164
- JSON.stringify({
3165
- ...JSON.parse(b.replace(/^\uFEFF/, '')),
3166
- lifted: 0,
3167
- built: 0,
3168
- })
3169
- );
3170
- } catch {
3171
- return false;
3172
- }
5380
+ const [x, y] = [settingsJson(a), settingsJson(b)];
5381
+ return (
5382
+ x !== undefined &&
5383
+ y !== undefined &&
5384
+ JSON.stringify({...x, lifted: 0, built: 0}) ===
5385
+ JSON.stringify({...y, lifted: 0, built: 0})
5386
+ );
3173
5387
  };
3174
5388
  while (history.length && same(history[history.length - 1], nowText))
3175
5389
  history.pop();
@@ -3182,8 +5396,10 @@ export async function themeEditUndo(theme, options = {}) {
3182
5396
  const ctx = await context(cwd);
3183
5397
  const prevText = /** @type {string} */ (history.pop());
3184
5398
  let prev = /** @type {import('./_settings.mjs').ThemeData} */ (
3185
- JSON.parse(prevText.replace(/^\uFEFF/, ''))
5399
+ settingsJson(prevText)
3186
5400
  );
5401
+ // A step is read as a change reads the settings file.
5402
+ readAsMeant(prev, cwd);
3187
5403
  // A step always restores into this theme, whatever name it holds.
3188
5404
  prev.name = theme;
3189
5405
  // What the step's build showed is restored with it, not saved as a
@@ -3278,8 +5494,10 @@ export async function themeEditUndo(theme, options = {}) {
3278
5494
  undone.push(
3279
5495
  `base ${current.like ?? 'none'} is back to ${prev.like ?? 'none'}`,
3280
5496
  );
3281
- if (current && current.mode !== prev.mode)
5497
+ if (current && current.mode !== prev.mode) {
3282
5498
  undone.push(`mode ${current.mode} is back to ${prev.mode}`);
5499
+ undone.push(...modeWiringNotes(cwd, theme, current.mode, prev.mode));
5500
+ }
3283
5501
  // The page most about what the step reverted: Colors for a color,
3284
5502
  // Components for a part setting, else Overview.
3285
5503
  const touched = [
@@ -3291,7 +5509,7 @@ export async function themeEditUndo(theme, options = {}) {
3291
5509
  : touched.includes('components')
3292
5510
  ? 'components'
3293
5511
  : 'overview';
3294
- const p = await previewAndRoute(ctx, theme, prev, png, focus);
5512
+ const p = await previewAndRoute(ctx, theme, prev, png, focus, 'undo');
3295
5513
  return {
3296
5514
  type: 'themeEdit.undo',
3297
5515
  data: {
@@ -3320,3 +5538,14 @@ export async function editorStale(cwd, slug) {
3320
5538
  const data = loadTheme(cwd, slug);
3321
5539
  return staleBuild(cwd, slug, data) || null;
3322
5540
  }
5541
+
5542
+ /**
5543
+ * The notes the last build of the theme left (settings it could not write
5544
+ * as they are).
5545
+ * @param {unknown} ctx
5546
+ * @returns {string[]}
5547
+ */
5548
+ function buildNotes(ctx) {
5549
+ const notes = /** @type {{compileNotes?: unknown}} */ (ctx)?.compileNotes;
5550
+ return Array.isArray(notes) ? notes.map(String) : [];
5551
+ }