@astryxdesign/cli 0.7.15 → 0.7.16-canary.g07c77c0

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 (159) hide show
  1. package/README.md +5 -3
  2. package/api/build/_adapter.d.mts +1 -0
  3. package/api/build/blocks/blocks.d.mts +1 -0
  4. package/api/build/blocks/blocks.mjs +18 -1
  5. package/api/component/_adapter.d.mts +1 -1
  6. package/api/component/_adapter.mjs +28 -1
  7. package/api/doctor/_adapter.d.mts +17 -0
  8. package/api/doctor/_adapter.mjs +43 -0
  9. package/api/doctor/built-checks.mjs +1 -1
  10. package/api/doctor/doctor.mjs +18 -4
  11. package/api/doctor/theme-checks.mjs +1 -1
  12. package/api/integration/add-contribution.mjs +3 -3
  13. package/api/integration/pack-check.mjs +14 -8
  14. package/api/integration/validate-integration.mjs +1 -1
  15. package/api/search/_adapter.mjs +15 -16
  16. package/api/search/_entries.d.mts +2 -1
  17. package/api/search/_entries.mjs +28 -1
  18. package/api/swizzle/_moduleGraph.mjs +1 -1
  19. package/api/theme/_adapter.d.mts +5 -2
  20. package/api/theme/_adapter.mjs +43 -12
  21. package/api/theme/_fork.mjs +1 -1
  22. package/api/theme/build/build.d.mts +116 -32
  23. package/api/theme/build/build.mjs +449 -102
  24. package/api/theme/eject/eject.mjs +22 -1
  25. package/api/theme/template/template.d.mts +19 -0
  26. package/api/theme/template/template.mjs +102 -25
  27. package/api/theme/theme.type.d.mts +5 -1
  28. package/api/theme/theme.type.mjs +2 -1
  29. package/api/theme/themeBuild.doc.mjs +3 -3
  30. package/api/theme/themeEject.doc.mjs +1 -1
  31. package/api/theme/themeTemplate.doc.mjs +9 -3
  32. package/api/theme-edit/_adapter.d.mts +32 -2
  33. package/api/theme-edit/_adapter.mjs +213 -36
  34. package/api/theme-edit/_check.d.mts +69 -3
  35. package/api/theme-edit/_check.mjs +1517 -218
  36. package/api/theme-edit/_color.d.mts +2 -8
  37. package/api/theme-edit/_color.mjs +292 -219
  38. package/api/theme-edit/_compiler.d.mts +1 -0
  39. package/api/theme-edit/_compiler.mjs +20 -1
  40. package/api/theme-edit/_context.d.mts +29 -0
  41. package/api/theme-edit/_context.mjs +426 -40
  42. package/api/theme-edit/_css.d.mts +60 -1
  43. package/api/theme-edit/_css.mjs +404 -28
  44. package/api/theme-edit/_edit.d.mts +9 -0
  45. package/api/theme-edit/_edit.mjs +1300 -135
  46. package/api/theme-edit/_how-commands.d.mts +11 -26
  47. package/api/theme-edit/_how-commands.mjs +30 -2
  48. package/api/theme-edit/_how-question.d.mts +7 -0
  49. package/api/theme-edit/_how-question.mjs +1304 -176
  50. package/api/theme-edit/_how.mjs +144 -30
  51. package/api/theme-edit/_overview.mjs +2 -0
  52. package/api/theme-edit/_palette.d.mts +11 -0
  53. package/api/theme-edit/_palette.mjs +194 -65
  54. package/api/theme-edit/_parts.d.mts +33 -0
  55. package/api/theme-edit/_parts.mjs +138 -9
  56. package/api/theme-edit/_png.d.mts +18 -0
  57. package/api/theme-edit/_png.mjs +95 -14
  58. package/api/theme-edit/_preview-app.d.mts +9 -0
  59. package/api/theme-edit/_preview-app.mjs +1191 -71
  60. package/api/theme-edit/_preview.d.mts +16 -3
  61. package/api/theme-edit/_preview.mjs +335 -30
  62. package/api/theme-edit/_project.d.mts +11 -0
  63. package/api/theme-edit/_project.mjs +46 -12
  64. package/api/theme-edit/_settings.d.mts +240 -5
  65. package/api/theme-edit/_settings.mjs +2561 -115
  66. package/api/theme-edit/_tables.d.mts +24 -0
  67. package/api/theme-edit/_tables.mjs +211 -149
  68. package/api/theme-edit/_vet.d.mts +42 -0
  69. package/api/theme-edit/_vet.mjs +144 -0
  70. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  71. package/api/theme-edit/theme-edit.type.mjs +1 -1
  72. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  73. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  74. package/api/upgrade/registry/registry.mjs +6 -1
  75. package/assets/codemods/parse.mjs +2 -2
  76. package/assets/docs/tree/single-component.doc.mjs +11 -2
  77. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  78. package/assets/docs.generated.json +2 -2
  79. package/assets/preview-app/next.config.mjs +7 -1
  80. package/assets/preview-app/package.json +1 -0
  81. package/assets/preview-app/src/app/globals.css +1 -0
  82. package/assets/self-audit.generated.json +1 -1
  83. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  84. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  85. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  86. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  87. package/assets/templates/components.generated.json +1 -1
  88. package/assets/templates/pages/dashboard/page.tsx +1 -1
  89. package/authoring/doctypes/_schema.d.mts +52 -5
  90. package/authoring/doctypes/_schema.mjs +62 -7
  91. package/authoring/doctypes/base/type.ts +10 -0
  92. package/authoring/doctypes/component/component.doc.mjs +1 -1
  93. package/authoring/doctypes/function/function.doc.mjs +6 -0
  94. package/authoring/doctypes/function/type.ts +3 -0
  95. package/authoring/doctypes/legacy.mjs +5 -1
  96. package/authoring/index.d.ts +1 -0
  97. package/authoring/shadcn/source-variants.d.mts +1 -1
  98. package/authoring/shadcn/source-variants.mjs +32 -10
  99. package/clients/cli/build-id.generated.json +1 -1
  100. package/clients/cli/commands/doctor.doc.mjs +2 -2
  101. package/clients/cli/commands/experimental/theme.mjs +237 -45
  102. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  103. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  104. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  105. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  106. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  108. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  109. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  110. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  111. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  112. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  113. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  114. package/clients/cli/commands/theme.mjs +190 -46
  115. package/clients/cli/formatters/index.mjs +7 -4
  116. package/clients/cli/lib/cli-error.mjs +9 -3
  117. package/clients/cli/lib/component-format.mjs +27 -9
  118. package/clients/cli/lib/json-shim.mjs +72 -2
  119. package/clients/cli/manifest.generated.json +1 -1
  120. package/clients/cli/run.mjs +49 -0
  121. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  122. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  123. package/foundation/agent-docs/agent-docs.mjs +3 -2
  124. package/foundation/config/config-writer.mjs +2 -2
  125. package/foundation/config/project.mjs +60 -14
  126. package/foundation/discovery/component-discovery.mjs +5 -17
  127. package/foundation/discovery/icon-set-writer.mjs +1 -1
  128. package/foundation/discovery/module-exports.mjs +1 -15
  129. package/foundation/discovery/template-adapter.mjs +44 -19
  130. package/foundation/discovery/template-source-tree.mjs +3 -16
  131. package/foundation/discovery/theme-discovery.d.mts +5 -1
  132. package/foundation/discovery/theme-discovery.mjs +30 -35
  133. package/foundation/fs/exact-codec.d.mts +35 -0
  134. package/foundation/fs/exact-codec.mjs +148 -0
  135. package/foundation/fs/gather-cache.d.mts +15 -5
  136. package/foundation/fs/gather-cache.mjs +123 -30
  137. package/foundation/fs/paths.d.mts +39 -0
  138. package/foundation/fs/paths.mjs +44 -11
  139. package/foundation/fs/read-record.mjs +11 -1
  140. package/foundation/integrations/contribution-fixes.mjs +1 -16
  141. package/foundation/integrations/may-have-integrations.mjs +3 -2
  142. package/foundation/integrations/public-imports.mjs +1 -1
  143. package/foundation/render/embedded-imports.mjs +1 -1
  144. package/foundation/render/host-exit.d.mts +8 -0
  145. package/foundation/render/host-exit.mjs +11 -0
  146. package/foundation/render/page-host.mjs +56 -10
  147. package/foundation/render/page-worker.mjs +14 -0
  148. package/foundation/render/render-page.mjs +37 -2
  149. package/foundation/response/error-codes.d.mts +2 -1
  150. package/foundation/response/error-codes.d.ts +1 -0
  151. package/foundation/response/error-codes.doc.mjs +5 -0
  152. package/foundation/response/error-codes.mjs +3 -0
  153. package/foundation/response/json.d.mts +15 -0
  154. package/foundation/response/json.mjs +52 -1
  155. package/foundation/response/response-types.doc.mjs +1 -1
  156. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  157. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  158. package/foundation/xle/browser.d.mts +2 -2
  159. package/package.json +7 -6
@@ -10,11 +10,14 @@
10
10
  * @position api/theme-edit — storage and compile for the theme commands
11
11
  */
12
12
 
13
+ import {parse as parseModule} from '@babel/parser';
13
14
  import {createHash} from 'node:crypto';
14
15
  import * as fs from 'node:fs';
16
+ import {coversProperty, cssNumber, longhandsOf} from './_css.mjs';
15
17
  import postcss from 'postcss';
16
18
  import {createRequire} from 'node:module';
17
19
  import * as path from 'node:path';
20
+ import {themeFileImports} from '../../foundation/discovery/theme-discovery.mjs';
18
21
  import {pathToFileURL} from 'node:url';
19
22
  import {cliVersion} from '../../foundation/release/run-context.mjs';
20
23
  import {AstryxError} from '../error.mjs';
@@ -39,9 +42,12 @@ import {
39
42
  TEXT_SIZE,
40
43
  TYPE_STYLES,
41
44
  familyOf,
45
+ WRAPPED_PARTS,
46
+ CARD_LIKE,
42
47
  } from './_tables.mjs';
43
48
  import {
44
49
  alphaOf,
50
+ colorProblem,
45
51
  compositeOver,
46
52
  isColorValue,
47
53
  isSafeValue,
@@ -63,11 +69,21 @@ import {
63
69
  lockHeld,
64
70
  removeEmptyFolder,
65
71
  writeWhole,
72
+ setOwnTokenReader,
66
73
  } from './_palette.mjs';
74
+ import {EDITOR_STAMP, pngTexts} from './_png.mjs';
67
75
  import {MODAL, isColorToken} from './_compiler.mjs';
68
- import {baseResolved, baseThemeFile} from './_project.mjs';
76
+ import {
77
+ baseInstalled,
78
+ baseModule,
79
+ baseResolved,
80
+ baseThemeFile,
81
+ } from './_project.mjs';
69
82
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
70
83
 
84
+ // The palette reads the tokens the own source sets through this module.
85
+ setOwnTokenReader((cwd, slug) => ownSourceTokenValues(cwd, slug));
86
+
71
87
  /**
72
88
  * One setting the CLI owns.
73
89
  * @typedef {object} Setting
@@ -97,7 +113,7 @@ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
97
113
  /** What lifted secondary text sits on: the contrast check measures it there. */
98
114
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
99
115
 
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 */
116
+ /** @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
117
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
102
118
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
103
119
 
@@ -113,12 +129,17 @@ export const slugOk = s =>
113
129
  !windowsReserved(s);
114
130
 
115
131
  /**
116
- * A name Windows reserves for a device (con, nul, com1…): a folder named
117
- * so cannot be checked out there.
132
+ * A name Windows does not allow for a file or folder, so it cannot be
133
+ * checked out there: a device name (con, nul, com1, com¹…), a character
134
+ * Windows reserves (`<>:"|?*` and control characters), or a dot or space
135
+ * at the end.
118
136
  * @param {string} s
119
137
  */
120
138
  export const windowsReserved = s =>
121
- /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(s);
139
+ /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i.test(s) ||
140
+ // eslint-disable-next-line no-control-regex
141
+ /[<>:"|?*\u0000-\u001f]/.test(s) ||
142
+ /[. ]$/.test(s);
122
143
  /**
123
144
  * The theme name closest to what was typed: spaces and accents dropped,
124
145
  * lower case, anything else a dash.
@@ -167,10 +188,271 @@ export function themeFiles(cwd, slug) {
167
188
  preview: path.join(dir, 'preview.html'),
168
189
  sheet: path.join(dir, 'sheet.html'),
169
190
  previewPng: path.join(dir, 'preview.png'),
191
+ pictures: path.join(dir, `${slug}.pictures.json`),
170
192
  sheetPng: path.join(dir, 'sheet.png'),
171
193
  };
172
194
  }
173
195
 
196
+ /**
197
+ * Whether a value fits what a dial takes, read from the dial's own list of
198
+ * values: a named rung in any case, or a value of the kind it names (a size,
199
+ * a color, a number). `set` still checks the value in full.
200
+ * @param {string} dial
201
+ * @param {string} value
202
+ */
203
+ export function dialValueFits(dial, value) {
204
+ const spec = DIALS[/** @type {keyof typeof DIALS} */ (dial)]?.values;
205
+ if (!spec) return false;
206
+ const v = String(value).trim();
207
+ if (v === '') return false;
208
+ return spec.split('|').some(option => {
209
+ if (!option.startsWith('<') && !option.startsWith('"'))
210
+ return option === v.toLowerCase();
211
+ if (option.startsWith('"')) return true;
212
+ if (option.includes('size')) return /^\d*\.?\d+(px|rem|em)$/.test(v);
213
+ // A color by the editor's own color check (a bare word only when it
214
+ // names a color).
215
+ if (option === '<color>') return colorProblem(v) == null;
216
+ if (option === '<0-100>') return /^\d{1,3}$/.test(v) && Number(v) <= 100;
217
+ if (option === '<number>') return /^\d*\.?\d+$/.test(v);
218
+ return false;
219
+ });
220
+ }
221
+
222
+ /**
223
+ * Where the editor records the pictures it wrote into a theme folder: a
224
+ * file of the theme's own beside its settings and history, each picture by
225
+ * its name with the hash of what was written, so the record moves and is
226
+ * copied with the theme.
227
+ * @param {string} cwd
228
+ * @param {string} slug
229
+ */
230
+ function writtenRecord(cwd, slug) {
231
+ return themeFiles(cwd, slug).pictures;
232
+ }
233
+
234
+ /** @param {string} file @returns {string | null} */
235
+ const contentHash = file => {
236
+ try {
237
+ return createHash('sha256').update(fs.readFileSync(file)).digest('hex');
238
+ } catch {
239
+ return null;
240
+ }
241
+ };
242
+
243
+ /** @param {string} rec @returns {Record<string, string>} */
244
+ const readRecord = rec => {
245
+ try {
246
+ const json = JSON.parse(fs.readFileSync(rec, 'utf8'));
247
+ return json && typeof json === 'object' && !Array.isArray(json) ? json : {};
248
+ } catch {
249
+ return {};
250
+ }
251
+ };
252
+
253
+ /** @param {string} rec @param {Record<string, string>} map */
254
+ const writeRecord = (rec, map) => {
255
+ try {
256
+ if (!Object.keys(map).length) fs.rmSync(rec, {force: true});
257
+ else writeWhole(rec, `${JSON.stringify(map, null, 2)}\n`);
258
+ } catch {
259
+ // Without a record nothing is removed later: the safe way round.
260
+ }
261
+ };
262
+
263
+ /**
264
+ * Record files the editor just wrote into a theme folder.
265
+ * @param {string} cwd
266
+ * @param {string} slug
267
+ * @param {string[]} files
268
+ */
269
+ export function recordWritten(cwd, slug, files) {
270
+ const rec = writtenRecord(cwd, slug);
271
+ const map = readRecord(rec);
272
+ for (const file of files) {
273
+ const hash = contentHash(file);
274
+ if (hash) map[path.basename(file)] = hash;
275
+ }
276
+ writeRecord(rec, map);
277
+ }
278
+
279
+ /**
280
+ * Whether the editor wrote this file in the theme folder and it is
281
+ * unchanged since.
282
+ * @param {string} cwd
283
+ * @param {string} slug
284
+ * @param {string} file
285
+ */
286
+ export function editorWrote(cwd, slug, file) {
287
+ const map = readRecord(writtenRecord(cwd, slug));
288
+ const was = map[path.basename(file)];
289
+ // A recorded picture is the editor's only while it is as it wrote it: a
290
+ // picture changed after (re-saved by another tool, stamp and all) is the
291
+ // person's.
292
+ if (was) return was === contentHash(file);
293
+ // With no record of it, the picture's stamp names the theme it shows.
294
+ try {
295
+ return pngTexts(fs.readFileSync(file))[EDITOR_STAMP] === slug;
296
+ } catch {
297
+ return false;
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Adopt a picture an older editor took (before it recorded or stamped its
303
+ * pictures) into the record: only while the theme has no record at all, the
304
+ * name is one the editor writes, and the picture is the editor's 1280-pixel
305
+ * wide window. Returns whether it was adopted.
306
+ * @param {string} cwd
307
+ * @param {string} slug
308
+ * @param {string} file
309
+ */
310
+ export function adoptOlderPicture(cwd, slug, file) {
311
+ if (fs.existsSync(themeFiles(cwd, slug).pictures)) return false;
312
+ if (!/^(sheet|preview)(-[a-z-]+)?\.png$/.test(path.basename(file)))
313
+ return false;
314
+ /** @type {Buffer} */
315
+ let bytes;
316
+ try {
317
+ bytes = fs.readFileSync(file);
318
+ } catch {
319
+ return false;
320
+ }
321
+ // The width in the PNG header: the editor takes a 1280-pixel window.
322
+ if (
323
+ bytes.length < 24 ||
324
+ bytes.toString('latin1', 12, 16) !== 'IHDR' ||
325
+ bytes.readUInt32BE(16) !== 1280
326
+ )
327
+ return false;
328
+ recordWritten(cwd, slug, [file]);
329
+ return true;
330
+ }
331
+
332
+ /**
333
+ * Drop names from the record of what the editor wrote.
334
+ * @param {string} cwd
335
+ * @param {string} slug
336
+ * @param {string[]} names
337
+ */
338
+ function forgetWritten(cwd, slug, names) {
339
+ if (!names.length) return;
340
+ const rec = writtenRecord(cwd, slug);
341
+ const map = readRecord(rec);
342
+ for (const n of names) delete map[n];
343
+ writeRecord(rec, map);
344
+ }
345
+
346
+ /**
347
+ * A name `new` takes, for a suggestion: `name` itself when it is valid, not a
348
+ * built-in theme and its folder is free; `my-<name>` for a built-in theme's
349
+ * name; else the first free numbered name.
350
+ * @param {string} cwd
351
+ * @param {string} name
352
+ */
353
+ export function usableNewName(cwd, name) {
354
+ const base = LIKE.includes(name) ? `my-${name}` : name;
355
+ return slugOk(base) && !fs.existsSync(themeFiles(cwd, base).dir)
356
+ ? base
357
+ : freeThemeName(cwd, base);
358
+ }
359
+
360
+ /**
361
+ * A theme name near `name` that is valid and whose folder is free: `name-2`,
362
+ * `name-3`, …, shortened to fit the name's length limit.
363
+ * @param {string} cwd
364
+ * @param {string} name
365
+ */
366
+ export function freeThemeName(cwd, name) {
367
+ for (let n = 2; n < 1000; n += 1) {
368
+ const suffix = `-${n}`;
369
+ const candidate = `${name.slice(0, 64 - suffix.length).replace(/-+$/, '')}${suffix}`;
370
+ if (slugOk(candidate) && !fs.existsSync(themeFiles(cwd, candidate).dir))
371
+ return candidate;
372
+ }
373
+ return '<another name>';
374
+ }
375
+
376
+ /**
377
+ * Why the editor cannot read one of its files, or null when it can (or the
378
+ * file is not there): a folder in the file's place, or no permission to read
379
+ * it. Bad content is a different problem, judged where the file is parsed.
380
+ * @param {string} file
381
+ * @returns {string | null}
382
+ */
383
+ export function unreadableReason(file) {
384
+ let st;
385
+ try {
386
+ st = fs.statSync(file);
387
+ } catch (e) {
388
+ const code = /** @type {any} */ (e)?.code;
389
+ return code === 'ENOENT' || code === 'ENOTDIR'
390
+ ? null
391
+ : `it cannot be read (${code ?? 'unknown error'})`;
392
+ }
393
+ if (st.isDirectory()) return 'it is a folder, not a file';
394
+ try {
395
+ fs.accessSync(file, fs.constants.R_OK);
396
+ } catch (e) {
397
+ return `it cannot be read (${/** @type {any} */ (e)?.code ?? 'no permission'}: permission denied)`;
398
+ }
399
+ return null;
400
+ }
401
+
402
+ /**
403
+ * Refuse, by name, when a file of the theme is a folder or cannot be read:
404
+ * every command reads them, and none should crash on one. The fix is to
405
+ * look at the file and give it back its place; a file is never deleted.
406
+ * @param {string} cwd
407
+ * @param {string} slug
408
+ */
409
+ export function refuseUnreadableFiles(cwd, slug) {
410
+ const f = themeFiles(cwd, slug);
411
+ // The files the editor reads (the settings, the source, the history) are
412
+ // named here; the files the build writes (with their types) by the
413
+ // build's own check, the same one show uses.
414
+ refuseUnreadable(cwd, [
415
+ ...builtFiles(cwd, slug, {name: slug, mode: 'both', settings: []}),
416
+ path.join(f.dir, `${slug}.variants.d.ts`),
417
+ ]);
418
+ for (const file of [f.settings, f.ts, f.history]) {
419
+ const why = unreadableReason(file);
420
+ if (why)
421
+ throw new AstryxError(
422
+ `${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.`,
423
+ [
424
+ {
425
+ name: `ls -la ${quoteCommandArgument(path.relative(cwd, file))}`,
426
+ reason: 'see what is there',
427
+ },
428
+ ],
429
+ ERROR_CODES.ERR_THEME_INVALID,
430
+ );
431
+ }
432
+ }
433
+
434
+ /**
435
+ * Refuse when the app's themes/ is a file or a link to something other
436
+ * than a folder: every editor theme lives in themes/<name>/. The run lists
437
+ * what is there; the message says to rename or move it.
438
+ * @param {string} cwd
439
+ */
440
+ export function refuseThemesNotFolder(cwd) {
441
+ const root = path.join(cwd, 'themes');
442
+ const st = fs.lstatSync(root, {throwIfNoEntry: false});
443
+ if (!st) return;
444
+ const isDir =
445
+ st.isDirectory() ||
446
+ (st.isSymbolicLink() &&
447
+ fs.statSync(root, {throwIfNoEntry: false})?.isDirectory());
448
+ if (isDir) return;
449
+ refuse(
450
+ ERROR_CODES.ERR_FILE_EXISTS,
451
+ `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.`,
452
+ {run: ['ls -la themes']},
453
+ );
454
+ }
455
+
174
456
  /**
175
457
  * The themes the editor made in the app (a settings file of its own), by
176
458
  * name, or with `changed` the one an editor command changed last first: the
@@ -183,6 +465,7 @@ export function themeFiles(cwd, slug) {
183
465
  export function editedThemes(cwd, order = 'name') {
184
466
  const root = path.join(cwd, 'themes');
185
467
  if (!fs.existsSync(root)) return [];
468
+ refuseThemesNotFolder(cwd);
186
469
  const names = fs
187
470
  .readdirSync(root)
188
471
  .filter(d => fs.existsSync(themeFiles(cwd, d).settings))
@@ -259,6 +542,29 @@ export function refuse(code, message, extra = {}) {
259
542
  throw new AstryxError(`${message} ${tail}`, suggestions, code);
260
543
  }
261
544
 
545
+ /**
546
+ * A theme name as typed, read the way the editor reads it: a path to its
547
+ * folder or a file in it (t.theme.ts, Brand.settings.json), in any case,
548
+ * names the theme. The result may still need slugFor.
549
+ * @param {unknown} s
550
+ * @returns {string}
551
+ */
552
+ export function typedThemeName(s) {
553
+ return (
554
+ String(s ?? '')
555
+ .trim()
556
+ .toLowerCase()
557
+ // ./t and .\t name the theme t.
558
+ .replace(/^(\.[\\/])+/, '')
559
+ .replace(/^.*themes[\\/]/, '')
560
+ .replace(/[\\/].*$/, '')
561
+ .replace(
562
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|css|js|ts)$/,
563
+ '',
564
+ )
565
+ );
566
+ }
567
+
262
568
  /**
263
569
  * The settings of a theme, or a refusal naming the command that makes it.
264
570
  * @param {string} cwd
@@ -273,19 +579,12 @@ export function loadTheme(
273
579
  slug,
274
580
  skip = /** @type {string | Partial<Setting>} */ (''),
275
581
  ) {
582
+ refuseThemesNotFolder(cwd);
276
583
  if (!slugOk(slug)) {
277
584
  // A path or a capital letter typed for a theme that exists names it.
278
585
  // A file name typed for the theme (t.theme.ts, Brand.settings.json)
279
586
  // 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
- );
587
+ const plain = typedThemeName(slug);
289
588
  const fixed = slugFor(plain);
290
589
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
291
590
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
@@ -309,6 +608,27 @@ export function loadTheme(
309
608
  },
310
609
  );
311
610
  }
611
+ // An empty name (an unset variable, a lone dash): no theme to guess
612
+ // from it, so the themes here are named instead of a new one.
613
+ if (!same && !/[a-z0-9]/i.test(String(slug ?? ''))) {
614
+ const have = fs.existsSync(themeFiles(cwd, 'x').root)
615
+ ? fs
616
+ .readdirSync(themeFiles(cwd, 'x').root)
617
+ .filter(
618
+ d => slugOk(d) && fs.existsSync(themeFiles(cwd, d).settings),
619
+ )
620
+ .sort()
621
+ : [];
622
+ refuse(
623
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
624
+ `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(', ')}.` : ''}`,
625
+ {
626
+ run: have.length
627
+ ? have.slice(0, 3).map(t => `${P} show ${t}`)
628
+ : [`${P} new my-theme`],
629
+ },
630
+ );
631
+ }
312
632
  refuse(
313
633
  ERROR_CODES.ERR_INVALID_ARGUMENT,
314
634
  `"${String(slug ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE}).`,
@@ -348,29 +668,79 @@ export function loadTheme(
348
668
  ERROR_CODES.ERR_UNKNOWN_THEME,
349
669
  stopped
350
670
  ? `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` : ''}.`,
671
+ : `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)` : ''}.`,
352
672
  {run: [`${P} new ${slug}`]},
353
673
  );
674
+ // A folder copied or renamed by hand from an editor theme: its files
675
+ // still carry the old name (t.settings.json in themes/t2).
676
+ const copied =
677
+ !same && fs.existsSync(f.dir)
678
+ ? fs
679
+ .readdirSync(f.dir)
680
+ .map(n => /^(.+)\.settings\.json$/.exec(n)?.[1])
681
+ .find(n => n && n !== slug)
682
+ : undefined;
683
+ if (copied) {
684
+ const files = fs
685
+ .readdirSync(f.dir)
686
+ .filter(n => n.startsWith(`${copied}.`))
687
+ .sort();
688
+ const original = fs.existsSync(themeFiles(cwd, copied).settings);
689
+ refuse(
690
+ ERROR_CODES.ERR_UNKNOWN_THEME,
691
+ `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
692
+ .slice(0, 2)
693
+ .map(n => `${n} to ${slug}${n.slice(copied.length)}`)
694
+ .join(', ')}${files.length > 2 ? ', and so on' : ''})${
695
+ // The theme source names the theme inside it too: every step.
696
+ files.includes(`${copied}.theme.ts`)
697
+ ? `, 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`
698
+ : ''
699
+ }${original ? `; ${copied} itself is still in themes/${copied}` : ''}.`,
700
+ {
701
+ run: original
702
+ ? [`${P} show ${copied}`, `ls -la themes/${slug}`]
703
+ : [`ls -la themes/${slug}`],
704
+ },
705
+ );
706
+ }
354
707
  if (!same && (other || LIKE.includes(slug)))
355
708
  refuse(
356
709
  ERROR_CODES.ERR_UNKNOWN_THEME,
357
710
  `${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
711
  {
359
712
  run: [
360
- `${P} new my-${slug}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
713
+ // The user's own theme on that base, when there is one, then a
714
+ // free valid name for a new one.
715
+ ...(fs.existsSync(themeFiles(cwd, `my-${slug}`).settings)
716
+ ? [`${P} show my-${slug}`]
717
+ : []),
718
+ `${P} new ${usableNewName(cwd, `my-${slug}`)}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
361
719
  ],
362
720
  },
363
721
  );
364
722
  refuse(
365
723
  ERROR_CODES.ERR_UNKNOWN_THEME,
366
724
  `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
- },
725
+ (() => {
726
+ const near = same ? [same] : nearest(slug, have);
727
+ // A theme near the name comes first; a new theme of the name as
728
+ // typed only after.
729
+ return {
730
+ didYouMean: near,
731
+ run: same
732
+ ? [`${P} show ${same}`]
733
+ : near.length
734
+ ? [`${P} show ${near[0]}`, `${P} new ${slug}`]
735
+ : [`${P} new ${slug}`],
736
+ };
737
+ })(),
371
738
  );
372
739
  }
373
740
  refuseLinks(cwd, slug);
741
+ // A file of the theme that is a folder or cannot be read is named, never
742
+ // called damaged.
743
+ refuseUnreadableFiles(cwd, slug);
374
744
  // undo is offered only when there is a step to go back to.
375
745
  const steps = readHistory(f.history).steps.length;
376
746
  const recover = steps
@@ -472,22 +842,73 @@ export function loadTheme(
472
842
  );
473
843
  }
474
844
  // A bad mode or base is fixed by setting it.
845
+ // A value written in other letters (Dark-Only, Neutral) is the one meant.
846
+ const modeMeant = String(data?.mode ?? '')
847
+ .trim()
848
+ .toLowerCase();
849
+ const likeMeant = String(data?.like ?? '')
850
+ .trim()
851
+ .toLowerCase();
475
852
  const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
476
- ? `${P} set ${slug} mode both`
853
+ ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
477
854
  : /^base "/.test(problem ?? '')
478
- ? `${P} set ${slug} base none`
855
+ ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : 'none'}`
479
856
  : null;
857
+ // A setting listed twice: setting it to one of its values, or undoing
858
+ // it, keeps one entry or none.
859
+ const twice = problem?.includes(' is listed twice (')
860
+ ? duplicated(data)
861
+ : null;
480
862
  if (problem)
481
863
  throw new AstryxError(
482
- `themes/${slug}/${slug}.settings.json: ${problem}. ${fieldFix ? 'Set it again' : `Fix it by hand${recover.text}`}. Nothing was changed.`,
864
+ `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
865
  fieldFix
484
866
  ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
485
- : recover.run,
867
+ : twice
868
+ ? [
869
+ ...twice.values
870
+ .filter(
871
+ v =>
872
+ typeof v === 'string' &&
873
+ !valueProblem({...twice.setting, value: v}),
874
+ )
875
+ .slice(0, 2)
876
+ .map(v => ({
877
+ name: `${P} set ${slug} ${undoArgs(twice.setting).replace(twice.setting.thing, `${twice.setting.thing} ${quoteCommandArgument(String(v))}`)}`,
878
+ reason: `keep ${v}`,
879
+ })),
880
+ {
881
+ name: `${P} undo ${slug} ${undoArgs(twice.setting)}`,
882
+ reason: 'remove both',
883
+ },
884
+ ...recover.run,
885
+ ]
886
+ : recover.run,
486
887
  ERROR_CODES.ERR_THEME_INVALID,
487
888
  );
488
889
  return data;
489
890
  }
490
891
 
892
+ /**
893
+ * The first setting listed more than once, with every value it is listed
894
+ * with, in order.
895
+ * @param {any} data
896
+ * @returns {{setting: any, values: unknown[]} | null}
897
+ */
898
+ function duplicated(data) {
899
+ /** @type {Map<string, any[]>} */
900
+ const byKey = new Map();
901
+ for (const s of data.settings ?? []) {
902
+ if (!s || typeof s.thing !== 'string') continue;
903
+ const key = keyOf(s);
904
+ byKey.set(key, [...(byKey.get(key) ?? []), s]);
905
+ }
906
+ for (const list of byKey.values())
907
+ if (list.length > 1)
908
+ return {setting: list[0], values: [...new Set(list.map(x => x.value))]};
909
+ return null;
910
+ }
911
+
491
912
  /**
492
913
  * What is wrong with settings data, or null: its shape, and each value with
493
914
  * the same rules `set` checks it by (without the installed Core), so a value
@@ -513,7 +934,15 @@ export function settingsProblem(
513
934
  if (!field && data.like != null && !LIKE.includes(data.like))
514
935
  return `base "${data.like}" is not a built-in theme (${LIKE.join(', ')})`;
515
936
  if (!Array.isArray(data.settings)) return 'settings is not a list';
516
- const keys = new Set();
937
+ // `lifted` is written by the build: a list of text, or absent.
938
+ if (
939
+ data.lifted != null &&
940
+ (!Array.isArray(data.lifted) ||
941
+ data.lifted.some((/** @type {unknown} */ x) => typeof x !== 'string'))
942
+ )
943
+ 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)`;
944
+ /** @type {Map<string, any>} */
945
+ const keys = new Map();
517
946
  for (const s of data.settings) {
518
947
  // A value or scope that is not text is a bad setting `undo` removes;
519
948
  // a setting with no name is damage.
@@ -524,8 +953,11 @@ export function settingsProblem(
524
953
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
525
954
  return `${s.thing} has mode "${s.mode}"`;
526
955
  const key = keyOf(s);
527
- if (keys.has(key)) return `${describe(s)} is listed twice`;
528
- keys.add(key);
956
+ // The command that changes or removes a setting listed twice keeps one
957
+ // value, or none, so it fixes the list.
958
+ if (keys.has(key) && !skips(s, skip))
959
+ return `${describe({...s, value: '?'}).replace(' = ?', '')} is listed twice (${JSON.stringify(keys.get(key).value)}, ${JSON.stringify(s.value)})`;
960
+ keys.set(key, s);
529
961
  if (skips(s, skip)) continue;
530
962
  const problem = valueProblem(s);
531
963
  if (problem) return problem;
@@ -636,6 +1068,12 @@ export function valueProblem(s) {
636
1068
  if (s.source !== 'dial') return null;
637
1069
  const d = DIALS[s.thing];
638
1070
  if (!d) return `${s.thing} is not a dial`;
1071
+ // A color dial needs a fixed opaque seed, as `set` checks it: a
1072
+ // see-through, system or variable color generates no shades.
1073
+ if (PALETTE_DIALS.includes(s.thing) && isColorValue(s.value)) {
1074
+ const seed = colorProblem(s.value);
1075
+ if (seed) return `${bad} ${seed.message}`;
1076
+ }
639
1077
  const words = d.values.split('|').filter(w => !w.startsWith('<'));
640
1078
  const ok =
641
1079
  s.thing === 'corners'
@@ -658,6 +1096,637 @@ export function valueProblem(s) {
658
1096
  return null;
659
1097
  }
660
1098
 
1099
+ /**
1100
+ * The page-wide tokens a theme's own source sets: the keys of the top-level
1101
+ * `tokens` map in its `defineTheme({...})`, read from the syntax tree, each
1102
+ * with its value when that is plain text (else null). A token set only in a
1103
+ * scope (`onDark`, `components`) is not one: it does not apply page-wide.
1104
+ * @param {string} cwd
1105
+ * @param {string} slug
1106
+ * @returns {Map<string, string | null>}
1107
+ */
1108
+ function ownPageTokens(cwd, slug) {
1109
+ /** @type {Map<string, string | null>} */
1110
+ const out = new Map();
1111
+ /** @type {string} */
1112
+ let code;
1113
+ try {
1114
+ code = fs.readFileSync(themeFiles(cwd, slug).ts, 'utf8');
1115
+ } catch {
1116
+ return out;
1117
+ }
1118
+ /** @type {any} */
1119
+ let ast;
1120
+ try {
1121
+ ast = parseModule(code, {sourceType: 'module', plugins: ['typescript']});
1122
+ } catch {
1123
+ return out;
1124
+ }
1125
+ /** @param {any} node @returns {string | null} */
1126
+ const keyOf = node =>
1127
+ node?.type === 'StringLiteral'
1128
+ ? node.value
1129
+ : node?.type === 'Identifier'
1130
+ ? node.name
1131
+ : null;
1132
+ /** @param {any} node @returns {string | null} */
1133
+ const textOf = node =>
1134
+ node?.type === 'StringLiteral'
1135
+ ? node.value
1136
+ : node?.type === 'TemplateLiteral' && node.expressions.length === 0
1137
+ ? node.quasis.map((/** @type {any} */ q) => q.value.cooked).join('')
1138
+ : null;
1139
+ // Every const binding in the file, by name, so a value given by name
1140
+ // (tokens: mine, ...mine) is read as written.
1141
+ /** @type {Map<string, any>} */
1142
+ const consts = new Map();
1143
+ /** @type {any[]} */
1144
+ const calls = [];
1145
+ /** @param {any} node @param {any} owner the exported name, when exported */
1146
+ const visit = (node, owner = null) => {
1147
+ if (!node || typeof node !== 'object') return;
1148
+ if (node.type === 'VariableDeclarator' && node.id?.type === 'Identifier')
1149
+ consts.set(node.id.name, node.init);
1150
+ if (
1151
+ node.type === 'CallExpression' &&
1152
+ node.callee?.type === 'Identifier' &&
1153
+ node.callee.name === 'defineTheme' &&
1154
+ node.arguments?.[0]
1155
+ )
1156
+ calls.push({call: node, owner});
1157
+ for (const [k, v] of Object.entries(node)) {
1158
+ const nextOwner =
1159
+ node.type === 'VariableDeclarator' && k === 'init'
1160
+ ? (node.id?.name ?? owner)
1161
+ : node.type === 'ExportDefaultDeclaration'
1162
+ ? 'default'
1163
+ : owner;
1164
+ if (Array.isArray(v)) v.forEach(c => visit(c, nextOwner));
1165
+ else if (v && typeof v === 'object' && v.type) visit(v, nextOwner);
1166
+ }
1167
+ };
1168
+ visit(ast.program);
1169
+ /** @param {any} node @param {number} [depth] @returns {any} */
1170
+ const unwrap = (node, depth = 0) => {
1171
+ if (!node || depth > 20) return null;
1172
+ if (
1173
+ [
1174
+ 'TSAsExpression',
1175
+ 'TSSatisfiesExpression',
1176
+ 'TSNonNullExpression',
1177
+ 'TSTypeAssertion',
1178
+ 'ParenthesizedExpression',
1179
+ ].includes(node.type)
1180
+ )
1181
+ return unwrap(node.expression, depth + 1);
1182
+ if (node.type === 'Identifier' && consts.has(node.name))
1183
+ return unwrap(consts.get(node.name), depth + 1);
1184
+ return node;
1185
+ };
1186
+ // The theme the build loads: the defineTheme that names it, else the one
1187
+ // exported as <camel>Theme or by default, else the only one.
1188
+ const named = calls.find(({call}) => {
1189
+ const obj = unwrap(call.arguments[0]);
1190
+ return (
1191
+ obj?.type === 'ObjectExpression' &&
1192
+ obj.properties.some(
1193
+ (/** @type {any} */ p) =>
1194
+ p.type === 'ObjectProperty' &&
1195
+ keyOf(p.key) === 'name' &&
1196
+ textOf(unwrap(p.value)) === slug,
1197
+ )
1198
+ );
1199
+ });
1200
+ const chosen =
1201
+ named ??
1202
+ calls.find(
1203
+ c => c.owner === `${camel(slug)}Theme` || c.owner === 'default',
1204
+ ) ??
1205
+ (calls.length === 1 ? calls[0] : null);
1206
+ if (!chosen) return out;
1207
+ const def = unwrap(chosen.call.arguments[0]);
1208
+ if (def?.type !== 'ObjectExpression') return out;
1209
+ const tokensProp = def.properties.find(
1210
+ (/** @type {any} */ p) =>
1211
+ p.type === 'ObjectProperty' && !p.computed && keyOf(p.key) === 'tokens',
1212
+ );
1213
+ if (!tokensProp) return out;
1214
+ let unresolved = false;
1215
+ /** @param {any} node @param {number} depth */
1216
+ const collect = (node, depth) => {
1217
+ const obj = unwrap(node);
1218
+ if (obj?.type !== 'ObjectExpression' || depth > 20) {
1219
+ unresolved = true;
1220
+ return;
1221
+ }
1222
+ // Spreads and keys merge in order: a later one wins.
1223
+ for (const p of obj.properties) {
1224
+ if (p.type === 'SpreadElement') collect(p.argument, depth + 1);
1225
+ else if (p.type === 'ObjectProperty' && !p.computed) {
1226
+ const k = keyOf(p.key);
1227
+ if (k?.startsWith('--')) out.set(k, textOf(unwrap(p.value)));
1228
+ } else unresolved = true;
1229
+ }
1230
+ };
1231
+ collect(tokensProp.value, 0);
1232
+ // A value no read of the file can resolve (a call, an import) is read
1233
+ // from the build (ownTokens), and checked again after the next one.
1234
+ void unresolved;
1235
+ return out;
1236
+ }
1237
+
1238
+ /**
1239
+ * The var() loops among a theme's built top-level tokens, each with a key
1240
+ * that names it whatever token it starts from.
1241
+ * @param {string} cwd
1242
+ * @param {string} slug
1243
+ * @returns {Array<{key: string, path: string[], part?: string}>}
1244
+ */
1245
+ function builtLoops(cwd, slug) {
1246
+ const tokens = builtTopTokens(cwd, slug);
1247
+ /** @param {string} t */
1248
+ const refs = t =>
1249
+ [...String(tokens.get(t) ?? '').matchAll(/var\(\s*(--[a-z0-9-]+)/gi)].map(
1250
+ m => m[1],
1251
+ );
1252
+ /** @type {Array<{key: string, path: string[], part?: string}>} */
1253
+ const loops = [];
1254
+ const seen = new Set();
1255
+ for (const start of tokens.keys()) {
1256
+ /** @type {string[]} */
1257
+ const path = [];
1258
+ /** @param {string} t @returns {boolean} */
1259
+ const walk = t => {
1260
+ const at = path.indexOf(t);
1261
+ if (at >= 0) {
1262
+ const cycle = path.slice(at);
1263
+ const key = [...cycle].sort().join(' ');
1264
+ if (!seen.has(key)) {
1265
+ seen.add(key);
1266
+ loops.push({key, path: [...cycle, t]});
1267
+ }
1268
+ return true;
1269
+ }
1270
+ if (!tokens.has(t) || path.length > 50) return false;
1271
+ path.push(t);
1272
+ for (const r of refs(t)) if (walk(r)) return true;
1273
+ path.pop();
1274
+ return false;
1275
+ };
1276
+ walk(start);
1277
+ }
1278
+ // Inside one part: a part's own token reads the part's other own tokens
1279
+ // first, and a whole-theme one only as already resolved, so a loop there
1280
+ // closes among the part's own tokens.
1281
+ const js = themeFiles(cwd, slug).js;
1282
+ for (const part of blockKeys(js, ['components'])) {
1283
+ const plain = blockOf(js, ['components', part, 'base']);
1284
+ // Each state or variant rule of the part also has its plain rule.
1285
+ for (const scope of blockKeys(js, ['components', part])) {
1286
+ const own =
1287
+ scope === 'base' ? plain : blockOf(js, ['components', part, scope]);
1288
+ const block = new Map([...plain, ...own]);
1289
+ const where = scope === 'base' ? part : `${part} ${scope}`;
1290
+ for (const start of own.keys()) {
1291
+ if (!start.startsWith('--')) continue;
1292
+ /** @type {string[]} */
1293
+ const path = [];
1294
+ /** @param {string} t @returns {boolean} */
1295
+ const walk = t => {
1296
+ const at = path.indexOf(t);
1297
+ if (at >= 0) {
1298
+ const cycle = path.slice(at);
1299
+ const key = `${where}: ${[...cycle].sort().join(' ')}`;
1300
+ if (!seen.has(key)) {
1301
+ seen.add(key);
1302
+ loops.push({key, path: [...cycle, t], part: where});
1303
+ }
1304
+ return true;
1305
+ }
1306
+ if (!block.has(t) || path.length > 50) return false;
1307
+ path.push(t);
1308
+ for (const m of String(block.get(t) ?? '').matchAll(
1309
+ /var\(\s*(--[a-z0-9-]+)/gi,
1310
+ ))
1311
+ if (walk(m[1])) return true;
1312
+ path.pop();
1313
+ return false;
1314
+ };
1315
+ walk(start);
1316
+ }
1317
+ }
1318
+ }
1319
+ return loops;
1320
+ }
1321
+
1322
+ /**
1323
+ * The keys of one object in a built theme module (see blockOf).
1324
+ * @param {string} file
1325
+ * @param {string[]} keys
1326
+ * @returns {string[]}
1327
+ */
1328
+ function blockKeys(file, keys) {
1329
+ return [...blockOf(file, keys).keys()];
1330
+ }
1331
+
1332
+ /**
1333
+ * The top-level tokens of a theme's built module (<slug>.js), which the
1334
+ * build wrote as plain data, or an empty map.
1335
+ * @param {string} cwd
1336
+ * @param {string} slug
1337
+ * @returns {Map<string, string | null>}
1338
+ */
1339
+ function builtTopTokens(cwd, slug) {
1340
+ return topTokensOf(themeFiles(cwd, slug).js);
1341
+ }
1342
+
1343
+ /**
1344
+ * The tokens a base theme's own component rules for a part read through
1345
+ * var() (neutral's progress-bar reads --color-border-emphasized), from its
1346
+ * built module; an empty set when it is not installed.
1347
+ * @param {string} cwd
1348
+ * @param {string | null | undefined} like
1349
+ * @param {string} target
1350
+ * @returns {Set<string>}
1351
+ */
1352
+ export function baseComponentReads(cwd, like, target) {
1353
+ /** @type {Set<string>} */
1354
+ const out = new Set();
1355
+ const file = like ? baseModule(cwd, like) : null;
1356
+ if (!file) return out;
1357
+ try {
1358
+ const ast = /** @type {any} */ (
1359
+ parseModule(fs.readFileSync(file, 'utf8'), {sourceType: 'module'})
1360
+ );
1361
+ /** @param {any} node */
1362
+ const visit = node => {
1363
+ if (!node || typeof node !== 'object') return;
1364
+ if (
1365
+ node.type === 'ObjectProperty' &&
1366
+ (node.key?.name ?? node.key?.value) === 'components' &&
1367
+ node.value?.type === 'ObjectExpression'
1368
+ ) {
1369
+ const part = node.value.properties.find(
1370
+ (/** @type {any} */ p) => (p.key?.value ?? p.key?.name) === target,
1371
+ );
1372
+ if (part) {
1373
+ const text = JSON.stringify(part.value);
1374
+ for (const m of text.matchAll(/var\(\s*(--[a-z0-9-]+)/gi))
1375
+ out.add(m[1]);
1376
+ }
1377
+ return;
1378
+ }
1379
+ for (const v of Object.values(node))
1380
+ if (Array.isArray(v)) v.forEach(visit);
1381
+ else if (v && typeof v === 'object' && v.type) visit(v);
1382
+ };
1383
+ visit(ast.program);
1384
+ } catch {
1385
+ // Not one this reads.
1386
+ }
1387
+ return out;
1388
+ }
1389
+
1390
+ /**
1391
+ * The top-level tokens a base theme's built module gives (what the
1392
+ * editor's settings extend), or an empty map when it is not installed.
1393
+ * @param {string} cwd
1394
+ * @param {string | null | undefined} like
1395
+ * @returns {Map<string, string | null>}
1396
+ */
1397
+ export function baseTopTokens(cwd, like) {
1398
+ const file = like ? baseModule(cwd, like) : null;
1399
+ return file ? topTokensOf(file) : new Map();
1400
+ }
1401
+
1402
+ /**
1403
+ * The top-level tokens of a built theme module (plain data the build
1404
+ * wrote), or an empty map.
1405
+ * @param {string} file
1406
+ * @returns {Map<string, string | null>}
1407
+ */
1408
+ function topTokensOf(file) {
1409
+ /** @type {Map<string, string | null>} */
1410
+ const out = new Map();
1411
+ for (const [k, v] of blockOf(file, ['tokens']))
1412
+ if (k.startsWith('--')) out.set(k, v);
1413
+ return out;
1414
+ }
1415
+
1416
+ /**
1417
+ * One block of a built theme module (plain data the build wrote), by its
1418
+ * path from the theme object (`['tokens']`, `['components', 'card',
1419
+ * 'base']`): every key with its text value, a [light, dark] pair as the
1420
+ * build writes it, else null. An empty map when it is not there.
1421
+ * @param {string} file
1422
+ * @param {string[]} keys
1423
+ * @returns {Map<string, string | null>}
1424
+ */
1425
+ function blockOf(file, keys) {
1426
+ /** @type {Map<string, string | null>} */
1427
+ const out = new Map();
1428
+ try {
1429
+ const ast = /** @type {any} */ (
1430
+ parseModule(fs.readFileSync(file, 'utf8'), {
1431
+ sourceType: 'module',
1432
+ plugins: ['typescript'],
1433
+ })
1434
+ );
1435
+ for (const st of ast.program.body) {
1436
+ const decl = st.declaration?.declarations?.[0];
1437
+ /** @type {any} */
1438
+ let obj = decl?.init;
1439
+ // The generated settings module: defineTheme({...}).
1440
+ if (obj?.type === 'CallExpression') obj = obj.arguments?.[0];
1441
+ for (const key of keys)
1442
+ obj =
1443
+ obj?.type === 'ObjectExpression'
1444
+ ? obj.properties.find(
1445
+ (/** @type {any} */ p) => (p.key?.name ?? p.key?.value) === key,
1446
+ )?.value
1447
+ : undefined;
1448
+ if (obj?.type !== 'ObjectExpression') continue;
1449
+ for (const p of obj.properties) {
1450
+ const k = p.key?.value ?? p.key?.name;
1451
+ if (typeof k === 'string')
1452
+ out.set(
1453
+ k,
1454
+ p.value?.type === 'StringLiteral'
1455
+ ? p.value.value
1456
+ : // A [light, dark] pair, as the build writes it.
1457
+ p.value?.type === 'ArrayExpression' &&
1458
+ p.value.elements.length === 2 &&
1459
+ p.value.elements.every(
1460
+ (/** @type {any} */ e) => e?.type === 'StringLiteral',
1461
+ )
1462
+ ? `light-dark(${p.value.elements.map((/** @type {any} */ e) => e.value).join(', ')})`
1463
+ : null,
1464
+ );
1465
+ }
1466
+ if (out.size) break;
1467
+ }
1468
+ } catch {
1469
+ // No build yet, or not one this reads.
1470
+ }
1471
+ return out;
1472
+ }
1473
+
1474
+ /**
1475
+ * What a part's plain rule (its `base` block) holds in the theme as built
1476
+ * (the base theme's, the settings' and the own source's together), else in
1477
+ * the base theme alone when there is no build: tokens and properties by
1478
+ * name. Kebab-case property names, as the editor names them.
1479
+ * @param {string} cwd
1480
+ * @param {string} slug
1481
+ * @param {string | null | undefined} like
1482
+ * @param {string} part
1483
+ * @returns {Map<string, string | null>}
1484
+ */
1485
+ export function partRuleTokens(cwd, slug, like, part) {
1486
+ const built = blockOf(themeFiles(cwd, slug).js, ['components', part, 'base']);
1487
+ const baseFile = like ? baseModule(cwd, like) : null;
1488
+ const base = baseFile
1489
+ ? blockOf(baseFile, ['components', part, 'base'])
1490
+ : new Map();
1491
+ /** @type {Map<string, string | null>} */
1492
+ const out = new Map();
1493
+ for (const m of [base, built])
1494
+ for (const [k, v] of m)
1495
+ out.set(
1496
+ k.startsWith('--')
1497
+ ? k
1498
+ : k.replace(
1499
+ /[A-Z]/g,
1500
+ (/** @type {string} */ c) => `-${c.toLowerCase()}`,
1501
+ ),
1502
+ v,
1503
+ );
1504
+ return out;
1505
+ }
1506
+
1507
+ /**
1508
+ * The tokens and properties a theme's own source sets on a part's plain
1509
+ * rule, read from the build as ownTokens reads page-wide ones: what the
1510
+ * built rule holds that the settings module and the base theme do not give
1511
+ * as they are, and that the person's files name.
1512
+ * @param {string} cwd
1513
+ * @param {string} slug
1514
+ * @param {string} part
1515
+ * @param {string} [scope] the rule: `base` (the plain one), or a variant
1516
+ * such as `variant:primary`
1517
+ * @returns {Map<string, string | null>}
1518
+ */
1519
+ export function ownPartTokens(cwd, slug, part, scope = 'base') {
1520
+ /** @type {Map<string, string | null>} */
1521
+ const out = new Map();
1522
+ const f = themeFiles(cwd, slug);
1523
+ /** @type {string} */
1524
+ let module;
1525
+ try {
1526
+ module = fs.readFileSync(f.settingsTs, 'utf8');
1527
+ } catch {
1528
+ return out;
1529
+ }
1530
+ const stamp = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1531
+ module,
1532
+ )?.[1];
1533
+ if (!stamp || stamp !== themeSourceHash(cwd, slug)) return out;
1534
+ const like = /\/\/ Built on @astryxdesign\/theme-([a-z0-9-]+) /.exec(
1535
+ module,
1536
+ )?.[1];
1537
+ const baseFile = like ? baseModule(cwd, like) : null;
1538
+ const base = baseFile
1539
+ ? blockOf(baseFile, ['components', part, scope])
1540
+ : new Map();
1541
+ const settings = blockOf(f.settingsTs, ['components', part, scope]);
1542
+ const named = namedInOwnSource(cwd, slug);
1543
+ for (const [k, v] of blockOf(f.js, ['components', part, scope])) {
1544
+ const given = settings.has(k) ? settings.get(k) : base.get(k);
1545
+ if (given !== v && named(k))
1546
+ out.set(
1547
+ k.startsWith('--')
1548
+ ? k
1549
+ : k.replace(
1550
+ /[A-Z]/g,
1551
+ (/** @type {string} */ c) => `-${c.toLowerCase()}`,
1552
+ ),
1553
+ v,
1554
+ );
1555
+ }
1556
+ return out;
1557
+ }
1558
+
1559
+ /**
1560
+ * The page-wide tokens the theme's own source sets, read from what the
1561
+ * build made of it: the built module's top-level tokens that the
1562
+ * generated settings module does not give as they are (the own source wins
1563
+ * over the settings it extends). The build evaluates the file, so any way
1564
+ * of writing it counts (a namespace import, a renamed defineTheme, a
1565
+ * template, a spread of a shared object). Only a build made from the
1566
+ * source as it is now is read; with none, the file is read as written.
1567
+ * Both are joined: a key either names is the source's.
1568
+ * @param {string} cwd
1569
+ * @param {string} slug
1570
+ * @returns {Map<string, string | null>}
1571
+ */
1572
+ function ownTokens(cwd, slug) {
1573
+ const out = new Map(ownPageTokens(cwd, slug));
1574
+ const fromBuild = builtOwnTokens(cwd, slug);
1575
+ if (fromBuild) for (const [k, v] of fromBuild) out.set(k, v);
1576
+ return out;
1577
+ }
1578
+
1579
+ /**
1580
+ * The tokens the own source sets, as the current build shows them, or null
1581
+ * when there is no build made from the source as it is now.
1582
+ * @param {string} cwd
1583
+ * @param {string} slug
1584
+ * @returns {Map<string, string | null> | null}
1585
+ */
1586
+ function builtOwnTokens(cwd, slug) {
1587
+ const f = themeFiles(cwd, slug);
1588
+ /** @type {string} */
1589
+ let module;
1590
+ try {
1591
+ module = fs.readFileSync(f.settingsTs, 'utf8');
1592
+ } catch {
1593
+ return null;
1594
+ }
1595
+ const built = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(
1596
+ module,
1597
+ )?.[1];
1598
+ if (!built || !fs.existsSync(f.js) || built !== themeSourceHash(cwd, slug))
1599
+ return null;
1600
+ // What the settings module gives each top-level token: a text value as
1601
+ // it is, a [light, dark] pair as a pair.
1602
+ /** @type {Map<string, string | 'pair' | 'other'>} */
1603
+ const settings = new Map();
1604
+ try {
1605
+ const ast = /** @type {any} */ (
1606
+ parseModule(module, {sourceType: 'module', plugins: ['typescript']})
1607
+ );
1608
+ /** @param {any} node */
1609
+ const visit = node => {
1610
+ if (!node || typeof node !== 'object') return;
1611
+ if (
1612
+ node.type === 'CallExpression' &&
1613
+ node.callee?.name === 'defineTheme' &&
1614
+ node.arguments?.[0]?.type === 'ObjectExpression'
1615
+ ) {
1616
+ const tokens = node.arguments[0].properties.find(
1617
+ (/** @type {any} */ p) =>
1618
+ (p.key?.value ?? p.key?.name) === 'tokens' &&
1619
+ p.value?.type === 'ObjectExpression',
1620
+ );
1621
+ for (const p of tokens?.value.properties ?? []) {
1622
+ const k = p.key?.value ?? p.key?.name;
1623
+ if (typeof k !== 'string') continue;
1624
+ settings.set(
1625
+ k,
1626
+ p.value?.type === 'StringLiteral'
1627
+ ? p.value.value
1628
+ : p.value?.type === 'ArrayExpression'
1629
+ ? 'pair'
1630
+ : 'other',
1631
+ );
1632
+ }
1633
+ return;
1634
+ }
1635
+ for (const v of Object.values(node))
1636
+ if (Array.isArray(v)) v.forEach(visit);
1637
+ else if (v && typeof v === 'object' && v.type) visit(v);
1638
+ };
1639
+ visit(ast.program);
1640
+ } catch {
1641
+ return null;
1642
+ }
1643
+ // What the base theme's built module gives: the tokens the settings
1644
+ // extend, which are no more the source's than the settings' are.
1645
+ const like = /\/\/ Built on @astryxdesign\/theme-([a-z0-9-]+) /.exec(
1646
+ module,
1647
+ )?.[1];
1648
+ const baseFile = like ? baseModule(cwd, like) : null;
1649
+ const base = baseFile ? topTokensOf(baseFile) : new Map();
1650
+ const named = namedInOwnSource(cwd, slug);
1651
+ /** @type {Map<string, string | null>} */
1652
+ const out = new Map();
1653
+ for (const [k, v] of builtTopTokens(cwd, slug)) {
1654
+ const given = settings.get(k);
1655
+ const own =
1656
+ given === undefined
1657
+ ? !base.has(k) || base.get(k) !== v
1658
+ : given === 'pair'
1659
+ ? !/^light-dark\(/.test(String(v ?? ''))
1660
+ : given !== 'other' && given !== v;
1661
+ if (own && named(k)) out.set(k, v);
1662
+ }
1663
+ return out;
1664
+ }
1665
+
1666
+ /**
1667
+ * Whether a token or property name appears in the person's theme files: a
1668
+ * value the build shows that no file of theirs names came from the
1669
+ * settings (a dial's typography, a lifted value), not from them.
1670
+ * @param {string} cwd
1671
+ * @param {string} slug
1672
+ * @returns {(name: string) => boolean}
1673
+ */
1674
+ function namedInOwnSource(cwd, slug) {
1675
+ const text = ownSourceFiles(cwd, slug)
1676
+ .map(file => {
1677
+ try {
1678
+ return fs.readFileSync(file, 'utf8');
1679
+ } catch {
1680
+ return '';
1681
+ }
1682
+ })
1683
+ .join('\n');
1684
+ // A font set through `typography` (heading: {family: ...}) names its
1685
+ // role there, not the token the build writes for it.
1686
+ const typography = /\btypography\b/.test(text);
1687
+ return name =>
1688
+ text.includes(name) ||
1689
+ (typography &&
1690
+ (/^--font-family-([a-z]+)$/.exec(name)?.[1] ?? '') !== '' &&
1691
+ text.includes(
1692
+ /** @type {string[]} */ (/^--font-family-([a-z]+)$/.exec(name))[1],
1693
+ )) ||
1694
+ (typography &&
1695
+ /^--text-([a-z]+)-\d*-?weight$/.test(name) &&
1696
+ text.includes(
1697
+ /** @type {string[]} */ (/^--text-([a-z]+)/.exec(name))[1],
1698
+ ) &&
1699
+ /weight/.test(text)) ||
1700
+ // A property may be written camelCase (borderRadius).
1701
+ (!name.startsWith('--') &&
1702
+ text.includes(name.replace(/-([a-z])/g, (_, c) => c.toUpperCase())));
1703
+ }
1704
+
1705
+ /**
1706
+ * The page-wide tokens a theme's own source sets itself (see ownTokens):
1707
+ * they win over the settings it extends.
1708
+ * @param {string} cwd
1709
+ * @param {string} slug
1710
+ * @returns {string[]}
1711
+ */
1712
+ export function ownSourceTokens(cwd, slug) {
1713
+ return [...ownTokens(cwd, slug).keys()];
1714
+ }
1715
+
1716
+ /**
1717
+ * The values a theme's own source gives page-wide tokens as plain text, by
1718
+ * token (see ownTokens).
1719
+ * @param {string} cwd
1720
+ * @param {string} slug
1721
+ * @returns {Record<string, string>}
1722
+ */
1723
+ export function ownSourceTokenValues(cwd, slug) {
1724
+ /** @type {Record<string, string>} */
1725
+ const out = {};
1726
+ for (const [k, v] of ownTokens(cwd, slug)) if (v != null) out[k] = v;
1727
+ return out;
1728
+ }
1729
+
661
1730
  /**
662
1731
  * What is wrong with where a setting applies, or null: names only, as
663
1732
  * `set` takes them.
@@ -723,7 +1792,11 @@ export {modesOf};
723
1792
  * @returns {number | null}
724
1793
  */
725
1794
  export function lengthPx(v) {
726
- const m = /^\s*(-?\d+(?:\.\d+)?|-?\.\d+)\s*(px|rem|em)?\s*$/i.exec(String(v));
1795
+ // A CSS number: a sign, digits with or without a fraction, an exponent.
1796
+ const m =
1797
+ /^\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)\s*(px|rem|em)?\s*$/i.exec(
1798
+ String(v),
1799
+ );
727
1800
  if (!m) return null;
728
1801
  const n = Number(m[1]);
729
1802
  return (m[2] ?? 'px').toLowerCase() === 'px' ? n : n * 16;
@@ -768,7 +1841,8 @@ export function fontOf(value) {
768
1841
  .split(',')
769
1842
  .map(x => x.trim())
770
1843
  .filter(Boolean);
771
- const family = unquote(parts[0] ?? v);
1844
+ // Runs of spaces or tabs inside a family name are one space.
1845
+ const family = familySpaces(unquote(parts[0] ?? v)).trim();
772
1846
  return {
773
1847
  family: cssFamily(family),
774
1848
  fallbacks:
@@ -779,6 +1853,19 @@ export function fontOf(value) {
779
1853
  };
780
1854
  }
781
1855
 
1856
+ /**
1857
+ * Spacing in a font family name as CSS reads a bare name: every Unicode
1858
+ * space (a no-break space, a thin space, a tab) is one space, a run of them
1859
+ * one, and zero-width and format characters (zero-width space, joiners,
1860
+ * word joiner, byte-order mark) are dropped.
1861
+ * @param {string} v
1862
+ */
1863
+ export function familySpaces(v) {
1864
+ return v
1865
+ .replace(/[\u200B-\u200D\u2060\uFEFF]/g, '')
1866
+ .replace(/[\s\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g, ' ');
1867
+ }
1868
+
782
1869
  /**
783
1870
  * A font family name as CSS reads it. A name that is a sequence of CSS
784
1871
  * identifiers stays bare; any other is quoted, or the browser drops the
@@ -789,6 +1876,7 @@ export function fontOf(value) {
789
1876
  * @param {boolean} [spaced]
790
1877
  */
791
1878
  export function cssFamily(name, spaced = false) {
1879
+ name = familySpaces(name);
792
1880
  const words = name.trim().split(/\s+/);
793
1881
  const ident = (/** @type {string} */ w) =>
794
1882
  /^-?(?:[A-Za-z_]|[\u0080-\uffff])(?:[\w-]|[\u0080-\uffff])*$/.test(w) &&
@@ -849,6 +1937,42 @@ function sealModule(text) {
849
1937
  );
850
1938
  }
851
1939
 
1940
+ /**
1941
+ * The staleness reason for an own source changed since the editor's build.
1942
+ * @param {string} slug
1943
+ */
1944
+ export function sourceChangedReason(slug) {
1945
+ return `${slug}.theme.ts or a module it imports changed since the last build`;
1946
+ }
1947
+
1948
+ /** The type tokens base themes set again for phones: families and weights. */
1949
+ export const PHONE_TYPE = /^--font-family|^--(text-[a-z0-9-]+|font)-weight/;
1950
+
1951
+ /**
1952
+ * Record in an editor theme's generated settings that they were built with
1953
+ * its own source as it is now, after `compile` built that source (the
1954
+ * settings do not depend on what the source sets), only in a module as the
1955
+ * editor wrote it.
1956
+ * @param {string} cwd
1957
+ * @param {string} slug
1958
+ * @returns {boolean} whether it was recorded
1959
+ */
1960
+ export function refreshSourceStamp(cwd, slug) {
1961
+ const f = themeFiles(cwd, slug);
1962
+ const ts = fs.readFileSync(f.settingsTs, 'utf8');
1963
+ if (moduleUnedited(ts) !== true) return false;
1964
+ const stamp = /\/\/ Built with (\S+\.theme\.ts) ([0-9a-f]{16})\./.exec(ts);
1965
+ if (!stamp) return false;
1966
+ const now = themeSourceHash(cwd, slug);
1967
+ if (stamp[2] === now) return true;
1968
+ const text = ts
1969
+ .replace(/\r\n/g, '\n')
1970
+ .replace(SEAL, '')
1971
+ .replace(stamp[0], `// Built with ${stamp[1]} ${now}.`);
1972
+ fs.writeFileSync(f.settingsTs, sealModule(text));
1973
+ return true;
1974
+ }
1975
+
852
1976
  /**
853
1977
  * Whether a generated module is as the editor wrote it: true, false for a
854
1978
  * hand edit, null for a module with no hash (an earlier editor's).
@@ -1000,10 +2124,543 @@ export function compileTheme(ctx, data, base) {
1000
2124
  if (tg?.states.includes(s.state) && s.when == null) b = t[s.state] ??= {};
1001
2125
  else if (tg?.states.includes(s.state))
1002
2126
  b = t[`${s.when}+${s.state}`] ??= {};
1003
- else b = b[stateKey(s.state)] ??= {};
2127
+ else b = b[stateKey(s.state, wrapsOneControl(ctx, target))] ??= {};
1004
2128
  }
1005
2129
  return b;
1006
2130
  };
2131
+ /**
2132
+ * A padding on a part whose padding Core writes one variable per side
2133
+ * (its derivedVarRegistry's container expansion), as each side's value,
2134
+ * split at top-level spaces by the CSS shorthand rules: Core splits a
2135
+ * shorthand at every space, which cuts calc(4px + 2px) and loses a
2136
+ * fourth value. On the part itself the sides go as logical longhands,
2137
+ * which Core carries as they are; for a variant or state they go to the
2138
+ * side variables themselves, since Core writes one variable for equal
2139
+ * sides there and the part's own side variables would win over it.
2140
+ * Null for any other property or part.
2141
+ * @param {string} target @param {Setting} s
2142
+ * @returns {Record<string, string> | null}
2143
+ */
2144
+ const containerSides = (target, s) => {
2145
+ const prop = kebab(s.thing);
2146
+ if (
2147
+ s.mode ||
2148
+ !/^padding(-block|-inline|-left|-right|-top|-bottom|-block-start|-block-end|-inline-start|-inline-end)?$/.test(
2149
+ prop,
2150
+ )
2151
+ )
2152
+ return null;
2153
+ if (
2154
+ !(ctx.derived?.[target] ?? []).some(
2155
+ d => d.property === 'padding' && d.expand,
2156
+ )
2157
+ )
2158
+ return null;
2159
+ const scoped0 = s.when != null || s.state != null;
2160
+ // padding's initial value is 0, and padding does not inherit, so unset
2161
+ // is 0 too: on Core's side variables a keyword means no value at all.
2162
+ const value = /^(initial|unset)$/i.test(String(s.value).trim())
2163
+ ? '0'
2164
+ : String(s.value).trim();
2165
+ // A physical left or right stays physical, as Core keeps it (it maps
2166
+ // no physical side to a logical one but top and bottom, which it maps
2167
+ // itself): it is written as it is, and a later padding that covers it
2168
+ // takes it out of the block (below).
2169
+ const physical = /** @type {Record<string, string>} */ ({
2170
+ // One logical side is that side (its keyword resolved too).
2171
+ 'padding-block-start': 'block-start',
2172
+ 'padding-block-end': 'block-end',
2173
+ 'padding-inline-start': 'inline-start',
2174
+ 'padding-inline-end': 'inline-end',
2175
+ 'padding-top': 'block-start',
2176
+ 'padding-bottom': 'block-end',
2177
+ })[prop];
2178
+ if (physical)
2179
+ return {
2180
+ [scoped0
2181
+ ? `--astryx-${target}-padding-${physical}`
2182
+ : camel(`padding-${physical}`)]: value,
2183
+ };
2184
+ // A physical left or right is written as it is (its keyword resolved),
2185
+ // never split as an axis: there is no padding-left-start.
2186
+ if (prop === 'padding-left' || prop === 'padding-right')
2187
+ return {[camel(prop)]: value};
2188
+ const w = splitTop(value, ' ').map(x => x.trim());
2189
+ if (!w.length || w.length > (prop === 'padding' ? 4 : 2)) return null;
2190
+ const scoped = s.when != null || s.state != null;
2191
+ // Only what Core would split wrong is written side by side: math or a
2192
+ // function, four values with different left and right sides; and, for
2193
+ // a variant or state, any padding once the part sets a side itself.
2194
+ const coreSplitsWrong =
2195
+ value !== String(s.value).trim() ||
2196
+ /\(/.test(value) ||
2197
+ (prop === 'padding' && w.length === 4 && w[1] !== w[3]);
2198
+ const partSides = data.settings.some(
2199
+ x =>
2200
+ x !== s &&
2201
+ x.source === 'property' &&
2202
+ // The part's own, or a group's it is in.
2203
+ (x.on === s.on ||
2204
+ (FAMILIES[/** @type {string} */ (x.on)] ?? []).includes(target)) &&
2205
+ x.when == null &&
2206
+ x.state == null &&
2207
+ (/^padding-/.test(kebab(x.thing)) ||
2208
+ (kebab(x.thing) === 'padding' &&
2209
+ /\(|\S+\s+\S+\s+\S+\s+\S+/.test(x.value))),
2210
+ );
2211
+ // A side set on the part or its group: every side is written, so the
2212
+ // later setting wins as written.
2213
+ if (!coreSplitsWrong && !partSides) return null;
2214
+ /** @type {Record<string, string>} */
2215
+ const side = {};
2216
+ if (prop === 'padding') {
2217
+ const [top, right = top, bottom = top, left = right] = w;
2218
+ Object.assign(side, {
2219
+ 'block-start': top,
2220
+ 'inline-end': right,
2221
+ 'block-end': bottom,
2222
+ 'inline-start': left,
2223
+ });
2224
+ } else {
2225
+ const axis = prop.slice('padding-'.length);
2226
+ side[`${axis}-start`] = w[0];
2227
+ side[`${axis}-end`] = w[1] ?? w[0];
2228
+ }
2229
+ return Object.fromEntries(
2230
+ Object.entries(side).map(([k, v]) => [
2231
+ scoped ? `--astryx-${target}-padding-${k}` : camel(`padding-${k}`),
2232
+ v,
2233
+ ]),
2234
+ );
2235
+ };
2236
+ /**
2237
+ * A radius of more than one value on a part whose radius Core copies
2238
+ * into a variable for the content inside it (a card's full-bleed
2239
+ * children), as each corner's own radius, so Core writes no copy of the
2240
+ * whole value there (where one corner reads it, and `10px / 20px` or four
2241
+ * values are wrong). The inner variable takes one radius, the first
2242
+ * corner's across: Core gives the content one radius for every corner.
2243
+ * Null for any other property, part or a single radius.
2244
+ * @param {string} target @param {Setting} s
2245
+ * @returns {Record<string, string> | null}
2246
+ */
2247
+ const cornerRadii = (target, s) => {
2248
+ if (s.mode || kebab(s.thing) !== 'border-radius') return null;
2249
+ const vars = (ctx.derived?.[target] ?? []).find(
2250
+ d => d.property === 'borderRadius' && d.vars?.length,
2251
+ )?.vars;
2252
+ if (!vars) return null;
2253
+ const [across, down] = splitTop(String(s.value).trim(), '/').map(x =>
2254
+ splitTop(x.trim(), ' ').map(y => y.trim()),
2255
+ );
2256
+ if (!across?.length || (across.length === 1 && !down)) return null;
2257
+ /** @param {string[]} w top-left, top-right, bottom-right, bottom-left */
2258
+ const four = w => {
2259
+ const [tl, tr = tl, br = tl, bl = tr] = w;
2260
+ return [tl, tr, br, bl];
2261
+ };
2262
+ const h = four(across);
2263
+ const v = down?.length ? four(down) : null;
2264
+ const corner = (/** @type {number} */ i) =>
2265
+ v && v[i] !== h[i] ? `${h[i]} ${v[i]}` : h[i];
2266
+ return {
2267
+ borderTopLeftRadius: corner(0),
2268
+ borderTopRightRadius: corner(1),
2269
+ borderBottomRightRadius: corner(2),
2270
+ borderBottomLeftRadius: corner(3),
2271
+ ...Object.fromEntries(vars.map(name => [name, h[0]])),
2272
+ };
2273
+ };
2274
+ /**
2275
+ * A one-side logical padding on a part whose whole padding Core copies
2276
+ * into a variable of its own (a composer's or a menu's inner padding),
2277
+ * written for each direction (a left-to-right box's left is a
2278
+ * right-to-left box's right): Core feeds every logical padding into that
2279
+ * variable, so one side would set the whole box. Null for any other
2280
+ * property or part.
2281
+ * @param {string} target @param {Setting} s
2282
+ * @returns {Record<string, string | Record<string, string>> | null}
2283
+ */
2284
+ const boxSides = (target, s) => {
2285
+ const prop = kebab(s.thing);
2286
+ if (s.mode) return null;
2287
+ const derived = ctx.derived?.[target] ?? [];
2288
+ if (
2289
+ derived.some(d => d.property === 'padding' && d.expand) ||
2290
+ !derived.some(d => d.property === 'padding' && d.vars?.length)
2291
+ )
2292
+ return null;
2293
+ const SIDES = /** @type {Record<string, string[]>} */ ({
2294
+ 'padding-block-start': ['block-start'],
2295
+ 'padding-block-end': ['block-end'],
2296
+ 'padding-inline-start': ['inline-start'],
2297
+ 'padding-inline-end': ['inline-end'],
2298
+ 'padding-block': ['block-start', 'block-end'],
2299
+ 'padding-inline': ['inline-start', 'inline-end'],
2300
+ });
2301
+ const sides = SIDES[prop];
2302
+ if (!sides) return null;
2303
+ const w = splitTop(String(s.value).trim(), ' ').map(x => x.trim());
2304
+ // Each side for each direction: a block side is the top or bottom; an
2305
+ // inline side is the left in a left-to-right box and the right in a
2306
+ // right-to-left one, written under :dir(), where Core writes the
2307
+ // declarations as they are and feeds none into the whole-box variable.
2308
+ /** @type {Record<string, string>} */
2309
+ const plain = {};
2310
+ /** @type {Record<string, string>} */
2311
+ const ltr = {};
2312
+ /** @type {Record<string, string>} */
2313
+ const rtl = {};
2314
+ sides.forEach((side, i) => {
2315
+ const v = w[i] ?? w[0];
2316
+ if (side === 'block-start') plain.paddingTop = v;
2317
+ else if (side === 'block-end') plain.paddingBottom = v;
2318
+ else if (side === 'inline-start') {
2319
+ ltr.paddingLeft = v;
2320
+ rtl.paddingRight = v;
2321
+ } else {
2322
+ ltr.paddingRight = v;
2323
+ rtl.paddingLeft = v;
2324
+ }
2325
+ });
2326
+ return {
2327
+ ...plain,
2328
+ ...(Object.keys(ltr).length ? {':dir(ltr)': ltr, ':dir(rtl)': rtl} : {}),
2329
+ };
2330
+ };
2331
+ /**
2332
+ * A padding on a part whose visible box sits inside its themed wrapper,
2333
+ * as the padding variable that box reads, not the wrapper's own padding
2334
+ * (which would add a gap outside the box). Null for any other part.
2335
+ * @param {string} target @param {Setting} s
2336
+ * @returns {Record<string, string> | null}
2337
+ */
2338
+ const wrappedPadding = (target, s) => {
2339
+ if (s.mode || !WRAPPED_PARTS[target] || kebab(s.thing) !== 'padding')
2340
+ return null;
2341
+ const name = (ctx.derived?.[target] ?? []).find(
2342
+ d => d.property === 'padding' && d.vars?.length,
2343
+ )?.vars?.[0];
2344
+ return name ? {[name]: String(s.value).trim()} : null;
2345
+ };
2346
+ /**
2347
+ * The prefix of the padding variables a part's box reads, for a part whose
2348
+ * padding Core writes to them (its derivedVarRegistry's container
2349
+ * expansion), or for one drawn by such a part (a clickable card is a
2350
+ * card); null for any other part.
2351
+ * @param {string} target
2352
+ */
2353
+ const padVars = target => {
2354
+ if (
2355
+ (ctx.derived?.[target] ?? []).some(
2356
+ d => d.property === 'padding' && d.expand,
2357
+ )
2358
+ )
2359
+ return `--astryx-${target}-padding`;
2360
+ return CARD_LIKE.includes(target) ? '--astryx-card-padding' : null;
2361
+ };
2362
+ /**
2363
+ * Padding settings per part and per scope (the block a setting writes
2364
+ * to), in the order they were made.
2365
+ * @type {Map<string, {target: string, s: Setting, list: Setting[]}>}
2366
+ */
2367
+ const padQueue = new Map();
2368
+ /** @param {Setting} s @param {string} target */
2369
+ const queuePadding = (s, target) => {
2370
+ const key = `${target}\0${s.when ?? ''}\0${s.state ?? ''}`;
2371
+ const q = padQueue.get(key) ?? {target, s, list: []};
2372
+ q.list.push(s);
2373
+ padQueue.set(key, q);
2374
+ };
2375
+ /**
2376
+ * One padding model: each scope's settings, in order, resolved to the
2377
+ * four logical sides for each direction (a physical left is the
2378
+ * inline-start in a left-to-right box and the inline-end in a
2379
+ * right-to-left one; the padding shorthand is physical too), then written
2380
+ * to the variables the part's box reads: a side the same in both
2381
+ * directions in the scope's own block, one that differs in a rule for
2382
+ * each direction (one level deep under a state). So the derived and
2383
+ * full-bleed values follow, and a variant or a state out-ranks the base
2384
+ * as Core's own rules do.
2385
+ */
2386
+ const emitPadding = () => {
2387
+ // The side variables written on a narrower selector (a variant, a
2388
+ // state, a clickable card), by the part whose variables they are, with
2389
+ // that selector: they inherit, so a plain one of those parts inside is
2390
+ // reset to its own fallback (below), never given a copy of a value.
2391
+ /** @type {Map<string, Map<string, Set<string>>>} */
2392
+ const narrow = new Map();
2393
+ /** A side as CSS reads it inside calc(): a bare 0 is no length. @param {string} v */
2394
+ const length = v => {
2395
+ const n = cssNumber(v);
2396
+ return n && n.unit === '' && n.value === 0 ? '0px' : v;
2397
+ };
2398
+ for (const {target, s, list} of padQueue.values()) {
2399
+ const prefix = /** @type {string} */ (padVars(target));
2400
+ const owner = prefix.slice('--astryx-'.length, -'-padding'.length);
2401
+ const scoped = target !== owner || s.when != null || s.state != null;
2402
+ /** @type {Record<'ltr' | 'rtl', Record<string, string>>} */
2403
+ const side = {ltr: {}, rtl: {}};
2404
+ for (const x of list) {
2405
+ const prop = kebab(x.thing);
2406
+ const raw = String(x.value).trim();
2407
+ // initial and unset leave the variable without a value, so the part
2408
+ // takes Core's own default for it.
2409
+ const value = /^(initial|unset)$/i.test(raw) ? 'initial' : raw;
2410
+ const w = splitTop(value, ' ').map(y => length(y.trim()));
2411
+ const one = length(value);
2412
+ for (const dir of /** @type {const} */ (['ltr', 'rtl'])) {
2413
+ const o = side[dir];
2414
+ const left = dir === 'ltr' ? 'inline-start' : 'inline-end';
2415
+ const right = dir === 'ltr' ? 'inline-end' : 'inline-start';
2416
+ if (prop === 'padding') {
2417
+ const [top, r = top, bottom = top, l = r] = w;
2418
+ Object.assign(o, {
2419
+ 'block-start': top,
2420
+ [right]: r,
2421
+ 'block-end': bottom,
2422
+ [left]: l,
2423
+ });
2424
+ } else if (prop === 'padding-block') {
2425
+ o['block-start'] = w[0];
2426
+ o['block-end'] = w[1] ?? w[0];
2427
+ } else if (prop === 'padding-inline') {
2428
+ o['inline-start'] = w[0];
2429
+ o['inline-end'] = w[1] ?? w[0];
2430
+ } else if (prop === 'padding-top') o['block-start'] = one;
2431
+ else if (prop === 'padding-bottom') o['block-end'] = one;
2432
+ else if (prop === 'padding-left') o[left] = one;
2433
+ else if (prop === 'padding-right') o[right] = one;
2434
+ else {
2435
+ const k = prop.slice('padding-'.length);
2436
+ if (/^(block|inline)-(start|end)$/.test(k)) o[k] = one;
2437
+ }
2438
+ }
2439
+ }
2440
+ /** @type {Record<string, string>} */
2441
+ let plain = {};
2442
+ /** @type {Record<string, string>} */
2443
+ const ltr = {};
2444
+ /** @type {Record<string, string>} */
2445
+ const rtl = {};
2446
+ for (const k of [
2447
+ 'block-start',
2448
+ 'block-end',
2449
+ 'inline-start',
2450
+ 'inline-end',
2451
+ ]) {
2452
+ const [a, b] = [side.ltr[k], side.rtl[k]];
2453
+ if (a != null && a === b) plain[`${prefix}-${k}`] = a;
2454
+ else {
2455
+ if (a != null) ltr[`${prefix}-${k}`] = a;
2456
+ if (b != null) rtl[`${prefix}-${k}`] = b;
2457
+ }
2458
+ }
2459
+ // On the part's own base, a side that is the same in both
2460
+ // directions is written as its logical padding property, which Core
2461
+ // lowers to the variables together with the base theme's and the own
2462
+ // source's padding in the same block: the later wins by key, and four
2463
+ // equal sides come out as the whole padding (a nested section keeps
2464
+ // following its parent's), whatever sides the base theme set.
2465
+ // Only the plain rule: a variant's or a state's rule written that way
2466
+ // would come out as the whole padding alone, which the base's own side
2467
+ // variables out-rank.
2468
+ const lowered = target === owner && !s.when && !s.state;
2469
+ if (lowered)
2470
+ plain = Object.fromEntries(
2471
+ Object.entries(plain).map(([k, v]) => [
2472
+ camel(`padding-${k.slice(prefix.length + 1)}`),
2473
+ v,
2474
+ ]),
2475
+ );
2476
+ // A part drawn by another (a clickable card) writes its sides for each
2477
+ // direction too, so a direction rule the card's own base has never
2478
+ // out-ranks it.
2479
+ if (target !== owner)
2480
+ for (const [k, v] of Object.entries(plain)) {
2481
+ ltr[k] ??= v;
2482
+ rtl[k] ??= v;
2483
+ }
2484
+ if (scoped) {
2485
+ const sel = narrowSelector(target, s);
2486
+ if (sel) {
2487
+ const bySel = narrow.get(owner) ?? new Map();
2488
+ const names = bySel.get(sel) ?? new Set();
2489
+ for (const k of [
2490
+ ...Object.keys(plain),
2491
+ ...Object.keys(ltr),
2492
+ ...Object.keys(rtl),
2493
+ ])
2494
+ names.add(k);
2495
+ bySel.set(sel, names);
2496
+ narrow.set(owner, bySel);
2497
+ }
2498
+ }
2499
+ for (const [k, v] of Object.entries(plain)) putComp(s, target, k, v);
2500
+ for (const [dir, rule] of /** @type {const} */ ([
2501
+ [':dir(ltr)', ltr],
2502
+ [':dir(rtl)', rtl],
2503
+ ]))
2504
+ if (Object.keys(rule).length) {
2505
+ const [b, key] = dirBlock(s, target, dir);
2506
+ b[key] = {...(b[key] ?? {}), ...rule};
2507
+ }
2508
+ }
2509
+ // A plain part inside a narrower one: each side the narrower selector
2510
+ // writes is reset (left without a value, so Core's own fallback holds),
2511
+ // on the part's own class at its own weight, before any base setting a
2512
+ // theme gives it (the part's own base, or a source of the user's own,
2513
+ // which comes later and so wins).
2514
+ for (const [owner, bySel] of narrow) {
2515
+ const b = ((theme.components[owner] ??= {}).base ??= {});
2516
+ // The variables Core writes on the part's own rule, from the base
2517
+ // theme's, the settings' and the own source's padding there: the
2518
+ // reset leaves those alone, so the part's own value always holds.
2519
+ const own = basePaddingVars(owner, b);
2520
+ for (const [sel, names] of bySel) {
2521
+ /** @type {Record<string, string>} */
2522
+ const reset = {};
2523
+ for (const name of names)
2524
+ if (!(name in b) && !own.has(name)) reset[name] = 'initial';
2525
+ if (Object.keys(reset).length) {
2526
+ const key = `:where(${sel} *)`;
2527
+ b[key] = {...(b[key] ?? {}), ...reset};
2528
+ }
2529
+ }
2530
+ }
2531
+ };
2532
+ /**
2533
+ * The padding variables Core writes on a part's plain rule, as Core lowers
2534
+ * the padding properties there (the base theme's, then the settings',
2535
+ * then the own source's, later keys winning): the whole padding when the
2536
+ * four sides are equal, else each side given (an inline pair as one).
2537
+ * @param {string} owner @param {Record<string, any>} mine
2538
+ * @returns {Set<string>}
2539
+ */
2540
+ const basePaddingVars = (owner, mine) => {
2541
+ const prefix = `--astryx-${owner}-padding`;
2542
+ /** @type {Array<[string, string]>} */
2543
+ const keys = [];
2544
+ const fromBase = /** @type {any} */ (base).components?.[owner]?.base ?? {};
2545
+ for (const [k, v] of Object.entries(fromBase))
2546
+ if (typeof v === 'string') keys.push([k, v]);
2547
+ for (const [k, v] of Object.entries(mine))
2548
+ if (typeof v === 'string') keys.push([k, v]);
2549
+ try {
2550
+ for (const [k, v] of ownPartTokens(ctx.project.cwd, data.name, owner))
2551
+ if (v != null && !k.startsWith('--')) keys.push([camel(k), v]);
2552
+ } catch {
2553
+ // No own source.
2554
+ }
2555
+ /** @type {Record<string, string | undefined>} */
2556
+ const r = {};
2557
+ for (const [k, v] of keys) {
2558
+ const w = splitTop(v.trim(), ' ');
2559
+ if (k === 'padding') {
2560
+ r.bs = w[0];
2561
+ r.in = w[1] ?? w[0];
2562
+ r.be = w[2] ?? w[0];
2563
+ delete r.is;
2564
+ delete r.ie;
2565
+ } else if (k === 'paddingBlock') {
2566
+ r.bs = w[0];
2567
+ r.be = w[1] ?? w[0];
2568
+ } else if (k === 'paddingInline') {
2569
+ if (w.length > 1) [r.is, r.ie] = w;
2570
+ else r.in = w[0];
2571
+ } else if (k === 'paddingTop' || k === 'paddingBlockStart') r.bs = v;
2572
+ else if (k === 'paddingBottom' || k === 'paddingBlockEnd') r.be = v;
2573
+ else if (k === 'paddingInlineStart') r.is = v;
2574
+ else if (k === 'paddingInlineEnd') r.ie = v;
2575
+ }
2576
+ const out = new Set(Object.keys(mine).filter(k => k.startsWith(prefix)));
2577
+ const is = r.is ?? r.in;
2578
+ const ie = r.ie ?? r.in;
2579
+ if (is != null && is === ie && r.bs === is && r.be === is) out.add(prefix);
2580
+ else {
2581
+ if (r.is != null || r.ie != null) {
2582
+ if (is != null) out.add(`${prefix}-inline-start`);
2583
+ if (ie != null) out.add(`${prefix}-inline-end`);
2584
+ } else if (r.in != null) out.add(`${prefix}-inline`);
2585
+ if (r.bs != null) out.add(`${prefix}-block-start`);
2586
+ if (r.be != null) out.add(`${prefix}-block-end`);
2587
+ }
2588
+ return out;
2589
+ };
2590
+ /**
2591
+ * The selector a narrower padding scope is written with (a clickable
2592
+ * card's class, a variant's attribute, a state's pseudo-class), or null
2593
+ * for a state Core writes as a block of its own.
2594
+ * @param {string} target @param {Setting} s
2595
+ */
2596
+ const narrowSelector = (target, s) => {
2597
+ const tg = ctx.project.target.get(target);
2598
+ if (s.state && tg?.states.includes(s.state)) return null;
2599
+ const [k, v] = s.when ? String(s.when).split(':') : [];
2600
+ return `.astryx-${target}${s.when ? `[data-${k}="${v}"]` : ''}${s.state ? stateKey(s.state, wrapsOneControl(ctx, target)) : ''}`;
2601
+ };
2602
+
2603
+ /**
2604
+ * Each part's blocks with its base first, and in each block the rules for
2605
+ * a direction before a state's: Core writes them in this order, and a
2606
+ * variant or a state comes after the base it out-ranks (rules of the same
2607
+ * weight win by order).
2608
+ */
2609
+ const orderBlocks = () => {
2610
+ /** @param {Record<string, any>} b @returns {Record<string, any>} */
2611
+ const dirFirst = b => {
2612
+ const keys = Object.keys(b);
2613
+ const plain = keys.filter(k => !k.startsWith(':'));
2614
+ const dirs = keys.filter(k => /^:dir\(/.test(k));
2615
+ const rest = keys.filter(k => k.startsWith(':') && !/^:dir\(/.test(k));
2616
+ return Object.fromEntries(
2617
+ [...plain, ...dirs, ...rest].map(k => [
2618
+ k,
2619
+ k.startsWith(':') && b[k] && typeof b[k] === 'object'
2620
+ ? dirFirst(b[k])
2621
+ : b[k],
2622
+ ]),
2623
+ );
2624
+ };
2625
+ // A part drawn by another (a clickable card) after the part drawing it,
2626
+ // so its own padding wins over the base's reset at the same weight.
2627
+ theme.components = Object.fromEntries([
2628
+ ...Object.entries(theme.components ?? {}).filter(
2629
+ ([t]) => !CARD_LIKE.includes(t),
2630
+ ),
2631
+ ...Object.entries(theme.components ?? {}).filter(([t]) =>
2632
+ CARD_LIKE.includes(t),
2633
+ ),
2634
+ ]);
2635
+ for (const [target, blocks] of Object.entries(theme.components ?? {})) {
2636
+ const keys = Object.keys(blocks);
2637
+ const ordered = keys.includes('base')
2638
+ ? ['base', ...keys.filter(k => k !== 'base')]
2639
+ : keys;
2640
+ theme.components[target] = Object.fromEntries(
2641
+ ordered.map(k => [
2642
+ k,
2643
+ blocks[k] && typeof blocks[k] === 'object'
2644
+ ? dirFirst(blocks[k])
2645
+ : blocks[k],
2646
+ ]),
2647
+ );
2648
+ }
2649
+ };
2650
+ /**
2651
+ * Where a per-direction rule goes for a setting, one level deep, as the
2652
+ * block and its key: in the setting's own block, or under a state Core
2653
+ * writes as a pseudo-class, beside that state with the direction after it.
2654
+ * @param {Setting} s @param {string} target @param {string} dir `:dir(ltr)`
2655
+ * @returns {[Record<string, any>, string]}
2656
+ */
2657
+ const dirBlock = (s, target, dir) => {
2658
+ const tg = ctx.project.target.get(target);
2659
+ if (!s.state || tg?.states.includes(s.state))
2660
+ return [block(s, target), dir];
2661
+ const parent = block({...s, state: undefined}, target);
2662
+ return [parent, `${stateKey(s.state, wrapsOneControl(ctx, target))}${dir}`];
2663
+ };
1007
2664
  /** @param {Setting} s @param {string} target @param {string} prop @param {string} v */
1008
2665
  const putComp = (s, target, prop, v) => {
1009
2666
  const b = block(s, target);
@@ -1256,9 +2913,89 @@ export function compileTheme(ctx, data, base) {
1256
2913
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
1257
2914
  else putTok(s.thing, s.value, s.mode);
1258
2915
  } else if (s.source === 'property') {
1259
- for (const t of parts) putComp(s, t, camel(s.thing), s.value);
2916
+ for (const t of parts) {
2917
+ // A padding on a part whose box reads Core's padding variables is
2918
+ // resolved with the rest of that part's padding, below.
2919
+ if (padVars(t) && /^padding(-|$)/.test(kebab(s.thing))) {
2920
+ queuePadding(s, t);
2921
+ continue;
2922
+ }
2923
+ const sides =
2924
+ wrappedPadding(t, s) ??
2925
+ containerSides(t, s) ??
2926
+ cornerRadii(t, s) ??
2927
+ boxSides(t, s);
2928
+ if (sides)
2929
+ for (const [k, v] of Object.entries(sides)) {
2930
+ // A per-direction block joins what that direction already has,
2931
+ // one level deep: under a state it is the state's own key with
2932
+ // the direction after it (`:hover:dir(ltr)`), which Core writes
2933
+ // as one rule.
2934
+ if (k.startsWith(':') && typeof v === 'object') {
2935
+ const [b, key] = dirBlock(s, t, k);
2936
+ b[key] = {...(b[key] ?? {}), ...v};
2937
+ } else putComp(s, t, k, /** @type {string} */ (v));
2938
+ }
2939
+ else putComp(s, t, camel(s.thing), s.value);
2940
+ // A later padding takes out what it covers that would beat it: a
2941
+ // physical side written as it is (a group's left under a later part
2942
+ // padding; left-to-right, inline-start is the left), and a side
2943
+ // written per direction, whose :dir() rule is more specific.
2944
+ {
2945
+ const prop = kebab(s.thing);
2946
+ /** @type {Record<string, Array<'paddingLeft' | 'paddingRight'>>} */
2947
+ const COVERS = {
2948
+ padding: ['paddingLeft', 'paddingRight'],
2949
+ 'padding-inline': ['paddingLeft', 'paddingRight'],
2950
+ 'padding-inline-start': ['paddingLeft'],
2951
+ 'padding-inline-end': ['paddingRight'],
2952
+ 'padding-left': [],
2953
+ 'padding-right': [],
2954
+ };
2955
+ const plain = COVERS[prop];
2956
+ if (plain) {
2957
+ const b = block(s, t);
2958
+ // A side written per direction leaves a physical side as it is:
2959
+ // its :dir(ltr) rule already wins in a left-to-right box, and in
2960
+ // a right-to-left one the physical left is still the left.
2961
+ const perDirection =
2962
+ !!sides && Object.keys(sides).some(x => x.startsWith(':'));
2963
+ if (!perDirection)
2964
+ for (const k of plain)
2965
+ if (b[k] != null && !(sides && k in sides)) delete b[k];
2966
+ // Per direction: a whole padding or inline padding covers both
2967
+ // sides in both directions; a physical side, that side in both.
2968
+ const dirSides =
2969
+ prop === 'padding' || prop === 'padding-inline'
2970
+ ? ['paddingLeft', 'paddingRight']
2971
+ : prop === 'padding-left'
2972
+ ? ['paddingLeft']
2973
+ : prop === 'padding-right'
2974
+ ? ['paddingRight']
2975
+ : [];
2976
+ if (
2977
+ dirSides.length &&
2978
+ !(sides && Object.keys(sides).some(x => x.startsWith(':')))
2979
+ )
2980
+ for (const d of [':dir(ltr)', ':dir(rtl)']) {
2981
+ const [db, key] = dirBlock(s, t, d);
2982
+ const rule = db[key];
2983
+ if (!rule) continue;
2984
+ for (const x of dirSides) delete rule[x];
2985
+ if (!Object.keys(rule).length) delete db[key];
2986
+ }
2987
+ }
2988
+ }
2989
+ // A part's own corner radii replace a single radius a group or an
2990
+ // earlier setting left in the same block, which Core would copy into
2991
+ // the content's radius after the editor's own.
2992
+ if (sides && 'borderTopLeftRadius' in sides)
2993
+ delete block(s, t).borderRadius;
2994
+ }
1260
2995
  }
1261
2996
  }
2997
+ emitPadding();
2998
+ orderBlocks();
1262
2999
  // Core gives headings the body font when a theme sets only the body's:
1263
3000
  // a font for the body alone keeps the base theme's heading font.
1264
3001
  if (theme.typography?.body && !theme.typography.heading) {
@@ -1323,21 +3060,30 @@ export function compileTheme(ctx, data, base) {
1323
3060
  theme.tokens[k] = l === d ? l : [l, d];
1324
3061
  }
1325
3062
  // 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
3063
+ // below the lg width); an exact font family or weight, and the headings
3064
+ // dial's weights, are written there too, so they apply on every screen.
3065
+ // Sizes are not: phones keep their reading base. (What the theme's own
3066
+ // source sets is not repeated: on phones the base theme's type comes
3067
+ // back for it, a Core limit the notes name.)
3068
+ const phone = Object.fromEntries([
3069
+ ...data.settings
1330
3070
  .filter(
1331
3071
  x =>
1332
3072
  x.source === 'token' &&
1333
3073
  !x.on &&
1334
3074
  !x.mode &&
1335
- // Families only: phones keep their own reading sizes.
1336
- /^--font-family/.test(x.thing) &&
3075
+ PHONE_TYPE.test(x.thing) &&
1337
3076
  !(modeOnly && x.mode && x.mode !== modeOnly),
1338
3077
  )
1339
3078
  .map(x => [x.thing, x.value]),
1340
- );
3079
+ ]);
3080
+ // The headings dial's weights, unless an exact token sets one.
3081
+ const headingsWeight = [...data.settings]
3082
+ .reverse()
3083
+ .find(x => x.thing === 'headings' && x.axis !== 'tracking' && !x.on);
3084
+ if (headingsWeight && HEADING_WEIGHTS[headingsWeight.value])
3085
+ for (const k of headingWeightTokens)
3086
+ phone[k] ??= HEADING_WEIGHTS[headingsWeight.value];
1341
3087
  if (Object.keys(phone).length)
1342
3088
  theme.adaptations = {
1343
3089
  rules: [
@@ -1367,9 +3113,10 @@ const SMALL_STEPS = /** @type {Array<[string, number]>} */ ([
1367
3113
  * Settings whose effect a later or stronger setting hides, with why: `type`
1368
3114
  * loses heading weight and tracking to `headings`.
1369
3115
  * @param {ThemeData} data
3116
+ * @param {Ctx | null} [ctx] with it, a later setting that reaches the parts through a spread counts too
1370
3117
  * @returns {Map<Setting, string>}
1371
3118
  */
1372
- export function maskedSettings(data) {
3119
+ export function maskedSettings(data, ctx = null) {
1373
3120
  /** @type {Map<Setting, string>} */
1374
3121
  const out = new Map();
1375
3122
  const axes = new Set(
@@ -1409,6 +3156,37 @@ export function maskedSettings(data) {
1409
3156
  `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
1410
3157
  );
1411
3158
  });
3159
+ // With the parts known: a later setting of the same thing that reaches
3160
+ // every part an earlier one styles (a member that spreads to its group,
3161
+ // the same part without --only), dial or CSS property, covers it too.
3162
+ if (ctx)
3163
+ data.settings.forEach((s, i) => {
3164
+ if (
3165
+ out.has(s) ||
3166
+ !s.on ||
3167
+ (s.source !== 'dial' && s.source !== 'property')
3168
+ )
3169
+ return;
3170
+ const mine = partsOf(ctx, s);
3171
+ if (!mine.length) return;
3172
+ const later = data.settings
3173
+ .slice(i + 1)
3174
+ .find(
3175
+ x =>
3176
+ x.thing === s.thing &&
3177
+ x.source === s.source &&
3178
+ x.on &&
3179
+ (x.when ?? '') === (s.when ?? '') &&
3180
+ (x.state ?? '') === (s.state ?? '') &&
3181
+ (x.mode ?? '') === (s.mode ?? '') &&
3182
+ mine.every(t => partsOf(ctx, x).includes(t)),
3183
+ );
3184
+ if (later)
3185
+ out.set(
3186
+ s,
3187
+ `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
3188
+ );
3189
+ });
1412
3190
  for (const s of data.settings) {
1413
3191
  if (s.thing !== 'type' || !axes.size) continue;
1414
3192
  const T = TYPE_STYLES[s.value];
@@ -1448,16 +3226,13 @@ export function findOverrides(cssText, theme) {
1448
3226
  'g',
1449
3227
  );
1450
3228
  // 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$/;
3229
+ // (background after background-color) is the one in effect. Which
3230
+ // longhands a shorthand sets is MDN's data (background-blend-mode is
3231
+ // no part of background).
1456
3232
  /** @param {string} a @param {string} b */
1457
3233
  const sameProperty = (a, b) => {
1458
3234
  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;
3235
+ return x === y || coversProperty(x, y) || coversProperty(y, x);
1461
3236
  };
1462
3237
  const last = props.filter(
1463
3238
  (p, i) => !props.slice(i + 1).some(later => sameProperty(later, p)),
@@ -1592,6 +3367,12 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1592
3367
  [
1593
3368
  `// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
1594
3369
  `// Built from settings ${settingsStamp(data)}.`,
3370
+ // The theme source as it is when the build starts (the editor's
3371
+ // own when the build writes it), so an own change to it after the
3372
+ // build is told by content.
3373
+ ...(cwd
3374
+ ? [`// Built with ${slug}.theme.ts ${themeSourceHash(cwd, slug)}.`]
3375
+ : []),
1595
3376
  ...(like && cwd
1596
3377
  ? [
1597
3378
  `// Built on @astryxdesign/theme-${like} ${baseVersionOf(cwd, like) ?? 'unknown'}.`,
@@ -1615,6 +3396,130 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1615
3396
  );
1616
3397
  }
1617
3398
 
3399
+ /**
3400
+ * A hash of a theme's source file as the next build reads it: the file, or
3401
+ * the source the editor writes when there is none.
3402
+ * @param {string} cwd
3403
+ * @param {string} slug
3404
+ */
3405
+ function themeSourceHash(cwd, slug) {
3406
+ const f = themeFiles(cwd, slug);
3407
+ const hash = createHash('sha256');
3408
+ if (!fs.existsSync(f.ts)) {
3409
+ // The same as the file the build is about to write would hash.
3410
+ hash.update(`${path.basename(f.ts)}\0`);
3411
+ hash.update(themeModuleSource(slug));
3412
+ return hash.digest('hex').slice(0, 16);
3413
+ }
3414
+ for (const file of ownSourceFiles(cwd, slug)) {
3415
+ hash.update(`${path.relative(f.dir, file)}\0`);
3416
+ hash.update(fs.readFileSync(file));
3417
+ }
3418
+ return hash.digest('hex').slice(0, 16);
3419
+ }
3420
+
3421
+ /**
3422
+ * The theme source and every local module it reaches (an own helper such
3423
+ * as ./my-tokens), read the way theme discovery reads them: the person's
3424
+ * files. The editor's generated modules change with each build and are
3425
+ * judged by their own stamps.
3426
+ * @param {string} cwd
3427
+ * @param {string} slug
3428
+ * @returns {string[]}
3429
+ */
3430
+ function ownSourceFiles(cwd, slug) {
3431
+ const f = themeFiles(cwd, slug);
3432
+ if (!fs.existsSync(f.ts)) return [];
3433
+ const generated = new Set([f.settingsTs]);
3434
+ const seen = new Set();
3435
+ /** @type {string[]} */
3436
+ const files = [];
3437
+ const queue = [f.ts];
3438
+ while (queue.length) {
3439
+ const file = /** @type {string} */ (queue.shift());
3440
+ if (seen.has(file)) continue;
3441
+ seen.add(file);
3442
+ files.push(file);
3443
+ /** @type {string[]} */
3444
+ let specifiers = [];
3445
+ try {
3446
+ specifiers = themeFileImports(file, {withRequire: true});
3447
+ } catch {
3448
+ // A file that does not parse is hashed as it is; the build names it.
3449
+ }
3450
+ for (const spec of specifiers) {
3451
+ if (!spec.startsWith('.')) continue;
3452
+ const target = localModuleFile(path.dirname(file), spec);
3453
+ // Only the editor's own generated palette files are judged by their
3454
+ // stamps; any other file the theme reaches, in tokens/ too, is the
3455
+ // person's.
3456
+ if (
3457
+ target &&
3458
+ !generated.has(target) &&
3459
+ !isGeneratedPaletteFile(f.dir, slug, target)
3460
+ )
3461
+ queue.push(target);
3462
+ }
3463
+ }
3464
+ return files;
3465
+ }
3466
+
3467
+ /** The extensions a theme's local module may have, as the build reads them. */
3468
+ const MODULE_EXTENSIONS = [
3469
+ '.ts',
3470
+ '.tsx',
3471
+ '.mts',
3472
+ '.cts',
3473
+ '.js',
3474
+ '.jsx',
3475
+ '.mjs',
3476
+ '.cjs',
3477
+ ];
3478
+
3479
+ /**
3480
+ * The file a relative import names, resolved as TypeScript resolves it: a
3481
+ * JavaScript extension names its TypeScript source (`.js` → `.ts`/`.tsx`,
3482
+ * `.jsx` → `.tsx`, `.mjs` → `.mts`, `.cjs` → `.cts`), then the path as
3483
+ * written, with each module extension, and as a folder's index file.
3484
+ * @param {string} dir
3485
+ * @param {string} spec
3486
+ * @returns {string | undefined}
3487
+ */
3488
+ function localModuleFile(dir, spec) {
3489
+ const base = path.resolve(dir, spec);
3490
+ const ext = path.extname(base);
3491
+ const stem = base.slice(0, base.length - ext.length);
3492
+ const sourceFor = /** @type {Record<string, string[]>} */ ({
3493
+ '.js': ['.ts', '.tsx'],
3494
+ '.jsx': ['.tsx'],
3495
+ '.mjs': ['.mts'],
3496
+ '.cjs': ['.cts'],
3497
+ })[ext];
3498
+ return [
3499
+ ...(sourceFor ?? []).map(x => stem + x),
3500
+ base,
3501
+ ...MODULE_EXTENSIONS.map(x => base + x),
3502
+ ...MODULE_EXTENSIONS.map(x => path.join(base, `index${x}`)),
3503
+ ].find(p => fs.existsSync(p) && fs.statSync(p).isFile());
3504
+ }
3505
+
3506
+ /**
3507
+ * Whether a file is one of the palette files the editor generates in a
3508
+ * theme's tokens/ folder (`tokens/<slug>.palette*`).
3509
+ * @param {string} dir the theme folder
3510
+ * @param {string} slug
3511
+ * @param {string} file
3512
+ */
3513
+ function isGeneratedPaletteFile(dir, slug, file) {
3514
+ const rel = path.relative(path.join(dir, 'tokens'), file);
3515
+ return (
3516
+ !rel.startsWith('..') &&
3517
+ !path.isAbsolute(rel) &&
3518
+ !rel.includes(path.sep) &&
3519
+ rel.startsWith(`${slug}.palette`)
3520
+ );
3521
+ }
3522
+
1618
3523
  /**
1619
3524
  * The theme module, written once: it extends the generated settings and is
1620
3525
  * the person's own from then on, so hand edits in it survive every change.
@@ -1666,6 +3571,52 @@ export function themeSourceProblem(cwd, slug) {
1666
3571
  return null;
1667
3572
  }
1668
3573
 
3574
+ /**
3575
+ * Why the person's own theme source does not parse (its line and the
3576
+ * parser's message), or null when it parses or is not there.
3577
+ * @param {string} cwd
3578
+ * @param {string} slug
3579
+ * @returns {string | null}
3580
+ */
3581
+ export function themeSourceParseError(cwd, slug) {
3582
+ const f = themeFiles(cwd, slug);
3583
+ let code;
3584
+ try {
3585
+ code = fs.readFileSync(f.ts, 'utf8');
3586
+ } catch {
3587
+ return null;
3588
+ }
3589
+ try {
3590
+ parseModule(code, {sourceType: 'module', plugins: ['typescript']});
3591
+ return null;
3592
+ } catch (e) {
3593
+ const err = /** @type {any} */ (e);
3594
+ return `${slug}.theme.ts does not parse${err?.loc?.line ? ` (line ${err.loc.line})` : ''}: ${String(err?.message ?? e).replace(/\s*\(\d+:\d+\)\s*$/, '')}`;
3595
+ }
3596
+ }
3597
+
3598
+ /**
3599
+ * Refuse, before anything is written or removed, a command whose build
3600
+ * would load the person's own theme source when it does not parse: the
3601
+ * build would fail part way.
3602
+ * @param {string} cwd
3603
+ * @param {string} slug
3604
+ */
3605
+ export function refuseThemeParse(cwd, slug) {
3606
+ const why = themeSourceParseError(cwd, slug);
3607
+ if (why)
3608
+ throw new AstryxError(
3609
+ `${why}, so the theme cannot build. It is your own file: fix it, then run the command again. Nothing was changed.`,
3610
+ [
3611
+ {
3612
+ name: `cat ${path.posix.join('themes', slug, `${slug}.theme.ts`)}`,
3613
+ reason: 'see the file',
3614
+ },
3615
+ ],
3616
+ ERROR_CODES.ERR_THEME_INVALID,
3617
+ );
3618
+ }
3619
+
1669
3620
  /**
1670
3621
  * Refuse a build whose theme source cannot carry the settings, naming the
1671
3622
  * lines that put it back.
@@ -1673,6 +3624,7 @@ export function themeSourceProblem(cwd, slug) {
1673
3624
  * @param {string} slug
1674
3625
  */
1675
3626
  export function refuseThemeSource(cwd, slug) {
3627
+ refuseThemeParse(cwd, slug);
1676
3628
  const why = themeSourceProblem(cwd, slug);
1677
3629
  if (why)
1678
3630
  throw new AstryxError(
@@ -1682,6 +3634,75 @@ export function refuseThemeSource(cwd, slug) {
1682
3634
  );
1683
3635
  }
1684
3636
 
3637
+ /**
3638
+ * Refuse a [light, dark] pair the theme's own source gives a token that is
3639
+ * not a color (a font family, a size, a weight): the build would write
3640
+ * `light-dark()`, which browsers take only for colors. The editor refuses
3641
+ * `--mode` on those tokens for the same reason.
3642
+ * @param {Ctx} ctx
3643
+ * @param {string} cwd
3644
+ * @param {string} slug
3645
+ */
3646
+ function refuseOwnPairs(ctx, cwd, slug) {
3647
+ const f = themeFiles(cwd, slug);
3648
+ /** @type {string[]} */
3649
+ const bad = [];
3650
+ try {
3651
+ const ast = /** @type {any} */ (
3652
+ parseModule(fs.readFileSync(f.ts, 'utf8'), {
3653
+ sourceType: 'module',
3654
+ plugins: ['typescript'],
3655
+ })
3656
+ );
3657
+ /** @param {any} node */
3658
+ const visit = node => {
3659
+ if (!node || typeof node !== 'object') return;
3660
+ if (
3661
+ node.type === 'ObjectProperty' &&
3662
+ typeof (node.key?.value ?? node.key?.name) === 'string' &&
3663
+ String(node.key?.value ?? node.key?.name).startsWith('--') &&
3664
+ node.value?.type === 'ArrayExpression' &&
3665
+ node.value.elements.length === 2 &&
3666
+ // A pair holding a value that is not text is named by the value
3667
+ // checks, with the fix for that value.
3668
+ node.value.elements.every(
3669
+ (/** @type {any} */ e) =>
3670
+ e?.type === 'StringLiteral' || e?.type === 'TemplateLiteral',
3671
+ )
3672
+ ) {
3673
+ const k = String(node.key.value ?? node.key.name);
3674
+ const type = ctx.C.typeOf(k);
3675
+ // A size given as a bare number is named by the value check, with
3676
+ // the unit it needs.
3677
+ const unitless =
3678
+ type === 'size' &&
3679
+ node.value.elements.some(
3680
+ (/** @type {any} */ e) =>
3681
+ e?.type === 'StringLiteral' && /^\d*\.?\d+$/.test(e.value.trim()),
3682
+ );
3683
+ if (!MODAL.has(type) && !unitless) bad.push(k);
3684
+ }
3685
+ for (const v of Object.values(node))
3686
+ if (Array.isArray(v)) v.forEach(visit);
3687
+ else if (v && typeof v === 'object' && v.type) visit(v);
3688
+ };
3689
+ visit(ast.program);
3690
+ } catch {
3691
+ return;
3692
+ }
3693
+ if (bad.length)
3694
+ throw new AstryxError(
3695
+ `themes/${slug}/${slug}.theme.ts gives ${[...new Set(bad)].join(', ')} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors. Give ${bad.length > 1 ? 'each' : 'it'} one value in ${slug}.theme.ts. Nothing was changed.`,
3696
+ [
3697
+ {
3698
+ name: `grep -n -- ${quoteCommandArgument(bad[0])} ${quoteCommandArgument(`themes/${slug}/${slug}.theme.ts`)}`,
3699
+ reason: 'see the line',
3700
+ },
3701
+ ],
3702
+ ERROR_CODES.ERR_THEME_INVALID,
3703
+ );
3704
+ }
3705
+
1685
3706
  /**
1686
3707
  * Generate the theme source, build it with the theme build, then repeat any
1687
3708
  * part setting a more specific rule would beat and build again.
@@ -1694,6 +3715,7 @@ export async function buildTheme(ctx, slug, data) {
1694
3715
  const {cwd} = ctx.project;
1695
3716
  const f = themeFiles(cwd, slug);
1696
3717
  refuseThemeSource(cwd, slug);
3718
+ refuseOwnPairs(ctx, cwd, slug);
1697
3719
  if (data.like) baseThemeFile(ctx.project, data.like);
1698
3720
  const base = await baseResolved(ctx.project, data.like);
1699
3721
  fs.mkdirSync(f.dir, {recursive: true});
@@ -1737,23 +3759,26 @@ export async function buildTheme(ctx, slug, data) {
1737
3759
  if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
1738
3760
  });
1739
3761
  // 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.
3762
+ // of an older base, and the pictures the editor took of an older look.
3763
+ // Only a picture the editor recorded writing, unchanged since, goes: a
3764
+ // file of the user's is never touched. Section sheets stay, marked as
3765
+ // out of date like sheet.html.
1741
3766
  await step(() => {
3767
+ const pictures = fs.existsSync(f.dir)
3768
+ ? fs
3769
+ .readdirSync(f.dir)
3770
+ .filter(
3771
+ n =>
3772
+ /^(sheet|preview)(-[a-z-]+)?\.png$/.test(n) &&
3773
+ editorWrote(cwd, slug, path.join(f.dir, n)),
3774
+ )
3775
+ : [];
1742
3776
  for (const file of [
1743
3777
  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
- : []),
3778
+ ...pictures.map(n => path.join(f.dir, n)),
1755
3779
  ])
1756
3780
  fs.rmSync(file, {force: true});
3781
+ forgetWritten(cwd, slug, pictures);
1757
3782
  });
1758
3783
  let receipt = await step(() => runBuild(ctx, slug));
1759
3784
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
@@ -1764,7 +3789,16 @@ export async function buildTheme(ctx, slug, data) {
1764
3789
  if (found.length) {
1765
3790
  for (const x of found) {
1766
3791
  const t = theme.components[x.target];
1767
- (t[x.key] ??= {})[x.prop] ??= x.value;
3792
+ // The base value goes before the variant's own declarations, so a
3793
+ // longhand or shorthand the variant sets itself (border-color after
3794
+ // a base border) still wins over it.
3795
+ const own = t[x.key] ?? {};
3796
+ // A variant that sets every longhand of the property itself needs
3797
+ // none of the base value (and a lifted radius would feed Core's copy
3798
+ // of it into the content's radius, after the variant's own).
3799
+ const longs = [...longhandsOf(kebab(x.prop))];
3800
+ if (longs.length && longs.every(l => camel(l) in own)) continue;
3801
+ t[x.key] = {[x.prop]: x.value, ...own};
1768
3802
  lifted.push(`${x.target} ${x.key} ${kebab(x.prop)}`);
1769
3803
  }
1770
3804
  await step(() => {
@@ -1808,6 +3842,46 @@ async function runBuild(ctx, slug) {
1808
3842
  }
1809
3843
  }
1810
3844
 
3845
+ /**
3846
+ * Why the built outputs differ from what the theme builds now: one that is
3847
+ * missing or changed by hand, found the way `compile --check` finds it
3848
+ * (the same build, compared and not written), or null when they match.
3849
+ * @param {Ctx} ctx
3850
+ * @param {string} slug
3851
+ * @returns {Promise<string | null>}
3852
+ */
3853
+ export async function outputsDrift(ctx, slug) {
3854
+ const {cwd} = ctx.project;
3855
+ const f = themeFiles(cwd, slug);
3856
+ const silent = logger.silent;
3857
+ logger.setSilent(true);
3858
+ try {
3859
+ const {receipt} = await themeBuildForReport(
3860
+ shown(cwd, f.ts),
3861
+ {check: true},
3862
+ {cwd},
3863
+ {compact: true},
3864
+ );
3865
+ const first = /** @type {any} */ (receipt)?.data?.stale?.[0];
3866
+ if (!first) return null;
3867
+ const name = path.basename(String(first.path));
3868
+ return first.reason === 'missing'
3869
+ ? `${name} was missing`
3870
+ : `${name} differs from what the settings build, after an edit by hand or by another tool`;
3871
+ } catch (e) {
3872
+ // A theme source that does not load is named by its own checks; any
3873
+ // other failure means the outputs could not be compared: built again.
3874
+ const err = /** @type {any} */ (e);
3875
+ if (err instanceof AstryxError && err.code === ERROR_CODES.ERR_THEME_LOAD)
3876
+ return null;
3877
+ return `the outputs could not be checked (${String(err?.message ?? e)
3878
+ .split('\n')[0]
3879
+ .slice(0, 160)})`;
3880
+ } finally {
3881
+ logger.setSilent(silent);
3882
+ }
3883
+ }
3884
+
1811
3885
  /**
1812
3886
  * Resolved tokens of the built theme in both modes.
1813
3887
  * @param {Ctx} ctx
@@ -1855,10 +3929,41 @@ export async function resolvedTokens(ctx, slug) {
1855
3929
  v => v && typeof v === 'object' && typeof v.name === 'string',
1856
3930
  );
1857
3931
  const {core} = ctx.project;
1858
- const out = {
1859
- light: core.resolveThemeTokens(t, {mode: 'light'}),
1860
- dark: core.resolveThemeTokens(t, {mode: 'dark'}),
3932
+ // A token value an own theme source gives as a number (8 for 8px)
3933
+ // reads as its text, never as a crash.
3934
+ const asText = (/** @type {Record<string, unknown>} */ m) =>
3935
+ Object.fromEntries(
3936
+ Object.entries(m ?? {}).map(([k, v]) => [
3937
+ k,
3938
+ typeof v === 'string' ? v : String(v),
3939
+ ]),
3940
+ );
3941
+ // A token value that is not text (a number in an own theme source) is
3942
+ // named, never a crash.
3943
+ const resolve = (/** @type {'light' | 'dark'} */ mode) => {
3944
+ try {
3945
+ return asText(core.resolveThemeTokens(t, {mode}));
3946
+ } catch (e) {
3947
+ const bad = nonTextToken(t, ctx.C.typeOf);
3948
+ throw new AstryxError(
3949
+ bad
3950
+ ? nonTextMessage(ctx, slug, bad)
3951
+ : `${slug} could not be read: ${e instanceof Error ? e.message : String(e)}.`,
3952
+ [{name: `${P} how --list tokens`, reason: 'every token and its type'}],
3953
+ ERROR_CODES.ERR_THEME_INVALID,
3954
+ );
3955
+ }
1861
3956
  };
3957
+ // A pair that holds a value that is not text ([8, 8]) resolves, but
3958
+ // builds nothing a browser reads: named the same way.
3959
+ const pairBad = nonTextToken(t, ctx.C.typeOf);
3960
+ if (pairBad)
3961
+ throw new AstryxError(
3962
+ nonTextMessage(ctx, slug, pairBad),
3963
+ [{name: `${P} how --list tokens`, reason: 'every token and its type'}],
3964
+ ERROR_CODES.ERR_THEME_INVALID,
3965
+ );
3966
+ const out = {light: resolve('light'), dark: resolve('dark')};
1862
3967
  // The tokens each part sets for itself (the official themes lift
1863
3968
  // secondary text on some parts), for the contrast check; kept out of the
1864
3969
  // modes so nothing that lists the resolved tokens sees it.
@@ -1873,6 +3978,90 @@ export async function resolvedTokens(ctx, slug) {
1873
3978
  return out;
1874
3979
  }
1875
3980
 
3981
+ /**
3982
+ * The first token a built theme gives a value that is not text, alone or
3983
+ * in a [light, dark] pair, or null.
3984
+ * @param {any} t
3985
+ * @param {(name: string) => string} [typeOf] a token's type (size, color…)
3986
+ * @returns {[string, unknown, 'object' | 'pair' | 'unit' | 'value'] | null}
3987
+ */
3988
+ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
3989
+ for (const [k, raw] of Object.entries(t?.tokens ?? {})) {
3990
+ // An object ({light, dark}) is not a value Core builds: it would write
3991
+ // [object Object].
3992
+ if (raw && typeof raw === 'object' && !Array.isArray(raw))
3993
+ return [k, raw, 'object'];
3994
+ // A built theme writes a pair as light-dark(). A half that was not text
3995
+ // comes out as nothing, null or a boolean; a bare number is text the
3996
+ // source may have quoted, and is wrong only for a size, which needs a
3997
+ // unit.
3998
+ const pair =
3999
+ typeof raw === 'string' ? /^light-dark\((.*)\)$/s.exec(raw.trim()) : null;
4000
+ // Split at the top-level comma: a half may hold commas (rgb(0, 0, 0)).
4001
+ const parts = pair ? splitTop(pair[1], ',').map(x => x.trim()) : [];
4002
+ if (pair && parts.length === 2) {
4003
+ const halves = parts;
4004
+ const missing = halves.some(x =>
4005
+ /^(|null|undefined|true|false)$/.test(x),
4006
+ );
4007
+ const unitless =
4008
+ typeOf(k) === 'size' &&
4009
+ halves.some(x => /^-?\d+(\.\d+)?$/.test(x) && Number(x) !== 0);
4010
+ if (missing || unitless) {
4011
+ const half = (/** @type {string} */ x) =>
4012
+ /^-?\d+(\.\d+)?$/.test(x)
4013
+ ? Number(x)
4014
+ : x === '' || x === 'undefined' || x === 'null'
4015
+ ? null
4016
+ : x === 'true' || x === 'false'
4017
+ ? x === 'true'
4018
+ : x;
4019
+ return [k, [half(parts[0]), half(parts[1])], missing ? 'pair' : 'unit'];
4020
+ }
4021
+ continue;
4022
+ }
4023
+ if (Array.isArray(raw)) {
4024
+ if (raw.length !== 2 || raw.some(x => typeof x !== 'string'))
4025
+ return [k, raw, 'pair'];
4026
+ continue;
4027
+ }
4028
+ if (typeof raw !== 'string') return [k, raw, 'value'];
4029
+ }
4030
+ return null;
4031
+ }
4032
+
4033
+ /**
4034
+ * Why a token value is not one, with a value of the token's own type to
4035
+ * write instead (a size in px, a weight as a number in quotes), or none.
4036
+ * @param {Ctx} ctx
4037
+ * @param {string} slug
4038
+ * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value')?]} bad
4039
+ */
4040
+ function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
4041
+ const type = ctx.C.typeOf(name);
4042
+ if (kind === 'object')
4043
+ 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).`;
4044
+ if (kind === 'unit') {
4045
+ const n = /** @type {unknown[]} */ (value).find(
4046
+ x => typeof x === 'number' && x !== 0,
4047
+ );
4048
+ 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'.`;
4049
+ }
4050
+ const one = Array.isArray(value)
4051
+ ? value.find(x => typeof x !== 'string')
4052
+ : value;
4053
+ const example =
4054
+ typeof one === 'number'
4055
+ ? type === 'size'
4056
+ ? `'${one}px'`
4057
+ : `'${one}'`
4058
+ : null;
4059
+ const shape = Array.isArray(value)
4060
+ ? 'a [light, dark] pair of two CSS values in quotes'
4061
+ : 'a CSS value in quotes';
4062
+ 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})` : ''}.`;
4063
+ }
4064
+
1876
4065
  /**
1877
4066
  * Contrast problems this theme caused: text below 4.5:1 that was not as low
1878
4067
  * in the base theme. A part's own color or background setting, or a token
@@ -2050,7 +4239,7 @@ export async function contrastProblems(ctx, data, res) {
2050
4239
  })(),
2051
4240
  ...(unchecked.length
2052
4241
  ? [
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`,
4242
+ `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
4243
  ]
2055
4244
  : []),
2056
4245
  ];
@@ -2118,7 +4307,9 @@ export function baseComponent(base, ctx, target, prop, s) {
2118
4307
  const states = ctx.project.target.get(target)?.states ?? [];
2119
4308
  b = states.includes(s.state)
2120
4309
  ? t[s.when == null ? s.state : `${s.when}+${s.state}`]
2121
- : (b?.[stateKey(s.state)] ?? b?.[`:${s.state}`]);
4310
+ : (b?.[stateKey(s.state, wrapsOneControl(ctx, target))] ??
4311
+ b?.[stateKey(s.state)] ??
4312
+ b?.[`:${s.state}`]);
2122
4313
  }
2123
4314
  const v = b?.[prop];
2124
4315
  return typeof v === 'string' ? v : null;
@@ -2184,15 +4375,64 @@ export function clearNewMarker(dir) {
2184
4375
 
2185
4376
  /**
2186
4377
  * 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.
4378
+ * button, link or tab with aria-disabled (it stays focusable). A form
4379
+ * control styled on a wrapper (a typeahead, a complex selector) has its
4380
+ * input or button inside marked, so it also matches a disabled form
4381
+ * control inside it (never a list row); an action part that holds
4382
+ * children (a button group, a segmented control) never does, so one
4383
+ * disabled child never makes the whole part look disabled.
2189
4384
  * @param {string} state
4385
+ * @param {boolean} [wrapsControl]
2190
4386
  * @returns {string}
2191
4387
  */
2192
- export function stateKey(state) {
2193
- return state === 'disabled'
2194
- ? ':is(:disabled,[aria-disabled="true"])'
2195
- : `:${state}`;
4388
+ export function stateKey(state, wrapsControl = false) {
4389
+ if (state !== 'disabled') return `:${state}`;
4390
+ return wrapsControl
4391
+ ? ':is(:disabled,[aria-disabled="true"],:has(:is(input,button,select,textarea):is(:disabled,[aria-disabled="true"])))'
4392
+ : ':is(:disabled,[aria-disabled="true"])';
4393
+ }
4394
+
4395
+ /**
4396
+ * The component docs of a part: its own component's, and the one named like
4397
+ * the part (tab is Tab, under TabList), each with its name, for the ones the
4398
+ * project has.
4399
+ * @param {Ctx} ctx
4400
+ * @param {string} part
4401
+ * @returns {Array<{name: string, doc: any}>}
4402
+ */
4403
+ export function partComponentDocs(ctx, part) {
4404
+ const comps = /** @type {Record<string, any>} */ (
4405
+ ctx.project.components ?? {}
4406
+ );
4407
+ const pascal = part.replace(/(^|-)([a-z0-9])/g, (_, __, c) =>
4408
+ c.toUpperCase(),
4409
+ );
4410
+ return [ctx.project.target.get(part)?.component, pascal]
4411
+ .filter(n => n != null && comps[n])
4412
+ .map(n => ({
4413
+ name: /** @type {string} */ (n),
4414
+ doc: comps[/** @type {string} */ (n)],
4415
+ }));
4416
+ }
4417
+
4418
+ /**
4419
+ * Whether a part's styled element wraps one control: its component (or the
4420
+ * one named like the part) is a form control (Core's own category) that
4421
+ * takes a disabled prop. An action part that holds children (a button
4422
+ * group) never does.
4423
+ * @param {Ctx} ctx
4424
+ * @param {string} target
4425
+ */
4426
+ export function wrapsOneControl(ctx, target) {
4427
+ // One control: a form control with a disabled prop whose content is not
4428
+ // other elements (a radio list's items, an input group's or a field's
4429
+ // children each hold controls of their own).
4430
+ return partComponentDocs(ctx, target).some(
4431
+ ({doc: d}) =>
4432
+ /form/i.test(String(d.category ?? '')) &&
4433
+ Object.keys(d.props ?? {}).some(p => /disabled/i.test(p)) &&
4434
+ d.props?.children?.type !== 'ReactNode',
4435
+ );
2196
4436
  }
2197
4437
 
2198
4438
  /**
@@ -2303,8 +4543,22 @@ export const EDITOR_SUFFIXES = [
2303
4543
  'd.ts',
2304
4544
  'variants.d.ts',
2305
4545
  'history.json',
4546
+ 'pictures.json',
2306
4547
  ];
2307
4548
 
4549
+ /**
4550
+ * Whether a name in a theme folder is a file the editor writes: the
4551
+ * theme's generated files, settings, history, picture record, pages and
4552
+ * pictures, and its color config.
4553
+ * @param {string} slug
4554
+ * @param {string} n
4555
+ */
4556
+ export const isEditorFile = (slug, n) =>
4557
+ EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
4558
+ /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config(\.damaged(-\d+)?)?\.json)$/.test(
4559
+ n,
4560
+ );
4561
+
2308
4562
  /**
2309
4563
  * The files in a theme folder that the editor writes, by name: the
2310
4564
  * theme's generated files, its settings, history and pages, and its color
@@ -2318,11 +4572,7 @@ export const EDITOR_SUFFIXES = [
2318
4572
  function ownFiles(dir) {
2319
4573
  if (!fs.lstatSync(dir, {throwIfNoEntry: false})?.isDirectory()) return [];
2320
4574
  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
- );
4575
+ const mine = (/** @type {string} */ n) => isEditorFile(slug, n);
2326
4576
  /** @type {string[]} */
2327
4577
  const out = [];
2328
4578
  for (const e of fs.readdirSync(dir, {withFileTypes: true}))
@@ -2394,8 +4644,12 @@ function restoreWritten(was, wrote) {
2394
4644
  continue;
2395
4645
  }
2396
4646
  const old = was.get(p);
2397
- if (old) writeWhole(p, old);
2398
- else fs.rmSync(p, {force: true});
4647
+ if (old) {
4648
+ // A folder the change removed (tokens/ once its palette went) comes
4649
+ // back with the file.
4650
+ fs.mkdirSync(path.dirname(p), {recursive: true});
4651
+ writeWhole(p, old);
4652
+ } else fs.rmSync(p, {force: true});
2399
4653
  } catch {
2400
4654
  failed.push(path.basename(p));
2401
4655
  }
@@ -2427,30 +4681,65 @@ export function refuseLinks(cwd, slug) {
2427
4681
  const f = themeFiles(cwd, slug);
2428
4682
  /** @param {string} p */
2429
4683
  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
- );
4684
+ // A path under a file (themes written as a file) is not a link: its
4685
+ // own refusal names it.
4686
+ /** @type {fs.Stats | undefined} */
4687
+ let st;
4688
+ try {
4689
+ st = fs.lstatSync(p, {throwIfNoEntry: false});
4690
+ } catch {
4691
+ return;
4692
+ }
4693
+ if (!st?.isSymbolicLink()) return;
4694
+ const rel = path.relative(cwd, p) || p;
4695
+ /** @type {string} */
4696
+ let target;
4697
+ try {
4698
+ target = fs.readlinkSync(p);
4699
+ } catch {
4700
+ target = '';
4701
+ }
4702
+ // Named, with where it points; nothing is removed or moved for the
4703
+ // user.
4704
+ const gone = !fs.existsSync(p);
4705
+ throw new AstryxError(
4706
+ `${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.`,
4707
+ [
4708
+ {
4709
+ name: `ls -l ${quoteCommandArgument(path.relative(cwd, p))}`,
4710
+ reason: 'shows where the link points',
4711
+ },
4712
+ ],
4713
+ ERROR_CODES.ERR_THEME_INVALID,
4714
+ );
2441
4715
  };
2442
4716
  link(f.root);
2443
4717
  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);
4718
+ // Only the files the editor reads or writes: a link to a file of the
4719
+ // user's (notes, a mockup) is theirs, and is left alone.
4720
+ const own = (/** @type {string} */ n) =>
4721
+ isEditorFile(slug, n) || n === `${slug}.theme.ts` || n === 'tokens';
4722
+ /** @type {string[]} */
4723
+ let names;
4724
+ try {
4725
+ names = fs.readdirSync(f.dir);
4726
+ } catch {
4727
+ return;
4728
+ }
4729
+ for (const n of names.filter(own)) {
4730
+ const p = path.join(f.dir, n);
4731
+ link(p);
4732
+ if (n === 'tokens') {
4733
+ /** @type {string[]} */
4734
+ let inner;
4735
+ try {
4736
+ inner = fs.readdirSync(p);
4737
+ } catch {
4738
+ inner = [];
4739
+ }
4740
+ for (const m of inner) link(path.join(p, m));
2451
4741
  }
2452
- };
2453
- walk(f.dir);
4742
+ }
2454
4743
  }
2455
4744
 
2456
4745
  /**
@@ -2483,15 +4772,12 @@ export function settingsStamp(data) {
2483
4772
  */
2484
4773
  export function staleBuild(cwd, slug, data) {
2485
4774
  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
- );
4775
+ const files = builtFiles(cwd, slug, data);
4776
+ // An output that cannot be read (its permissions, or a folder in its
4777
+ // place) is refused by name: the build cannot replace it either. That
4778
+ // includes the files a build writes only for some themes.
4779
+ refuseUnreadable(cwd, [...files, ...builtFiles(cwd, slug, data, true)]);
4780
+ const missing = files.find(p => !fs.existsSync(p));
2495
4781
  if (missing) return `${path.relative(f.dir, missing)} was missing`;
2496
4782
  const ts = fs.readFileSync(f.settingsTs, 'utf8');
2497
4783
  const stamp =
@@ -2510,6 +4796,16 @@ export function staleBuild(cwd, slug, data) {
2510
4796
  if (built && now && built !== now)
2511
4797
  return `@astryxdesign/theme-${data.like} is ${now} now, and the build was made on ${built}`;
2512
4798
  }
4799
+ // The generated module seals its own text: a hand edit inside it (the
4800
+ // file says not to) is built over from the settings, and said. Checked
4801
+ // after the stamps, whose reasons say more.
4802
+ if (moduleUnedited(ts) === false)
4803
+ return `${slug}.settings.ts was edited by hand, though it is generated from ${slug}.settings.json and says not to edit it`;
4804
+ // An own change to <slug>.theme.ts since the build (the file says it
4805
+ // wins over the settings) is built in.
4806
+ const source = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(ts);
4807
+ if (source && fs.existsSync(f.ts) && source[1] !== themeSourceHash(cwd, slug))
4808
+ return sourceChangedReason(slug);
2513
4809
  // By content, never by file times (an editor's re-save or a checkout
2514
4810
  // changes those): a generated module cut short, or built outputs whose
2515
4811
  // header names another CLI than the settings were written by (a build
@@ -2526,6 +4822,17 @@ export function staleBuild(cwd, slug, data) {
2526
4822
  })
2527
4823
  )
2528
4824
  return 'the last build did not finish (a command stopped while building)';
4825
+ // Outputs another theme's build wrote over (`compile other.theme.ts --out
4826
+ // themes/g/g.css`): their header names another source.
4827
+ const builtFrom = (/** @type {string} */ file) =>
4828
+ /^ \* Source: (.+)$/m
4829
+ .exec(fs.readFileSync(file, 'utf8').slice(0, 600))?.[1]
4830
+ ?.trim() ?? null;
4831
+ for (const file of [f.css, f.js]) {
4832
+ const from = builtFrom(file);
4833
+ if (from != null && path.basename(from) !== path.basename(f.ts))
4834
+ return `${path.basename(file)} was built from ${from}, not ${slug}.theme.ts`;
4835
+ }
2529
4836
  // A built stylesheet cut short (a crash, a bad merge) is built again, as
2530
4837
  // an unreadable built module is.
2531
4838
  try {
@@ -2536,6 +4843,79 @@ export function staleBuild(cwd, slug, data) {
2536
4843
  return null;
2537
4844
  }
2538
4845
 
4846
+ /**
4847
+ * Every file the editor's build of a theme writes, the one list staleness
4848
+ * reads: the generated settings module, the built stylesheet, module and
4849
+ * their types, and, with a color dial set, the generated color files.
4850
+ * @param {string} cwd
4851
+ * @param {string} slug
4852
+ * @param {ThemeData} data
4853
+ * @param {boolean} [some] the files a build writes only for some themes
4854
+ * (the variants types, for a theme with component variants) instead
4855
+ * @returns {string[]}
4856
+ */
4857
+ export function builtFiles(cwd, slug, data, some = false) {
4858
+ const f = themeFiles(cwd, slug);
4859
+ if (some) return [path.join(f.dir, `${slug}.variants.d.ts`)];
4860
+ const pal = paletteFiles(slug);
4861
+ const colors = data.settings.some(
4862
+ s => s.source === 'dial' && PALETTE_DIALS.includes(s.thing),
4863
+ )
4864
+ ? [pal.palette, pal.refs, pal.receipt].map(p => path.join(cwd, p))
4865
+ : [];
4866
+ return [
4867
+ f.settingsTs,
4868
+ // The theme's own source: the editor writes it once, and every build
4869
+ // reads it, so one deleted by hand is written again.
4870
+ f.ts,
4871
+ f.css,
4872
+ f.js,
4873
+ path.join(f.dir, `${slug}.d.ts`),
4874
+ path.join(f.dir, `${slug}.css.d.ts`),
4875
+ ...colors,
4876
+ ];
4877
+ }
4878
+
4879
+ /**
4880
+ * Refuse, by name, a built file that is there but cannot be read: its
4881
+ * permissions, or a folder where the file goes.
4882
+ * @param {string} cwd
4883
+ * @param {string[]} files
4884
+ */
4885
+ function refuseUnreadable(cwd, files) {
4886
+ for (const file of files) {
4887
+ const st = fs.statSync(file, {throwIfNoEntry: false});
4888
+ if (!st) continue;
4889
+ const rel = shown(cwd, file);
4890
+ if (st.isDirectory())
4891
+ throw new AstryxError(
4892
+ `${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.`,
4893
+ [
4894
+ {
4895
+ name: `ls -la ${quoteCommandArgument(rel)}`,
4896
+ reason: 'see what is there',
4897
+ },
4898
+ ],
4899
+ ERROR_CODES.ERR_FILE_EXISTS,
4900
+ );
4901
+ try {
4902
+ fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK);
4903
+ } catch (e) {
4904
+ const code = /** @type {any} */ (e)?.code ?? 'EACCES';
4905
+ throw new AstryxError(
4906
+ `${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.`,
4907
+ [
4908
+ {
4909
+ name: `ls -la ${quoteCommandArgument(rel)}`,
4910
+ reason: 'see its permissions',
4911
+ },
4912
+ ],
4913
+ ERROR_CODES.ERR_WRITE_FAILED,
4914
+ );
4915
+ }
4916
+ }
4917
+ }
4918
+
2539
4919
  /**
2540
4920
  * The installed version of a base theme package, or null.
2541
4921
  * @param {string} cwd
@@ -2572,6 +4952,19 @@ export const HISTORY_STEPS = 80;
2572
4952
  */
2573
4953
  export function readHistory(file) {
2574
4954
  if (!fs.existsSync(file)) return {steps: [], dropped: 0};
4955
+ // A history that cannot be read is not damaged: it is refused by name.
4956
+ const why = unreadableReason(file);
4957
+ if (why)
4958
+ throw new AstryxError(
4959
+ `${path.basename(file)} ${why}, so the undo history cannot be read. Give it back its place or its read permission; nothing was changed.`,
4960
+ [
4961
+ {
4962
+ name: `ls -la ${quoteCommandArgument(file)}`,
4963
+ reason: 'see what is there',
4964
+ },
4965
+ ],
4966
+ ERROR_CODES.ERR_THEME_INVALID,
4967
+ );
2575
4968
  /** @type {unknown} */
2576
4969
  let h;
2577
4970
  try {
@@ -2646,7 +5039,14 @@ export async function commitTheme(
2646
5039
  // A no-op change still mends a build that does not match the settings
2647
5040
  // (an undo stopped part way): it is built again, with no new step.
2648
5041
  const noop = history && same(parseSettings(snapBefore));
2649
- if (noop && fs.existsSync(f.js) && !staleBuild(cwd, slug, data))
5042
+ const stale =
5043
+ noop && fs.existsSync(f.js) ? staleBuild(cwd, slug, data) : null;
5044
+ // The no-op that mends one says what it built again.
5045
+ if (noop && stale)
5046
+ notes.push(
5047
+ `the build was not current (${stale}), so it was built again from the settings`,
5048
+ );
5049
+ if (noop && fs.existsSync(f.js) && !stale)
2650
5050
  return {
2651
5051
  changed: [],
2652
5052
  res: {light: {}, dark: {}},
@@ -2656,6 +5056,11 @@ export async function commitTheme(
2656
5056
  notes,
2657
5057
  unchanged: true,
2658
5058
  };
5059
+ // With no last build (deleted, never committed), nothing is compared.
5060
+ if (snapBefore && !fs.existsSync(f.js))
5061
+ notes.push(
5062
+ `there was no last build (${path.basename(f.js)} is missing), so the token changes are not listed; the theme is built again`,
5063
+ );
2659
5064
  const resBefore =
2660
5065
  snapBefore && fs.existsSync(f.js)
2661
5066
  ? await resolvedTokens(ctx, slug).catch(() => {
@@ -2668,7 +5073,9 @@ export async function commitTheme(
2668
5073
  })
2669
5074
  : null;
2670
5075
  const before = parseSettings(snapBefore);
2671
- const liftedBefore = new Set(before?.lifted ?? []);
5076
+ const liftedBefore = new Set(
5077
+ Array.isArray(before?.lifted) ? before.lifted : [],
5078
+ );
2672
5079
  // A change that leaves every color setting as it was keeps the shades the
2673
5080
  // theme already shows: a theme an earlier editor built keeps its colors
2674
5081
  // until a color, the mode or the base changes, and undo brings them back.
@@ -2728,6 +5135,10 @@ export async function commitTheme(
2728
5135
  fs.mkdirSync(f.dir, {recursive: true});
2729
5136
  /** @type {{warnings: string[], lifted: string[], notes: string[]}} */
2730
5137
  let built;
5138
+ // The token loops the last build had, so a change that adds one (through
5139
+ // tokens the own source sets in a way no read of the file follows) is
5140
+ // refused once the build shows it.
5141
+ const loopsBefore = new Set(builtLoops(cwd, slug).map(l => l.key));
2731
5142
  try {
2732
5143
  refuseIfLockLost();
2733
5144
  try {
@@ -2738,6 +5149,18 @@ export async function commitTheme(
2738
5149
  // The build writes its outputs itself: a lock lost meanwhile is seen
2739
5150
  // before anything else is written.
2740
5151
  refuseIfLockLost();
5152
+ const loop = builtLoops(cwd, slug).find(l => !loopsBefore.has(l.key));
5153
+ if (loop)
5154
+ throw new AstryxError(
5155
+ `${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.`,
5156
+ [
5157
+ {
5158
+ name: `${P} how ${loop.path[0].replace(/^--/, '')}`,
5159
+ reason: 'see what it takes',
5160
+ },
5161
+ ],
5162
+ ERROR_CODES.ERR_THEME_BAD_VALUE,
5163
+ );
2741
5164
  data.lifted = built.lifted;
2742
5165
  // The undo step and the settings are part of the change: written whole,
2743
5166
  // inside the rollback, the settings first. A command stopped between
@@ -2784,7 +5207,7 @@ export async function commitTheme(
2784
5207
  const code = /** @type {any} */ (e)?.code;
2785
5208
  if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO', 'EISDIR'].includes(code))
2786
5209
  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.`,
5210
+ `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
5211
  [
2789
5212
  {
2790
5213
  name: `ls -ld ${quoteCommandArgument(themeFiles(ctx.project.cwd, slug).dir)}`,
@@ -2800,9 +5223,27 @@ export async function commitTheme(
2800
5223
  e.code === ERROR_CODES.ERR_THEME_INVALID ||
2801
5224
  e.code === ERROR_CODES.ERR_PALETTE_GENERATION ||
2802
5225
  e.code === ERROR_CODES.ERR_WRITE_FAILED ||
2803
- e.code === ERROR_CODES.ERR_THEME_BUSY)
5226
+ e.code === ERROR_CODES.ERR_THEME_BUSY ||
5227
+ e.code === ERROR_CODES.ERR_THEME_BAD_VALUE)
2804
5228
  )
2805
5229
  throw e;
5230
+ // A folder where a built file goes: named for the editor, which has no
5231
+ // --out to pick.
5232
+ const folder =
5233
+ e instanceof AstryxError
5234
+ ? /^The output (.+) is a folder\./.exec(e.message)?.[1]
5235
+ : undefined;
5236
+ if (folder)
5237
+ throw new AstryxError(
5238
+ `${folder} is a folder, not a file, so the theme cannot be built. Put the file back in its place; nothing was changed.`,
5239
+ [
5240
+ {
5241
+ name: `ls -la ${quoteCommandArgument(folder)}`,
5242
+ reason: 'see what is there',
5243
+ },
5244
+ ],
5245
+ ERROR_CODES.ERR_THEME_INVALID,
5246
+ );
2806
5247
  const why = (e instanceof Error ? e.message : String(e))
2807
5248
  .split(`${cwd}${path.sep}`)
2808
5249
  .join('')
@@ -2812,12 +5253,17 @@ export async function commitTheme(
2812
5253
  .join(' | ');
2813
5254
  const own = why.includes(path.basename(f.ts));
2814
5255
  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)` : ''}`,
5256
+ `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
5257
  [
2817
- {
2818
- name: `${P} show ${slug}`,
2819
- reason: 'do this instead: see the settings as they are',
2820
- },
5258
+ own
5259
+ ? {
5260
+ name: `cat ${quoteCommandArgument(shown(cwd, f.ts))}`,
5261
+ reason: 'see your own file, then fix it',
5262
+ }
5263
+ : {
5264
+ name: `${P} show ${slug}`,
5265
+ reason: 'do this instead: see the settings as they are',
5266
+ },
2821
5267
  ],
2822
5268
  ERROR_CODES.ERR_THEME_INVALID,
2823
5269
  );