@astryxdesign/cli 0.7.14 → 0.7.15-canary.g061b2fa

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 (164) hide show
  1. package/README.md +63 -63
  2. package/api/build/_adapter.d.mts +4 -0
  3. package/api/build/_adapter.mjs +28 -2
  4. package/api/build/blocks/blocks.d.mts +10 -1
  5. package/api/build/blocks/blocks.mjs +84 -7
  6. package/api/build/build.mjs +6 -1
  7. package/api/build/tree.d.mts +4 -0
  8. package/api/build/tree.mjs +9 -2
  9. package/api/doctor/_adapter.d.mts +3 -1
  10. package/api/doctor/_adapter.mjs +14 -1
  11. package/api/doctor/_authoring-audit.d.mts +42 -0
  12. package/api/doctor/_authoring-audit.mjs +106 -0
  13. package/api/doctor/doctor.d.mts +7 -0
  14. package/api/doctor/doctor.mjs +24 -39
  15. package/api/doctor/theme-checks.mjs +56 -21
  16. package/api/integration/validate-integration.mjs +17 -3
  17. package/api/integration/validateIntegration.doc.mjs +1 -1
  18. package/api/search/_adapter.mjs +124 -3
  19. package/api/search/_candidate-score.mjs +63 -9
  20. package/api/search/_entries.d.mts +10 -0
  21. package/api/search/_entries.mjs +68 -1
  22. package/api/search/_gather-templates.d.mts +11 -0
  23. package/api/search/_gather-templates.mjs +22 -2
  24. package/api/search/_words.mjs +26 -6
  25. package/api/swizzle/copy/copy.mjs +1 -1
  26. package/api/theme/_adapter.d.mts +17 -1
  27. package/api/theme/_adapter.mjs +185 -40
  28. package/api/theme/build/build.d.mts +29 -1
  29. package/api/theme/build/build.mjs +426 -65
  30. package/api/theme/eject/eject.mjs +10 -6
  31. package/api/theme/targets/targets.d.mts +8 -0
  32. package/api/theme/targets/targets.mjs +24 -4
  33. package/api/theme/template/template.mjs +48 -2
  34. package/api/theme/theme.type.d.mts +8 -0
  35. package/api/theme/theme.type.mjs +5 -1
  36. package/api/theme/themeBuild.doc.mjs +7 -4
  37. package/api/theme/themeEject.doc.mjs +3 -3
  38. package/api/theme/themeRemove.doc.mjs +5 -2
  39. package/api/theme/themeTargets.doc.mjs +1 -1
  40. package/api/theme/themeTemplate.doc.mjs +2 -2
  41. package/api/theme/themeUse.doc.mjs +8 -2
  42. package/api/theme-edit/_adapter.d.mts +46 -3
  43. package/api/theme-edit/_adapter.mjs +372 -109
  44. package/api/theme-edit/_check.d.mts +6 -3
  45. package/api/theme-edit/_check.mjs +665 -87
  46. package/api/theme-edit/_color.mjs +4 -2
  47. package/api/theme-edit/_compiler.d.mts +2 -1
  48. package/api/theme-edit/_compiler.mjs +27 -13
  49. package/api/theme-edit/_context.d.mts +2 -1
  50. package/api/theme-edit/_context.mjs +47 -8
  51. package/api/theme-edit/_edit.d.mts +9 -3
  52. package/api/theme-edit/_edit.mjs +484 -66
  53. package/api/theme-edit/_how-commands.d.mts +33 -7
  54. package/api/theme-edit/_how-commands.mjs +57 -45
  55. package/api/theme-edit/_how-question.d.mts +4 -0
  56. package/api/theme-edit/_how-question.mjs +1004 -223
  57. package/api/theme-edit/_how.mjs +96 -9
  58. package/api/theme-edit/_palette.d.mts +38 -13
  59. package/api/theme-edit/_palette.mjs +620 -223
  60. package/api/theme-edit/_parts.mjs +63 -7
  61. package/api/theme-edit/_png.d.mts +4 -4
  62. package/api/theme-edit/_png.mjs +4 -2
  63. package/api/theme-edit/_preview-app.d.mts +6 -0
  64. package/api/theme-edit/_preview-app.mjs +1194 -207
  65. package/api/theme-edit/_preview.mjs +2 -2
  66. package/api/theme-edit/_project.d.mts +12 -1
  67. package/api/theme-edit/_project.mjs +37 -6
  68. package/api/theme-edit/_settings.d.mts +104 -33
  69. package/api/theme-edit/_settings.mjs +818 -118
  70. package/api/theme-edit/_tables.d.mts +7 -0
  71. package/api/theme-edit/_tables.mjs +61 -0
  72. package/api/theme-edit/theme-edit.type.d.mts +11 -1
  73. package/api/theme-edit/theme-edit.type.mjs +4 -3
  74. package/api/theme-edit/themeEditHow.doc.mjs +6 -0
  75. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  76. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  77. package/api/theme-edit/themeEditPreviewList.doc.mjs +1 -1
  78. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +5 -1
  79. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  80. package/api/upgrade/_adapter.d.mts +1 -0
  81. package/assets/codemods/run-codemod.mjs +61 -0
  82. package/assets/codemods/runner.mjs +5 -4
  83. package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +3 -0
  84. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +5 -1
  85. package/assets/codemods/transforms/v0.6.4/migrate-native-picker-to-presentation.mjs +3 -0
  86. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +4 -0
  87. package/assets/codemods/transforms/v0.7.0/rename-empty-search-results-text.mjs +17 -12
  88. package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +3 -0
  89. package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +3 -0
  90. package/assets/codemods/transforms/v0.7.8/promote-tokenizer-presentation.mjs +3 -0
  91. package/assets/docs/tree/calendars.doc.mjs +1 -3
  92. package/assets/docs/tree/checks.doc.mjs +22 -1
  93. package/assets/docs.generated.json +2 -1
  94. package/assets/self-audit.generated.json +1 -0
  95. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.doc.mjs +14 -0
  96. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.tsx +31 -0
  97. package/assets/templates/components.generated.json +1 -1
  98. package/authoring/integration/integration.doc.mjs +8 -0
  99. package/authoring/integration/schema.d.mts +8 -0
  100. package/authoring/integration/schema.mjs +1 -0
  101. package/authoring/integration/type.ts +9 -0
  102. package/clients/cli/bin/astryx.mjs +19 -15
  103. package/clients/cli/build-id.generated.json +1 -0
  104. package/clients/cli/commands/ensure-core-built.mjs +12 -5
  105. package/clients/cli/commands/experimental/theme.mjs +178 -78
  106. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +1 -1
  108. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -2
  109. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  110. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  111. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  112. package/clients/cli/commands/experimental-theme-eject.doc.mjs +3 -3
  113. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  114. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  115. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +1 -1
  116. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +1 -1
  117. package/clients/cli/commands/experimental-theme-remove.doc.mjs +1 -1
  118. package/clients/cli/commands/experimental-theme-template.doc.mjs +4 -3
  119. package/clients/cli/commands/manifest.mjs +5 -2
  120. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  121. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  122. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  123. package/clients/cli/commands/theme.mjs +374 -42
  124. package/clients/cli/index.mjs +9 -3
  125. package/clients/cli/lib/manifest.mjs +37 -0
  126. package/clients/cli/lib/resolve-theme.mjs +2 -1
  127. package/clients/cli/manifest.generated.json +1 -0
  128. package/foundation/config/theme-state.d.mts +16 -0
  129. package/foundation/config/theme-state.mjs +84 -13
  130. package/foundation/discovery/module-exports.mjs +16 -2
  131. package/foundation/discovery/stored-self-audit.d.mts +31 -0
  132. package/foundation/discovery/stored-self-audit.mjs +119 -0
  133. package/foundation/discovery/template-adapter.d.mts +48 -2
  134. package/foundation/discovery/template-adapter.mjs +51 -19
  135. package/foundation/discovery/template-needs.d.mts +19 -0
  136. package/foundation/discovery/template-needs.mjs +50 -16
  137. package/foundation/discovery/template-source-tree.d.mts +7 -0
  138. package/foundation/discovery/template-source-tree.mjs +15 -0
  139. package/foundation/discovery/theme-discovery.d.mts +2 -1
  140. package/foundation/discovery/theme-discovery.mjs +2 -8
  141. package/foundation/discovery/theme-module-extensions.d.mts +18 -0
  142. package/foundation/discovery/theme-module-extensions.mjs +30 -0
  143. package/foundation/doc-compiler/import.mjs +22 -15
  144. package/foundation/doc-compiler/stored-docs.d.mts +18 -12
  145. package/foundation/doc-compiler/stored-docs.mjs +52 -19
  146. package/foundation/env/private-dir.d.mts +17 -0
  147. package/foundation/env/private-dir.mjs +42 -0
  148. package/foundation/fs/gather-cache.d.mts +108 -0
  149. package/foundation/fs/gather-cache.mjs +741 -0
  150. package/foundation/fs/jiti-cache.d.mts +21 -0
  151. package/foundation/fs/jiti-cache.mjs +66 -0
  152. package/foundation/fs/module-loader.mjs +14 -3
  153. package/foundation/fs/read-record.d.mts +31 -1
  154. package/foundation/fs/read-record.mjs +100 -7
  155. package/foundation/integrations/integrations.d.mts +8 -0
  156. package/foundation/integrations/integrations.mjs +4 -0
  157. package/foundation/integrations/validate-contributions.d.mts +62 -1
  158. package/foundation/integrations/validate-contributions.mjs +476 -40
  159. package/foundation/release/cache.d.mts +11 -2
  160. package/foundation/release/cache.mjs +59 -10
  161. package/foundation/release/folder-lock.d.mts +21 -0
  162. package/foundation/release/folder-lock.mjs +171 -0
  163. package/foundation/response/response-types.doc.mjs +1 -1
  164. package/package.json +8 -6
@@ -12,6 +12,7 @@
12
12
 
13
13
  import {createHash} from 'node:crypto';
14
14
  import * as fs from 'node:fs';
15
+ import {createRequire} from 'node:module';
15
16
  import * as path from 'node:path';
16
17
  import {pathToFileURL} from 'node:url';
17
18
  import {cliVersion} from '../../foundation/release/run-context.mjs';
@@ -43,21 +44,24 @@ import {
43
44
  compositeOver,
44
45
  isColorValue,
45
46
  isSafeValue,
46
- isSize,
47
47
  parseColor,
48
48
  ratio,
49
49
  } from './_color.mjs';
50
50
  import {
51
51
  PALETTE_DIALS,
52
52
  assertNoPlaceholder,
53
+ LIFT_PARTS,
54
+ modesOf,
55
+ paletteFiles,
53
56
  paletteImport,
54
57
  paletteMapping,
55
58
  syncPalette,
56
59
  syncPaletteRefs,
57
60
  writeWhole,
58
61
  } from './_palette.mjs';
59
- import {MODAL} from './_compiler.mjs';
62
+ import {MODAL, isColorToken} from './_compiler.mjs';
60
63
  import {baseResolved, baseThemeFile} from './_project.mjs';
64
+ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
61
65
 
62
66
  /**
63
67
  * One setting the CLI owns.
@@ -85,7 +89,10 @@ import {baseResolved, baseThemeFile} from './_project.mjs';
85
89
  * @property {string} [palette] - The hash of the palette.config.json the editor last wrote.
86
90
  */
87
91
 
88
- /** @typedef {{project: import('./_project.mjs').ThemeProject, C: import('./_compiler.mjs').Compiler, unchecked?: string | null, wrote?: Map<string, string | null>, base?: {light: Record<string, string>, dark: Record<string, string>}}} Ctx */
92
+ /** What lifted secondary text sits on: the contrast check measures it there. */
93
+ const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
94
+
95
+ /** @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>}}} Ctx */
89
96
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
90
97
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
91
98
 
@@ -106,9 +113,6 @@ export const kebab = s =>
106
113
  */
107
114
  export const camel = s =>
108
115
  s.replace(/-+([a-z0-9])?/g, (_, c) => (c ? c.toUpperCase() : ''));
109
- /** Quote a value for a suggested command. @param {unknown} v */
110
- export const q = v =>
111
- /[\s"#(]/.test(String(v)) ? `"${String(v).replace(/"/g, '\\"')}"` : String(v);
112
116
 
113
117
  /**
114
118
  * The files of one theme, absolute.
@@ -133,6 +137,36 @@ export function themeFiles(cwd, slug) {
133
137
  };
134
138
  }
135
139
 
140
+ /**
141
+ * The themes the editor made in the app (a settings file of its own), by
142
+ * name, or with `changed` the one an editor command changed last first: the
143
+ * undo history is written only by an editor command, so its time is the
144
+ * last change made there.
145
+ * @param {string} cwd
146
+ * @param {'name' | 'changed'} [order]
147
+ * @returns {string[]}
148
+ */
149
+ export function editedThemes(cwd, order = 'name') {
150
+ const root = path.join(cwd, 'themes');
151
+ if (!fs.existsSync(root)) return [];
152
+ const names = fs
153
+ .readdirSync(root)
154
+ .filter(d => fs.existsSync(themeFiles(cwd, d).settings))
155
+ .sort();
156
+ if (order === 'name') return names;
157
+ const when = (/** @type {string} */ d) => {
158
+ const f = themeFiles(cwd, d);
159
+ const t =
160
+ [f.history, f.settingsTs, f.settings].find(x => fs.existsSync(x)) ??
161
+ f.settings;
162
+ return fs.statSync(t).mtimeMs;
163
+ };
164
+ return names
165
+ .map(d => ({d, t: when(d)}))
166
+ .sort((a, b) => b.t - a.t || a.d.localeCompare(b.d))
167
+ .map(x => x.d);
168
+ }
169
+
136
170
  /** A path as the person sees it: relative to cwd. @param {string} cwd @param {string} f */
137
171
  export const shown = (cwd, f) =>
138
172
  path.relative(cwd, f).split(path.sep).join('/');
@@ -195,11 +229,16 @@ export function refuse(code, message, extra = {}) {
195
229
  * The settings of a theme, or a refusal naming the command that makes it.
196
230
  * @param {string} cwd
197
231
  * @param {string} slug
198
- * @param {string} [skip] the thing a command changes or removes: its value
199
- * is not checked, so a value made under looser rules can be fixed
232
+ * @param {string | Partial<Setting>} [skip] the thing (or the one setting)
233
+ * a command changes or removes: its value is not checked, so a value made
234
+ * under looser rules can be fixed
200
235
  * @returns {ThemeData}
201
236
  */
202
- export function loadTheme(cwd, slug, skip = '') {
237
+ export function loadTheme(
238
+ cwd,
239
+ slug,
240
+ skip = /** @type {string | Partial<Setting>} */ (''),
241
+ ) {
203
242
  if (!slugOk(slug)) {
204
243
  // A path or a capital letter typed for a theme that exists names it.
205
244
  const plain = String(slug ?? '')
@@ -231,6 +270,29 @@ export function loadTheme(cwd, slug, skip = '') {
231
270
  .replace(/^.*themes[\\/]/, '')
232
271
  .replace(/[\\/].*$/, '');
233
272
  const same = have.includes(plain) ? plain : null;
273
+ // A theme written by hand, ejected or built in: not one the editor
274
+ // made, and `new` with its name would be refused.
275
+ const other = [
276
+ [f.dir, `themes/${slug}`],
277
+ [path.join(cwd, 'src', 'themes', slug), `src/themes/${slug}`],
278
+ ].find(([d]) => fs.existsSync(d));
279
+ // A `new` that was stopped part way left its marker: `new` finishes it.
280
+ if (!same && fs.existsSync(path.join(f.dir, '.astryx-new.json')))
281
+ refuse(
282
+ ERROR_CODES.ERR_UNKNOWN_THEME,
283
+ `themes/${slug} was left by a \`new\` that was stopped part way, so it has no settings yet. Run new again to finish it.`,
284
+ {run: [`${P} new ${slug}`]},
285
+ );
286
+ if (!same && (other || LIKE.includes(slug)))
287
+ refuse(
288
+ ERROR_CODES.ERR_UNKNOWN_THEME,
289
+ `${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}` : ''}.`,
290
+ {
291
+ run: [
292
+ `${P} new my-${slug}${LIKE.includes(slug) ? ` --like ${slug}` : ''}`,
293
+ ],
294
+ },
295
+ );
234
296
  refuse(
235
297
  ERROR_CODES.ERR_UNKNOWN_THEME,
236
298
  `There is no theme "${slug}" made by this command (no themes/${slug}/${slug}.settings.json).`,
@@ -264,13 +326,51 @@ export function loadTheme(cwd, slug, skip = '') {
264
326
  }
265
327
  const problem = settingsProblem(data, skip);
266
328
  // A value made under looser rules is not damage: the command that
267
- // changes or removes that setting still works.
329
+ // changes or removes that setting still works, with the other bad ones
330
+ // left out of the build, so each listed fix runs on its own.
331
+ const all = problem ? badSettings(data) : [];
332
+ if (
333
+ problem &&
334
+ skip &&
335
+ all.some(s => skips(s, skip)) &&
336
+ !settingsProblem({
337
+ ...data,
338
+ settings: data.settings.filter(
339
+ (/** @type {any} */ s) => !all.includes(s),
340
+ ),
341
+ })
342
+ )
343
+ return data;
344
+ if (
345
+ problem &&
346
+ all.length &&
347
+ !settingsProblem({
348
+ ...data,
349
+ settings: data.settings.filter(
350
+ (/** @type {any} */ s) => !all.includes(s),
351
+ ),
352
+ }) &&
353
+ all.length > 1
354
+ )
355
+ throw new AstryxError(
356
+ `themes/${slug}/${slug}.settings.json holds ${all.length} settings the editor no longer accepts: ${all
357
+ .slice(0, 6)
358
+ .map(s => valueProblem(s))
359
+ .join(
360
+ '; ',
361
+ )}${all.length > 6 ? `; and ${all.length - 6} more` : ''}. Remove or change each; nothing else needs to change. Nothing was changed.`,
362
+ all.slice(0, 6).map(s => ({
363
+ name: `${P} undo ${slug} ${undoArgs(s)}`,
364
+ reason: 'do this instead',
365
+ })),
366
+ ERROR_CODES.ERR_THEME_INVALID,
367
+ );
268
368
  const bad = problem ? badSetting(data) : null;
269
369
  if (problem && bad && settingsProblem(data, bad.thing) !== problem) {
270
370
  // A value it takes, for a dial; a color for a color token.
271
371
  const example = DIALS[bad.thing]
272
372
  ? DIALS[bad.thing].values.split('|').find(w => !w.startsWith('<'))
273
- : bad.thing.startsWith('--color-')
373
+ : isColorToken(bad.thing)
274
374
  ? '#1f2937'
275
375
  : null;
276
376
  throw new AstryxError(
@@ -280,7 +380,7 @@ export function loadTheme(cwd, slug, skip = '') {
280
380
  ...(example
281
381
  ? [
282
382
  {
283
- name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${q(example)}`)}`,
383
+ name: `${P} set ${slug} ${undoArgs(bad).replace(bad.thing, `${bad.thing} ${quoteCommandArgument(example)}`)}`,
284
384
  reason: 'or give it a value it takes',
285
385
  },
286
386
  ]
@@ -289,10 +389,18 @@ export function loadTheme(cwd, slug, skip = '') {
289
389
  ERROR_CODES.ERR_THEME_INVALID,
290
390
  );
291
391
  }
392
+ // A bad mode or base is fixed by setting it.
393
+ const fieldFix = /^(it has no mode|mode ")/.test(problem ?? '')
394
+ ? `${P} set ${slug} mode both`
395
+ : /^base "/.test(problem ?? '')
396
+ ? `${P} set ${slug} base none`
397
+ : null;
292
398
  if (problem)
293
399
  throw new AstryxError(
294
- `themes/${slug}/${slug}.settings.json: ${problem}. Fix it by hand${recover.text}. Nothing was changed.`,
295
- recover.run,
400
+ `themes/${slug}/${slug}.settings.json: ${problem}. ${fieldFix ? 'Set it again' : `Fix it by hand${recover.text}`}. Nothing was changed.`,
401
+ fieldFix
402
+ ? [{name: fieldFix, reason: 'do this instead'}, ...recover.run]
403
+ : recover.run,
296
404
  ERROR_CODES.ERR_THEME_INVALID,
297
405
  );
298
406
  return data;
@@ -303,50 +411,88 @@ export function loadTheme(cwd, slug, skip = '') {
303
411
  * the same rules `set` checks it by (without the installed Core), so a value
304
412
  * edited by hand never reaches the build.
305
413
  * @param {any} data
306
- * @param {string} [skip] a thing whose value is not checked (the one a
414
+ * @param {string | Partial<Setting>} [skip] a thing or setting whose value is not checked (the one a
307
415
  * command is about to change or remove)
308
416
  * @returns {string | null}
309
417
  */
310
- export function settingsProblem(data, skip = '') {
418
+ export function settingsProblem(
419
+ data,
420
+ skip = /** @type {string | Partial<Setting>} */ (''),
421
+ ) {
311
422
  if (!data || typeof data !== 'object' || Array.isArray(data))
312
423
  return 'the file is not a settings object';
313
- if (!['both', 'light-only', 'dark-only'].includes(data.mode))
314
- return `mode "${data.mode}" is not both, light-only or dark-only`;
315
- if (data.like != null && !LIKE.includes(data.like))
424
+ // `set <theme> mode` and `set <theme> base` fix their own field.
425
+ const fixing = typeof skip === 'string' ? skip : skip?.thing;
426
+ const field = fixing === 'mode' || fixing === 'base';
427
+ if (!field && !['both', 'light-only', 'dark-only'].includes(data.mode))
428
+ return data.mode == null
429
+ ? 'it has no mode'
430
+ : `mode "${data.mode}" is not both, light-only or dark-only`;
431
+ if (!field && data.like != null && !LIKE.includes(data.like))
316
432
  return `base "${data.like}" is not a built-in theme (${LIKE.join(', ')})`;
317
433
  if (!Array.isArray(data.settings)) return 'settings is not a list';
318
434
  const keys = new Set();
319
435
  for (const s of data.settings) {
320
- if (!s || typeof s.thing !== 'string' || typeof s.value !== 'string')
436
+ // A value or scope that is not text is a bad setting `undo` removes;
437
+ // a setting with no name is damage.
438
+ if (!s || typeof s.thing !== 'string' || !('value' in s))
321
439
  return 'a setting has no thing or value';
322
440
  if (!['dial', 'token', 'property'].includes(s.source))
323
441
  return `${s.thing} has no source (dial, token or property)`;
324
- for (const k of ['on', 'when', 'state'])
325
- if (s[k] != null && typeof s[k] !== 'string')
326
- return `${s.thing} has a ${k} that is not a word`;
327
442
  if (s.mode != null && s.mode !== 'light' && s.mode !== 'dark')
328
443
  return `${s.thing} has mode "${s.mode}"`;
329
444
  const key = keyOf(s);
330
445
  if (keys.has(key)) return `${describe(s)} is listed twice`;
331
446
  keys.add(key);
332
- if (s.thing === skip) continue;
447
+ if (skips(s, skip)) continue;
333
448
  const problem = valueProblem(s);
334
449
  if (problem) return problem;
335
450
  }
336
451
  return null;
337
452
  }
338
453
 
454
+ /**
455
+ * Whether a setting is the one a command changes or removes: by thing, or
456
+ * by the whole identity (part, variant, state, mode) when one is given.
457
+ * @param {any} s
458
+ * @param {string | Partial<Setting> | undefined} skip
459
+ */
460
+ function skips(s, skip) {
461
+ if (!skip) return false;
462
+ if (typeof skip === 'string') return s.thing === skip;
463
+ return (
464
+ s.thing === skip.thing &&
465
+ (s.on ?? '') === (skip.on ?? '') &&
466
+ (s.when ?? '') === (skip.when ?? '') &&
467
+ (s.state ?? '') === (skip.state ?? '') &&
468
+ (s.mode ?? '') === (skip.mode ?? '')
469
+ );
470
+ }
471
+
472
+ /**
473
+ * Every setting whose only problem is its value or scope, each with the
474
+ * command that removes it.
475
+ * @param {any} data
476
+ * @returns {Setting[]}
477
+ */
478
+ export function badSettings(data) {
479
+ return (Array.isArray(data?.settings) ? data.settings : []).filter(
480
+ (/** @type {any} */ s) =>
481
+ s && typeof s.thing === 'string' && valueProblem(s),
482
+ );
483
+ }
484
+
339
485
  /**
340
486
  * The words that name a setting for `undo`.
341
487
  * @param {import('./_settings.mjs').Setting} x
342
488
  */
343
489
  export function undoArgs(x) {
344
490
  return [
345
- x.thing,
346
- ...(x.on ? [`--on ${x.on}`] : []),
347
- ...(x.when ? [`--when ${x.when}`] : []),
348
- ...(x.state ? [`--state ${x.state}`] : []),
349
- ...(x.mode ? [`--mode ${x.mode}`] : []),
491
+ quoteCommandArgument(String(x.thing)),
492
+ ...(x.on ? [`--on ${quoteCommandArgument(String(x.on))}`] : []),
493
+ ...(x.when ? [`--when ${quoteCommandArgument(String(x.when))}`] : []),
494
+ ...(x.state ? [`--state ${quoteCommandArgument(String(x.state))}`] : []),
495
+ ...(x.mode ? [`--mode ${quoteCommandArgument(String(x.mode))}`] : []),
350
496
  ...(x.only ? ['--only'] : []),
351
497
  ].join(' ');
352
498
  }
@@ -383,11 +529,24 @@ export function withoutBadValues(data) {
383
529
  * @returns {string | null}
384
530
  */
385
531
  function valueProblem(s) {
532
+ if (typeof s.value !== 'string')
533
+ return `${s.thing} has a value that is not text (${JSON.stringify(s.value)})`;
534
+ for (const k of ['on', 'when', 'state', 'mode'])
535
+ if (s[k] != null && typeof s[k] !== 'string')
536
+ return `${s.thing} has a ${k} that is not text`;
537
+ const scope = scopeProblem(s);
538
+ if (scope) return scope;
386
539
  {
387
540
  const bad = `${s.thing} "${s.value}"`;
388
- if (!isSafeValue(s.value)) return `${bad} cannot be a CSS value`;
541
+ // A font family name may hold an apostrophe (O'Reilly Sans): Core
542
+ // quotes the family itself.
543
+ const checked =
544
+ s.source === 'dial' && s.thing === 'font'
545
+ ? s.value.replace(/'/g, '')
546
+ : s.value;
547
+ if (!isSafeValue(checked)) return `${bad} cannot be a CSS value`;
389
548
  if (s.source === 'token') {
390
- if (s.mode && !s.thing.startsWith('--color-'))
549
+ if (s.mode && !isColorToken(s.thing))
391
550
  return `${s.thing} is set for ${s.mode} only, but only colors differ by mode`;
392
551
  if (new RegExp(`var\\(\\s*${s.thing}\\s*[,)]`, 'i').test(s.value))
393
552
  return `${bad} reads itself`;
@@ -398,7 +557,7 @@ function valueProblem(s) {
398
557
  const words = d.values.split('|').filter(w => !w.startsWith('<'));
399
558
  const ok =
400
559
  s.thing === 'corners'
401
- ? words.includes(s.value) || isSize(s.value, '--radius')
560
+ ? words.includes(s.value) || /^\d+(\.\d+)?px$/.test(s.value)
402
561
  : s.thing === 'text-size'
403
562
  ? words.includes(s.value) ||
404
563
  (/^\d+(\.\d+)?$/.test(s.value) &&
@@ -412,11 +571,29 @@ function valueProblem(s) {
412
571
  ? s.value.trim() !== ''
413
572
  : words.includes(s.value);
414
573
  if (!ok || s.value === 'more' || s.value === 'less')
415
- return `${bad} is not a value ${s.thing} takes (${d.values})`;
574
+ return `${bad} is not a value ${s.thing} takes (${d.values.replace('|more|less', '')})`;
416
575
  }
417
576
  return null;
418
577
  }
419
578
 
579
+ /**
580
+ * What is wrong with where a setting applies, or null: names only, as
581
+ * `set` takes them.
582
+ * @param {any} s
583
+ * @returns {string | null}
584
+ */
585
+ function scopeProblem(s) {
586
+ if (s.on != null && !/^[a-z][a-z0-9-]*$/.test(s.on))
587
+ return `${s.thing} is set on "${s.on}", which is not a part or group name`;
588
+ if (s.state != null && !/^[a-z][a-z-]*$/.test(s.state))
589
+ return `${s.thing} has state "${s.state}", which is not a state name`;
590
+ if (s.when != null && !/^[\w-]+:[\w.-]+$/.test(s.when))
591
+ return `${s.thing} has --when "${s.when}", which is not prop:value`;
592
+ if ((s.when != null || s.state != null) && s.on == null)
593
+ return `${s.thing} has a variant or state but no part`;
594
+ return null;
595
+ }
596
+
420
597
  /** The identity of a setting: a new one with the same identity replaces it. @param {Setting} s */
421
598
  export const keyOf = s =>
422
599
  [
@@ -455,13 +632,20 @@ export function partsOf(ctx, s) {
455
632
  return [s.on];
456
633
  }
457
634
 
458
- /** @param {ThemeData} d @returns {Array<'light' | 'dark'>} */
459
- export const modesOf = d =>
460
- d.mode === 'light-only'
461
- ? ['light']
462
- : d.mode === 'dark-only'
463
- ? ['dark']
464
- : ['light', 'dark'];
635
+ export {modesOf};
636
+
637
+ /**
638
+ * A length in pixels: px as given, rem and em at 16px; null for anything
639
+ * else (a percentage, calc(), a word).
640
+ * @param {string} v
641
+ * @returns {number | null}
642
+ */
643
+ export function lengthPx(v) {
644
+ const m = /^\s*(-?\d+(?:\.\d+)?|-?\.\d+)\s*(px|rem|em)?\s*$/i.exec(String(v));
645
+ if (!m) return null;
646
+ const n = Number(m[1]);
647
+ return (m[2] ?? 'px').toLowerCase() === 'px' ? n : n * 16;
648
+ }
465
649
 
466
650
  /** @param {string} v */
467
651
  export const cornerPx = v =>
@@ -476,7 +660,6 @@ export const textPx = v => TEXT_SIZE.find(([n]) => n === v)?.[1] ?? Number(v);
476
660
  * @returns {{family: string, fallbacks: string, pkg: string | null}}
477
661
  */
478
662
  export function fontOf(value) {
479
- // Core quotes the family itself, so it is stored without quotes.
480
663
  const unquote = (/** @type {string} */ x) => x.replace(/^["']|["']$/g, '');
481
664
  if (FONTS[value])
482
665
  return {
@@ -493,24 +676,46 @@ export function fontOf(value) {
493
676
  f.family.replace(/"/g, '').toLowerCase() ===
494
677
  family.replace(/["']/g, '').toLowerCase(),
495
678
  )?.pkg ?? null;
496
- if (v.includes(',')) {
497
- const parts = v
498
- .split(',')
499
- .map(x => x.trim())
500
- .filter(Boolean);
501
- return {
502
- family: unquote(parts[0]),
503
- fallbacks: parts.slice(1).join(', ') || 'system-ui, sans-serif',
504
- pkg: pkgOf(parts[0]),
505
- };
506
- }
679
+ /** Fallbacks without the family itself, so `system-ui` never repeats. @param {string} family @param {string[]} list */
680
+ const without = (family, list) =>
681
+ list
682
+ .filter(x => unquote(x).toLowerCase() !== family.toLowerCase())
683
+ .map(x => cssFamily(unquote(x), true))
684
+ .join(', ');
685
+ const parts = v
686
+ .split(',')
687
+ .map(x => x.trim())
688
+ .filter(Boolean);
689
+ const family = unquote(parts[0] ?? v);
507
690
  return {
508
- family: unquote(v),
509
- fallbacks: 'system-ui, sans-serif',
510
- pkg: pkgOf(v),
691
+ family: cssFamily(family),
692
+ fallbacks:
693
+ parts.length > 1
694
+ ? without(family, parts.slice(1))
695
+ : without(family, ['system-ui', 'sans-serif']),
696
+ pkg: pkgOf(family),
511
697
  };
512
698
  }
513
699
 
700
+ /**
701
+ * A font family name as CSS reads it. A name that is a sequence of CSS
702
+ * identifiers stays bare; any other is quoted, or the browser drops the
703
+ * whole font (`3Dumb`, `My/Font`, `a.b`). Core quotes a family that has
704
+ * a space itself, so such a name is quoted here only as a fallback
705
+ * (`spaced`), where Core writes the list as given.
706
+ * @param {string} name without quotes
707
+ * @param {boolean} [spaced]
708
+ */
709
+ export function cssFamily(name, spaced = false) {
710
+ const words = name.trim().split(/\s+/);
711
+ const ident = (/** @type {string} */ w) =>
712
+ /^-?(?:[A-Za-z_]|[\u0080-\uffff])(?:[\w-]|[\u0080-\uffff])*$/.test(w) &&
713
+ !w.startsWith('--');
714
+ if (words.every(ident)) return name.trim();
715
+ if (words.length > 1 && !spaced && !/["\\]/.test(name)) return name.trim();
716
+ return `"${name.trim().replace(/["\\]/g, '\\$&')}"`;
717
+ }
718
+
514
719
  /**
515
720
  * What a part reads for a property when the theme does not set it, so a
516
721
  * one-mode component setting keeps the other mode as it was.
@@ -518,8 +723,9 @@ export function fontOf(value) {
518
723
  * @param {string} target
519
724
  * @param {string} prop camelCase or kebab-case
520
725
  * @param {string | undefined} when
726
+ * @param {string} [state] a state (hover): that state's own value
521
727
  */
522
- function partDefault(ctx, target, prop, when) {
728
+ function partDefault(ctx, target, prop, when, state) {
523
729
  const k = kebab(prop);
524
730
  const g = ctx.C.groupOfProp(k === 'background' ? 'background-color' : k);
525
731
  const want = (/** @type {import('./_compiler.mjs').Read} */ x) =>
@@ -528,6 +734,15 @@ function partDefault(ctx, target, prop, when) {
528
734
  );
529
735
  const reads = g ? ctx.C.partReads(target, g).filter(want) : [];
530
736
  const wv = when ? when.replace(':', '=') : null;
737
+ // With a state, that state's own value (for the variant, if named);
738
+ // when the state does not change this property, the plain value is what
739
+ // shows in that state too.
740
+ if (state) {
741
+ const sr = reads.find(x =>
742
+ x.when.some(w => w.includes(`:${state}`) && (!wv || w.includes(wv))),
743
+ );
744
+ if (sr) return `var(${sr.token})`;
745
+ }
531
746
  const r =
532
747
  (wv && reads.find(x => x.when.some(w => w === wv))) ||
533
748
  reads.find(x => x.when.includes('')) ||
@@ -544,6 +759,8 @@ function partDefault(ctx, target, prop, when) {
544
759
  * @returns {any}
545
760
  */
546
761
  export function compileTheme(ctx, data, base) {
762
+ // A setting the editor no longer accepts never reaches the build.
763
+ data = {...data, settings: data.settings.filter(s => !valueProblem(s))};
547
764
  const TOKENS = ctx.project.core.tokenDefaults;
548
765
  // The base theme's type scale, read back from its sizes: base text, and
549
766
  // the ratio (2xl is three steps above base).
@@ -604,7 +821,18 @@ export function compileTheme(ctx, data, base) {
604
821
  const b = block(s, target);
605
822
  if (s.mode && !modeOnly) {
606
823
  const prev = b[prop];
607
- const other = prev ?? partDefault(ctx, target, prop, s.when) ?? v;
824
+ // The other mode keeps exactly what it had: the value set for it, the
825
+ // part's own, else what the property shows unset (light-dark() takes
826
+ // colors only, so never inherit).
827
+ const other =
828
+ prev ??
829
+ baseComponent(base, ctx, target, prop, s) ??
830
+ partDefault(ctx, target, prop, s.when, s.state) ??
831
+ (s.state
832
+ ? baseComponent(base, ctx, target, prop, {...s, state: undefined})
833
+ : null) ??
834
+ partDefault(ctx, target, prop, s.when) ??
835
+ (/^background/.test(kebab(prop)) ? 'transparent' : 'currentcolor');
608
836
  const split = (/** @type {string} */ x, /** @type {1 | 2} */ side) =>
609
837
  x.replace(/^light-dark\((.*),\s*(.*)\)$/, `$${side}`);
610
838
  b[prop] =
@@ -617,6 +845,30 @@ export function compileTheme(ctx, data, base) {
617
845
  const pal = paletteMapping(ctx.project.cwd, data.name, data, base, TOKENS);
618
846
  for (const [k, v] of Object.entries(pal?.tokens ?? {}))
619
847
  putTok(k, [v.light.color, v.dark.color]);
848
+ // Secondary text lifted on the parts the official neutral theme lifts it
849
+ // on, each for what it sits on. It is written into the very block the
850
+ // base theme lifts it in, so it replaces the base's lift. A setting of it
851
+ // on the part (no --when or --state) wins there, per mode, so a numbered
852
+ // citation shows what `--on citation` set.
853
+ for (const [target, key, ground] of pal?.lift ? LIFT_PARTS : []) {
854
+ const lift = pal?.lift?.[ground];
855
+ if (!lift || !ctx.project.target.has(target)) continue;
856
+ /** @type {Partial<Record<'light' | 'dark', {color: string}>>} */
857
+ const value = {...lift};
858
+ for (const x of data.settings)
859
+ if (
860
+ x.source === 'token' &&
861
+ x.thing === '--color-text-secondary' &&
862
+ x.on &&
863
+ !x.when &&
864
+ !x.state &&
865
+ partsOf(ctx, x).includes(target)
866
+ )
867
+ for (const m of /** @type {const} */ (['light', 'dark']))
868
+ if (!x.mode || x.mode === m) value[m] = {color: x.value};
869
+ ((theme.components[target] ??= {})[key] ??= {})['--color-text-secondary'] =
870
+ liftValue(value, modeOnly);
871
+ }
620
872
  // `headings` owns heading weight and tracking whatever the order: `type`
621
873
  // sets them only where no `headings` setting does.
622
874
  const headingsAxis = (/** @type {'weight' | 'tracking'} */ axis) =>
@@ -643,28 +895,34 @@ export function compileTheme(ctx, data, base) {
643
895
  const parts = partsOf(ctx, s);
644
896
  if (s.source === 'dial') {
645
897
  if (s.thing === 'corners') {
646
- const px = cornerPx(s.value);
647
- const val = (/** @type {number} */ x) =>
648
- px >= 9999 ? '9999px' : `${x}px`;
898
+ // Past 1000px a radius is fully round: the pill tokens apply.
899
+ const px = cornerPx(s.value) >= 1000 ? 9999 : cornerPx(s.value);
900
+ const pill = px >= 9999;
901
+ const rung = CORNERS.some(([n]) => n === s.value);
902
+ /** @param {string} token */
903
+ const derived = token => `${radiusAt(base, s.value, token)}px`;
649
904
  if (parts.length)
650
- for (const t of parts)
651
- putComp({...s, mode: undefined}, t, 'borderRadius', val(px));
652
- else {
653
- putTok('--radius-element', val(px));
654
- // A checkbox stays a rounded square next to a round radio.
655
- putTok(
905
+ for (const t of parts) {
906
+ // A rung on a part gives what the whole-theme rung gives the
907
+ // radius token the part reads; an exact size is as given.
908
+ const token = /^var\((--radius-[\w-]+)\)$/.exec(
909
+ partDefault(ctx, t, 'borderRadius', s.when) ?? '',
910
+ )?.[1];
911
+ putComp(
912
+ {...s, mode: undefined},
913
+ t,
914
+ 'borderRadius',
915
+ rung || pill ? derived(token ?? '--radius-element') : `${px}px`,
916
+ );
917
+ }
918
+ else
919
+ for (const token of [
920
+ '--radius-element',
656
921
  '--radius-inner',
657
- px >= 9999 ? '6px' : val(Math.round(px * 0.6)),
658
- );
659
- putTok(
660
922
  '--radius-container',
661
- px >= 9999 ? '24px' : `${Math.round(px * 1.25)}px`,
662
- );
663
- putTok(
664
923
  '--radius-page',
665
- px >= 9999 ? '32px' : `${Math.round(px * 2.5)}px`,
666
- );
667
- }
924
+ ])
925
+ putTok(token, derived(token));
668
926
  } else if (PALETTE_DIALS.includes(s.thing) || s.thing === 'vibrancy') {
669
927
  // The palette mapping above sets these tokens.
670
928
  } else if (s.thing === 'font') {
@@ -750,8 +1008,10 @@ export function compileTheme(ctx, data, base) {
750
1008
  let nv = null;
751
1009
  if (/^--spacing-/.test(k) && /rem$/.test(v))
752
1010
  nv = `${Number((parseFloat(v) * f).toFixed(3))}rem`;
1011
+ // A control never gets smaller than 24px, the smallest target a
1012
+ // pointer can use comfortably.
753
1013
  if (/^--size-element-/.test(k) && /px$/.test(v))
754
- nv = `${Math.round(parseFloat(v) * f)}px`;
1014
+ nv = `${Math.max(Math.min(24, parseFloat(v)), Math.round(parseFloat(v) * f))}px`;
755
1015
  if (nv === null) continue;
756
1016
  if (parts.length) for (const t of parts) block(s, t)[k] = nv;
757
1017
  else putTok(k, nv);
@@ -764,6 +1024,15 @@ export function compileTheme(ctx, data, base) {
764
1024
  for (const t of parts) putComp(s, t, camel(s.thing), s.value);
765
1025
  }
766
1026
  }
1027
+ // A one-mode theme looks the same whatever the system asks for: every
1028
+ // color the theme does not set takes its mode's value from the base (or
1029
+ // Core) on both sides.
1030
+ if (modeOnly)
1031
+ for (const k of Object.keys(/** @type {Record<string, string>} */ (TOKENS)))
1032
+ if (MODAL.has(ctx.C.typeOf(k)) && !tok[k]) {
1033
+ const v = base[modeOnly]?.[k];
1034
+ if (v && !/var\(/.test(v)) putTok(k, v);
1035
+ }
767
1036
  // A scale steeper than the standard one enlarges the headings; the steps
768
1037
  // below the base text size keep the standard ratio, so small text stays
769
1038
  // readable. An exact token setting still wins.
@@ -876,6 +1145,26 @@ export function maskedSettings(data) {
876
1145
  s,
877
1146
  `saved for ${s.mode} mode, which a ${data.mode} theme does not have, so it does not apply`,
878
1147
  );
1148
+ // A part setting that a later setting on a group holding that part
1149
+ // covers: the later one is written after it, so it wins.
1150
+ data.settings.forEach((s, i) => {
1151
+ if (s.source !== 'dial' || !s.on || FAMILIES[s.on]) return;
1152
+ const later = data.settings
1153
+ .slice(i + 1)
1154
+ .find(
1155
+ x =>
1156
+ x.thing === s.thing &&
1157
+ x.on &&
1158
+ (FAMILIES[x.on] ?? []).includes(/** @type {string} */ (s.on)) &&
1159
+ (x.when ?? '') === (s.when ?? '') &&
1160
+ (x.state ?? '') === (s.state ?? ''),
1161
+ );
1162
+ if (later)
1163
+ out.set(
1164
+ s,
1165
+ `${describe(later)} comes later and covers ${s.on}, so ${s.on} shows ${later.value}; set ${s.on} again to make it win`,
1166
+ );
1167
+ });
879
1168
  for (const s of data.settings) {
880
1169
  if (s.thing !== 'type' || !axes.size) continue;
881
1170
  const T = TYPE_STYLES[s.value];
@@ -914,13 +1203,32 @@ export function findOverrides(cssText, theme) {
914
1203
  `\\.astryx-${target.replace(/-/g, '\\-')}\\[data-([a-z-]+)="([^"]+)"\\]\\s*\\{([^}]*)\\}`,
915
1204
  'g',
916
1205
  );
1206
+ // A shorthand and its longhands are one property: the last one set
1207
+ // (background after background-color) is the one in effect.
1208
+ // border-radius, border-collapse and border-spacing are not part of
1209
+ // border.
1210
+ const NOT_LONGHAND =
1211
+ /^border-(radius|collapse|spacing)|^border-[a-z]+-radius$/;
1212
+ /** @param {string} a @param {string} b */
1213
+ const sameProperty = (a, b) => {
1214
+ const [x, y] = [kebab(a), kebab(b)];
1215
+ if (NOT_LONGHAND.test(x) || NOT_LONGHAND.test(y)) return x === y;
1216
+ return x.startsWith(`${y}-`) || y.startsWith(`${x}-`) || x === y;
1217
+ };
1218
+ const last = props.filter(
1219
+ (p, i) => !props.slice(i + 1).some(later => sameProperty(later, p)),
1220
+ );
917
1221
  for (const m of cssText.matchAll(re)) {
918
- for (const prop of props) {
1222
+ for (const prop of last) {
919
1223
  // A prop named for the property itself (weight for font-weight,
920
1224
  // color for color) is the author's own choice: it keeps winning.
921
1225
  const css = kebab(prop);
922
1226
  if (css === m[1] || css.endsWith(`-${m[1]}`)) continue;
923
- if (new RegExp(`(^|[;\\s])${kebab(prop)}\\s*:`).test(m[3]))
1227
+ // The override may set the property or one of its longhands.
1228
+ const declared = [...m[3].matchAll(/(?:^|[;\s])([a-z-]+)\s*:/g)].map(
1229
+ d => d[1],
1230
+ );
1231
+ if (declared.some(d => sameProperty(d, css)))
924
1232
  extra.push({
925
1233
  target,
926
1234
  key: `${m[1]}:${m[2]}`,
@@ -933,6 +1241,17 @@ export function findOverrides(cssText, theme) {
933
1241
  return extra;
934
1242
  }
935
1243
 
1244
+ /**
1245
+ * The CSS value of lifted secondary text: one color in a one-mode theme,
1246
+ * else light-dark().
1247
+ * @param {Partial<Record<'light' | 'dark', {color: string}>>} lift
1248
+ * @param {'light' | 'dark' | null} only
1249
+ */
1250
+ const liftValue = (lift, only) =>
1251
+ only
1252
+ ? String(lift[only]?.color)
1253
+ : `light-dark(${lift.light?.color}, ${lift.dark?.color})`;
1254
+
936
1255
  /**
937
1256
  * The generated theme source. A token the palette mapping set, and no exact
938
1257
  * token setting replaced, reads its palette stop from the generated palette
@@ -942,7 +1261,7 @@ export function findOverrides(cssText, theme) {
942
1261
  * @param {any} theme
943
1262
  * @param {import('./_palette.mjs').PaletteMapping | null} pal
944
1263
  */
945
- function settingsSource(slug, data, theme, pal) {
1264
+ function settingsSource(slug, data, theme, pal, cwd = '') {
946
1265
  const like = data.like;
947
1266
  const REF = '@@palette:';
948
1267
  /** @param {string} family @param {'light' | 'dark'} m @param {import('./_palette.mjs').StopRef} r */
@@ -975,18 +1294,64 @@ function settingsSource(slug, data, theme, pal) {
975
1294
  ];
976
1295
  }
977
1296
  }
1297
+ // A lifted part reads the neutral color's stops too.
1298
+ if (pal?.lift && out.components) {
1299
+ out.components = {...out.components};
1300
+ for (const [target, key, ground] of LIFT_PARTS) {
1301
+ const lift = pal.lift[ground];
1302
+ if (!lift) continue;
1303
+ const literal = liftValue(lift, only);
1304
+ /** A shade of the neutral palette as a reference; a color as it is. @param {'light' | 'dark'} m */
1305
+ const one = m => {
1306
+ const r = /** @type {any} */ (lift[m]);
1307
+ return r.family === 'literal' ? r.color : refOf('neutral', m, r);
1308
+ };
1309
+ const refs = only
1310
+ ? one(only)
1311
+ : `light-dark(${one('light')}, ${one('dark')})`;
1312
+ const block = out.components[target]?.[key];
1313
+ if (block?.['--color-text-secondary'] !== literal) continue;
1314
+ out.components[target] = {
1315
+ ...out.components[target],
1316
+ [key]: {...block, '--color-text-secondary': refs},
1317
+ };
1318
+ }
1319
+ }
978
1320
  let usesPalette = false;
979
- const body = JSON.stringify(out, null, 2).replace(
980
- /"@@palette:(?:(black|white)|([a-z][a-z0-9-]*)\.(light|dark)\.(\d+(?:\.\d+)?)(?:\+([0-9a-f]{2}))?)"/g,
981
- (_, end, family, m, stop, alpha) => {
982
- usesPalette = true;
983
- if (end) return `palette.${end}`;
984
- return `palette${/^[a-z]\w*$/.test(family) ? `.${family}` : `[${JSON.stringify(family)}]`}.${m}[${stop}]${alpha ? ` + '${alpha}'` : ''}`;
985
- },
986
- );
1321
+ const body = JSON.stringify(out, null, 2)
1322
+ .replace(
1323
+ /"@@palette:(?:(black|white)|([a-z][a-z0-9-]*)\.(light|dark)\.(\d+(?:\.\d+)?)(?:\+([0-9a-f]{2}))?)"/g,
1324
+ (_, end, family, m, stop, alpha) => {
1325
+ usesPalette = true;
1326
+ if (end) return `palette.${end}`;
1327
+ return `palette${/^[a-z]\w*$/.test(family) ? `.${family}` : `[${JSON.stringify(family)}]`}.${m}[${stop}]${alpha ? ` + '${alpha}'` : ''}`;
1328
+ },
1329
+ )
1330
+ .replace(
1331
+ // A stop inside a longer value (light-dark()) becomes a template.
1332
+ /"([^"\n]*@@palette:[^"\n]*)"/g,
1333
+ (_, inner) => {
1334
+ usesPalette = true;
1335
+ return `\`${inner.replace(
1336
+ /@@palette:([a-z][a-z0-9-]*)\.(light|dark)\.(\d+(?:\.\d+)?)/g,
1337
+ (
1338
+ /** @type {string} */ __,
1339
+ /** @type {string} */ family,
1340
+ /** @type {string} */ m,
1341
+ /** @type {string} */ stop,
1342
+ ) =>
1343
+ `\${palette${/^[a-z]\w*$/.test(family) ? `.${family}` : `[${JSON.stringify(family)}]`}.${m}[${stop}]}`,
1344
+ )}\``;
1345
+ },
1346
+ );
987
1347
  return [
988
1348
  `// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
989
1349
  `// Built from settings ${settingsStamp(data)}.`,
1350
+ ...(like && cwd
1351
+ ? [
1352
+ `// Built on @astryxdesign/theme-${like} ${baseVersionOf(cwd, like) ?? 'unknown'}.`,
1353
+ ]
1354
+ : []),
990
1355
  `// Change it with \`${P} set ${slug} ...\`; your own changes go in ${slug}.theme.ts.`,
991
1356
  "import {defineTheme} from '@astryxdesign/core/theme';",
992
1357
  ...(like
@@ -1025,6 +1390,52 @@ function themeModuleSource(slug) {
1025
1390
  ].join('\n');
1026
1391
  }
1027
1392
 
1393
+ /** The theme source as the editor first writes it. @param {string} slug */
1394
+ export const themeSource = slug => themeModuleSource(slug);
1395
+
1396
+ /**
1397
+ * Why `<slug>.theme.ts` cannot carry the settings, or null: it must import
1398
+ * `./<slug>.settings`, extend `<camel>Settings` and keep the name, or no
1399
+ * setting takes effect.
1400
+ * @param {string} cwd
1401
+ * @param {string} slug
1402
+ * @returns {string | null}
1403
+ */
1404
+ export function themeSourceProblem(cwd, slug) {
1405
+ const f = themeFiles(cwd, slug);
1406
+ if (!fs.existsSync(f.ts)) return null;
1407
+ const code = fs
1408
+ .readFileSync(f.ts, 'utf8')
1409
+ .replace(/\/\*[\s\S]*?\*\//g, '')
1410
+ .replace(/\/\/.*$/gm, '');
1411
+ const settings = `${camel(slug)}Settings`;
1412
+ if (
1413
+ !new RegExp(`from\\s+['"]\\./${slug}\\.settings(\\.[jt]s)?['"]`).test(code)
1414
+ )
1415
+ return `${slug}.theme.ts does not import ./${slug}.settings`;
1416
+ if (!new RegExp(`extends\\s*:\\s*${settings}\\b`).test(code))
1417
+ return `${slug}.theme.ts no longer extends ${settings}`;
1418
+ if (!new RegExp(`name\\s*:\\s*(['"\`])${slug}\\1`).test(code))
1419
+ return `${slug}.theme.ts no longer names the theme '${slug}'`;
1420
+ return null;
1421
+ }
1422
+
1423
+ /**
1424
+ * Refuse a build whose theme source cannot carry the settings, naming the
1425
+ * lines that put it back.
1426
+ * @param {string} cwd
1427
+ * @param {string} slug
1428
+ */
1429
+ export function refuseThemeSource(cwd, slug) {
1430
+ const why = themeSourceProblem(cwd, slug);
1431
+ if (why)
1432
+ throw new AstryxError(
1433
+ `${why}, so settings cannot take effect. Put back the import of ${camel(slug)}Settings from './${slug}.settings', extends: ${camel(slug)}Settings and name: '${slug}' in themes/${slug}/${slug}.theme.ts (your own changes stay below them). Nothing was changed.`,
1434
+ [{name: `${P} show ${slug}`, reason: 'see the theme as it is'}],
1435
+ ERROR_CODES.ERR_THEME_INVALID,
1436
+ );
1437
+ }
1438
+
1028
1439
  /**
1029
1440
  * Generate the theme source, build it with the theme build, then repeat any
1030
1441
  * part setting a more specific rule would beat and build again.
@@ -1036,6 +1447,7 @@ function themeModuleSource(slug) {
1036
1447
  export async function buildTheme(ctx, slug, data) {
1037
1448
  const {cwd} = ctx.project;
1038
1449
  const f = themeFiles(cwd, slug);
1450
+ refuseThemeSource(cwd, slug);
1039
1451
  if (data.like) baseThemeFile(ctx.project, data.like);
1040
1452
  const base = await baseResolved(ctx.project, data.like);
1041
1453
  const theme = compileTheme(ctx, data, base);
@@ -1054,10 +1466,29 @@ export async function buildTheme(ctx, slug, data) {
1054
1466
  let notes = [];
1055
1467
  await step(() => {
1056
1468
  notes = syncPalette(cwd, slug, data, base);
1057
- writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal));
1469
+ writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
1058
1470
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
1059
1471
  if (!fs.existsSync(f.ts)) writeAtomic(f.ts, themeModuleSource(slug));
1060
1472
  });
1473
+ // Files an earlier build wrote that this one may not: the variants types
1474
+ // of an older base, and section sheets of an older look.
1475
+ await step(() => {
1476
+ for (const file of [
1477
+ path.join(f.dir, `${slug}.variants.d.ts`),
1478
+ ...(fs.existsSync(f.dir)
1479
+ ? fs
1480
+ .readdirSync(f.dir)
1481
+ // Section sheets, and every picture: all show the look before
1482
+ // this build. The full sheet and the preview page are written
1483
+ // again by the commands that make them.
1484
+ .filter(n =>
1485
+ /^(sheet-[a-z-]+\.html|(sheet|preview)(-[a-z-]+)?\.png)$/.test(n),
1486
+ )
1487
+ .map(n => path.join(f.dir, n))
1488
+ : []),
1489
+ ])
1490
+ fs.rmSync(file, {force: true});
1491
+ });
1061
1492
  let receipt = await step(() => runBuild(ctx, slug));
1062
1493
  const found = findOverrides(fs.readFileSync(f.css, 'utf8'), theme).filter(
1063
1494
  x => !(theme.components[x.target][x.key] ?? {})[x.prop],
@@ -1071,7 +1502,7 @@ export async function buildTheme(ctx, slug, data) {
1071
1502
  lifted.push(`${x.target} ${x.key} ${kebab(x.prop)}`);
1072
1503
  }
1073
1504
  await step(() => {
1074
- writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal));
1505
+ writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
1075
1506
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
1076
1507
  });
1077
1508
  receipt = await step(() => runBuild(ctx, slug));
@@ -1096,9 +1527,12 @@ async function runBuild(ctx, slug) {
1096
1527
  const silent = logger.silent;
1097
1528
  logger.setSilent(true);
1098
1529
  try {
1530
+ // No --out: the theme's name is its slug, so the build writes
1531
+ // <slug>.css beside the source, and the generated headers read as a
1532
+ // plain `compile themes/<slug>/<slug>.theme.ts` writes them.
1099
1533
  const {receipt} = await themeBuildForReport(
1100
1534
  shown(cwd, f.ts),
1101
- {out: shown(cwd, f.css)},
1535
+ {},
1102
1536
  {cwd},
1103
1537
  {compact: true},
1104
1538
  );
@@ -1155,10 +1589,22 @@ export async function resolvedTokens(ctx, slug) {
1155
1589
  v => v && typeof v === 'object' && typeof v.name === 'string',
1156
1590
  );
1157
1591
  const {core} = ctx.project;
1158
- return {
1592
+ const out = {
1159
1593
  light: core.resolveThemeTokens(t, {mode: 'light'}),
1160
1594
  dark: core.resolveThemeTokens(t, {mode: 'dark'}),
1161
1595
  };
1596
+ // The tokens each part sets for itself (the official themes lift
1597
+ // secondary text on some parts), for the contrast check; kept out of the
1598
+ // modes so nothing that lists the resolved tokens sees it.
1599
+ /** @type {Record<string, Record<string, string>>} */
1600
+ const parts = {};
1601
+ for (const [target, blocks] of Object.entries(t?.components ?? {}))
1602
+ for (const block of Object.values(/** @type {any} */ (blocks) ?? {}))
1603
+ for (const [k, v] of Object.entries(/** @type {any} */ (block) ?? {}))
1604
+ if (k.startsWith('--') && typeof v === 'string')
1605
+ (parts[target] ??= {})[k] = v;
1606
+ Object.defineProperty(out, 'parts', {value: parts, enumerable: false});
1607
+ return out;
1162
1608
  }
1163
1609
 
1164
1610
  /**
@@ -1172,8 +1618,8 @@ export async function resolvedTokens(ctx, slug) {
1172
1618
  */
1173
1619
  export async function contrastProblems(ctx, data, res) {
1174
1620
  const base = await baseResolved(ctx.project, data.like);
1175
- /** @param {PaintSide} side @param {'fg' | 'bg'} which @param {string} m */
1176
- const override = (side, which, m) => {
1621
+ /** @param {PaintSide} side @param {'fg' | 'bg'} which @param {string} m @param {string} [when] */
1622
+ const override = (side, which, m, when) => {
1177
1623
  if (!side.target) return null;
1178
1624
  const props =
1179
1625
  which === 'fg' ? ['color'] : ['background', 'background-color'];
@@ -1182,7 +1628,7 @@ export async function contrastProblems(ctx, data, res) {
1182
1628
  .find(
1183
1629
  x =>
1184
1630
  partsOf(ctx, x).includes(/** @type {string} */ (side.target)) &&
1185
- !x.when &&
1631
+ (!x.when || x.when === when) &&
1186
1632
  !x.state &&
1187
1633
  (!x.mode || x.mode === m) &&
1188
1634
  ((x.source === 'property' && props.includes(x.thing)) ||
@@ -1190,11 +1636,56 @@ export async function contrastProblems(ctx, data, res) {
1190
1636
  );
1191
1637
  return hit?.value ?? null;
1192
1638
  };
1639
+ /**
1640
+ * Text on a lifted background (the accent tint, the neutral track) as
1641
+ * the part sets it for itself: the official themes lift secondary text
1642
+ * there, and so does a generated theme.
1643
+ * @param {TextPair} p @param {string} m
1644
+ */
1645
+ const onTint = (p, m) => {
1646
+ const tok = p.fg.tokens[0];
1647
+ if (!tok || !LIFT_GROUND_TOKENS.has(String(p.bg.tokens[0]))) return null;
1648
+ const own = /** @type {any} */ (res).parts?.[p.fg.target ?? p.text]?.[tok];
1649
+ if (typeof own !== 'string') return null;
1650
+ const split = /^light-dark\((.*),\s*([^,]*)\)$/.exec(own.trim());
1651
+ const v = split ? split[m === 'dark' ? 2 : 1].trim() : own;
1652
+ const ref = /^var\((--[\w-]+)\)$/.exec(v);
1653
+ return ref ? res[/** @type {'light' | 'dark'} */ (m)][ref[1]] : v;
1654
+ };
1655
+ /** @type {(p: TextPair, side: 'fg' | 'bg', m: string) => string | null} */
1656
+ const ofBase = (p, side, m) => {
1657
+ const target = p[side].target;
1658
+ if (!target) return null;
1659
+ const own =
1660
+ baseComponent(
1661
+ base,
1662
+ ctx,
1663
+ target,
1664
+ side === 'fg' ? 'color' : 'backgroundColor',
1665
+ {
1666
+ when: /** @type {any} */ (p).when,
1667
+ },
1668
+ ) ??
1669
+ (side === 'bg'
1670
+ ? baseComponent(base, ctx, target, 'background', {
1671
+ when: /** @type {any} */ (p).when,
1672
+ })
1673
+ : null);
1674
+ if (!own) return null;
1675
+ const ref = /^var\((--[\w-]+)\)$/.exec(own.trim());
1676
+ return ref
1677
+ ? (res[/** @type {'light' | 'dark'} */ (m)][ref[1]] ?? null)
1678
+ : own;
1679
+ };
1193
1680
  /** @type {(p: TextPair, side: 'fg' | 'bg', m: string) => string | null} */
1194
1681
  const value = (p, side, m) => {
1195
1682
  const s = p[side];
1196
1683
  return (
1197
- override(s, side, m) ??
1684
+ override(s, side, m, /** @type {any} */ (p).when) ??
1685
+ // The base theme's own part style (neutral's destructive button),
1686
+ // which Core's reads do not know.
1687
+ ofBase(p, side, m) ??
1688
+ (side === 'fg' ? onTint(p, m) : null) ??
1198
1689
  (s.tokens.length
1199
1690
  ? res[/** @type {'light' | 'dark'} */ (m)][s.tokens[0]]
1200
1691
  : s.raw)
@@ -1202,11 +1693,50 @@ export async function contrastProblems(ctx, data, res) {
1202
1693
  };
1203
1694
  /** @type {(p: TextPair, side: 'fg' | 'bg', m: string) => string | null} */
1204
1695
  const baseValue = (p, side, m) => {
1696
+ // Lifted text on the tint is held to 4.5:1, never excused by an
1697
+ // unlifted base pair.
1698
+ if (onTint(p, m) != null) return null;
1205
1699
  const s = p[side];
1206
1700
  return s.tokens.length
1207
1701
  ? base[/** @type {'light' | 'dark'} */ (m)][s.tokens[0]]
1208
1702
  : s.raw;
1209
1703
  };
1704
+ // The census renders each part once, with its default props: text on a
1705
+ // part whose variants each have their own colors (a destructive button)
1706
+ // is measured per variant too, from what each variant reads.
1707
+ /** @type {TextPair[]} */
1708
+ const variantPairs = [];
1709
+ for (const p of /** @type {any} */ (ctx).parts.pairs) {
1710
+ const t = p.fg.target;
1711
+ if (!t || t !== p.bg.target) continue;
1712
+ const fgReads = ctx.C.partReads(t, 'text');
1713
+ const bgReads = ctx.C.partReads(t, 'background');
1714
+ const variants = [
1715
+ ...new Set(
1716
+ bgReads
1717
+ .flatMap(r => r.when)
1718
+ .map(w => /^variant=([\w-]+)$/.exec(w)?.[1])
1719
+ .filter(Boolean),
1720
+ ),
1721
+ ];
1722
+ for (const v of /** @type {string[]} */ (variants)) {
1723
+ const bgTok = bgReads.find(r => r.when.includes(`variant=${v}`))?.token;
1724
+ const fgTok =
1725
+ fgReads.find(r => r.when.includes(`variant=${v}`))?.token ??
1726
+ p.fg.tokens[0];
1727
+ if (!bgTok || !fgTok) continue;
1728
+ if (bgTok === p.bg.tokens[0] && fgTok === p.fg.tokens[0]) continue;
1729
+ variantPairs.push(
1730
+ /** @type {any} */ ({
1731
+ ...p,
1732
+ text: `${p.text} (variant ${v})`,
1733
+ when: `variant:${v}`,
1734
+ fg: {...p.fg, tokens: [fgTok]},
1735
+ bg: {...p.bg, tokens: [bgTok]},
1736
+ }),
1737
+ );
1738
+ }
1739
+ }
1210
1740
  const {problems, more, unchecked} = ctx.C.contrast(
1211
1741
  value,
1212
1742
  baseValue,
@@ -1219,6 +1749,7 @@ export async function contrastProblems(ctx, data, res) {
1219
1749
  page: m =>
1220
1750
  res[/** @type {'light' | 'dark'} */ (m)]['--color-background-body'],
1221
1751
  },
1752
+ variantPairs,
1222
1753
  );
1223
1754
  return [
1224
1755
  ...problems.map(
@@ -1233,7 +1764,8 @@ export async function contrastProblems(ctx, data, res) {
1233
1764
  const scoped = data.settings.filter(
1234
1765
  x =>
1235
1766
  (x.on &&
1236
- (x.when || x.state) &&
1767
+ // A variant's own colors are measured with the variant pairs.
1768
+ (x.state || (x.when && !/^variant:/.test(x.when))) &&
1237
1769
  (/^(color|background|background-color)$/.test(x.thing) ||
1238
1770
  /^--color-/.test(x.thing))) ||
1239
1771
  // The button style recolors the primary button only.
@@ -1281,20 +1813,119 @@ function parseSettings(text) {
1281
1813
  function hashDir(dir) {
1282
1814
  /** @type {Map<string, string>} */
1283
1815
  const out = new Map();
1284
- if (!fs.lstatSync(dir, {throwIfNoEntry: false})?.isDirectory()) return out;
1285
- /** @param {string} d */
1286
- const walk = d => {
1287
- for (const e of fs.readdirSync(d, {withFileTypes: true})) {
1288
- const p = path.join(d, e.name);
1289
- if (e.isDirectory()) walk(p);
1290
- else if (e.isFile())
1291
- out.set(
1292
- p,
1293
- createHash('sha256').update(fs.readFileSync(p)).digest('hex'),
1294
- );
1295
- }
1816
+ for (const p of ownFiles(dir))
1817
+ out.set(p, createHash('sha256').update(fs.readFileSync(p)).digest('hex'));
1818
+ return out;
1819
+ }
1820
+
1821
+ /**
1822
+ * The value the base theme itself gives a part's property where a setting
1823
+ * applies (its variant and state), as the build keys part styles; null
1824
+ * when the base theme leaves it to Core.
1825
+ * @param {{light: Record<string, string>, components?: Record<string, any>}} base
1826
+ * @param {Ctx} ctx
1827
+ * @param {string} target
1828
+ * @param {string} prop camelCase
1829
+ * @param {{when?: string, state?: string}} s
1830
+ * @returns {string | null}
1831
+ */
1832
+ export function baseComponent(base, ctx, target, prop, s) {
1833
+ const t = base.components?.[target];
1834
+ if (!t) return null;
1835
+ let b = t[s.when ?? 'base'];
1836
+ if (s.state) {
1837
+ const states = ctx.project.target.get(target)?.states ?? [];
1838
+ b = states.includes(s.state)
1839
+ ? t[s.when == null ? s.state : `${s.when}+${s.state}`]
1840
+ : b?.[`:${s.state}`];
1841
+ }
1842
+ const v = b?.[prop];
1843
+ return typeof v === 'string' ? v : null;
1844
+ }
1845
+
1846
+ /**
1847
+ * The radius, in px, the build writes for a radius token at a corners value
1848
+ * (a rung, or a size). The derived radii keep the base theme's own
1849
+ * proportions to the element radius (matcha's page is 3.5 times it), so a
1850
+ * bigger element radius never makes them smaller; a checkbox stays a
1851
+ * rounded square at pill, and a container or page at pill is half again as
1852
+ * round as at `round` (a fully round card is a capsule). Past 1000px a
1853
+ * radius is fully round.
1854
+ * @param {{light: Record<string, string>}} base the base theme's tokens
1855
+ * @param {string} value
1856
+ * @param {string} token
1857
+ * @returns {number}
1858
+ */
1859
+ export function radiusAt(base, value, token) {
1860
+ const px = cornerPx(value) >= 1000 ? 9999 : cornerPx(value);
1861
+ const pill = px >= 9999;
1862
+ const el = lengthPx(base.light['--radius-element'] ?? '');
1863
+ /** @param {string} t @param {number} fallback */
1864
+ const ratio = (t, fallback) => {
1865
+ const v = lengthPx(base.light[t] ?? '');
1866
+ return el && v != null ? v / el : fallback;
1296
1867
  };
1297
- walk(dir);
1868
+ const roundPx = CORNERS.find(([n]) => n === 'round')?.[1] ?? 16;
1869
+ if (token === '--radius-inner')
1870
+ return pill ? 6 : Math.round(px * Math.min(1, ratio(token, 0.6)));
1871
+ if (token === '--radius-container')
1872
+ return Math.round(
1873
+ pill
1874
+ ? Math.max(24, 1.5 * roundPx * ratio(token, 1.25))
1875
+ : px * ratio(token, 1.25),
1876
+ );
1877
+ if (token === '--radius-page')
1878
+ return Math.round(
1879
+ pill
1880
+ ? Math.max(32, 1.5 * roundPx * ratio(token, 2.5))
1881
+ : px * ratio(token, 2.5),
1882
+ );
1883
+ return pill ? 9999 : px;
1884
+ }
1885
+
1886
+ /**
1887
+ * The files the editor writes for a theme, after `<slug>.`: the only ones a
1888
+ * change reads, hashes or puts back, and the only ones a stopped `new`
1889
+ * leaves (a designer's `<slug>.design.psd` beside them is never touched).
1890
+ */
1891
+ export const EDITOR_SUFFIXES = [
1892
+ 'settings.ts',
1893
+ 'settings.json',
1894
+ 'css',
1895
+ 'css.d.ts',
1896
+ 'js',
1897
+ 'd.ts',
1898
+ 'variants.d.ts',
1899
+ 'history.json',
1900
+ ];
1901
+
1902
+ /**
1903
+ * The files in a theme folder that the editor writes, by name: the
1904
+ * theme's generated files, its settings, history and pages, and its color
1905
+ * files. Anything else there (notes, a designer's source file, the
1906
+ * person's own tokens) is never read, hashed or put back.
1907
+ * `<slug>.theme.ts` is the person's file: it is listed only while it does
1908
+ * not exist yet, so the run that creates it can take it back.
1909
+ * @param {string} dir
1910
+ * @returns {string[]}
1911
+ */
1912
+ function ownFiles(dir) {
1913
+ if (!fs.lstatSync(dir, {throwIfNoEntry: false})?.isDirectory()) return [];
1914
+ const slug = path.basename(dir);
1915
+ const mine = (/** @type {string} */ n) =>
1916
+ EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
1917
+ /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config(\.damaged(-\d+)?)?\.json)$/.test(
1918
+ n,
1919
+ );
1920
+ /** @type {string[]} */
1921
+ const out = [];
1922
+ for (const e of fs.readdirSync(dir, {withFileTypes: true}))
1923
+ if (e.isFile() && mine(e.name)) out.push(path.join(dir, e.name));
1924
+ const tokens = path.join(dir, 'tokens');
1925
+ if (fs.lstatSync(tokens, {throwIfNoEntry: false})?.isDirectory())
1926
+ for (const e of fs.readdirSync(tokens, {withFileTypes: true}))
1927
+ if (e.isFile() && e.name.startsWith(`${slug}.palette`))
1928
+ out.push(path.join(tokens, e.name));
1298
1929
  return out;
1299
1930
  }
1300
1931
 
@@ -1310,10 +1941,18 @@ function hashDir(dir) {
1310
1941
  */
1311
1942
  async function track(dir, wrote, fn) {
1312
1943
  const before = hashDir(dir);
1944
+ const theme = path.join(dir, `${path.basename(dir)}.theme.ts`);
1945
+ const themeWasThere = fs.existsSync(theme);
1313
1946
  try {
1314
1947
  return await fn();
1315
1948
  } finally {
1316
1949
  const after = hashDir(dir);
1950
+ // The theme source this run made is its own to take back.
1951
+ if (!themeWasThere && fs.existsSync(theme))
1952
+ after.set(
1953
+ theme,
1954
+ createHash('sha256').update(fs.readFileSync(theme)).digest('hex'),
1955
+ );
1317
1956
  for (const [p, h] of after) if (before.get(p) !== h) wrote.set(p, h);
1318
1957
  for (const p of before.keys()) if (!after.has(p)) wrote.set(p, null);
1319
1958
  }
@@ -1387,7 +2026,7 @@ export function refuseLinks(cwd, slug) {
1387
2026
  `${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.`,
1388
2027
  [
1389
2028
  {
1390
- name: `cp -rL ${q(path.relative(cwd, p))} ${q(`${path.relative(cwd, p)}.copy`)}`,
2029
+ name: `cp -rL ${quoteCommandArgument(path.relative(cwd, p))} ${quoteCommandArgument(`${path.relative(cwd, p)}.copy`)}`,
1391
2030
  reason: 'copy what it points to, then put the copy in its place',
1392
2031
  },
1393
2032
  ],
@@ -1450,8 +2089,16 @@ export function buildCurrent(cwd, slug, data) {
1450
2089
  */
1451
2090
  export function staleBuild(cwd, slug, data) {
1452
2091
  const f = themeFiles(cwd, slug);
1453
- const missing = [f.js, f.css, f.settingsTs].find(p => !fs.existsSync(p));
1454
- if (missing) return `${path.basename(missing)} was missing`;
2092
+ // The generated colors are part of the build when a color dial is set.
2093
+ const colors = data.settings.some(
2094
+ s => s.source === 'dial' && PALETTE_DIALS.includes(s.thing),
2095
+ )
2096
+ ? [path.join(cwd, paletteFiles(slug).palette)]
2097
+ : [];
2098
+ const missing = [f.js, f.css, f.settingsTs, ...colors].find(
2099
+ p => !fs.existsSync(p),
2100
+ );
2101
+ if (missing) return `${path.relative(f.dir, missing)} was missing`;
1455
2102
  const ts = fs.readFileSync(f.settingsTs, 'utf8');
1456
2103
  const stamp =
1457
2104
  /\/\/ Built from settings ([0-9a-f]{16}) \(CLI ([^)]+)\)\./.exec(ts);
@@ -1459,7 +2106,16 @@ export function staleBuild(cwd, slug, data) {
1459
2106
  if (stamp && stamp[1] === hash && stamp[2] !== cliVersion())
1460
2107
  return `it was built by CLI ${stamp[2]}, and this is ${cliVersion()}`;
1461
2108
  if (!stamp || stamp[1] !== hash)
1462
- return `${slug}.settings.json changed after the build (edited by hand, or by another tool)`;
2109
+ return `${slug}.settings.json does not match the build (a command stopped part way, a hand edit, or another tool)`;
2110
+ // A base theme updated since the build changes what the theme builds on.
2111
+ if (data.like) {
2112
+ const built = new RegExp(
2113
+ `// Built on @astryxdesign/theme-${data.like} ([^.\\s]+(?:\\.[^.\\s]+)*)\\.`,
2114
+ ).exec(ts)?.[1];
2115
+ const now = baseVersionOf(cwd, data.like);
2116
+ if (built && now && built !== now)
2117
+ return `@astryxdesign/theme-${data.like} is ${now} now, and the build was made on ${built}`;
2118
+ }
1463
2119
  if (
1464
2120
  !ts.trimEnd().endsWith('});') ||
1465
2121
  fs.statSync(f.css).mtimeMs < fs.statSync(f.settingsTs).mtimeMs - 1000
@@ -1468,6 +2124,30 @@ export function staleBuild(cwd, slug, data) {
1468
2124
  return null;
1469
2125
  }
1470
2126
 
2127
+ /**
2128
+ * The installed version of a base theme package, or null.
2129
+ * @param {string} cwd
2130
+ * @param {string} like
2131
+ */
2132
+ function baseVersionOf(cwd, like) {
2133
+ const pkg = `@astryxdesign/theme-${like}`;
2134
+ try {
2135
+ // The package exports no package.json: find it above its built module.
2136
+ let dir = path.dirname(
2137
+ createRequire(path.join(cwd, 'package.json')).resolve(`${pkg}/built`),
2138
+ );
2139
+ for (let i = 0; i < 6; i++, dir = path.dirname(dir)) {
2140
+ const file = path.join(dir, 'package.json');
2141
+ if (!fs.existsSync(file)) continue;
2142
+ const json = JSON.parse(fs.readFileSync(file, 'utf8'));
2143
+ if (json.name === pkg) return String(json.version ?? '') || null;
2144
+ }
2145
+ return null;
2146
+ } catch {
2147
+ return null;
2148
+ }
2149
+ }
2150
+
1471
2151
  /** @param {string} dir */
1472
2152
  function removeIfEmpty(dir) {
1473
2153
  try {
@@ -1540,6 +2220,7 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1540
2220
  const {cwd} = ctx.project;
1541
2221
  const f = themeFiles(cwd, slug);
1542
2222
  refuseLinks(cwd, slug);
2223
+ refuseThemeSource(cwd, slug);
1543
2224
  const snapBefore = fs.existsSync(f.settings)
1544
2225
  ? fs.readFileSync(f.settings, 'utf8')
1545
2226
  : null;
@@ -1574,7 +2255,14 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1574
2255
  };
1575
2256
  const resBefore =
1576
2257
  snapBefore && fs.existsSync(f.js)
1577
- ? await resolvedTokens(ctx, slug).catch(() => null)
2258
+ ? await resolvedTokens(ctx, slug).catch(() => {
2259
+ // The last build is damaged: the change still stands, and the
2260
+ // result says why it lists no token changes.
2261
+ notes.push(
2262
+ `the last build (${path.basename(f.js)}) could not be read, so the token changes are not listed; the theme is built again`,
2263
+ );
2264
+ return null;
2265
+ })
1578
2266
  : null;
1579
2267
  const before = parseSettings(snapBefore);
1580
2268
  const liftedBefore = new Set(before?.lifted ?? []);
@@ -1593,8 +2281,12 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1593
2281
  built = await buildTheme(ctx, slug, data);
1594
2282
  data.lifted = built.lifted;
1595
2283
  // The undo step and the settings are part of the change: written whole,
1596
- // inside the rollback, the history before the settings.
2284
+ // inside the rollback, the settings first. A command stopped between
2285
+ // the two leaves the change saved with the history one step short (or,
2286
+ // for an undo, a top step equal to the settings, which undo skips),
2287
+ // never a step that undoes nothing or a lost step.
1597
2288
  await track(f.dir, wrote, () => {
2289
+ writeAtomic(f.settings, `${JSON.stringify(data, null, 2)}\n`);
1598
2290
  if (historyAfter)
1599
2291
  writeAtomic(
1600
2292
  f.history,
@@ -1605,7 +2297,6 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1605
2297
  f.history,
1606
2298
  JSON.stringify([...past, snapBefore].slice(-HISTORY_STEPS)),
1607
2299
  );
1608
- writeAtomic(f.settings, `${JSON.stringify(data, null, 2)}\n`);
1609
2300
  });
1610
2301
  } catch (e) {
1611
2302
  const {failed, skipped} = restoreWritten(was, wrote);
@@ -1630,7 +2321,8 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1630
2321
  e instanceof AstryxError &&
1631
2322
  (e.code === ERROR_CODES.ERR_UNKNOWN_THEME ||
1632
2323
  e.code === ERROR_CODES.ERR_THEME_INVALID ||
1633
- e.code === ERROR_CODES.ERR_PALETTE_GENERATION)
2324
+ e.code === ERROR_CODES.ERR_PALETTE_GENERATION ||
2325
+ e.code === ERROR_CODES.ERR_WRITE_FAILED)
1634
2326
  )
1635
2327
  throw e;
1636
2328
  const why = (e instanceof Error ? e.message : String(e))
@@ -1667,7 +2359,12 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1667
2359
  if (resBefore) {
1668
2360
  for (const m of modes) {
1669
2361
  for (const k of Object.keys(res[m])) {
1670
- if (resBefore[m][k] === res[m][k]) continue;
2362
+ // A change of letter case alone (#FFFFFF, #ffffff) is no change.
2363
+ if (
2364
+ String(resBefore[m][k]).toLowerCase() ===
2365
+ String(res[m][k]).toLowerCase()
2366
+ )
2367
+ continue;
1671
2368
  const modal = MODAL.has(ctx.C.typeOf(k));
1672
2369
  if (!modal && m === 'dark' && modes.length > 1) continue;
1673
2370
  changed.push(
@@ -1677,6 +2374,9 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
1677
2374
  }
1678
2375
  }
1679
2376
  problems = await contrastProblems(ctx, data, res);
2377
+ // What cannot be measured is a note, not a problem.
2378
+ notes.push(...problems.filter(x => x.startsWith('not checked')));
2379
+ problems = problems.filter(x => !x.startsWith('not checked'));
1680
2380
  } catch (e) {
1681
2381
  ctx.unchecked ??= `checking it failed: ${e instanceof Error ? e.message : String(e)}`;
1682
2382
  }