@astryxdesign/cli 0.7.16 → 0.7.17-canary.g335a172

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 (339) 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.mjs +69 -16
  13. package/api/build/kit/start.d.mts +5 -4
  14. package/api/build/kit/start.mjs +12 -8
  15. package/api/build/kit/weights.d.mts +16 -3
  16. package/api/build/kit/weights.json +1 -1
  17. package/api/build/kit/weights.mjs +251 -35
  18. package/api/build/kit/word-model.d.mts +23 -0
  19. package/api/build/kit/word-model.mjs +46 -0
  20. package/api/build/kit/words.d.mts +48 -0
  21. package/api/build/kit/words.mjs +90 -1
  22. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  23. package/api/component/list/list.d.mts +1 -1
  24. package/api/component/list/list.mjs +48 -6
  25. package/api/discover/_adapter.d.mts +1 -1
  26. package/api/discover/search/search.mjs +3 -2
  27. package/api/docs/_adapter.d.mts +26 -2
  28. package/api/docs/_adapter.mjs +219 -6
  29. package/api/docs/docs.d.mts +3 -0
  30. package/api/docs/docs.doc.mjs +7 -1
  31. package/api/docs/docs.mjs +12 -0
  32. package/api/docs/docs.type.d.mts +5 -0
  33. package/api/docs/docs.type.mjs +2 -0
  34. package/api/docs/node/node.mjs +1 -1
  35. package/api/doctor/_adapter.d.mts +27 -5
  36. package/api/doctor/_adapter.mjs +83 -10
  37. package/api/doctor/built-checks.mjs +40 -14
  38. package/api/doctor/doctor.d.mts +4 -3
  39. package/api/doctor/doctor.mjs +14 -7
  40. package/api/doctor/theme-checks.mjs +121 -17
  41. package/api/icon/_records.mjs +2 -1
  42. package/api/index.d.mts +2 -0
  43. package/api/index.mjs +2 -0
  44. package/api/integration/_adapter.d.mts +44 -0
  45. package/api/integration/_adapter.mjs +77 -1
  46. package/api/integration/authoring-checks.mjs +6 -6
  47. package/api/integration/example-scope.d.mts +14 -0
  48. package/api/integration/example-scope.mjs +44 -0
  49. package/api/integration/example-scope.type.d.mts +29 -0
  50. package/api/integration/example-scope.type.mjs +25 -0
  51. package/api/integration/integrationExampleScope.doc.d.mts +11 -0
  52. package/api/integration/integrationExampleScope.doc.mjs +59 -0
  53. package/api/integration/validate-integration.mjs +19 -1
  54. package/api/integration/validate-integration.type.d.mts +9 -0
  55. package/api/integration/validate-integration.type.mjs +1 -1
  56. package/api/integration/validateIntegration.doc.mjs +1 -1
  57. package/api/render/_adapter.mjs +591 -195
  58. package/api/render/render.doc.mjs +11 -3
  59. package/api/render/render.type.d.mts +52 -0
  60. package/api/render/render.type.mjs +31 -1
  61. package/api/search/ORDERING.md +1 -1
  62. package/api/search/_candidate-score.mjs +51 -32
  63. package/api/search/_fit-order.mjs +3 -3
  64. package/api/search/_gather-components.d.mts +3 -2
  65. package/api/search/_gather-components.mjs +12 -3
  66. package/api/search/_lexical.d.mts +5 -0
  67. package/api/search/_lexical.mjs +8 -2
  68. package/api/search/_result.d.mts +11 -9
  69. package/api/search/_result.mjs +4 -4
  70. package/api/search/_score.d.mts +6 -1
  71. package/api/search/_score.mjs +15 -3
  72. package/api/search/search-index.mjs +7 -1
  73. package/api/search/search.d.mts +1 -1
  74. package/api/theme/_adapter.mjs +12 -1
  75. package/api/theme/build/build.d.mts +60 -0
  76. package/api/theme/build/build.mjs +210 -54
  77. package/api/theme/build/font-warning.d.mts +8 -0
  78. package/api/theme/build/font-warning.mjs +19 -0
  79. package/api/theme/theme.type.d.mts +10 -0
  80. package/api/theme/theme.type.mjs +7 -1
  81. package/api/theme-edit/_adapter.d.mts +55 -0
  82. package/api/theme-edit/_adapter.mjs +673 -42
  83. package/api/theme-edit/_check.d.mts +28 -22
  84. package/api/theme-edit/_check.mjs +1858 -312
  85. package/api/theme-edit/_color.d.mts +10 -0
  86. package/api/theme-edit/_color.mjs +49 -1
  87. package/api/theme-edit/_compiler.mjs +9 -0
  88. package/api/theme-edit/_context.mjs +60 -3
  89. package/api/theme-edit/_css.mjs +21 -1
  90. package/api/theme-edit/_edit.d.mts +22 -0
  91. package/api/theme-edit/_edit.mjs +1533 -92
  92. package/api/theme-edit/_how-commands.d.mts +57 -0
  93. package/api/theme-edit/_how-commands.mjs +587 -1
  94. package/api/theme-edit/_how-question.d.mts +78 -0
  95. package/api/theme-edit/_how-question.mjs +4716 -235
  96. package/api/theme-edit/_how.mjs +134 -8
  97. package/api/theme-edit/_marks.d.mts +31 -5
  98. package/api/theme-edit/_marks.mjs +57 -5
  99. package/api/theme-edit/_normal.d.mts +219 -0
  100. package/api/theme-edit/_normal.mjs +1041 -0
  101. package/api/theme-edit/_palette.mjs +10 -4
  102. package/api/theme-edit/_parts.d.mts +8 -0
  103. package/api/theme-edit/_parts.mjs +103 -2
  104. package/api/theme-edit/_playwright-picture.d.mts +4 -0
  105. package/api/theme-edit/_playwright-picture.mjs +34 -0
  106. package/api/theme-edit/_preview-app.d.mts +7 -1
  107. package/api/theme-edit/_preview-app.mjs +394 -74
  108. package/api/theme-edit/_preview.d.mts +69 -8
  109. package/api/theme-edit/_preview.mjs +531 -108
  110. package/api/theme-edit/_settings.d.mts +243 -6
  111. package/api/theme-edit/_settings.mjs +2415 -147
  112. package/api/theme-edit/_tables.d.mts +6 -0
  113. package/api/theme-edit/_tables.mjs +44 -1
  114. package/api/theme-edit/_vet.d.mts +18 -0
  115. package/api/theme-edit/_vet.mjs +32 -0
  116. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  117. package/api/theme-edit/theme-edit.type.mjs +4 -1
  118. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  119. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  120. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  121. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  122. package/api/upgrade/run/run.mjs +4 -3
  123. package/assets/codemods/integration-discovery.mjs +2 -1
  124. package/assets/codemods/run-codemod.mjs +87 -7
  125. package/assets/codemods/transforms/next/index.mjs +11 -1
  126. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  127. package/assets/component-list.generated.json +1 -0
  128. package/assets/docs/author-a-theme.doc.mjs +1 -0
  129. package/assets/docs/theme.doc.dense.mjs +2 -2
  130. package/assets/docs/theme.doc.mjs +1 -1
  131. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  132. package/assets/docs/tree/checks.doc.mjs +1 -1
  133. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  134. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  135. package/assets/docs/tree/single-component.doc.mjs +4 -0
  136. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  137. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  138. package/assets/docs/use-a-theme.doc.mjs +1 -1
  139. package/assets/docs.generated.json +2 -2
  140. package/assets/self-audit.generated.json +1 -1
  141. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  142. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  143. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  144. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  145. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  146. package/assets/templates/components.generated.json +1 -1
  147. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  148. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  149. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  150. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  151. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  152. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  153. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  154. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  155. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  156. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  157. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  158. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  159. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  160. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  161. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  162. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  163. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  164. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  165. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  166. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  167. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  168. package/assets/templates/pages/ide/page.tsx +24 -2
  169. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  170. package/assets/templates/pages/library/template.doc.mjs +4 -1
  171. package/assets/templates/pages/login/template.doc.mjs +2 -1
  172. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  173. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  174. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  175. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  176. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  177. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  178. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  179. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  180. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  181. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  182. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  183. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  184. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  185. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  186. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  187. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  188. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  189. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  190. package/assets/theme.template.ts +6 -0
  191. package/authoring/debug/parse.d.mts +3 -3
  192. package/authoring/doctypes/_schema.d.mts +3 -3
  193. package/authoring/doctypes/command/command.doc.mjs +1 -1
  194. package/authoring/doctypes/component/categories.d.mts +37 -0
  195. package/authoring/doctypes/component/categories.mjs +54 -0
  196. package/authoring/doctypes/template/template.doc.mjs +1 -1
  197. package/authoring/doctypes/template/type.ts +9 -0
  198. package/authoring/example/example.doc.d.mts +12 -0
  199. package/authoring/example/example.doc.mjs +69 -0
  200. package/authoring/example/preview.d.mts +92 -0
  201. package/authoring/example/preview.mjs +994 -0
  202. package/authoring/example/type.ts +102 -0
  203. package/authoring/index.d.mts +1 -0
  204. package/authoring/index.d.ts +12 -0
  205. package/authoring/index.mjs +3 -1
  206. package/clients/cli/bin/astryx.mjs +6 -9
  207. package/clients/cli/build-id.generated.json +1 -1
  208. package/clients/cli/commands/component.doc.mjs +1 -1
  209. package/clients/cli/commands/component.mjs +22 -3
  210. package/clients/cli/commands/docs.doc.mjs +7 -1
  211. package/clients/cli/commands/docs.mjs +3 -1
  212. package/clients/cli/commands/doctor.mjs +32 -14
  213. package/clients/cli/commands/experimental/render.mjs +42 -1
  214. package/clients/cli/commands/experimental/theme.mjs +145 -16
  215. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  216. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  217. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  218. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  219. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  220. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  221. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  222. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  223. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  224. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  225. package/clients/cli/commands/search.doc.mjs +2 -1
  226. package/clients/cli/commands/search.mjs +6 -1
  227. package/clients/cli/commands/template.mjs +4 -2
  228. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  229. package/clients/cli/commands/theme.doc.mjs +1 -1
  230. package/clients/cli/commands/theme.mjs +183 -6
  231. package/clients/cli/commands/upgrade.mjs +42 -7
  232. package/clients/cli/index.mjs +1 -1
  233. package/clients/cli/lib/cli-error.mjs +2 -1
  234. package/clients/cli/lib/component-format.mjs +205 -98
  235. package/clients/cli/lib/hook-format.mjs +9 -19
  236. package/clients/cli/lib/json-shim.mjs +77 -21
  237. package/clients/cli/lib/manifest.mjs +3 -2
  238. package/clients/cli/manifest.generated.json +1 -1
  239. package/foundation/agent-docs/agent-docs.mjs +1 -1
  240. package/foundation/config/theme-state.d.mts +13 -1
  241. package/foundation/config/theme-state.mjs +47 -7
  242. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  243. package/foundation/discovery/component-discovery.d.mts +11 -0
  244. package/foundation/discovery/component-discovery.mjs +56 -8
  245. package/foundation/discovery/component-replacement.mjs +130 -1
  246. package/foundation/discovery/copied-passages.mjs +2 -1
  247. package/foundation/discovery/doc-types.mjs +4 -3
  248. package/foundation/discovery/entry-name-files.d.mts +43 -0
  249. package/foundation/discovery/entry-name-files.mjs +264 -0
  250. package/foundation/discovery/hook-discovery.d.mts +8 -2
  251. package/foundation/discovery/hook-discovery.mjs +22 -8
  252. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  253. package/foundation/discovery/icon-set-checks.mjs +2 -1
  254. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  255. package/foundation/discovery/integration-doc-files.mjs +2 -1
  256. package/foundation/discovery/package-exports.d.mts +10 -0
  257. package/foundation/discovery/package-exports.mjs +56 -3
  258. package/foundation/discovery/prop-drift.mjs +9 -9
  259. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  260. package/foundation/discovery/runner-allowlist.mjs +2 -0
  261. package/foundation/discovery/stored-component-list.d.mts +43 -0
  262. package/foundation/discovery/stored-component-list.mjs +90 -0
  263. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  264. package/foundation/discovery/stored-self-audit.mjs +38 -18
  265. package/foundation/discovery/template-adapter.d.mts +52 -0
  266. package/foundation/discovery/template-adapter.mjs +176 -12
  267. package/foundation/discovery/template-icons.mjs +2 -1
  268. package/foundation/discovery/theme-discovery.mjs +3 -2
  269. package/foundation/discovery/theme-imports.d.mts +14 -0
  270. package/foundation/discovery/theme-imports.mjs +43 -1
  271. package/foundation/discovery/theming-targets.mjs +3 -2
  272. package/foundation/doc-compiler/import.mjs +7 -1
  273. package/foundation/doc-compiler/inputs.mjs +3 -2
  274. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  275. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  276. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  277. package/foundation/env/semver.mjs +3 -1
  278. package/foundation/fonts/font-stylesheet.d.mts +31 -0
  279. package/foundation/fonts/font-stylesheet.mjs +115 -0
  280. package/foundation/fs/cache-eviction.d.mts +21 -0
  281. package/foundation/fs/cache-eviction.mjs +73 -0
  282. package/foundation/fs/file-protection.mjs +4 -3
  283. package/foundation/fs/gather-cache.d.mts +25 -4
  284. package/foundation/fs/gather-cache.mjs +164 -55
  285. package/foundation/fs/jiti-cache.d.mts +19 -1
  286. package/foundation/fs/jiti-cache.mjs +130 -6
  287. package/foundation/fs/kept-tree.d.mts +60 -0
  288. package/foundation/fs/kept-tree.mjs +154 -0
  289. package/foundation/fs/listing-cache.d.mts +7 -0
  290. package/foundation/fs/listing-cache.mjs +10 -0
  291. package/foundation/fs/module-loader.d.mts +24 -2
  292. package/foundation/fs/module-loader.mjs +94 -21
  293. package/foundation/fs/paths.d.mts +18 -0
  294. package/foundation/fs/paths.mjs +15 -2
  295. package/foundation/identity/provider-identity.d.mts +6 -0
  296. package/foundation/identity/provider-identity.mjs +10 -1
  297. package/foundation/integrations/contribution-inventory.mjs +4 -3
  298. package/foundation/integrations/example-code.d.mts +63 -0
  299. package/foundation/integrations/example-code.mjs +416 -0
  300. package/foundation/integrations/public-imports.d.mts +9 -0
  301. package/foundation/integrations/public-imports.mjs +3 -2
  302. package/foundation/integrations/validate-contributions.mjs +17 -45
  303. package/foundation/render/embedded-files.d.mts +6 -0
  304. package/foundation/render/embedded-files.mjs +25 -5
  305. package/foundation/render/embedded-imports.d.mts +39 -7
  306. package/foundation/render/embedded-imports.mjs +66 -27
  307. package/foundation/render/file-header.d.mts +66 -0
  308. package/foundation/render/file-header.mjs +118 -0
  309. package/foundation/render/host-answer.d.mts +18 -0
  310. package/foundation/render/host-answer.mjs +46 -0
  311. package/foundation/render/host-exit.d.mts +1 -0
  312. package/foundation/render/host-exit.mjs +6 -1
  313. package/foundation/render/html-reader.d.mts +55 -2
  314. package/foundation/render/html-reader.mjs +145 -26
  315. package/foundation/render/markup-edits.d.mts +57 -0
  316. package/foundation/render/markup-edits.mjs +182 -0
  317. package/foundation/render/page-host.mjs +29 -12
  318. package/foundation/render/page-worker.mjs +121 -13
  319. package/foundation/render/rebuild.mjs +2 -1
  320. package/foundation/render/render-page.d.mts +35 -3
  321. package/foundation/render/render-page.mjs +316 -42
  322. package/foundation/render/source-block.d.mts +85 -6
  323. package/foundation/render/source-block.mjs +211 -20
  324. package/foundation/render/ts-paths.d.mts +69 -6
  325. package/foundation/render/ts-paths.mjs +326 -40
  326. package/foundation/response/error-codes.d.mts +3 -1
  327. package/foundation/response/error-codes.d.ts +1 -0
  328. package/foundation/response/error-codes.doc.mjs +12 -1
  329. package/foundation/response/error-codes.mjs +11 -1
  330. package/foundation/response/response-types.doc.mjs +2 -2
  331. package/foundation/text/compare-text.d.mts +14 -0
  332. package/foundation/text/compare-text.mjs +68 -0
  333. package/foundation/text/string-utils.d.mts +3 -2
  334. package/foundation/text/string-utils.mjs +18 -4
  335. package/foundation/text/suggest-order.d.mts +9 -0
  336. package/foundation/text/suggest-order.mjs +15 -1
  337. package/foundation/xle/expand.mjs +2 -1
  338. package/host/index.mjs +8 -6
  339. package/package.json +7 -6
@@ -9,11 +9,18 @@
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
14
  import {coversProperty} 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 {allowedLine, colorPair, withoutCopyDebris} from './_normal.mjs';
17
24
  import {
18
25
  AUTO_SPREAD,
19
26
  CORNERS,
@@ -38,6 +45,8 @@ import {
38
45
  radiusTokenOf,
39
46
  contrastProblems,
40
47
  describe,
48
+ entryDamage,
49
+ entryNotes,
41
50
  keyOf,
42
51
  loadTheme,
43
52
  maskedSettings,
@@ -66,13 +75,18 @@ import {
66
75
  NEW_MARKER,
67
76
  clearNewMarker,
68
77
  refuseThemeSource,
69
- settingsShapeOk,
78
+ settingsEntriesOk,
70
79
  slugFor,
80
+ typedThemeName,
81
+ themeNameReadings,
71
82
  themeSource,
72
83
  themeSourceProblem,
73
84
  refuseThemeParse,
74
85
  ownSourceTokens,
75
86
  ownSourceTokenValues,
87
+ ownTokenEntries,
88
+ evaluatedTheme,
89
+ nonTextMessage,
76
90
  ownPartTokens,
77
91
  PHONE_TYPE,
78
92
  refreshSourceStamp,
@@ -83,16 +97,14 @@ import {
83
97
  refuseLinks,
84
98
  usableNewName,
85
99
  FOLDER_JUNK,
100
+ folderIsEmpty,
86
101
  dialValueFits,
87
102
  holdAfterBuild,
103
+ fieldsMeant,
88
104
  } from './_settings.mjs';
89
- import {
90
- checkSetting,
91
- exampleOf,
92
- normalizeEntry,
93
- storedProblems,
94
- } from './_check.mjs';
95
- import {MODAL} from './_compiler.mjs';
105
+ import {checkSetting, normalizeEntry, storedProblems} from './_check.mjs';
106
+ import {MODAL, isColorToken} from './_compiler.mjs';
107
+ import {colorProblem} from './_color.mjs';
96
108
  import {
97
109
  PALETTE_DIALS,
98
110
  VIBRANCY_DEFAULT,
@@ -105,15 +117,21 @@ import {
105
117
  writeWhole,
106
118
  isGraySeed,
107
119
  seedOf,
120
+ isEditorTemp,
108
121
  } from './_palette.mjs';
109
122
  import {
110
123
  renderPreview,
111
124
  renderSheet,
112
125
  previewIsCurrent,
113
126
  takeFirstAppCopy,
127
+ appCopyBehind,
128
+ appCopyStale,
129
+ copyFontsCss,
114
130
  writeAppCopy,
115
131
  } from './_preview.mjs';
116
132
  import {appWiring, refreshPreviewRoute, seeLine} from './_preview-app.mjs';
133
+ /** The preview command, as a person runs it. */
134
+ const PREVIEW_CMD = `${P.replace(/ editor$/, '')} preview`;
117
135
  import {baseInstalled, baseResolved, installLine} from './_project.mjs';
118
136
  import {reactMissing} from './_parts.mjs';
119
137
  import {
@@ -129,6 +147,7 @@ import {
129
147
  } from './_context.mjs';
130
148
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
131
149
  import {
150
+ formatCliCommand,
132
151
  getCliInvocation,
133
152
  quoteCommandArgument,
134
153
  } from '../../foundation/env/package-manager.mjs';
@@ -171,12 +190,11 @@ function editorLeftovers(dir, slug, damaged = false) {
171
190
  const named = (/** @type {string} */ n) =>
172
191
  n === NEW_MARKER ||
173
192
  EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
174
- /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config\.json)$/.test(
193
+ /^(preview(-dark)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config\.json)$/.test(
175
194
  n,
176
195
  ) ||
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);
196
+ // The editor's temp names (writes, builds, pictures).
197
+ isEditorTemp(n);
180
198
  for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
181
199
  const p = path.join(dir, e.name);
182
200
  if (FOLDER_JUNK.has(e.name)) continue;
@@ -209,7 +227,9 @@ function editorLeftovers(dir, slug, damaged = false) {
209
227
  /** Whether a settings file parses, in the shape the editor reads. @param {string} file */
210
228
  function readableJson(file) {
211
229
  try {
212
- return settingsShapeOk(
230
+ // An entry with no thing or no source is damage too: `new` keeps the
231
+ // file aside, as the refusal for it says.
232
+ return settingsEntriesOk(
213
233
  JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')),
214
234
  );
215
235
  } catch {
@@ -346,10 +366,20 @@ export async function themeEditNew(name, options = {}) {
346
366
  /** @type {string | null | undefined} */ likeValue = likeFixed,
347
367
  ) => `${P} new ${newName}${newFlags(likeValue, fitSettings, png)}`;
348
368
  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);
369
+ // A path typed for the name (themes/brand, ./t, t/) names the theme the
370
+ // path ends in.
371
+ // A file name, the app copy's export (tTheme), camelCase or spaces
372
+ // (BrandDark, "Brand Dark") name the theme they read as: when it is
373
+ // here already, that is said, never a numbered second copy offered.
374
+ const typed = String(name ?? '');
375
+ const path_ = /[\\/]/.test(typed);
376
+ const readings = themeNameReadings(typed);
377
+ const present = readings.find(n =>
378
+ fs.existsSync(themeFiles(cwd, n).settings),
379
+ );
380
+ const fixed =
381
+ present ?? readings[0] ?? slugFor(path_ ? typedThemeName(typed) : typed);
382
+ const exists = Boolean(present);
353
383
  refuse(
354
384
  E.ERR_INVALID_ARGUMENT,
355
385
  `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE})${exists ? `; ${fixed} is a theme here already` : ''}.${dropped}`,
@@ -360,6 +390,16 @@ export async function themeEditNew(name, options = {}) {
360
390
  },
361
391
  );
362
392
  }
393
+ // A name the theme commands' own discovery skips ("a--b", "b-") would
394
+ // make an app copy no `theme add`, `theme list` or doctor takes.
395
+ if (!THEME_SLUG_RE.test(name)) {
396
+ const cleaned = name.replace(/-{2,}/g, '-').replace(/-+$/, '');
397
+ refuse(
398
+ E.ERR_INVALID_ARGUMENT,
399
+ `"${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}`,
400
+ {run: [again(usableNewName(cwd, cleaned))]},
401
+ );
402
+ }
363
403
  // A built-in theme's name would collide with the theme of that name the
364
404
  // app may also use.
365
405
  if (LIKE.includes(name))
@@ -426,7 +466,8 @@ export async function themeEditNew(name, options = {}) {
426
466
  const holdsOther =
427
467
  fs.existsSync(f.dir) &&
428
468
  !left &&
429
- fs.readdirSync(f.dir).some(n => !FOLDER_JUNK.has(n));
469
+ // Empty folders (an empty tokens/) hold nothing of anyone's.
470
+ !folderIsEmpty(f.dir);
430
471
  if (holdsOther)
431
472
  refuse(
432
473
  E.ERR_FILE_EXISTS,
@@ -469,6 +510,18 @@ export async function themeEditNew(name, options = {}) {
469
510
  // Every check comes before the first change to the folder: the settings,
470
511
  // and a source of the user's own kept from before (it must still extend
471
512
  // the settings, or the build fails after the folder was cleared).
513
+ try {
514
+ applyNewSettings(
515
+ ctx,
516
+ name,
517
+ structuredClone(data),
518
+ settings,
519
+ png,
520
+ likeFixed ?? undefined,
521
+ );
522
+ } catch (e) {
523
+ throw await followNewLine(e, ctx, name, data);
524
+ }
472
525
  applyNewSettings(ctx, name, data, settings, png, likeFixed ?? undefined);
473
526
  if (left?.keep.some(p => path.basename(p) === `${name}.theme.ts`))
474
527
  refuseThemeSource(cwd, name);
@@ -576,7 +629,7 @@ export async function themeEditNew(name, options = {}) {
576
629
  }
577
630
  refuseIfLockLost();
578
631
  fs.rmSync(marker, {force: true});
579
- const p = await previewAndRoute(ctx, name, data, png);
632
+ const p = await previewAndRoute(ctx, name, data, png, 'overview', 'new');
580
633
  /** @type {string[]} */
581
634
  const notes = [
582
635
  ...keptNotes,
@@ -610,6 +663,77 @@ export async function themeEditNew(name, options = {}) {
610
663
  };
611
664
  }
612
665
 
666
+ /**
667
+ * A refused `new` whose suggestions include another `new` of the theme:
668
+ * that line is checked as `new` checks its dial flags (in memory, nothing
669
+ * written), and each repair a refusal of it offers is folded in, so the one
670
+ * line fixes or drops every bad flag. It comes first.
671
+ * @param {unknown} e
672
+ * @param {import('./_settings.mjs').Ctx} ctx
673
+ * @param {string} slug
674
+ * @param {import('./_settings.mjs').ThemeData} data the theme before any dial
675
+ * @returns {Promise<unknown>}
676
+ */
677
+ async function followNewLine(e, ctx, slug, data) {
678
+ if (!(e instanceof AstryxError)) return e;
679
+ const prefix = `${P} new ${slug}`;
680
+ const isNew = (/** @type {string} */ n) =>
681
+ n === prefix || n.startsWith(`${prefix} `);
682
+ const first = (e.suggestions ?? []).find(x => isNew(x.name));
683
+ if (!first) return e;
684
+ const followed = await followLine(
685
+ first.name,
686
+ line => {
687
+ const args = splitCommand(line.slice(prefix.length));
688
+ if (!args) return null;
689
+ /** @type {Record<string, string | string[]>} */
690
+ const settings = {};
691
+ /** @type {string | undefined} */
692
+ let like;
693
+ let png = false;
694
+ for (let j = 0; j < args.length; j += 1) {
695
+ const m = /^--([a-z-]+)$/.exec(args[j]);
696
+ if (m?.[1] === 'png') png = true;
697
+ else if (m && args[j + 1] != null) {
698
+ const v = args[(j += 1)];
699
+ if (m[1] === 'like') like = v;
700
+ else {
701
+ const had = settings[m[1]];
702
+ settings[m[1]] = had == null ? v : [...[had].flat(), v];
703
+ }
704
+ } else return null;
705
+ }
706
+ try {
707
+ applyNewSettings(
708
+ ctx,
709
+ slug,
710
+ structuredClone(data),
711
+ settings,
712
+ png,
713
+ like ?? data.like,
714
+ );
715
+ return null;
716
+ } catch (again) {
717
+ if (again instanceof AstryxError) return again;
718
+ throw again;
719
+ }
720
+ },
721
+ isNew,
722
+ );
723
+ if (followed.line === first.name) return e;
724
+ e.suggestions = [
725
+ {
726
+ ...first,
727
+ name: followed.line,
728
+ reason: `do this instead: every flag fixed${followed.why ? `, but this still needs a fix: ${followed.why}` : ''}`,
729
+ },
730
+ ...(e.suggestions ?? []).filter(
731
+ x => x !== first && x.name !== followed.line,
732
+ ),
733
+ ];
734
+ return e;
735
+ }
736
+
613
737
  /**
614
738
  * The dial settings of `new`, checked one at a time in dial order (mode
615
739
  * first; a color before vibrancy, which needs one) into `data`.
@@ -655,15 +779,34 @@ function applyNewSettings(
655
779
  /** @type {import('./_settings.mjs').Setting} */
656
780
  let s;
657
781
  try {
658
- s = checkSetting(ctx, slug, data, thing, String(value), {}, false);
782
+ // The same input cleanup set gives a typed value (quotes of any
783
+ // kind around a font, invisible spaces, a pasted `name: value`).
784
+ const typed = normalizeEntry(thing, String(value)).value;
785
+ s = checkSetting(
786
+ ctx,
787
+ slug,
788
+ data,
789
+ thing,
790
+ typed ?? String(value),
791
+ {},
792
+ false,
793
+ );
659
794
  } catch (e) {
660
- throw asNewRefusal(
661
- vetSuggestions(e, ctx, slug, data),
795
+ throw newColorPair(
796
+ asNewRefusal(
797
+ vetSuggestions(e, ctx, slug, data),
798
+ slug,
799
+ settings,
800
+ likeFlag,
801
+ png,
802
+ {thing, index},
803
+ ),
662
804
  slug,
663
805
  settings,
664
806
  likeFlag,
665
807
  png,
666
- {thing, index},
808
+ thing,
809
+ String(value),
667
810
  );
668
811
  }
669
812
  if (thing === 'mode')
@@ -771,6 +914,81 @@ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
771
914
  return e;
772
915
  }
773
916
 
917
+ /**
918
+ * A color dial on `new` given a light and a dark color ("light #111111 dark
919
+ * #eeeeee"): the refusal offers the user's own colors, per mode, as set
920
+ * does, never a stock color they did not type.
921
+ * @param {unknown} e
922
+ * @param {string} slug
923
+ * @param {Record<string, any>} settings
924
+ * @param {string | undefined} like
925
+ * @param {boolean} png
926
+ * @param {string} thing
927
+ * @param {string} typed
928
+ */
929
+ function newColorPair(e, slug, settings, like, png, thing, typed) {
930
+ if (!(e instanceof AstryxError) || !PALETTE_DIALS.includes(thing)) return e;
931
+ const typedLower = typed.toLowerCase();
932
+ // A color in a line the user did not type (a stock example) goes.
933
+ e.suggestions = (e.suggestions ?? []).filter(x => {
934
+ if (!x.name.startsWith(`${P} new `)) return true;
935
+ const m = new RegExp(`--${thing} '?(#[0-9a-f]{3,8})'?`, 'i').exec(x.name);
936
+ return !m || typedLower.includes(m[1].toLowerCase());
937
+ });
938
+ // With every color line gone, the same new without that color, every
939
+ // other option kept.
940
+ if (!e.suggestions.some(x => x.name.startsWith(`${P} new `)))
941
+ e.suggestions.push({
942
+ name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: undefined}, png)}`,
943
+ reason: `without --${thing} ${quoteCommandArgument(typed)}`,
944
+ });
945
+ /** @type {Record<string, string>} */
946
+ const pair = {};
947
+ for (const m of typed.matchAll(
948
+ /\b(light|dark)\b\s*(?:mode\s*)?[:=]?\s*(#[0-9a-f]{3,8}\b|[a-z]+\([^)]*\)|[a-z]+)/gi,
949
+ ))
950
+ pair[m[1].toLowerCase()] = m[2];
951
+ if (!pair.light && !pair.dark) return e;
952
+ const mode = String(
953
+ Array.isArray(settings.mode) ? settings.mode[0] : (settings.mode ?? 'both'),
954
+ );
955
+ /** @type {Array<{name: string, reason: string}>} */
956
+ const lines = [];
957
+ /** @param {string} color @param {string} reason @param {Record<string, any>} [extra] */
958
+ const line = (color, reason, extra = {}) =>
959
+ lines.push({
960
+ name: `${P} new ${slug}${newFlags(like, {...settings, ...extra, [thing]: color}, png)}`,
961
+ reason,
962
+ });
963
+ if (mode === 'dark-only' && pair.dark)
964
+ line(pair.dark, 'do this instead: the dark color you gave');
965
+ else if (mode === 'light-only' && pair.light)
966
+ line(pair.light, 'do this instead: the light color you gave');
967
+ else if (mode === 'both') {
968
+ if (pair.light)
969
+ line(
970
+ pair.light,
971
+ `the light color you gave; then set ${slug} --color-${thing} ${pair.dark ?? '…'} --mode dark for the dark one`,
972
+ );
973
+ if (pair.dark)
974
+ line(pair.dark, 'or a dark-only theme with the dark color you gave', {
975
+ mode: 'dark-only',
976
+ });
977
+ }
978
+ // No color for the mode the theme has: how the dial works, and the
979
+ // same new without it, never a color made up.
980
+ if (!lines.length)
981
+ lines.push({
982
+ name: `${P} how ${thing}`,
983
+ reason: `no ${mode === 'light-only' ? 'light' : 'dark'} color was given for this ${mode} theme`,
984
+ });
985
+ e.suggestions = [
986
+ ...lines,
987
+ ...(e.suggestions ?? []).filter(x => !lines.some(l => l.name === x.name)),
988
+ ];
989
+ return e;
990
+ }
991
+
774
992
  /**
775
993
  * Headings values with every later value for an axis already given left
776
994
  * out (the first weight and the first tracking stay); a word of neither
@@ -822,6 +1040,32 @@ function changeFocus(s) {
822
1040
  return 'overview';
823
1041
  }
824
1042
 
1043
+ /**
1044
+ * A signal handler for the checks and pictures after a change is saved: it
1045
+ * says what is saved (in the words of the command that ran) and how to run
1046
+ * what did not, with the project's own CLI invocation, then lets the
1047
+ * signal end the process (the render's own handler re-raises it; with none,
1048
+ * this one does).
1049
+ * @param {string} slug
1050
+ * @param {'set' | 'undo' | 'new'} [kind] the command that saved
1051
+ * @param {string} [cwd] the project, for the CLI invocation
1052
+ * @returns {(sig: NodeJS.Signals) => void}
1053
+ */
1054
+ export function stoppedAfterSave(slug, kind = 'set', cwd = process.cwd()) {
1055
+ const done =
1056
+ kind === 'undo'
1057
+ ? `the undo is done: ${slug} is saved and built as it was before that change`
1058
+ : kind === 'new'
1059
+ ? `${slug} is made and built`
1060
+ : `the change to ${slug} is saved and built (and its undo step kept)`;
1061
+ return sig => {
1062
+ process.stderr.write(
1063
+ `Stopped: ${done}; its checks and pictures did not run. ${formatCliCommand(`${P} show ${slug}`, cwd)} runs them.\n`,
1064
+ );
1065
+ if (process.listenerCount(sig) === 0) process.kill(process.pid, sig);
1066
+ };
1067
+ }
1068
+
825
1069
  /**
826
1070
  * The preview after a change, with the in-app preview route kept in step:
827
1071
  * its imports follow the theme, such as the stylesheet of a font package
@@ -832,13 +1076,34 @@ function changeFocus(s) {
832
1076
  * @param {boolean} png
833
1077
  * @param {'colors' | 'components' | 'overview'} [focus] the preview page
834
1078
  * most about the change: Colors for a color, Components for a part
1079
+ * @param {'set' | 'undo' | 'new'} [kind] the command that saved
835
1080
  */
836
- async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
837
- const p = await previewAfter(ctx, slug, data, png);
1081
+ async function previewAndRoute(
1082
+ ctx,
1083
+ slug,
1084
+ data,
1085
+ png,
1086
+ focus = 'overview',
1087
+ kind = /** @type {'set' | 'undo' | 'new'} */ ('set'),
1088
+ ) {
1089
+ // Stopped (Ctrl-C) while the checks and pictures run: the change is saved
1090
+ // and built already, which one line says before the process ends.
1091
+ const stopped = stoppedAfterSave(slug, kind, ctx.project.cwd);
1092
+ process.once('SIGINT', stopped);
1093
+ process.once('SIGTERM', stopped);
1094
+ /** @type {Awaited<ReturnType<typeof previewAfter>>} */
1095
+ let p;
1096
+ try {
1097
+ p = await previewAfter(ctx, slug, data, png);
1098
+ } finally {
1099
+ process.removeListener('SIGINT', stopped);
1100
+ process.removeListener('SIGTERM', stopped);
1101
+ }
838
1102
  const wrote = takeFirstAppCopy(ctx.project.cwd, slug);
1103
+ const previewStale = await keepPreviewRoute(ctx, slug);
839
1104
  return {
840
1105
  ...p,
841
- previewStale: await keepPreviewRoute(ctx, slug),
1106
+ previewStale,
842
1107
  // How to see the change: the page about it, at its own URL.
843
1108
  // A page not written this time (preview null) still shows the theme
844
1109
  // as it was; checks that failed with the page written do not.
@@ -852,9 +1117,18 @@ async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
852
1117
  cause: 'no preview was rendered',
853
1118
  })
854
1119
  : null,
1120
+ {
1121
+ // Only a run that took no picture failed: a note on pictures that
1122
+ // were taken (cut to 2400 pixels, adopted) is not a failure.
1123
+ pictureProblem:
1124
+ png && !(p.pictures ?? []).length ? p.pictureProblem : null,
1125
+ stale: previewStale,
1126
+ },
855
1127
  ),
856
1128
  // The first time the theme's app copy is written, its files are named.
857
1129
  ...(wrote ? {appCopy: {wrote}} : {}),
1130
+ // A copy a file of yours kept from being written: said, never a quiet ok.
1131
+ ...appCopyStale(ctx.project.cwd, slug),
858
1132
  };
859
1133
  }
860
1134
 
@@ -870,12 +1144,48 @@ async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
870
1144
  async function keepPreviewRoute(ctx, slug) {
871
1145
  try {
872
1146
  return (await refreshPreviewRoute(ctx.project.cwd, slug)).stale;
873
- } catch {
874
- // A damaged or moved preview.
1147
+ } catch (e) {
1148
+ // A route that could not be written (its permissions, a folder in its
1149
+ // place) does not follow this change: said, never a quiet ok. A
1150
+ // damaged preview record is named by the preview commands themselves.
1151
+ const code = /** @type {any} */ (e)?.code;
1152
+ if (code && /^E[A-Z]+$/.test(code)) {
1153
+ const where = /** @type {any} */ (e)?.path;
1154
+ return [
1155
+ `${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`,
1156
+ ];
1157
+ }
875
1158
  return [];
876
1159
  }
877
1160
  }
878
1161
 
1162
+ /**
1163
+ * What a change of mode asks of the app's wiring: a one-mode theme is
1164
+ * given its mode by the app's <Theme>, and one back to both modes no longer.
1165
+ * @param {string} slug
1166
+ * @param {string | undefined} before
1167
+ * @param {string | undefined} after
1168
+ * @returns {string[]}
1169
+ */
1170
+ function modeWiringNotes(slug, before, after) {
1171
+ const one = (/** @type {string | undefined} */ m) =>
1172
+ m === 'light-only' ? 'light' : m === 'dark-only' ? 'dark' : null;
1173
+ const [was, now] = [one(before), one(after)];
1174
+ if (was === now) return [];
1175
+ return [
1176
+ ...(was
1177
+ ? [
1178
+ `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`,
1179
+ ]
1180
+ : []),
1181
+ ...(now && !was
1182
+ ? [
1183
+ `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`,
1184
+ ]
1185
+ : []),
1186
+ ];
1187
+ }
1188
+
879
1189
  /**
880
1190
  * Change one thing in a theme: checked, built, previewed.
881
1191
  * @experimental
@@ -886,7 +1196,61 @@ async function keepPreviewRoute(ctx, slug) {
886
1196
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
887
1197
  */
888
1198
  export async function themeEditSet(theme, thing, value, options = {}) {
889
- return change('set', theme, thing, value, options);
1199
+ try {
1200
+ return await change('set', theme, thing, value, options);
1201
+ } catch (e) {
1202
+ throw await swappedOrder(e, 'set', [theme, thing, value], options);
1203
+ }
1204
+ }
1205
+
1206
+ /**
1207
+ * A refused theme name when the theme was typed after the setting (`set
1208
+ * --color-accent '#123457' t`): the same command with the theme first,
1209
+ * checked by that command, comes first, and no `new` of the setting's name
1210
+ * is offered.
1211
+ * @param {unknown} e
1212
+ * @param {'set' | 'undo'} sub
1213
+ * @param {Array<string | undefined>} words the positionals as typed
1214
+ * @param {{cwd?: string, on?: string, when?: string, state?: string, mode?: string, only?: boolean}} options
1215
+ * @returns {Promise<unknown>}
1216
+ */
1217
+ async function swappedOrder(e, sub, words, options) {
1218
+ if (
1219
+ !(e instanceof AstryxError) ||
1220
+ (e.code !== E.ERR_INVALID_ARGUMENT && e.code !== E.ERR_UNKNOWN_THEME)
1221
+ )
1222
+ return e;
1223
+ const cwd = options.cwd ?? process.cwd();
1224
+ const [first, ...rest] = words.map(w => (w == null ? '' : String(w)));
1225
+ if (slugOk(first) && fs.existsSync(themeFiles(cwd, first).settings)) return e;
1226
+ const at = rest.findIndex(
1227
+ w => slugOk(w) && fs.existsSync(themeFiles(cwd, w).settings),
1228
+ );
1229
+ if (at < 0) return e;
1230
+ const theme = rest[at];
1231
+ const moved = [first, ...rest.filter((_, i) => i !== at)].filter(
1232
+ w => w !== '',
1233
+ );
1234
+ const flags = [
1235
+ ...(options.on ? ['--on', options.on] : []),
1236
+ ...(options.when ? ['--when', options.when] : []),
1237
+ ...(options.state ? ['--state', options.state] : []),
1238
+ ...(options.mode ? ['--mode', options.mode] : []),
1239
+ ];
1240
+ const line = `${P} ${sub} ${theme} ${[...moved, ...flags]
1241
+ .map(w => quoteCommandArgument(w))
1242
+ .join(' ')}${options.only ? ' --only' : ''}`;
1243
+ const followed = await followChangeLine(sub, theme, line, cwd);
1244
+ e.suggestions = [
1245
+ {
1246
+ name: followed.line,
1247
+ reason: `do this instead: ${theme} is the theme, so it comes first${followed.why ? `, but this still needs a fix: ${followed.why}` : ''}`,
1248
+ },
1249
+ ...(e.suggestions ?? []).filter(
1250
+ x => x.name !== followed.line && !x.name.startsWith(`${P} new `),
1251
+ ),
1252
+ ];
1253
+ return e;
890
1254
  }
891
1255
 
892
1256
  /**
@@ -900,9 +1264,46 @@ export async function themeEditSet(theme, thing, value, options = {}) {
900
1264
  function refuseStoredTokens(ctx, slug, data, skip) {
901
1265
  const bad = storedProblems(ctx, slug, data, skip);
902
1266
  if (!bad.length) return;
1267
+ // A repair offers only the value it holds, cleaned: never a stock value
1268
+ // the saved setting did not hold.
1269
+ for (const b of bad) {
1270
+ if (
1271
+ b.fix &&
1272
+ !allowedLine({
1273
+ offered: String(b.fix),
1274
+ typed: String(b.setting.value),
1275
+ thing: b.setting.thing,
1276
+ })
1277
+ )
1278
+ delete b.fix;
1279
+ // A light and a dark color saved as one (`red / blue`) is that pair.
1280
+ const pair =
1281
+ !b.fix && isColorToken(b.setting.thing)
1282
+ ? colorPair(String(b.setting.value))
1283
+ : null;
1284
+ if (pair && !colorProblem(pair.light) && !colorProblem(pair.dark))
1285
+ b.fix = `light-dark(${pair.light}, ${pair.dark})`;
1286
+ }
903
1287
  const found = bad.length === 1 ? bad[0] : null;
904
1288
  // A clean value is offered only when set takes it, so the line works.
905
1289
  const takes = (/** @type {typeof found} */ b) => {
1290
+ if (!b?.fix) return true;
1291
+ // A value whose only fault was curly quotes around it: without them,
1292
+ // when set takes that (`“#e11d48”` is #e11d48).
1293
+ const bare = /^(["'])(.*)\1$/.exec(b.fix)?.[2];
1294
+ if (
1295
+ bare &&
1296
+ b.setting.source === 'token' &&
1297
+ !/font|content/.test(b.setting.thing)
1298
+ ) {
1299
+ const was = b.fix;
1300
+ b.fix = bare;
1301
+ if (takesOne(b)) return true;
1302
+ b.fix = was;
1303
+ }
1304
+ return takesOne(b);
1305
+ };
1306
+ const takesOne = (/** @type {typeof found} */ b) => {
906
1307
  if (!b?.fix) return true;
907
1308
  try {
908
1309
  checkSetting(
@@ -941,13 +1342,14 @@ function refuseStoredTokens(ctx, slug, data, skip) {
941
1342
  // A value to set only for a token whose stored value has the wrong
942
1343
  // type; any other thing `set` would refuse, or read as a dial.
943
1344
  ...(one &&
1345
+ one.fix &&
944
1346
  !one.scope &&
945
1347
  one.setting.source === 'token' &&
946
1348
  ctx.C.isToken(one.setting.thing)
947
1349
  ? [
948
1350
  // The value the check suggests for this value, else a stock
949
1351
  // 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))}`,
1352
+ `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(String(one.fix))}${one.setting.mode ? ` --mode ${one.setting.mode}` : ''}`,
951
1353
  ]
952
1354
  : one && one.fix && one.setting.source === 'dial'
953
1355
  ? [
@@ -977,6 +1379,305 @@ export async function editorStoredRefusal(root, slug) {
977
1379
  }
978
1380
  }
979
1381
 
1382
+ /**
1383
+ * The token values the theme's own source gives that `set` refuses (a
1384
+ * radius of `banana`, a color of `12px`), each with why and the line of
1385
+ * the file that sets it; checked with the very rules `set` uses.
1386
+ * @param {import('./_settings.mjs').Ctx} ctx
1387
+ * @param {string} slug
1388
+ * @param {import('./_settings.mjs').ThemeData} data
1389
+ * @returns {Promise<Array<{token: string, value: string, why: string, line: number | null, file?: string | null}>>}
1390
+ */
1391
+ async function ownTokenProblems(ctx, slug, data) {
1392
+ const {cwd} = ctx.project;
1393
+ /** @type {Array<{token: string, value: string, why: string, line: number | null, file?: string | null}>} */
1394
+ const out = [];
1395
+ const known = ctx.project.core.tokenDefaults;
1396
+ /** @param {string} token @param {string} value @returns {string | null} */
1397
+ const refused = (token, value) => {
1398
+ try {
1399
+ checkSetting(ctx, slug, {...data, settings: []}, token, value, {});
1400
+ return null;
1401
+ } catch (e) {
1402
+ if (!(e instanceof AstryxError)) throw e;
1403
+ return e.message.replace(/ Nothing was changed\.$/, '');
1404
+ }
1405
+ };
1406
+ /** The file an entry is in, as the project names it; null for the theme file. @param {{file?: string}} e */
1407
+ const fileOf = e => (e.file ? path.relative(cwd, e.file) : null);
1408
+ // Every value is judged as a build made now writes it (an import, an
1409
+ // expression, a spread or a computed key is its evaluated value). The
1410
+ // source is read only to name the file and line that hold each value,
1411
+ // and for the two facts a build erases: a `tokens` key given twice
1412
+ // (JavaScript keeps the last) and a [light, dark] pair with other than
1413
+ // two values (the build drops the rest).
1414
+ const entries = ownTokenEntries(cwd, slug).filter(e => !e.overridden);
1415
+ const built = await evaluatedTheme(ctx, slug);
1416
+ const tokensLine = entries.find(e => e.kind === 'unresolved')?.line ?? null;
1417
+ /** Where the build's value for a token comes from. @param {string} token */
1418
+ const whereOf = token => {
1419
+ const e = entries.find(x => x.token === token);
1420
+ return e ? {line: e.line, file: fileOf(e)} : {line: tokensLine, file: null};
1421
+ };
1422
+ for (const e of entries) {
1423
+ if (e.kind === 'duplicate')
1424
+ out.push({
1425
+ token: 'tokens',
1426
+ value: '',
1427
+ 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`,
1428
+ line: e.line,
1429
+ file: fileOf(e),
1430
+ });
1431
+ else if (
1432
+ e.kind === 'pair' &&
1433
+ e.token &&
1434
+ e.token in known &&
1435
+ (e.halves ?? []).length !== 2
1436
+ ) {
1437
+ const halves = e.halves ?? [];
1438
+ out.push({
1439
+ token: e.token,
1440
+ value: `[${halves.map(h => (h === undefined ? '…' : JSON.stringify(h))).join(', ')}]`,
1441
+ 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'}`,
1442
+ line: e.line,
1443
+ file: fileOf(e),
1444
+ });
1445
+ }
1446
+ }
1447
+ if (!built) return out;
1448
+ const named = new Set(out.map(b => b.token));
1449
+ // A family or size the typography builds is judged with the typography.
1450
+ const typo = entries.filter(e => e.kind === 'typography');
1451
+ const roles = new Set(typo.map(e => e.key.split('.')[0]));
1452
+ /** @param {string} token */
1453
+ const byTypography = token => {
1454
+ const role = /^--font-family-([a-z]+)$/.exec(token)?.[1];
1455
+ if (role)
1456
+ return roles.has(role) || (role === 'heading' && roles.has('body'));
1457
+ return roles.has('scale') && /^--(font-size|text)-/.test(token);
1458
+ };
1459
+ for (const token of built.own.keys()) {
1460
+ if (!(token in known) || named.has(token) || byTypography(token)) continue;
1461
+ const shape = built.shapes.get(token) ?? {kind: 'other'};
1462
+ const at = whereOf(token);
1463
+ if (
1464
+ shape.kind === 'number' ||
1465
+ shape.kind === 'object' ||
1466
+ shape.kind === 'pair'
1467
+ ) {
1468
+ const bad =
1469
+ shape.kind === 'object'
1470
+ ? /** @type {[string, unknown, 'object']} */ ([
1471
+ token,
1472
+ shape.value,
1473
+ 'object',
1474
+ ])
1475
+ : /** @type {[string, unknown]} */ ([
1476
+ token,
1477
+ shape.kind === 'pair' ? shape.halves : shape.value,
1478
+ ]);
1479
+ // A pair of two text values is the light-dark() the build writes,
1480
+ // judged below; any other pair, a number or an object is no text.
1481
+ if (!(
1482
+ shape.kind === 'pair' &&
1483
+ (shape.halves ?? []).every(h => typeof h === 'string')
1484
+ )) {
1485
+ out.push({
1486
+ token,
1487
+ value: '',
1488
+ why: nonTextMessage(ctx, slug, bad),
1489
+ ...at,
1490
+ });
1491
+ continue;
1492
+ }
1493
+ }
1494
+ const value = built.own.get(token);
1495
+ if (value == null) continue;
1496
+ // A pair on a token that is not a color is the pair refusal's.
1497
+ if (/^light-dark\(/i.test(value) && !isColorToken(token)) continue;
1498
+ const why = refused(token, value);
1499
+ if (why) out.push({token, value, why, ...at});
1500
+ }
1501
+ // Typography as the build was given it (each field the source sets, by
1502
+ // its evaluated value), then the families and sizes the build writes.
1503
+ /** @type {Set<string>} */
1504
+ const flagged = new Set();
1505
+ for (const e of typo) {
1506
+ const value = e.key
1507
+ .split('.')
1508
+ .reduce(
1509
+ (/** @type {any} */ o, /** @type {string} */ k) => o?.[k],
1510
+ built.typography,
1511
+ );
1512
+ const why = typographyProblem(e.key, value);
1513
+ if (why) {
1514
+ flagged.add(e.key.split('.')[0]);
1515
+ out.push({
1516
+ token: `typography.${e.key}`,
1517
+ value: value == null ? '' : String(value),
1518
+ why,
1519
+ line: e.line,
1520
+ file: fileOf(e),
1521
+ });
1522
+ }
1523
+ }
1524
+ for (const role of ['body', 'heading', 'code']) {
1525
+ const at = typo.find(e => e.key.startsWith(`${role}.`));
1526
+ if (!at || flagged.has(role)) continue;
1527
+ const token = `--font-family-${role}`;
1528
+ const v = built.tops.get(token);
1529
+ const why = v == null ? null : refused(token, v);
1530
+ if (why && v != null)
1531
+ out.push({
1532
+ token: `typography.${role} (builds ${token})`,
1533
+ value: v,
1534
+ why,
1535
+ line: at.line,
1536
+ file: fileOf(at),
1537
+ });
1538
+ }
1539
+ const scale = typo.find(e => e.key.startsWith('scale.'));
1540
+ if (scale && !flagged.has('scale')) {
1541
+ const broken = [...built.tops].find(
1542
+ ([k, v]) =>
1543
+ /^--font-size-/.test(k) && /NaN|Infinity|^-/.test(String(v ?? '')),
1544
+ );
1545
+ if (broken)
1546
+ out.push({
1547
+ token: `typography.scale (builds ${broken[0]})`,
1548
+ value: String(broken[1]),
1549
+ why: typo.some(e => e.key === 'scale.base')
1550
+ ? 'the type scale builds a size no page can use; the base is a positive number of pixels (such as 16) and the ratio a number above 1 and at most 4'
1551
+ : 'the type scale is given no base, and Core needs one with the ratio: it builds sizes no page can use; add the body size in pixels, such as scale: {base: 16, ratio: …}',
1552
+ line: scale.line,
1553
+ file: fileOf(scale),
1554
+ });
1555
+ }
1556
+ return out;
1557
+ }
1558
+
1559
+ /**
1560
+ * What is wrong with one typography field of a theme's own source, or
1561
+ * null: a family is one family name without quotes (Core quotes it whole)
1562
+ * and with nothing CSS would read as the end of the value; the scale's
1563
+ * ratio is above 1 and at most 4, its base a positive number of pixels.
1564
+ * @param {string} key the dotted field (`body.family`, `scale.ratio`)
1565
+ * @param {unknown} value
1566
+ * @returns {string | null}
1567
+ */
1568
+ function typographyProblem(key, value) {
1569
+ const field = key.split('.').pop();
1570
+ if (field === 'family') {
1571
+ if (typeof value !== 'string')
1572
+ return 'a typography family is a family name in quotes, such as "Inter"';
1573
+ const v = value.trim();
1574
+ if (/[;{}<>]/.test(v))
1575
+ return `"${v}" holds a ; { } < or >, so the CSS writer drops the whole declaration; give the family name alone, such as "Inter"`;
1576
+ const quoted = /^(["'])(.*)\1$/.exec(v);
1577
+ if (quoted)
1578
+ 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]}'`;
1579
+ // Core quotes a family with a space whole, so a list here is one
1580
+ // family by that whole name, which exists nowhere.
1581
+ if (v.includes(','))
1582
+ 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
1583
+ .split(',')[0]
1584
+ .trim()
1585
+ .replace(
1586
+ /^["']|["']$/g,
1587
+ '',
1588
+ )}', fallbacks: '${v.split(',').slice(1).join(',').trim()}'`;
1589
+ if (!v || /^[-+]?\d/.test(v) || /^(inherit|initial|unset|revert)$/i.test(v))
1590
+ return `"${v}" is no font family name; give one such as "Inter"`;
1591
+ return null;
1592
+ }
1593
+ if (field === 'ratio') {
1594
+ const n = Number(value);
1595
+ if (!Number.isFinite(n) || n <= 1 || n > 4)
1596
+ 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'}`;
1597
+ return null;
1598
+ }
1599
+ if (field === 'base') {
1600
+ const n = Number(value);
1601
+ if (!Number.isFinite(n) || n <= 0) {
1602
+ // A size with a unit builds NaNrem: the number of pixels it means.
1603
+ const m = /^\s*([0-9.]+)\s*(px|rem|em)\s*$/i.exec(String(value));
1604
+ const px = m ? Number(m[1]) * (/^r?em$/i.test(m[2]) ? 16 : 1) : null;
1605
+ 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)' : ''}`;
1606
+ }
1607
+ return null;
1608
+ }
1609
+ return null;
1610
+ }
1611
+
1612
+ /**
1613
+ * Refuse a theme whose own source gives a token a value `set` refuses: the
1614
+ * build would write it as it is (a browser drops it), so it is named, with
1615
+ * the line of the file, before anything is written.
1616
+ * @param {import('./_settings.mjs').Ctx} ctx
1617
+ * @param {string} slug
1618
+ * @param {import('./_settings.mjs').ThemeData} data
1619
+ */
1620
+ async function refuseOwnTokenValues(ctx, slug, data) {
1621
+ const err = await ownTokenRefusal(ctx, slug, data);
1622
+ if (err) throw err;
1623
+ }
1624
+
1625
+ /**
1626
+ * The refusal for own-source token values `set` refuses, or null.
1627
+ * @param {import('./_settings.mjs').Ctx} ctx
1628
+ * @param {string} slug
1629
+ * @param {import('./_settings.mjs').ThemeData} data
1630
+ * @returns {Promise<AstryxError | null>}
1631
+ */
1632
+ async function ownTokenRefusal(ctx, slug, data) {
1633
+ const bad = await ownTokenProblems(ctx, slug, data);
1634
+ if (!bad.length) return null;
1635
+ const own = `themes/${slug}/${slug}.theme.ts`;
1636
+ const file = bad[0].file ?? own;
1637
+ return new AstryxError(
1638
+ `${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
1639
+ .slice(0, 3)
1640
+ .map(
1641
+ b =>
1642
+ `${b.token}${b.value ? `: "${b.value}"` : ''}${b.file ? ` (in ${b.file}${b.line ? `, line ${b.line}` : ''})` : b.line ? ` (line ${b.line})` : ''}: ${b.why.replace(/\.+$/, '')}`,
1643
+ )
1644
+ .join(
1645
+ '; ',
1646
+ )}${bad.length > 3 ? `; and ${bad.length - 3} more` : ''}. Change it in ${file}. Nothing was changed.`,
1647
+ [
1648
+ bad[0].line
1649
+ ? {
1650
+ name: `sed -n ${bad[0].line}p ${quoteCommandArgument(file)}`,
1651
+ reason: 'see the line that sets it',
1652
+ }
1653
+ : {
1654
+ name: `grep -n -- ${quoteCommandArgument(bad[0].token)} ${quoteCommandArgument(file)}`,
1655
+ reason: 'see the line',
1656
+ },
1657
+ ],
1658
+ ERROR_CODES.ERR_THEME_INVALID,
1659
+ );
1660
+ }
1661
+
1662
+ /**
1663
+ * The refusal `compile` gives an editor theme whose own source gives a
1664
+ * token a value `set` refuses, or null.
1665
+ * @param {string} root
1666
+ * @param {string} slug
1667
+ * @returns {Promise<AstryxError | null>}
1668
+ */
1669
+ export async function editorOwnTokenRefusal(root, slug) {
1670
+ const ctx = await context(root);
1671
+ /** @type {import('./_settings.mjs').ThemeData} */
1672
+ let data;
1673
+ try {
1674
+ data = loadTheme(root, slug);
1675
+ } catch {
1676
+ return null;
1677
+ }
1678
+ return ownTokenRefusal(ctx, slug, data);
1679
+ }
1680
+
980
1681
  /**
981
1682
  * For `compile`: the refusal of [light, dark] pairs on tokens that are not
982
1683
  * colors in what the theme builds now, or null.
@@ -1021,6 +1722,218 @@ function extremeSteps(res) {
1021
1722
  : [];
1022
1723
  }
1023
1724
 
1725
+ export {carriesTyped, offersTyped} from './_normal.mjs';
1726
+
1727
+ /**
1728
+ * An object of settings written as JSON, with single quotes, or as its
1729
+ * entries with no braces (`"accent": "#e11d48", "corners": "pill"`).
1730
+ * Throws when it is none of these.
1731
+ * @param {string} text
1732
+ * @returns {any}
1733
+ */
1734
+ function looseObject(text) {
1735
+ const t = text.trim();
1736
+ const braced = t.startsWith('{') ? t : `{${t}}`;
1737
+ try {
1738
+ return JSON.parse(braced);
1739
+ } catch {
1740
+ return JSON.parse(
1741
+ braced.replace(/'((?:[^'\\]|\\.)*)'/g, (_, x) =>
1742
+ JSON.stringify(x.replace(/\\'/g, "'")),
1743
+ ),
1744
+ );
1745
+ }
1746
+ }
1747
+
1748
+ /**
1749
+ * A refusal with each line that sets the typed setting again kept only
1750
+ * when it carries the value typed; with none left, `how` for the setting.
1751
+ * Another setting's line, an undo or a look stays.
1752
+ * @param {any} e
1753
+ * @param {'set' | 'undo'} sub
1754
+ * @param {string} slug
1755
+ * @param {string} thing
1756
+ * @param {unknown} typed
1757
+ * @param {import('./_settings.mjs').ThemeData} [data] the theme, whose saved
1758
+ * values a keep line may carry
1759
+ */
1760
+ function carryTyped(e, sub, slug, thing, typed, data) {
1761
+ if (
1762
+ sub !== 'set' ||
1763
+ !(e instanceof AstryxError) ||
1764
+ typeof typed !== 'string' ||
1765
+ !e.suggestions?.length
1766
+ )
1767
+ return e;
1768
+ const head = new RegExp(
1769
+ `^.* set \\S+ (?:'([^']+)'|(\\S+)) (?:'((?:[^']|'\\\\'')*)'|(\\S+))`,
1770
+ );
1771
+ const same = (/** @type {string} */ x) =>
1772
+ x.replace(/^-+/, '').toLowerCase() ===
1773
+ String(thing).replace(/^-+/, '').toLowerCase();
1774
+ // Every set line, of this setting or another (a dial's other name, a
1775
+ // label, a theme-wide equivalent), offers a value only through the
1776
+ // allowlist of exact readings: never a stock, reset or nearest value.
1777
+ // Another setting's line may carry words of the thing typed too (an
1778
+ // object or a label typed as the thing).
1779
+ const typedText = `${String(thing)} ${typed}`;
1780
+ const saved = data
1781
+ ? [
1782
+ data.like ?? '',
1783
+ data.mode ?? '',
1784
+ ...data.settings.map(x => String(x.value ?? '')),
1785
+ ].join(' ')
1786
+ : '';
1787
+ /** @type {Set<string>} */
1788
+ const dropped = new Set();
1789
+ const lines = e.suggestions.filter(x => {
1790
+ const m = head.exec(x.name);
1791
+ if (!m) return true;
1792
+ const v = m[3] ?? m[4];
1793
+ if (
1794
+ allowedLine({
1795
+ offered: v,
1796
+ typed: same(m[1] ?? m[2]) ? typed : typedText,
1797
+ thing: m[1] ?? m[2],
1798
+ saved,
1799
+ })
1800
+ )
1801
+ return true;
1802
+ dropped.add(v.replace(/^'(.*)'$/, '$1').toLowerCase());
1803
+ return false;
1804
+ });
1805
+ // A value named as a did-you-mean goes with its line.
1806
+ const kept = lines.filter(
1807
+ x => !(x.reason === 'did you mean' && dropped.has(x.name.toLowerCase())),
1808
+ );
1809
+ // A refusal always names a command that works: with no set, undo, new or
1810
+ // how line left, how for the setting.
1811
+ const runnable = kept.some(
1812
+ x => x.reason !== 'did you mean' && !/ --help$/.test(x.name),
1813
+ );
1814
+ if (kept.length === e.suggestions.length && runnable) return e;
1815
+ e.suggestions = runnable
1816
+ ? kept
1817
+ : [
1818
+ ...kept.filter(x => !/ --help$/.test(x.name)),
1819
+ {
1820
+ name: `${P} how ${quoteCommandArgument(String(thing))}`,
1821
+ reason: 'what it takes',
1822
+ },
1823
+ ];
1824
+ return e;
1825
+ }
1826
+
1827
+ /**
1828
+ * A theme's settings file as written, for the values a keep line may carry
1829
+ * when the theme does not load (a damaged entry); null when it cannot be
1830
+ * read.
1831
+ * @param {string} cwd
1832
+ * @param {string} slug
1833
+ * @returns {import('./_settings.mjs').ThemeData | undefined}
1834
+ */
1835
+ function savedAsWritten(cwd, slug) {
1836
+ try {
1837
+ const j = JSON.parse(
1838
+ fs
1839
+ .readFileSync(themeFiles(cwd, slug).settings, 'utf8')
1840
+ .replace(/^\uFEFF/, ''),
1841
+ );
1842
+ return j && Array.isArray(j.settings) ? j : undefined;
1843
+ } catch {
1844
+ return undefined;
1845
+ }
1846
+ }
1847
+
1848
+ /**
1849
+ * The lines of a repair that work: each run through set's own check (in
1850
+ * memory) and offered only when set takes it as offered and its value
1851
+ * passes the allowlist of exact readings of what was typed. With none
1852
+ * left, how for the thing.
1853
+ * @param {'set' | 'undo'} sub
1854
+ * @param {string} slug
1855
+ * @param {string[]} lines
1856
+ * @param {string} cwd
1857
+ * @param {string} typed
1858
+ * @param {string} thing
1859
+ * @returns {Promise<string[]>}
1860
+ */
1861
+ async function workingLines(sub, slug, lines, cwd, typed, thing) {
1862
+ /** @type {string[]} */
1863
+ const out = [];
1864
+ for (const line of lines) {
1865
+ // The line as set takes it (a repair set offers for it folded in).
1866
+ const followed = await followChangeLine(sub, slug, line, cwd);
1867
+ if (followed.why) continue;
1868
+ const read = readSetLine(followed.line, slug);
1869
+ if (
1870
+ sub === 'set' &&
1871
+ read &&
1872
+ !allowedLine({offered: read.value, typed, thing: read.thing})
1873
+ )
1874
+ continue;
1875
+ out.push(followed.line);
1876
+ }
1877
+ return out.length ? out : [`${P} how ${quoteCommandArgument(thing)}`];
1878
+ }
1879
+
1880
+ /**
1881
+ * A `set` or `undo` line for the theme a path or other letters named, run
1882
+ * through that command's own check (in memory, nothing written). Each
1883
+ * repair a refusal of it offers is folded into the one line, so the line
1884
+ * runs as offered; `why` names what is still refused when no repair is
1885
+ * offered.
1886
+ * @param {'set' | 'undo'} sub
1887
+ * @param {string} slug
1888
+ * @param {string} line
1889
+ * @param {string} cwd
1890
+ * @returns {Promise<{line: string, why: string | null}>}
1891
+ */
1892
+ async function followChangeLine(sub, slug, line, cwd) {
1893
+ /** @type {import('./_settings.mjs').ThemeData} */
1894
+ let data;
1895
+ /** @type {import('./_settings.mjs').Ctx} */
1896
+ let ctx;
1897
+ try {
1898
+ data = loadTheme(cwd, slug);
1899
+ ctx = /** @type {import('./_settings.mjs').Ctx} */ (await context(cwd));
1900
+ ctx.base = await baseResolved(ctx.project, data.like);
1901
+ } catch {
1902
+ return {line, why: null};
1903
+ }
1904
+ const prefix = `${P} ${sub} ${slug} `;
1905
+ return followLine(
1906
+ line,
1907
+ now => {
1908
+ const read = readSetLine(
1909
+ sub === 'undo' ? now.replace(`${P} undo `, `${P} set `) : now,
1910
+ slug,
1911
+ );
1912
+ if (!read) return null;
1913
+ try {
1914
+ const s = checkSetting(
1915
+ ctx,
1916
+ slug,
1917
+ structuredClone(data),
1918
+ read.thing,
1919
+ read.value,
1920
+ read.flags,
1921
+ sub === 'undo',
1922
+ );
1923
+ return sub === 'undo' && !data.settings.some(x => keyOf(x) === keyOf(s))
1924
+ ? new AstryxError(
1925
+ `${slug} does not set ${describe({...s, value: '?'}).replace(' = ?', '')}`,
1926
+ )
1927
+ : null;
1928
+ } catch (e) {
1929
+ if (e instanceof AstryxError) return e;
1930
+ throw e;
1931
+ }
1932
+ },
1933
+ name => name.startsWith(prefix),
1934
+ );
1935
+ }
1936
+
1024
1937
  /**
1025
1938
  * @param {'set' | 'undo'} sub
1026
1939
  * @param {string} slug
@@ -1033,21 +1946,169 @@ async function change(sub, slug, thing, value, options) {
1033
1946
  // As typed: an undo of a saved entry written in a form the cleanup below
1034
1947
  // repairs (`Corners`, `var(--radius-page)`) removes that exact entry.
1035
1948
  const typedThing = thing;
1949
+ const typedValue = value;
1950
+ // An object of several settings pasted as one (JSON, single quotes, or
1951
+ // its entries with no braces, split at the first colon on the way): one
1952
+ // set line each.
1953
+ const objectText =
1954
+ typeof thing !== 'string'
1955
+ ? null
1956
+ : value == null || value === ''
1957
+ ? /^\s*\{[\s\S]*\}\s*$/.test(thing)
1958
+ ? thing
1959
+ : null
1960
+ : /^\s*\{?\s*["']/.test(thing) && /["']\s*:/.test(String(value))
1961
+ ? `${thing}:${value}`
1962
+ : null;
1963
+ if (objectText != null) {
1964
+ /** @type {any} */
1965
+ let obj = null;
1966
+ try {
1967
+ obj = looseObject(objectText);
1968
+ } catch {
1969
+ // Not an object: read as typed.
1970
+ }
1971
+ if (obj && typeof obj === 'object' && Object.keys(obj).length > 1)
1972
+ refuse(
1973
+ E.ERR_INVALID_ARGUMENT,
1974
+ `This holds ${Object.keys(obj).length} settings; ${sub} changes one at a time.`,
1975
+ {
1976
+ // Each entry as its own line, a nested value (`{"$value": …}`, a
1977
+ // light and dark pair) written back as typed; each line checked,
1978
+ // and one set refuses is left out.
1979
+ run: await workingLines(
1980
+ sub,
1981
+ slug,
1982
+ Object.entries(obj)
1983
+ .slice(0, 6)
1984
+ .map(
1985
+ ([k, x]) =>
1986
+ `${P} ${sub} ${slug} ${quoteCommandArgument(k)}${sub === 'set' ? ` ${quoteCommandArgument(String(normalizeEntry(k, x != null && typeof x === 'object' ? JSON.stringify(x) : String(x)).value ?? ''))}` : ''}`,
1987
+ ),
1988
+ options.cwd ?? process.cwd(),
1989
+ objectText,
1990
+ 'settings',
1991
+ ),
1992
+ },
1993
+ );
1994
+ }
1995
+ // A flag typed inside the value (`'red --mode dark'`, `'4px --state
1996
+ // hover'`, `'pill --on button'`): the same command with the flag lifted
1997
+ // out, never the value alone, which would change another scope.
1998
+ if (typeof value === 'string' && /\s--(mode|state|on|when)\b/.test(value)) {
1999
+ /** @type {Record<string, string>} */
2000
+ const lifted = {};
2001
+ // The rest is cleaned as any value is (a trailing `;`, `!important`,
2002
+ // a comment).
2003
+ const bare = withoutCopyDebris(
2004
+ value.replace(
2005
+ /\s+--(mode|state|on|when)(?:\s*=\s*|\s+)("[^"]*"|'[^']*'|\S+)/g,
2006
+ (_, f, x) => {
2007
+ lifted[f] = x.replace(/^(["'])(.*)\1$/, '$2');
2008
+ return '';
2009
+ },
2010
+ ),
2011
+ );
2012
+ if (bare && Object.keys(lifted).length) {
2013
+ const opts = /** @type {Record<string, unknown>} */ ({
2014
+ ...options,
2015
+ ...lifted,
2016
+ });
2017
+ const flagText = ['on', 'when', 'state', 'mode']
2018
+ .filter(f => opts[f])
2019
+ .map(f => ` --${f} ${quoteCommandArgument(String(opts[f]))}`)
2020
+ .join('');
2021
+ refuse(
2022
+ E.ERR_INVALID_ARGUMENT,
2023
+ `"${value}" holds ${Object.keys(lifted)
2024
+ .map(f => `--${f}`)
2025
+ .join(' and ')} inside the value; a flag goes outside the quotes.`,
2026
+ {
2027
+ // The line is checked as set checks it; one set refuses is left
2028
+ // out, and how is named instead.
2029
+ run: await workingLines(
2030
+ sub,
2031
+ slug,
2032
+ [
2033
+ `${P} ${sub} ${slug} ${quoteCommandArgument(String(thing))}${sub === 'set' ? ` ${quoteCommandArgument(bare)}` : ''}${flagText}${options.only ? ' --only' : ''}`,
2034
+ ],
2035
+ options.cwd ?? process.cwd(),
2036
+ value,
2037
+ String(thing),
2038
+ ),
2039
+ },
2040
+ );
2041
+ }
2042
+ }
1036
2043
  // How it was typed, put right before anything reads it (a pasted
1037
2044
  // declaration, a dash, a var(), invisible spaces).
2045
+ /** @type {string | undefined} */
2046
+ let dropped;
1038
2047
  if (typeof thing === 'string') {
1039
2048
  const entry = normalizeEntry(thing, value);
1040
2049
  thing = entry.thing;
1041
2050
  value = entry.value;
2051
+ dropped = entry.dropped;
1042
2052
  }
1043
2053
  /** @type {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} */
1044
2054
  const seen = {};
1045
2055
  try {
1046
- return await changeOnce(sub, slug, thing, value, options, seen, typedThing);
2056
+ const r = await changeOnce(
2057
+ sub,
2058
+ slug,
2059
+ thing,
2060
+ value,
2061
+ options,
2062
+ seen,
2063
+ typedThing,
2064
+ );
2065
+ // A second declaration pasted after the first is not set: said, with
2066
+ // its own set line.
2067
+ if (dropped && sub === 'set') {
2068
+ const m = /^([^:]+):\s*(.*?);?\s*$/.exec(dropped);
2069
+ const flags = [
2070
+ ...(options.on ? [`--on ${options.on}`] : []),
2071
+ ...(options.when ? [`--when ${options.when}`] : []),
2072
+ ...(options.state ? [`--state ${options.state}`] : []),
2073
+ ].join(' ');
2074
+ /** @type {any} */ (r.data).notes = [
2075
+ ...(r.data.notes ?? []),
2076
+ `the pasted text also held "${dropped}", which this did not set${m ? `: ${P} set ${slug} ${quoteCommandArgument(m[1].trim())} ${quoteCommandArgument(m[2].trim())}${flags ? ` ${flags}` : ''} sets it` : ''}`,
2077
+ ];
2078
+ }
2079
+ // A mode or base entry in the settings list does nothing: said after
2080
+ // every change, with the undo that removes it.
2081
+ if (seen.ctx && r.data.theme) {
2082
+ /** @type {import('./_settings.mjs').ThemeData | null} */
2083
+ let now = null;
2084
+ try {
2085
+ now = loadTheme(seen.ctx.project.cwd, r.data.theme);
2086
+ } catch {
2087
+ now = null;
2088
+ }
2089
+ const left = now ? misplacedNotes(r.data.theme, now) : [];
2090
+ if (left.length)
2091
+ /** @type {any} */ (r.data).notes = [...left, ...(r.data.notes ?? [])];
2092
+ }
2093
+ return r;
1047
2094
  } 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) {
2095
+ // A theme name one letter off an existing theme, or typed in other
2096
+ // letters or as a path (T, ./t, themes/t): the same command with that
2097
+ // name comes first, never a bare look at the theme that drops the change.
2098
+ const named =
2099
+ e instanceof AstryxError &&
2100
+ (e.code === E.ERR_UNKNOWN_THEME ||
2101
+ (e.code === E.ERR_INVALID_ARGUMENT &&
2102
+ (e.suggestions ?? []).some(
2103
+ x =>
2104
+ x.reason === 'did you mean' &&
2105
+ slugOk(x.name) &&
2106
+ x.name !== slug &&
2107
+ fs.existsSync(
2108
+ themeFiles(options.cwd ?? process.cwd(), x.name).settings,
2109
+ ),
2110
+ )));
2111
+ if (named) {
1051
2112
  const near = (e.suggestions ?? []).find(x => x.reason === 'did you mean');
1052
2113
  if (near && slugOk(near.name)) {
1053
2114
  const flags = [
@@ -1062,18 +2123,38 @@ async function change(sub, slug, thing, value, options) {
1062
2123
  .map(w =>
1063
2124
  String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
1064
2125
  );
2126
+ const followed = await followChangeLine(
2127
+ sub,
2128
+ near.name,
2129
+ `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
2130
+ options.cwd ?? process.cwd(),
2131
+ );
1065
2132
  e.suggestions = [
1066
2133
  {
1067
- name: `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
1068
- reason: `do this instead: ${near.name} is a theme here`,
2134
+ name: followed.line,
2135
+ reason: `do this instead: ${near.name} is a theme here${followed.why ? `, but this still needs a fix: ${followed.why}` : ''}`,
1069
2136
  },
1070
- ...(e.suggestions ?? []).filter(x => x !== near),
2137
+ ...(e.suggestions ?? []).filter(
2138
+ x => x !== near && x.name !== `${P} show ${near.name}`,
2139
+ ),
1071
2140
  ];
1072
2141
  }
1073
2142
  throw e;
1074
2143
  }
1075
- // Every `set` the refusal suggests is checked as `set` checks it.
1076
- throw vetSuggestions(e, seen.ctx, slug, seen.data);
2144
+ // Every `set` the refusal suggests is checked as `set` checks it, and
2145
+ // carries the value typed (cleaned), never a stock value.
2146
+ throw misplacedFirst(
2147
+ carryTyped(
2148
+ vetSuggestions(e, seen.ctx, slug, seen.data),
2149
+ sub,
2150
+ slug,
2151
+ typedThing,
2152
+ typedValue,
2153
+ seen.data ?? savedAsWritten(options.cwd ?? process.cwd(), slug),
2154
+ ),
2155
+ seen.data?.name ?? slug,
2156
+ seen.data,
2157
+ );
1077
2158
  }
1078
2159
  }
1079
2160
 
@@ -1107,29 +2188,53 @@ async function changeOnce(
1107
2188
  when: options.when,
1108
2189
  state: options.state,
1109
2190
  mode: options.mode,
2191
+ // An undo removes the entry it names even when that entry's mode or
2192
+ // source means nothing.
2193
+ ...(sub === 'undo' ? {removing: true} : {}),
1110
2194
  });
1111
2195
  const data = loadTheme(cwd, slug, target);
1112
2196
  /** @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.
2197
+ const fieldNotes = [...entryNotes(data)];
2198
+ {
2199
+ // A damaged field the command does not set goes back to its default,
2200
+ // so the theme loads again (a change or removal of any setting repairs
2201
+ // it on the way).
2202
+ // One written in other letters or as a package name (`Dark-Only`,
2203
+ // `@astryxdesign/theme-neutral`) is cleaned to the value meant, never
2204
+ // reset.
2205
+ const meant = fieldsMeant(data);
1117
2206
  if (
1118
2207
  thing !== 'mode' &&
1119
2208
  !['both', 'light-only', 'dark-only'].includes(data.mode)
1120
2209
  ) {
1121
- data.mode = 'both';
1122
- fieldNotes.push('mode was missing or damaged, so it is both again');
2210
+ if (['both', 'light-only', 'dark-only'].includes(meant.mode)) {
2211
+ fieldNotes.push(
2212
+ `mode was written "${data.mode}", so it is saved as ${meant.mode}`,
2213
+ );
2214
+ data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (
2215
+ meant.mode
2216
+ );
2217
+ } else {
2218
+ data.mode = 'both';
2219
+ fieldNotes.push('mode was missing or damaged, so it is both again');
2220
+ }
1123
2221
  }
1124
2222
  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');
2223
+ if (LIKE.includes(meant.like) && baseInstalled(cwd, meant.like)) {
2224
+ fieldNotes.push(
2225
+ `base was written "${data.like}", so it is saved as ${meant.like}`,
2226
+ );
2227
+ data.like = meant.like;
2228
+ } else {
2229
+ delete data.like;
2230
+ fieldNotes.push('base was not a built-in theme, so it is none again');
2231
+ }
1127
2232
  }
1128
2233
  }
1129
2234
  const ctx = await context(cwd);
1130
2235
  // An undo of one setting only removes it, so it never waits on the
1131
2236
  // others being fixed.
1132
- if (sub !== 'undo')
2237
+ if (sub !== 'undo') {
1133
2238
  refuseStoredTokens(ctx, slug, data, {
1134
2239
  thing,
1135
2240
  on: options.on,
@@ -1137,6 +2242,10 @@ async function changeOnce(
1137
2242
  state: options.state,
1138
2243
  mode: options.mode,
1139
2244
  });
2245
+ }
2246
+ // The own source's token values are checked before every change, an
2247
+ // undo too: an undo rebuilds the theme from that source.
2248
+ await refuseOwnTokenValues(ctx, slug, data);
1140
2249
  const flags = {
1141
2250
  on: options.on,
1142
2251
  when: options.when,
@@ -1175,8 +2284,25 @@ async function changeOnce(
1175
2284
  Boolean(x.only) === Boolean(flags.only),
1176
2285
  )
1177
2286
  : -1;
1178
- let rawIdx = -1;
1179
- if (exactIdx >= 0) {
2287
+ // An entry of this name whose mode or source means nothing is the one an
2288
+ // undo removes: only that entry, never a valid one beside it.
2289
+ const damagedIdx =
2290
+ sub === 'undo'
2291
+ ? data.settings.findIndex(
2292
+ x =>
2293
+ (x.thing === typedThing || x.thing === thing) &&
2294
+ (x.on ?? null) === (flags.on ?? null) &&
2295
+ (x.when ?? null) === (flags.when ?? null) &&
2296
+ (x.state ?? null) === (flags.state ?? null) &&
2297
+ (entryDamage(x) === 'only' ||
2298
+ Boolean(x.only) === Boolean(flags.only)) &&
2299
+ (entryDamage(x) === 'source' || entryDamage(x) === 'only'
2300
+ ? (x.mode ?? null) === (flags.mode ?? null)
2301
+ : entryDamage(x) === 'mode' && !flags.mode),
2302
+ )
2303
+ : -1;
2304
+ let rawIdx = damagedIdx;
2305
+ if (exactIdx >= 0 && rawIdx < 0) {
1180
2306
  // Only an entry the editor would not save as written: one it refuses,
1181
2307
  // or reads as another name, part or state.
1182
2308
  const entry = data.settings[exactIdx];
@@ -1341,7 +2467,28 @@ async function changeOnce(
1341
2467
  );
1342
2468
  }
1343
2469
  const compiledBefore = compileTheme(ctx, data, base);
2470
+ // The build notes the theme had before this change: only new ones are
2471
+ // this change's to report.
2472
+ const notesBefore = new Set(buildNotes(ctx));
1344
2473
  if (sub === 'set' && (s.thing === 'base' || s.thing === 'mode')) {
2474
+ // A built-in base this project has not installed: install it, then the
2475
+ // same set, whichever letters it was typed in.
2476
+ if (
2477
+ s.thing === 'base' &&
2478
+ s.value !== 'none' &&
2479
+ !baseInstalled(cwd, s.value)
2480
+ )
2481
+ refuse(
2482
+ E.ERR_UNKNOWN_THEME,
2483
+ `The ${s.value} theme is not installed, so ${slug} cannot build on it. Install @astryxdesign/theme-${s.value}, then set the base again, or build on no theme.`,
2484
+ {
2485
+ run: [
2486
+ installLine(cwd, [`@astryxdesign/theme-${s.value}`]),
2487
+ `${P} set ${slug} base ${s.value}`,
2488
+ `${P} set ${slug} base none`,
2489
+ ],
2490
+ },
2491
+ );
1345
2492
  const before = s.thing === 'base' ? (data.like ?? 'none') : data.mode;
1346
2493
  if (s.thing === 'base') {
1347
2494
  if (s.value === 'none') delete data.like;
@@ -1349,7 +2496,7 @@ async function changeOnce(
1349
2496
  } else
1350
2497
  data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (s.value);
1351
2498
  const r = await commitTheme(ctx, slug, data, {history: true});
1352
- const p = await previewAndRoute(ctx, slug, data, png);
2499
+ const p = await previewAndRoute(ctx, slug, data, png, 'overview', sub);
1353
2500
  const after = await baseResolved(ctx.project, data.like).catch(() => base);
1354
2501
  return {
1355
2502
  type: 'themeEdit.set',
@@ -1377,6 +2524,15 @@ async function changeOnce(
1377
2524
  ]
1378
2525
  : []),
1379
2526
  ...otherModeNotes(data),
2527
+ // Back to both modes: a mode the app's <Theme> was given for the
2528
+ // one-mode theme pins it still.
2529
+ ...(s.thing === 'mode' &&
2530
+ data.mode === 'both' &&
2531
+ (before === 'light-only' || before === 'dark-only')
2532
+ ? [
2533
+ `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`,
2534
+ ]
2535
+ : []),
1380
2536
  // Core has no mode inside a theme: the app's <Theme> is given it.
1381
2537
  ...(s.thing === 'mode' &&
1382
2538
  (data.mode === 'light-only' || data.mode === 'dark-only')
@@ -1411,13 +2567,27 @@ async function changeOnce(
1411
2567
  }
1412
2568
  const k = keyOf(s);
1413
2569
  const prevIdx =
1414
- rawIdx >= 0 ? rawIdx : data.settings.findIndex(x => keyOf(x) === k);
2570
+ rawIdx >= 0
2571
+ ? rawIdx
2572
+ : // A setting listed twice by hand: the last entry is the one the
2573
+ // build reads, so it is the one this command changes.
2574
+ data.settings.map(x => keyOf(x)).lastIndexOf(k);
1415
2575
  /** @type {string | null} */
1416
2576
  let vibrancyGone = null;
1417
2577
  const prev = prevIdx >= 0 ? data.settings[prevIdx] : null;
1418
2578
  if (sub === 'undo') {
1419
2579
  if (!prev) {
1420
- const near = data.settings.filter(x => x.thing === s.thing).map(describe);
2580
+ // A padding set in the other form (a side for the shorthand, or the
2581
+ // shorthand for a side) on the same part is a near one too.
2582
+ const PAD = /^padding(?:-(?:inline|block|top|right|bottom|left))?$/;
2583
+ const nearOnes = data.settings.filter(
2584
+ x =>
2585
+ x.thing === s.thing ||
2586
+ (PAD.test(s.thing) &&
2587
+ PAD.test(x.thing) &&
2588
+ (x.on ?? null) === (s.on ?? null)),
2589
+ );
2590
+ const near = nearOnes.map(describe);
1421
2591
  // headings has two halves: name the one that is set.
1422
2592
  const otherHalf =
1423
2593
  s.thing === 'headings'
@@ -1430,11 +2600,12 @@ async function changeOnce(
1430
2600
  : `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
1431
2601
  {
1432
2602
  also: near.length
1433
- ? [`settings for ${s.thing}: ${near.join('; ')}`]
2603
+ ? [
2604
+ `settings for ${s.thing}: ${near.join('; ')}${nearOnes.some(x => x.thing === 'padding' && s.thing !== 'padding') ? ' (undoing padding removes all four sides)' : ''}`,
2605
+ ]
1434
2606
  : [],
1435
2607
  run: [
1436
- ...data.settings
1437
- .filter(x => x.thing === s.thing)
2608
+ ...nearOnes
1438
2609
  .slice(0, 3)
1439
2610
  .map(x => `${P} undo ${slug} ${undoArgs(x)}`),
1440
2611
  `${P} show ${slug}`,
@@ -1493,7 +2664,21 @@ async function changeOnce(
1493
2664
  const covered =
1494
2665
  sub === 'set' && !s.mode && s.source !== 'dial'
1495
2666
  ? data.settings.filter(
1496
- x => x !== s && x.mode && keyOf({...x, mode: undefined}) === k,
2667
+ x =>
2668
+ x !== s &&
2669
+ x.mode &&
2670
+ (keyOf({...x, mode: undefined}) === k ||
2671
+ // The background shorthand and its color are one property
2672
+ // here: a one-mode one is replaced by either for both modes.
2673
+ (s.source === 'property' &&
2674
+ x.source === 'property' &&
2675
+ x.on === s.on &&
2676
+ x.when === s.when &&
2677
+ x.state === s.state &&
2678
+ [x.thing, s.thing].every(t =>
2679
+ /^background(-color)?$/.test(kebab(t)),
2680
+ ) &&
2681
+ !/gradient\(|url\(/i.test(String(s.value)))),
1497
2682
  )
1498
2683
  : [];
1499
2684
  data.settings = data.settings.filter(x => !covered.includes(x));
@@ -1513,6 +2698,9 @@ async function changeOnce(
1513
2698
  ))) &&
1514
2699
  x.when === s.when &&
1515
2700
  x.state === s.state &&
2701
+ // A shorthand for one mode replaces longhands of that mode or of
2702
+ // both, never the other mode's.
2703
+ (!s.mode || !x.mode || x.mode === s.mode) &&
1516
2704
  // A longhand the shorthand really sets (MDN's data), never a
1517
2705
  // property that only shares its name (overflow-wrap).
1518
2706
  (coversProperty(s.thing, x.thing) ||
@@ -1537,6 +2725,12 @@ async function changeOnce(
1537
2725
  : [];
1538
2726
  const r = await commitTheme(ctx, slug, data, {history: true});
1539
2727
  const compiledAfter = compileTheme(ctx, data, base);
2728
+ // What the spacing dial said of the sizes it could not keep apart.
2729
+ // What the build said of settings it could not write as they are.
2730
+ const compileNotes = buildNotes(ctx).filter(n => !notesBefore.has(n));
2731
+ const sizeNotes =
2732
+ /** @type {{sizeNotes?: string[]}} */ (/** @type {unknown} */ (ctx))
2733
+ .sizeNotes ?? [];
1540
2734
  const styled = styledChanges(compiledBefore, compiledAfter, base);
1541
2735
  const parts = partsOf(ctx, s);
1542
2736
  // Exact whole-theme tokens that win over what this dial writes: the dial
@@ -1562,6 +2756,29 @@ async function changeOnce(
1562
2756
  !x.when &&
1563
2757
  x.thing === `--font-family-${s.on}`,
1564
2758
  );
2759
+ // A whole-theme spacing dial keeps a part's own exact control size too,
2760
+ // on that part.
2761
+ if (sub === 'set' && s.source === 'dial' && s.thing === 'spacing' && !s.on)
2762
+ exactWins.push(
2763
+ ...data.settings.filter(
2764
+ x =>
2765
+ x.source === 'token' &&
2766
+ !!x.on &&
2767
+ !x.state &&
2768
+ /^--size-element-/.test(x.thing),
2769
+ ),
2770
+ );
2771
+ // A spacing dial on a part keeps the exact spacing and sizes there too:
2772
+ // the whole theme's, and the part's own.
2773
+ if (sub === 'set' && s.source === 'dial' && s.thing === 'spacing' && s.on)
2774
+ exactWins = data.settings.filter(
2775
+ x =>
2776
+ x.source === 'token' &&
2777
+ !x.when &&
2778
+ !x.state &&
2779
+ /^--(size-element|spacing)-/.test(x.thing) &&
2780
+ (!x.on || x.on === s.on),
2781
+ );
1565
2782
  // The theme's own source wins over an exact setting, as the exact
1566
2783
  // setting does over a dial: an exact token the file also sets is named
1567
2784
  // as the file's below, never as the one that shows after an undo.
@@ -1762,6 +2979,7 @@ async function changeOnce(
1762
2979
  : null;
1763
2980
  /** @type {string[]} */
1764
2981
  const notes = [
2982
+ ...fieldNotes,
1765
2983
  ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
1766
2984
  ...(ownPartHits.length
1767
2985
  ? [
@@ -1773,7 +2991,7 @@ async function changeOnce(
1773
2991
  )
1774
2992
  .join(
1775
2993
  ', ',
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)}\`` : ''}`,
2994
+ )}${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
2995
  ]
1778
2996
  : []),
1779
2997
  ...(ownOverToken
@@ -1786,6 +3004,8 @@ async function changeOnce(
1786
3004
  `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
3005
  ]
1788
3006
  : []),
3007
+ ...(sub === 'set' && s.thing === 'spacing' ? sizeNotes : []),
3008
+ ...(sub === 'set' ? compileNotes : []),
1789
3009
  ...(covers.length
1790
3010
  ? [
1791
3011
  `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 +3051,18 @@ async function changeOnce(
1831
3051
  // An exact property on the same part wins over a dial there.
1832
3052
  ...(exactOver
1833
3053
  ? [
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)}\``,
3054
+ // The own source holding only some sides or corners there leaves
3055
+ // the dial the others once the exact property is undone.
3056
+ ownPartHits.length &&
3057
+ ownPartHits.every(h =>
3058
+ /(Top|Bottom|Left|Right|Start|End|Block|Inline)/.test(
3059
+ camel(String(h.prop)),
3060
+ ),
3061
+ )
3062
+ ? `${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`
3063
+ : ownPartHits.length
3064
+ ? `${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`
3065
+ : `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1837
3066
  ]
1838
3067
  : []),
1839
3068
  // A whole-theme font under fonts set for each role shows only where no
@@ -2018,6 +3247,12 @@ async function changeOnce(
2018
3247
  // once preview.html was rendered from the theme as it is now (a retry
2019
3248
  // after a render that failed renders it).
2020
3249
  const f0 = themeFiles(cwd, slug);
3250
+ // A change that changed nothing still writes back an app copy file that
3251
+ // is gone or not the current build.
3252
+ // Its font stylesheet follows the fonts the theme loads now (a font
3253
+ // package installed or removed since).
3254
+ if (r.unchanged && appCopyBehind(cwd, slug, copyFontsCss(ctx, slug, data)))
3255
+ writeAppCopy(ctx, slug, data);
2021
3256
  const p =
2022
3257
  r.unchanged &&
2023
3258
  !png &&
@@ -2030,8 +3265,10 @@ async function changeOnce(
2030
3265
  notChecked: null,
2031
3266
  previewStale: [],
2032
3267
  see: seeLine(cwd, slug, changeFocus(s)),
3268
+ // A copy something keeps behind is said here too.
3269
+ ...appCopyStale(cwd, slug),
2033
3270
  }
2034
- : await previewAndRoute(ctx, slug, data, png, changeFocus(s));
3271
+ : await previewAndRoute(ctx, slug, data, png, changeFocus(s), sub);
2035
3272
  return {
2036
3273
  type: sub === 'set' ? 'themeEdit.set' : 'themeEdit.undo',
2037
3274
  data: {
@@ -2105,6 +3342,50 @@ function unsetColorNotes(data, base, slug) {
2105
3342
  ];
2106
3343
  }
2107
3344
 
3345
+ /**
3346
+ * Whether a settings entry is a mode or base a hand edit put in the list:
3347
+ * it does nothing there (the theme's mode and base are its own fields).
3348
+ * @param {{thing: string}} s
3349
+ */
3350
+ const misplaced = s => s.thing === 'mode' || s.thing === 'base';
3351
+
3352
+ /**
3353
+ * The note for each misplaced entry: listed here only, never as a
3354
+ * setting, with the undo that removes it first.
3355
+ * @param {string} slug
3356
+ * @param {import('./_settings.mjs').ThemeData} data
3357
+ * @returns {string[]}
3358
+ */
3359
+ function misplacedNotes(slug, data) {
3360
+ return data.settings
3361
+ .filter(misplaced)
3362
+ .map(
3363
+ x =>
3364
+ `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}`,
3365
+ );
3366
+ }
3367
+
3368
+ /**
3369
+ * A refusal for a theme with misplaced entries, its suggestions led by the
3370
+ * undo that removes each.
3371
+ * @param {unknown} e
3372
+ * @param {string} slug
3373
+ * @param {import('./_settings.mjs').ThemeData | undefined} data
3374
+ */
3375
+ function misplacedFirst(e, slug, data) {
3376
+ if (!(e instanceof AstryxError) || !data) return e;
3377
+ const undos = data.settings.filter(misplaced).map(x => ({
3378
+ name: `${P} undo ${slug} ${x.thing}`,
3379
+ reason: `removes the ${x.thing} entry that does nothing in the settings list`,
3380
+ }));
3381
+ if (!undos.length) return e;
3382
+ e.suggestions = [
3383
+ ...undos,
3384
+ ...(e.suggestions ?? []).filter(x => !undos.some(u => u.name === x.name)),
3385
+ ];
3386
+ return e;
3387
+ }
3388
+
2108
3389
  /**
2109
3390
  * Every setting of a theme, key resolved values, problems it caused, the
2110
3391
  * sample page and the theme-building page with every component.
@@ -2126,6 +3407,7 @@ export async function themeEditShow(theme, options = {}) {
2126
3407
  // build a later refusal puts back.
2127
3408
  holdAfterBuild(ctx);
2128
3409
  refuseStoredTokens(ctx, theme, data);
3410
+ await refuseOwnTokenValues(ctx, theme, data);
2129
3411
  // Without React, show still lists the settings and builds the theme, as
2130
3412
  // set does; only the pages, pictures and the checks that render are
2131
3413
  // skipped, and the result says how to fix it.
@@ -2287,6 +3569,16 @@ export async function themeEditShow(theme, options = {}) {
2287
3569
  if (!(e instanceof Error)) throw e;
2288
3570
  if (e instanceof AstryxError && e.code !== E.ERR_RENDER_FAILED) throw e;
2289
3571
  putBack(kept, tokensDir);
3572
+ // A folder it cannot write is no render failure: the folder is named.
3573
+ const code = /** @type {any} */ (e).code;
3574
+ if (['EACCES', 'EPERM', 'EROFS'].includes(code)) {
3575
+ const where = /** @type {any} */ (e).path;
3576
+ return refuse(
3577
+ E.ERR_WRITE_FAILED,
3578
+ `${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.`,
3579
+ {run: [`${P} show ${theme}`]},
3580
+ );
3581
+ }
2290
3582
  return refuse(
2291
3583
  E.ERR_RENDER_FAILED,
2292
3584
  `${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 +3620,15 @@ export async function themeEditShow(theme, options = {}) {
2328
3620
  ],
2329
3621
  modes,
2330
3622
  )
2331
- : {files: [], problem: null};
3623
+ : // Pictures asked for but not taken: said, never a quiet none.
3624
+ {
3625
+ files: [],
3626
+ problem: png
3627
+ ? readOnly
3628
+ ? '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'
3629
+ : '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'
3630
+ : null,
3631
+ };
2332
3632
  // The app copy follows the build there now, also when the build was
2333
3633
  // current and only the copy is missing (a theme made before it existed).
2334
3634
  if (!readOnly)
@@ -2347,29 +3647,32 @@ export async function themeEditShow(theme, options = {}) {
2347
3647
  const looksBase = await baseResolved(ctx.project, data.like).catch(
2348
3648
  () => null,
2349
3649
  );
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
- });
3650
+ return data.settings
3651
+ .filter(s => !misplaced(s))
3652
+ .map(s => {
3653
+ let masked = maskedSettings(data, ctx).get(s);
3654
+ // A look dial (buttons, surfaces) under an exact property on a
3655
+ // part it writes: named, as corners under border-radius is.
3656
+ if (!masked && looksBase && s.source === 'dial' && !s.on) {
3657
+ const writes = dialWrites(ctx, data, s, looksBase);
3658
+ const exact = writes.size
3659
+ ? data.settings.find(
3660
+ x =>
3661
+ x.source === 'property' &&
3662
+ x.on &&
3663
+ !x.when &&
3664
+ !x.state &&
3665
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
3666
+ )
3667
+ : undefined;
3668
+ if (exact)
3669
+ masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
3670
+ }
3671
+ return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
3672
+ });
2371
3673
  })(),
2372
3674
  notes: [
3675
+ ...misplacedNotes(theme, data),
2373
3676
  ...(noReact
2374
3677
  ? [
2375
3678
  `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`,
@@ -2443,6 +3746,7 @@ export async function themeEditShow(theme, options = {}) {
2443
3746
  const wrote = takeFirstAppCopy(cwd, theme);
2444
3747
  return wrote ? {appCopy: {wrote}} : {};
2445
3748
  })(),
3749
+ ...appCopyStale(cwd, theme),
2446
3750
  colorFiles: pal ? colorFiles(theme) : null,
2447
3751
  },
2448
3752
  };
@@ -2492,6 +3796,10 @@ function dialWrites(ctx, data, dial, base) {
2492
3796
  * @returns {string}
2493
3797
  */
2494
3798
  function nowApplies(ctx, data, removed, base) {
3799
+ // Vibrancy has no base theme value: the colors are made again at the
3800
+ // default.
3801
+ if (removed.source === 'dial' && removed.thing === 'vibrancy')
3802
+ return `the default vibrancy, ${VIBRANCY_DEFAULT}`;
2495
3803
  // A token the theme's own source sets shows its value, whatever else
2496
3804
  // the settings give it.
2497
3805
  if (removed.source === 'token' && !removed.on && !removed.when) {
@@ -2726,8 +4034,28 @@ function ownPhoneNotes(cwd, slug, data) {
2726
4034
  .filter(x => x.source === 'token' && !x.on && !x.when && !x.state)
2727
4035
  .map(x => x.thing),
2728
4036
  );
4037
+ // A family or size the theme's typography sets is kept on phones (the
4038
+ // base theme's rule for those screens keeps the theme's typography); only
4039
+ // one the tokens map sets is lost there.
4040
+ const entries = ownTokenEntries(cwd, slug);
4041
+ const roles = new Set(
4042
+ entries.filter(e => e.kind === 'typography').map(e => e.key.split('.')[0]),
4043
+ );
4044
+ const inMap = new Set(
4045
+ entries.filter(e => e.token && !e.overridden).map(e => e.token),
4046
+ );
4047
+ /** @param {string} k */
4048
+ const fromTypography = k => {
4049
+ const role = /^--font-family-([a-z]+)$/.exec(k)?.[1];
4050
+ if (role)
4051
+ return roles.has(role) || (role === 'heading' && roles.has('body'));
4052
+ return roles.has('scale') && !/^--font-family-/.test(k);
4053
+ };
2729
4054
  const lost = ownSourceTokens(cwd, slug).filter(
2730
- k => PHONE_TYPE.test(k) && !exact.has(k),
4055
+ k =>
4056
+ PHONE_TYPE.test(k) &&
4057
+ !exact.has(k) &&
4058
+ (!fromTypography(k) || inMap.has(k)),
2731
4059
  );
2732
4060
  if (!lost.length) return [];
2733
4061
  const families = lost.filter(k => /^--font-family-/.test(k));
@@ -3038,10 +4366,99 @@ function colorFiles(slug) {
3038
4366
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditUndoResponse | import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
3039
4367
  */
3040
4368
  export async function themeEditUndo(theme, options = {}) {
4369
+ try {
4370
+ return await undoTheme(theme, options).catch(async e => {
4371
+ throw await swappedOrder(
4372
+ e,
4373
+ 'undo',
4374
+ [theme, options.thing, options.value],
4375
+ options,
4376
+ );
4377
+ });
4378
+ } catch (e) {
4379
+ // A theme name typed in another form (tTheme, T, brand_dark, themes/t):
4380
+ // the same undo with the theme's name comes first, never a look at the
4381
+ // theme that drops the undo.
4382
+ if (
4383
+ e instanceof AstryxError &&
4384
+ (e.code === E.ERR_INVALID_ARGUMENT || e.code === E.ERR_UNKNOWN_THEME)
4385
+ ) {
4386
+ const cwd = options.cwd ?? process.cwd();
4387
+ const showOf = (/** @type {{name: string}} */ x) => {
4388
+ const rest = x.name.startsWith(`${P} show `)
4389
+ ? x.name.slice(`${P} show `.length)
4390
+ : null;
4391
+ return rest && !/\s/.test(rest) ? rest : null;
4392
+ };
4393
+ // A list of themes (t,u) stays a look at each: one theme at a time.
4394
+ const shows = (e.suggestions ?? []).filter(x => showOf(x) != null);
4395
+ const near = (shows.length === 1 ? shows : []).find(x => {
4396
+ const n = showOf(x);
4397
+ return (
4398
+ n != null &&
4399
+ n !== theme &&
4400
+ slugOk(n) &&
4401
+ fs.existsSync(themeFiles(cwd, n).settings)
4402
+ );
4403
+ });
4404
+ const name = near ? showOf(near) : null;
4405
+ if (near && name) {
4406
+ const words = [
4407
+ ...(options.thing ? [options.thing] : []),
4408
+ ...(options.value ? [options.value] : []),
4409
+ ...(options.on ? ['--on', options.on] : []),
4410
+ ...(options.when ? ['--when', options.when] : []),
4411
+ ...(options.state ? ['--state', options.state] : []),
4412
+ ...(options.mode ? ['--mode', options.mode] : []),
4413
+ ].map(w =>
4414
+ String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
4415
+ );
4416
+ const followed = await followChangeLine(
4417
+ 'undo',
4418
+ name,
4419
+ `${P} undo ${name}${words.length ? ` ${words.join(' ')}` : ''}`,
4420
+ cwd,
4421
+ );
4422
+ e.suggestions = [
4423
+ {
4424
+ name: followed.line,
4425
+ reason: `do this instead: ${name} is a theme here${followed.why ? `, but this still needs a fix: ${followed.why}` : ''}`,
4426
+ },
4427
+ ...(e.suggestions ?? []).filter(x => x !== near),
4428
+ ];
4429
+ }
4430
+ }
4431
+ throw e;
4432
+ }
4433
+ }
4434
+
4435
+ /**
4436
+ * {@link themeEditUndo}'s work.
4437
+ * @param {string} theme
4438
+ * @param {import('./theme-edit.type.mjs').ThemeEditUndoOptions} options
4439
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditUndoResponse | import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
4440
+ */
4441
+ async function undoTheme(theme, options) {
3041
4442
  const {cwd = process.cwd(), png = false, thing} = options;
3042
4443
  // base and mode are not settings in the list: undoing one goes back to
3043
4444
  // what the theme was made with (the oldest step the history keeps).
3044
- if (thing === 'base' || thing === 'mode') {
4445
+ // A `base` or `mode` entry a hand edit put in the settings list is a
4446
+ // setting like any other there: undo removes it.
4447
+ const listed =
4448
+ (thing === 'base' || thing === 'mode') &&
4449
+ slugOk(theme) &&
4450
+ (() => {
4451
+ try {
4452
+ return JSON.parse(
4453
+ fs
4454
+ .readFileSync(themeFiles(cwd, theme).settings, 'utf8')
4455
+ .replace(/^\uFEFF/, ''),
4456
+ ).settings.some((/** @type {any} */ x) => x?.thing === thing);
4457
+ } catch {
4458
+ return false;
4459
+ }
4460
+ })();
4461
+ if ((thing === 'base' || thing === 'mode') && !listed) {
3045
4462
  requireProject(cwd);
3046
4463
  const now = loadTheme(cwd, theme, thing);
3047
4464
  const historyFile = themeFiles(cwd, theme).history;
@@ -3128,10 +4545,18 @@ export async function themeEditUndo(theme, options = {}) {
3128
4545
  // A link in the theme is refused as set refuses it, never read as an
3129
4546
  // empty history.
3130
4547
  if (slugOk(theme)) refuseLinks(cwd, theme);
4548
+ /** The command that works when the settings cannot be read. @type {string[] | null} */
4549
+ let repair = null;
3131
4550
  try {
3132
4551
  current = loadTheme(cwd, theme);
3133
4552
  } catch (e) {
3134
4553
  if (!(e instanceof AstryxError && e.code === E.ERR_THEME_INVALID)) throw e;
4554
+ // What the refusal itself names (make the theme again, keeping the
4555
+ // damaged file), never `show`, which fails the same way.
4556
+ repair = (e.suggestions ?? [])
4557
+ .map(x => x.name)
4558
+ .filter(n => !/ show /.test(` ${n} `) && !/ undo /.test(` ${n} `));
4559
+ if (!repair.length) repair = [`${P} new ${theme}`];
3135
4560
  }
3136
4561
  const f = themeFiles(cwd, theme);
3137
4562
  const {steps: history, dropped} = readHistory(f.history);
@@ -3141,15 +4566,18 @@ export async function themeEditUndo(theme, options = {}) {
3141
4566
  `${theme}.history.json is damaged, so there is no step to go back to.`,
3142
4567
  {
3143
4568
  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}`],
4569
+ run: repair ?? [`${P} show ${theme}`],
3145
4570
  },
3146
4571
  );
3147
4572
  if (!history.length)
3148
4573
  refuse(
3149
4574
  E.ERR_THEME_NOTHING_TO_UNDO,
3150
- `Nothing to undo: ${theme} has no earlier change.`,
3151
- {run: [`${P} show ${theme}`]},
4575
+ `Nothing to undo: ${theme} has no earlier change${repair ? `, and ${theme}.settings.json cannot be read` : ''}.`,
4576
+ {run: repair ?? [`${P} show ${theme}`]},
3152
4577
  );
4578
+ // The step rebuilds the theme from its own source: a token value there
4579
+ // that set refuses is refused here too, before anything is written.
4580
+ if (current) await refuseOwnTokenValues(await context(cwd), theme, current);
3153
4581
  // A top step equal to the settings now (left by an undo stopped between
3154
4582
  // its two writes) changes nothing: skip it.
3155
4583
  const nowText = fs.readFileSync(f.settings, 'utf8');
@@ -3278,8 +4706,10 @@ export async function themeEditUndo(theme, options = {}) {
3278
4706
  undone.push(
3279
4707
  `base ${current.like ?? 'none'} is back to ${prev.like ?? 'none'}`,
3280
4708
  );
3281
- if (current && current.mode !== prev.mode)
4709
+ if (current && current.mode !== prev.mode) {
3282
4710
  undone.push(`mode ${current.mode} is back to ${prev.mode}`);
4711
+ undone.push(...modeWiringNotes(theme, current.mode, prev.mode));
4712
+ }
3283
4713
  // The page most about what the step reverted: Colors for a color,
3284
4714
  // Components for a part setting, else Overview.
3285
4715
  const touched = [
@@ -3291,7 +4721,7 @@ export async function themeEditUndo(theme, options = {}) {
3291
4721
  : touched.includes('components')
3292
4722
  ? 'components'
3293
4723
  : 'overview';
3294
- const p = await previewAndRoute(ctx, theme, prev, png, focus);
4724
+ const p = await previewAndRoute(ctx, theme, prev, png, focus, 'undo');
3295
4725
  return {
3296
4726
  type: 'themeEdit.undo',
3297
4727
  data: {
@@ -3320,3 +4750,14 @@ export async function editorStale(cwd, slug) {
3320
4750
  const data = loadTheme(cwd, slug);
3321
4751
  return staleBuild(cwd, slug, data) || null;
3322
4752
  }
4753
+
4754
+ /**
4755
+ * The notes the last build of the theme left (settings it could not write
4756
+ * as they are).
4757
+ * @param {unknown} ctx
4758
+ * @returns {string[]}
4759
+ */
4760
+ function buildNotes(ctx) {
4761
+ const notes = /** @type {{compileNotes?: unknown}} */ (ctx)?.compileNotes;
4762
+ return Array.isArray(notes) ? notes.map(String) : [];
4763
+ }