@designtools/tokens 0.3.0 → 0.5.0

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.
package/dist/cli.js CHANGED
@@ -5,20 +5,30 @@ import {
5
5
  SHADE_PRESETS,
6
6
  TOKEN_SECTIONS,
7
7
  VALID_SHADES,
8
+ checkRampChroma,
8
9
  checkSemanticContrast,
9
10
  checkSemanticContrastAPCA,
11
+ checkSurfaceContrast,
10
12
  computeAccessibilityScore,
13
+ diffSlice,
11
14
  exportTokens,
15
+ extendedBridgeShades,
16
+ externalReferences,
12
17
  generateTokens,
18
+ isInGamut,
19
+ mergeSlice,
20
+ overrideContract,
13
21
  parseProvenance,
14
22
  parseToOklch,
15
23
  provenanceComment,
16
24
  resolveShades,
25
+ ringBridgeShade,
17
26
  seedFingerprint,
18
27
  selectTokenSections,
19
28
  snapShade,
29
+ tokenFamilies,
20
30
  withJsonProvenance
21
- } from "./chunk-3OG7U5V2.js";
31
+ } from "./chunk-D6675UF5.js";
22
32
 
23
33
  // src/cli.ts
24
34
  import { parseArgs } from "util";
@@ -34,7 +44,10 @@ Seeds:
34
44
  --primary <colour> Brand colour (hex, rgb(), hsl(), oklch(), named). Required
35
45
  unless supplied by --seed.
36
46
  --neutral <colour> Neutral seed. Default: ${DEFAULT_NEUTRAL_COLOR}
37
- --color <name>=<colour> Additional brand colour scale. Repeatable.
47
+ --color <name>=<colour>[@<shade>]
48
+ Additional brand colour scale. Repeatable. Append
49
+ @<shade> to anchor its seed on that step, as
50
+ --seed-shade does for the primary: accent=#fde68a@200.
38
51
  --seed <file.json> Replay a saved configuration (the shape the web tool
39
52
  persists). Any flag given alongside it wins, so a seed
40
53
  file is a set of defaults rather than a lock.
@@ -43,19 +56,43 @@ Generation options:
43
56
  --contrast <wcag|apca> Contrast algorithm for foreground selection. Default: wcag
44
57
  --target <aa-large|aa|aaa> Contrast target level. Default: aa
45
58
  --lightness <fixed|perceptual> Lightness distribution strategy. Default: fixed
46
- --seed-shade <25..950> Which step the seed colour lands on. Default: 500.
59
+ --seed-shade <25..950> Which step the primary seed lands on. Default: 500.
47
60
  Brand colours arrive as whatever they are; a deep
48
61
  navy or a pale tint forced onto 500 leaves no
49
62
  headroom on one side and wrecks the ramp.
63
+ Moves the primary only: neutral and the derived
64
+ status colours stay on 500. (Before 0.5.0 it moved
65
+ every family.) Anchor the others with
66
+ --neutral-seed-shade and --color name=colour@shade.
67
+ --neutral-seed-shade <25..950> Which step the neutral seed lands on. Default: 500.
50
68
  --shades <list|preset> Which steps to emit. Default: all twelve (25-950).
51
69
  Presets: tailwind (50-950, matching Tailwind's
52
70
  stock ramps) and full. Or a list: 50,100,500,900.
53
71
  Tokens naming a dropped step snap to the nearest
54
72
  emitted one, reported on stderr.
73
+ --gamut <srgb|p3> Which displays to generate for. Default: srgb.
74
+ srgb: every colour is one every screen shows exactly,
75
+ so the contrast checks measure what is displayed.
76
+ p3: also emit richer ramps in a
77
+ @media (color-gamut: p3) block for displays that can
78
+ show them (most phones and Macs). Every foreground is
79
+ chosen to pass on both. css and tailwind-v4 only;
80
+ json carries them as "p3".
55
81
  --overrides <file.json> JSON file with { shadeOverrides, surfaceShadeOverrides,
56
82
  utilityShadeOverrides } (same shape as the web tool).
57
83
 
58
84
  Selection:
85
+ --ramps <names> Restrict output to these colour families, comma-separated
86
+ or repeated. A family is one colour plus everything
87
+ computed against it: its ramp, its alias ramp, and its
88
+ semantic tokens with their contrast-derived foregrounds.
89
+ That is the safe unit to regenerate on its own, because
90
+ the contrast search runs inside it.
91
+ Use with --merge to regenerate part of a token file
92
+ without rewriting regions a human has edited.
93
+ Surfaces and utilities belong to no single colour, so a
94
+ family-scoped slice leaves them alone.
95
+
59
96
  --only <sections> Emit only these slices, comma-separated or repeated:
60
97
  ramp the twelve-step colour ramps alone
61
98
  primitives the ramps plus black and white
@@ -76,10 +113,9 @@ Output:
76
113
  Default: oklch
77
114
  --out <path> File to write (or directory when --format all).
78
115
  Omit to print to stdout.
79
- --vanilla Accepted and ignored. The shadcn/ui aliases it used to
80
- switch off are gone in 0.2, so vanilla is now the only
81
- behaviour. Kept for one version so existing calls do not
82
- break; it will be removed in 0.3.
116
+ --vanilla Deprecated no-op, warns. The shadcn/ui aliases it used to
117
+ switch off no longer exist, so vanilla is the only
118
+ behaviour. Still accepted so existing calls keep working.
83
119
  --no-replace-palette tailwind-v4 only: keep Tailwind's stock colour palette.
84
120
  By default the generated theme clears it
85
121
  (--color-*: initial), so a colour class this tool does
@@ -87,7 +123,13 @@ Output:
87
123
  rendering off-brand. Pass this when adopting the
88
124
  generator into an existing Tailwind codebase that still
89
125
  uses stock hues like bg-slate-900.
90
- --replace-palette Accepted and ignored; this is the default in 0.3.
126
+ --replace-palette Deprecated no-op, warns; clearing the palette is the
127
+ default. Use --no-replace-palette to opt out instead.
128
+ --merge Rewrite only the declarations this run generates into the
129
+ existing file at --out, preserving every other line byte
130
+ for byte. A colour family spans four blocks (:root, light,
131
+ dark and the prefers-color-scheme fallback), so this is
132
+ what makes a partial regeneration safe to apply.
91
133
  --no-provenance Omit the "Generated by \u2026" header. The header is what
92
134
  makes --check able to distinguish a generator upgrade
93
135
  from a hand edit, so dropping it costs you that.
@@ -97,6 +139,9 @@ Verification:
97
139
  at --out. Writes nothing. Exit 0 if identical, 1 if it
98
140
  differs, and reports a version mismatch distinctly from
99
141
  an edit. Requires --out.
142
+ With --ramps or --merge, only the declarations this run
143
+ generates are compared, so hand-edited regions elsewhere
144
+ in the file are not reported as drift.
100
145
  --report Print the measured contrast of every semantic foreground
101
146
  pairing to stderr, with an overall score against the
102
147
  --contrast algorithm and --target level. Writes no files
@@ -138,10 +183,14 @@ try {
138
183
  contrast: { type: "string" },
139
184
  target: { type: "string" },
140
185
  lightness: { type: "string" },
186
+ gamut: { type: "string" },
141
187
  "seed-shade": { type: "string" },
188
+ "neutral-seed-shade": { type: "string" },
142
189
  shades: { type: "string" },
143
190
  overrides: { type: "string" },
144
191
  only: { type: "string", multiple: true },
192
+ ramps: { type: "string", multiple: true },
193
+ merge: { type: "boolean" },
145
194
  format: { type: "string" },
146
195
  "color-format": { type: "string" },
147
196
  out: { type: "string" },
@@ -203,22 +252,32 @@ var neutral = validateColor(
203
252
  values.neutral ?? seed.neutralColor ?? DEFAULT_NEUTRAL_COLOR
204
253
  );
205
254
  var additionalColors = {};
206
- for (const { name, color } of seed.additionalColors ?? []) {
255
+ var additionalAnchors = {};
256
+ for (const { name, color, seedShade: anchor } of seed.additionalColors ?? []) {
207
257
  additionalColors[name] = validateColor(`seed colour ${name}`, color);
258
+ if (anchor !== void 0) additionalAnchors[name] = { flag: `seed (additionalColors ${name})`, raw: anchor };
208
259
  }
209
260
  for (const entry of values.color ?? []) {
210
261
  const eq = entry.indexOf("=");
211
262
  if (eq === -1) fail(`--color expects name=colour (got "${entry}")`);
212
263
  const name = entry.slice(0, eq).trim();
213
- const colour = entry.slice(eq + 1).trim();
264
+ let colour = entry.slice(eq + 1).trim();
214
265
  if (!/^[a-z][a-z0-9-]*$/i.test(name)) {
215
266
  fail(`--color name must be alphanumeric/kebab-case (got "${name}")`);
216
267
  }
268
+ const at = /^(.*)@(\d+)$/.exec(colour);
269
+ if (at) {
270
+ colour = at[1].trim();
271
+ additionalAnchors[name] = { flag: `color ${name}@`, raw: at[2] };
272
+ } else {
273
+ delete additionalAnchors[name];
274
+ }
217
275
  additionalColors[name] = validateColor(`color ${name}`, colour);
218
276
  }
219
277
  var contrastAlgorithm = validateChoice("contrast", values.contrast ?? seed.contrastAlgorithm, ["wcag", "apca"], "wcag");
220
278
  var contrastTarget = validateChoice("target", values.target ?? seed.contrastTarget, ["aa-large", "aa", "aaa"], "aa");
221
279
  var lightnessStrategy = validateChoice("lightness", values.lightness ?? seed.lightnessStrategy, ["fixed", "perceptual"], "fixed");
280
+ var gamut = validateChoice("gamut", values.gamut ?? seed.gamut, ["srgb", "p3"], "srgb");
222
281
  var format = validateChoice(
223
282
  "format",
224
283
  values.format,
@@ -227,7 +286,7 @@ var format = validateChoice(
227
286
  );
228
287
  var colorFormat = validateChoice("color-format", values["color-format"] ?? seed.colorFormat, ["oklch", "hex", "rgb", "hsl"], "oklch");
229
288
  function parseShade(flag, raw) {
230
- const n = Number(raw.trim());
289
+ const n = Number(String(raw).trim());
231
290
  if (!VALID_SHADES.includes(n)) {
232
291
  fail(`--${flag} must be one of: ${VALID_SHADES.join(", ")} (got "${raw}")`);
233
292
  }
@@ -241,9 +300,21 @@ if (shadesInput !== void 0) {
241
300
  if (shades.length < 3) fail(`--shades needs at least 3 steps (got ${shades.length})`);
242
301
  }
243
302
  var seedShade = values["seed-shade"] !== void 0 ? parseShade("seed-shade", values["seed-shade"]) : seed.seedShade;
244
- if (seedShade !== void 0 && shades !== void 0 && !shades.includes(seedShade)) {
245
- const emitted = shades;
246
- fail(`--seed-shade ${seedShade} is not in --shades (${emitted.join(", ")})`);
303
+ var neutralSeedShade = values["neutral-seed-shade"] !== void 0 ? parseShade("neutral-seed-shade", values["neutral-seed-shade"]) : seed.neutralSeedShade;
304
+ var seedShades = {};
305
+ if (neutralSeedShade !== void 0) seedShades.neutral = neutralSeedShade;
306
+ for (const [name, { flag, raw }] of Object.entries(additionalAnchors)) {
307
+ seedShades[name] = parseShade(flag, raw);
308
+ }
309
+ for (const [flag, anchor] of [
310
+ ["--seed-shade", seedShade],
311
+ ...Object.entries(seedShades).map(
312
+ ([name, a]) => [name === "neutral" && neutralSeedShade !== void 0 ? "--neutral-seed-shade" : `--color ${name}@`, a]
313
+ )
314
+ ]) {
315
+ if (anchor !== void 0 && shades !== void 0 && !shades.includes(anchor)) {
316
+ fail(`${flag} ${anchor} is not in --shades (${shades.join(", ")})`);
317
+ }
247
318
  }
248
319
  var sections = (values.only ?? []).flatMap((entry) => entry.split(",")).map((s) => s.trim()).filter((s) => s.length > 0).map((s) => {
249
320
  if (!TOKEN_SECTIONS.includes(s)) {
@@ -251,6 +322,17 @@ var sections = (values.only ?? []).flatMap((entry) => entry.split(",")).map((s)
251
322
  }
252
323
  return s;
253
324
  });
325
+ var families = (values.ramps ?? []).flatMap((entry) => entry.split(",")).map((f) => f.trim()).filter((f) => f.length > 0);
326
+ if (families.length > 0 && !SECTIONED_FORMATS.includes(format) && format !== "json" && format !== "all") {
327
+ fail(`--ramps is not supported by --format ${format} (supported: ${[...SECTIONED_FORMATS, "json"].join(", ")})`);
328
+ }
329
+ if (values.merge) {
330
+ if (!values.out) fail("--merge needs --out to merge into");
331
+ if (format === "all") fail("--merge writes one file, so it cannot be used with --format all");
332
+ if (format === "dtcg" || format === "tailwind-v3" || format === "json") {
333
+ fail(`--merge only understands CSS-shaped output, not --format ${format}`);
334
+ }
335
+ }
254
336
  if (sections.length > 0) {
255
337
  const sectionable = [...SECTIONED_FORMATS, "json"];
256
338
  const targets = format === "all" ? SECTIONED_FORMATS : [format];
@@ -281,12 +363,57 @@ var options = {
281
363
  contrastTarget,
282
364
  lightnessStrategy,
283
365
  seedShade,
366
+ ...Object.keys(seedShades).length > 0 ? { seedShades } : {},
284
367
  shades,
285
368
  shadeOverrides: overrides.shadeOverrides ?? {},
286
369
  surfaceShadeOverrides: overrides.surfaceShadeOverrides,
287
- utilityShadeOverrides: overrides.utilityShadeOverrides
370
+ utilityShadeOverrides: overrides.utilityShadeOverrides,
371
+ gamut
288
372
  };
373
+ {
374
+ const seeds = [
375
+ ["--primary", primary],
376
+ ["--neutral", neutral],
377
+ ...Object.entries(additionalColors).map(([name, c]) => [`--color ${name}`, c])
378
+ ];
379
+ for (const [label, colour] of seeds) {
380
+ if (isInGamut(colour, "srgb")) continue;
381
+ const kept = gamut === "p3" && isInGamut(colour, "p3");
382
+ process.stderr.write(
383
+ `generate-tokens: ${label} ${colour} is outside sRGB; its chroma is reduced to fit, keeping lightness and hue.` + (kept ? ` The p3 layer keeps it as given.
384
+ ` : `
385
+ `)
386
+ );
387
+ }
388
+ }
389
+ if (gamut === "p3") {
390
+ const flat = (format === "all" ? ["tailwind-v3", "dtcg"] : [format]).filter(
391
+ (f) => f === "tailwind-v3" || f === "dtcg"
392
+ );
393
+ for (const f of flat) {
394
+ process.stderr.write(
395
+ `generate-tokens: --format ${f} has no way to carry a wide-gamut layer; it gets the sRGB values only.
396
+ `
397
+ );
398
+ }
399
+ }
400
+ for (const [flag, why] of [
401
+ ["vanilla", "the shadcn/ui aliases it switched off no longer exist, so this is already the only behaviour"],
402
+ ["replace-palette", "clearing Tailwind's stock palette is the default; use --no-replace-palette to opt out"]
403
+ ]) {
404
+ if (values[flag]) {
405
+ process.stderr.write(`generate-tokens: --${flag} does nothing \u2014 ${why}
406
+ `);
407
+ }
408
+ }
289
409
  var tokens = generateTokens(brandColors, options);
410
+ if (families.length > 0) {
411
+ const known = tokenFamilies(tokens);
412
+ const unknown = families.filter((f) => !known.includes(f));
413
+ if (unknown.length > 0) {
414
+ fail(`--ramps names no such colour: ${unknown.join(", ")} (available: ${known.join(", ")})`);
415
+ }
416
+ }
290
417
  if (shades) {
291
418
  const named = [
292
419
  ["muted (light)", 25],
@@ -321,16 +448,24 @@ var replacePalette = values["no-replace-palette"] !== true;
321
448
  var resolvedSeed = {
322
449
  primaryColor: primary,
323
450
  neutralColor: neutral,
324
- additionalColors: Object.entries(additionalColors).map(([name, color]) => ({ name, color })),
451
+ additionalColors: Object.entries(additionalColors).map(([name, color]) => ({
452
+ name,
453
+ color,
454
+ seedShade: seedShades[name]
455
+ })),
325
456
  colorFormat,
326
457
  contrastAlgorithm,
327
458
  contrastTarget,
328
459
  lightnessStrategy,
329
460
  seedShade,
461
+ neutralSeedShade,
330
462
  shades,
331
463
  shadeOverrides: options.shadeOverrides ?? {},
332
464
  surfaceShadeOverrides: options.surfaceShadeOverrides,
333
- utilityShadeOverrides: options.utilityShadeOverrides
465
+ utilityShadeOverrides: options.utilityShadeOverrides,
466
+ // srgb is the default and was the only behaviour before --gamut existed, so
467
+ // it is left out: an sRGB seed keeps the fingerprint it always had.
468
+ gamut: gamut === "p3" ? gamut : void 0
334
469
  };
335
470
  var provenance = {
336
471
  version: VERSION,
@@ -338,17 +473,24 @@ var provenance = {
338
473
  };
339
474
  var stampProvenance = values["no-provenance"] !== true;
340
475
  var JSON_FORMATS = ["json", "dtcg"];
476
+ var CSS_SHAPED_FORMATS = ["css", "tailwind-v4"];
341
477
  function serialise(fmt) {
342
- const body = fmt === "json" ? JSON.stringify(selectTokenSections(tokens, sections), null, 2) : exportTokens(tokens, fmt, {
478
+ const body = fmt === "json" ? JSON.stringify(selectTokenSections(tokens, sections, families), null, 2) : exportTokens(tokens, fmt, {
343
479
  colorFormat,
344
480
  shadeOverrides: options.shadeOverrides,
345
481
  replacePalette,
346
482
  // `--format all` writes every format; only the sectionable ones get filtered.
347
483
  sections: SECTIONED_FORMATS.includes(fmt) ? sections : void 0,
348
- shades
484
+ shades,
485
+ families: SECTIONED_FORMATS.includes(fmt) ? families : void 0,
486
+ seedShade: options.seedShade,
487
+ seedShades: options.seedShades
349
488
  });
350
489
  if (!stampProvenance) return body;
351
- return JSON_FORMATS.includes(fmt) ? withJsonProvenance(body, provenance) : `${provenanceComment(provenance)}
490
+ if (JSON_FORMATS.includes(fmt)) return withJsonProvenance(body, provenance);
491
+ const header = CSS_SHAPED_FORMATS.includes(fmt) ? `${provenanceComment(provenance)}
492
+ ${overrideContract()}` : provenanceComment(provenance);
493
+ return `${header}
352
494
  ${body}`;
353
495
  }
354
496
  function targetPath(fmt, out) {
@@ -392,42 +534,176 @@ function check(fmt, target) {
392
534
  }
393
535
  return false;
394
536
  }
395
- function report() {
396
- const width = 34;
537
+ function reportBridge() {
538
+ const active = resolveShades(shades);
539
+ const anchored = Object.entries(seedShades);
540
+ process.stderr.write(
541
+ `
542
+ semantic bridge for primary, anchored at ${options.seedShade ?? 500} (${anchored.map(([n, a]) => `${n} at ${a}; `).join("")}other families at 500)
543
+ `
544
+ );
397
545
  for (const mode of ["light", "dark"]) {
398
- const semantic = tokens.semantic[mode];
399
- process.stderr.write(`
400
- ${mode} mode (${contrastAlgorithm}, target ${contrastTarget})
546
+ const e = extendedBridgeShades(mode, options.seedShade, active);
547
+ process.stderr.write(
548
+ ` ${mode.padEnd(6)} default ${String(e.DEFAULT).padStart(3)} subdued ${String(e.subdued).padStart(3)} highlight ${String(e.highlight).padStart(3)} ring ${String(ringBridgeShade(mode, options.seedShade, active)).padStart(3)}
549
+ `
550
+ );
551
+ }
552
+ }
553
+ function reportChroma() {
554
+ const chroma = checkRampChroma(tokens.primitives);
555
+ const unintended = ([name, r]) => r.low && name !== "neutral";
556
+ const low = Object.entries(chroma).filter(unintended);
557
+ process.stderr.write(`
558
+ ramp chroma (peak C per family)
401
559
  `);
402
- if (contrastAlgorithm === "wcag") {
403
- for (const [pair, r] of Object.entries(checkSemanticContrast(semantic))) {
404
- const mark = r.passesAAA ? "AAA" : r.passesAA ? "AA " : "- ";
405
- process.stderr.write(` ${mark} ${pair.padEnd(width)} ${r.ratio.toFixed(2)}:1
560
+ for (const [name, r] of Object.entries(chroma)) {
561
+ const mark = unintended([name, r]) ? "grey" : " ";
562
+ process.stderr.write(` ${mark} ${name.padEnd(14)} ${r.peak.toFixed(4)} at ${r.atShade}
406
563
  `);
407
- }
408
- } else {
409
- for (const [pair, r] of Object.entries(checkSemanticContrastAPCA(semantic))) {
410
- process.stderr.write(
411
- ` ${r.level.padEnd(10)} ${pair.padEnd(width)} Lc ${r.lcValue.toFixed(1)}
564
+ }
565
+ if (low.length > 0) {
566
+ process.stderr.write(
567
+ ` note: ${low.map(([n]) => n).join(", ")} carr${low.length === 1 ? "ies" : "y"} too little chroma to read as a marking
568
+ at small sizes. Picking harder will not fix it; a palette can be short of a colour.
412
569
  `
413
- );
570
+ );
571
+ }
572
+ }
573
+ function reportGamuts() {
574
+ const out = [
575
+ { gamut: "srgb", label: "", tiers: tokens }
576
+ ];
577
+ if (tokens.p3) out.push({ gamut: "p3", label: " on p3 displays", tiers: tokens.p3 });
578
+ return out;
579
+ }
580
+ function reportSurfaces() {
581
+ const width = 34;
582
+ for (const { gamut: g, label, tiers } of reportGamuts()) {
583
+ for (const mode of ["light", "dark"]) {
584
+ process.stderr.write(`
585
+ ${mode} surfaces and utilities${label} (wcag, not counted in the score)
586
+ `);
587
+ for (const [pair, r] of Object.entries(
588
+ checkSurfaceContrast(tiers.surface[mode], tiers.utility[mode], g)
589
+ )) {
590
+ const mark = r.advisory ? " " : r.nonText ? r.passes ? "3:1" : "- " : r.passesAAA ? "AAA" : r.passesAA ? "AA " : "- ";
591
+ const note = r.advisory ? " (advisory: 3:1 only where it bounds a control)" : r.nonText ? " (non-text, 1.4.11)" : "";
592
+ process.stderr.write(` ${mark} ${pair.padEnd(width)} ${r.ratio.toFixed(2)}:1${note}
593
+ `);
414
594
  }
415
595
  }
416
- const { score, passed, total } = computeAccessibilityScore(
417
- semantic,
418
- contrastAlgorithm,
419
- contrastTarget
420
- );
421
- process.stderr.write(` score: ${score}% (${passed}/${total} pairings)
596
+ }
597
+ }
598
+ function report() {
599
+ const width = 34;
600
+ reportBridge();
601
+ reportChroma();
602
+ for (const { gamut: g, label, tiers } of reportGamuts()) {
603
+ for (const mode of ["light", "dark"]) {
604
+ const semantic = tiers.semantic[mode];
605
+ process.stderr.write(`
606
+ ${mode} mode${label} (${contrastAlgorithm}, target ${contrastTarget})
422
607
  `);
608
+ if (contrastAlgorithm === "wcag") {
609
+ for (const [pair, r] of Object.entries(checkSemanticContrast(semantic, g))) {
610
+ const mark = r.passesAAA ? "AAA" : r.passesAA ? "AA " : "- ";
611
+ process.stderr.write(` ${mark} ${pair.padEnd(width)} ${r.ratio.toFixed(2)}:1
612
+ `);
613
+ }
614
+ } else {
615
+ for (const [pair, r] of Object.entries(checkSemanticContrastAPCA(semantic, g))) {
616
+ process.stderr.write(
617
+ ` ${r.level.padEnd(10)} ${pair.padEnd(width)} Lc ${r.lcValue.toFixed(1)}
618
+ `
619
+ );
620
+ }
621
+ }
622
+ const { score, passed, total } = computeAccessibilityScore(
623
+ semantic,
624
+ contrastAlgorithm,
625
+ contrastTarget,
626
+ g
627
+ );
628
+ process.stderr.write(` score: ${score}% (${passed}/${total} pairings)
629
+ `);
630
+ }
423
631
  }
632
+ reportSurfaces();
424
633
  }
425
634
  if (values.report) report();
426
635
  var formats = format === "all" ? Object.keys(FILE_NAMES) : [format];
636
+ var isSlice = families.length > 0 || sections.length > 0;
637
+ function reportExternalReferences(css) {
638
+ const external = externalReferences(css);
639
+ if (external.length === 0) return;
640
+ process.stderr.write(
641
+ `slice references ${external.length} token${external.length === 1 ? "" : "s"} defined elsewhere:
642
+ `
643
+ );
644
+ for (const name of external) process.stderr.write(` ${name}
645
+ `);
646
+ }
647
+ function checkSlice(target, slice) {
648
+ let existing;
649
+ try {
650
+ existing = readFileSync(target, "utf8");
651
+ } catch {
652
+ process.stderr.write(`check: ${target} does not exist
653
+ `);
654
+ return false;
655
+ }
656
+ const { matches, differing, missing } = diffSlice(existing, slice);
657
+ const scope = families.length > 0 ? families.join(", ") : sections.join(", ");
658
+ if (matches) {
659
+ process.stderr.write(`check: ${target} up to date for ${scope}
660
+ `);
661
+ return true;
662
+ }
663
+ process.stderr.write(
664
+ `check: ${target} differs for ${scope} \u2014 ${differing.length} changed, ${missing.length} missing
665
+ `
666
+ );
667
+ for (const d of differing.slice(0, 10)) {
668
+ process.stderr.write(` ${d.property} in ${d.block}
669
+ on disk: ${d.actual}
670
+ expected: ${d.expected}
671
+ `);
672
+ }
673
+ for (const m of missing.slice(0, 10)) {
674
+ process.stderr.write(` missing ${m.property} in ${m.block}
675
+ `);
676
+ }
677
+ return false;
678
+ }
427
679
  if (values.check) {
428
680
  const out = values.out;
681
+ if (isSlice) {
682
+ process.exit(checkSlice(targetPath(format, out), serialise(format)) ? 0 : 1);
683
+ }
429
684
  const ok = formats.map((fmt) => check(fmt, format === "all" ? join(out, FILE_NAMES[fmt]) : targetPath(fmt, out)));
430
685
  process.exit(ok.every(Boolean) ? 0 : 1);
686
+ } else if (values.merge) {
687
+ const target = targetPath(format, values.out);
688
+ let existing;
689
+ try {
690
+ existing = readFileSync(target, "utf8");
691
+ } catch (err) {
692
+ fail(`--merge needs an existing file at ${target}: ${err instanceof Error ? err.message : String(err)}`);
693
+ }
694
+ const slice = serialise(format).replace(/^\/\* Generated by [^\n]*\n/, "");
695
+ const result = mergeSlice(existing, slice);
696
+ if (result.missingBlocks.length > 0) {
697
+ fail(
698
+ `--merge cannot place ${result.missingBlocks.length} block(s) absent from ${target}: ` + result.missingBlocks.join(", ")
699
+ );
700
+ }
701
+ writeFileSync(target, result.css);
702
+ process.stderr.write(
703
+ `merged into ${target}: ${result.updated.length} updated, ${result.added.length} added, ${result.unchanged.length} already current
704
+ `
705
+ );
706
+ reportExternalReferences(slice);
431
707
  } else if (format === "all") {
432
708
  const dir = values.out ?? ".";
433
709
  mkdirSync(dir, { recursive: true });
@@ -447,4 +723,5 @@ if (values.check) {
447
723
  } else {
448
724
  process.stdout.write(output);
449
725
  }
726
+ if (isSlice && SECTIONED_FORMATS.includes(format)) reportExternalReferences(output);
450
727
  }