@astryxdesign/cli 0.7.15-canary.gf890983 → 0.7.15

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 (115) hide show
  1. package/CHANGELOG.md +353 -3
  2. package/api/doctor/_adapter.d.mts +2 -1
  3. package/api/doctor/_adapter.mjs +6 -1
  4. package/api/doctor/doctor.mjs +2 -2
  5. package/api/doctor/theme-checks.mjs +56 -21
  6. package/api/integration/add-helpers.mjs +5 -0
  7. package/api/integration/add-theme.mjs +15 -110
  8. package/api/theme/_adapter.d.mts +37 -5
  9. package/api/theme/_adapter.mjs +363 -50
  10. package/api/theme/_fork.d.mts +90 -0
  11. package/api/theme/_fork.mjs +246 -0
  12. package/api/theme/build/build.d.mts +25 -1
  13. package/api/theme/build/build.mjs +352 -41
  14. package/api/theme/eject/eject.mjs +36 -15
  15. package/api/theme/list/list.mjs +3 -6
  16. package/api/theme/palette/generate/generator.d.mts +13 -0
  17. package/api/theme/palette/generate/generator.mjs +32 -2
  18. package/api/theme/targets/targets.mjs +10 -3
  19. package/api/theme/template/template.mjs +48 -2
  20. package/api/theme/theme.type.d.mts +8 -0
  21. package/api/theme/theme.type.mjs +5 -1
  22. package/api/theme/themeBuild.doc.mjs +2 -2
  23. package/api/theme/themeRemove.doc.mjs +5 -2
  24. package/api/theme/themeTemplate.doc.mjs +2 -2
  25. package/api/theme/themeUse.doc.mjs +8 -2
  26. package/api/theme-edit/_adapter.mjs +157 -36
  27. package/api/theme-edit/_catalog.d.mts +1 -6
  28. package/api/theme-edit/_catalog.mjs +5 -268
  29. package/api/theme-edit/_check.d.mts +3 -1
  30. package/api/theme-edit/_check.mjs +733 -308
  31. package/api/theme-edit/_color.d.mts +19 -0
  32. package/api/theme-edit/_color.mjs +277 -33
  33. package/api/theme-edit/_compiler.d.mts +1 -0
  34. package/api/theme-edit/_compiler.mjs +25 -0
  35. package/api/theme-edit/_context.d.mts +2 -0
  36. package/api/theme-edit/_context.mjs +83 -9
  37. package/api/theme-edit/_css.d.mts +84 -0
  38. package/api/theme-edit/_css.mjs +700 -0
  39. package/api/theme-edit/_edit.mjs +370 -85
  40. package/api/theme-edit/_how-commands.d.mts +5 -0
  41. package/api/theme-edit/_how-commands.mjs +20 -13
  42. package/api/theme-edit/_how-question.d.mts +29 -0
  43. package/api/theme-edit/_how-question.mjs +1573 -182
  44. package/api/theme-edit/_how.mjs +306 -22
  45. package/api/theme-edit/_overview.mjs +2 -7
  46. package/api/theme-edit/_palette.d.mts +27 -5
  47. package/api/theme-edit/_palette.mjs +231 -97
  48. package/api/theme-edit/_parts.d.mts +42 -10
  49. package/api/theme-edit/_parts.mjs +224 -69
  50. package/api/theme-edit/_preview-app.d.mts +8 -0
  51. package/api/theme-edit/_preview-app.mjs +549 -96
  52. package/api/theme-edit/_preview.d.mts +7 -16
  53. package/api/theme-edit/_preview.mjs +77 -84
  54. package/api/theme-edit/_project.d.mts +20 -1
  55. package/api/theme-edit/_project.mjs +43 -13
  56. package/api/theme-edit/_settings.d.mts +96 -20
  57. package/api/theme-edit/_settings.mjs +646 -141
  58. package/api/theme-edit/_tables.d.mts +18 -12
  59. package/api/theme-edit/_tables.mjs +144 -147
  60. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  61. package/api/theme-edit/theme-edit.type.mjs +3 -1
  62. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  63. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  64. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  65. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  66. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  67. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  68. package/assets/docs/tree/publishing.doc.mjs +1 -0
  69. package/assets/docs.generated.json +2 -2
  70. package/assets/self-audit.generated.json +1 -1
  71. package/clients/cli/build-id.generated.json +1 -1
  72. package/clients/cli/commands/experimental/index.mjs +10 -10
  73. package/clients/cli/commands/experimental/theme.mjs +22 -3
  74. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  75. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  76. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  77. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  78. package/clients/cli/commands/integration.mjs +8 -0
  79. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  80. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  81. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  82. package/clients/cli/commands/theme.mjs +325 -48
  83. package/clients/cli/index.mjs +18 -3
  84. package/clients/cli/lib/cli-error.mjs +118 -3
  85. package/clients/cli/manifest.generated.json +1 -1
  86. package/foundation/config/project.mjs +34 -8
  87. package/foundation/config/theme-state.d.mts +16 -0
  88. package/foundation/config/theme-state.mjs +84 -13
  89. package/foundation/discovery/template-needs.d.mts +13 -0
  90. package/foundation/discovery/template-needs.mjs +30 -15
  91. package/foundation/discovery/theme-discovery.mjs +14 -2
  92. package/foundation/discovery/theme-imports.d.mts +16 -0
  93. package/foundation/discovery/theme-imports.mjs +30 -2
  94. package/foundation/doc-compiler/import.mjs +10 -4
  95. package/foundation/fs/gather-cache.mjs +82 -23
  96. package/foundation/fs/jiti-cache.d.mts +21 -0
  97. package/foundation/fs/jiti-cache.mjs +66 -0
  98. package/foundation/fs/module-loader.mjs +7 -2
  99. package/foundation/integrations/autolink.d.mts +1 -24
  100. package/foundation/integrations/autolink.mjs +7 -60
  101. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  102. package/foundation/integrations/declared-dependencies.mjs +73 -0
  103. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  104. package/foundation/integrations/may-have-integrations.mjs +47 -0
  105. package/foundation/release/cache.d.mts +21 -2
  106. package/foundation/release/cache.mjs +48 -8
  107. package/foundation/release/folder-lock.d.mts +7 -0
  108. package/foundation/release/folder-lock.mjs +60 -26
  109. package/foundation/release/lock-lease.d.mts +2 -1
  110. package/foundation/release/lock-lease.mjs +7 -2
  111. package/foundation/response/error-codes.doc.mjs +1 -1
  112. package/foundation/response/response-types.doc.mjs +4 -4
  113. package/package.json +6 -6
  114. package/api/theme-edit/_css-properties.d.mts +0 -10
  115. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -12,6 +12,7 @@
12
12
 
13
13
  import {createHash} from 'node:crypto';
14
14
  import * as fs from 'node:fs';
15
+ import postcss from 'postcss';
15
16
  import {createRequire} from 'node:module';
16
17
  import * as path from 'node:path';
17
18
  import {pathToFileURL} from 'node:url';
@@ -46,6 +47,7 @@ import {
46
47
  isSafeValue,
47
48
  parseColor,
48
49
  ratio,
50
+ splitTop,
49
51
  } from './_color.mjs';
50
52
  import {
51
53
  PALETTE_DIALS,
@@ -57,6 +59,9 @@ import {
57
59
  paletteMapping,
58
60
  syncPalette,
59
61
  syncPaletteRefs,
62
+ refuseIfLockLost,
63
+ lockHeld,
64
+ removeEmptyFolder,
60
65
  writeWhole,
61
66
  } from './_palette.mjs';
62
67
  import {MODAL, isColorToken} from './_compiler.mjs';
@@ -92,17 +97,46 @@ import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
92
97
  /** What lifted secondary text sits on: the contrast check measures it there. */
93
98
  const LIFT_GROUND_TOKENS = new Set(LIFT_PARTS.map(([, , g]) => g));
94
99
 
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 */
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 */
96
101
  /** @typedef {import('./_parts.mjs').PaintSide} PaintSide */
97
102
  /** @typedef {import('./_parts.mjs').TextPair} TextPair */
98
103
 
99
104
  /** What a theme name may be, in words. */
100
105
  export const NAME_RULE =
101
- 'lowercase letters, digits and dashes, starting with a letter, 64 characters at most';
106
+ 'lowercase letters, digits and dashes, starting with a letter, 64 characters at most, and not a name Windows reserves (con, prn, aux, nul, com1-com9, lpt1-lpt9)';
102
107
 
103
108
  /** A theme name: lowercase letters, digits and dashes, starting with a letter, 64 characters at most. @param {string} s */
104
109
  export const slugOk = s =>
105
- typeof s === 'string' && s.length <= 64 && /^[a-z][a-z0-9-]*$/.test(s);
110
+ typeof s === 'string' &&
111
+ s.length <= 64 &&
112
+ /^[a-z][a-z0-9-]*$/.test(s) &&
113
+ !windowsReserved(s);
114
+
115
+ /**
116
+ * A name Windows reserves for a device (con, nul, com1…): a folder named
117
+ * so cannot be checked out there.
118
+ * @param {string} s
119
+ */
120
+ export const windowsReserved = s =>
121
+ /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(s);
122
+ /**
123
+ * The theme name closest to what was typed: spaces and accents dropped,
124
+ * lower case, anything else a dash.
125
+ * @param {unknown} name
126
+ */
127
+ export const slugFor = name =>
128
+ String(name ?? '')
129
+ .trim()
130
+ .normalize('NFKD')
131
+ .replace(/[\u0300-\u036f]/g, '')
132
+ .toLowerCase()
133
+ .replace(/[^a-z0-9-]+/g, '-')
134
+ .replace(/^[^a-z]+/, '')
135
+ .replace(/-+$/, '')
136
+ .slice(0, 64)
137
+ // A device name Windows reserves gets a suffix.
138
+ .replace(/^.+$/, w => (windowsReserved(w) ? `${w}-theme` : w)) ||
139
+ 'my-theme';
106
140
  /** @param {string} s */
107
141
  export const kebab = s =>
108
142
  s.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
@@ -241,20 +275,46 @@ export function loadTheme(
241
275
  ) {
242
276
  if (!slugOk(slug)) {
243
277
  // A path or a capital letter typed for a theme that exists names it.
278
+ // A file name typed for the theme (t.theme.ts, Brand.settings.json)
279
+ // names the theme.
244
280
  const plain = String(slug ?? '')
281
+ .trim()
245
282
  .toLowerCase()
246
283
  .replace(/^.*themes[\\/]/, '')
247
- .replace(/[\\/].*$/, '');
248
- const same =
249
- slugOk(plain) && fs.existsSync(themeFiles(cwd, plain).settings)
250
- ? plain
251
- : null;
284
+ .replace(/[\\/].*$/, '')
285
+ .replace(
286
+ /\.(theme\.ts|settings\.(json|ts)|history\.json|css\.d\.ts|d\.ts|css|js|ts)$/,
287
+ '',
288
+ );
289
+ const fixed = slugFor(plain);
290
+ const same = fs.existsSync(themeFiles(cwd, fixed).settings) ? fixed : null;
291
+ // A list where one theme goes (t,u or "t;u"): one theme at a time,
292
+ // each that exists named; never a new theme made of the list. A name
293
+ // with spaces ("My Theme") is one name: its theme, found above, wins.
294
+ const words = String(slug ?? '')
295
+ .split(/\s*[,;|]\s*/)
296
+ .map(w => slugFor(w.trim()))
297
+ .filter(Boolean);
298
+ if (!same && words.length > 1) {
299
+ const existing = words.filter(
300
+ w => slugOk(w) && fs.existsSync(themeFiles(cwd, w).settings),
301
+ );
302
+ refuse(
303
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
304
+ `"${String(slug ?? '').slice(0, 80)}" names more than one theme; a command takes one theme at a time.`,
305
+ {
306
+ run: existing.length
307
+ ? existing.map(w => `${P} show ${w}`)
308
+ : [`${P} new ${words[0]}`],
309
+ },
310
+ );
311
+ }
252
312
  refuse(
253
313
  ERROR_CODES.ERR_INVALID_ARGUMENT,
254
314
  `"${String(slug ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE}).`,
255
315
  same
256
316
  ? {didYouMean: [same], run: [`${P} show ${same}`]}
257
- : {run: [`${P} new my-theme`]},
317
+ : {run: [`${P} new ${fixed}`]},
258
318
  );
259
319
  }
260
320
  const f = themeFiles(cwd, slug);
@@ -276,11 +336,19 @@ export function loadTheme(
276
336
  [f.dir, `themes/${slug}`],
277
337
  [path.join(cwd, 'src', 'themes', slug), `src/themes/${slug}`],
278
338
  ].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')))
339
+ // A `new` that was stopped part way left its marker, or the settings
340
+ // were removed beside the editor's generated module: `new` makes the
341
+ // theme again and keeps every file it did not write.
342
+ // A marker beside a history is from a `new` that finished (it writes
343
+ // none): the settings were lost after.
344
+ const stopped =
345
+ fs.existsSync(path.join(f.dir, NEW_MARKER)) && !fs.existsSync(f.history);
346
+ if (!same && (stopped || madeByEditor(f.settingsTs)))
281
347
  refuse(
282
348
  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.`,
349
+ stopped
350
+ ? `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` : ''}.`,
284
352
  {run: [`${P} new ${slug}`]},
285
353
  );
286
354
  if (!same && (other || LIKE.includes(slug)))
@@ -310,20 +378,34 @@ export function loadTheme(
310
378
  text: `, or step back to the settings before the last change with ${P} undo ${slug} (the last change is then lost)`,
311
379
  run: [{name: `${P} undo ${slug}`, reason: 'do this instead'}],
312
380
  }
313
- : {text: '; there is no earlier step to go back to', run: []};
381
+ : {
382
+ text: `; or make the theme again with ${P} new ${slug}, which keeps the damaged file beside it and every file of yours`,
383
+ run: [{name: `${P} new ${slug}`, reason: 'do this instead'}],
384
+ };
314
385
  /** @type {any} */
315
386
  let data;
316
387
  try {
317
388
  data = JSON.parse(
318
389
  fs.readFileSync(f.settings, 'utf8').replace(/^\uFEFF/, ''),
319
390
  );
320
- } catch (e) {
391
+ } catch {
321
392
  throw new AstryxError(
322
- `themes/${slug}/${slug}.settings.json is not valid JSON (${e instanceof Error ? e.message : String(e)}). Fix it by hand${recover.text}.`,
393
+ `themes/${slug}/${slug}.settings.json is not valid JSON. Fix it by hand${recover.text}.`,
323
394
  recover.run,
324
395
  ERROR_CODES.ERR_THEME_INVALID,
325
396
  );
326
397
  }
398
+ // Valid JSON of the wrong shape ([], {}, settings: null) is damage like
399
+ // invalid JSON: `new` makes the theme again, keeping the file aside.
400
+ if (!settingsShapeOk(data))
401
+ throw new AstryxError(
402
+ `themes/${slug}/${slug}.settings.json is damaged: ${settingsProblem(data) ?? 'it is not a settings object'}. Fix it by hand${steps ? `, step back to the settings before the last change with ${P} undo ${slug},` : ''} or make the theme again with ${P} new ${slug}, which keeps the damaged file beside it and every file of yours. Nothing was changed.`,
403
+ [
404
+ ...recover.run.filter(r => !/ new /.test(r.name)),
405
+ {name: `${P} new ${slug}`, reason: 'do this instead'},
406
+ ],
407
+ ERROR_CODES.ERR_THEME_INVALID,
408
+ );
327
409
  const problem = settingsProblem(data, skip);
328
410
  // A value made under looser rules is not damage: the command that
329
411
  // changes or removes that setting still works, with the other bad ones
@@ -528,7 +610,7 @@ export function withoutBadValues(data) {
528
610
  * @param {any} s
529
611
  * @returns {string | null}
530
612
  */
531
- function valueProblem(s) {
613
+ export function valueProblem(s) {
532
614
  if (typeof s.value !== 'string')
533
615
  return `${s.thing} has a value that is not text (${JSON.stringify(s.value)})`;
534
616
  for (const k of ['on', 'when', 'state', 'mode'])
@@ -751,6 +833,112 @@ function partDefault(ctx, target, prop, when, state) {
751
833
  return r ? `var(${r.token})` : null;
752
834
  }
753
835
 
836
+ /** The line that records a generated module's own hash. */
837
+ const SEAL = /^\/\/ Module ([0-9a-f]{16})\.\n/m;
838
+
839
+ /**
840
+ * A generated module with its own hash after its header, so a hand edit to
841
+ * it is told from a module an earlier editor wrote (which has none).
842
+ * @param {string} text
843
+ */
844
+ function sealModule(text) {
845
+ const hash = createHash('sha256').update(text).digest('hex').slice(0, 16);
846
+ return text.replace(
847
+ /^(\/\/ Built from settings [^\n]*\n)/m,
848
+ `$1// Module ${hash}.\n`,
849
+ );
850
+ }
851
+
852
+ /**
853
+ * Whether a generated module is as the editor wrote it: true, false for a
854
+ * hand edit, null for a module with no hash (an earlier editor's).
855
+ * @param {string} text
856
+ * @returns {boolean | null}
857
+ */
858
+ export function moduleUnedited(text) {
859
+ // A checkout that writes CRLF line endings changes no line.
860
+ text = text.replace(/\r\n/g, '\n');
861
+ const seal = SEAL.exec(text);
862
+ if (!seal) return null;
863
+ return (
864
+ createHash('sha256')
865
+ .update(text.replace(SEAL, ''))
866
+ .digest('hex')
867
+ .slice(0, 16) === seal[1]
868
+ );
869
+ }
870
+
871
+ /**
872
+ * The palette stops each token reads in a generated settings module, as
873
+ * written there (`palette.accent.light[85]`, with ` + 'aa'` for a
874
+ * see-through one): `[light, dark]` per token.
875
+ * @param {string} source
876
+ * @returns {Record<string, Record<'light' | 'dark', {family: string, stop: number, alpha?: string}>>}
877
+ */
878
+ export function stopsIn(source) {
879
+ /** @type {Record<string, Record<'light' | 'dark', {family: string, stop: number, alpha?: string}>>} */
880
+ const out = {};
881
+ const one = String.raw`palette(?:\.([a-z][\w]*)|\["([a-z][\w-]*)"\])\.(?:light|dark)\[(\d+(?:\.\d+)?)\](?: \+ '([0-9a-f]{2})')?`;
882
+ const pair = new RegExp(
883
+ String.raw`"(--[\w-]+)": \[\s*${one},\s*${one}\s*\]`,
884
+ 'g',
885
+ );
886
+ // Whether the module lifts secondary text on parts (an earlier editor
887
+ // did not): the key cannot be a token's name.
888
+ out['lifted parts'] = /** @type {any} */ (
889
+ /"components":[\s\S]*"--color-text-secondary"/.test(source)
890
+ );
891
+ for (const m of source.matchAll(pair))
892
+ out[m[1]] = {
893
+ light: {
894
+ family: m[2] ?? m[3],
895
+ stop: Number(m[4]),
896
+ ...(m[5] ? {alpha: m[5]} : {}),
897
+ },
898
+ dark: {
899
+ family: m[6] ?? m[7],
900
+ stop: Number(m[8]),
901
+ ...(m[9] ? {alpha: m[9]} : {}),
902
+ },
903
+ };
904
+ return out;
905
+ }
906
+
907
+ /**
908
+ * The palette mapping with the shades a theme already shows kept, where
909
+ * the palette still has them (see commitTheme).
910
+ * @param {import('./_palette.mjs').PaletteMapping | null} pal
911
+ * @param {ReturnType<typeof stopsIn> | null | undefined} kept
912
+ * @returns {import('./_palette.mjs').PaletteMapping | null}
913
+ */
914
+ function keepShades(pal, kept) {
915
+ if (!pal || !kept) return pal;
916
+ const tokens = {...pal.tokens};
917
+ for (const [k, v] of Object.entries(tokens)) {
918
+ if (k === 'lifted parts') continue;
919
+ const old = kept[k];
920
+ if (!old) continue;
921
+ /** @type {any} */
922
+ const next = {...v};
923
+ for (const m of /** @type {const} */ (['light', 'dark'])) {
924
+ const r = old[m];
925
+ const color = /** @type {any} */ (pal.candidate.palette)[r.family]?.[m]?.[
926
+ r.stop
927
+ ];
928
+ if (typeof color !== 'string') continue;
929
+ next[m] = {
930
+ stop: r.stop,
931
+ color: r.alpha ? `${color}${r.alpha}` : color,
932
+ ...(r.alpha ? {alpha: r.alpha} : {}),
933
+ ...(r.family !== v.family ? {family: r.family} : {}),
934
+ };
935
+ }
936
+ tokens[k] = next;
937
+ }
938
+ // A theme built without lifted text keeps the base theme's own.
939
+ return {...pal, tokens, lift: kept['lifted parts'] ? pal.lift : null};
940
+ }
941
+
754
942
  /**
755
943
  * The settings, as a `defineTheme` object.
756
944
  * @param {Ctx} ctx
@@ -812,7 +1000,7 @@ export function compileTheme(ctx, data, base) {
812
1000
  if (tg?.states.includes(s.state) && s.when == null) b = t[s.state] ??= {};
813
1001
  else if (tg?.states.includes(s.state))
814
1002
  b = t[`${s.when}+${s.state}`] ??= {};
815
- else b = b[`:${s.state}`] ??= {};
1003
+ else b = b[stateKey(s.state)] ??= {};
816
1004
  }
817
1005
  return b;
818
1006
  };
@@ -833,8 +1021,12 @@ export function compileTheme(ctx, data, base) {
833
1021
  : null) ??
834
1022
  partDefault(ctx, target, prop, s.when) ??
835
1023
  (/^background/.test(kebab(prop)) ? 'transparent' : 'currentcolor');
836
- const split = (/** @type {string} */ x, /** @type {1 | 2} */ side) =>
837
- x.replace(/^light-dark\((.*),\s*(.*)\)$/, `$${side}`);
1024
+ // At the top-level comma: a mode's color may hold commas itself.
1025
+ const split = (/** @type {string} */ x, /** @type {1 | 2} */ side) => {
1026
+ const inner = /^light-dark\((.*)\)$/s.exec(x.trim())?.[1];
1027
+ const halves = inner == null ? [] : splitTop(inner, ',');
1028
+ return halves.length === 2 ? halves[side - 1].trim() : x;
1029
+ };
838
1030
  b[prop] =
839
1031
  s.mode === 'light'
840
1032
  ? `light-dark(${v}, ${prev ? split(prev, 2) : other})`
@@ -842,7 +1034,10 @@ export function compileTheme(ctx, data, base) {
842
1034
  } else b[prop] = v;
843
1035
  };
844
1036
  // Palette stops go first, so an exact token setting always wins over them.
845
- const pal = paletteMapping(ctx.project.cwd, data.name, data, base, TOKENS);
1037
+ const pal = keepShades(
1038
+ paletteMapping(ctx.project.cwd, data.name, data, base, TOKENS),
1039
+ ctx.keepStops,
1040
+ );
846
1041
  for (const [k, v] of Object.entries(pal?.tokens ?? {}))
847
1042
  putTok(k, [v.light.color, v.dark.color]);
848
1043
  // Secondary text lifted on the parts the official neutral theme lifts it
@@ -850,8 +1045,41 @@ export function compileTheme(ctx, data, base) {
850
1045
  // base theme lifts it in, so it replaces the base's lift. A setting of it
851
1046
  // on the part (no --when or --state) wins there, per mode, so a numbered
852
1047
  // citation shows what `--on citation` set.
853
- for (const [target, key, ground] of pal?.lift ? LIFT_PARTS : []) {
854
- const lift = pal?.lift?.[ground];
1048
+ // Without a color dial nothing is lifted, but an exact secondary text
1049
+ // still reaches those parts, and the base theme's own lift stays in the
1050
+ // mode it does not cover.
1051
+ /** @type {Partial<Record<'light' | 'dark', string>>} */
1052
+ const exactText = {};
1053
+ for (const x of data.settings)
1054
+ if (
1055
+ x.source === 'token' &&
1056
+ x.thing === '--color-text-secondary' &&
1057
+ !x.on &&
1058
+ !x.when &&
1059
+ !x.state
1060
+ )
1061
+ for (const m of /** @type {const} */ (['light', 'dark']))
1062
+ if (!x.mode || x.mode === m) exactText[m] = x.value;
1063
+ const blocks =
1064
+ /** @type {{components?: Record<string, any>}} */ (base).components ?? {};
1065
+ for (const [target, key, ground] of pal?.lift || Object.keys(exactText).length
1066
+ ? LIFT_PARTS
1067
+ : []) {
1068
+ /** @type {Partial<Record<'light' | 'dark', {color: string}>> | undefined} */
1069
+ let lift = pal?.lift?.[ground];
1070
+ if (!lift) {
1071
+ const own = blocks[target]?.[key]?.['--color-text-secondary'];
1072
+ const split =
1073
+ typeof own === 'string'
1074
+ ? /^light-dark\((.*),\s*([^,]*)\)$/.exec(own.trim())
1075
+ : null;
1076
+ /** @param {'light' | 'dark'} m */
1077
+ const at = m =>
1078
+ exactText[m] ??
1079
+ (split ? split[m === 'light' ? 1 : 2].trim() : own) ??
1080
+ base[m]['--color-text-secondary'];
1081
+ lift = {light: {color: at('light')}, dark: {color: at('dark')}};
1082
+ }
855
1083
  if (!lift || !ctx.project.target.has(target)) continue;
856
1084
  /** @type {Partial<Record<'light' | 'dark', {color: string}>>} */
857
1085
  const value = {...lift};
@@ -905,14 +1133,11 @@ export function compileTheme(ctx, data, base) {
905
1133
  for (const t of parts) {
906
1134
  // A rung on a part gives what the whole-theme rung gives the
907
1135
  // 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
1136
  putComp(
912
1137
  {...s, mode: undefined},
913
1138
  t,
914
1139
  'borderRadius',
915
- rung || pill ? derived(token ?? '--radius-element') : `${px}px`,
1140
+ rung || pill ? derived(radiusTokenOf(ctx, t, s.when)) : `${px}px`,
916
1141
  );
917
1142
  }
918
1143
  else
@@ -922,7 +1147,10 @@ export function compileTheme(ctx, data, base) {
922
1147
  '--radius-container',
923
1148
  '--radius-page',
924
1149
  ])
925
- putTok(token, derived(token));
1150
+ // The radii the build already shows for this corners value (a
1151
+ // build by an earlier editor, or a step back) are kept, as the
1152
+ // colors are: they change only when corners or the base does.
1153
+ putTok(token, ctx.keepRadii?.[token] ?? derived(token));
926
1154
  } else if (PALETTE_DIALS.includes(s.thing) || s.thing === 'vibrancy') {
927
1155
  // The palette mapping above sets these tokens.
928
1156
  } else if (s.thing === 'font') {
@@ -932,7 +1160,14 @@ export function compileTheme(ctx, data, base) {
932
1160
  theme.typography[r] = {
933
1161
  ...(theme.typography[r] ?? {}),
934
1162
  family: f.family,
935
- fallbacks: f.fallbacks,
1163
+ // Code falls back to a monospace font unless the value names
1164
+ // its own fallbacks.
1165
+ fallbacks:
1166
+ r === 'code' &&
1167
+ !s.value.includes(',') &&
1168
+ !/monospace/.test(f.fallbacks)
1169
+ ? 'ui-monospace, monospace'
1170
+ : f.fallbacks,
936
1171
  };
937
1172
  } else if (s.thing === 'surfaces') {
938
1173
  for (const t of SURFACE_PARTS.filter(x => ctx.project.target.has(x)))
@@ -1024,6 +1259,15 @@ export function compileTheme(ctx, data, base) {
1024
1259
  for (const t of parts) putComp(s, t, camel(s.thing), s.value);
1025
1260
  }
1026
1261
  }
1262
+ // Core gives headings the body font when a theme sets only the body's:
1263
+ // a font for the body alone keeps the base theme's heading font.
1264
+ if (theme.typography?.body && !theme.typography.heading) {
1265
+ const heading = base.light['--font-family-heading'];
1266
+ if (heading) {
1267
+ const f = fontOf(heading);
1268
+ theme.typography.heading = {family: f.family, fallbacks: f.fallbacks};
1269
+ }
1270
+ }
1027
1271
  // A one-mode theme looks the same whatever the system asks for: every
1028
1272
  // color the theme does not set takes its mode's value from the base (or
1029
1273
  // Core) on both sides.
@@ -1033,11 +1277,11 @@ export function compileTheme(ctx, data, base) {
1033
1277
  const v = base[modeOnly]?.[k];
1034
1278
  if (v && !/var\(/.test(v)) putTok(k, v);
1035
1279
  }
1036
- // A scale steeper than the standard one enlarges the headings; the steps
1037
- // below the base text size keep the standard ratio, so small text stays
1038
- // readable. An exact token setting still wins.
1280
+ // A scale steeper or flatter than the standard one changes the headings;
1281
+ // the steps below the base text size keep the standard ratio, so small
1282
+ // text stays as it was. An exact token setting still wins.
1039
1283
  const scale = theme.typography?.scale;
1040
- if (scale && scale.ratio > STANDARD_RATIO)
1284
+ if (scale && scale.ratio !== STANDARD_RATIO)
1041
1285
  for (const [k, step] of SMALL_STEPS)
1042
1286
  if (
1043
1287
  !data.settings.some(x => x.source === 'token' && x.thing === k && !x.on)
@@ -1344,29 +1588,31 @@ function settingsSource(slug, data, theme, pal, cwd = '') {
1344
1588
  )}\``;
1345
1589
  },
1346
1590
  );
1347
- return [
1348
- `// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
1349
- `// Built from settings ${settingsStamp(data)}.`,
1350
- ...(like && cwd
1351
- ? [
1352
- `// Built on @astryxdesign/theme-${like} ${baseVersionOf(cwd, like) ?? 'unknown'}.`,
1353
- ]
1354
- : []),
1355
- `// Change it with \`${P} set ${slug} ...\`; your own changes go in ${slug}.theme.ts.`,
1356
- "import {defineTheme} from '@astryxdesign/core/theme';",
1357
- ...(like
1358
- ? [
1359
- `import {${like}Theme as base} from '@astryxdesign/theme-${like}/built';`,
1360
- ]
1361
- : []),
1362
- ...(usesPalette ? [paletteImport(slug)] : []),
1363
- '',
1364
- `export const ${camel(slug)}Settings = defineTheme({`,
1365
- ...(like ? [' extends: base,'] : []),
1366
- ...body.split('\n').slice(1, -1),
1367
- '});',
1368
- '',
1369
- ].join('\n');
1591
+ return sealModule(
1592
+ [
1593
+ `// Generated by \`${P}\` from ${slug}.settings.json on every change: do not edit.`,
1594
+ `// Built from settings ${settingsStamp(data)}.`,
1595
+ ...(like && cwd
1596
+ ? [
1597
+ `// Built on @astryxdesign/theme-${like} ${baseVersionOf(cwd, like) ?? 'unknown'}.`,
1598
+ ]
1599
+ : []),
1600
+ `// Change it with \`${P} set ${slug} ...\`; your own changes go in ${slug}.theme.ts.`,
1601
+ "import {defineTheme} from '@astryxdesign/core/theme';",
1602
+ ...(like
1603
+ ? [
1604
+ `import {${like}Theme as base} from '@astryxdesign/theme-${like}/built';`,
1605
+ ]
1606
+ : []),
1607
+ ...(usesPalette ? [paletteImport(slug)] : []),
1608
+ '',
1609
+ `export const ${camel(slug)}Settings = defineTheme({`,
1610
+ ...(like ? [' extends: base,'] : []),
1611
+ ...body.split('\n').slice(1, -1),
1612
+ '});',
1613
+ '',
1614
+ ].join('\n'),
1615
+ );
1370
1616
  }
1371
1617
 
1372
1618
  /**
@@ -1450,25 +1696,45 @@ export async function buildTheme(ctx, slug, data) {
1450
1696
  refuseThemeSource(cwd, slug);
1451
1697
  if (data.like) baseThemeFile(ctx.project, data.like);
1452
1698
  const base = await baseResolved(ctx.project, data.like);
1453
- const theme = compileTheme(ctx, data, base);
1454
- const pal = paletteMapping(
1455
- cwd,
1456
- slug,
1457
- data,
1458
- base,
1459
- ctx.project.core.tokenDefaults,
1460
- );
1461
1699
  fs.mkdirSync(f.dir, {recursive: true});
1462
1700
  // Each write is recorded for a rollback; the time between them is not.
1701
+ // Each step checks first that this command still holds the theme lock:
1702
+ // the build's own writes (the stylesheet and module the stable build
1703
+ // writes, the files it removes) are fenced as each step starts.
1463
1704
  /** @type {<T>(fn: () => T) => Promise<Awaited<T>>} */
1464
- const step = fn => track(f.dir, ctx.wrote ?? new Map(), fn);
1705
+ const step = fn => {
1706
+ refuseIfLockLost();
1707
+ return track(f.dir, ctx.wrote ?? new Map(), fn);
1708
+ };
1465
1709
  /** @type {string[]} */
1466
1710
  let notes = [];
1711
+ // The palette files are written first, and the theme is built from them
1712
+ // as written: a config an earlier editor wrote is brought up to date
1713
+ // before any color is read from it.
1714
+ const paletteFile = path.join(cwd, paletteFiles(slug).palette);
1715
+ const paletteBefore = fs.existsSync(paletteFile)
1716
+ ? fs.readFileSync(paletteFile, 'utf8')
1717
+ : null;
1467
1718
  await step(() => {
1468
1719
  notes = syncPalette(cwd, slug, data, base);
1469
- writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
1720
+ });
1721
+ // Shades a theme already shows are kept only while its palette stays the
1722
+ // same: a palette made again moves every shade.
1723
+ if (
1724
+ (fs.existsSync(paletteFile)
1725
+ ? fs.readFileSync(paletteFile, 'utf8')
1726
+ : null) !== paletteBefore
1727
+ )
1728
+ ctx.keepStops = null;
1729
+ const theme = compileTheme(ctx, data, base);
1730
+ const pal = keepShades(
1731
+ paletteMapping(cwd, slug, data, base, ctx.project.core.tokenDefaults),
1732
+ ctx.keepStops,
1733
+ );
1734
+ await step(() => {
1735
+ writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
1470
1736
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
1471
- if (!fs.existsSync(f.ts)) writeAtomic(f.ts, themeModuleSource(slug));
1737
+ if (!fs.existsSync(f.ts)) writeWhole(f.ts, themeModuleSource(slug));
1472
1738
  });
1473
1739
  // Files an earlier build wrote that this one may not: the variants types
1474
1740
  // of an older base, and section sheets of an older look.
@@ -1502,7 +1768,7 @@ export async function buildTheme(ctx, slug, data) {
1502
1768
  lifted.push(`${x.target} ${x.key} ${kebab(x.prop)}`);
1503
1769
  }
1504
1770
  await step(() => {
1505
- writeAtomic(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
1771
+ writeWhole(f.settingsTs, settingsSource(slug, data, theme, pal, cwd));
1506
1772
  syncPaletteRefs(cwd, slug, fs.readFileSync(f.settingsTs, 'utf8'), pal);
1507
1773
  });
1508
1774
  receipt = await step(() => runBuild(ctx, slug));
@@ -1798,12 +2064,27 @@ export async function contrastProblems(ctx, data, res) {
1798
2064
  function parseSettings(text) {
1799
2065
  if (text == null) return null;
1800
2066
  try {
1801
- return JSON.parse(text);
2067
+ const data = JSON.parse(text);
2068
+ return settingsShapeOk(data) ? data : null;
1802
2069
  } catch {
1803
2070
  return null;
1804
2071
  }
1805
2072
  }
1806
2073
 
2074
+ /**
2075
+ * Whether parsed settings have the shape the editor reads: an object with a
2076
+ * list of settings.
2077
+ * @param {any} data
2078
+ */
2079
+ export function settingsShapeOk(data) {
2080
+ return (
2081
+ !!data &&
2082
+ typeof data === 'object' &&
2083
+ !Array.isArray(data) &&
2084
+ Array.isArray(data.settings)
2085
+ );
2086
+ }
2087
+
1807
2088
  /**
1808
2089
  * Every regular file under `dir` and the hash of its bytes; empty when
1809
2090
  * there is no folder.
@@ -1837,12 +2118,117 @@ export function baseComponent(base, ctx, target, prop, s) {
1837
2118
  const states = ctx.project.target.get(target)?.states ?? [];
1838
2119
  b = states.includes(s.state)
1839
2120
  ? t[s.when == null ? s.state : `${s.when}+${s.state}`]
1840
- : b?.[`:${s.state}`];
2121
+ : (b?.[stateKey(s.state)] ?? b?.[`:${s.state}`]);
1841
2122
  }
1842
2123
  const v = b?.[prop];
1843
2124
  return typeof v === 'string' ? v : null;
1844
2125
  }
1845
2126
 
2127
+ /**
2128
+ * The focus state a part's own styles key on: a part whose styled element
2129
+ * is a wrapper (a text input's box) shows focus only through
2130
+ * `focus-within`; null when it keys on none.
2131
+ * @param {Ctx} ctx
2132
+ * @param {string} part
2133
+ * @returns {string | null}
2134
+ */
2135
+ export function focusStateOf(ctx, part) {
2136
+ const conds = JSON.stringify(ctx.C.MAP[part]?.own ?? {});
2137
+ for (const st of ['focus-within', 'focus-visible', 'focus'])
2138
+ if (conds.includes(`:${st}`)) return st;
2139
+ return null;
2140
+ }
2141
+
2142
+ /**
2143
+ * The radius token a part's resting corners read. A part the census saw
2144
+ * closed (a menu, a popover) has none recorded: a container or menu reads
2145
+ * the container radius, like every Core surface; any other part reads the
2146
+ * element radius.
2147
+ * @param {Ctx} ctx
2148
+ * @param {string} part
2149
+ * @param {string} [when]
2150
+ * @returns {string}
2151
+ */
2152
+ export function radiusTokenOf(ctx, part, when) {
2153
+ return (
2154
+ /var\((--radius-[\w-]+)\)/.exec(
2155
+ partDefault(ctx, part, 'borderRadius', when) ?? '',
2156
+ )?.[1] ??
2157
+ ctx.C.partReads(part, 'corners').find(
2158
+ (/** @type {any} */ x) =>
2159
+ x.props.includes('border-radius') && /^--radius-/.test(x.token),
2160
+ )?.token ??
2161
+ (['containers', 'menus'].includes(familyOf(part) ?? '')
2162
+ ? '--radius-container'
2163
+ : '--radius-element')
2164
+ );
2165
+ }
2166
+
2167
+ /** The file a `new` keeps beside the files it writes until it is done. */
2168
+ export const NEW_MARKER = '.astryx-new.json';
2169
+
2170
+ /**
2171
+ * Remove a `new` marker from a theme folder whose settings are whole: the
2172
+ * `new` that left it made the theme, and nothing is left to finish.
2173
+ * @param {string} dir
2174
+ */
2175
+ export function clearNewMarker(dir) {
2176
+ // Fenced like every write under the theme lock.
2177
+ refuseIfLockLost();
2178
+ try {
2179
+ fs.rmSync(path.join(dir, NEW_MARKER), {force: true});
2180
+ } catch {
2181
+ // Read-only: the next writing command tries again.
2182
+ }
2183
+ }
2184
+
2185
+ /**
2186
+ * 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.
2189
+ * @param {string} state
2190
+ * @returns {string}
2191
+ */
2192
+ export function stateKey(state) {
2193
+ return state === 'disabled'
2194
+ ? ':is(:disabled,[aria-disabled="true"])'
2195
+ : `:${state}`;
2196
+ }
2197
+
2198
+ /**
2199
+ * The whole-theme radius tokens a generated settings module writes, or null
2200
+ * when it writes none.
2201
+ * @param {string} source
2202
+ * @returns {Record<string, string> | null}
2203
+ */
2204
+ export function radiiIn(source) {
2205
+ /** @type {Record<string, string>} */
2206
+ const out = {};
2207
+ for (const m of source.matchAll(
2208
+ /^ {4}"(--radius-(?:element|inner|container|page))": "([^"]+)"/gm,
2209
+ ))
2210
+ out[m[1]] = m[2];
2211
+ return Object.keys(out).length ? out : null;
2212
+ }
2213
+
2214
+ /**
2215
+ * A history step: the settings as they were, with the radii their build
2216
+ * showed (so a step back restores them exactly, also for a theme an earlier
2217
+ * editor built). A step an older CLI wrote has none, and is read as before.
2218
+ * @param {string} text
2219
+ * @param {Record<string, string> | null} radii
2220
+ */
2221
+ function withBuilt(text, radii) {
2222
+ if (!radii) return text;
2223
+ try {
2224
+ const data = JSON.parse(text.replace(/^\uFEFF/, ''));
2225
+ if (!settingsShapeOk(data)) return text;
2226
+ return `${JSON.stringify({...data, built: {radii}}, null, 2)}\n`;
2227
+ } catch {
2228
+ return text;
2229
+ }
2230
+ }
2231
+
1846
2232
  /**
1847
2233
  * The radius, in px, the build writes for a radius token at a corners value
1848
2234
  * (a rung, or a size). The derived radii keep the base theme's own
@@ -1866,23 +2252,43 @@ export function radiusAt(base, value, token) {
1866
2252
  return el && v != null ? v / el : fallback;
1867
2253
  };
1868
2254
  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')
2255
+ // Inner corners (a checkbox) stay a rounded square: never rounder than
2256
+ // at round, so pill keeps round's and no step makes them smaller.
2257
+ if (token === '--radius-inner') {
2258
+ const inner = (/** @type {number} */ x) =>
2259
+ Math.round(x * Math.min(1, ratio(token, 0.6)));
2260
+ return Math.min(inner(roundPx), inner(pill ? roundPx : px));
2261
+ }
2262
+ // A container or page is never rounder than at pill, so pill never makes
2263
+ // one less round, and a size just under 1000px meets pill smoothly.
2264
+ if (token === '--radius-container') {
2265
+ const atPill = Math.max(24, 1.5 * roundPx * ratio(token, 1.25));
1878
2266
  return Math.round(
1879
- pill
1880
- ? Math.max(32, 1.5 * roundPx * ratio(token, 2.5))
1881
- : px * ratio(token, 2.5),
2267
+ pill ? atPill : Math.min(atPill, px * ratio(token, 1.25)),
1882
2268
  );
2269
+ }
2270
+ if (token === '--radius-page') {
2271
+ const atPill = Math.max(32, 1.5 * roundPx * ratio(token, 2.5));
2272
+ return Math.round(pill ? atPill : Math.min(atPill, px * ratio(token, 2.5)));
2273
+ }
1883
2274
  return pill ? 9999 : px;
1884
2275
  }
1885
2276
 
2277
+ /**
2278
+ * Whether a file is a module the editor generated (its first line is the
2279
+ * editor's header).
2280
+ * @param {string} file
2281
+ */
2282
+ export function madeByEditor(file) {
2283
+ try {
2284
+ return fs
2285
+ .readFileSync(file, 'utf8')
2286
+ .startsWith('// Generated by `astryx experimental theme editor`');
2287
+ } catch {
2288
+ return false;
2289
+ }
2290
+ }
2291
+
1886
2292
  /**
1887
2293
  * The files the editor writes for a theme, after `<slug>.`: the only ones a
1888
2294
  * change reads, hashes or puts back, and the only ones a stopped `new`
@@ -2066,18 +2472,6 @@ export function settingsStamp(data) {
2066
2472
  return `${hash} (CLI ${cliVersion()})`;
2067
2473
  }
2068
2474
 
2069
- /**
2070
- * Whether the theme's build was made, whole, from these settings by this
2071
- * CLI (a command stopped mid-build, or settings edited by hand, leave it
2072
- * behind).
2073
- * @param {string} cwd
2074
- * @param {string} slug
2075
- * @param {ThemeData} data
2076
- */
2077
- export function buildCurrent(cwd, slug, data) {
2078
- return staleBuild(cwd, slug, data) == null;
2079
- }
2080
-
2081
2475
  /**
2082
2476
  * Why the theme's build does not match its settings, in words, or null when
2083
2477
  * it does: a file missing, another CLI version, settings changed since the
@@ -2116,11 +2510,29 @@ export function staleBuild(cwd, slug, data) {
2116
2510
  if (built && now && built !== now)
2117
2511
  return `@astryxdesign/theme-${data.like} is ${now} now, and the build was made on ${built}`;
2118
2512
  }
2513
+ // By content, never by file times (an editor's re-save or a checkout
2514
+ // changes those): a generated module cut short, or built outputs whose
2515
+ // header names another CLI than the settings were written by (a build
2516
+ // stopped after the settings module was written).
2517
+ const builtBy = (/** @type {string} */ file) =>
2518
+ /^ \* CLI: @astryxdesign\/cli@(\S+)$/m.exec(
2519
+ fs.readFileSync(file, 'utf8').slice(0, 600),
2520
+ )?.[1] ?? null;
2119
2521
  if (
2120
2522
  !ts.trimEnd().endsWith('});') ||
2121
- fs.statSync(f.css).mtimeMs < fs.statSync(f.settingsTs).mtimeMs - 1000
2523
+ [f.css, f.js].some(file => {
2524
+ const by = builtBy(file);
2525
+ return by != null && by !== stamp[2];
2526
+ })
2122
2527
  )
2123
2528
  return 'the last build did not finish (a command stopped while building)';
2529
+ // A built stylesheet cut short (a crash, a bad merge) is built again, as
2530
+ // an unreadable built module is.
2531
+ try {
2532
+ postcss.parse(fs.readFileSync(f.css, 'utf8'));
2533
+ } catch {
2534
+ return `${slug}.css is not valid CSS (cut short or damaged)`;
2535
+ }
2124
2536
  return null;
2125
2537
  }
2126
2538
 
@@ -2148,27 +2560,9 @@ function baseVersionOf(cwd, like) {
2148
2560
  }
2149
2561
  }
2150
2562
 
2151
- /** @param {string} dir */
2152
- function removeIfEmpty(dir) {
2153
- try {
2154
- fs.rmdirSync(dir);
2155
- } catch {
2156
- // Not empty, or gone already.
2157
- }
2158
- }
2159
-
2160
2563
  /** The undo steps a theme keeps; older ones are dropped. */
2161
2564
  export const HISTORY_STEPS = 80;
2162
2565
 
2163
- /**
2164
- * Write a file whole: a new file beside it, renamed into place.
2165
- * @param {string} file
2166
- * @param {string} text
2167
- */
2168
- export function writeAtomic(file, text) {
2169
- writeWhole(file, text);
2170
- }
2171
-
2172
2566
  /**
2173
2567
  * A theme's undo history: the settings text before each change, oldest
2174
2568
  * first, and how many damaged steps were dropped. Every step after the
@@ -2213,10 +2607,16 @@ export function readHistory(file) {
2213
2607
  * @param {Ctx} ctx
2214
2608
  * @param {string} slug
2215
2609
  * @param {ThemeData} data
2216
- * @param {{history: boolean, historyAfter?: string[]}} options
2217
- * `historyAfter`: the history to write with the change (a step back pops it)
2610
+ * @param {{history: boolean, historyAfter?: string[], radii?: Record<string, string> | null}} options
2611
+ * `historyAfter`: the history to write with the change (a step back pops it);
2612
+ * `radii`: the whole-theme radii the step being restored was built with
2218
2613
  */
2219
- export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2614
+ export async function commitTheme(
2615
+ ctx,
2616
+ slug,
2617
+ data,
2618
+ {history, historyAfter, radii},
2619
+ ) {
2220
2620
  const {cwd} = ctx.project;
2221
2621
  const f = themeFiles(cwd, slug);
2222
2622
  refuseLinks(cwd, slug);
@@ -2243,7 +2643,10 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2243
2643
  a != null &&
2244
2644
  JSON.stringify({...a, lifted: undefined}) ===
2245
2645
  JSON.stringify({...data, lifted: undefined});
2246
- if (history && same(parseSettings(snapBefore)) && fs.existsSync(f.js))
2646
+ // A no-op change still mends a build that does not match the settings
2647
+ // (an undo stopped part way): it is built again, with no new step.
2648
+ const noop = history && same(parseSettings(snapBefore));
2649
+ if (noop && fs.existsSync(f.js) && !staleBuild(cwd, slug, data))
2247
2650
  return {
2248
2651
  changed: [],
2249
2652
  res: {light: {}, dark: {}},
@@ -2266,6 +2669,54 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2266
2669
  : null;
2267
2670
  const before = parseSettings(snapBefore);
2268
2671
  const liftedBefore = new Set(before?.lifted ?? []);
2672
+ // A change that leaves every color setting as it was keeps the shades the
2673
+ // theme already shows: a theme an earlier editor built keeps its colors
2674
+ // until a color, the mode or the base changes, and undo brings them back.
2675
+ /** @param {ThemeData | null} d */
2676
+ const colorKey = d =>
2677
+ d &&
2678
+ JSON.stringify({
2679
+ mode: d.mode ?? 'both',
2680
+ like: d.like ?? null,
2681
+ colors: d.settings.filter(
2682
+ x =>
2683
+ (x.source === 'dial' &&
2684
+ (PALETTE_DIALS.includes(x.thing) || x.thing === 'vibrancy')) ||
2685
+ (x.source === 'token' && isColorToken(x.thing)),
2686
+ ),
2687
+ });
2688
+ // A module edited by hand (it says "do not edit") keeps nothing: it is
2689
+ // built over from the settings, as its header says.
2690
+ const moduleNow = fs.existsSync(f.settingsTs)
2691
+ ? fs.readFileSync(f.settingsTs, 'utf8')
2692
+ : null;
2693
+ ctx.keepStops =
2694
+ before &&
2695
+ colorKey(before) === colorKey(data) &&
2696
+ moduleNow &&
2697
+ moduleUnedited(moduleNow) !== false
2698
+ ? stopsIn(moduleNow)
2699
+ : null;
2700
+ // The same for the whole-theme radii: kept while corners and the base
2701
+ // stay as they are; a step back restores the radii it was built with.
2702
+ /** @param {ThemeData | null} d */
2703
+ const cornersKey = d =>
2704
+ d &&
2705
+ JSON.stringify({
2706
+ like: d.like ?? null,
2707
+ corners: d.settings.filter(x => x.thing === 'corners' && !x.on),
2708
+ // An exact radius token feeds the built radii too.
2709
+ tokens: d.settings.filter(
2710
+ x => x.source === 'token' && /^--radius-/.test(x.thing),
2711
+ ),
2712
+ });
2713
+ const radiiNow =
2714
+ moduleNow && moduleUnedited(moduleNow) !== false
2715
+ ? radiiIn(moduleNow)
2716
+ : null;
2717
+ ctx.keepRadii =
2718
+ radii ??
2719
+ (before && cornersKey(before) === cornersKey(data) ? radiiNow : null);
2269
2720
  // What this run writes is recorded as it writes it, so a failed change
2270
2721
  // puts back exactly that and nothing else.
2271
2722
  const rootMade = !fs.existsSync(f.root);
@@ -2278,7 +2729,15 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2278
2729
  /** @type {{warnings: string[], lifted: string[], notes: string[]}} */
2279
2730
  let built;
2280
2731
  try {
2281
- built = await buildTheme(ctx, slug, data);
2732
+ refuseIfLockLost();
2733
+ try {
2734
+ built = await buildTheme(ctx, slug, data);
2735
+ } finally {
2736
+ ctx.keepStops = null;
2737
+ }
2738
+ // The build writes its outputs itself: a lock lost meanwhile is seen
2739
+ // before anything else is written.
2740
+ refuseIfLockLost();
2282
2741
  data.lifted = built.lifted;
2283
2742
  // The undo step and the settings are part of the change: written whole,
2284
2743
  // inside the rollback, the settings first. A command stopped between
@@ -2286,23 +2745,36 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2286
2745
  // for an undo, a top step equal to the settings, which undo skips),
2287
2746
  // never a step that undoes nothing or a lost step.
2288
2747
  await track(f.dir, wrote, () => {
2289
- writeAtomic(f.settings, `${JSON.stringify(data, null, 2)}\n`);
2748
+ writeWhole(f.settings, `${JSON.stringify(data, null, 2)}\n`);
2290
2749
  if (historyAfter)
2291
- writeAtomic(
2750
+ writeWhole(
2292
2751
  f.history,
2293
2752
  JSON.stringify(historyAfter.slice(-HISTORY_STEPS)),
2294
2753
  );
2295
- else if (snapBefore && history)
2296
- writeAtomic(
2754
+ else if (snapBefore && history && !noop)
2755
+ writeWhole(
2297
2756
  f.history,
2298
- JSON.stringify([...past, snapBefore].slice(-HISTORY_STEPS)),
2757
+ JSON.stringify(
2758
+ [...past, withBuilt(snapBefore, radiiNow)].slice(-HISTORY_STEPS),
2759
+ ),
2299
2760
  );
2300
2761
  });
2762
+ // Settings written whole: a `new` marker left beside them (a `new`
2763
+ // stopped after its theme was made) has nothing left to finish.
2764
+ clearNewMarker(f.dir);
2301
2765
  } catch (e) {
2766
+ // A command that lost its lock while stopped owns none of these files
2767
+ // now: it puts nothing back and deletes nothing (that would undo the
2768
+ // other command's change).
2769
+ if (/** @type {any} */ (e)?.lockLost || !lockHeld()) {
2770
+ ctx.keepStops = null;
2771
+ if (/** @type {any} */ (e)?.lockLost) throw e;
2772
+ refuseIfLockLost();
2773
+ }
2302
2774
  const {failed, skipped} = restoreWritten(was, wrote);
2303
- removeIfEmpty(path.join(f.dir, 'tokens'));
2304
- if (dirMade) removeIfEmpty(f.dir);
2305
- if (rootMade) removeIfEmpty(f.root);
2775
+ removeEmptyFolder(path.join(f.dir, 'tokens'));
2776
+ if (dirMade) removeEmptyFolder(f.dir);
2777
+ if (rootMade) removeEmptyFolder(f.root);
2306
2778
  if (failed.length || skipped.length)
2307
2779
  throw new AstryxError(
2308
2780
  `The change failed (${e instanceof Error ? e.message.split('\n')[0] : String(e)}). ${failed.length ? `These files could not be put back: ${failed.join(', ')}. ` : ''}${skipped.length ? `These files changed while it ran, so they were left as they are: ${skipped.join(', ')}. ` : ''}Run ${P} show ${slug} to rebuild from the settings.`,
@@ -2313,7 +2785,12 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2313
2785
  if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO', 'EISDIR'].includes(code))
2314
2786
  throw new AstryxError(
2315
2787
  `Could not write the theme files (${code}), so the change was undone. Free space or fix the permission, then run the command again.`,
2316
- [],
2788
+ [
2789
+ {
2790
+ name: `ls -ld ${quoteCommandArgument(themeFiles(ctx.project.cwd, slug).dir)}`,
2791
+ reason: 'see who owns the theme folder',
2792
+ },
2793
+ ],
2317
2794
  ERROR_CODES.ERR_WRITE_FAILED,
2318
2795
  );
2319
2796
  // The color config's own refusals already name the file and the fix.
@@ -2322,7 +2799,8 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2322
2799
  (e.code === ERROR_CODES.ERR_UNKNOWN_THEME ||
2323
2800
  e.code === ERROR_CODES.ERR_THEME_INVALID ||
2324
2801
  e.code === ERROR_CODES.ERR_PALETTE_GENERATION ||
2325
- e.code === ERROR_CODES.ERR_WRITE_FAILED)
2802
+ e.code === ERROR_CODES.ERR_WRITE_FAILED ||
2803
+ e.code === ERROR_CODES.ERR_THEME_BUSY)
2326
2804
  )
2327
2805
  throw e;
2328
2806
  const why = (e instanceof Error ? e.message : String(e))
@@ -2357,18 +2835,37 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2357
2835
  res = await resolvedTokens(ctx, slug);
2358
2836
  const modes = modesOf(data);
2359
2837
  if (resBefore) {
2360
- for (const m of modes) {
2838
+ /** @param {unknown} a @param {unknown} b */
2839
+ const same = (a, b) =>
2840
+ String(a).toLowerCase() === String(b).toLowerCase();
2841
+ // Both modes are compared: a theme that becomes one-mode changes what
2842
+ // the other mode's visitors see, though it no longer has that mode.
2843
+ for (const m of /** @type {const} */ (['light', 'dark'])) {
2844
+ const own = modes.includes(m);
2361
2845
  for (const k of Object.keys(res[m])) {
2362
2846
  // A change of letter case alone (#FFFFFF, #ffffff) is no change.
2847
+ if (same(resBefore[m][k], res[m][k])) continue;
2848
+ const modal = MODAL.has(ctx.C.typeOf(k));
2849
+ if (!modal && m === 'dark') continue;
2850
+ // A one-mode theme writes its mode on both sides: the other side
2851
+ // that moved with it says nothing new, and a setting made for the
2852
+ // mode it dropped (and what reads it) is named as not applied
2853
+ // instead.
2363
2854
  if (
2364
- String(resBefore[m][k]).toLowerCase() ===
2365
- String(res[m][k]).toLowerCase()
2855
+ modal &&
2856
+ !own &&
2857
+ ((same(resBefore[m][k], resBefore[modes[0]][k]) &&
2858
+ same(res[m][k], res[modes[0]][k])) ||
2859
+ data.settings.some(
2860
+ x =>
2861
+ x.source === 'token' &&
2862
+ x.mode === m &&
2863
+ (x.thing === k || same(x.value, resBefore[m][k])),
2864
+ ))
2366
2865
  )
2367
2866
  continue;
2368
- const modal = MODAL.has(ctx.C.typeOf(k));
2369
- if (!modal && m === 'dark' && modes.length > 1) continue;
2370
2867
  changed.push(
2371
- `${k}${modal && modes.length > 1 ? ` (${m})` : ''}: ${resBefore[m][k]} -> ${res[m][k]}`,
2868
+ `${k}${modal && (modes.length > 1 || !own) ? ` (${m})` : ''}: ${resBefore[m][k]} -> ${res[m][k]}`,
2372
2869
  );
2373
2870
  }
2374
2871
  }
@@ -2393,19 +2890,27 @@ export async function commitTheme(ctx, slug, data, {history, historyAfter}) {
2393
2890
 
2394
2891
  /** @param {Ctx} ctx @param {ThemeData} data */
2395
2892
  export function fontPackages(ctx, data) {
2396
- /** @type {Array<{pkg: string, family: string, installed: boolean}>} */
2893
+ /** @type {Array<{pkg: string, family: string, installed: boolean, of: Setting}>} */
2397
2894
  const out = [];
2398
- for (const s of data.settings) {
2399
- if (s.thing !== 'font') continue;
2400
- const {pkg, family} = fontOf(s.value);
2401
- if (!pkg || out.some(x => x.pkg === pkg)) continue;
2402
- let installed = true;
2895
+ /** @param {string} pkg */
2896
+ const isInstalled = pkg => {
2403
2897
  try {
2404
2898
  ctx.project.req.resolve(`${pkg}/package.json`);
2899
+ return true;
2405
2900
  } catch {
2406
- installed = false;
2901
+ return false;
2407
2902
  }
2408
- out.push({pkg, family: family.replace(/["']/g, ''), installed});
2903
+ };
2904
+ for (const s of data.settings) {
2905
+ if (s.thing !== 'font') continue;
2906
+ const {pkg: known, family} = fontOf(s.value);
2907
+ const name = family.replace(/["']/g, '');
2908
+ // An installed @fontsource package of the family always loads it, even
2909
+ // for a family some systems ship.
2910
+ const own = `@fontsource/${name.toLowerCase().replace(/\s+/g, '-')}`;
2911
+ const pkg = known ?? (isInstalled(own) ? own : null);
2912
+ if (!pkg || out.some(x => x.pkg === pkg)) continue;
2913
+ out.push({pkg, family: name, installed: isInstalled(pkg), of: s});
2409
2914
  }
2410
2915
  return out;
2411
2916
  }