@astryxdesign/cli 0.7.15 → 0.7.16-canary.g8514aae

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 (116) hide show
  1. package/README.md +5 -3
  2. package/api/component/_adapter.d.mts +1 -1
  3. package/api/component/_adapter.mjs +28 -1
  4. package/api/doctor/_adapter.d.mts +17 -0
  5. package/api/doctor/_adapter.mjs +35 -0
  6. package/api/doctor/doctor.mjs +18 -4
  7. package/api/integration/validate-integration.mjs +1 -1
  8. package/api/theme/_adapter.d.mts +5 -2
  9. package/api/theme/_adapter.mjs +43 -12
  10. package/api/theme/build/build.d.mts +1 -21
  11. package/api/theme/build/build.mjs +149 -37
  12. package/api/theme/eject/eject.mjs +22 -1
  13. package/api/theme/template/template.d.mts +19 -0
  14. package/api/theme/template/template.mjs +91 -19
  15. package/api/theme/theme.type.d.mts +5 -1
  16. package/api/theme/theme.type.mjs +2 -1
  17. package/api/theme/themeBuild.doc.mjs +3 -3
  18. package/api/theme/themeEject.doc.mjs +1 -1
  19. package/api/theme/themeTemplate.doc.mjs +9 -3
  20. package/api/theme-edit/_adapter.d.mts +21 -0
  21. package/api/theme-edit/_adapter.mjs +176 -22
  22. package/api/theme-edit/_check.d.mts +7 -0
  23. package/api/theme-edit/_check.mjs +1050 -173
  24. package/api/theme-edit/_color.d.mts +2 -8
  25. package/api/theme-edit/_color.mjs +292 -219
  26. package/api/theme-edit/_compiler.d.mts +1 -0
  27. package/api/theme-edit/_compiler.mjs +20 -1
  28. package/api/theme-edit/_context.d.mts +21 -0
  29. package/api/theme-edit/_context.mjs +235 -12
  30. package/api/theme-edit/_css.d.mts +50 -1
  31. package/api/theme-edit/_css.mjs +310 -28
  32. package/api/theme-edit/_edit.d.mts +9 -0
  33. package/api/theme-edit/_edit.mjs +907 -123
  34. package/api/theme-edit/_how-commands.d.mts +11 -26
  35. package/api/theme-edit/_how-commands.mjs +30 -2
  36. package/api/theme-edit/_how-question.d.mts +7 -0
  37. package/api/theme-edit/_how-question.mjs +1304 -176
  38. package/api/theme-edit/_how.mjs +144 -30
  39. package/api/theme-edit/_palette.d.mts +6 -0
  40. package/api/theme-edit/_palette.mjs +164 -62
  41. package/api/theme-edit/_parts.d.mts +16 -0
  42. package/api/theme-edit/_parts.mjs +49 -1
  43. package/api/theme-edit/_png.mjs +19 -14
  44. package/api/theme-edit/_preview-app.mjs +514 -27
  45. package/api/theme-edit/_preview.d.mts +11 -0
  46. package/api/theme-edit/_preview.mjs +245 -24
  47. package/api/theme-edit/_project.d.mts +11 -0
  48. package/api/theme-edit/_project.mjs +35 -9
  49. package/api/theme-edit/_settings.d.mts +122 -5
  50. package/api/theme-edit/_settings.mjs +1363 -71
  51. package/api/theme-edit/_tables.d.mts +19 -0
  52. package/api/theme-edit/_tables.mjs +205 -149
  53. package/api/theme-edit/_vet.d.mts +42 -0
  54. package/api/theme-edit/_vet.mjs +144 -0
  55. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  56. package/api/theme-edit/theme-edit.type.mjs +1 -1
  57. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  58. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  59. package/assets/docs/tree/single-component.doc.mjs +11 -2
  60. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  61. package/assets/docs.generated.json +2 -2
  62. package/assets/preview-app/next.config.mjs +7 -1
  63. package/assets/preview-app/src/app/globals.css +1 -0
  64. package/assets/self-audit.generated.json +1 -1
  65. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  66. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  67. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  68. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  69. package/assets/templates/components.generated.json +1 -1
  70. package/authoring/doctypes/_schema.d.mts +52 -5
  71. package/authoring/doctypes/_schema.mjs +62 -7
  72. package/authoring/doctypes/base/type.ts +10 -0
  73. package/authoring/doctypes/component/component.doc.mjs +1 -1
  74. package/authoring/doctypes/function/function.doc.mjs +6 -0
  75. package/authoring/doctypes/function/type.ts +3 -0
  76. package/authoring/doctypes/legacy.mjs +5 -1
  77. package/authoring/index.d.ts +1 -0
  78. package/clients/cli/build-id.generated.json +1 -1
  79. package/clients/cli/commands/doctor.doc.mjs +2 -2
  80. package/clients/cli/commands/experimental/theme.mjs +188 -37
  81. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  82. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  83. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  84. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  85. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  86. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  87. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  88. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  89. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  90. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  91. package/clients/cli/commands/theme.mjs +89 -6
  92. package/clients/cli/formatters/index.mjs +7 -4
  93. package/clients/cli/lib/cli-error.mjs +9 -3
  94. package/clients/cli/lib/component-format.mjs +27 -9
  95. package/clients/cli/lib/json-shim.mjs +40 -2
  96. package/clients/cli/manifest.generated.json +1 -1
  97. package/foundation/config/project.mjs +50 -14
  98. package/foundation/discovery/theme-discovery.d.mts +5 -1
  99. package/foundation/discovery/theme-discovery.mjs +24 -3
  100. package/foundation/fs/gather-cache.d.mts +9 -2
  101. package/foundation/fs/gather-cache.mjs +36 -10
  102. package/foundation/fs/paths.d.mts +16 -0
  103. package/foundation/fs/paths.mjs +25 -0
  104. package/foundation/render/host-exit.d.mts +8 -0
  105. package/foundation/render/host-exit.mjs +11 -0
  106. package/foundation/render/page-host.mjs +56 -10
  107. package/foundation/render/page-worker.mjs +14 -0
  108. package/foundation/render/render-page.mjs +37 -2
  109. package/foundation/response/error-codes.d.mts +2 -1
  110. package/foundation/response/error-codes.d.ts +1 -0
  111. package/foundation/response/error-codes.doc.mjs +5 -0
  112. package/foundation/response/error-codes.mjs +3 -0
  113. package/foundation/response/json.d.mts +15 -0
  114. package/foundation/response/json.mjs +52 -1
  115. package/foundation/response/response-types.doc.mjs +1 -1
  116. 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, 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,11 @@ import {
39
42
  TEXT_SIZE,
40
43
  TYPE_STYLES,
41
44
  familyOf,
45
+ WRAPPED_PARTS,
42
46
  } from './_tables.mjs';
43
47
  import {
44
48
  alphaOf,
49
+ colorProblem,
45
50
  compositeOver,
46
51
  isColorValue,
47
52
  isSafeValue,
@@ -65,7 +70,7 @@ import {
65
70
  writeWhole,
66
71
  } from './_palette.mjs';
67
72
  import {MODAL, isColorToken} from './_compiler.mjs';
68
- import {baseResolved, baseThemeFile} from './_project.mjs';
73
+ import {baseInstalled, baseResolved, baseThemeFile} from './_project.mjs';
69
74
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
70
75
 
71
76
  /**
@@ -97,7 +102,7 @@ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
97
102
  /** What lifted secondary text sits on: the contrast check measures it there. */
98
103
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
99
104
 
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 */
105
+ /** @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
106
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
102
107
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
103
108
 
@@ -113,12 +118,17 @@ export const slugOk = s =>
113
118
  !windowsReserved(s);
114
119
 
115
120
  /**
116
- * A name Windows reserves for a device (con, nul, com1…): a folder named
117
- * so cannot be checked out there.
121
+ * A name Windows does not allow for a file or folder, so it cannot be
122
+ * checked out there: a device name (con, nul, com1, com¹…), a character
123
+ * Windows reserves (`<>:"|?*` and control characters), or a dot or space
124
+ * at the end.
118
125
  * @param {string} s
119
126
  */
120
127
  export const windowsReserved = s =>
121
- /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(s);
128
+ /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i.test(s) ||
129
+ // eslint-disable-next-line no-control-regex
130
+ /[<>:"|?*\u0000-\u001f]/.test(s) ||
131
+ /[. ]$/.test(s);
122
132
  /**
123
133
  * The theme name closest to what was typed: spaces and accents dropped,
124
134
  * lower case, anything else a dash.
@@ -171,6 +181,86 @@ export function themeFiles(cwd, slug) {
171
181
  };
172
182
  }
173
183
 
184
+ /**
185
+ * Why the editor cannot read one of its files, or null when it can (or the
186
+ * file is not there): a folder in the file's place, or no permission to read
187
+ * it. Bad content is a different problem, judged where the file is parsed.
188
+ * @param {string} file
189
+ * @returns {string | null}
190
+ */
191
+ export function unreadableReason(file) {
192
+ let st;
193
+ try {
194
+ st = fs.statSync(file);
195
+ } catch (e) {
196
+ const code = /** @type {any} */ (e)?.code;
197
+ return code === 'ENOENT' || code === 'ENOTDIR'
198
+ ? null
199
+ : `it cannot be read (${code ?? 'unknown error'})`;
200
+ }
201
+ if (st.isDirectory()) return 'it is a folder, not a file';
202
+ try {
203
+ fs.accessSync(file, fs.constants.R_OK);
204
+ } catch (e) {
205
+ return `it cannot be read (${/** @type {any} */ (e)?.code ?? 'no permission'}: permission denied)`;
206
+ }
207
+ return null;
208
+ }
209
+
210
+ /**
211
+ * Refuse, by name, when a file of the theme is a folder or cannot be read:
212
+ * every command reads them, and none should crash on one. The fix is to
213
+ * look at the file and give it back its place; a file is never deleted.
214
+ * @param {string} cwd
215
+ * @param {string} slug
216
+ */
217
+ export function refuseUnreadableFiles(cwd, slug) {
218
+ const f = themeFiles(cwd, slug);
219
+ // The files the editor reads (the settings, the source, the history) are
220
+ // named here; the files the build writes (with their types) by the
221
+ // build's own check, the same one show uses.
222
+ refuseUnreadable(cwd, [
223
+ ...builtFiles(cwd, slug, {name: slug, mode: 'both', settings: []}),
224
+ path.join(f.dir, `${slug}.variants.d.ts`),
225
+ ]);
226
+ for (const file of [f.settings, f.ts, f.history]) {
227
+ const why = unreadableReason(file);
228
+ if (why)
229
+ throw new AstryxError(
230
+ `${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.`,
231
+ [
232
+ {
233
+ name: `ls -la ${quoteCommandArgument(path.relative(cwd, file))}`,
234
+ reason: 'see what is there',
235
+ },
236
+ ],
237
+ ERROR_CODES.ERR_THEME_INVALID,
238
+ );
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Refuse when the app's themes/ is a file or a link to something other
244
+ * than a folder: every editor theme lives in themes/<name>/. The run lists
245
+ * what is there; the message says to rename or move it.
246
+ * @param {string} cwd
247
+ */
248
+ export function refuseThemesNotFolder(cwd) {
249
+ const root = path.join(cwd, 'themes');
250
+ const st = fs.lstatSync(root, {throwIfNoEntry: false});
251
+ if (!st) return;
252
+ const isDir =
253
+ st.isDirectory() ||
254
+ (st.isSymbolicLink() &&
255
+ fs.statSync(root, {throwIfNoEntry: false})?.isDirectory());
256
+ if (isDir) return;
257
+ refuse(
258
+ ERROR_CODES.ERR_FILE_EXISTS,
259
+ `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.`,
260
+ {run: ['ls -la themes']},
261
+ );
262
+ }
263
+
174
264
  /**
175
265
  * The themes the editor made in the app (a settings file of its own), by
176
266
  * name, or with `changed` the one an editor command changed last first: the
@@ -183,6 +273,7 @@ export function themeFiles(cwd, slug) {
183
273
  export function editedThemes(cwd, order = 'name') {
184
274
  const root = path.join(cwd, 'themes');
185
275
  if (!fs.existsSync(root)) return [];
276
+ refuseThemesNotFolder(cwd);
186
277
  const names = fs
187
278
  .readdirSync(root)
188
279
  .filter(d => fs.existsSync(themeFiles(cwd, d).settings))
@@ -259,6 +350,29 @@ export function refuse(code, message, extra = {}) {
259
350
  throw new AstryxError(`${message} ${tail}`, suggestions, code);
260
351
  }
261
352
 
353
+ /**
354
+ * A theme name as typed, read the way the editor reads it: a path to its
355
+ * folder or a file in it (t.theme.ts, Brand.settings.json), in any case,
356
+ * names the theme. The result may still need slugFor.
357
+ * @param {unknown} s
358
+ * @returns {string}
359
+ */
360
+ export function typedThemeName(s) {
361
+ return (
362
+ String(s ?? '')
363
+ .trim()
364
+ .toLowerCase()
365
+ // ./t and .\t name the theme t.
366
+ .replace(/^(\.[\\/])+/, '')
367
+ .replace(/^.*themes[\\/]/, '')
368
+ .replace(/[\\/].*$/, '')
369
+ .replace(
370
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|css|js|ts)$/,
371
+ '',
372
+ )
373
+ );
374
+ }
375
+
262
376
  /**
263
377
  * The settings of a theme, or a refusal naming the command that makes it.
264
378
  * @param {string} cwd
@@ -273,19 +387,12 @@ export function loadTheme(
273
387
  slug,
274
388
  skip = /** @type {string | Partial<Setting>} */ (''),
275
389
  ) {
390
+ refuseThemesNotFolder(cwd);
276
391
  if (!slugOk(slug)) {
277
392
  // A path or a capital letter typed for a theme that exists names it.
278
393
  // A file name typed for the theme (t.theme.ts, Brand.settings.json)
279
394
  // 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
- );
395
+ const plain = typedThemeName(slug);
289
396
  const fixed = slugFor(plain);
290
397
  const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
291
398
  // A list where one theme goes (t,u or "t;u"): one theme at a time,
@@ -309,6 +416,27 @@ export function loadTheme(
309
416
  },
310
417
  );
311
418
  }
419
+ // An empty name (an unset variable, a lone dash): no theme to guess
420
+ // from it, so the themes here are named instead of a new one.
421
+ if (!same && !/[a-z0-9]/i.test(String(slug ?? ''))) {
422
+ const have = fs.existsSync(themeFiles(cwd, 'x').root)
423
+ ? fs
424
+ .readdirSync(themeFiles(cwd, 'x').root)
425
+ .filter(
426
+ d => slugOk(d) && fs.existsSync(themeFiles(cwd, d).settings),
427
+ )
428
+ .sort()
429
+ : [];
430
+ refuse(
431
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
432
+ `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(', ')}.` : ''}`,
433
+ {
434
+ run: have.length
435
+ ? have.slice(0, 3).map(t => `${P} show ${t}`)
436
+ : [`${P} new my-theme`],
437
+ },
438
+ );
439
+ }
312
440
  refuse(
313
441
  ERROR_CODES.ERR_INVALID_ARGUMENT,
314
442
  `"${String(slug ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE}).`,
@@ -348,9 +476,39 @@ export function loadTheme(
348
476
  ERROR_CODES.ERR_UNKNOWN_THEME,
349
477
  stopped
350
478
  ? `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` : ''}.`,
479
+ : `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
480
  {run: [`${P} new ${slug}`]},
353
481
  );
482
+ // A folder copied or renamed by hand from an editor theme: its files
483
+ // still carry the old name (t.settings.json in themes/t2).
484
+ const copied =
485
+ !same && fs.existsSync(f.dir)
486
+ ? fs
487
+ .readdirSync(f.dir)
488
+ .map(n => /^(.+)\.settings\.json$/.exec(n)?.[1])
489
+ .find(n => n && n !== slug)
490
+ : undefined;
491
+ if (copied) {
492
+ const files = fs
493
+ .readdirSync(f.dir)
494
+ .filter(n => n.startsWith(`${copied}.`))
495
+ .sort();
496
+ const original = fs.existsSync(themeFiles(cwd, copied).settings);
497
+ refuse(
498
+ ERROR_CODES.ERR_UNKNOWN_THEME,
499
+ `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
500
+ .slice(0, 2)
501
+ .map(n => `${n} to ${slug}${n.slice(copied.length)}`)
502
+ .join(
503
+ ', ',
504
+ )}${files.length > 2 ? ', and so on' : ''})${original ? `; ${copied} itself is still in themes/${copied}` : ''}.`,
505
+ {
506
+ run: original
507
+ ? [`${P} show ${copied}`, `ls -la themes/${slug}`]
508
+ : [`ls -la themes/${slug}`],
509
+ },
510
+ );
511
+ }
354
512
  if (!same && (other || LIKE.includes(slug)))
355
513
  refuse(
356
514
  ERROR_CODES.ERR_UNKNOWN_THEME,
@@ -364,13 +522,25 @@ export function loadTheme(
364
522
  refuse(
365
523
  ERROR_CODES.ERR_UNKNOWN_THEME,
366
524
  `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
- },
525
+ (() => {
526
+ const near = same ? [same] : nearest(slug, have);
527
+ // A theme near the name comes first; a new theme of the name as
528
+ // typed only after.
529
+ return {
530
+ didYouMean: near,
531
+ run: same
532
+ ? [`${P} show ${same}`]
533
+ : near.length
534
+ ? [`${P} show ${near[0]}`, `${P} new ${slug}`]
535
+ : [`${P} new ${slug}`],
536
+ };
537
+ })(),
371
538
  );
372
539
  }
373
540
  refuseLinks(cwd, slug);
541
+ // A file of the theme that is a folder or cannot be read is named, never
542
+ // called damaged.
543
+ refuseUnreadableFiles(cwd, slug);
374
544
  // undo is offered only when there is a step to go back to.
375
545
  const steps = readHistory(f.history).steps.length;
376
546
  const recover = steps
@@ -472,22 +642,73 @@ export function loadTheme(
472
642
  );
473
643
  }
474
644
  // A bad mode or base is fixed by setting it.
645
+ // A value written in other letters (Dark-Only, Neutral) is the one meant.
646
+ const modeMeant = String(data?.mode ?? '')
647
+ .trim()
648
+ .toLowerCase();
649
+ const likeMeant = String(data?.like ?? '')
650
+ .trim()
651
+ .toLowerCase();
475
652
  const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
476
- ? `${P} set ${slug} mode both`
653
+ ? `${P} set ${slug} mode ${['both', 'light-only', 'dark-only'].includes(modeMeant) ? modeMeant : 'both'}`
477
654
  : /^base "/.test(problem ?? '')
478
- ? `${P} set ${slug} base none`
655
+ ? `${P} set ${slug} base ${LIKE.includes(likeMeant) && baseInstalled(cwd, likeMeant) ? likeMeant : 'none'}`
479
656
  : null;
657
+ // A setting listed twice: setting it to one of its values, or undoing
658
+ // it, keeps one entry or none.
659
+ const twice = problem?.includes(' is listed twice (')
660
+ ? duplicated(data)
661
+ : null;
480
662
  if (problem)
481
663
  throw new AstryxError(
482
- `themes/${slug}/${slug}.settings.json: ${problem}. ${fieldFix ? 'Set it again' : `Fix it by hand${recover.text}`}. Nothing was changed.`,
664
+ `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
665
  fieldFix
484
666
  ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
485
- : recover.run,
667
+ : twice
668
+ ? [
669
+ ...twice.values
670
+ .filter(
671
+ v =>
672
+ typeof v === 'string' &&
673
+ !valueProblem({...twice.setting, value: v}),
674
+ )
675
+ .slice(0, 2)
676
+ .map(v => ({
677
+ name: `${P} set ${slug} ${undoArgs(twice.setting).replace(twice.setting.thing, `${twice.setting.thing} ${quoteCommandArgument(String(v))}`)}`,
678
+ reason: `keep ${v}`,
679
+ })),
680
+ {
681
+ name: `${P} undo ${slug} ${undoArgs(twice.setting)}`,
682
+ reason: 'remove both',
683
+ },
684
+ ...recover.run,
685
+ ]
686
+ : recover.run,
486
687
  ERROR_CODES.ERR_THEME_INVALID,
487
688
  );
488
689
  return data;
489
690
  }
490
691
 
692
+ /**
693
+ * The first setting listed more than once, with every value it is listed
694
+ * with, in order.
695
+ * @param {any} data
696
+ * @returns {{setting: any, values: unknown[]} | null}
697
+ */
698
+ function duplicated(data) {
699
+ /** @type {Map<string, any[]>} */
700
+ const byKey = new Map();
701
+ for (const s of data.settings ?? []) {
702
+ if (!s || typeof s.thing !== 'string') continue;
703
+ const key = keyOf(s);
704
+ byKey.set(key, [...(byKey.get(key) ?? []), s]);
705
+ }
706
+ for (const list of byKey.values())
707
+ if (list.length > 1)
708
+ return {setting: list[0], values: [...new Set(list.map(x => x.value))]};
709
+ return null;
710
+ }
711
+
491
712
  /**
492
713
  * What is wrong with settings data, or null: its shape, and each value with
493
714
  * the same rules `set` checks it by (without the installed Core), so a value
@@ -513,7 +734,15 @@ export function settingsProblem(
513
734
  if (!field && data.like != null && !LIKE.includes(data.like))
514
735
  return `base "${data.like}" is not a built-in theme (${LIKE.join(', ')})`;
515
736
  if (!Array.isArray(data.settings)) return 'settings is not a list';
516
- const keys = new Set();
737
+ // `lifted` is written by the build: a list of text, or absent.
738
+ if (
739
+ data.lifted != null &&
740
+ (!Array.isArray(data.lifted) ||
741
+ data.lifted.some((/** @type {unknown} */ x) => typeof x !== 'string'))
742
+ )
743
+ 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)`;
744
+ /** @type {Map<string, any>} */
745
+ const keys = new Map();
517
746
  for (const s of data.settings) {
518
747
  // A value or scope that is not text is a bad setting `undo` removes;
519
748
  // a setting with no name is damage.
@@ -524,8 +753,11 @@ export function settingsProblem(
524
753
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
525
754
  return `${s.thing} has mode "${s.mode}"`;
526
755
  const key = keyOf(s);
527
- if (keys.has(key)) return `${describe(s)} is listed twice`;
528
- keys.add(key);
756
+ // The command that changes or removes a setting listed twice keeps one
757
+ // value, or none, so it fixes the list.
758
+ if (keys.has(key) && !skips(s, skip))
759
+ return `${describe({...s, value: '?'}).replace(' = ?', '')} is listed twice (${JSON.stringify(keys.get(key).value)}, ${JSON.stringify(s.value)})`;
760
+ keys.set(key, s);
529
761
  if (skips(s, skip)) continue;
530
762
  const problem = valueProblem(s);
531
763
  if (problem) return problem;
@@ -636,6 +868,12 @@ export function valueProblem(s) {
636
868
  if (s.source !== 'dial') return null;
637
869
  const d = DIALS[s.thing];
638
870
  if (!d) return `${s.thing} is not a dial`;
871
+ // A color dial needs a fixed opaque seed, as `set` checks it: a
872
+ // see-through, system or variable color generates no shades.
873
+ if (PALETTE_DIALS.includes(s.thing) && isColorValue(s.value)) {
874
+ const seed = colorProblem(s.value);
875
+ if (seed) return `${bad} ${seed.message}`;
876
+ }
639
877
  const words = d.values.split('|').filter(w => !w.startsWith('<'));
640
878
  const ok =
641
879
  s.thing === 'corners'
@@ -658,6 +896,209 @@ export function valueProblem(s) {
658
896
  return null;
659
897
  }
660
898
 
899
+ /**
900
+ * The page-wide tokens a theme's own source sets: the keys of the top-level
901
+ * `tokens` map in its `defineTheme({...})`, read from the syntax tree, each
902
+ * with its value when that is plain text (else null). A token set only in a
903
+ * scope (`onDark`, `components`) is not one: it does not apply page-wide.
904
+ * @param {string} cwd
905
+ * @param {string} slug
906
+ * @returns {Map<string, string | null>}
907
+ */
908
+ function ownPageTokens(cwd, slug) {
909
+ /** @type {Map<string, string | null>} */
910
+ const out = new Map();
911
+ /** @type {string} */
912
+ let code;
913
+ try {
914
+ code = fs.readFileSync(themeFiles(cwd, slug).ts, 'utf8');
915
+ } catch {
916
+ return out;
917
+ }
918
+ /** @type {any} */
919
+ let ast;
920
+ try {
921
+ ast = parseModule(code, {sourceType: 'module', plugins: ['typescript']});
922
+ } catch {
923
+ return out;
924
+ }
925
+ /** @param {any} node @returns {string | null} */
926
+ const keyOf = node =>
927
+ node?.type === 'StringLiteral'
928
+ ? node.value
929
+ : node?.type === 'Identifier'
930
+ ? node.name
931
+ : null;
932
+ /** @param {any} node @returns {string | null} */
933
+ const textOf = node =>
934
+ node?.type === 'StringLiteral'
935
+ ? node.value
936
+ : node?.type === 'TemplateLiteral' && node.expressions.length === 0
937
+ ? node.quasis.map((/** @type {any} */ q) => q.value.cooked).join('')
938
+ : null;
939
+ // Every const binding in the file, by name, so a value given by name
940
+ // (tokens: mine, ...mine) is read as written.
941
+ /** @type {Map<string, any>} */
942
+ const consts = new Map();
943
+ /** @type {any[]} */
944
+ const calls = [];
945
+ /** @param {any} node @param {any} owner the exported name, when exported */
946
+ const visit = (node, owner = null) => {
947
+ if (!node || typeof node !== 'object') return;
948
+ if (node.type === 'VariableDeclarator' && node.id?.type === 'Identifier')
949
+ consts.set(node.id.name, node.init);
950
+ if (
951
+ node.type === 'CallExpression' &&
952
+ node.callee?.type === 'Identifier' &&
953
+ node.callee.name === 'defineTheme' &&
954
+ node.arguments?.[0]
955
+ )
956
+ calls.push({call: node, owner});
957
+ for (const [k, v] of Object.entries(node)) {
958
+ const nextOwner =
959
+ node.type === 'VariableDeclarator' && k === 'init'
960
+ ? (node.id?.name ?? owner)
961
+ : node.type === 'ExportDefaultDeclaration'
962
+ ? 'default'
963
+ : owner;
964
+ if (Array.isArray(v)) v.forEach(c => visit(c, nextOwner));
965
+ else if (v && typeof v === 'object' && v.type) visit(v, nextOwner);
966
+ }
967
+ };
968
+ visit(ast.program);
969
+ /** @param {any} node @param {number} [depth] @returns {any} */
970
+ const unwrap = (node, depth = 0) => {
971
+ if (!node || depth > 20) return null;
972
+ if (
973
+ [
974
+ 'TSAsExpression',
975
+ 'TSSatisfiesExpression',
976
+ 'TSNonNullExpression',
977
+ 'TSTypeAssertion',
978
+ 'ParenthesizedExpression',
979
+ ].includes(node.type)
980
+ )
981
+ return unwrap(node.expression, depth + 1);
982
+ if (node.type === 'Identifier' && consts.has(node.name))
983
+ return unwrap(consts.get(node.name), depth + 1);
984
+ return node;
985
+ };
986
+ // The theme the build loads: the defineTheme that names it, else the one
987
+ // exported as <camel>Theme or by default, else the only one.
988
+ const named = calls.find(({call}) => {
989
+ const obj = unwrap(call.arguments[0]);
990
+ return (
991
+ obj?.type === 'ObjectExpression' &&
992
+ obj.properties.some(
993
+ (/** @type {any} */ p) =>
994
+ p.type === 'ObjectProperty' &&
995
+ keyOf(p.key) === 'name' &&
996
+ textOf(unwrap(p.value)) === slug,
997
+ )
998
+ );
999
+ });
1000
+ const chosen =
1001
+ named ??
1002
+ calls.find(
1003
+ c => c.owner === `${camel(slug)}Theme` || c.owner === 'default',
1004
+ ) ??
1005
+ (calls.length === 1 ? calls[0] : null);
1006
+ if (!chosen) return out;
1007
+ const def = unwrap(chosen.call.arguments[0]);
1008
+ if (def?.type !== 'ObjectExpression') return out;
1009
+ const tokensProp = def.properties.find(
1010
+ (/** @type {any} */ p) =>
1011
+ p.type === 'ObjectProperty' && !p.computed && keyOf(p.key) === 'tokens',
1012
+ );
1013
+ if (!tokensProp) return out;
1014
+ let unresolved = false;
1015
+ /** @param {any} node @param {number} depth */
1016
+ const collect = (node, depth) => {
1017
+ const obj = unwrap(node);
1018
+ if (obj?.type !== 'ObjectExpression' || depth > 20) {
1019
+ unresolved = true;
1020
+ return;
1021
+ }
1022
+ // Spreads and keys merge in order: a later one wins.
1023
+ for (const p of obj.properties) {
1024
+ if (p.type === 'SpreadElement') collect(p.argument, depth + 1);
1025
+ else if (p.type === 'ObjectProperty' && !p.computed) {
1026
+ const k = keyOf(p.key);
1027
+ if (k?.startsWith('--')) out.set(k, textOf(unwrap(p.value)));
1028
+ } else unresolved = true;
1029
+ }
1030
+ };
1031
+ collect(tokensProp.value, 0);
1032
+ // A value no read of the file can resolve (a call, an import): the
1033
+ // built theme's own top-level tokens, which the build evaluated.
1034
+ if (unresolved)
1035
+ for (const [k, v] of builtTopTokens(cwd, slug))
1036
+ if (!out.has(k)) out.set(k, v);
1037
+ return out;
1038
+ }
1039
+
1040
+ /**
1041
+ * The top-level tokens of a theme's built module (<slug>.js), which the
1042
+ * build wrote as plain data, or an empty map.
1043
+ * @param {string} cwd
1044
+ * @param {string} slug
1045
+ * @returns {Map<string, string | null>}
1046
+ */
1047
+ function builtTopTokens(cwd, slug) {
1048
+ /** @type {Map<string, string | null>} */
1049
+ const out = new Map();
1050
+ try {
1051
+ const ast = /** @type {any} */ (
1052
+ parseModule(fs.readFileSync(themeFiles(cwd, slug).js, 'utf8'), {
1053
+ sourceType: 'module',
1054
+ })
1055
+ );
1056
+ for (const st of ast.program.body) {
1057
+ const decl = st.declaration?.declarations?.[0];
1058
+ const obj = decl?.init;
1059
+ if (obj?.type !== 'ObjectExpression') continue;
1060
+ const tokens = obj.properties.find(
1061
+ (/** @type {any} */ p) =>
1062
+ (p.key?.name ?? p.key?.value) === 'tokens' &&
1063
+ p.value?.type === 'ObjectExpression',
1064
+ );
1065
+ for (const p of tokens?.value.properties ?? []) {
1066
+ const k = p.key?.value ?? p.key?.name;
1067
+ if (typeof k === 'string' && k.startsWith('--'))
1068
+ out.set(k, p.value?.type === 'StringLiteral' ? p.value.value : null);
1069
+ }
1070
+ }
1071
+ } catch {
1072
+ // No build yet, or not one this reads.
1073
+ }
1074
+ return out;
1075
+ }
1076
+
1077
+ /**
1078
+ * The page-wide tokens a theme's own source sets itself (the top-level
1079
+ * `tokens` of its `defineTheme`): they win over the settings it extends.
1080
+ * @param {string} cwd
1081
+ * @param {string} slug
1082
+ * @returns {string[]}
1083
+ */
1084
+ export function ownSourceTokens(cwd, slug) {
1085
+ return [...ownPageTokens(cwd, slug).keys()];
1086
+ }
1087
+
1088
+ /**
1089
+ * The values a theme's own source gives page-wide tokens as plain text
1090
+ * (`'--radius-page': 'var(--radius-element)'`), by token.
1091
+ * @param {string} cwd
1092
+ * @param {string} slug
1093
+ * @returns {Record<string, string>}
1094
+ */
1095
+ export function ownSourceTokenValues(cwd, slug) {
1096
+ /** @type {Record<string, string>} */
1097
+ const out = {};
1098
+ for (const [k, v] of ownPageTokens(cwd, slug)) if (v != null) out[k] = v;
1099
+ return out;
1100
+ }
1101
+
661
1102
  /**
662
1103
  * What is wrong with where a setting applies, or null: names only, as
663
1104
  * `set` takes them.
@@ -723,7 +1164,11 @@ export {modesOf};
723
1164
  * @returns {number | null}
724
1165
  */
725
1166
  export function lengthPx(v) {
726
- const m = /^\s*(-?\d+(?:\.\d+)?|-?\.\d+)\s*(px|rem|em)?\s*$/i.exec(String(v));
1167
+ // A CSS number: a sign, digits with or without a fraction, an exponent.
1168
+ const m =
1169
+ /^\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)\s*(px|rem|em)?\s*$/i.exec(
1170
+ String(v),
1171
+ );
727
1172
  if (!m) return null;
728
1173
  const n = Number(m[1]);
729
1174
  return (m[2] ?? 'px').toLowerCase() === 'px' ? n : n * 16;
@@ -1000,10 +1445,239 @@ export function compileTheme(ctx, data, base) {
1000
1445
  if (tg?.states.includes(s.state) && s.when == null) b = t[s.state] ??= {};
1001
1446
  else if (tg?.states.includes(s.state))
1002
1447
  b = t[`${s.when}+${s.state}`] ??= {};
1003
- else b = b[stateKey(s.state)] ??= {};
1448
+ else b = b[stateKey(s.state, wrapsOneControl(ctx, target))] ??= {};
1004
1449
  }
1005
1450
  return b;
1006
1451
  };
1452
+ /**
1453
+ * A padding on a part whose padding Core writes one variable per side
1454
+ * (its derivedVarRegistry's container expansion), as each side's value,
1455
+ * split at top-level spaces by the CSS shorthand rules: Core splits a
1456
+ * shorthand at every space, which cuts calc(4px + 2px) and loses a
1457
+ * fourth value. On the part itself the sides go as logical longhands,
1458
+ * which Core carries as they are; for a variant or state they go to the
1459
+ * side variables themselves, since Core writes one variable for equal
1460
+ * sides there and the part's own side variables would win over it.
1461
+ * Null for any other property or part.
1462
+ * @param {string} target @param {Setting} s
1463
+ * @returns {Record<string, string> | null}
1464
+ */
1465
+ const containerSides = (target, s) => {
1466
+ const prop = kebab(s.thing);
1467
+ if (
1468
+ s.mode ||
1469
+ !/^padding(-block|-inline|-left|-right|-top|-bottom|-block-start|-block-end|-inline-start|-inline-end)?$/.test(
1470
+ prop,
1471
+ )
1472
+ )
1473
+ return null;
1474
+ if (
1475
+ !(ctx.derived?.[target] ?? []).some(
1476
+ d => d.property === 'padding' && d.expand,
1477
+ )
1478
+ )
1479
+ return null;
1480
+ const scoped0 = s.when != null || s.state != null;
1481
+ // padding's initial value is 0, and padding does not inherit, so unset
1482
+ // is 0 too: on Core's side variables a keyword means no value at all.
1483
+ const value = /^(initial|unset)$/i.test(String(s.value).trim())
1484
+ ? '0'
1485
+ : String(s.value).trim();
1486
+ // A physical left or right stays physical, as Core keeps it (it maps
1487
+ // no physical side to a logical one but top and bottom, which it maps
1488
+ // itself): it is written as it is, and a later padding that covers it
1489
+ // takes it out of the block (below).
1490
+ const physical = /** @type {Record<string, string>} */ ({
1491
+ // One logical side is that side (its keyword resolved too).
1492
+ 'padding-block-start': 'block-start',
1493
+ 'padding-block-end': 'block-end',
1494
+ 'padding-inline-start': 'inline-start',
1495
+ 'padding-inline-end': 'inline-end',
1496
+ 'padding-top': 'block-start',
1497
+ 'padding-bottom': 'block-end',
1498
+ })[prop];
1499
+ if (physical)
1500
+ return {
1501
+ [scoped0
1502
+ ? `--astryx-${target}-padding-${physical}`
1503
+ : camel(`padding-${physical}`)]: value,
1504
+ };
1505
+ // A physical left or right is written as it is (its keyword resolved),
1506
+ // never split as an axis: there is no padding-left-start.
1507
+ if (prop === 'padding-left' || prop === 'padding-right')
1508
+ return {[camel(prop)]: value};
1509
+ const w = splitTop(value, ' ').map(x => x.trim());
1510
+ if (!w.length || w.length > (prop === 'padding' ? 4 : 2)) return null;
1511
+ const scoped = s.when != null || s.state != null;
1512
+ // Only what Core would split wrong is written side by side: math or a
1513
+ // function, four values with different left and right sides; and, for
1514
+ // a variant or state, any padding once the part sets a side itself.
1515
+ const coreSplitsWrong =
1516
+ value !== String(s.value).trim() ||
1517
+ /\(/.test(value) ||
1518
+ (prop === 'padding' && w.length === 4 && w[1] !== w[3]);
1519
+ const partSides = data.settings.some(
1520
+ x =>
1521
+ x !== s &&
1522
+ x.source === 'property' &&
1523
+ // The part's own, or a group's it is in.
1524
+ (x.on === s.on ||
1525
+ (FAMILIES[/** @type {string} */ (x.on)] ?? []).includes(target)) &&
1526
+ x.when == null &&
1527
+ x.state == null &&
1528
+ (/^padding-/.test(kebab(x.thing)) ||
1529
+ (kebab(x.thing) === 'padding' &&
1530
+ /\(|\S+\s+\S+\s+\S+\s+\S+/.test(x.value))),
1531
+ );
1532
+ // A side set on the part or its group: every side is written, so the
1533
+ // later setting wins as written.
1534
+ if (!coreSplitsWrong && !partSides) return null;
1535
+ /** @type {Record<string, string>} */
1536
+ const side = {};
1537
+ if (prop === 'padding') {
1538
+ const [top, right = top, bottom = top, left = right] = w;
1539
+ Object.assign(side, {
1540
+ 'block-start': top,
1541
+ 'inline-end': right,
1542
+ 'block-end': bottom,
1543
+ 'inline-start': left,
1544
+ });
1545
+ } else {
1546
+ const axis = prop.slice('padding-'.length);
1547
+ side[`${axis}-start`] = w[0];
1548
+ side[`${axis}-end`] = w[1] ?? w[0];
1549
+ }
1550
+ return Object.fromEntries(
1551
+ Object.entries(side).map(([k, v]) => [
1552
+ scoped ? `--astryx-${target}-padding-${k}` : camel(`padding-${k}`),
1553
+ v,
1554
+ ]),
1555
+ );
1556
+ };
1557
+ /**
1558
+ * A radius of more than one value on a part whose radius Core copies
1559
+ * into a variable for the content inside it (a card's full-bleed
1560
+ * children), as each corner's own radius, so Core writes no copy of the
1561
+ * whole value there (where one corner reads it, and `10px / 20px` or four
1562
+ * values are wrong). The inner variable takes one radius, the first
1563
+ * corner's across: Core gives the content one radius for every corner.
1564
+ * Null for any other property, part or a single radius.
1565
+ * @param {string} target @param {Setting} s
1566
+ * @returns {Record<string, string> | null}
1567
+ */
1568
+ const cornerRadii = (target, s) => {
1569
+ if (s.mode || kebab(s.thing) !== 'border-radius') return null;
1570
+ const vars = (ctx.derived?.[target] ?? []).find(
1571
+ d => d.property === 'borderRadius' && d.vars?.length,
1572
+ )?.vars;
1573
+ if (!vars) return null;
1574
+ const [across, down] = splitTop(String(s.value).trim(), '/').map(x =>
1575
+ splitTop(x.trim(), ' ').map(y => y.trim()),
1576
+ );
1577
+ if (!across?.length || (across.length === 1 && !down)) return null;
1578
+ /** @param {string[]} w top-left, top-right, bottom-right, bottom-left */
1579
+ const four = w => {
1580
+ const [tl, tr = tl, br = tl, bl = tr] = w;
1581
+ return [tl, tr, br, bl];
1582
+ };
1583
+ const h = four(across);
1584
+ const v = down?.length ? four(down) : null;
1585
+ const corner = (/** @type {number} */ i) =>
1586
+ v && v[i] !== h[i] ? `${h[i]} ${v[i]}` : h[i];
1587
+ return {
1588
+ borderTopLeftRadius: corner(0),
1589
+ borderTopRightRadius: corner(1),
1590
+ borderBottomRightRadius: corner(2),
1591
+ borderBottomLeftRadius: corner(3),
1592
+ ...Object.fromEntries(vars.map(name => [name, h[0]])),
1593
+ };
1594
+ };
1595
+ /**
1596
+ * A one-side logical padding on a part whose whole padding Core copies
1597
+ * into a variable of its own (a composer's or a menu's inner padding),
1598
+ * written for each direction (a left-to-right box's left is a
1599
+ * right-to-left box's right): Core feeds every logical padding into that
1600
+ * variable, so one side would set the whole box. Null for any other
1601
+ * property or part.
1602
+ * @param {string} target @param {Setting} s
1603
+ * @returns {Record<string, string | Record<string, string>> | null}
1604
+ */
1605
+ const boxSides = (target, s) => {
1606
+ const prop = kebab(s.thing);
1607
+ if (s.mode) return null;
1608
+ const derived = ctx.derived?.[target] ?? [];
1609
+ if (
1610
+ derived.some(d => d.property === 'padding' && d.expand) ||
1611
+ !derived.some(d => d.property === 'padding' && d.vars?.length)
1612
+ )
1613
+ return null;
1614
+ const SIDES = /** @type {Record<string, string[]>} */ ({
1615
+ 'padding-block-start': ['block-start'],
1616
+ 'padding-block-end': ['block-end'],
1617
+ 'padding-inline-start': ['inline-start'],
1618
+ 'padding-inline-end': ['inline-end'],
1619
+ 'padding-block': ['block-start', 'block-end'],
1620
+ 'padding-inline': ['inline-start', 'inline-end'],
1621
+ });
1622
+ const sides = SIDES[prop];
1623
+ if (!sides) return null;
1624
+ const w = splitTop(String(s.value).trim(), ' ').map(x => x.trim());
1625
+ // Each side for each direction: a block side is the top or bottom; an
1626
+ // inline side is the left in a left-to-right box and the right in a
1627
+ // right-to-left one, written under :dir(), where Core writes the
1628
+ // declarations as they are and feeds none into the whole-box variable.
1629
+ /** @type {Record<string, string>} */
1630
+ const plain = {};
1631
+ /** @type {Record<string, string>} */
1632
+ const ltr = {};
1633
+ /** @type {Record<string, string>} */
1634
+ const rtl = {};
1635
+ sides.forEach((side, i) => {
1636
+ const v = w[i] ?? w[0];
1637
+ if (side === 'block-start') plain.paddingTop = v;
1638
+ else if (side === 'block-end') plain.paddingBottom = v;
1639
+ else if (side === 'inline-start') {
1640
+ ltr.paddingLeft = v;
1641
+ rtl.paddingRight = v;
1642
+ } else {
1643
+ ltr.paddingRight = v;
1644
+ rtl.paddingLeft = v;
1645
+ }
1646
+ });
1647
+ return {
1648
+ ...plain,
1649
+ ...(Object.keys(ltr).length ? {':dir(ltr)': ltr, ':dir(rtl)': rtl} : {}),
1650
+ };
1651
+ };
1652
+ /**
1653
+ * A padding on a part whose visible box sits inside its themed wrapper,
1654
+ * as the padding variable that box reads, not the wrapper's own padding
1655
+ * (which would add a gap outside the box). Null for any other part.
1656
+ * @param {string} target @param {Setting} s
1657
+ * @returns {Record<string, string> | null}
1658
+ */
1659
+ const wrappedPadding = (target, s) => {
1660
+ if (s.mode || !WRAPPED_PARTS[target] || kebab(s.thing) !== 'padding')
1661
+ return null;
1662
+ const name = (ctx.derived?.[target] ?? []).find(
1663
+ d => d.property === 'padding' && d.vars?.length,
1664
+ )?.vars?.[0];
1665
+ return name ? {[name]: String(s.value).trim()} : null;
1666
+ };
1667
+ /**
1668
+ * Where a per-direction rule goes for a setting, one level deep, as the
1669
+ * block and its key: in the setting's own block, or under a state Core
1670
+ * writes as a pseudo-class, beside that state with the direction after it.
1671
+ * @param {Setting} s @param {string} target @param {string} dir `:dir(ltr)`
1672
+ * @returns {[Record<string, any>, string]}
1673
+ */
1674
+ const dirBlock = (s, target, dir) => {
1675
+ const tg = ctx.project.target.get(target);
1676
+ if (!s.state || tg?.states.includes(s.state))
1677
+ return [block(s, target), dir];
1678
+ const parent = block({...s, state: undefined}, target);
1679
+ return [parent, `${stateKey(s.state, wrapsOneControl(ctx, target))}${dir}`];
1680
+ };
1007
1681
  /** @param {Setting} s @param {string} target @param {string} prop @param {string} v */
1008
1682
  const putComp = (s, target, prop, v) => {
1009
1683
  const b = block(s, target);
@@ -1256,7 +1930,79 @@ export function compileTheme(ctx, data, base) {
1256
1930
  if (parts.length) for (const t of parts) putComp(s, t, s.thing, s.value);
1257
1931
  else putTok(s.thing, s.value, s.mode);
1258
1932
  } else if (s.source === 'property') {
1259
- for (const t of parts) putComp(s, t, camel(s.thing), s.value);
1933
+ for (const t of parts) {
1934
+ const sides =
1935
+ wrappedPadding(t, s) ??
1936
+ containerSides(t, s) ??
1937
+ cornerRadii(t, s) ??
1938
+ boxSides(t, s);
1939
+ if (sides)
1940
+ for (const [k, v] of Object.entries(sides)) {
1941
+ // A per-direction block joins what that direction already has,
1942
+ // one level deep: under a state it is the state's own key with
1943
+ // the direction after it (`:hover:dir(ltr)`), which Core writes
1944
+ // as one rule.
1945
+ if (k.startsWith(':') && typeof v === 'object') {
1946
+ const [b, key] = dirBlock(s, t, k);
1947
+ b[key] = {...(b[key] ?? {}), ...v};
1948
+ } else putComp(s, t, k, /** @type {string} */ (v));
1949
+ }
1950
+ else putComp(s, t, camel(s.thing), s.value);
1951
+ // A later padding takes out what it covers that would beat it: a
1952
+ // physical side written as it is (a group's left under a later part
1953
+ // padding; left-to-right, inline-start is the left), and a side
1954
+ // written per direction, whose :dir() rule is more specific.
1955
+ {
1956
+ const prop = kebab(s.thing);
1957
+ /** @type {Record<string, Array<'paddingLeft' | 'paddingRight'>>} */
1958
+ const COVERS = {
1959
+ padding: ['paddingLeft', 'paddingRight'],
1960
+ 'padding-inline': ['paddingLeft', 'paddingRight'],
1961
+ 'padding-inline-start': ['paddingLeft'],
1962
+ 'padding-inline-end': ['paddingRight'],
1963
+ 'padding-left': [],
1964
+ 'padding-right': [],
1965
+ };
1966
+ const plain = COVERS[prop];
1967
+ if (plain) {
1968
+ const b = block(s, t);
1969
+ // A side written per direction leaves a physical side as it is:
1970
+ // its :dir(ltr) rule already wins in a left-to-right box, and in
1971
+ // a right-to-left one the physical left is still the left.
1972
+ const perDirection =
1973
+ !!sides && Object.keys(sides).some(x => x.startsWith(':'));
1974
+ if (!perDirection)
1975
+ for (const k of plain)
1976
+ if (b[k] != null && !(sides && k in sides)) delete b[k];
1977
+ // Per direction: a whole padding or inline padding covers both
1978
+ // sides in both directions; a physical side, that side in both.
1979
+ const dirSides =
1980
+ prop === 'padding' || prop === 'padding-inline'
1981
+ ? ['paddingLeft', 'paddingRight']
1982
+ : prop === 'padding-left'
1983
+ ? ['paddingLeft']
1984
+ : prop === 'padding-right'
1985
+ ? ['paddingRight']
1986
+ : [];
1987
+ if (
1988
+ dirSides.length &&
1989
+ !(sides && Object.keys(sides).some(x => x.startsWith(':')))
1990
+ )
1991
+ for (const d of [':dir(ltr)', ':dir(rtl)']) {
1992
+ const [db, key] = dirBlock(s, t, d);
1993
+ const rule = db[key];
1994
+ if (!rule) continue;
1995
+ for (const x of dirSides) delete rule[x];
1996
+ if (!Object.keys(rule).length) delete db[key];
1997
+ }
1998
+ }
1999
+ }
2000
+ // A part's own corner radii replace a single radius a group or an
2001
+ // earlier setting left in the same block, which Core would copy into
2002
+ // the content's radius after the editor's own.
2003
+ if (sides && 'borderTopLeftRadius' in sides)
2004
+ delete block(s, t).borderRadius;
2005
+ }
1260
2006
  }
1261
2007
  }
1262
2008
  // Core gives headings the body font when a theme sets only the body's:
@@ -1323,8 +2069,9 @@ export function compileTheme(ctx, data, base) {
1323
2069
  theme.tokens[k] = l === d ? l : [l, d];
1324
2070
  }
1325
2071
  // 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.
2072
+ // below the lg width); an exact font family or weight, and the headings
2073
+ // dial's weights, are written there too, so they apply on every screen.
2074
+ // Sizes are not: phones keep their reading base.
1328
2075
  const phone = Object.fromEntries(
1329
2076
  data.settings
1330
2077
  .filter(
@@ -1332,12 +2079,18 @@ export function compileTheme(ctx, data, base) {
1332
2079
  x.source === 'token' &&
1333
2080
  !x.on &&
1334
2081
  !x.mode &&
1335
- // Families only: phones keep their own reading sizes.
1336
- /^--font-family/.test(x.thing) &&
2082
+ /^--font-family|^--(text-[a-z0-9-]+|font)-weight/.test(x.thing) &&
1337
2083
  !(modeOnly && x.mode && x.mode !== modeOnly),
1338
2084
  )
1339
2085
  .map(x => [x.thing, x.value]),
1340
2086
  );
2087
+ // The headings dial's weights, unless an exact token sets one.
2088
+ const headingsWeight = [...data.settings]
2089
+ .reverse()
2090
+ .find(x => x.thing === 'headings' && x.axis !== 'tracking' && !x.on);
2091
+ if (headingsWeight && HEADING_WEIGHTS[headingsWeight.value])
2092
+ for (const k of headingWeightTokens)
2093
+ phone[k] ??= HEADING_WEIGHTS[headingsWeight.value];
1341
2094
  if (Object.keys(phone).length)
1342
2095
  theme.adaptations = {
1343
2096
  rules: [
@@ -1367,9 +2120,10 @@ const SMALL_STEPS = /** @type {Array<[string, number]>} */ ([
1367
2120
  * Settings whose effect a later or stronger setting hides, with why: `type`
1368
2121
  * loses heading weight and tracking to `headings`.
1369
2122
  * @param {ThemeData} data
2123
+ * @param {Ctx | null} [ctx] with it, a later setting that reaches the parts through a spread counts too
1370
2124
  * @returns {Map<Setting, string>}
1371
2125
  */
1372
- export function maskedSettings(data) {
2126
+ export function maskedSettings(data, ctx = null) {
1373
2127
  /** @type {Map<Setting, string>} */
1374
2128
  const out = new Map();
1375
2129
  const axes = new Set(
@@ -1409,6 +2163,37 @@ export function maskedSettings(data) {
1409
2163
  `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
1410
2164
  );
1411
2165
  });
2166
+ // With the parts known: a later setting of the same thing that reaches
2167
+ // every part an earlier one styles (a member that spreads to its group,
2168
+ // the same part without --only), dial or CSS property, covers it too.
2169
+ if (ctx)
2170
+ data.settings.forEach((s, i) => {
2171
+ if (
2172
+ out.has(s) ||
2173
+ !s.on ||
2174
+ (s.source !== 'dial' && s.source !== 'property')
2175
+ )
2176
+ return;
2177
+ const mine = partsOf(ctx, s);
2178
+ if (!mine.length) return;
2179
+ const later = data.settings
2180
+ .slice(i + 1)
2181
+ .find(
2182
+ x =>
2183
+ x.thing === s.thing &&
2184
+ x.source === s.source &&
2185
+ x.on &&
2186
+ (x.when ?? '') === (s.when ?? '') &&
2187
+ (x.state ?? '') === (s.state ?? '') &&
2188
+ (x.mode ?? '') === (s.mode ?? '') &&
2189
+ mine.every(t => partsOf(ctx, x).includes(t)),
2190
+ );
2191
+ if (later)
2192
+ out.set(
2193
+ s,
2194
+ `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
2195
+ );
2196
+ });
1412
2197
  for (const s of data.settings) {
1413
2198
  if (s.thing !== 'type' || !axes.size) continue;
1414
2199
  const T = TYPE_STYLES[s.value];
@@ -1448,16 +2233,13 @@ export function findOverrides(cssText, theme) {
1448
2233
  'g',
1449
2234
  );
1450
2235
  // 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$/;
2236
+ // (background after background-color) is the one in effect. Which
2237
+ // longhands a shorthand sets is MDN's data (background-blend-mode is
2238
+ // no part of background).
1456
2239
  /** @param {string} a @param {string} b */
1457
2240
  const sameProperty = (a, b) => {
1458
2241
  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;
2242
+ return x === y || coversProperty(x, y) || coversProperty(y, x);
1461
2243
  };
1462
2244
  const last = props.filter(
1463
2245
  (p, i) => !props.slice(i + 1).some(later => sameProperty(later, p)),
@@ -1592,6 +2374,12 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1592
2374
  [
1593
2375
  `// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
1594
2376
  `// Built from settings ${settingsStamp(data)}.`,
2377
+ // The theme source as it is when the build starts (the editor's
2378
+ // own when the build writes it), so an own change to it after the
2379
+ // build is told by content.
2380
+ ...(cwd
2381
+ ? [`// Built with ${slug}.theme.ts ${themeSourceHash(cwd, slug)}.`]
2382
+ : []),
1595
2383
  ...(like && cwd
1596
2384
  ? [
1597
2385
  `// Built on @astryxdesign/theme-${like} ${baseVersionOf(cwd, like) ?? 'unknown'}.`,
@@ -1615,6 +2403,114 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1615
2403
  );
1616
2404
  }
1617
2405
 
2406
+ /**
2407
+ * A hash of a theme's source file as the next build reads it: the file, or
2408
+ * the source the editor writes when there is none.
2409
+ * @param {string} cwd
2410
+ * @param {string} slug
2411
+ */
2412
+ function themeSourceHash(cwd, slug) {
2413
+ const f = themeFiles(cwd, slug);
2414
+ const hash = createHash('sha256');
2415
+ if (!fs.existsSync(f.ts)) {
2416
+ // The same as the file the build is about to write would hash.
2417
+ hash.update(`${path.basename(f.ts)}\0`);
2418
+ hash.update(themeModuleSource(slug));
2419
+ return hash.digest('hex').slice(0, 16);
2420
+ }
2421
+ // The theme source and every local module it reaches (an own helper
2422
+ // such as ./my-tokens), read the way theme discovery reads them; the
2423
+ // editor's generated modules change with each build and are judged by
2424
+ // their own stamps.
2425
+ const generated = new Set([f.settingsTs]);
2426
+ const seen = new Set();
2427
+ const queue = [f.ts];
2428
+ while (queue.length) {
2429
+ const file = /** @type {string} */ (queue.shift());
2430
+ if (seen.has(file)) continue;
2431
+ seen.add(file);
2432
+ hash.update(`${path.relative(f.dir, file)}\0`);
2433
+ hash.update(fs.readFileSync(file));
2434
+ /** @type {string[]} */
2435
+ let specifiers = [];
2436
+ try {
2437
+ specifiers = themeFileImports(file, {withRequire: true});
2438
+ } catch {
2439
+ // A file that does not parse is hashed as it is; the build names it.
2440
+ }
2441
+ for (const spec of specifiers) {
2442
+ if (!spec.startsWith('.')) continue;
2443
+ const target = localModuleFile(path.dirname(file), spec);
2444
+ // Only the editor's own generated palette files are judged by their
2445
+ // stamps; any other file the theme reaches, in tokens/ too, is the
2446
+ // person's.
2447
+ if (
2448
+ target &&
2449
+ !generated.has(target) &&
2450
+ !isGeneratedPaletteFile(f.dir, slug, target)
2451
+ )
2452
+ queue.push(target);
2453
+ }
2454
+ }
2455
+ return hash.digest('hex').slice(0, 16);
2456
+ }
2457
+
2458
+ /** The extensions a theme's local module may have, as the build reads them. */
2459
+ const MODULE_EXTENSIONS = [
2460
+ '.ts',
2461
+ '.tsx',
2462
+ '.mts',
2463
+ '.cts',
2464
+ '.js',
2465
+ '.jsx',
2466
+ '.mjs',
2467
+ '.cjs',
2468
+ ];
2469
+
2470
+ /**
2471
+ * The file a relative import names, resolved as TypeScript resolves it: a
2472
+ * JavaScript extension names its TypeScript source (`.js` → `.ts`/`.tsx`,
2473
+ * `.jsx` → `.tsx`, `.mjs` → `.mts`, `.cjs` → `.cts`), then the path as
2474
+ * written, with each module extension, and as a folder's index file.
2475
+ * @param {string} dir
2476
+ * @param {string} spec
2477
+ * @returns {string | undefined}
2478
+ */
2479
+ function localModuleFile(dir, spec) {
2480
+ const base = path.resolve(dir, spec);
2481
+ const ext = path.extname(base);
2482
+ const stem = base.slice(0, base.length - ext.length);
2483
+ const sourceFor = /** @type {Record<string, string[]>} */ ({
2484
+ '.js': ['.ts', '.tsx'],
2485
+ '.jsx': ['.tsx'],
2486
+ '.mjs': ['.mts'],
2487
+ '.cjs': ['.cts'],
2488
+ })[ext];
2489
+ return [
2490
+ ...(sourceFor ?? []).map(x => stem + x),
2491
+ base,
2492
+ ...MODULE_EXTENSIONS.map(x => base + x),
2493
+ ...MODULE_EXTENSIONS.map(x => path.join(base, `index${x}`)),
2494
+ ].find(p => fs.existsSync(p) && fs.statSync(p).isFile());
2495
+ }
2496
+
2497
+ /**
2498
+ * Whether a file is one of the palette files the editor generates in a
2499
+ * theme's tokens/ folder (`tokens/<slug>.palette*`).
2500
+ * @param {string} dir the theme folder
2501
+ * @param {string} slug
2502
+ * @param {string} file
2503
+ */
2504
+ function isGeneratedPaletteFile(dir, slug, file) {
2505
+ const rel = path.relative(path.join(dir, 'tokens'), file);
2506
+ return (
2507
+ !rel.startsWith('..') &&
2508
+ !path.isAbsolute(rel) &&
2509
+ !rel.includes(path.sep) &&
2510
+ rel.startsWith(`${slug}.palette`)
2511
+ );
2512
+ }
2513
+
1618
2514
  /**
1619
2515
  * The theme module, written once: it extends the generated settings and is
1620
2516
  * the person's own from then on, so hand edits in it survive every change.
@@ -1666,6 +2562,52 @@ export function themeSourceProblem(cwd, slug) {
1666
2562
  return null;
1667
2563
  }
1668
2564
 
2565
+ /**
2566
+ * Why the person's own theme source does not parse (its line and the
2567
+ * parser's message), or null when it parses or is not there.
2568
+ * @param {string} cwd
2569
+ * @param {string} slug
2570
+ * @returns {string | null}
2571
+ */
2572
+ export function themeSourceParseError(cwd, slug) {
2573
+ const f = themeFiles(cwd, slug);
2574
+ let code;
2575
+ try {
2576
+ code = fs.readFileSync(f.ts, 'utf8');
2577
+ } catch {
2578
+ return null;
2579
+ }
2580
+ try {
2581
+ parseModule(code, {sourceType: 'module', plugins: ['typescript']});
2582
+ return null;
2583
+ } catch (e) {
2584
+ const err = /** @type {any} */ (e);
2585
+ return `${slug}.theme.ts does not parse${err?.loc?.line ? ` (line ${err.loc.line})` : ''}: ${String(err?.message ?? e).replace(/\s*\(\d+:\d+\)\s*$/, '')}`;
2586
+ }
2587
+ }
2588
+
2589
+ /**
2590
+ * Refuse, before anything is written or removed, a command whose build
2591
+ * would load the person's own theme source when it does not parse: the
2592
+ * build would fail part way.
2593
+ * @param {string} cwd
2594
+ * @param {string} slug
2595
+ */
2596
+ export function refuseThemeParse(cwd, slug) {
2597
+ const why = themeSourceParseError(cwd, slug);
2598
+ if (why)
2599
+ throw new AstryxError(
2600
+ `${why}, so the theme cannot build. It is your own file: fix it, then run the command again. Nothing was changed.`,
2601
+ [
2602
+ {
2603
+ name: `cat ${path.posix.join('themes', slug, `${slug}.theme.ts`)}`,
2604
+ reason: 'see the file',
2605
+ },
2606
+ ],
2607
+ ERROR_CODES.ERR_THEME_INVALID,
2608
+ );
2609
+ }
2610
+
1669
2611
  /**
1670
2612
  * Refuse a build whose theme source cannot carry the settings, naming the
1671
2613
  * lines that put it back.
@@ -1673,6 +2615,7 @@ export function themeSourceProblem(cwd, slug) {
1673
2615
  * @param {string} slug
1674
2616
  */
1675
2617
  export function refuseThemeSource(cwd, slug) {
2618
+ refuseThemeParse(cwd, slug);
1676
2619
  const why = themeSourceProblem(cwd, slug);
1677
2620
  if (why)
1678
2621
  throw new AstryxError(
@@ -1764,7 +2707,16 @@ export async function buildTheme(ctx, slug, data) {
1764
2707
  if (found.length) {
1765
2708
  for (const x of found) {
1766
2709
  const t = theme.components[x.target];
1767
- (t[x.key] ??= {})[x.prop] ??= x.value;
2710
+ // The base value goes before the variant's own declarations, so a
2711
+ // longhand or shorthand the variant sets itself (border-color after
2712
+ // a base border) still wins over it.
2713
+ const own = t[x.key] ?? {};
2714
+ // A variant that sets every longhand of the property itself needs
2715
+ // none of the base value (and a lifted radius would feed Core's copy
2716
+ // of it into the content's radius, after the variant's own).
2717
+ const longs = [...longhandsOf(kebab(x.prop))];
2718
+ if (longs.length && longs.every(l => camel(l) in own)) continue;
2719
+ t[x.key] = {[x.prop]: x.value, ...own};
1768
2720
  lifted.push(`${x.target} ${x.key} ${kebab(x.prop)}`);
1769
2721
  }
1770
2722
  await step(() => {
@@ -1808,6 +2760,46 @@ async function runBuild(ctx, slug) {
1808
2760
  }
1809
2761
  }
1810
2762
 
2763
+ /**
2764
+ * Why the built outputs differ from what the theme builds now: one that is
2765
+ * missing or changed by hand, found the way `compile --check` finds it
2766
+ * (the same build, compared and not written), or null when they match.
2767
+ * @param {Ctx} ctx
2768
+ * @param {string} slug
2769
+ * @returns {Promise<string | null>}
2770
+ */
2771
+ export async function outputsDrift(ctx, slug) {
2772
+ const {cwd} = ctx.project;
2773
+ const f = themeFiles(cwd, slug);
2774
+ const silent = logger.silent;
2775
+ logger.setSilent(true);
2776
+ try {
2777
+ const {receipt} = await themeBuildForReport(
2778
+ shown(cwd, f.ts),
2779
+ {check: true},
2780
+ {cwd},
2781
+ {compact: true},
2782
+ );
2783
+ const first = /** @type {any} */ (receipt)?.data?.stale?.[0];
2784
+ if (!first) return null;
2785
+ const name = path.basename(String(first.path));
2786
+ return first.reason === 'missing'
2787
+ ? `${name} was missing`
2788
+ : `${name} differs from what the settings build, after an edit by hand or by another tool`;
2789
+ } catch (e) {
2790
+ // A theme source that does not load is named by its own checks; any
2791
+ // other failure means the outputs could not be compared: built again.
2792
+ const err = /** @type {any} */ (e);
2793
+ if (err instanceof AstryxError && err.code === ERROR_CODES.ERR_THEME_LOAD)
2794
+ return null;
2795
+ return `the outputs could not be checked (${String(err?.message ?? e)
2796
+ .split('\n')[0]
2797
+ .slice(0, 160)})`;
2798
+ } finally {
2799
+ logger.setSilent(silent);
2800
+ }
2801
+ }
2802
+
1811
2803
  /**
1812
2804
  * Resolved tokens of the built theme in both modes.
1813
2805
  * @param {Ctx} ctx
@@ -1855,10 +2847,41 @@ export async function resolvedTokens(ctx, slug) {
1855
2847
  v => v && typeof v === 'object' && typeof v.name === 'string',
1856
2848
  );
1857
2849
  const {core} = ctx.project;
1858
- const out = {
1859
- light: core.resolveThemeTokens(t, {mode: 'light'}),
1860
- dark: core.resolveThemeTokens(t, {mode: 'dark'}),
2850
+ // A token value an own theme source gives as a number (8 for 8px)
2851
+ // reads as its text, never as a crash.
2852
+ const asText = (/** @type {Record<string, unknown>} */ m) =>
2853
+ Object.fromEntries(
2854
+ Object.entries(m ?? {}).map(([k, v]) => [
2855
+ k,
2856
+ typeof v === 'string' ? v : String(v),
2857
+ ]),
2858
+ );
2859
+ // A token value that is not text (a number in an own theme source) is
2860
+ // named, never a crash.
2861
+ const resolve = (/** @type {'light' | 'dark'} */ mode) => {
2862
+ try {
2863
+ return asText(core.resolveThemeTokens(t, {mode}));
2864
+ } catch (e) {
2865
+ const bad = nonTextToken(t, ctx.C.typeOf);
2866
+ throw new AstryxError(
2867
+ bad
2868
+ ? nonTextMessage(ctx, slug, bad)
2869
+ : `${slug} could not be read: ${e instanceof Error ? e.message : String(e)}.`,
2870
+ [{name: `${P} how --list tokens`, reason: 'every token and its type'}],
2871
+ ERROR_CODES.ERR_THEME_INVALID,
2872
+ );
2873
+ }
1861
2874
  };
2875
+ // A pair that holds a value that is not text ([8, 8]) resolves, but
2876
+ // builds nothing a browser reads: named the same way.
2877
+ const pairBad = nonTextToken(t, ctx.C.typeOf);
2878
+ if (pairBad)
2879
+ throw new AstryxError(
2880
+ nonTextMessage(ctx, slug, pairBad),
2881
+ [{name: `${P} how --list tokens`, reason: 'every token and its type'}],
2882
+ ERROR_CODES.ERR_THEME_INVALID,
2883
+ );
2884
+ const out = {light: resolve('light'), dark: resolve('dark')};
1862
2885
  // The tokens each part sets for itself (the official themes lift
1863
2886
  // secondary text on some parts), for the contrast check; kept out of the
1864
2887
  // modes so nothing that lists the resolved tokens sees it.
@@ -1873,6 +2896,90 @@ export async function resolvedTokens(ctx, slug) {
1873
2896
  return out;
1874
2897
  }
1875
2898
 
2899
+ /**
2900
+ * The first token a built theme gives a value that is not text, alone or
2901
+ * in a [light, dark] pair, or null.
2902
+ * @param {any} t
2903
+ * @param {(name: string) => string} [typeOf] a token's type (size, color…)
2904
+ * @returns {[string, unknown, 'object' | 'pair' | 'unit' | 'value'] | null}
2905
+ */
2906
+ function nonTextToken(t, typeOf = (/** @type {string} */ _k) => 'other') {
2907
+ for (const [k, raw] of Object.entries(t?.tokens ?? {})) {
2908
+ // An object ({light, dark}) is not a value Core builds: it would write
2909
+ // [object Object].
2910
+ if (raw && typeof raw === 'object' && !Array.isArray(raw))
2911
+ return [k, raw, 'object'];
2912
+ // A built theme writes a pair as light-dark(). A half that was not text
2913
+ // comes out as nothing, null or a boolean; a bare number is text the
2914
+ // source may have quoted, and is wrong only for a size, which needs a
2915
+ // unit.
2916
+ const pair =
2917
+ typeof raw === 'string' ? /^light-dark\((.*)\)$/s.exec(raw.trim()) : null;
2918
+ // Split at the top-level comma: a half may hold commas (rgb(0, 0, 0)).
2919
+ const parts = pair ? splitTop(pair[1], ',').map(x => x.trim()) : [];
2920
+ if (pair && parts.length === 2) {
2921
+ const halves = parts;
2922
+ const missing = halves.some(x =>
2923
+ /^(|null|undefined|true|false)$/.test(x),
2924
+ );
2925
+ const unitless =
2926
+ typeOf(k) === 'size' &&
2927
+ halves.some(x => /^-?\d+(\.\d+)?$/.test(x) && Number(x) !== 0);
2928
+ if (missing || unitless) {
2929
+ const half = (/** @type {string} */ x) =>
2930
+ /^-?\d+(\.\d+)?$/.test(x)
2931
+ ? Number(x)
2932
+ : x === '' || x === 'undefined' || x === 'null'
2933
+ ? null
2934
+ : x === 'true' || x === 'false'
2935
+ ? x === 'true'
2936
+ : x;
2937
+ return [k, [half(parts[0]), half(parts[1])], missing ? 'pair' : 'unit'];
2938
+ }
2939
+ continue;
2940
+ }
2941
+ if (Array.isArray(raw)) {
2942
+ if (raw.length !== 2 || raw.some(x => typeof x !== 'string'))
2943
+ return [k, raw, 'pair'];
2944
+ continue;
2945
+ }
2946
+ if (typeof raw !== 'string') return [k, raw, 'value'];
2947
+ }
2948
+ return null;
2949
+ }
2950
+
2951
+ /**
2952
+ * Why a token value is not one, with a value of the token's own type to
2953
+ * write instead (a size in px, a weight as a number in quotes), or none.
2954
+ * @param {Ctx} ctx
2955
+ * @param {string} slug
2956
+ * @param {[string, unknown, ('object' | 'pair' | 'unit' | 'value')?]} bad
2957
+ */
2958
+ function nonTextMessage(ctx, slug, [name, value, kind = 'value']) {
2959
+ const type = ctx.C.typeOf(name);
2960
+ if (kind === 'object')
2961
+ return `${slug}.theme.ts gives ${name} an object (${JSON.stringify(value)}); a token value is a CSS value in quotes, or a [light, dark] pair such as ['6px', '8px'].`;
2962
+ if (kind === 'unit') {
2963
+ const n = /** @type {unknown[]} */ (value).find(
2964
+ x => typeof x === 'number' && x !== 0,
2965
+ );
2966
+ 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, such as ['${n}px', '${n}px'].`;
2967
+ }
2968
+ const one = Array.isArray(value)
2969
+ ? value.find(x => typeof x !== 'string')
2970
+ : value;
2971
+ const example =
2972
+ typeof one === 'number'
2973
+ ? type === 'size'
2974
+ ? `'${one}px'`
2975
+ : `'${one}'`
2976
+ : null;
2977
+ const shape = Array.isArray(value)
2978
+ ? 'a [light, dark] pair of two CSS values in quotes'
2979
+ : 'a CSS value in quotes';
2980
+ 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})` : ''}.`;
2981
+ }
2982
+
1876
2983
  /**
1877
2984
  * Contrast problems this theme caused: text below 4.5:1 that was not as low
1878
2985
  * in the base theme. A part's own color or background setting, or a token
@@ -2050,7 +3157,7 @@ export async function contrastProblems(ctx, data, res) {
2050
3157
  })(),
2051
3158
  ...(unchecked.length
2052
3159
  ? [
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`,
3160
+ `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
3161
  ]
2055
3162
  : []),
2056
3163
  ];
@@ -2118,7 +3225,9 @@ export function baseComponent(base, ctx, target, prop, s) {
2118
3225
  const states = ctx.project.target.get(target)?.states ?? [];
2119
3226
  b = states.includes(s.state)
2120
3227
  ? t[s.when == null ? s.state : `${s.when}+${s.state}`]
2121
- : (b?.[stateKey(s.state)] ?? b?.[`:${s.state}`]);
3228
+ : (b?.[stateKey(s.state, wrapsOneControl(ctx, target))] ??
3229
+ b?.[stateKey(s.state)] ??
3230
+ b?.[`:${s.state}`]);
2122
3231
  }
2123
3232
  const v = b?.[prop];
2124
3233
  return typeof v === 'string' ? v : null;
@@ -2184,15 +3293,64 @@ export function clearNewMarker(dir) {
2184
3293
 
2185
3294
  /**
2186
3295
  * 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.
3296
+ * button, link or tab with aria-disabled (it stays focusable). A form
3297
+ * control styled on a wrapper (a typeahead, a complex selector) has its
3298
+ * input or button inside marked, so it also matches a disabled form
3299
+ * control inside it (never a list row); an action part that holds
3300
+ * children (a button group, a segmented control) never does, so one
3301
+ * disabled child never makes the whole part look disabled.
2189
3302
  * @param {string} state
3303
+ * @param {boolean} [wrapsControl]
2190
3304
  * @returns {string}
2191
3305
  */
2192
- export function stateKey(state) {
2193
- return state === 'disabled'
2194
- ? ':is(:disabled,[aria-disabled="true"])'
2195
- : `:${state}`;
3306
+ export function stateKey(state, wrapsControl = false) {
3307
+ if (state !== 'disabled') return `:${state}`;
3308
+ return wrapsControl
3309
+ ? ':is(:disabled,[aria-disabled="true"],:has(:is(input,button,select,textarea):is(:disabled,[aria-disabled="true"])))'
3310
+ : ':is(:disabled,[aria-disabled="true"])';
3311
+ }
3312
+
3313
+ /**
3314
+ * The component docs of a part: its own component's, and the one named like
3315
+ * the part (tab is Tab, under TabList), each with its name, for the ones the
3316
+ * project has.
3317
+ * @param {Ctx} ctx
3318
+ * @param {string} part
3319
+ * @returns {Array<{name: string, doc: any}>}
3320
+ */
3321
+ export function partComponentDocs(ctx, part) {
3322
+ const comps = /** @type {Record<string, any>} */ (
3323
+ ctx.project.components ?? {}
3324
+ );
3325
+ const pascal = part.replace(/(^|-)([a-z0-9])/g, (_, __, c) =>
3326
+ c.toUpperCase(),
3327
+ );
3328
+ return [ctx.project.target.get(part)?.component, pascal]
3329
+ .filter(n => n != null && comps[n])
3330
+ .map(n => ({
3331
+ name: /** @type {string} */ (n),
3332
+ doc: comps[/** @type {string} */ (n)],
3333
+ }));
3334
+ }
3335
+
3336
+ /**
3337
+ * Whether a part's styled element wraps one control: its component (or the
3338
+ * one named like the part) is a form control (Core's own category) that
3339
+ * takes a disabled prop. An action part that holds children (a button
3340
+ * group) never does.
3341
+ * @param {Ctx} ctx
3342
+ * @param {string} target
3343
+ */
3344
+ export function wrapsOneControl(ctx, target) {
3345
+ // One control: a form control with a disabled prop whose content is not
3346
+ // other elements (a radio list's items, an input group's or a field's
3347
+ // children each hold controls of their own).
3348
+ return partComponentDocs(ctx, target).some(
3349
+ ({doc: d}) =>
3350
+ /form/i.test(String(d.category ?? '')) &&
3351
+ Object.keys(d.props ?? {}).some(p => /disabled/i.test(p)) &&
3352
+ d.props?.children?.type !== 'ReactNode',
3353
+ );
2196
3354
  }
2197
3355
 
2198
3356
  /**
@@ -2394,8 +3552,12 @@ function restoreWritten(was, wrote) {
2394
3552
  continue;
2395
3553
  }
2396
3554
  const old = was.get(p);
2397
- if (old) writeWhole(p, old);
2398
- else fs.rmSync(p, {force: true});
3555
+ if (old) {
3556
+ // A folder the change removed (tokens/ once its palette went) comes
3557
+ // back with the file.
3558
+ fs.mkdirSync(path.dirname(p), {recursive: true});
3559
+ writeWhole(p, old);
3560
+ } else fs.rmSync(p, {force: true});
2399
3561
  } catch {
2400
3562
  failed.push(path.basename(p));
2401
3563
  }
@@ -2483,15 +3645,12 @@ export function settingsStamp(data) {
2483
3645
  */
2484
3646
  export function staleBuild(cwd, slug, data) {
2485
3647
  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
- );
3648
+ const files = builtFiles(cwd, slug, data);
3649
+ // An output that cannot be read (its permissions, or a folder in its
3650
+ // place) is refused by name: the build cannot replace it either. That
3651
+ // includes the files a build writes only for some themes.
3652
+ refuseUnreadable(cwd, [...files, ...builtFiles(cwd, slug, data, true)]);
3653
+ const missing = files.find(p => !fs.existsSync(p));
2495
3654
  if (missing) return `${path.relative(f.dir, missing)} was missing`;
2496
3655
  const ts = fs.readFileSync(f.settingsTs, 'utf8');
2497
3656
  const stamp =
@@ -2510,6 +3669,16 @@ export function staleBuild(cwd, slug, data) {
2510
3669
  if (built && now && built !== now)
2511
3670
  return `@astryxdesign/theme-${data.like} is ${now} now, and the build was made on ${built}`;
2512
3671
  }
3672
+ // The generated module seals its own text: a hand edit inside it (the
3673
+ // file says not to) is built over from the settings, and said. Checked
3674
+ // after the stamps, whose reasons say more.
3675
+ if (moduleUnedited(ts) === false)
3676
+ return `${slug}.settings.ts was edited by hand, though it is generated from ${slug}.settings.json and says not to edit it`;
3677
+ // An own change to <slug>.theme.ts since the build (the file says it
3678
+ // wins over the settings) is built in.
3679
+ const source = /\/\/ Built with \S+\.theme\.ts ([0-9a-f]{16})\./.exec(ts);
3680
+ if (source && fs.existsSync(f.ts) && source[1] !== themeSourceHash(cwd, slug))
3681
+ return `${slug}.theme.ts or a module it imports changed since the last build`;
2513
3682
  // By content, never by file times (an editor's re-save or a checkout
2514
3683
  // changes those): a generated module cut short, or built outputs whose
2515
3684
  // header names another CLI than the settings were written by (a build
@@ -2526,6 +3695,17 @@ export function staleBuild(cwd, slug, data) {
2526
3695
  })
2527
3696
  )
2528
3697
  return 'the last build did not finish (a command stopped while building)';
3698
+ // Outputs another theme's build wrote over (`compile other.theme.ts --out
3699
+ // themes/g/g.css`): their header names another source.
3700
+ const builtFrom = (/** @type {string} */ file) =>
3701
+ /^ \* Source: (.+)$/m
3702
+ .exec(fs.readFileSync(file, 'utf8').slice(0, 600))?.[1]
3703
+ ?.trim() ?? null;
3704
+ for (const file of [f.css, f.js]) {
3705
+ const from = builtFrom(file);
3706
+ if (from != null && path.basename(from) !== path.basename(f.ts))
3707
+ return `${path.basename(file)} was built from ${from}, not ${slug}.theme.ts`;
3708
+ }
2529
3709
  // A built stylesheet cut short (a crash, a bad merge) is built again, as
2530
3710
  // an unreadable built module is.
2531
3711
  try {
@@ -2536,6 +3716,76 @@ export function staleBuild(cwd, slug, data) {
2536
3716
  return null;
2537
3717
  }
2538
3718
 
3719
+ /**
3720
+ * Every file the editor's build of a theme writes, the one list staleness
3721
+ * reads: the generated settings module, the built stylesheet, module and
3722
+ * their types, and, with a color dial set, the generated color files.
3723
+ * @param {string} cwd
3724
+ * @param {string} slug
3725
+ * @param {ThemeData} data
3726
+ * @param {boolean} [some] the files a build writes only for some themes
3727
+ * (the variants types, for a theme with component variants) instead
3728
+ * @returns {string[]}
3729
+ */
3730
+ export function builtFiles(cwd, slug, data, some = false) {
3731
+ const f = themeFiles(cwd, slug);
3732
+ if (some) return [path.join(f.dir, `${slug}.variants.d.ts`)];
3733
+ const pal = paletteFiles(slug);
3734
+ const colors = data.settings.some(
3735
+ s => s.source === 'dial' && PALETTE_DIALS.includes(s.thing),
3736
+ )
3737
+ ? [pal.palette, pal.refs, pal.receipt].map(p => path.join(cwd, p))
3738
+ : [];
3739
+ return [
3740
+ f.settingsTs,
3741
+ f.css,
3742
+ f.js,
3743
+ path.join(f.dir, `${slug}.d.ts`),
3744
+ path.join(f.dir, `${slug}.css.d.ts`),
3745
+ ...colors,
3746
+ ];
3747
+ }
3748
+
3749
+ /**
3750
+ * Refuse, by name, a built file that is there but cannot be read: its
3751
+ * permissions, or a folder where the file goes.
3752
+ * @param {string} cwd
3753
+ * @param {string[]} files
3754
+ */
3755
+ function refuseUnreadable(cwd, files) {
3756
+ for (const file of files) {
3757
+ const st = fs.statSync(file, {throwIfNoEntry: false});
3758
+ if (!st) continue;
3759
+ const rel = shown(cwd, file);
3760
+ if (st.isDirectory())
3761
+ throw new AstryxError(
3762
+ `${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.`,
3763
+ [
3764
+ {
3765
+ name: `ls -la ${quoteCommandArgument(rel)}`,
3766
+ reason: 'see what is there',
3767
+ },
3768
+ ],
3769
+ ERROR_CODES.ERR_FILE_EXISTS,
3770
+ );
3771
+ try {
3772
+ fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK);
3773
+ } catch (e) {
3774
+ const code = /** @type {any} */ (e)?.code ?? 'EACCES';
3775
+ throw new AstryxError(
3776
+ `${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.`,
3777
+ [
3778
+ {
3779
+ name: `ls -la ${quoteCommandArgument(rel)}`,
3780
+ reason: 'see its permissions',
3781
+ },
3782
+ ],
3783
+ ERROR_CODES.ERR_WRITE_FAILED,
3784
+ );
3785
+ }
3786
+ }
3787
+ }
3788
+
2539
3789
  /**
2540
3790
  * The installed version of a base theme package, or null.
2541
3791
  * @param {string} cwd
@@ -2572,6 +3822,19 @@ export const HISTORY_STEPS = 80;
2572
3822
  */
2573
3823
  export function readHistory(file) {
2574
3824
  if (!fs.existsSync(file)) return {steps: [], dropped: 0};
3825
+ // A history that cannot be read is not damaged: it is refused by name.
3826
+ const why = unreadableReason(file);
3827
+ if (why)
3828
+ throw new AstryxError(
3829
+ `${path.basename(file)} ${why}, so the undo history cannot be read. Give it back its place or its read permission; nothing was changed.`,
3830
+ [
3831
+ {
3832
+ name: `ls -la ${quoteCommandArgument(file)}`,
3833
+ reason: 'see what is there',
3834
+ },
3835
+ ],
3836
+ ERROR_CODES.ERR_THEME_INVALID,
3837
+ );
2575
3838
  /** @type {unknown} */
2576
3839
  let h;
2577
3840
  try {
@@ -2656,6 +3919,11 @@ export async function commitTheme(
2656
3919
  notes,
2657
3920
  unchanged: true,
2658
3921
  };
3922
+ // With no last build (deleted, never committed), nothing is compared.
3923
+ if (snapBefore && !fs.existsSync(f.js))
3924
+ notes.push(
3925
+ `there was no last build (${path.basename(f.js)} is missing), so the token changes are not listed; the theme is built again`,
3926
+ );
2659
3927
  const resBefore =
2660
3928
  snapBefore && fs.existsSync(f.js)
2661
3929
  ? await resolvedTokens(ctx, slug).catch(() => {
@@ -2668,7 +3936,9 @@ export async function commitTheme(
2668
3936
  })
2669
3937
  : null;
2670
3938
  const before = parseSettings(snapBefore);
2671
- const liftedBefore = new Set(before?.lifted ?? []);
3939
+ const liftedBefore = new Set(
3940
+ Array.isArray(before?.lifted) ? before.lifted : [],
3941
+ );
2672
3942
  // A change that leaves every color setting as it was keeps the shades the
2673
3943
  // theme already shows: a theme an earlier editor built keeps its colors
2674
3944
  // until a color, the mode or the base changes, and undo brings them back.
@@ -2784,7 +4054,7 @@ export async function commitTheme(
2784
4054
  const code = /** @type {any} */ (e)?.code;
2785
4055
  if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO', 'EISDIR'].includes(code))
2786
4056
  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.`,
4057
+ `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
4058
  [
2789
4059
  {
2790
4060
  name: `ls -ld ${quoteCommandArgument(themeFiles(ctx.project.cwd, slug).dir)}`,
@@ -2803,6 +4073,23 @@ export async function commitTheme(
2803
4073
  e.code === ERROR_CODES.ERR_THEME_BUSY)
2804
4074
  )
2805
4075
  throw e;
4076
+ // A folder where a built file goes: named for the editor, which has no
4077
+ // --out to pick.
4078
+ const folder =
4079
+ e instanceof AstryxError
4080
+ ? /^The output (.+) is a folder\./.exec(e.message)?.[1]
4081
+ : undefined;
4082
+ if (folder)
4083
+ throw new AstryxError(
4084
+ `${folder} is a folder, not a file, so the theme cannot be built. Put the file back in its place; nothing was changed.`,
4085
+ [
4086
+ {
4087
+ name: `ls -la ${quoteCommandArgument(folder)}`,
4088
+ reason: 'see what is there',
4089
+ },
4090
+ ],
4091
+ ERROR_CODES.ERR_THEME_INVALID,
4092
+ );
2806
4093
  const why = (e instanceof Error ? e.message : String(e))
2807
4094
  .split(`${cwd}${path.sep}`)
2808
4095
  .join('')
@@ -2812,12 +4099,17 @@ export async function commitTheme(
2812
4099
  .join(' | ');
2813
4100
  const own = why.includes(path.basename(f.ts));
2814
4101
  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)` : ''}`,
4102
+ `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
4103
  [
2817
- {
2818
- name: `${P} show ${slug}`,
2819
- reason: 'do this instead: see the settings as they are',
2820
- },
4104
+ own
4105
+ ? {
4106
+ name: `cat ${quoteCommandArgument(shown(cwd, f.ts))}`,
4107
+ reason: 'see your own file, then fix it',
4108
+ }
4109
+ : {
4110
+ name: `${P} show ${slug}`,
4111
+ reason: 'do this instead: see the settings as they are',
4112
+ },
2821
4113
  ],
2822
4114
  ERROR_CODES.ERR_THEME_INVALID,
2823
4115
  );