@astryxdesign/cli 0.7.15 → 0.7.16-canary.g22213fd

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 (222) hide show
  1. package/README.md +6 -4
  2. package/api/build/_adapter.d.mts +10 -0
  3. package/api/build/_adapter.mjs +24 -0
  4. package/api/build/blocks/blocks.d.mts +1 -0
  5. package/api/build/blocks/blocks.mjs +18 -1
  6. package/api/build/kit/shell.weights.json +1 -0
  7. package/api/build/kit/shellcall.d.mts +26 -0
  8. package/api/build/kit/shellcall.mjs +87 -0
  9. package/api/build/kit/start.mjs +67 -4
  10. package/api/build/kit/weights.d.mts +15 -0
  11. package/api/build/kit/weights.mjs +27 -0
  12. package/api/component/__fixtures__/resolutions/modules.txt +1 -1
  13. package/api/component/_adapter.d.mts +1 -1
  14. package/api/component/_adapter.mjs +28 -1
  15. package/api/doctor/_adapter.d.mts +38 -2
  16. package/api/doctor/_adapter.mjs +76 -1
  17. package/api/doctor/built-checks.mjs +1 -1
  18. package/api/doctor/doctor.d.mts +26 -0
  19. package/api/doctor/doctor.doc.mjs +1 -1
  20. package/api/doctor/doctor.mjs +156 -11
  21. package/api/doctor/theme-checks.mjs +163 -18
  22. package/api/icon/_adapter.d.mts +7 -3
  23. package/api/icon/_adapter.mjs +12 -3
  24. package/api/icon/icon.type.d.mts +15 -0
  25. package/api/icon/icon.type.mjs +10 -3
  26. package/api/icon/iconUse.doc.mjs +19 -5
  27. package/api/icon/list/list.mjs +7 -1
  28. package/api/icon/use/use.d.mts +8 -5
  29. package/api/icon/use/use.mjs +95 -13
  30. package/api/init/run/run.mjs +1 -0
  31. package/api/integration/add-contribution.mjs +3 -3
  32. package/api/integration/pack-check.mjs +14 -8
  33. package/api/integration/validate-integration.mjs +1 -1
  34. package/api/search/_adapter.mjs +15 -16
  35. package/api/search/_entries.d.mts +2 -1
  36. package/api/search/_entries.mjs +28 -1
  37. package/api/swizzle/_moduleGraph.mjs +1 -1
  38. package/api/template/template.type.d.mts +6 -2
  39. package/api/template/template.type.mjs +2 -1
  40. package/api/theme/_adapter.d.mts +5 -2
  41. package/api/theme/_adapter.mjs +59 -14
  42. package/api/theme/_fork.mjs +1 -1
  43. package/api/theme/build/build.d.mts +120 -32
  44. package/api/theme/build/build.mjs +471 -111
  45. package/api/theme/eject/eject.mjs +22 -1
  46. package/api/theme/generateTonalPalette.doc.mjs +2 -2
  47. package/api/theme/palette/generate/generator.mjs +141 -2
  48. package/api/theme/template/template.d.mts +19 -0
  49. package/api/theme/template/template.mjs +102 -25
  50. package/api/theme/theme.type.d.mts +44 -1
  51. package/api/theme/theme.type.mjs +23 -1
  52. package/api/theme/themeBuild.doc.mjs +4 -4
  53. package/api/theme/themeEject.doc.mjs +1 -1
  54. package/api/theme/themePaletteGenerate.doc.mjs +1 -1
  55. package/api/theme/themeTemplate.doc.mjs +9 -3
  56. package/api/theme-edit/_adapter.d.mts +33 -2
  57. package/api/theme-edit/_adapter.mjs +276 -41
  58. package/api/theme-edit/_check.d.mts +93 -4
  59. package/api/theme-edit/_check.mjs +1712 -223
  60. package/api/theme-edit/_color.d.mts +2 -8
  61. package/api/theme-edit/_color.mjs +292 -219
  62. package/api/theme-edit/_compiler.d.mts +1 -0
  63. package/api/theme-edit/_compiler.mjs +20 -1
  64. package/api/theme-edit/_context.d.mts +31 -1
  65. package/api/theme-edit/_context.mjs +445 -41
  66. package/api/theme-edit/_css.d.mts +60 -1
  67. package/api/theme-edit/_css.mjs +404 -28
  68. package/api/theme-edit/_edit.d.mts +25 -0
  69. package/api/theme-edit/_edit.mjs +1620 -154
  70. package/api/theme-edit/_how-commands.d.mts +11 -26
  71. package/api/theme-edit/_how-commands.mjs +30 -2
  72. package/api/theme-edit/_how-question.d.mts +15 -0
  73. package/api/theme-edit/_how-question.mjs +1469 -194
  74. package/api/theme-edit/_how.mjs +144 -30
  75. package/api/theme-edit/_marks.d.mts +13 -0
  76. package/api/theme-edit/_marks.mjs +15 -0
  77. package/api/theme-edit/_overview.mjs +2 -0
  78. package/api/theme-edit/_palette.d.mts +38 -0
  79. package/api/theme-edit/_palette.mjs +306 -73
  80. package/api/theme-edit/_parts.d.mts +33 -0
  81. package/api/theme-edit/_parts.mjs +138 -9
  82. package/api/theme-edit/_png.d.mts +18 -0
  83. package/api/theme-edit/_png.mjs +95 -14
  84. package/api/theme-edit/_preview-app.d.mts +55 -1
  85. package/api/theme-edit/_preview-app.mjs +1552 -101
  86. package/api/theme-edit/_preview.d.mts +71 -3
  87. package/api/theme-edit/_preview.mjs +565 -35
  88. package/api/theme-edit/_project.d.mts +15 -0
  89. package/api/theme-edit/_project.mjs +68 -13
  90. package/api/theme-edit/_settings.d.mts +299 -5
  91. package/api/theme-edit/_settings.mjs +2806 -158
  92. package/api/theme-edit/_tables.d.mts +24 -0
  93. package/api/theme-edit/_tables.mjs +212 -150
  94. package/api/theme-edit/_vet.d.mts +42 -0
  95. package/api/theme-edit/_vet.mjs +144 -0
  96. package/api/theme-edit/theme-edit.type.d.mts +31 -2
  97. package/api/theme-edit/theme-edit.type.mjs +10 -2
  98. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  99. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  100. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  101. package/api/upgrade/registry/registry.mjs +6 -1
  102. package/assets/codemods/parse.mjs +2 -2
  103. package/assets/docs/author-a-theme.doc.mjs +1 -1
  104. package/assets/docs/theme.doc.dense.mjs +1 -1
  105. package/assets/docs/theme.doc.mjs +1 -1
  106. package/assets/docs/theme.doc.zh.mjs +4 -3
  107. package/assets/docs/tree/define-the-theme.doc.mjs +1 -1
  108. package/assets/docs/tree/icon-sets.doc.mjs +63 -8
  109. package/assets/docs/tree/single-component.doc.mjs +11 -2
  110. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  111. package/assets/docs.generated.json +2 -2
  112. package/assets/preview-app/next.config.mjs +7 -1
  113. package/assets/preview-app/package.json +1 -0
  114. package/assets/preview-app/src/app/globals.css +1 -0
  115. package/assets/self-audit.generated.json +1 -1
  116. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.doc.mjs +21 -0
  117. package/assets/templates/blocks/components/Outline/useOutlineFromDOMHookUsage.tsx +62 -0
  118. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  119. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  120. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  121. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  122. package/assets/templates/components.generated.json +1 -1
  123. package/assets/templates/pages/ai-chat/page.tsx +20 -2
  124. package/assets/templates/pages/dashboard/page.tsx +1 -1
  125. package/assets/templates/themes/neutral/neutralPalettes.generated.receipt.json +2 -0
  126. package/authoring/config/config.doc.mjs +8 -0
  127. package/authoring/config/parse.d.mts +1 -0
  128. package/authoring/config/parse.mjs +12 -0
  129. package/authoring/config/type.ts +8 -0
  130. package/authoring/doctypes/_schema.d.mts +52 -5
  131. package/authoring/doctypes/_schema.mjs +62 -7
  132. package/authoring/doctypes/base/type.ts +10 -0
  133. package/authoring/doctypes/component/component.doc.mjs +1 -1
  134. package/authoring/doctypes/function/function.doc.mjs +6 -0
  135. package/authoring/doctypes/function/type.ts +3 -0
  136. package/authoring/doctypes/icon-set/icon-set-data.doc.mjs +3 -3
  137. package/authoring/doctypes/legacy.mjs +5 -1
  138. package/authoring/index.d.ts +1 -0
  139. package/authoring/shadcn/source-variants.d.mts +1 -1
  140. package/authoring/shadcn/source-variants.mjs +32 -10
  141. package/clients/cli/build-id.generated.json +1 -1
  142. package/clients/cli/commands/doctor.doc.mjs +2 -2
  143. package/clients/cli/commands/experimental/icon.mjs +61 -6
  144. package/clients/cli/commands/experimental/theme.mjs +244 -45
  145. package/clients/cli/commands/experimental-icon-use.doc.mjs +12 -5
  146. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  147. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  148. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  149. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  150. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  151. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  152. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  153. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  154. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  155. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  156. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  157. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  158. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  159. package/clients/cli/commands/theme.doc.mjs +7 -2
  160. package/clients/cli/commands/theme.mjs +222 -55
  161. package/clients/cli/commands.generated.json +1 -1
  162. package/clients/cli/formatters/index.mjs +7 -4
  163. package/clients/cli/index.mjs +25 -5
  164. package/clients/cli/lib/cli-error.mjs +9 -3
  165. package/clients/cli/lib/component-format.mjs +27 -9
  166. package/clients/cli/lib/json-shim.mjs +72 -2
  167. package/clients/cli/manifest.generated.json +1 -1
  168. package/clients/cli/run.mjs +49 -0
  169. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  170. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  171. package/foundation/agent-docs/agent-docs.mjs +4 -3
  172. package/foundation/config/config-writer.d.mts +23 -0
  173. package/foundation/config/config-writer.mjs +152 -58
  174. package/foundation/config/project.mjs +103 -16
  175. package/foundation/discovery/component-discovery.mjs +11 -22
  176. package/foundation/discovery/icon-set-checks.mjs +164 -48
  177. package/foundation/discovery/icon-set-discovery.d.mts +38 -5
  178. package/foundation/discovery/icon-set-discovery.mjs +50 -6
  179. package/foundation/discovery/icon-set-theme-maps.d.mts +59 -0
  180. package/foundation/discovery/icon-set-theme-maps.mjs +95 -0
  181. package/foundation/discovery/icon-set-writer.d.mts +2 -3
  182. package/foundation/discovery/icon-set-writer.mjs +58 -17
  183. package/foundation/discovery/module-exports.mjs +1 -15
  184. package/foundation/discovery/template-adapter.mjs +44 -19
  185. package/foundation/discovery/template-icons.d.mts +27 -10
  186. package/foundation/discovery/template-icons.mjs +142 -26
  187. package/foundation/discovery/template-source-tree.mjs +3 -16
  188. package/foundation/discovery/theme-discovery.d.mts +30 -1
  189. package/foundation/discovery/theme-discovery.mjs +109 -50
  190. package/foundation/fs/exact-codec.d.mts +35 -0
  191. package/foundation/fs/exact-codec.mjs +148 -0
  192. package/foundation/fs/gather-cache.d.mts +15 -5
  193. package/foundation/fs/gather-cache.mjs +129 -31
  194. package/foundation/fs/paths.d.mts +39 -0
  195. package/foundation/fs/paths.mjs +44 -11
  196. package/foundation/fs/read-record.mjs +11 -1
  197. package/foundation/integrations/autolink.d.mts +4 -2
  198. package/foundation/integrations/autolink.mjs +4 -2
  199. package/foundation/integrations/cli-requirement.d.mts +16 -5
  200. package/foundation/integrations/cli-requirement.mjs +27 -6
  201. package/foundation/integrations/contribution-fixes.mjs +1 -16
  202. package/foundation/integrations/may-have-integrations.mjs +7 -3
  203. package/foundation/integrations/missing-dependency.d.mts +9 -0
  204. package/foundation/integrations/missing-dependency.mjs +100 -0
  205. package/foundation/integrations/public-imports.mjs +1 -1
  206. package/foundation/render/embedded-imports.mjs +1 -1
  207. package/foundation/render/host-exit.d.mts +8 -0
  208. package/foundation/render/host-exit.mjs +11 -0
  209. package/foundation/render/page-host.mjs +56 -10
  210. package/foundation/render/page-worker.mjs +14 -0
  211. package/foundation/render/render-page.mjs +37 -2
  212. package/foundation/response/error-codes.d.mts +2 -1
  213. package/foundation/response/error-codes.d.ts +1 -0
  214. package/foundation/response/error-codes.doc.mjs +5 -0
  215. package/foundation/response/error-codes.mjs +3 -0
  216. package/foundation/response/json.d.mts +15 -0
  217. package/foundation/response/json.mjs +52 -1
  218. package/foundation/response/response-types.doc.mjs +1 -1
  219. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  220. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  221. package/foundation/xle/browser.d.mts +2 -2
  222. package/package.json +7 -6
@@ -10,11 +10,15 @@
10
10
  * @position api/theme-edit — storage and compile for the theme commands
11
11
  */
12
12
 
13
+ import {EDITOR_GENERATED_MARK} from './_marks.mjs';
14
+ import {parse as parseModule} from '@babel/parser';
13
15
  import {createHash} from 'node:crypto';
14
16
  import * as fs from 'node:fs';
17
+ import {coversProperty, cssNumber, longhandsOf} from './_css.mjs';
15
18
  import postcss from 'postcss';
16
19
  import {createRequire} from 'node:module';
17
20
  import * as path from 'node:path';
21
+ import {themeFileImports} from '../../foundation/discovery/theme-discovery.mjs';
18
22
  import {pathToFileURL} from 'node:url';
19
23
  import {cliVersion} from '../../foundation/release/run-context.mjs';
20
24
  import {AstryxError} from '../error.mjs';
@@ -39,9 +43,12 @@ import {
39
43
  TEXT_SIZE,
40
44
  TYPE_STYLES,
41
45
  familyOf,
46
+ WRAPPED_PARTS,
47
+ CARD_LIKE,
42
48
  } from './_tables.mjs';
43
49
  import {
44
50
  alphaOf,
51
+ colorProblem,
45
52
  compositeOver,
46
53
  isColorValue,
47
54
  isSafeValue,
@@ -63,11 +70,23 @@ import {
63
70
  lockHeld,
64
71
  removeEmptyFolder,
65
72
  writeWhole,
73
+ setOwnTokenReader,
74
+ readWrittenRecord,
75
+ writeWrittenRecord,
66
76
  } from './_palette.mjs';
77
+ import {EDITOR_STAMP, pngTexts} from './_png.mjs';
67
78
  import {MODAL, isColorToken} from './_compiler.mjs';
68
- import {baseResolved, baseThemeFile} from './_project.mjs';
79
+ import {
80
+ baseInstalled,
81
+ baseModule,
82
+ baseResolved,
83
+ baseThemeFile,
84
+ } from './_project.mjs';
69
85
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
70
86
 
87
+ // The palette reads the tokens the own source sets through this module.
88
+ setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
89
+
71
90
  /**
72
91
  * One setting the CLI owns.
73
92
  * @typedef {object} Setting
@@ -97,7 +116,7 @@ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
97
116
  /** What lifted secondary text sits on: the contrast check measures it there. */
98
117
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
99
118
 
100
- /** @typedef {{project: import('./_project.mjs').ThemeProject, C: import('./_compiler.mjs').Compiler, unchecked?: string | null, uncheckedCode?: string | null, wrote?: Map<string, string | null>, base?: {light: Record<string, string>, dark: Record<string, string>, components?: Record<string, any>}, keepStops?: Record<string, Record<'light' | 'dark', {family: string, stop: number, alpha?: string}>> | null, keepRadii?: Record<string, string> | null}} Ctx */
119
+ /** @typedef {{project: import('./_project.mjs').ThemeProject, C: import('./_compiler.mjs').Compiler, unchecked?: string | null, uncheckedCode?: string | null, wrote?: Map<string, string | null>, base?: {light: Record<string, string>, dark: Record<string, string>, components?: Record<string, any>}, keepStops?: Record<string, Record<'light' | 'dark', {family: string, stop: number, alpha?: string}>> | null, keepRadii?: Record<string, string> | null, derived?: Record<string, Array<{property: string, vars?: string[], replaces?: boolean, expand?: string}>>}} Ctx */
101
120
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
102
121
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
103
122
 
@@ -113,12 +132,17 @@ export const slugOk = s =>
113
132
  !windowsReserved(s);
114
133
 
115
134
  /**
116
- * A name Windows reserves for a device (con, nul, com1…): a folder named
117
- * so cannot be checked out there.
135
+ * A name Windows does not allow for a file or folder, so it cannot be
136
+ * checked out there: a device name (con, nul, com1, com¹…), a character
137
+ * Windows reserves (`<>:"|?*` and control characters), or a dot or space
138
+ * at the end.
118
139
  * @param {string} s
119
140
  */
120
141
  export const windowsReserved = s =>
121
- /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(s);
142
+ /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i.test(s) ||
143
+ // eslint-disable-next-line no-control-regex
144
+ /[<>:"|?*\u0000-\u001f]/.test(s) ||
145
+ /[. ]$/.test(s);
122
146
  /**
123
147
  * The theme name closest to what was typed: spaces and accents dropped,
124
148
  * lower case, anything else a dash.
@@ -167,10 +191,258 @@ export function themeFiles(cwd, slug) {
167
191
  preview: path.join(dir, 'preview.html'),
168
192
  sheet: path.join(dir, 'sheet.html'),
169
193
  previewPng: path.join(dir, 'preview.png'),
194
+ pictures: path.join(dir, `${slug}.pictures.json`),
170
195
  sheetPng: path.join(dir, 'sheet.png'),
171
196
  };
172
197
  }
173
198
 
199
+ /** Files a system or a tool puts in any folder; a folder of only these is empty. */
200
+ export const FOLDER_JUNK = new Set(['.DS_Store', '.gitkeep', 'Thumbs.db']);
201
+
202
+ /**
203
+ * Whether `dir` holds nothing of anyone's: absent, empty, or only system
204
+ * files (what `git rm -r` or a branch switch leaves). A path that is not a
205
+ * folder, or one that does not read, is not empty.
206
+ * @param {string} dir
207
+ */
208
+ export function folderIsEmpty(dir) {
209
+ if (!fs.existsSync(dir)) return true;
210
+ try {
211
+ return (
212
+ fs.lstatSync(dir).isDirectory() &&
213
+ fs.readdirSync(dir).every(n => FOLDER_JUNK.has(n))
214
+ );
215
+ } catch {
216
+ return false;
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Whether a value fits what a dial takes, read from the dial's own list of
222
+ * values: a named rung in any case, or a value of the kind it names (a size,
223
+ * a color, a number). `set` still checks the value in full.
224
+ * @param {string} dial
225
+ * @param {string} value
226
+ */
227
+ export function dialValueFits(dial, value) {
228
+ const spec = DIALS[/** @type {keyof typeof DIALS} */ (dial)]?.values;
229
+ if (!spec) return false;
230
+ const v = String(value).trim();
231
+ if (v === '') return false;
232
+ return spec.split('|').some(option => {
233
+ if (!option.startsWith('<') && !option.startsWith('"'))
234
+ return option === v.toLowerCase();
235
+ if (option.startsWith('"')) return true;
236
+ if (option.includes('size')) return /^\d*\.?\d+(px|rem|em)$/.test(v);
237
+ // A color by the editor's own color check (a bare word only when it
238
+ // names a color).
239
+ if (option === '<color>') return colorProblem(v) == null;
240
+ if (option === '<0-100>') return /^\d{1,3}$/.test(v) && Number(v) <= 100;
241
+ if (option === '<number>') return /^\d*\.?\d+$/.test(v);
242
+ return false;
243
+ });
244
+ }
245
+
246
+ /** @param {string} file @returns {string | null} */
247
+ const contentHash = file => {
248
+ try {
249
+ return createHash('sha256').update(fs.readFileSync(file)).digest('hex');
250
+ } catch {
251
+ return null;
252
+ }
253
+ };
254
+
255
+ /**
256
+ * Record files the editor just wrote into a theme folder.
257
+ * @param {string} cwd
258
+ * @param {string} slug
259
+ * @param {string[]} files
260
+ */
261
+ export function recordWritten(cwd, slug, files) {
262
+ const map = readWrittenRecord(cwd, slug);
263
+ for (const file of files) {
264
+ const hash = contentHash(file);
265
+ if (hash) map[path.basename(file)] = hash;
266
+ }
267
+ writeWrittenRecord(cwd, slug, map);
268
+ }
269
+
270
+ /**
271
+ * Whether the editor wrote this file in the theme folder and it is
272
+ * unchanged since.
273
+ * @param {string} cwd
274
+ * @param {string} slug
275
+ * @param {string} file
276
+ */
277
+ export function editorWrote(cwd, slug, file) {
278
+ const map = readWrittenRecord(cwd, slug);
279
+ const was = map[path.basename(file)];
280
+ // A recorded picture is the editor's only while it is as it wrote it: a
281
+ // picture changed after (re-saved by another tool, stamp and all) is the
282
+ // person's.
283
+ if (was) return was === contentHash(file);
284
+ // With no record of it, the picture's stamp names the theme it shows.
285
+ try {
286
+ return pngTexts(fs.readFileSync(file))[EDITOR_STAMP] === slug;
287
+ } catch {
288
+ return false;
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Adopt a picture an older editor took (before it recorded or stamped its
294
+ * pictures) into the record: only while the theme has no record at all, the
295
+ * name is one the editor writes, and the picture is the editor's 1280-pixel
296
+ * wide window. Returns whether it was adopted.
297
+ * @param {string} cwd
298
+ * @param {string} slug
299
+ * @param {string} file
300
+ */
301
+ export function adoptOlderPicture(cwd, slug, file) {
302
+ if (fs.existsSync(themeFiles(cwd, slug).pictures)) return false;
303
+ if (!/^(sheet|preview)(-[a-z-]+)?\.png$/.test(path.basename(file)))
304
+ return false;
305
+ /** @type {Buffer} */
306
+ let bytes;
307
+ try {
308
+ bytes = fs.readFileSync(file);
309
+ } catch {
310
+ return false;
311
+ }
312
+ // The width in the PNG header: the editor takes a 1280-pixel window.
313
+ if (
314
+ bytes.length < 24 ||
315
+ bytes.toString('latin1', 12, 16) !== 'IHDR' ||
316
+ bytes.readUInt32BE(16) !== 1280
317
+ )
318
+ return false;
319
+ recordWritten(cwd, slug, [file]);
320
+ return true;
321
+ }
322
+
323
+ /**
324
+ * Drop names from the record of what the editor wrote.
325
+ * @param {string} cwd
326
+ * @param {string} slug
327
+ * @param {string[]} names
328
+ */
329
+ function forgetWritten(cwd, slug, names) {
330
+ if (!names.length) return;
331
+ const map = readWrittenRecord(cwd, slug);
332
+ for (const n of names) delete map[n];
333
+ writeWrittenRecord(cwd, slug, map);
334
+ }
335
+
336
+ /**
337
+ * A name `new` takes, for a suggestion: `name` itself when it is valid, not a
338
+ * built-in theme and its folder is free; `my-<name>` for a built-in theme's
339
+ * name; else the first free numbered name.
340
+ * @param {string} cwd
341
+ * @param {string} name
342
+ */
343
+ export function usableNewName(cwd, name) {
344
+ const base = LIKE.includes(name) ? `my-${name}` : name;
345
+ return slugOk(base) && !fs.existsSync(themeFiles(cwd, base).dir)
346
+ ? base
347
+ : freeThemeName(cwd, base);
348
+ }
349
+
350
+ /**
351
+ * A theme name near `name` that is valid and whose folder is free: `name-2`,
352
+ * `name-3`, …, shortened to fit the name's length limit.
353
+ * @param {string} cwd
354
+ * @param {string} name
355
+ */
356
+ export function freeThemeName(cwd, name) {
357
+ for (let n = 2; n < 1000; n += 1) {
358
+ const suffix = `-${n}`;
359
+ const candidate = `${name.slice(0, 64 - suffix.length).replace(/-+$/, '')}${suffix}`;
360
+ if (slugOk(candidate) && !fs.existsSync(themeFiles(cwd, candidate).dir))
361
+ return candidate;
362
+ }
363
+ return '<another name>';
364
+ }
365
+
366
+ /**
367
+ * Why the editor cannot read one of its files, or null when it can (or the
368
+ * file is not there): a folder in the file's place, or no permission to read
369
+ * it. Bad content is a different problem, judged where the file is parsed.
370
+ * @param {string} file
371
+ * @returns {string | null}
372
+ */
373
+ export function unreadableReason(file) {
374
+ let st;
375
+ try {
376
+ st = fs.statSync(file);
377
+ } catch (e) {
378
+ const code = /** @type {any} */ (e)?.code;
379
+ return code === 'ENOENT' || code === 'ENOTDIR'
380
+ ? null
381
+ : `it cannot be read (${code ?? 'unknown error'})`;
382
+ }
383
+ if (st.isDirectory()) return 'it is a folder, not a file';
384
+ try {
385
+ fs.accessSync(file, fs.constants.R_OK);
386
+ } catch (e) {
387
+ return `it cannot be read (${/** @type {any} */ (e)?.code ?? 'no permission'}: permission denied)`;
388
+ }
389
+ return null;
390
+ }
391
+
392
+ /**
393
+ * Refuse, by name, when a file of the theme is a folder or cannot be read:
394
+ * every command reads them, and none should crash on one. The fix is to
395
+ * look at the file and give it back its place; a file is never deleted.
396
+ * @param {string} cwd
397
+ * @param {string} slug
398
+ */
399
+ export function refuseUnreadableFiles(cwd, slug) {
400
+ const f = themeFiles(cwd, slug);
401
+ // The files the editor reads (the settings, the source, the history) are
402
+ // named here; the files the build writes (with their types) by the
403
+ // build's own check, the same one show uses.
404
+ refuseUnreadable(cwd, [
405
+ ...builtFiles(cwd, slug, {name: slug, mode: 'both', settings: []}),
406
+ path.join(f.dir, `${slug}.variants.d.ts`),
407
+ ]);
408
+ for (const file of [f.settings, f.ts, f.history]) {
409
+ const why = unreadableReason(file);
410
+ if (why)
411
+ throw new AstryxError(
412
+ `${path.relative(cwd, file)} ${why}, so the theme cannot be read. Put the file back in its place (or give it read permission); nothing was changed.`,
413
+ [
414
+ {
415
+ name: `ls -la ${quoteCommandArgument(path.relative(cwd, file))}`,
416
+ reason: 'see what is there',
417
+ },
418
+ ],
419
+ ERROR_CODES.ERR_THEME_INVALID,
420
+ );
421
+ }
422
+ }
423
+
424
+ /**
425
+ * Refuse when the app's themes/ is a file or a link to something other
426
+ * than a folder: every editor theme lives in themes/<name>/. The run lists
427
+ * what is there; the message says to rename or move it.
428
+ * @param {string} cwd
429
+ */
430
+ export function refuseThemesNotFolder(cwd) {
431
+ const root = path.join(cwd, 'themes');
432
+ const st = fs.lstatSync(root, {throwIfNoEntry: false});
433
+ if (!st) return;
434
+ const isDir =
435
+ st.isDirectory() ||
436
+ (st.isSymbolicLink() &&
437
+ fs.statSync(root, {throwIfNoEntry: false})?.isDirectory());
438
+ if (isDir) return;
439
+ refuse(
440
+ ERROR_CODES.ERR_FILE_EXISTS,
441
+ `themes in this app is ${st.isSymbolicLink() ? 'a link that does not lead to a folder' : 'a file, not a folder'}, so no editor theme can be read or made: every theme goes in themes/<name>/. Rename or move it, then run the command again.`,
442
+ {run: ['ls -la themes']},
443
+ );
444
+ }
445
+
174
446
  /**
175
447
  * The themes the editor made in the app (a settings file of its own), by
176
448
  * name, or with `changed` the one an editor command changed last first: the
@@ -183,6 +455,7 @@ export function themeFiles(cwd, slug) {
183
455
  export function editedThemes(cwd, order = 'name') {
184
456
  const root = path.join(cwd, 'themes');
185
457
  if (!fs.existsSync(root)) return [];
458
+ refuseThemesNotFolder(cwd);
186
459
  const names = fs
187
460
  .readdirSync(root)
188
461
  .filter(d => fs.existsSync(themeFiles(cwd, d).settings))
@@ -259,6 +532,51 @@ export function refuse(code, message, extra = {}) {
259
532
  throw new AstryxError(`${message} ${tail}`, suggestions, code);
260
533
  }
261
534
 
535
+ /**
536
+ * A theme name without a pasted label: `theme: t`, `name=t`, `--theme t`
537
+ * and `slug: "t"` name t; quotes and backticks around it go. Case is kept.
538
+ * A space is no label separator without dashes: "Theme Park" stays.
539
+ * The one reader of such labels, for --theme and every editor command.
540
+ * @param {unknown} s
541
+ * @returns {string}
542
+ */
543
+ export function unlabeledThemeName(s) {
544
+ return (
545
+ String(s ?? '')
546
+ .trim()
547
+ // A space ends a label only after dashes (`--theme t`): "Theme Park"
548
+ // is one name.
549
+ .replace(
550
+ /^(?:-+(?:theme|name|slug)(?:\s*[:=]\s*|\s+)|(?:theme|name|slug)\s*[:=]\s*)(?=\S)/i,
551
+ '',
552
+ )
553
+ .replace(/^['"`]+|['"`]+$/g, '')
554
+ .trim()
555
+ );
556
+ }
557
+
558
+ /**
559
+ * A theme name as typed, read the way the editor reads it: a path to its
560
+ * folder or a file in it (t.theme.ts, Brand.settings.json), in any case,
561
+ * or a pasted label (`theme: t`, `name: t`), names the theme. The result may still need slugFor.
562
+ * @param {unknown} s
563
+ * @returns {string}
564
+ */
565
+ export function typedThemeName(s) {
566
+ return (
567
+ unlabeledThemeName(s)
568
+ .toLowerCase()
569
+ // ./t and .\t name the theme t.
570
+ .replace(/^(\.[\\/])+/, '')
571
+ .replace(/^.*themes[\\/]/, '')
572
+ .replace(/[\\/].*$/, '')
573
+ .replace(
574
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|css|js|ts)$/,
575
+ '',
576
+ )
577
+ );
578
+ }
579
+
262
580
  /**
263
581
  * The settings of a theme, or a refusal naming the command that makes it.
264
582
  * @param {string} cwd
@@ -273,20 +591,23 @@ export function loadTheme(
273
591
  slug,
274
592
  skip = /** @type {string | Partial<Setting>} */ (''),
275
593
  ) {
594
+ refuseThemesNotFolder(cwd);
276
595
  if (!slugOk(slug)) {
277
596
  // A path or a capital letter typed for a theme that exists names it.
278
597
  // A file name typed for the theme (t.theme.ts, Brand.settings.json)
279
598
  // names the theme.
280
- const plain = String(slug ?? '')
281
- .trim()
282
- .toLowerCase()
283
- .replace(/^.*themes[\\/]/, '')
284
- .replace(/[\\/].*$/, '')
285
- .replace(
286
- /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|css|js|ts)$/,
287
- '',
288
- );
289
- const fixed = slugFor(plain);
599
+ // The name a pasted label gives ("theme: park" is park) when its theme
600
+ // exists; else the whole name as typed ("Theme Park" is theme-park).
601
+ const whole = slugFor(
602
+ String(slug ?? '')
603
+ .trim()
604
+ .toLowerCase(),
605
+ );
606
+ const plain = typedThemeName(slug);
607
+ const named = slugFor(plain);
608
+ const exists = (/** @type {string} */ n) =>
609
+ Boolean(n) && fs.existsSync(themeFiles(cwd, n).settings);
610
+ const fixed = !exists(named) && exists(whole) ? whole : named;
290
611
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
291
612
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
292
613
  // each that exists named; never a new theme made of the list. A name
@@ -309,6 +630,27 @@ export function loadTheme(
309
630
  },
310
631
  );
311
632
  }
633
+ // An empty name (an unset variable, a lone dash): no theme to guess
634
+ // from it, so the themes here are named instead of a new one.
635
+ if (!same && !/[a-z0-9]/i.test(String(slug ?? ''))) {
636
+ const have = fs.existsSync(themeFiles(cwd, 'x').root)
637
+ ? fs
638
+ .readdirSync(themeFiles(cwd, 'x').root)
639
+ .filter(
640
+ d => slugOk(d) && fs.existsSync(themeFiles(cwd, d).settings),
641
+ )
642
+ .sort()
643
+ : [];
644
+ refuse(
645
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
646
+ `The theme name is empty${String(slug ?? '').trim() ? ` ("${String(slug).slice(0, 20)}" has no letter or digit)` : ''}.${have.length ? ` Themes here: ${have.slice(0, 6).join(', ')}.` : ''}`,
647
+ {
648
+ run: have.length
649
+ ? have.slice(0, 3).map(t => `${P} show ${t}`)
650
+ : [`${P} new my-theme`],
651
+ },
652
+ );
653
+ }
312
654
  refuse(
313
655
  ERROR_CODES.ERR_INVALID_ARGUMENT,
314
656
  `"${String(slug ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE}).`,
@@ -348,7 +690,55 @@ export function loadTheme(
348
690
  ERROR_CODES.ERR_UNKNOWN_THEME,
349
691
  stopped
350
692
  ? `themes/${slug} was left by a \`new\` that was stopped part way, so it has no settings yet. Run new again to finish it; files you added there are kept.`
351
- : `themes/${slug} has lost its settings (${slug}.settings.json is gone), but the editor made it. Run new to make it again: your own files there are kept${fs.existsSync(f.history) ? `, and \`undo ${slug}\` then steps back to the earlier settings` : ''}.`,
693
+ : `themes/${slug} has lost its settings (${slug}.settings.json is gone), but the editor made it. Run new to make it again: your own files there are kept${fs.existsSync(f.history) ? `, and \`undo ${slug}\` then steps back to the settings from before the last change (the last change itself is not kept)` : ''}.`,
694
+ {run: [`${P} new ${slug}`]},
695
+ );
696
+ // A folder copied or renamed by hand from an editor theme: its files
697
+ // still carry the old name (t.settings.json in themes/t2).
698
+ const copied =
699
+ !same && fs.existsSync(f.dir)
700
+ ? fs
701
+ .readdirSync(f.dir)
702
+ .map(n => /^(.+)\.settings\.json$/.exec(n)?.[1])
703
+ .find(n => n && n !== slug)
704
+ : undefined;
705
+ if (copied) {
706
+ const files = fs
707
+ .readdirSync(f.dir)
708
+ .filter(n => n.startsWith(`${copied}.`))
709
+ .sort();
710
+ const original = fs.existsSync(themeFiles(cwd, copied).settings);
711
+ refuse(
712
+ ERROR_CODES.ERR_UNKNOWN_THEME,
713
+ `themes/${slug} holds the editor files of a theme named ${copied} (${files.slice(0, 4).join(', ')}${files.length > 4 ? ', …' : ''}): it looks like a copy or rename of ${copied}. The editor reads a theme's files by its folder's name, so to edit it as ${slug}, rename each ${copied}.* file there to ${slug}.* (${files
714
+ .slice(0, 2)
715
+ .map(n => `${n} to ${slug}${n.slice(copied.length)}`)
716
+ .join(', ')}${files.length > 2 ? ', and so on' : ''})${
717
+ // The theme source names the theme inside it too: every step.
718
+ files.includes(`${copied}.theme.ts`)
719
+ ? `, then in ${slug}.theme.ts change './${copied}.settings' to './${slug}.settings', ${camel(copied)}Settings to ${camel(slug)}Settings (in the import and in extends), name: '${copied}' to name: '${slug}', and ${camel(copied)}Theme to ${camel(slug)}Theme`
720
+ : ''
721
+ }${original ? `; ${copied} itself is still in themes/${copied}` : ''}.`,
722
+ {
723
+ run: original
724
+ ? [`${P} show ${copied}`, `ls -la themes/${slug}`]
725
+ : [`ls -la themes/${slug}`],
726
+ },
727
+ );
728
+ }
729
+ // An empty theme folder (or one of system files only) holds no theme
730
+ // yet: `new` makes one there.
731
+ if (
732
+ !same &&
733
+ other &&
734
+ other[0] === f.dir &&
735
+ !LIKE.includes(slug) &&
736
+ fs.lstatSync(f.dir).isDirectory() &&
737
+ folderIsEmpty(f.dir)
738
+ )
739
+ refuse(
740
+ ERROR_CODES.ERR_UNKNOWN_THEME,
741
+ `themes/${slug} is an empty folder: there is no theme ${slug} yet. new makes it there.`,
352
742
  {run: [`${P} new ${slug}`]},
353
743
  );
354
744
  if (!same && (other || LIKE.includes(slug)))
@@ -357,20 +747,37 @@ export function loadTheme(
357
747
  `${other ? `${other[1]} is a theme the editor did not make (written by hand, or ejected)` : `${slug} is a built-in theme`}, so the editor does not change it. Make an editor theme with its own name instead${LIKE.includes(slug) ? `, on top of ${slug}` : ''}.`,
358
748
  {
359
749
  run: [
360
- `${P} new my-${slug}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
750
+ // The user's own theme on that base, when there is one, then a
751
+ // free valid name for a new one.
752
+ ...(fs.existsSync(themeFiles(cwd, `my-${slug}`).settings)
753
+ ? [`${P} show my-${slug}`]
754
+ : []),
755
+ `${P} new ${usableNewName(cwd, `my-${slug}`)}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
361
756
  ],
362
757
  },
363
758
  );
364
759
  refuse(
365
760
  ERROR_CODES.ERR_UNKNOWN_THEME,
366
761
  `There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
367
- {
368
- didYouMean: same ? [same] : nearest(slug, have),
369
- run: same ? [`${P} show ${same}`] : [`${P} new ${slug}`],
370
- },
762
+ (() => {
763
+ const near = same ? [same] : nearest(slug, have);
764
+ // A theme near the name comes first; a new theme of the name as
765
+ // typed only after.
766
+ return {
767
+ didYouMean: near,
768
+ run: same
769
+ ? [`${P} show ${same}`]
770
+ : near.length
771
+ ? [`${P} show ${near[0]}`, `${P} new ${slug}`]
772
+ : [`${P} new ${slug}`],
773
+ };
774
+ })(),
371
775
  );
372
776
  }
373
777
  refuseLinks(cwd, slug);
778
+ // A file of the theme that is a folder or cannot be read is named, never
779
+ // called damaged.
780
+ refuseUnreadableFiles(cwd, slug);
374
781
  // undo is offered only when there is a step to go back to.
375
782
  const steps = readHistory(f.history).steps.length;
376
783
  const recover = steps
@@ -472,22 +879,73 @@ export function loadTheme(
472
879
  );
473
880
  }
474
881
  // A bad mode or base is fixed by setting it.
882
+ // A value written in other letters (Dark-Only, Neutral) is the one meant.
883
+ const modeMeant = String(data?.mode ?? '')
884
+ .trim()
885
+ .toLowerCase();
886
+ const likeMeant = String(data?.like ?? '')
887
+ .trim()
888
+ .toLowerCase();
475
889
  const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
476
- ? `${P} set ${slug} mode both`
890
+ ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
477
891
  : /^base "/.test(problem ?? '')
478
- ? `${P} set ${slug} base none`
892
+ ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : 'none'}`
479
893
  : null;
894
+ // A setting listed twice: setting it to one of its values, or undoing
895
+ // it, keeps one entry or none.
896
+ const twice = problem?.includes(' is listed twice (')
897
+ ? duplicated(data)
898
+ : null;
480
899
  if (problem)
481
900
  throw new AstryxError(
482
- `themes/${slug}/${slug}.settings.json: ${problem}. ${fieldFix ? 'Set it again' : `Fix it by hand${recover.text}`}. Nothing was changed.`,
901
+ `themes/${slug}/${slug}.settings.json: ${problem}. ${fieldFix ? 'Set it again' : twice ? `Set it to one of its values or undo it, or fix it by hand${recover.text}` : `Fix it by hand${recover.text}`}. Nothing was changed.`,
483
902
  fieldFix
484
903
  ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
485
- : recover.run,
904
+ : twice
905
+ ? [
906
+ ...twice.values
907
+ .filter(
908
+ v =>
909
+ typeof v === 'string' &&
910
+ !valueProblem({...twice.setting, value: v}),
911
+ )
912
+ .slice(0, 2)
913
+ .map(v => ({
914
+ name: `${P} set ${slug} ${undoArgs(twice.setting).replace(twice.setting.thing, `${twice.setting.thing} ${quoteCommandArgument(String(v))}`)}`,
915
+ reason: `keep ${v}`,
916
+ })),
917
+ {
918
+ name: `${P} undo ${slug} ${undoArgs(twice.setting)}`,
919
+ reason: 'remove both',
920
+ },
921
+ ...recover.run,
922
+ ]
923
+ : recover.run,
486
924
  ERROR_CODES.ERR_THEME_INVALID,
487
925
  );
488
926
  return data;
489
927
  }
490
928
 
929
+ /**
930
+ * The first setting listed more than once, with every value it is listed
931
+ * with, in order.
932
+ * @param {any} data
933
+ * @returns {{setting: any, values: unknown[]} | null}
934
+ */
935
+ function duplicated(data) {
936
+ /** @type {Map<string, any[]>} */
937
+ const byKey = new Map();
938
+ for (const s of data.settings ?? []) {
939
+ if (!s || typeof s.thing !== 'string') continue;
940
+ const key = keyOf(s);
941
+ byKey.set(key, [...(byKey.get(key) ?? []), s]);
942
+ }
943
+ for (const list of byKey.values())
944
+ if (list.length > 1)
945
+ return {setting: list[0], values: [...new Set(list.map(x => x.value))]};
946
+ return null;
947
+ }
948
+
491
949
  /**
492
950
  * What is wrong with settings data, or null: its shape, and each value with
493
951
  * the same rules `set` checks it by (without the installed Core), so a value
@@ -513,7 +971,15 @@ export function settingsProblem(
513
971
  if (!field && data.like != null && !LIKE.includes(data.like))
514
972
  return `base "${data.like}" is not a built-in theme (${LIKE.join(', ')})`;
515
973
  if (!Array.isArray(data.settings)) return 'settings is not a list';
516
- const keys = new Set();
974
+ // `lifted` is written by the build: a list of text, or absent.
975
+ if (
976
+ data.lifted != null &&
977
+ (!Array.isArray(data.lifted) ||
978
+ data.lifted.some((/** @type {unknown} */ x) => typeof x !== 'string'))
979
+ )
980
+ return `lifted is ${JSON.stringify(data.lifted)}, not a list of text (the build writes it; remove the field and the next build writes it again)`;
981
+ /** @type {Map<string, any>} */
982
+ const keys = new Map();
517
983
  for (const s of data.settings) {
518
984
  // A value or scope that is not text is a bad setting `undo` removes;
519
985
  // a setting with no name is damage.
@@ -524,8 +990,11 @@ export function settingsProblem(
524
990
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
525
991
  return `${s.thing} has mode "${s.mode}"`;
526
992
  const key = keyOf(s);
527
- if (keys.has(key)) return `${describe(s)} is listed twice`;
528
- keys.add(key);
993
+ // The command that changes or removes a setting listed twice keeps one
994
+ // value, or none, so it fixes the list.
995
+ if (keys.has(key) && !skips(s, skip))
996
+ return `${describe({...s, value: '?'}).replace(' = ?', '')} is listed twice (${JSON.stringify(keys.get(key).value)}, ${JSON.stringify(s.value)})`;
997
+ keys.set(key, s);
529
998
  if (skips(s, skip)) continue;
530
999
  const problem = valueProblem(s);
531
1000
  if (problem) return problem;
@@ -636,6 +1105,12 @@ export function valueProblem(s) {
636
1105
  if (s.source !== 'dial') return null;
637
1106
  const d = DIALS[s.thing];
638
1107
  if (!d) return `${s.thing} is not a dial`;
1108
+ // A color dial needs a fixed opaque seed, as `set` checks it: a
1109
+ // see-through, system or variable color generates no shades.
1110
+ if (PALETTE_DIALS.includes(s.thing) && isColorValue(s.value)) {
1111
+ const seed = colorProblem(s.value);
1112
+ if (seed) return `${bad} ${seed.message}`;
1113
+ }
639
1114
  const words = d.values.split('|').filter(w => !w.startsWith('<'));
640
1115
  const ok =
641
1116
  s.thing === 'corners'
@@ -655,7 +1130,639 @@ export function valueProblem(s) {
655
1130
  if (!ok || s.value === 'more' || s.value === 'less')
656
1131
  return `${bad} is not a value ${s.thing} takes (${d.values.replace('|more|less', '')})`;
657
1132
  }
658
- return null;
1133
+ return null;
1134
+ }
1135
+
1136
+ /**
1137
+ * The page-wide tokens a theme's own source sets: the keys of the top-level
1138
+ * `tokens` map in its `defineTheme({...})`, read from the syntax tree, each
1139
+ * with its value when that is plain text (else null). A token set only in a
1140
+ * scope (`onDark`, `components`) is not one: it does not apply page-wide.
1141
+ * @param {string} cwd
1142
+ * @param {string} slug
1143
+ * @returns {Map<string, string | null>}
1144
+ */
1145
+ function ownPageTokens(cwd, slug) {
1146
+ /** @type {Map<string, string | null>} */
1147
+ const out = new Map();
1148
+ /** @type {string} */
1149
+ let code;
1150
+ try {
1151
+ code = fs.readFileSync(themeFiles(cwd, slug).ts, 'utf8');
1152
+ } catch {
1153
+ return out;
1154
+ }
1155
+ /** @type {any} */
1156
+ let ast;
1157
+ try {
1158
+ ast = parseModule(code, {sourceType: 'module', plugins: ['typescript']});
1159
+ } catch {
1160
+ return out;
1161
+ }
1162
+ /** @param {any} node @returns {string | null} */
1163
+ const keyOf = node =>
1164
+ node?.type === 'StringLiteral'
1165
+ ? node.value
1166
+ : node?.type === 'Identifier'
1167
+ ? node.name
1168
+ : null;
1169
+ /** @param {any} node @returns {string | null} */
1170
+ const textOf = node =>
1171
+ node?.type === 'StringLiteral'
1172
+ ? node.value
1173
+ : node?.type === 'TemplateLiteral' && node.expressions.length === 0
1174
+ ? node.quasis.map((/** @type {any} */ q) => q.value.cooked).join('')
1175
+ : null;
1176
+ // Every const binding in the file, by name, so a value given by name
1177
+ // (tokens: mine, ...mine) is read as written.
1178
+ /** @type {Map<string, any>} */
1179
+ const consts = new Map();
1180
+ /** @type {any[]} */
1181
+ const calls = [];
1182
+ /** @param {any} node @param {any} owner the exported name, when exported */
1183
+ const visit = (node, owner = null) => {
1184
+ if (!node || typeof node !== 'object') return;
1185
+ if (node.type === 'VariableDeclarator' && node.id?.type === 'Identifier')
1186
+ consts.set(node.id.name, node.init);
1187
+ if (
1188
+ node.type === 'CallExpression' &&
1189
+ node.callee?.type === 'Identifier' &&
1190
+ node.callee.name === 'defineTheme' &&
1191
+ node.arguments?.[0]
1192
+ )
1193
+ calls.push({call: node, owner});
1194
+ for (const [k, v] of Object.entries(node)) {
1195
+ const nextOwner =
1196
+ node.type === 'VariableDeclarator' && k === 'init'
1197
+ ? (node.id?.name ?? owner)
1198
+ : node.type === 'ExportDefaultDeclaration'
1199
+ ? 'default'
1200
+ : owner;
1201
+ if (Array.isArray(v)) v.forEach(c => visit(c, nextOwner));
1202
+ else if (v && typeof v === 'object' && v.type) visit(v, nextOwner);
1203
+ }
1204
+ };
1205
+ visit(ast.program);
1206
+ /** @param {any} node @param {number} [depth] @returns {any} */
1207
+ const unwrap = (node, depth = 0) => {
1208
+ if (!node || depth > 20) return null;
1209
+ if (
1210
+ [
1211
+ 'TSAsExpression',
1212
+ 'TSSatisfiesExpression',
1213
+ 'TSNonNullExpression',
1214
+ 'TSTypeAssertion',
1215
+ 'ParenthesizedExpression',
1216
+ ].includes(node.type)
1217
+ )
1218
+ return unwrap(node.expression, depth + 1);
1219
+ if (node.type === 'Identifier' && consts.has(node.name))
1220
+ return unwrap(consts.get(node.name), depth + 1);
1221
+ return node;
1222
+ };
1223
+ // The theme the build loads: the defineTheme that names it, else the one
1224
+ // exported as <camel>Theme or by default, else the only one.
1225
+ const named = calls.find(({call}) => {
1226
+ const obj = unwrap(call.arguments[0]);
1227
+ return (
1228
+ obj?.type === 'ObjectExpression' &&
1229
+ obj.properties.some(
1230
+ (/** @type {any} */ p) =>
1231
+ p.type === 'ObjectProperty' &&
1232
+ keyOf(p.key) === 'name' &&
1233
+ textOf(unwrap(p.value)) === slug,
1234
+ )
1235
+ );
1236
+ });
1237
+ const chosen =
1238
+ named ??
1239
+ calls.find(
1240
+ c => c.owner === `${camel(slug)}Theme` || c.owner === 'default',
1241
+ ) ??
1242
+ (calls.length === 1 ? calls[0] : null);
1243
+ if (!chosen) return out;
1244
+ const def = unwrap(chosen.call.arguments[0]);
1245
+ if (def?.type !== 'ObjectExpression') return out;
1246
+ const tokensProp = def.properties.find(
1247
+ (/** @type {any} */ p) =>
1248
+ p.type === 'ObjectProperty' && !p.computed && keyOf(p.key) === 'tokens',
1249
+ );
1250
+ if (!tokensProp) return out;
1251
+ let unresolved = false;
1252
+ /** @param {any} node @param {number} depth */
1253
+ const collect = (node, depth) => {
1254
+ const obj = unwrap(node);
1255
+ if (obj?.type !== 'ObjectExpression' || depth > 20) {
1256
+ unresolved = true;
1257
+ return;
1258
+ }
1259
+ // Spreads and keys merge in order: a later one wins.
1260
+ for (const p of obj.properties) {
1261
+ if (p.type === 'SpreadElement') collect(p.argument, depth + 1);
1262
+ else if (p.type === 'ObjectProperty' && !p.computed) {
1263
+ const k = keyOf(p.key);
1264
+ if (k?.startsWith('--')) out.set(k, textOf(unwrap(p.value)));
1265
+ } else unresolved = true;
1266
+ }
1267
+ };
1268
+ collect(tokensProp.value, 0);
1269
+ // A value no read of the file can resolve (a call, an import) is read
1270
+ // from the build (ownTokens), and checked again after the next one.
1271
+ void unresolved;
1272
+ return out;
1273
+ }
1274
+
1275
+ /**
1276
+ * The var() loops among a theme's built top-level tokens, each with a key
1277
+ * that names it whatever token it starts from.
1278
+ * @param {string} cwd
1279
+ * @param {string} slug
1280
+ * @returns {Array<{key: string, path: string[], part?: string}>}
1281
+ */
1282
+ function builtLoops(cwd, slug) {
1283
+ const tokens = builtTopTokens(cwd, slug);
1284
+ /** @param {string} t */
1285
+ const refs = t =>
1286
+ [...String(tokens.get(t) ?? '').matchAll(/var\(\s*(--[a-z0-9-]+)/gi)].map(
1287
+ m => m[1],
1288
+ );
1289
+ /** @type {Array<{key: string, path: string[], part?: string}>} */
1290
+ const loops = [];
1291
+ const seen = new Set();
1292
+ for (const start of tokens.keys()) {
1293
+ /** @type {string[]} */
1294
+ const path = [];
1295
+ /** @param {string} t @returns {boolean} */
1296
+ const walk = t => {
1297
+ const at = path.indexOf(t);
1298
+ if (at >= 0) {
1299
+ const cycle = path.slice(at);
1300
+ const key = [...cycle].sort().join(' ');
1301
+ if (!seen.has(key)) {
1302
+ seen.add(key);
1303
+ loops.push({key, path: [...cycle, t]});
1304
+ }
1305
+ return true;
1306
+ }
1307
+ if (!tokens.has(t) || path.length > 50) return false;
1308
+ path.push(t);
1309
+ for (const r of refs(t)) if (walk(r)) return true;
1310
+ path.pop();
1311
+ return false;
1312
+ };
1313
+ walk(start);
1314
+ }
1315
+ // Inside one part: a part's own token reads the part's other own tokens
1316
+ // first, and a whole-theme one only as already resolved, so a loop there
1317
+ // closes among the part's own tokens.
1318
+ const js = themeFiles(cwd, slug).js;
1319
+ for (const part of blockKeys(js, ['components'])) {
1320
+ const plain = blockOf(js, ['components', part, 'base']);
1321
+ // Each state or variant rule of the part also has its plain rule.
1322
+ for (const scope of blockKeys(js, ['components', part])) {
1323
+ const own =
1324
+ scope === 'base' ? plain : blockOf(js, ['components', part, scope]);
1325
+ const block = new Map([...plain, ...own]);
1326
+ const where = scope === 'base' ? part : `${part} ${scope}`;
1327
+ for (const start of own.keys()) {
1328
+ if (!start.startsWith('--')) continue;
1329
+ /** @type {string[]} */
1330
+ const path = [];
1331
+ /** @param {string} t @returns {boolean} */
1332
+ const walk = t => {
1333
+ const at = path.indexOf(t);
1334
+ if (at >= 0) {
1335
+ const cycle = path.slice(at);
1336
+ const key = `${where}: ${[...cycle].sort().join(' ')}`;
1337
+ if (!seen.has(key)) {
1338
+ seen.add(key);
1339
+ loops.push({key, path: [...cycle, t], part: where});
1340
+ }
1341
+ return true;
1342
+ }
1343
+ if (!block.has(t) || path.length > 50) return false;
1344
+ path.push(t);
1345
+ for (const m of String(block.get(t) ?? '').matchAll(
1346
+ /var\(\s*(--[a-z0-9-]+)/gi,
1347
+ ))
1348
+ if (walk(m[1])) return true;
1349
+ path.pop();
1350
+ return false;
1351
+ };
1352
+ walk(start);
1353
+ }
1354
+ }
1355
+ }
1356
+ return loops;
1357
+ }
1358
+
1359
+ /**
1360
+ * The keys of one object in a built theme module (see blockOf).
1361
+ * @param {string} file
1362
+ * @param {string[]} keys
1363
+ * @returns {string[]}
1364
+ */
1365
+ function blockKeys(file, keys) {
1366
+ return [...blockOf(file, keys).keys()];
1367
+ }
1368
+
1369
+ /**
1370
+ * The top-level tokens of a theme's built module (<slug>.js), which the
1371
+ * build wrote as plain data, or an empty map.
1372
+ * @param {string} cwd
1373
+ * @param {string} slug
1374
+ * @returns {Map<string, string | null>}
1375
+ */
1376
+ function builtTopTokens(cwd, slug) {
1377
+ return topTokensOf(themeFiles(cwd, slug).js);
1378
+ }
1379
+
1380
+ /**
1381
+ * The tokens a base theme's own component rules for a part read through
1382
+ * var() (neutral's progress-bar reads --color-border-emphasized), from its
1383
+ * built module; an empty set when it is not installed.
1384
+ * @param {string} cwd
1385
+ * @param {string | null | undefined} like
1386
+ * @param {string} target
1387
+ * @returns {Set<string>}
1388
+ */
1389
+ export function baseComponentReads(cwd, like, target) {
1390
+ /** @type {Set<string>} */
1391
+ const out = new Set();
1392
+ const file = like ? baseModule(cwd, like) : null;
1393
+ if (!file) return out;
1394
+ try {
1395
+ const ast = /** @type {any} */ (
1396
+ parseModule(fs.readFileSync(file, 'utf8'), {sourceType: 'module'})
1397
+ );
1398
+ /** @param {any} node */
1399
+ const visit = node => {
1400
+ if (!node || typeof node !== 'object') return;
1401
+ if (
1402
+ node.type === 'ObjectProperty' &&
1403
+ (node.key?.name ?? node.key?.value) === 'components' &&
1404
+ node.value?.type === 'ObjectExpression'
1405
+ ) {
1406
+ const part = node.value.properties.find(
1407
+ (/** @type {any} */ p) => (p.key?.value ?? p.key?.name) === target,
1408
+ );
1409
+ if (part) {
1410
+ const text = JSON.stringify(part.value);
1411
+ for (const m of text.matchAll(/var\(\s*(--[a-z0-9-]+)/gi))
1412
+ out.add(m[1]);
1413
+ }
1414
+ return;
1415
+ }
1416
+ for (const v of Object.values(node))
1417
+ if (Array.isArray(v)) v.forEach(visit);
1418
+ else if (v && typeof v === 'object' && v.type) visit(v);
1419
+ };
1420
+ visit(ast.program);
1421
+ } catch {
1422
+ // Not one this reads.
1423
+ }
1424
+ return out;
1425
+ }
1426
+
1427
+ /**
1428
+ * The top-level tokens a base theme's built module gives (what the
1429
+ * editor's settings extend), or an empty map when it is not installed.
1430
+ * @param {string} cwd
1431
+ * @param {string | null | undefined} like
1432
+ * @returns {Map<string, string | null>}
1433
+ */
1434
+ export function baseTopTokens(cwd, like) {
1435
+ const file = like ? baseModule(cwd, like) : null;
1436
+ return file ? topTokensOf(file) : new Map();
1437
+ }
1438
+
1439
+ /**
1440
+ * The top-level tokens of a built theme module (plain data the build
1441
+ * wrote), or an empty map.
1442
+ * @param {string} file
1443
+ * @returns {Map<string, string | null>}
1444
+ */
1445
+ function topTokensOf(file) {
1446
+ /** @type {Map<string, string | null>} */
1447
+ const out = new Map();
1448
+ for (const [k, v] of blockOf(file, ['tokens']))
1449
+ if (k.startsWith('--')) out.set(k, v);
1450
+ return out;
1451
+ }
1452
+
1453
+ /**
1454
+ * One block of a built theme module (plain data the build wrote), by its
1455
+ * path from the theme object (`['tokens']`, `['components', 'card',
1456
+ * 'base']`): every key with its text value, a [light, dark] pair as the
1457
+ * build writes it, else null. An empty map when it is not there.
1458
+ * @param {string} file
1459
+ * @param {string[]} keys
1460
+ * @returns {Map<string, string | null>}
1461
+ */
1462
+ function blockOf(file, keys) {
1463
+ /** @type {Map<string, string | null>} */
1464
+ const out = new Map();
1465
+ try {
1466
+ const ast = /** @type {any} */ (
1467
+ parseModule(fs.readFileSync(file, 'utf8'), {
1468
+ sourceType: 'module',
1469
+ plugins: ['typescript'],
1470
+ })
1471
+ );
1472
+ for (const st of ast.program.body) {
1473
+ const decl = st.declaration?.declarations?.[0];
1474
+ /** @type {any} */
1475
+ let obj = decl?.init;
1476
+ // The generated settings module: defineTheme({...}).
1477
+ if (obj?.type === 'CallExpression') obj = obj.arguments?.[0];
1478
+ for (const key of keys)
1479
+ obj =
1480
+ obj?.type === 'ObjectExpression'
1481
+ ? obj.properties.find(
1482
+ (/** @type {any} */ p) => (p.key?.name ?? p.key?.value) === key,
1483
+ )?.value
1484
+ : undefined;
1485
+ if (obj?.type !== 'ObjectExpression') continue;
1486
+ for (const p of obj.properties) {
1487
+ const k = p.key?.value ?? p.key?.name;
1488
+ if (typeof k === 'string')
1489
+ out.set(
1490
+ k,
1491
+ p.value?.type === 'StringLiteral'
1492
+ ? p.value.value
1493
+ : // A [light, dark] pair, as the build writes it.
1494
+ p.value?.type === 'ArrayExpression' &&
1495
+ p.value.elements.length === 2 &&
1496
+ p.value.elements.every(
1497
+ (/** @type {any} */ e) => e?.type === 'StringLiteral',
1498
+ )
1499
+ ? `light-dark(${p.value.elements.map((/** @type {any} */ e) => e.value).join(', ')})`
1500
+ : null,
1501
+ );
1502
+ }
1503
+ if (out.size) break;
1504
+ }
1505
+ } catch {
1506
+ // No build yet, or not one this reads.
1507
+ }
1508
+ return out;
1509
+ }
1510
+
1511
+ /**
1512
+ * What a part's plain rule (its `base` block) holds in the theme as built
1513
+ * (the base theme's, the settings' and the own source's together), else in
1514
+ * the base theme alone when there is no build: tokens and properties by
1515
+ * name. Kebab-case property names, as the editor names them.
1516
+ * @param {string} cwd
1517
+ * @param {string} slug
1518
+ * @param {string | null | undefined} like
1519
+ * @param {string} part
1520
+ * @returns {Map<string, string | null>}
1521
+ */
1522
+ export function partRuleTokens(cwd, slug, like, part) {
1523
+ const built = blockOf(themeFiles(cwd, slug).js, ['components', part, 'base']);
1524
+ const baseFile = like ? baseModule(cwd, like) : null;
1525
+ const base = baseFile
1526
+ ? blockOf(baseFile, ['components', part, 'base'])
1527
+ : new Map();
1528
+ /** @type {Map<string, string | null>} */
1529
+ const out = new Map();
1530
+ for (const m of [base, built])
1531
+ for (const [k, v] of m)
1532
+ out.set(
1533
+ k.startsWith('--')
1534
+ ? k
1535
+ : k.replace(
1536
+ /[A-Z]/g,
1537
+ (/** @type {string} */ c) => `-${c.toLowerCase()}`,
1538
+ ),
1539
+ v,
1540
+ );
1541
+ return out;
1542
+ }
1543
+
1544
+ /**
1545
+ * The tokens and properties a theme's own source sets on a part's plain
1546
+ * rule, read from the build as ownTokens reads page-wide ones: what the
1547
+ * built rule holds that the settings module and the base theme do not give
1548
+ * as they are, and that the person's files name.
1549
+ * @param {string} cwd
1550
+ * @param {string} slug
1551
+ * @param {string} part
1552
+ * @param {string} [scope] the rule: `base` (the plain one), or a variant
1553
+ * such as `variant:primary`
1554
+ * @param {string | null} [state] a state block inside that rule (`:hover`)
1555
+ * @returns {Map<string, string | null>}
1556
+ */
1557
+ export function ownPartTokens(cwd, slug, part, scope = 'base', state = null) {
1558
+ const at = ['components', part, scope, ...(state ? [state] : [])];
1559
+ /** @type {Map<string, string | null>} */
1560
+ const out = new Map();
1561
+ const f = themeFiles(cwd, slug);
1562
+ /** @type {string} */
1563
+ let module;
1564
+ try {
1565
+ module = fs.readFileSync(f.settingsTs, 'utf8');
1566
+ } catch {
1567
+ return out;
1568
+ }
1569
+ const stamp = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1570
+ module,
1571
+ )?.[1];
1572
+ /** @param {string} k */
1573
+ const css = k =>
1574
+ k.startsWith('--')
1575
+ ? k
1576
+ : k.replace(/[A-Z]/g, (/** @type {string} */ c) => `-${c.toLowerCase()}`);
1577
+ // With no build made from the source as it is now (an edit since the last
1578
+ // build), the file is read as written, as ownTokens reads page tokens.
1579
+ if (!stamp || stamp !== themeSourceHash(cwd, slug)) {
1580
+ for (const [k, v] of blockOf(f.ts, at)) out.set(css(k), v);
1581
+ return out;
1582
+ }
1583
+ const like = /\/\/ Built on @astryxdesign\/theme-([a-z0-9-]+) /.exec(
1584
+ module,
1585
+ )?.[1];
1586
+ const baseFile = like ? baseModule(cwd, like) : null;
1587
+ const base = baseFile ? blockOf(baseFile, at) : new Map();
1588
+ const settings = blockOf(f.settingsTs, at);
1589
+ const named = namedInOwnSource(cwd, slug);
1590
+ for (const [k, v] of blockOf(f.js, at)) {
1591
+ const given = settings.has(k) ? settings.get(k) : base.get(k);
1592
+ if (given !== v && named(k)) out.set(css(k), v);
1593
+ }
1594
+ return out;
1595
+ }
1596
+
1597
+ /**
1598
+ * The page-wide tokens the theme's own source sets, read from what the
1599
+ * build made of it: the built module's top-level tokens that the
1600
+ * generated settings module does not give as they are (the own source wins
1601
+ * over the settings it extends). The build evaluates the file, so any way
1602
+ * of writing it counts (a namespace import, a renamed defineTheme, a
1603
+ * template, a spread of a shared object). Only a build made from the
1604
+ * source as it is now is read; with none, the file is read as written.
1605
+ * Both are joined: a key either names is the source's.
1606
+ * @param {string} cwd
1607
+ * @param {string} slug
1608
+ * @returns {Map<string, string | null>}
1609
+ */
1610
+ function ownTokens(cwd, slug) {
1611
+ const out = new Map(ownPageTokens(cwd, slug));
1612
+ const fromBuild = builtOwnTokens(cwd, slug);
1613
+ if (fromBuild) for (const [k, v] of fromBuild) out.set(k, v);
1614
+ return out;
1615
+ }
1616
+
1617
+ /**
1618
+ * The tokens the own source sets, as the current build shows them, or null
1619
+ * when there is no build made from the source as it is now.
1620
+ * @param {string} cwd
1621
+ * @param {string} slug
1622
+ * @returns {Map<string, string | null> | null}
1623
+ */
1624
+ function builtOwnTokens(cwd, slug) {
1625
+ const f = themeFiles(cwd, slug);
1626
+ /** @type {string} */
1627
+ let module;
1628
+ try {
1629
+ module = fs.readFileSync(f.settingsTs, 'utf8');
1630
+ } catch {
1631
+ return null;
1632
+ }
1633
+ const built = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1634
+ module,
1635
+ )?.[1];
1636
+ if (!built || !fs.existsSync(f.js) || built !== themeSourceHash(cwd, slug))
1637
+ return null;
1638
+ // What the settings module gives each top-level token: a text value as
1639
+ // it is, a [light, dark] pair as a pair.
1640
+ /** @type {Map<string, string | 'pair' | 'other'>} */
1641
+ const settings = new Map();
1642
+ try {
1643
+ const ast = /** @type {any} */ (
1644
+ parseModule(module, {sourceType: 'module', plugins: ['typescript']})
1645
+ );
1646
+ /** @param {any} node */
1647
+ const visit = node => {
1648
+ if (!node || typeof node !== 'object') return;
1649
+ if (
1650
+ node.type === 'CallExpression' &&
1651
+ node.callee?.name === 'defineTheme' &&
1652
+ node.arguments?.[0]?.type === 'ObjectExpression'
1653
+ ) {
1654
+ const tokens = node.arguments[0].properties.find(
1655
+ (/** @type {any} */ p) =>
1656
+ (p.key?.value ?? p.key?.name) === 'tokens' &&
1657
+ p.value?.type === 'ObjectExpression',
1658
+ );
1659
+ for (const p of tokens?.value.properties ?? []) {
1660
+ const k = p.key?.value ?? p.key?.name;
1661
+ if (typeof k !== 'string') continue;
1662
+ settings.set(
1663
+ k,
1664
+ p.value?.type === 'StringLiteral'
1665
+ ? p.value.value
1666
+ : p.value?.type === 'ArrayExpression'
1667
+ ? 'pair'
1668
+ : 'other',
1669
+ );
1670
+ }
1671
+ return;
1672
+ }
1673
+ for (const v of Object.values(node))
1674
+ if (Array.isArray(v)) v.forEach(visit);
1675
+ else if (v && typeof v === 'object' && v.type) visit(v);
1676
+ };
1677
+ visit(ast.program);
1678
+ } catch {
1679
+ return null;
1680
+ }
1681
+ // What the base theme's built module gives: the tokens the settings
1682
+ // extend, which are no more the source's than the settings' are.
1683
+ const like = /\/\/ Built on @astryxdesign\/theme-([a-z0-9-]+) /.exec(
1684
+ module,
1685
+ )?.[1];
1686
+ const baseFile = like ? baseModule(cwd, like) : null;
1687
+ const base = baseFile ? topTokensOf(baseFile) : new Map();
1688
+ const named = namedInOwnSource(cwd, slug);
1689
+ /** @type {Map<string, string | null>} */
1690
+ const out = new Map();
1691
+ for (const [k, v] of builtTopTokens(cwd, slug)) {
1692
+ const given = settings.get(k);
1693
+ const own =
1694
+ given === undefined
1695
+ ? !base.has(k) || base.get(k) !== v
1696
+ : given === 'pair'
1697
+ ? !/^light-dark\(/.test(String(v ?? ''))
1698
+ : given !== 'other' && given !== v;
1699
+ if (own && named(k)) out.set(k, v);
1700
+ }
1701
+ return out;
1702
+ }
1703
+
1704
+ /**
1705
+ * Whether a token or property name appears in the person's theme files: a
1706
+ * value the build shows that no file of theirs names came from the
1707
+ * settings (a dial's typography, a lifted value), not from them.
1708
+ * @param {string} cwd
1709
+ * @param {string} slug
1710
+ * @returns {(name: string) => boolean}
1711
+ */
1712
+ function namedInOwnSource(cwd, slug) {
1713
+ const text = ownSourceFiles(cwd, slug)
1714
+ .map(file => {
1715
+ try {
1716
+ return fs.readFileSync(file, 'utf8');
1717
+ } catch {
1718
+ return '';
1719
+ }
1720
+ })
1721
+ .join('\n');
1722
+ // A font set through `typography` (heading: {family: ...}) names its
1723
+ // role there, not the token the build writes for it.
1724
+ const typography = /\btypography\b/.test(text);
1725
+ return name =>
1726
+ text.includes(name) ||
1727
+ (typography &&
1728
+ (/^--font-family-([a-z]+)$/.exec(name)?.[1] ?? '') !== '' &&
1729
+ text.includes(
1730
+ /** @type {string[]} */ (/^--font-family-([a-z]+)$/.exec(name))[1],
1731
+ )) ||
1732
+ (typography &&
1733
+ /^--text-([a-z]+)-\d*-?weight$/.test(name) &&
1734
+ text.includes(
1735
+ /** @type {string[]} */ (/^--text-([a-z]+)/.exec(name))[1],
1736
+ ) &&
1737
+ /weight/.test(text)) ||
1738
+ // A property may be written camelCase (borderRadius).
1739
+ (!name.startsWith('--') &&
1740
+ text.includes(name.replace(/-([a-z])/g, (_, c) => c.toUpperCase())));
1741
+ }
1742
+
1743
+ /**
1744
+ * The page-wide tokens a theme's own source sets itself (see ownTokens):
1745
+ * they win over the settings it extends.
1746
+ * @param {string} cwd
1747
+ * @param {string} slug
1748
+ * @returns {string[]}
1749
+ */
1750
+ export function ownSourceTokens(cwd, slug) {
1751
+ return [...ownTokens(cwd, slug).keys()];
1752
+ }
1753
+
1754
+ /**
1755
+ * The values a theme's own source gives page-wide tokens as plain text, by
1756
+ * token (see ownTokens).
1757
+ * @param {string} cwd
1758
+ * @param {string} slug
1759
+ * @returns {Record<string, string>}
1760
+ */
1761
+ export function ownSourceTokenValues(cwd, slug) {
1762
+ /** @type {Record<string, string>} */
1763
+ const out = {};
1764
+ for (const [k, v] of ownTokens(cwd, slug)) if (v != null) out[k] = v;
1765
+ return out;
659
1766
  }
660
1767
 
661
1768
  /**
@@ -723,7 +1830,11 @@ export {modesOf};
723
1830
  * @returns {number | null}
724
1831
  */
725
1832
  export function lengthPx(v) {
726
- const m = /^\s*(-?\d+(?:\.\d+)?|-?\.\d+)\s*(px|rem|em)?\s*$/i.exec(String(v));
1833
+ // A CSS number: a sign, digits with or without a fraction, an exponent.
1834
+ const m =
1835
+ /^\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)\s*(px|rem|em)?\s*$/i.exec(
1836
+ String(v),
1837
+ );
727
1838
  if (!m) return null;
728
1839
  const n = Number(m[1]);
729
1840
  return (m[2] ?? 'px').toLowerCase() === 'px' ? n : n * 16;
@@ -768,7 +1879,8 @@ export function fontOf(value) {
768
1879
  .split(',')
769
1880
  .map(x => x.trim())
770
1881
  .filter(Boolean);
771
- const family = unquote(parts[0] ?? v);
1882
+ // Runs of spaces or tabs inside a family name are one space.
1883
+ const family = familySpaces(unquote(parts[0] ?? v)).trim();
772
1884
  return {
773
1885
  family: cssFamily(family),
774
1886
  fallbacks:
@@ -779,6 +1891,19 @@ export function fontOf(value) {
779
1891
  };
780
1892
  }
781
1893
 
1894
+ /**
1895
+ * Spacing in a font family name as CSS reads a bare name: every Unicode
1896
+ * space (a no-break space, a thin space, a tab) is one space, a run of them
1897
+ * one, and zero-width and format characters (zero-width space, joiners,
1898
+ * word joiner, byte-order mark) are dropped.
1899
+ * @param {string} v
1900
+ */
1901
+ export function familySpaces(v) {
1902
+ return v
1903
+ .replace(/[\u200B-\u200D\u2060\uFEFF]/g, '')
1904
+ .replace(/[\s\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g, ' ');
1905
+ }
1906
+
782
1907
  /**
783
1908
  * A font family name as CSS reads it. A name that is a sequence of CSS
784
1909
  * identifiers stays bare; any other is quoted, or the browser drops the
@@ -789,6 +1914,7 @@ export function fontOf(value) {
789
1914
  * @param {boolean} [spaced]
790
1915
  */
791
1916
  export function cssFamily(name, spaced = false) {
1917
+ name = familySpaces(name);
792
1918
  const words = name.trim().split(/\s+/);
793
1919
  const ident = (/** @type {string} */ w) =>
794
1920
  /^-?(?:[A-Za-z_]|[\u0080-\uffff])(?:[\w-]|[\u0080-\uffff])*$/.test(w) &&
@@ -849,6 +1975,42 @@ function sealModule(text) {
849
1975
  );
850
1976
  }
851
1977
 
1978
+ /**
1979
+ * The staleness reason for an own source changed since the editor's build.
1980
+ * @param {string} slug
1981
+ */
1982
+ export function sourceChangedReason(slug) {
1983
+ return `${slug}.theme.ts or a module it imports changed since the last build`;
1984
+ }
1985
+
1986
+ /** The type tokens base themes set again for phones: families and weights. */
1987
+ export const PHONE_TYPE = /^--font-family|^--(text-[a-z0-9-]+|font)-weight/;
1988
+
1989
+ /**
1990
+ * Record in an editor theme's generated settings that they were built with
1991
+ * its own source as it is now, after `compile` built that source (the
1992
+ * settings do not depend on what the source sets), only in a module as the
1993
+ * editor wrote it.
1994
+ * @param {string} cwd
1995
+ * @param {string} slug
1996
+ * @returns {boolean} whether it was recorded
1997
+ */
1998
+ export function refreshSourceStamp(cwd, slug) {
1999
+ const f = themeFiles(cwd, slug);
2000
+ const ts = fs.readFileSync(f.settingsTs, 'utf8');
2001
+ if (moduleUnedited(ts) !== true) return false;
2002
+ const stamp = /\/\/ Built with (\S+\.theme\.ts) ([0-9a-f]{16})\./.exec(ts);
2003
+ if (!stamp) return false;
2004
+ const now = themeSourceHash(cwd, slug);
2005
+ if (stamp[2] === now) return true;
2006
+ const text = ts
2007
+ .replace(/\r\n/g, '\n')
2008
+ .replace(SEAL, '')
2009
+ .replace(stamp[0], `// Built with ${stamp[1]} ${now}.`);
2010
+ fs.writeFileSync(f.settingsTs, sealModule(text));
2011
+ return true;
2012
+ }
2013
+
852
2014
  /**
853
2015
  * Whether a generated module is as the editor wrote it: true, false for a
854
2016
  * hand edit, null for a module with no hash (an earlier editor's).
@@ -939,6 +2101,39 @@ function keepShades(pal, kept) {
939
2101
  return {...pal, tokens, lift: kept['lifted parts'] ? pal.lift : null};
940
2102
  }
941
2103
 
2104
+ /**
2105
+ * Control heights scaled with the spacing dial (a denser theme has shorter
2106
+ * controls), each kept distinct and in order: smallest to largest, a
2107
+ * control never under 24px (the smallest target a pointer can use
2108
+ * comfortably, unless the theme starts below it), each the plain scaled
2109
+ * value unless it would meet the one below, which then keeps its own step
2110
+ * scaled above it.
2111
+ * @param {Array<[string, string]>} sizes token name and the theme's value
2112
+ * @param {number} f the spacing rung's factor
2113
+ * @returns {Array<[string, string]>} the tokens it writes, in px
2114
+ */
2115
+ export function controlSizes(sizes, f) {
2116
+ const px = sizes
2117
+ .filter(([, v]) => /^[\d.]+px$/.test(String(v).trim()))
2118
+ .map(([k, v]) => /** @type {[string, number]} */ ([k, parseFloat(v)]))
2119
+ .sort((a, b) => a[1] - b[1]);
2120
+ /** @type {Array<[string, string]>} */
2121
+ const out = [];
2122
+ let prev = null;
2123
+ let prevOwn = null;
2124
+ for (const [k, v] of px) {
2125
+ let n = Math.max(Math.min(24, v), Math.round(v * f));
2126
+ // Only a size that would meet (or pass) the one below moves: the plain
2127
+ // scaled value otherwise.
2128
+ if (prev != null && prevOwn != null && n <= prev)
2129
+ n = prev + Math.max(1, Math.round((v - prevOwn) * f));
2130
+ out.push([k, `${n}px`]);
2131
+ prev = n;
2132
+ prevOwn = v;
2133
+ }
2134
+ return out;
2135
+ }
2136
+
942
2137
  /**
943
2138
  * The settings, as a `defineTheme` object.
944
2139
  * @param {Ctx} ctx
@@ -974,11 +2169,9 @@ export function compileTheme(ctx, data, base) {
974
2169
  /** @param {string} name @param {string | [string, string]} v @param {string} [mode] */
975
2170
  const putTok = (name, v, mode) => {
976
2171
  const t = (tok[name] ??= {});
977
- // A one-mode theme writes the value of its mode to both sides.
978
- if (Array.isArray(v) && modeOnly) {
979
- t.light = t.dark = v[modeOnly === 'light' ? 0 : 1];
980
- return;
981
- }
2172
+ // A one-mode theme keeps both halves of a pair: its mode is the one the
2173
+ // app's <Theme> is given, and a region Core draws in the other mode
2174
+ // (a toast, a lightbox) still reads the other half.
982
2175
  if (Array.isArray(v)) {
983
2176
  if (!mode || mode === 'light') t.light = v[0];
984
2177
  if (!mode || mode === 'dark') t.dark = v[1];
@@ -1000,10 +2193,580 @@ export function compileTheme(ctx, data, base) {
1000
2193
  if (tg?.states.includes(s.state) && s.when == null) b = t[s.state] ??= {};
1001
2194
  else if (tg?.states.includes(s.state))
1002
2195
  b = t[`${s.when}+${s.state}`] ??= {};
1003
- else b = b[stateKey(s.state)] ??= {};
2196
+ else b = b[stateKey(s.state, wrapsOneControl(ctx, target))] ??= {};
1004
2197
  }
1005
2198
  return b;
1006
2199
  };
2200
+ /**
2201
+ * A padding on a part whose padding Core writes one variable per side
2202
+ * (its derivedVarRegistry's container expansion), as each side's value,
2203
+ * split at top-level spaces by the CSS shorthand rules: Core splits a
2204
+ * shorthand at every space, which cuts calc(4px + 2px) and loses a
2205
+ * fourth value. On the part itself the sides go as logical longhands,
2206
+ * which Core carries as they are; for a variant or state they go to the
2207
+ * side variables themselves, since Core writes one variable for equal
2208
+ * sides there and the part's own side variables would win over it.
2209
+ * Null for any other property or part.
2210
+ * @param {string} target @param {Setting} s
2211
+ * @returns {Record<string, string> | null}
2212
+ */
2213
+ const containerSides = (target, s) => {
2214
+ const prop = kebab(s.thing);
2215
+ if (
2216
+ s.mode ||
2217
+ !/^padding(-block|-inline|-left|-right|-top|-bottom|-block-start|-block-end|-inline-start|-inline-end)?$/.test(
2218
+ prop,
2219
+ )
2220
+ )
2221
+ return null;
2222
+ if (
2223
+ !(ctx.derived?.[target] ?? []).some(
2224
+ d => d.property === 'padding' && d.expand,
2225
+ )
2226
+ )
2227
+ return null;
2228
+ const scoped0 = s.when != null || s.state != null;
2229
+ // padding's initial value is 0, and padding does not inherit, so unset
2230
+ // is 0 too: on Core's side variables a keyword means no value at all.
2231
+ const value = /^(initial|unset)$/i.test(String(s.value).trim())
2232
+ ? '0'
2233
+ : String(s.value).trim();
2234
+ // A physical left or right stays physical, as Core keeps it (it maps
2235
+ // no physical side to a logical one but top and bottom, which it maps
2236
+ // itself): it is written as it is, and a later padding that covers it
2237
+ // takes it out of the block (below).
2238
+ const physical = /** @type {Record<string, string>} */ ({
2239
+ // One logical side is that side (its keyword resolved too).
2240
+ 'padding-block-start': 'block-start',
2241
+ 'padding-block-end': 'block-end',
2242
+ 'padding-inline-start': 'inline-start',
2243
+ 'padding-inline-end': 'inline-end',
2244
+ 'padding-top': 'block-start',
2245
+ 'padding-bottom': 'block-end',
2246
+ })[prop];
2247
+ if (physical)
2248
+ return {
2249
+ [scoped0
2250
+ ? `--astryx-${target}-padding-${physical}`
2251
+ : camel(`padding-${physical}`)]: value,
2252
+ };
2253
+ // A physical left or right is written as it is (its keyword resolved),
2254
+ // never split as an axis: there is no padding-left-start.
2255
+ if (prop === 'padding-left' || prop === 'padding-right')
2256
+ return {[camel(prop)]: value};
2257
+ const w = splitTop(value, ' ').map(x => x.trim());
2258
+ if (!w.length || w.length > (prop === 'padding' ? 4 : 2)) return null;
2259
+ const scoped = s.when != null || s.state != null;
2260
+ // Only what Core would split wrong is written side by side: math or a
2261
+ // function, four values with different left and right sides; and, for
2262
+ // a variant or state, any padding once the part sets a side itself.
2263
+ const coreSplitsWrong =
2264
+ value !== String(s.value).trim() ||
2265
+ /\(/.test(value) ||
2266
+ (prop === 'padding' && w.length === 4 && w[1] !== w[3]);
2267
+ const partSides = data.settings.some(
2268
+ x =>
2269
+ x !== s &&
2270
+ x.source === 'property' &&
2271
+ // The part's own, or a group's it is in.
2272
+ (x.on === s.on ||
2273
+ (FAMILIES[/** @type {string} */ (x.on)] ?? []).includes(target)) &&
2274
+ x.when == null &&
2275
+ x.state == null &&
2276
+ (/^padding-/.test(kebab(x.thing)) ||
2277
+ (kebab(x.thing) === 'padding' &&
2278
+ /\(|\S+\s+\S+\s+\S+\s+\S+/.test(x.value))),
2279
+ );
2280
+ // A side set on the part or its group: every side is written, so the
2281
+ // later setting wins as written.
2282
+ if (!coreSplitsWrong && !partSides) return null;
2283
+ /** @type {Record<string, string>} */
2284
+ const side = {};
2285
+ if (prop === 'padding') {
2286
+ const [top, right = top, bottom = top, left = right] = w;
2287
+ Object.assign(side, {
2288
+ 'block-start': top,
2289
+ 'inline-end': right,
2290
+ 'block-end': bottom,
2291
+ 'inline-start': left,
2292
+ });
2293
+ } else {
2294
+ const axis = prop.slice('padding-'.length);
2295
+ side[`${axis}-start`] = w[0];
2296
+ side[`${axis}-end`] = w[1] ?? w[0];
2297
+ }
2298
+ return Object.fromEntries(
2299
+ Object.entries(side).map(([k, v]) => [
2300
+ scoped ? `--astryx-${target}-padding-${k}` : camel(`padding-${k}`),
2301
+ v,
2302
+ ]),
2303
+ );
2304
+ };
2305
+ /**
2306
+ * A radius of more than one value on a part whose radius Core copies
2307
+ * into a variable for the content inside it (a card's full-bleed
2308
+ * children), as each corner's own radius, so Core writes no copy of the
2309
+ * whole value there (where one corner reads it, and `10px / 20px` or four
2310
+ * values are wrong). The inner variable takes one radius, the first
2311
+ * corner's across: Core gives the content one radius for every corner.
2312
+ * Null for any other property, part or a single radius.
2313
+ * @param {string} target @param {Setting} s
2314
+ * @returns {Record<string, string> | null}
2315
+ */
2316
+ const cornerRadii = (target, s) => {
2317
+ if (s.mode || kebab(s.thing) !== 'border-radius') return null;
2318
+ const vars = (ctx.derived?.[target] ?? []).find(
2319
+ d => d.property === 'borderRadius' && d.vars?.length,
2320
+ )?.vars;
2321
+ if (!vars) return null;
2322
+ const [across, down] = splitTop(String(s.value).trim(), '/').map(x =>
2323
+ splitTop(x.trim(), ' ').map(y => y.trim()),
2324
+ );
2325
+ if (!across?.length || (across.length === 1 && !down)) return null;
2326
+ /** @param {string[]} w top-left, top-right, bottom-right, bottom-left */
2327
+ const four = w => {
2328
+ const [tl, tr = tl, br = tl, bl = tr] = w;
2329
+ return [tl, tr, br, bl];
2330
+ };
2331
+ const h = four(across);
2332
+ const v = down?.length ? four(down) : null;
2333
+ const corner = (/** @type {number} */ i) =>
2334
+ v && v[i] !== h[i] ? `${h[i]} ${v[i]}` : h[i];
2335
+ // The whole radius as one value first, which Core turns into the
2336
+ // part's inner-corner variable itself (a theme writes no private
2337
+ // variable), then each corner, which the box shows.
2338
+ return {
2339
+ borderRadius: h[0],
2340
+ borderTopLeftRadius: corner(0),
2341
+ borderTopRightRadius: corner(1),
2342
+ borderBottomRightRadius: corner(2),
2343
+ borderBottomLeftRadius: corner(3),
2344
+ };
2345
+ };
2346
+ /**
2347
+ * A one-side logical padding on a part whose whole padding Core copies
2348
+ * into a variable of its own (a composer's or a menu's inner padding),
2349
+ * written for each direction (a left-to-right box's left is a
2350
+ * right-to-left box's right): Core feeds every logical padding into that
2351
+ * variable, so one side would set the whole box. Null for any other
2352
+ * property or part.
2353
+ * @param {string} target @param {Setting} s
2354
+ * @returns {Record<string, string | Record<string, string>> | null}
2355
+ */
2356
+ const boxSides = (target, s) => {
2357
+ const prop = kebab(s.thing);
2358
+ if (s.mode) return null;
2359
+ const derived = ctx.derived?.[target] ?? [];
2360
+ if (
2361
+ derived.some(d => d.property === 'padding' && d.expand) ||
2362
+ !derived.some(d => d.property === 'padding' && d.vars?.length)
2363
+ )
2364
+ return null;
2365
+ const SIDES = /** @type {Record<string, string[]>} */ ({
2366
+ 'padding-block-start': ['block-start'],
2367
+ 'padding-block-end': ['block-end'],
2368
+ 'padding-inline-start': ['inline-start'],
2369
+ 'padding-inline-end': ['inline-end'],
2370
+ 'padding-block': ['block-start', 'block-end'],
2371
+ 'padding-inline': ['inline-start', 'inline-end'],
2372
+ });
2373
+ const sides = SIDES[prop];
2374
+ if (!sides) return null;
2375
+ const w = splitTop(String(s.value).trim(), ' ').map(x => x.trim());
2376
+ // Each side for each direction: a block side is the top or bottom; an
2377
+ // inline side is the left in a left-to-right box and the right in a
2378
+ // right-to-left one, written under :dir(), where Core writes the
2379
+ // declarations as they are and feeds none into the whole-box variable.
2380
+ /** @type {Record<string, string>} */
2381
+ const plain = {};
2382
+ /** @type {Record<string, string>} */
2383
+ const ltr = {};
2384
+ /** @type {Record<string, string>} */
2385
+ const rtl = {};
2386
+ sides.forEach((side, i) => {
2387
+ const v = w[i] ?? w[0];
2388
+ if (side === 'block-start') plain.paddingTop = v;
2389
+ else if (side === 'block-end') plain.paddingBottom = v;
2390
+ else if (side === 'inline-start') {
2391
+ ltr.paddingLeft = v;
2392
+ rtl.paddingRight = v;
2393
+ } else {
2394
+ ltr.paddingRight = v;
2395
+ rtl.paddingLeft = v;
2396
+ }
2397
+ });
2398
+ return {
2399
+ ...plain,
2400
+ ...(Object.keys(ltr).length ? {':dir(ltr)': ltr, ':dir(rtl)': rtl} : {}),
2401
+ };
2402
+ };
2403
+ /**
2404
+ * A padding on a part whose visible box sits inside its themed wrapper,
2405
+ * as the padding variable that box reads, not the wrapper's own padding
2406
+ * (which would add a gap outside the box). Null for any other part.
2407
+ * @param {string} target @param {Setting} s
2408
+ * @returns {Record<string, string> | null}
2409
+ */
2410
+ const wrappedPadding = (target, s) => {
2411
+ if (s.mode || !WRAPPED_PARTS[target] || kebab(s.thing) !== 'padding')
2412
+ return null;
2413
+ const name = (ctx.derived?.[target] ?? []).find(
2414
+ d => d.property === 'padding' && d.vars?.length,
2415
+ )?.vars?.[0];
2416
+ // The box reads only Core's own variable, which a theme may not write,
2417
+ // and a padding property would pad the wrapper: nothing is written (a
2418
+ // saved one is refused, as set refuses it).
2419
+ return name ? {} : null;
2420
+ };
2421
+ /**
2422
+ * The prefix of the padding variables a part's box reads, for a part whose
2423
+ * padding Core writes to them (its derivedVarRegistry's container
2424
+ * expansion), or for one drawn by such a part (a clickable card is a
2425
+ * card); null for any other part.
2426
+ * @param {string} target
2427
+ */
2428
+ const padVars = target => {
2429
+ if (
2430
+ (ctx.derived?.[target] ?? []).some(
2431
+ d => d.property === 'padding' && d.expand,
2432
+ )
2433
+ )
2434
+ return `--astryx-${target}-padding`;
2435
+ return CARD_LIKE.includes(target) ? '--astryx-card-padding' : null;
2436
+ };
2437
+ /**
2438
+ * Padding settings per part and per scope (the block a setting writes
2439
+ * to), in the order they were made.
2440
+ * @type {Map<string, {target: string, s: Setting, list: Setting[]}>}
2441
+ */
2442
+ const padQueue = new Map();
2443
+ /** @param {Setting} s @param {string} target */
2444
+ const queuePadding = (s, target) => {
2445
+ const key = `${target}\0${s.when ?? ''}\0${s.state ?? ''}`;
2446
+ const q = padQueue.get(key) ?? {target, s, list: []};
2447
+ q.list.push(s);
2448
+ padQueue.set(key, q);
2449
+ };
2450
+ /**
2451
+ * One padding model: each scope's settings, in order, resolved to the
2452
+ * four logical sides for each direction (a physical left is the
2453
+ * inline-start in a left-to-right box and the inline-end in a
2454
+ * right-to-left one; the padding shorthand is physical too), then written
2455
+ * to the variables the part's box reads: a side the same in both
2456
+ * directions in the scope's own block, one that differs in a rule for
2457
+ * each direction (one level deep under a state). So the derived and
2458
+ * full-bleed values follow, and a variant or a state out-ranks the base
2459
+ * as Core's own rules do.
2460
+ */
2461
+ const emitPadding = () => {
2462
+ // The side variables written on a narrower selector (a variant, a
2463
+ // state, a clickable card), by the part whose variables they are, with
2464
+ // that selector: they inherit, so a plain one of those parts inside is
2465
+ // reset to its own fallback (below), never given a copy of a value.
2466
+ /** @type {Map<string, Map<string, Set<string>>>} */
2467
+ const narrow = new Map();
2468
+ /** A side as CSS reads it inside calc(): a bare 0 is no length. @param {string} v */
2469
+ const length = v => {
2470
+ const n = cssNumber(v);
2471
+ return n && n.unit === '' && n.value === 0 ? '0px' : v;
2472
+ };
2473
+ for (const {target, s, list} of padQueue.values()) {
2474
+ // The own source's padding on the same rule wins over the editor's:
2475
+ // nothing is written there (the result says so).
2476
+ if (ownPads(target, s)) continue;
2477
+ const prefix = /** @type {string} */ (padVars(target));
2478
+ const owner = prefix.slice('--astryx-'.length, -'-padding'.length);
2479
+ const scoped = target !== owner || s.when != null || s.state != null;
2480
+ /** @type {Record<'ltr' | 'rtl', Record<string, string>>} */
2481
+ const side = {ltr: {}, rtl: {}};
2482
+ for (const x of list) {
2483
+ const prop = kebab(x.thing);
2484
+ const raw = String(x.value).trim();
2485
+ // initial and unset leave the variable without a value, so the part
2486
+ // takes Core's own default for it.
2487
+ const value = /^(initial|unset|inherit|revert|revert-layer)$/i.test(raw)
2488
+ ? 'initial'
2489
+ : raw;
2490
+ const w = splitTop(value, ' ').map(y => length(y.trim()));
2491
+ const one = length(value);
2492
+ for (const dir of /** @type {const} */ (['ltr', 'rtl'])) {
2493
+ const o = side[dir];
2494
+ const left = dir === 'ltr' ? 'inline-start' : 'inline-end';
2495
+ const right = dir === 'ltr' ? 'inline-end' : 'inline-start';
2496
+ if (prop === 'padding') {
2497
+ const [top, r = top, bottom = top, l = r] = w;
2498
+ Object.assign(o, {
2499
+ 'block-start': top,
2500
+ [right]: r,
2501
+ 'block-end': bottom,
2502
+ [left]: l,
2503
+ });
2504
+ } else if (prop === 'padding-block') {
2505
+ o['block-start'] = w[0];
2506
+ o['block-end'] = w[1] ?? w[0];
2507
+ } else if (prop === 'padding-inline') {
2508
+ o['inline-start'] = w[0];
2509
+ o['inline-end'] = w[1] ?? w[0];
2510
+ } else if (prop === 'padding-top') o['block-start'] = one;
2511
+ else if (prop === 'padding-bottom') o['block-end'] = one;
2512
+ else if (prop === 'padding-left') o[left] = one;
2513
+ else if (prop === 'padding-right') o[right] = one;
2514
+ else {
2515
+ const k = prop.slice('padding-'.length);
2516
+ if (/^(block|inline)-(start|end)$/.test(k)) o[k] = one;
2517
+ }
2518
+ }
2519
+ }
2520
+ /** @type {Record<string, string>} */
2521
+ let plain = {};
2522
+ /** @type {Record<string, string>} */
2523
+ const ltr = {};
2524
+ /** @type {Record<string, string>} */
2525
+ const rtl = {};
2526
+ for (const k of [
2527
+ 'block-start',
2528
+ 'block-end',
2529
+ 'inline-start',
2530
+ 'inline-end',
2531
+ ]) {
2532
+ const [a, b] = [side.ltr[k], side.rtl[k]];
2533
+ if (a != null && a === b) plain[`${prefix}-${k}`] = a;
2534
+ else {
2535
+ if (a != null) ltr[`${prefix}-${k}`] = a;
2536
+ if (b != null) rtl[`${prefix}-${k}`] = b;
2537
+ }
2538
+ }
2539
+ // On the part's own base, a side that is the same in both
2540
+ // directions is written as its logical padding property, which Core
2541
+ // lowers to the variables together with the base theme's and the own
2542
+ // source's padding in the same block: the later wins by key, and four
2543
+ // equal sides come out as the whole padding (a nested section keeps
2544
+ // following its parent's), whatever sides the base theme set.
2545
+ // Only the plain rule: a variant's or a state's rule written that way
2546
+ // would come out as the whole padding alone, which the base's own side
2547
+ // variables out-rank.
2548
+ const lowered = target === owner && !s.when && !s.state;
2549
+ if (lowered)
2550
+ plain = Object.fromEntries(
2551
+ Object.entries(plain).map(([k, v]) => [
2552
+ camel(`padding-${k.slice(prefix.length + 1)}`),
2553
+ v,
2554
+ ]),
2555
+ );
2556
+ // A part drawn by another (a clickable card) writes its sides for each
2557
+ // direction too, so a direction rule the card's own base has never
2558
+ // out-ranks it.
2559
+ if (target !== owner)
2560
+ for (const [k, v] of Object.entries(plain)) {
2561
+ ltr[k] ??= v;
2562
+ rtl[k] ??= v;
2563
+ }
2564
+ if (scoped) {
2565
+ const sel = narrowSelector(target, s);
2566
+ if (sel) {
2567
+ const bySel = narrow.get(owner) ?? new Map();
2568
+ const names = bySel.get(sel) ?? new Set();
2569
+ for (const k of [
2570
+ ...Object.keys(plain),
2571
+ ...Object.keys(ltr),
2572
+ ...Object.keys(rtl),
2573
+ ])
2574
+ names.add(k);
2575
+ bySel.set(sel, names);
2576
+ narrow.set(owner, bySel);
2577
+ }
2578
+ }
2579
+ for (const [k, v] of Object.entries(plain)) putComp(s, target, k, v);
2580
+ for (const [dir, rule] of /** @type {const} */ ([
2581
+ [':dir(ltr)', ltr],
2582
+ [':dir(rtl)', rtl],
2583
+ ]))
2584
+ if (Object.keys(rule).length) {
2585
+ const [b, key] = dirBlock(s, target, dir);
2586
+ b[key] = {...(b[key] ?? {}), ...rule};
2587
+ }
2588
+ }
2589
+ // A plain part inside a narrower one: each side the narrower selector
2590
+ // writes is reset (left without a value, so Core's own fallback holds),
2591
+ // on the part's own class at its own weight, before any base setting a
2592
+ // theme gives it (the part's own base, or a source of the user's own,
2593
+ // which comes later and so wins).
2594
+ for (const [owner, bySel] of narrow) {
2595
+ const b = ((theme.components[owner] ??= {}).base ??= {});
2596
+ // The variables Core writes on the part's own rule, from the base
2597
+ // theme's, the settings' and the own source's padding there: the
2598
+ // reset leaves those alone, so the part's own value always holds.
2599
+ const own = basePaddingVars(owner, b);
2600
+ for (const [sel, names] of bySel) {
2601
+ /** @type {Record<string, string>} */
2602
+ const reset = {};
2603
+ for (const name of names)
2604
+ if (!(name in b) && !own.has(name)) reset[name] = 'initial';
2605
+ if (Object.keys(reset).length) {
2606
+ const key = `:where(${sel} *)`;
2607
+ b[key] = {...(b[key] ?? {}), ...reset};
2608
+ }
2609
+ }
2610
+ }
2611
+ };
2612
+ /**
2613
+ * The padding variables Core writes on a part's plain rule, as Core lowers
2614
+ * the padding properties there (the base theme's, then the settings',
2615
+ * then the own source's, later keys winning): the whole padding when the
2616
+ * four sides are equal, else each side given (an inline pair as one).
2617
+ * @param {string} owner @param {Record<string, any>} mine
2618
+ * @returns {Set<string>}
2619
+ */
2620
+ const basePaddingVars = (owner, mine) => {
2621
+ const prefix = `--astryx-${owner}-padding`;
2622
+ /** @type {Array<[string, string]>} */
2623
+ const keys = [];
2624
+ const fromBase = /** @type {any} */ (base).components?.[owner]?.base ?? {};
2625
+ for (const [k, v] of Object.entries(fromBase))
2626
+ if (typeof v === 'string') keys.push([k, v]);
2627
+ for (const [k, v] of Object.entries(mine))
2628
+ if (typeof v === 'string') keys.push([k, v]);
2629
+ try {
2630
+ for (const [k, v] of ownPartTokens(ctx.project.cwd, data.name, owner))
2631
+ if (v != null && !k.startsWith('--')) keys.push([camel(k), v]);
2632
+ } catch {
2633
+ // No own source.
2634
+ }
2635
+ /** @type {Record<string, string | undefined>} */
2636
+ const r = {};
2637
+ for (const [k, v] of keys) {
2638
+ const w = splitTop(v.trim(), ' ');
2639
+ if (k === 'padding') {
2640
+ r.bs = w[0];
2641
+ r.in = w[1] ?? w[0];
2642
+ r.be = w[2] ?? w[0];
2643
+ delete r.is;
2644
+ delete r.ie;
2645
+ } else if (k === 'paddingBlock') {
2646
+ r.bs = w[0];
2647
+ r.be = w[1] ?? w[0];
2648
+ } else if (k === 'paddingInline') {
2649
+ if (w.length > 1) [r.is, r.ie] = w;
2650
+ else r.in = w[0];
2651
+ } else if (k === 'paddingTop' || k === 'paddingBlockStart') r.bs = v;
2652
+ else if (k === 'paddingBottom' || k === 'paddingBlockEnd') r.be = v;
2653
+ else if (k === 'paddingInlineStart') r.is = v;
2654
+ else if (k === 'paddingInlineEnd') r.ie = v;
2655
+ }
2656
+ const out = new Set(Object.keys(mine).filter(k => k.startsWith(prefix)));
2657
+ const is = r.is ?? r.in;
2658
+ const ie = r.ie ?? r.in;
2659
+ if (is != null && is === ie && r.bs === is && r.be === is) out.add(prefix);
2660
+ else {
2661
+ if (r.is != null || r.ie != null) {
2662
+ if (is != null) out.add(`${prefix}-inline-start`);
2663
+ if (ie != null) out.add(`${prefix}-inline-end`);
2664
+ } else if (r.in != null) out.add(`${prefix}-inline`);
2665
+ if (r.bs != null) out.add(`${prefix}-block-start`);
2666
+ if (r.be != null) out.add(`${prefix}-block-end`);
2667
+ }
2668
+ return out;
2669
+ };
2670
+ /**
2671
+ * Whether the theme's own source sets a padding on a part's rule for a
2672
+ * scope (its plain rule, a variant, a state).
2673
+ * @param {string} target @param {Setting} s
2674
+ */
2675
+ const ownPads = (target, s) => {
2676
+ try {
2677
+ return [
2678
+ ...ownPartTokens(
2679
+ ctx.project.cwd,
2680
+ data.name,
2681
+ target,
2682
+ s.when ?? 'base',
2683
+ s.state ? `:${s.state}` : null,
2684
+ ).keys(),
2685
+ ].some(k => /^padding(-|$)/.test(k));
2686
+ } catch {
2687
+ return false;
2688
+ }
2689
+ };
2690
+ /**
2691
+ * The selector a narrower padding scope is written with (a clickable
2692
+ * card's class, a variant's attribute, a state's pseudo-class), or null
2693
+ * for a state Core writes as a block of its own.
2694
+ * @param {string} target @param {Setting} s
2695
+ */
2696
+ const narrowSelector = (target, s) => {
2697
+ const tg = ctx.project.target.get(target);
2698
+ if (s.state && tg?.states.includes(s.state)) return null;
2699
+ const [k, v] = s.when ? String(s.when).split(':') : [];
2700
+ return `.astryx-${target}${s.when ? `[data-${k}="${v}"]` : ''}${s.state ? stateKey(s.state, wrapsOneControl(ctx, target)) : ''}`;
2701
+ };
2702
+
2703
+ /**
2704
+ * Each part's blocks with its base first, and in each block the rules for
2705
+ * a direction before a state's: Core writes them in this order, and a
2706
+ * variant or a state comes after the base it out-ranks (rules of the same
2707
+ * weight win by order).
2708
+ */
2709
+ const orderBlocks = () => {
2710
+ /** @param {Record<string, any>} b @returns {Record<string, any>} */
2711
+ const dirFirst = b => {
2712
+ const keys = Object.keys(b);
2713
+ const plain = keys.filter(k => !k.startsWith(':'));
2714
+ const dirs = keys.filter(k => /^:(where\()?dir\(/.test(k));
2715
+ const rest = keys.filter(
2716
+ k => k.startsWith(':') && !/^:(where\()?dir\(/.test(k),
2717
+ );
2718
+ return Object.fromEntries(
2719
+ [...plain, ...dirs, ...rest].map(k => [
2720
+ k,
2721
+ k.startsWith(':') && b[k] && typeof b[k] === 'object'
2722
+ ? dirFirst(b[k])
2723
+ : b[k],
2724
+ ]),
2725
+ );
2726
+ };
2727
+ // A part drawn by another (a clickable card) after the part drawing it,
2728
+ // so its own padding wins over the base's reset at the same weight.
2729
+ theme.components = Object.fromEntries([
2730
+ ...Object.entries(theme.components ?? {}).filter(
2731
+ ([t]) => !CARD_LIKE.includes(t),
2732
+ ),
2733
+ ...Object.entries(theme.components ?? {}).filter(([t]) =>
2734
+ CARD_LIKE.includes(t),
2735
+ ),
2736
+ ]);
2737
+ for (const [target, blocks] of Object.entries(theme.components ?? {})) {
2738
+ const keys = Object.keys(blocks);
2739
+ const ordered = keys.includes('base')
2740
+ ? ['base', ...keys.filter(k => k !== 'base')]
2741
+ : keys;
2742
+ theme.components[target] = Object.fromEntries(
2743
+ ordered.map(k => [
2744
+ k,
2745
+ blocks[k] && typeof blocks[k] === 'object'
2746
+ ? dirFirst(blocks[k])
2747
+ : blocks[k],
2748
+ ]),
2749
+ );
2750
+ }
2751
+ };
2752
+ /**
2753
+ * Where a per-direction rule goes for a setting, one level deep, as the
2754
+ * block and its key: in the setting's own block, or under a state Core
2755
+ * writes as a pseudo-class, beside that state with the direction after it.
2756
+ * @param {Setting} s @param {string} target @param {string} dir `:dir(ltr)`
2757
+ * @returns {[Record<string, any>, string]}
2758
+ */
2759
+ const dirBlock = (s, target, dir) => {
2760
+ const tg = ctx.project.target.get(target);
2761
+ // On the plain rule, a direction's rule keeps the plain rule's weight
2762
+ // (:where), so any variant, the own source's included, out-ranks it as
2763
+ // it out-ranks the plain rule.
2764
+ if (!s.state && !s.when) return [block(s, target), `:where(${dir})`];
2765
+ if (!s.state || tg?.states.includes(s.state))
2766
+ return [block(s, target), dir];
2767
+ const parent = block({...s, state: undefined}, target);
2768
+ return [parent, `${stateKey(s.state, wrapsOneControl(ctx, target))}${dir}`];
2769
+ };
1007
2770
  /** @param {Setting} s @param {string} target @param {string} prop @param {string} v */
1008
2771
  const putComp = (s, target, prop, v) => {
1009
2772
  const b = block(s, target);
@@ -1095,7 +2858,7 @@ export function compileTheme(ctx, data, base) {
1095
2858
  for (const m of /** @type {const} */ (['light', 'dark']))
1096
2859
  if (!x.mode || x.mode === m) value[m] = {color: x.value};
1097
2860
  ((theme.components[target] ??= {})[key] ??= {})['--color-text-secondary'] =
1098
- liftValue(value, modeOnly);
2861
+ liftValue(value, null);
1099
2862
  }
1100
2863
  // `headings` owns heading weight and tracking whatever the order: `type`
1101
2864
  // sets them only where no `headings` setting does.
@@ -1236,29 +2999,117 @@ export function compileTheme(ctx, data, base) {
1236
2999
  } else if (s.thing === 'spacing') {
1237
3000
  const f = SPACING.find(([n]) => n === s.value)?.[1] ?? 1;
1238
3001
  // The rungs scale the spacing the base theme starts from.
3002
+ /** @param {string} k @param {string} nv */
3003
+ const put = (k, nv) => {
3004
+ if (parts.length) for (const t of parts) block(s, t)[k] = nv;
3005
+ else putTok(k, nv);
3006
+ };
1239
3007
  for (const [k, core] of Object.entries(
1240
3008
  /** @type {Record<string, string>} */ (TOKENS),
1241
3009
  )) {
1242
3010
  const v = base.light[k] ?? core;
1243
- let nv = null;
1244
3011
  if (/^--spacing-/.test(k) && /rem$/.test(v))
1245
- nv = `${Number((parseFloat(v) * f).toFixed(3))}rem`;
1246
- // A control never gets smaller than 24px, the smallest target a
1247
- // pointer can use comfortably.
1248
- if (/^--size-element-/.test(k) && /px$/.test(v))
1249
- nv = `${Math.max(Math.min(24, parseFloat(v)), Math.round(parseFloat(v) * f))}px`;
1250
- if (nv === null) continue;
1251
- if (parts.length) for (const t of parts) block(s, t)[k] = nv;
1252
- else putTok(k, nv);
3012
+ put(k, `${Number((parseFloat(v) * f).toFixed(3))}rem`);
1253
3013
  }
3014
+ for (const [k, nv] of controlSizes(
3015
+ Object.keys(/** @type {Record<string, string>} */ (TOKENS))
3016
+ .filter(k => /^--size-element-/.test(k))
3017
+ .map(k => [k, base.light[k] ?? TOKENS[k]]),
3018
+ f,
3019
+ ))
3020
+ put(k, nv);
1254
3021
  }
1255
3022
  } else if (s.source === 'token') {
1256
3023
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
1257
3024
  else putTok(s.thing, s.value, s.mode);
1258
3025
  } else if (s.source === 'property') {
1259
- for (const t of parts) putComp(s, t, camel(s.thing), s.value);
3026
+ for (const t of parts) {
3027
+ // A padding on a part whose box reads Core's padding variables is
3028
+ // resolved with the rest of that part's padding, below.
3029
+ if (padVars(t) && /^padding(-|$)/.test(kebab(s.thing))) {
3030
+ queuePadding(s, t);
3031
+ continue;
3032
+ }
3033
+ const sides =
3034
+ wrappedPadding(t, s) ??
3035
+ containerSides(t, s) ??
3036
+ cornerRadii(t, s) ??
3037
+ boxSides(t, s);
3038
+ if (sides)
3039
+ for (const [k, v] of Object.entries(sides)) {
3040
+ // A per-direction block joins what that direction already has,
3041
+ // one level deep: under a state it is the state's own key with
3042
+ // the direction after it (`:hover:dir(ltr)`), which Core writes
3043
+ // as one rule.
3044
+ if (k.startsWith(':') && typeof v === 'object') {
3045
+ const [b, key] = dirBlock(s, t, k);
3046
+ b[key] = {...(b[key] ?? {}), ...v};
3047
+ } else putComp(s, t, k, /** @type {string} */ (v));
3048
+ }
3049
+ else putComp(s, t, camel(s.thing), s.value);
3050
+ // A later padding takes out what it covers that would beat it: a
3051
+ // physical side written as it is (a group's left under a later part
3052
+ // padding; left-to-right, inline-start is the left), and a side
3053
+ // written per direction, whose :dir() rule is more specific.
3054
+ {
3055
+ const prop = kebab(s.thing);
3056
+ /** @type {Record<string, Array<'paddingLeft' | 'paddingRight'>>} */
3057
+ const COVERS = {
3058
+ padding: ['paddingLeft', 'paddingRight'],
3059
+ 'padding-inline': ['paddingLeft', 'paddingRight'],
3060
+ 'padding-inline-start': ['paddingLeft'],
3061
+ 'padding-inline-end': ['paddingRight'],
3062
+ 'padding-left': [],
3063
+ 'padding-right': [],
3064
+ };
3065
+ const plain = COVERS[prop];
3066
+ if (plain) {
3067
+ const b = block(s, t);
3068
+ // A side written per direction leaves a physical side as it is:
3069
+ // its :dir(ltr) rule already wins in a left-to-right box, and in
3070
+ // a right-to-left one the physical left is still the left.
3071
+ const perDirection =
3072
+ !!sides && Object.keys(sides).some(x => x.startsWith(':'));
3073
+ if (!perDirection)
3074
+ for (const k of plain)
3075
+ if (b[k] != null && !(sides && k in sides)) delete b[k];
3076
+ // Per direction: a whole padding or inline padding covers both
3077
+ // sides in both directions; a physical side, that side in both.
3078
+ const dirSides =
3079
+ prop === 'padding' || prop === 'padding-inline'
3080
+ ? ['paddingLeft', 'paddingRight']
3081
+ : prop === 'padding-left'
3082
+ ? ['paddingLeft']
3083
+ : prop === 'padding-right'
3084
+ ? ['paddingRight']
3085
+ : [];
3086
+ if (
3087
+ dirSides.length &&
3088
+ !(sides && Object.keys(sides).some(x => x.startsWith(':')))
3089
+ )
3090
+ for (const d of [':dir(ltr)', ':dir(rtl)']) {
3091
+ const [db, key] = dirBlock(s, t, d);
3092
+ const rule = db[key];
3093
+ if (!rule) continue;
3094
+ for (const x of dirSides) delete rule[x];
3095
+ if (!Object.keys(rule).length) delete db[key];
3096
+ }
3097
+ }
3098
+ }
3099
+ // A part's own corner radii replace a single radius a group or an
3100
+ // earlier setting left in the same block, in their own order: the
3101
+ // whole radius (which Core turns into the content's radius) before
3102
+ // the corners, which the box shows.
3103
+ if (sides && 'borderTopLeftRadius' in sides) {
3104
+ const b = block(s, t);
3105
+ for (const k of Object.keys(sides)) delete b[k];
3106
+ Object.assign(b, sides);
3107
+ }
3108
+ }
1260
3109
  }
1261
3110
  }
3111
+ emitPadding();
3112
+ orderBlocks();
1262
3113
  // Core gives headings the body font when a theme sets only the body's:
1263
3114
  // a font for the body alone keeps the base theme's heading font.
1264
3115
  if (theme.typography?.body && !theme.typography.heading) {
@@ -1268,15 +3119,6 @@ export function compileTheme(ctx, data, base) {
1268
3119
  theme.typography.heading = {family: f.family, fallbacks: f.fallbacks};
1269
3120
  }
1270
3121
  }
1271
- // A one-mode theme looks the same whatever the system asks for: every
1272
- // color the theme does not set takes its mode's value from the base (or
1273
- // Core) on both sides.
1274
- if (modeOnly)
1275
- for (const k of Object.keys(/** @type {Record<string, string>} */ (TOKENS)))
1276
- if (MODAL.has(ctx.C.typeOf(k)) && !tok[k]) {
1277
- const v = base[modeOnly]?.[k];
1278
- if (v && !/var\(/.test(v)) putTok(k, v);
1279
- }
1280
3122
  // A scale steeper or flatter than the standard one changes the headings;
1281
3123
  // the steps below the base text size keep the standard ratio, so small
1282
3124
  // text stays as it was. An exact token setting still wins.
@@ -1323,21 +3165,30 @@ export function compileTheme(ctx, data, base) {
1323
3165
  theme.tokens[k] = l === d ? l : [l, d];
1324
3166
  }
1325
3167
  // Base themes set the type tokens again for phones (a coarse pointer
1326
- // below the lg width); an exact font family is written there too, so it
1327
- // applies on every screen. Sizes are not: phones keep their reading base.
1328
- const phone = Object.fromEntries(
1329
- data.settings
3168
+ // below the lg width); an exact font family or weight, and the headings
3169
+ // dial's weights, are written there too, so they apply on every screen.
3170
+ // Sizes are not: phones keep their reading base. (What the theme's own
3171
+ // source sets is not repeated: on phones the base theme's type comes
3172
+ // back for it, by Core contract; the notes name the fix.)
3173
+ const phone = Object.fromEntries([
3174
+ ...data.settings
1330
3175
  .filter(
1331
3176
  x =>
1332
3177
  x.source === 'token' &&
1333
3178
  !x.on &&
1334
3179
  !x.mode &&
1335
- // Families only: phones keep their own reading sizes.
1336
- /^--font-family/.test(x.thing) &&
3180
+ PHONE_TYPE.test(x.thing) &&
1337
3181
  !(modeOnly && x.mode && x.mode !== modeOnly),
1338
3182
  )
1339
3183
  .map(x => [x.thing, x.value]),
1340
- );
3184
+ ]);
3185
+ // The headings dial's weights, unless an exact token sets one.
3186
+ const headingsWeight = [...data.settings]
3187
+ .reverse()
3188
+ .find(x => x.thing === 'headings' && x.axis !== 'tracking' && !x.on);
3189
+ if (headingsWeight && HEADING_WEIGHTS[headingsWeight.value])
3190
+ for (const k of headingWeightTokens)
3191
+ phone[k] ??= HEADING_WEIGHTS[headingsWeight.value];
1341
3192
  if (Object.keys(phone).length)
1342
3193
  theme.adaptations = {
1343
3194
  rules: [
@@ -1367,9 +3218,10 @@ const SMALL_STEPS = /** @type {Array<[string, number]>} */ ([
1367
3218
  * Settings whose effect a later or stronger setting hides, with why: `type`
1368
3219
  * loses heading weight and tracking to `headings`.
1369
3220
  * @param {ThemeData} data
3221
+ * @param {Ctx | null} [ctx] with it, a later setting that reaches the parts through a spread counts too
1370
3222
  * @returns {Map<Setting, string>}
1371
3223
  */
1372
- export function maskedSettings(data) {
3224
+ export function maskedSettings(data, ctx = null) {
1373
3225
  /** @type {Map<Setting, string>} */
1374
3226
  const out = new Map();
1375
3227
  const axes = new Set(
@@ -1409,6 +3261,37 @@ export function maskedSettings(data) {
1409
3261
  `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
1410
3262
  );
1411
3263
  });
3264
+ // With the parts known: a later setting of the same thing that reaches
3265
+ // every part an earlier one styles (a member that spreads to its group,
3266
+ // the same part without --only), dial or CSS property, covers it too.
3267
+ if (ctx)
3268
+ data.settings.forEach((s, i) => {
3269
+ if (
3270
+ out.has(s) ||
3271
+ !s.on ||
3272
+ (s.source !== 'dial' && s.source !== 'property')
3273
+ )
3274
+ return;
3275
+ const mine = partsOf(ctx, s);
3276
+ if (!mine.length) return;
3277
+ const later = data.settings
3278
+ .slice(i + 1)
3279
+ .find(
3280
+ x =>
3281
+ x.thing === s.thing &&
3282
+ x.source === s.source &&
3283
+ x.on &&
3284
+ (x.when ?? '') === (s.when ?? '') &&
3285
+ (x.state ?? '') === (s.state ?? '') &&
3286
+ (x.mode ?? '') === (s.mode ?? '') &&
3287
+ mine.every(t => partsOf(ctx, x).includes(t)),
3288
+ );
3289
+ if (later)
3290
+ out.set(
3291
+ s,
3292
+ `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
3293
+ );
3294
+ });
1412
3295
  for (const s of data.settings) {
1413
3296
  if (s.thing !== 'type' || !axes.size) continue;
1414
3297
  const T = TYPE_STYLES[s.value];
@@ -1448,16 +3331,13 @@ export function findOverrides(cssText, theme) {
1448
3331
  'g',
1449
3332
  );
1450
3333
  // A shorthand and its longhands are one property: the last one set
1451
- // (background after background-color) is the one in effect.
1452
- // border-radius, border-collapse and border-spacing are not part of
1453
- // border.
1454
- const NOT_LONGHAND =
1455
- /^border-(radius|collapse|spacing)|^border-[a-z]+-radius$/;
3334
+ // (background after background-color) is the one in effect. Which
3335
+ // longhands a shorthand sets is MDN's data (background-blend-mode is
3336
+ // no part of background).
1456
3337
  /** @param {string} a @param {string} b */
1457
3338
  const sameProperty = (a, b) => {
1458
3339
  const [x, y] = [kebab(a), kebab(b)];
1459
- if (NOT_LONGHAND.test(x) || NOT_LONGHAND.test(y)) return x === y;
1460
- return x.startsWith(`${y}-`) || y.startsWith(`${x}-`) || x === y;
3340
+ return x === y || coversProperty(x, y) || coversProperty(y, x);
1461
3341
  };
1462
3342
  const last = props.filter(
1463
3343
  (p, i) => !props.slice(i + 1).some(later => sameProperty(later, p)),
@@ -1514,22 +3394,11 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1514
3394
  ? `${REF}${r.family}`
1515
3395
  : `${REF}${r.family ?? family}.${m}.${r.stop}${r.alpha ? `+${r.alpha}` : ''}`;
1516
3396
  const out = {...theme, name: `${slug}-settings`};
1517
- const only =
1518
- data.mode === 'light-only'
1519
- ? 'light'
1520
- : data.mode === 'dark-only'
1521
- ? 'dark'
1522
- : null;
3397
+ // A one-mode theme keeps both halves too (see compileTheme).
1523
3398
  if (pal && theme.tokens) {
1524
3399
  out.tokens = {...theme.tokens};
1525
3400
  for (const [k, v] of Object.entries(pal.tokens)) {
1526
3401
  const now = theme.tokens[k];
1527
- // A one-mode theme reads one shade, its mode's, on both sides.
1528
- if (only) {
1529
- if (now === v[only].color)
1530
- out.tokens[k] = refOf(v.family, only, v[only]);
1531
- continue;
1532
- }
1533
3402
  const [l, d] = Array.isArray(now) ? now : [now, now];
1534
3403
  if (l !== v.light.color || d !== v.dark.color) continue;
1535
3404
  out.tokens[k] = [
@@ -1544,15 +3413,13 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1544
3413
  for (const [target, key, ground] of LIFT_PARTS) {
1545
3414
  const lift = pal.lift[ground];
1546
3415
  if (!lift) continue;
1547
- const literal = liftValue(lift, only);
3416
+ const literal = liftValue(lift, null);
1548
3417
  /** A shade of the neutral palette as a reference; a color as it is. @param {'light' | 'dark'} m */
1549
3418
  const one = m => {
1550
3419
  const r = /** @type {any} */ (lift[m]);
1551
3420
  return r.family === 'literal' ? r.color : refOf('neutral', m, r);
1552
3421
  };
1553
- const refs = only
1554
- ? one(only)
1555
- : `light-dark(${one('light')}, ${one('dark')})`;
3422
+ const refs = `light-dark(${one('light')}, ${one('dark')})`;
1556
3423
  const block = out.components[target]?.[key];
1557
3424
  if (block?.['--color-text-secondary'] !== literal) continue;
1558
3425
  out.components[target] = {
@@ -1592,6 +3459,12 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1592
3459
  [
1593
3460
  `// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
1594
3461
  `// Built from settings ${settingsStamp(data)}.`,
3462
+ // The theme source as it is when the build starts (the editor's
3463
+ // own when the build writes it), so an own change to it after the
3464
+ // build is told by content.
3465
+ ...(cwd
3466
+ ? [`// Built with ${slug}.theme.ts ${themeSourceHash(cwd, slug)}.`]
3467
+ : []),
1595
3468
  ...(like && cwd
1596
3469
  ? [
1597
3470
  `// Built on @astryxdesign/theme-${like} ${baseVersionOf(cwd, like) ?? 'unknown'}.`,
@@ -1615,6 +3488,130 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1615
3488
  );
1616
3489
  }
1617
3490
 
3491
+ /**
3492
+ * A hash of a theme's source file as the next build reads it: the file, or
3493
+ * the source the editor writes when there is none.
3494
+ * @param {string} cwd
3495
+ * @param {string} slug
3496
+ */
3497
+ function themeSourceHash(cwd, slug) {
3498
+ const f = themeFiles(cwd, slug);
3499
+ const hash = createHash('sha256');
3500
+ if (!fs.existsSync(f.ts)) {
3501
+ // The same as the file the build is about to write would hash.
3502
+ hash.update(`${path.basename(f.ts)}\0`);
3503
+ hash.update(themeModuleSource(slug));
3504
+ return hash.digest('hex').slice(0, 16);
3505
+ }
3506
+ for (const file of ownSourceFiles(cwd, slug)) {
3507
+ hash.update(`${path.relative(f.dir, file)}\0`);
3508
+ hash.update(fs.readFileSync(file));
3509
+ }
3510
+ return hash.digest('hex').slice(0, 16);
3511
+ }
3512
+
3513
+ /**
3514
+ * The theme source and every local module it reaches (an own helper such
3515
+ * as ./my-tokens), read the way theme discovery reads them: the person's
3516
+ * files. The editor's generated modules change with each build and are
3517
+ * judged by their own stamps.
3518
+ * @param {string} cwd
3519
+ * @param {string} slug
3520
+ * @returns {string[]}
3521
+ */
3522
+ function ownSourceFiles(cwd, slug) {
3523
+ const f = themeFiles(cwd, slug);
3524
+ if (!fs.existsSync(f.ts)) return [];
3525
+ const generated = new Set([f.settingsTs]);
3526
+ const seen = new Set();
3527
+ /** @type {string[]} */
3528
+ const files = [];
3529
+ const queue = [f.ts];
3530
+ while (queue.length) {
3531
+ const file = /** @type {string} */ (queue.shift());
3532
+ if (seen.has(file)) continue;
3533
+ seen.add(file);
3534
+ files.push(file);
3535
+ /** @type {string[]} */
3536
+ let specifiers = [];
3537
+ try {
3538
+ specifiers = themeFileImports(file, {withRequire: true});
3539
+ } catch {
3540
+ // A file that does not parse is hashed as it is; the build names it.
3541
+ }
3542
+ for (const spec of specifiers) {
3543
+ if (!spec.startsWith('.')) continue;
3544
+ const target = localModuleFile(path.dirname(file), spec);
3545
+ // Only the editor's own generated palette files are judged by their
3546
+ // stamps; any other file the theme reaches, in tokens/ too, is the
3547
+ // person's.
3548
+ if (
3549
+ target &&
3550
+ !generated.has(target) &&
3551
+ !isGeneratedPaletteFile(f.dir, slug, target)
3552
+ )
3553
+ queue.push(target);
3554
+ }
3555
+ }
3556
+ return files;
3557
+ }
3558
+
3559
+ /** The extensions a theme's local module may have, as the build reads them. */
3560
+ const MODULE_EXTENSIONS = [
3561
+ '.ts',
3562
+ '.tsx',
3563
+ '.mts',
3564
+ '.cts',
3565
+ '.js',
3566
+ '.jsx',
3567
+ '.mjs',
3568
+ '.cjs',
3569
+ ];
3570
+
3571
+ /**
3572
+ * The file a relative import names, resolved as TypeScript resolves it: a
3573
+ * JavaScript extension names its TypeScript source (`.js` → `.ts`/`.tsx`,
3574
+ * `.jsx` → `.tsx`, `.mjs` → `.mts`, `.cjs` → `.cts`), then the path as
3575
+ * written, with each module extension, and as a folder's index file.
3576
+ * @param {string} dir
3577
+ * @param {string} spec
3578
+ * @returns {string | undefined}
3579
+ */
3580
+ function localModuleFile(dir, spec) {
3581
+ const base = path.resolve(dir, spec);
3582
+ const ext = path.extname(base);
3583
+ const stem = base.slice(0, base.length - ext.length);
3584
+ const sourceFor = /** @type {Record<string, string[]>} */ ({
3585
+ '.js': ['.ts', '.tsx'],
3586
+ '.jsx': ['.tsx'],
3587
+ '.mjs': ['.mts'],
3588
+ '.cjs': ['.cts'],
3589
+ })[ext];
3590
+ return [
3591
+ ...(sourceFor ?? []).map(x => stem + x),
3592
+ base,
3593
+ ...MODULE_EXTENSIONS.map(x => base + x),
3594
+ ...MODULE_EXTENSIONS.map(x => path.join(base, `index${x}`)),
3595
+ ].find(p => fs.existsSync(p) && fs.statSync(p).isFile());
3596
+ }
3597
+
3598
+ /**
3599
+ * Whether a file is one of the palette files the editor generates in a
3600
+ * theme's tokens/ folder (`tokens/<slug>.palette*`).
3601
+ * @param {string} dir the theme folder
3602
+ * @param {string} slug
3603
+ * @param {string} file
3604
+ */
3605
+ function isGeneratedPaletteFile(dir, slug, file) {
3606
+ const rel = path.relative(path.join(dir, 'tokens'), file);
3607
+ return (
3608
+ !rel.startsWith('..') &&
3609
+ !path.isAbsolute(rel) &&
3610
+ !rel.includes(path.sep) &&
3611
+ rel.startsWith(`${slug}.palette`)
3612
+ );
3613
+ }
3614
+
1618
3615
  /**
1619
3616
  * The theme module, written once: it extends the generated settings and is
1620
3617
  * the person's own from then on, so hand edits in it survive every change.
@@ -1666,6 +3663,52 @@ export function themeSourceProblem(cwd, slug) {
1666
3663
  return null;
1667
3664
  }
1668
3665
 
3666
+ /**
3667
+ * Why the person's own theme source does not parse (its line and the
3668
+ * parser's message), or null when it parses or is not there.
3669
+ * @param {string} cwd
3670
+ * @param {string} slug
3671
+ * @returns {string | null}
3672
+ */
3673
+ export function themeSourceParseError(cwd, slug) {
3674
+ const f = themeFiles(cwd, slug);
3675
+ let code;
3676
+ try {
3677
+ code = fs.readFileSync(f.ts, 'utf8');
3678
+ } catch {
3679
+ return null;
3680
+ }
3681
+ try {
3682
+ parseModule(code, {sourceType: 'module', plugins: ['typescript']});
3683
+ return null;
3684
+ } catch (e) {
3685
+ const err = /** @type {any} */ (e);
3686
+ return `${slug}.theme.ts does not parse${err?.loc?.line ? ` (line ${err.loc.line})` : ''}: ${String(err?.message ?? e).replace(/\s*\(\d+:\d+\)\s*$/, '')}`;
3687
+ }
3688
+ }
3689
+
3690
+ /**
3691
+ * Refuse, before anything is written or removed, a command whose build
3692
+ * would load the person's own theme source when it does not parse: the
3693
+ * build would fail part way.
3694
+ * @param {string} cwd
3695
+ * @param {string} slug
3696
+ */
3697
+ export function refuseThemeParse(cwd, slug) {
3698
+ const why = themeSourceParseError(cwd, slug);
3699
+ if (why)
3700
+ throw new AstryxError(
3701
+ `${why}, so the theme cannot build. It is your own file: fix it, then run the command again. Nothing was changed.`,
3702
+ [
3703
+ {
3704
+ name: `cat ${path.posix.join('themes', slug, `${slug}.theme.ts`)}`,
3705
+ reason: 'see the file',
3706
+ },
3707
+ ],
3708
+ ERROR_CODES.ERR_THEME_INVALID,
3709
+ );
3710
+ }
3711
+
1669
3712
  /**
1670
3713
  * Refuse a build whose theme source cannot carry the settings, naming the
1671
3714
  * lines that put it back.
@@ -1673,6 +3716,7 @@ export function themeSourceProblem(cwd, slug) {
1673
3716
  * @param {string} slug
1674
3717
  */
1675
3718
  export function refuseThemeSource(cwd, slug) {
3719
+ refuseThemeParse(cwd, slug);
1676
3720
  const why = themeSourceProblem(cwd, slug);
1677
3721
  if (why)
1678
3722
  throw new AstryxError(
@@ -1682,6 +3726,162 @@ export function refuseThemeSource(cwd, slug) {
1682
3726
  );
1683
3727
  }
1684
3728
 
3729
+ /**
3730
+ * Refuse a [light, dark] pair the theme's own source gives a token that is
3731
+ * not a color (a font family, a size, a weight): the build would write
3732
+ * `light-dark()`, which browsers take only for colors. The editor refuses
3733
+ * `--mode` on those tokens for the same reason.
3734
+ * @param {Ctx} ctx
3735
+ * @param {string} cwd
3736
+ * @param {string} slug
3737
+ */
3738
+ function refuseOwnPairs(ctx, cwd, slug) {
3739
+ const f = themeFiles(cwd, slug);
3740
+ /** @type {string[]} */
3741
+ const bad = [];
3742
+ try {
3743
+ const ast = /** @type {any} */ (
3744
+ parseModule(fs.readFileSync(f.ts, 'utf8'), {
3745
+ sourceType: 'module',
3746
+ plugins: ['typescript'],
3747
+ })
3748
+ );
3749
+ /** @param {any} node */
3750
+ const visit = node => {
3751
+ if (!node || typeof node !== 'object') return;
3752
+ if (
3753
+ node.type === 'ObjectProperty' &&
3754
+ typeof (node.key?.value ?? node.key?.name) === 'string' &&
3755
+ String(node.key?.value ?? node.key?.name).startsWith('--') &&
3756
+ node.value?.type === 'ArrayExpression' &&
3757
+ node.value.elements.length === 2 &&
3758
+ // A pair holding a value that is not text is named by the value
3759
+ // checks, with the fix for that value.
3760
+ node.value.elements.every(
3761
+ (/** @type {any} */ e) =>
3762
+ e?.type === 'StringLiteral' || e?.type === 'TemplateLiteral',
3763
+ )
3764
+ ) {
3765
+ const k = String(node.key.value ?? node.key.name);
3766
+ const type = ctx.C.typeOf(k);
3767
+ // A size given as a bare number is named by the value check, with
3768
+ // the unit it needs.
3769
+ const unitless =
3770
+ type === 'size' &&
3771
+ node.value.elements.some(
3772
+ (/** @type {any} */ e) =>
3773
+ e?.type === 'StringLiteral' && /^\d*\.?\d+$/.test(e.value.trim()),
3774
+ );
3775
+ if (type !== 'color' && !unitless) bad.push(k);
3776
+ }
3777
+ for (const v of Object.values(node))
3778
+ if (Array.isArray(v)) v.forEach(visit);
3779
+ else if (v && typeof v === 'object' && v.type) visit(v);
3780
+ };
3781
+ visit(ast.program);
3782
+ } catch {
3783
+ return;
3784
+ }
3785
+ if (bad.length)
3786
+ throw new AstryxError(
3787
+ ownPairMessage(slug, [...new Set(bad)]),
3788
+ [
3789
+ {
3790
+ name: `grep -n -- ${quoteCommandArgument(bad[0])} ${quoteCommandArgument(`themes/${slug}/${slug}.theme.ts`)}`,
3791
+ reason: 'see the line',
3792
+ },
3793
+ ],
3794
+ ERROR_CODES.ERR_THEME_INVALID,
3795
+ );
3796
+ }
3797
+
3798
+ /**
3799
+ * The tokens that are not colors the theme as it builds now gives a
3800
+ * [light, dark] pair (light-dark()), however its file writes them (a
3801
+ * constant, `as const`, `satisfies`, a spread from an imported module):
3802
+ * read from a build made into the project's cache folder, never beside the
3803
+ * theme. Empty when it does not build there (the build names that itself).
3804
+ * @param {Ctx} ctx
3805
+ * @param {string} slug
3806
+ * @returns {Promise<string[]>}
3807
+ */
3808
+ export async function builtPairs(ctx, slug) {
3809
+ const {cwd} = ctx.project;
3810
+ const f = themeFiles(cwd, slug);
3811
+ // The build writes only inside the project: the cache folder when it is
3812
+ // there, else a hidden folder in the theme's (removed after).
3813
+ const name = `.${slug}.pairs-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
3814
+ const inside = !path.relative(cwd, ctx.project.cacheDir).startsWith('..');
3815
+ const dir = path.join(inside ? ctx.project.cacheDir : f.dir, name);
3816
+ const silent = logger.silent;
3817
+ logger.setSilent(true);
3818
+ try {
3819
+ fs.mkdirSync(dir, {recursive: true});
3820
+ await themeBuildForReport(
3821
+ shown(cwd, f.ts),
3822
+ {out: path.relative(cwd, path.join(dir, `${slug}.css`))},
3823
+ {cwd},
3824
+ {compact: true},
3825
+ );
3826
+ const js = fs
3827
+ .readdirSync(dir)
3828
+ .find(n => n.endsWith('.js') && !n.endsWith('.d.js'));
3829
+ if (!js) return [];
3830
+ return [...topTokensOf(path.join(dir, js))]
3831
+ .filter(
3832
+ ([k, v]) =>
3833
+ /^light-dark\(/.test(String(v ?? '')) && ctx.C.typeOf(k) !== 'color',
3834
+ )
3835
+ .map(([k]) => k);
3836
+ } catch {
3837
+ return [];
3838
+ } finally {
3839
+ logger.setSilent(silent);
3840
+ fs.rmSync(dir, {recursive: true, force: true});
3841
+ }
3842
+ }
3843
+
3844
+ /**
3845
+ * The refusal of a [light, dark] pair on tokens that are not colors.
3846
+ * @param {string} slug
3847
+ * @param {string[]} names
3848
+ */
3849
+ export function ownPairMessage(slug, names) {
3850
+ return `themes/${slug}/${slug}.theme.ts gives ${names.join(', ')} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors. Give ${names.length > 1 ? 'each' : 'it'} one value in ${slug}.theme.ts. Nothing was changed.`;
3851
+ }
3852
+
3853
+ /**
3854
+ * What runs after every build of a theme, set by the adapter (the app copy
3855
+ * of the theme): null until it is set.
3856
+ * @type {((ctx: Ctx, slug: string, data: ThemeData) => void) | null}
3857
+ */
3858
+ let afterBuild = null;
3859
+
3860
+ /**
3861
+ * Set what runs after every build of a theme.
3862
+ * @param {((ctx: Ctx, slug: string, data: ThemeData) => void) | null} fn
3863
+ */
3864
+ export function setAfterBuild(fn) {
3865
+ afterBuild = fn;
3866
+ }
3867
+
3868
+ /**
3869
+ * Builds whose after-build hook waits for the change to be saved: a change
3870
+ * that fails after its build puts its theme folder back, and its app copy
3871
+ * was never written.
3872
+ * @type {WeakSet<Ctx>}
3873
+ */
3874
+ const afterSave = new WeakSet();
3875
+
3876
+ /**
3877
+ * Hold the after-build hook for this command's builds: the command writes
3878
+ * the app copy itself once it succeeds (show).
3879
+ * @param {Ctx} ctx
3880
+ */
3881
+ export function holdAfterBuild(ctx) {
3882
+ afterSave.add(ctx);
3883
+ }
3884
+
1685
3885
  /**
1686
3886
  * Generate the theme source, build it with the theme build, then repeat any
1687
3887
  * part setting a more specific rule would beat and build again.
@@ -1694,6 +3894,7 @@ export async function buildTheme(ctx, slug, data) {
1694
3894
  const {cwd} = ctx.project;
1695
3895
  const f = themeFiles(cwd, slug);
1696
3896
  refuseThemeSource(cwd, slug);
3897
+ refuseOwnPairs(ctx, cwd, slug);
1697
3898
  if (data.like) baseThemeFile(ctx.project, data.like);
1698
3899
  const base = await baseResolved(ctx.project, data.like);
1699
3900
  fs.mkdirSync(f.dir, {recursive: true});
@@ -1737,23 +3938,26 @@ export async function buildTheme(ctx, slug, data) {
1737
3938
  if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
1738
3939
  });
1739
3940
  // Files an earlier build wrote that this one may not: the variants types
1740
- // of an older base, and section sheets of an older look.
3941
+ // of an older base, and the pictures the editor took of an older look.
3942
+ // Only a picture the editor recorded writing, unchanged since, goes: a
3943
+ // file of the user's is never touched. Section sheets stay, marked as
3944
+ // out of date like sheet.html.
1741
3945
  await step(() => {
3946
+ const pictures = fs.existsSync(f.dir)
3947
+ ? fs
3948
+ .readdirSync(f.dir)
3949
+ .filter(
3950
+ n =>
3951
+ /^(sheet|preview)(-[a-z-]+)?\.png$/.test(n) &&
3952
+ editorWrote(cwd, slug, path.join(f.dir, n)),
3953
+ )
3954
+ : [];
1742
3955
  for (const file of [
1743
3956
  path.join(f.dir, `${slug}.variants.d.ts`),
1744
- ...(fs.existsSync(f.dir)
1745
- ? fs
1746
- .readdirSync(f.dir)
1747
- // Section sheets, and every picture: all show the look before
1748
- // this build. The full sheet and the preview page are written
1749
- // again by the commands that make them.
1750
- .filter(n =>
1751
- /^(sheet-[a-z-]+\.html|(sheet|preview)(-[a-z-]+)?\.png)$/.test(n),
1752
- )
1753
- .map(n => path.join(f.dir, n))
1754
- : []),
3957
+ ...pictures.map(n => path.join(f.dir, n)),
1755
3958
  ])
1756
3959
  fs.rmSync(file, {force: true});
3960
+ forgetWritten(cwd, slug, pictures);
1757
3961
  });
1758
3962
  let receipt = await step(() => runBuild(ctx, slug));
1759
3963
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
@@ -1764,7 +3968,16 @@ export async function buildTheme(ctx, slug, data) {
1764
3968
  if (found.length) {
1765
3969
  for (const x of found) {
1766
3970
  const t = theme.components[x.target];
1767
- (t[x.key] ??= {})[x.prop] ??= x.value;
3971
+ // The base value goes before the variant's own declarations, so a
3972
+ // longhand or shorthand the variant sets itself (border-color after
3973
+ // a base border) still wins over it.
3974
+ const own = t[x.key] ?? {};
3975
+ // A variant that sets every longhand of the property itself needs
3976
+ // none of the base value (and a lifted radius would feed Core's copy
3977
+ // of it into the content's radius, after the variant's own).
3978
+ const longs = [...longhandsOf(kebab(x.prop))];
3979
+ if (longs.length && longs.every(l => camel(l) in own)) continue;
3980
+ t[x.key] = {[x.prop]: x.value, ...own};
1768
3981
  lifted.push(`${x.target} ${x.key} ${kebab(x.prop)}`);
1769
3982
  }
1770
3983
  await step(() => {
@@ -1783,6 +3996,12 @@ export async function buildTheme(ctx, slug, data) {
1783
3996
  ]
1784
3997
  .map(String)
1785
3998
  .filter(w => !/^Font "/.test(w));
3999
+ // The app's copy, a standard local theme `theme add` reads, follows the
4000
+ // build (written by the hook the adapter sets: it owns that write).
4001
+ if (afterBuild && !afterSave.has(ctx))
4002
+ await step(() => {
4003
+ afterBuild?.(ctx, slug, data);
4004
+ });
1786
4005
  return {warnings, lifted, notes};
1787
4006
  }
1788
4007
 
@@ -1808,6 +4027,46 @@ async function runBuild(ctx, slug) {
1808
4027
  }
1809
4028
  }
1810
4029
 
4030
+ /**
4031
+ * Why the built outputs differ from what the theme builds now: one that is
4032
+ * missing or changed by hand, found the way `compile --check` finds it
4033
+ * (the same build, compared and not written), or null when they match.
4034
+ * @param {Ctx} ctx
4035
+ * @param {string} slug
4036
+ * @returns {Promise<string | null>}
4037
+ */
4038
+ export async function outputsDrift(ctx, slug) {
4039
+ const {cwd} = ctx.project;
4040
+ const f = themeFiles(cwd, slug);
4041
+ const silent = logger.silent;
4042
+ logger.setSilent(true);
4043
+ try {
4044
+ const {receipt} = await themeBuildForReport(
4045
+ shown(cwd, f.ts),
4046
+ {check: true},
4047
+ {cwd},
4048
+ {compact: true},
4049
+ );
4050
+ const first = /** @type {any} */ (receipt)?.data?.stale?.[0];
4051
+ if (!first) return null;
4052
+ const name = path.basename(String(first.path));
4053
+ return first.reason === 'missing'
4054
+ ? `${name} was missing`
4055
+ : `${name} differs from what the settings build, after an edit by hand or by another tool`;
4056
+ } catch (e) {
4057
+ // A theme source that does not load is named by its own checks; any
4058
+ // other failure means the outputs could not be compared: built again.
4059
+ const err = /** @type {any} */ (e);
4060
+ if (err instanceof AstryxError && err.code === ERROR_CODES.ERR_THEME_LOAD)
4061
+ return null;
4062
+ return `the outputs could not be checked (${String(err?.message ?? e)
4063
+ .split('\n')[0]
4064
+ .slice(0, 160)})`;
4065
+ } finally {
4066
+ logger.setSilent(silent);
4067
+ }
4068
+ }
4069
+
1811
4070
  /**
1812
4071
  * Resolved tokens of the built theme in both modes.
1813
4072
  * @param {Ctx} ctx
@@ -1855,10 +4114,41 @@ export async function resolvedTokens(ctx, slug) {
1855
4114
  v => v && typeof v === 'object' && typeof v.name === 'string',
1856
4115
  );
1857
4116
  const {core} = ctx.project;
1858
- const out = {
1859
- light: core.resolveThemeTokens(t, {mode: 'light'}),
1860
- dark: core.resolveThemeTokens(t, {mode: 'dark'}),
4117
+ // A token value an own theme source gives as a number (8 for 8px)
4118
+ // reads as its text, never as a crash.
4119
+ const asText = (/** @type {Record<string, unknown>} */ m) =>
4120
+ Object.fromEntries(
4121
+ Object.entries(m ?? {}).map(([k, v]) => [
4122
+ k,
4123
+ typeof v === 'string' ? v : String(v),
4124
+ ]),
4125
+ );
4126
+ // A token value that is not text (a number in an own theme source) is
4127
+ // named, never a crash.
4128
+ const resolve = (/** @type {'light' | 'dark'} */ mode) => {
4129
+ try {
4130
+ return asText(core.resolveThemeTokens(t, {mode}));
4131
+ } catch (e) {
4132
+ const bad = nonTextToken(t, ctx.C.typeOf);
4133
+ throw new AstryxError(
4134
+ bad
4135
+ ? nonTextMessage(ctx, slug, bad)
4136
+ : `${slug} could not be read: ${e instanceof Error ? e.message : String(e)}.`,
4137
+ [{name: `${P} how --list tokens`, reason: 'every token and its type'}],
4138
+ ERROR_CODES.ERR_THEME_INVALID,
4139
+ );
4140
+ }
1861
4141
  };
4142
+ // A pair that holds a value that is not text ([8, 8]) resolves, but
4143
+ // builds nothing a browser reads: named the same way.
4144
+ const pairBad = nonTextToken(t, ctx.C.typeOf);
4145
+ if (pairBad)
4146
+ throw new AstryxError(
4147
+ nonTextMessage(ctx, slug, pairBad),
4148
+ [{name: `${P} how --list tokens`, reason: 'every token and its type'}],
4149
+ ERROR_CODES.ERR_THEME_INVALID,
4150
+ );
4151
+ const out = {light: resolve('light'), dark: resolve('dark')};
1862
4152
  // The tokens each part sets for itself (the official themes lift
1863
4153
  // secondary text on some parts), for the contrast check; kept out of the
1864
4154
  // modes so nothing that lists the resolved tokens sees it.
@@ -1873,6 +4163,96 @@ export async function resolvedTokens(ctx, slug) {
1873
4163
  return out;
1874
4164
  }
1875
4165
 
4166
+ /**
4167
+ * The first token a built theme gives a value that is not text, alone or
4168
+ * in a [light, dark] pair, or null.
4169
+ * @param {any} t
4170
+ * @param {(name: string) => string} [typeOf] a token's type (size, color…)
4171
+ * @returns {[string, unknown, 'object' | 'pair' | 'unit' | 'value' | 'mode'] | null}
4172
+ */
4173
+ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
4174
+ for (const [k, raw] of Object.entries(t?.tokens ?? {})) {
4175
+ // An object ({light, dark}) is not a value Core builds: it would write
4176
+ // [object Object].
4177
+ if (raw && typeof raw === 'object' && !Array.isArray(raw))
4178
+ return [k, raw, 'object'];
4179
+ // A built theme writes a pair as light-dark(). A half that was not text
4180
+ // comes out as nothing, null or a boolean; a bare number is text the
4181
+ // source may have quoted, and is wrong only for a size, which needs a
4182
+ // unit.
4183
+ const pair =
4184
+ typeof raw === 'string' ? /^light-dark\((.*)\)$/s.exec(raw.trim()) : null;
4185
+ // Split at the top-level comma: a half may hold commas (rgb(0, 0, 0)).
4186
+ const parts = pair ? splitTop(pair[1], ',').map(x => x.trim()) : [];
4187
+ if (pair && parts.length === 2) {
4188
+ const halves = parts;
4189
+ const missing = halves.some(x =>
4190
+ /^(|null|undefined|true|false)$/.test(x),
4191
+ );
4192
+ const unitless =
4193
+ typeOf(k) === 'size' &&
4194
+ halves.some(x => /^-?\d+(\.\d+)?$/.test(x) && Number(x) !== 0);
4195
+ if (missing || unitless) {
4196
+ const half = (/** @type {string} */ x) =>
4197
+ /^-?\d+(\.\d+)?$/.test(x)
4198
+ ? Number(x)
4199
+ : x === '' || x === 'undefined' || x === 'null'
4200
+ ? null
4201
+ : x === 'true' || x === 'false'
4202
+ ? x === 'true'
4203
+ : x;
4204
+ return [k, [half(parts[0]), half(parts[1])], missing ? 'pair' : 'unit'];
4205
+ }
4206
+ // light-dark() takes only colors: a pair on any other token (a size,
4207
+ // a font, a shadow) is dropped by the browser, however the theme
4208
+ // file wrote it (a constant, `as const`, an imported module).
4209
+ if (typeOf(k) !== 'color') return [k, parts, 'mode'];
4210
+ continue;
4211
+ }
4212
+ if (Array.isArray(raw)) {
4213
+ if (raw.length !== 2 || raw.some(x => typeof x !== 'string'))
4214
+ return [k, raw, 'pair'];
4215
+ if (typeOf(k) !== 'color') return [k, raw, 'mode'];
4216
+ continue;
4217
+ }
4218
+ if (typeof raw !== 'string') return [k, raw, 'value'];
4219
+ }
4220
+ return null;
4221
+ }
4222
+
4223
+ /**
4224
+ * Why a token value is not one, with a value of the token's own type to
4225
+ * write instead (a size in px, a weight as a number in quotes), or none.
4226
+ * @param {Ctx} ctx
4227
+ * @param {string} slug
4228
+ * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value' | 'mode')?]} bad
4229
+ */
4230
+ function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4231
+ const type = ctx.C.typeOf(name);
4232
+ if (kind === 'mode') return ownPairMessage(slug, [name]);
4233
+ if (kind === 'object')
4234
+ return `${slug}.theme.ts gives ${name} an object (${JSON.stringify(value)}); a token value is a CSS value in quotes, such as '8px' (only a color takes a [light, dark] pair).`;
4235
+ if (kind === 'unit') {
4236
+ const n = /** @type {unknown[]} */ (value).find(
4237
+ x => typeof x === 'number' && x !== 0,
4238
+ );
4239
+ return `${slug}.theme.ts gives ${name}, a size, a [light, dark] pair with a number without a unit (${/** @type {unknown[]} */ (value).join(', ')}); a size needs one, and is the same in light and dark, so give one value, such as '${n}px'.`;
4240
+ }
4241
+ const one = Array.isArray(value)
4242
+ ? value.find(x => typeof x !== 'string')
4243
+ : value;
4244
+ const example =
4245
+ typeof one === 'number'
4246
+ ? type === 'size'
4247
+ ? `'${one}px'`
4248
+ : `'${one}'`
4249
+ : null;
4250
+ const shape = Array.isArray(value)
4251
+ ? 'a [light, dark] pair of two CSS values in quotes'
4252
+ : 'a CSS value in quotes';
4253
+ return `${slug}.theme.ts gives ${name} the value ${JSON.stringify(value)}, which is not text: a token value is ${shape}${example ? ` (such as ${Array.isArray(value) ? `[${example}, ${example}]` : example})` : ''}.`;
4254
+ }
4255
+
1876
4256
  /**
1877
4257
  * Contrast problems this theme caused: text below 4.5:1 that was not as low
1878
4258
  * in the base theme. A part's own color or background setting, or a token
@@ -2050,7 +4430,7 @@ export async function contrastProblems(ctx, data, res) {
2050
4430
  })(),
2051
4431
  ...(unchecked.length
2052
4432
  ? [
2053
- `not checked: text on or in ${unchecked.slice(0, 3).join(', ')}${unchecked.length > 3 ? ` and ${unchecked.length - 3} more` : ''}, which ${unchecked.length === 1 ? 'is' : 'are'} not a fixed color`,
4433
+ `not checked: text on or in ${unchecked.slice(0, 3).join(', ')}${unchecked.length > 3 ? ` and ${unchecked.length - 3} more` : ''}, which the editor cannot read as one fixed color`,
2054
4434
  ]
2055
4435
  : []),
2056
4436
  ];
@@ -2118,7 +4498,9 @@ export function baseComponent(base, ctx, target, prop, s) {
2118
4498
  const states = ctx.project.target.get(target)?.states ?? [];
2119
4499
  b = states.includes(s.state)
2120
4500
  ? t[s.when == null ? s.state : `${s.when}+${s.state}`]
2121
- : (b?.[stateKey(s.state)] ?? b?.[`:${s.state}`]);
4501
+ : (b?.[stateKey(s.state, wrapsOneControl(ctx, target))] ??
4502
+ b?.[stateKey(s.state)] ??
4503
+ b?.[`:${s.state}`]);
2122
4504
  }
2123
4505
  const v = b?.[prop];
2124
4506
  return typeof v === 'string' ? v : null;
@@ -2184,15 +4566,64 @@ export function clearNewMarker(dir) {
2184
4566
 
2185
4567
  /**
2186
4568
  * The pseudo key a state writes in a part's styles. Core marks a disabled
2187
- * button, link, tab or menu item with aria-disabled (it stays focusable),
2188
- * and its own styles match both forms: so does the theme.
4569
+ * button, link or tab with aria-disabled (it stays focusable). A form
4570
+ * control styled on a wrapper (a typeahead, a complex selector) has its
4571
+ * input or button inside marked, so it also matches a disabled form
4572
+ * control inside it (never a list row); an action part that holds
4573
+ * children (a button group, a segmented control) never does, so one
4574
+ * disabled child never makes the whole part look disabled.
2189
4575
  * @param {string} state
4576
+ * @param {boolean} [wrapsControl]
2190
4577
  * @returns {string}
2191
4578
  */
2192
- export function stateKey(state) {
2193
- return state === 'disabled'
2194
- ? ':is(:disabled,[aria-disabled="true"])'
2195
- : `:${state}`;
4579
+ export function stateKey(state, wrapsControl = false) {
4580
+ if (state !== 'disabled') return `:${state}`;
4581
+ return wrapsControl
4582
+ ? ':is(:disabled,[aria-disabled="true"],:has(:is(input,button,select,textarea):is(:disabled,[aria-disabled="true"])))'
4583
+ : ':is(:disabled,[aria-disabled="true"])';
4584
+ }
4585
+
4586
+ /**
4587
+ * The component docs of a part: its own component's, and the one named like
4588
+ * the part (tab is Tab, under TabList), each with its name, for the ones the
4589
+ * project has.
4590
+ * @param {Ctx} ctx
4591
+ * @param {string} part
4592
+ * @returns {Array<{name: string, doc: any}>}
4593
+ */
4594
+ export function partComponentDocs(ctx, part) {
4595
+ const comps = /** @type {Record<string, any>} */ (
4596
+ ctx.project.components ?? {}
4597
+ );
4598
+ const pascal = part.replace(/(^|-)([a-z0-9])/g, (_, __, c) =>
4599
+ c.toUpperCase(),
4600
+ );
4601
+ return [ctx.project.target.get(part)?.component, pascal]
4602
+ .filter(n => n != null && comps[n])
4603
+ .map(n => ({
4604
+ name: /** @type {string} */ (n),
4605
+ doc: comps[/** @type {string} */ (n)],
4606
+ }));
4607
+ }
4608
+
4609
+ /**
4610
+ * Whether a part's styled element wraps one control: its component (or the
4611
+ * one named like the part) is a form control (Core's own category) that
4612
+ * takes a disabled prop. An action part that holds children (a button
4613
+ * group) never does.
4614
+ * @param {Ctx} ctx
4615
+ * @param {string} target
4616
+ */
4617
+ export function wrapsOneControl(ctx, target) {
4618
+ // One control: a form control with a disabled prop whose content is not
4619
+ // other elements (a radio list's items, an input group's or a field's
4620
+ // children each hold controls of their own).
4621
+ return partComponentDocs(ctx, target).some(
4622
+ ({doc: d}) =>
4623
+ /form/i.test(String(d.category ?? '')) &&
4624
+ Object.keys(d.props ?? {}).some(p => /disabled/i.test(p)) &&
4625
+ d.props?.children?.type !== 'ReactNode',
4626
+ );
2196
4627
  }
2197
4628
 
2198
4629
  /**
@@ -2283,7 +4714,7 @@ export function madeByEditor(file) {
2283
4714
  try {
2284
4715
  return fs
2285
4716
  .readFileSync(file, 'utf8')
2286
- .startsWith('// Generated by `astryx experimental theme editor`');
4717
+ .startsWith(`// ${EDITOR_GENERATED_MARK}`);
2287
4718
  } catch {
2288
4719
  return false;
2289
4720
  }
@@ -2303,8 +4734,22 @@ export const EDITOR_SUFFIXES = [
2303
4734
  'd.ts',
2304
4735
  'variants.d.ts',
2305
4736
  'history.json',
4737
+ 'pictures.json',
2306
4738
  ];
2307
4739
 
4740
+ /**
4741
+ * Whether a name in a theme folder is a file the editor writes: the
4742
+ * theme's generated files, settings, history, picture record, pages and
4743
+ * pictures, and its color config.
4744
+ * @param {string} slug
4745
+ * @param {string} n
4746
+ */
4747
+ export const isEditorFile = (slug, n) =>
4748
+ EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
4749
+ /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config(\.damaged(-\d+)?)?\.json)$/.test(
4750
+ n,
4751
+ );
4752
+
2308
4753
  /**
2309
4754
  * The files in a theme folder that the editor writes, by name: the
2310
4755
  * theme's generated files, its settings, history and pages, and its color
@@ -2318,11 +4763,7 @@ export const EDITOR_SUFFIXES = [
2318
4763
  function ownFiles(dir) {
2319
4764
  if (!fs.lstatSync(dir, {throwIfNoEntry: false})?.isDirectory()) return [];
2320
4765
  const slug = path.basename(dir);
2321
- const mine = (/** @type {string} */ n) =>
2322
- EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
2323
- /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config(\.damaged(-\d+)?)?\.json)$/.test(
2324
- n,
2325
- );
4766
+ const mine = (/** @type {string} */ n) => isEditorFile(slug, n);
2326
4767
  /** @type {string[]} */
2327
4768
  const out = [];
2328
4769
  for (const e of fs.readdirSync(dir, {withFileTypes: true}))
@@ -2394,8 +4835,12 @@ function restoreWritten(was, wrote) {
2394
4835
  continue;
2395
4836
  }
2396
4837
  const old = was.get(p);
2397
- if (old) writeWhole(p, old);
2398
- else fs.rmSync(p, {force: true});
4838
+ if (old) {
4839
+ // A folder the change removed (tokens/ once its palette went) comes
4840
+ // back with the file.
4841
+ fs.mkdirSync(path.dirname(p), {recursive: true});
4842
+ writeWhole(p, old);
4843
+ } else fs.rmSync(p, {force: true});
2399
4844
  } catch {
2400
4845
  failed.push(path.basename(p));
2401
4846
  }
@@ -2427,30 +4872,65 @@ export function refuseLinks(cwd, slug) {
2427
4872
  const f = themeFiles(cwd, slug);
2428
4873
  /** @param {string} p */
2429
4874
  const link = p => {
2430
- if (fs.lstatSync(p, {throwIfNoEntry: false})?.isSymbolicLink())
2431
- throw new AstryxError(
2432
- `${path.relative(cwd, p) || p} is a link; the editor writes a theme's own files only, never through a link. Replace the link with a copy of what it points to. Nothing was changed.`,
2433
- [
2434
- {
2435
- name: `cp -rL ${quoteCommandArgument(path.relative(cwd, p))} ${quoteCommandArgument(`${path.relative(cwd, p)}.copy`)}`,
2436
- reason: 'copy what it points to, then put the copy in its place',
2437
- },
2438
- ],
2439
- ERROR_CODES.ERR_THEME_INVALID,
2440
- );
4875
+ // A path under a file (themes written as a file) is not a link: its
4876
+ // own refusal names it.
4877
+ /** @type {fs.Stats | undefined} */
4878
+ let st;
4879
+ try {
4880
+ st = fs.lstatSync(p, {throwIfNoEntry: false});
4881
+ } catch {
4882
+ return;
4883
+ }
4884
+ if (!st?.isSymbolicLink()) return;
4885
+ const rel = path.relative(cwd, p) || p;
4886
+ /** @type {string} */
4887
+ let target;
4888
+ try {
4889
+ target = fs.readlinkSync(p);
4890
+ } catch {
4891
+ target = '';
4892
+ }
4893
+ // Named, with where it points; nothing is removed or moved for the
4894
+ // user.
4895
+ const gone = !fs.existsSync(p);
4896
+ throw new AstryxError(
4897
+ `${rel} is a link to ${target || 'another file'}${gone ? ', which does not exist' : ''}; the editor reads and writes a theme's own files only, never through a link. ${gone ? `Put ${target || 'that file'} back, then put` : 'Put'} a copy of it in place of the link. Nothing was changed.`,
4898
+ [
4899
+ {
4900
+ name: `ls -l ${quoteCommandArgument(path.relative(cwd, p))}`,
4901
+ reason: 'shows where the link points',
4902
+ },
4903
+ ],
4904
+ ERROR_CODES.ERR_THEME_INVALID,
4905
+ );
2441
4906
  };
2442
4907
  link(f.root);
2443
4908
  link(f.dir);
2444
- /** @param {string} d */
2445
- const walk = d => {
2446
- if (!fs.lstatSync(d, {throwIfNoEntry: false})?.isDirectory()) return;
2447
- for (const e of fs.readdirSync(d, {withFileTypes: true})) {
2448
- const p = path.join(d, e.name);
2449
- link(p);
2450
- if (e.isDirectory()) walk(p);
4909
+ // Only the files the editor reads or writes: a link to a file of the
4910
+ // user's (notes, a mockup) is theirs, and is left alone.
4911
+ const own = (/** @type {string} */ n) =>
4912
+ isEditorFile(slug, n) || n === `${slug}.theme.ts` || n === 'tokens';
4913
+ /** @type {string[]} */
4914
+ let names;
4915
+ try {
4916
+ names = fs.readdirSync(f.dir);
4917
+ } catch {
4918
+ return;
4919
+ }
4920
+ for (const n of names.filter(own)) {
4921
+ const p = path.join(f.dir, n);
4922
+ link(p);
4923
+ if (n === 'tokens') {
4924
+ /** @type {string[]} */
4925
+ let inner;
4926
+ try {
4927
+ inner = fs.readdirSync(p);
4928
+ } catch {
4929
+ inner = [];
4930
+ }
4931
+ for (const m of inner) link(path.join(p, m));
2451
4932
  }
2452
- };
2453
- walk(f.dir);
4933
+ }
2454
4934
  }
2455
4935
 
2456
4936
  /**
@@ -2483,15 +4963,12 @@ export function settingsStamp(data) {
2483
4963
  */
2484
4964
  export function staleBuild(cwd, slug, data) {
2485
4965
  const f = themeFiles(cwd, slug);
2486
- // The generated colors are part of the build when a color dial is set.
2487
- const colors = data.settings.some(
2488
- s => s.source === 'dial' && PALETTE_DIALS.includes(s.thing),
2489
- )
2490
- ? [path.join(cwd, paletteFiles(slug).palette)]
2491
- : [];
2492
- const missing = [f.js, f.css, f.settingsTs, ...colors].find(
2493
- p => !fs.existsSync(p),
2494
- );
4966
+ const files = builtFiles(cwd, slug, data);
4967
+ // An output that cannot be read (its permissions, or a folder in its
4968
+ // place) is refused by name: the build cannot replace it either. That
4969
+ // includes the files a build writes only for some themes.
4970
+ refuseUnreadable(cwd, [...files, ...builtFiles(cwd, slug, data, true)]);
4971
+ const missing = files.find(p => !fs.existsSync(p));
2495
4972
  if (missing) return `${path.relative(f.dir, missing)} was missing`;
2496
4973
  const ts = fs.readFileSync(f.settingsTs, 'utf8');
2497
4974
  const stamp =
@@ -2510,6 +4987,16 @@ export function staleBuild(cwd, slug, data) {
2510
4987
  if (built && now && built !== now)
2511
4988
  return `@astryxdesign/theme-${data.like} is ${now} now, and the build was made on ${built}`;
2512
4989
  }
4990
+ // The generated module seals its own text: a hand edit inside it (the
4991
+ // file says not to) is built over from the settings, and said. Checked
4992
+ // after the stamps, whose reasons say more.
4993
+ if (moduleUnedited(ts) === false)
4994
+ return `${slug}.settings.ts was edited by hand, though it is generated from ${slug}.settings.json and says not to edit it`;
4995
+ // An own change to <slug>.theme.ts since the build (the file says it
4996
+ // wins over the settings) is built in.
4997
+ const source = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(ts);
4998
+ if (source && fs.existsSync(f.ts) && source[1] !== themeSourceHash(cwd, slug))
4999
+ return sourceChangedReason(slug);
2513
5000
  // By content, never by file times (an editor's re-save or a checkout
2514
5001
  // changes those): a generated module cut short, or built outputs whose
2515
5002
  // header names another CLI than the settings were written by (a build
@@ -2526,6 +5013,17 @@ export function staleBuild(cwd, slug, data) {
2526
5013
  })
2527
5014
  )
2528
5015
  return 'the last build did not finish (a command stopped while building)';
5016
+ // Outputs another theme's build wrote over (`compile other.theme.ts --out
5017
+ // themes/g/g.css`): their header names another source.
5018
+ const builtFrom = (/** @type {string} */ file) =>
5019
+ /^ \* Source: (.+)$/m
5020
+ .exec(fs.readFileSync(file, 'utf8').slice(0, 600))?.[1]
5021
+ ?.trim() ?? null;
5022
+ for (const file of [f.css, f.js]) {
5023
+ const from = builtFrom(file);
5024
+ if (from != null && path.basename(from) !== path.basename(f.ts))
5025
+ return `${path.basename(file)} was built from ${from}, not ${slug}.theme.ts`;
5026
+ }
2529
5027
  // A built stylesheet cut short (a crash, a bad merge) is built again, as
2530
5028
  // an unreadable built module is.
2531
5029
  try {
@@ -2536,6 +5034,79 @@ export function staleBuild(cwd, slug, data) {
2536
5034
  return null;
2537
5035
  }
2538
5036
 
5037
+ /**
5038
+ * Every file the editor's build of a theme writes, the one list staleness
5039
+ * reads: the generated settings module, the built stylesheet, module and
5040
+ * their types, and, with a color dial set, the generated color files.
5041
+ * @param {string} cwd
5042
+ * @param {string} slug
5043
+ * @param {ThemeData} data
5044
+ * @param {boolean} [some] the files a build writes only for some themes
5045
+ * (the variants types, for a theme with component variants) instead
5046
+ * @returns {string[]}
5047
+ */
5048
+ export function builtFiles(cwd, slug, data, some = false) {
5049
+ const f = themeFiles(cwd, slug);
5050
+ if (some) return [path.join(f.dir, `${slug}.variants.d.ts`)];
5051
+ const pal = paletteFiles(slug);
5052
+ const colors = data.settings.some(
5053
+ s => s.source === 'dial' && PALETTE_DIALS.includes(s.thing),
5054
+ )
5055
+ ? [pal.palette, pal.refs, pal.receipt].map(p => path.join(cwd, p))
5056
+ : [];
5057
+ return [
5058
+ f.settingsTs,
5059
+ // The theme's own source: the editor writes it once, and every build
5060
+ // reads it, so one deleted by hand is written again.
5061
+ f.ts,
5062
+ f.css,
5063
+ f.js,
5064
+ path.join(f.dir, `${slug}.d.ts`),
5065
+ path.join(f.dir, `${slug}.css.d.ts`),
5066
+ ...colors,
5067
+ ];
5068
+ }
5069
+
5070
+ /**
5071
+ * Refuse, by name, a built file that is there but cannot be read: its
5072
+ * permissions, or a folder where the file goes.
5073
+ * @param {string} cwd
5074
+ * @param {string[]} files
5075
+ */
5076
+ function refuseUnreadable(cwd, files) {
5077
+ for (const file of files) {
5078
+ const st = fs.statSync(file, {throwIfNoEntry: false});
5079
+ if (!st) continue;
5080
+ const rel = shown(cwd, file);
5081
+ if (st.isDirectory())
5082
+ throw new AstryxError(
5083
+ `${rel} is a folder where the build writes a file, so the theme cannot be built. Move or rename the folder, then run the command again. Nothing was changed.`,
5084
+ [
5085
+ {
5086
+ name: `ls -la ${quoteCommandArgument(rel)}`,
5087
+ reason: 'see what is there',
5088
+ },
5089
+ ],
5090
+ ERROR_CODES.ERR_FILE_EXISTS,
5091
+ );
5092
+ try {
5093
+ fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK);
5094
+ } catch (e) {
5095
+ const code = /** @type {any} */ (e)?.code ?? 'EACCES';
5096
+ throw new AstryxError(
5097
+ `${rel} cannot be read or replaced (${code}: its permissions), so the theme cannot be built. Give yourself read and write permission on it (chmod u+rw ${rel}), then run the command again. Nothing was changed.`,
5098
+ [
5099
+ {
5100
+ name: `ls -la ${quoteCommandArgument(rel)}`,
5101
+ reason: 'see its permissions',
5102
+ },
5103
+ ],
5104
+ ERROR_CODES.ERR_WRITE_FAILED,
5105
+ );
5106
+ }
5107
+ }
5108
+ }
5109
+
2539
5110
  /**
2540
5111
  * The installed version of a base theme package, or null.
2541
5112
  * @param {string} cwd
@@ -2572,6 +5143,19 @@ export const HISTORY_STEPS = 80;
2572
5143
  */
2573
5144
  export function readHistory(file) {
2574
5145
  if (!fs.existsSync(file)) return {steps: [], dropped: 0};
5146
+ // A history that cannot be read is not damaged: it is refused by name.
5147
+ const why = unreadableReason(file);
5148
+ if (why)
5149
+ throw new AstryxError(
5150
+ `${path.basename(file)} ${why}, so the undo history cannot be read. Give it back its place or its read permission; nothing was changed.`,
5151
+ [
5152
+ {
5153
+ name: `ls -la ${quoteCommandArgument(file)}`,
5154
+ reason: 'see what is there',
5155
+ },
5156
+ ],
5157
+ ERROR_CODES.ERR_THEME_INVALID,
5158
+ );
2575
5159
  /** @type {unknown} */
2576
5160
  let h;
2577
5161
  try {
@@ -2646,7 +5230,14 @@ export async function commitTheme(
2646
5230
  // A no-op change still mends a build that does not match the settings
2647
5231
  // (an undo stopped part way): it is built again, with no new step.
2648
5232
  const noop = history && same(parseSettings(snapBefore));
2649
- if (noop && fs.existsSync(f.js) && !staleBuild(cwd, slug, data))
5233
+ const stale =
5234
+ noop && fs.existsSync(f.js) ? staleBuild(cwd, slug, data) : null;
5235
+ // The no-op that mends one says what it built again.
5236
+ if (noop && stale)
5237
+ notes.push(
5238
+ `the build was not current (${stale}), so it was built again from the settings`,
5239
+ );
5240
+ if (noop && fs.existsSync(f.js) && !stale)
2650
5241
  return {
2651
5242
  changed: [],
2652
5243
  res: {light: {}, dark: {}},
@@ -2656,6 +5247,11 @@ export async function commitTheme(
2656
5247
  notes,
2657
5248
  unchanged: true,
2658
5249
  };
5250
+ // With no last build (deleted, never committed), nothing is compared.
5251
+ if (snapBefore && !fs.existsSync(f.js))
5252
+ notes.push(
5253
+ `there was no last build (${path.basename(f.js)} is missing), so the token changes are not listed; the theme is built again`,
5254
+ );
2659
5255
  const resBefore =
2660
5256
  snapBefore && fs.existsSync(f.js)
2661
5257
  ? await resolvedTokens(ctx, slug).catch(() => {
@@ -2668,7 +5264,9 @@ export async function commitTheme(
2668
5264
  })
2669
5265
  : null;
2670
5266
  const before = parseSettings(snapBefore);
2671
- const liftedBefore = new Set(before?.lifted ?? []);
5267
+ const liftedBefore = new Set(
5268
+ Array.isArray(before?.lifted) ? before.lifted : [],
5269
+ );
2672
5270
  // A change that leaves every color setting as it was keeps the shades the
2673
5271
  // theme already shows: a theme an earlier editor built keeps its colors
2674
5272
  // until a color, the mode or the base changes, and undo brings them back.
@@ -2728,6 +5326,12 @@ export async function commitTheme(
2728
5326
  fs.mkdirSync(f.dir, {recursive: true});
2729
5327
  /** @type {{warnings: string[], lifted: string[], notes: string[]}} */
2730
5328
  let built;
5329
+ // The token loops the last build had, so a change that adds one (through
5330
+ // tokens the own source sets in a way no read of the file follows) is
5331
+ // refused once the build shows it.
5332
+ const loopsBefore = new Set(builtLoops(cwd, slug).map(l => l.key));
5333
+ // The app copy is written once the change is saved, never before.
5334
+ afterSave.add(ctx);
2731
5335
  try {
2732
5336
  refuseIfLockLost();
2733
5337
  try {
@@ -2738,6 +5342,18 @@ export async function commitTheme(
2738
5342
  // The build writes its outputs itself: a lock lost meanwhile is seen
2739
5343
  // before anything else is written.
2740
5344
  refuseIfLockLost();
5345
+ const loop = builtLoops(cwd, slug).find(l => !loopsBefore.has(l.key));
5346
+ if (loop)
5347
+ throw new AstryxError(
5348
+ `${loop.path.join(' reads ')}${loop.part ? ` on ${loop.part}` : ''}: the change makes these tokens read each other (with what ${slug}.theme.ts or the base theme sets), so they would have no value at all. Nothing was changed.`,
5349
+ [
5350
+ {
5351
+ name: `${P} how ${loop.path[0].replace(/^--/, '')}`,
5352
+ reason: 'see what it takes',
5353
+ },
5354
+ ],
5355
+ ERROR_CODES.ERR_THEME_BAD_VALUE,
5356
+ );
2741
5357
  data.lifted = built.lifted;
2742
5358
  // The undo step and the settings are part of the change: written whole,
2743
5359
  // inside the rollback, the settings first. A command stopped between
@@ -2762,7 +5378,16 @@ export async function commitTheme(
2762
5378
  // Settings written whole: a `new` marker left beside them (a `new`
2763
5379
  // stopped after its theme was made) has nothing left to finish.
2764
5380
  clearNewMarker(f.dir);
5381
+ afterSave.delete(ctx);
5382
+ // The change is saved: its app copy follows. A copy that cannot be
5383
+ // written leaves the copy as it was; the change stands.
5384
+ try {
5385
+ afterBuild?.(ctx, slug, data);
5386
+ } catch (e) {
5387
+ if (/** @type {any} */ (e)?.lockLost) throw e;
5388
+ }
2765
5389
  } catch (e) {
5390
+ afterSave.delete(ctx);
2766
5391
  // A command that lost its lock while stopped owns none of these files
2767
5392
  // now: it puts nothing back and deletes nothing (that would undo the
2768
5393
  // other command's change).
@@ -2784,7 +5409,7 @@ export async function commitTheme(
2784
5409
  const code = /** @type {any} */ (e)?.code;
2785
5410
  if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO', 'EISDIR'].includes(code))
2786
5411
  throw new AstryxError(
2787
- `Could not write the theme files (${code}), so the change was undone. Free space or fix the permission, then run the command again.`,
5412
+ `Could not write the theme files (${code}), so the files were put back as they were. Free space or fix the permission, then run the command again. Nothing was changed.`,
2788
5413
  [
2789
5414
  {
2790
5415
  name: `ls -ld ${quoteCommandArgument(themeFiles(ctx.project.cwd, slug).dir)}`,
@@ -2800,9 +5425,27 @@ export async function commitTheme(
2800
5425
  e.code === ERROR_CODES.ERR_THEME_INVALID ||
2801
5426
  e.code === ERROR_CODES.ERR_PALETTE_GENERATION ||
2802
5427
  e.code === ERROR_CODES.ERR_WRITE_FAILED ||
2803
- e.code === ERROR_CODES.ERR_THEME_BUSY)
5428
+ e.code === ERROR_CODES.ERR_THEME_BUSY ||
5429
+ e.code === ERROR_CODES.ERR_THEME_BAD_VALUE)
2804
5430
  )
2805
5431
  throw e;
5432
+ // A folder where a built file goes: named for the editor, which has no
5433
+ // --out to pick.
5434
+ const folder =
5435
+ e instanceof AstryxError
5436
+ ? /^The output (.+) is a folder\./.exec(e.message)?.[1]
5437
+ : undefined;
5438
+ if (folder)
5439
+ throw new AstryxError(
5440
+ `${folder} is a folder, not a file, so the theme cannot be built. Put the file back in its place; nothing was changed.`,
5441
+ [
5442
+ {
5443
+ name: `ls -la ${quoteCommandArgument(folder)}`,
5444
+ reason: 'see what is there',
5445
+ },
5446
+ ],
5447
+ ERROR_CODES.ERR_THEME_INVALID,
5448
+ );
2806
5449
  const why = (e instanceof Error ? e.message : String(e))
2807
5450
  .split(`${cwd}${path.sep}`)
2808
5451
  .join('')
@@ -2812,12 +5455,17 @@ export async function commitTheme(
2812
5455
  .join(' | ');
2813
5456
  const own = why.includes(path.basename(f.ts));
2814
5457
  throw new AstryxError(
2815
- `The theme did not build, so the change was undone: ${why}${own ? ` (${shown(cwd, f.ts)} is your own file: fix it, then run the command again)` : ''}`,
5458
+ `The theme did not build, so the files were put back as they were: ${why}${own ? ` (${shown(cwd, f.ts)} is your own file: fix it, then run the command again)` : ''}. Nothing was changed.`,
2816
5459
  [
2817
- {
2818
- name: `${P} show ${slug}`,
2819
- reason: 'do this instead: see the settings as they are',
2820
- },
5460
+ own
5461
+ ? {
5462
+ name: `cat ${quoteCommandArgument(shown(cwd, f.ts))}`,
5463
+ reason: 'see your own file, then fix it',
5464
+ }
5465
+ : {
5466
+ name: `${P} show ${slug}`,
5467
+ reason: 'do this instead: see the settings as they are',
5468
+ },
2821
5469
  ],
2822
5470
  ERROR_CODES.ERR_THEME_INVALID,
2823
5471
  );