design-constraint-validator 1.0.0 → 1.1.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.
Files changed (116) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +215 -659
  3. package/adapters/README.md +46 -46
  4. package/adapters/css.ts +116 -116
  5. package/adapters/js.ts +14 -14
  6. package/adapters/json.ts +45 -45
  7. package/cli/build-css.ts +32 -32
  8. package/cli/commands/build.ts +65 -65
  9. package/cli/commands/graph.d.ts.map +1 -1
  10. package/cli/commands/graph.js +26 -10
  11. package/cli/commands/graph.ts +180 -137
  12. package/cli/commands/index.ts +7 -7
  13. package/cli/commands/patch-apply.ts +80 -80
  14. package/cli/commands/patch.ts +22 -22
  15. package/cli/commands/set.d.ts.map +1 -1
  16. package/cli/commands/set.js +12 -4
  17. package/cli/commands/set.ts +239 -225
  18. package/cli/commands/utils.ts +50 -50
  19. package/cli/commands/validate.d.ts.map +1 -1
  20. package/cli/commands/validate.js +86 -33
  21. package/cli/commands/validate.ts +176 -115
  22. package/cli/commands/why.d.ts.map +1 -1
  23. package/cli/commands/why.js +86 -20
  24. package/cli/commands/why.ts +158 -46
  25. package/cli/config-schema.ts +27 -27
  26. package/cli/config.ts +35 -35
  27. package/cli/constraint-registry.d.ts +101 -0
  28. package/cli/constraint-registry.d.ts.map +1 -0
  29. package/cli/constraint-registry.js +225 -0
  30. package/cli/constraint-registry.ts +304 -0
  31. package/cli/constraints-loader.d.ts +30 -0
  32. package/cli/constraints-loader.d.ts.map +1 -0
  33. package/cli/constraints-loader.js +58 -0
  34. package/cli/constraints-loader.ts +83 -0
  35. package/cli/cross-axis-loader.d.ts +91 -0
  36. package/cli/cross-axis-loader.d.ts.map +1 -0
  37. package/cli/cross-axis-loader.js +222 -0
  38. package/cli/cross-axis-loader.ts +289 -0
  39. package/cli/dcv.js +4 -0
  40. package/cli/dcv.ts +111 -107
  41. package/cli/engine-helpers.d.ts +33 -0
  42. package/cli/engine-helpers.d.ts.map +1 -1
  43. package/cli/engine-helpers.js +87 -22
  44. package/cli/engine-helpers.ts +133 -61
  45. package/cli/graph-poset.ts +74 -74
  46. package/cli/json-output.d.ts +64 -0
  47. package/cli/json-output.d.ts.map +1 -0
  48. package/cli/json-output.js +107 -0
  49. package/cli/json-output.ts +177 -0
  50. package/cli/result.ts +27 -27
  51. package/cli/run.ts +54 -54
  52. package/cli/smoke-test.ts +40 -40
  53. package/cli/types.d.ts +6 -0
  54. package/cli/types.d.ts.map +1 -1
  55. package/cli/types.ts +84 -78
  56. package/core/breakpoints.ts +50 -50
  57. package/core/cli-format.ts +31 -31
  58. package/core/color.ts +148 -148
  59. package/core/constraints/cross-axis.ts +114 -114
  60. package/core/constraints/monotonic-lightness.ts +38 -38
  61. package/core/constraints/monotonic.ts +74 -74
  62. package/core/constraints/threshold.ts +43 -43
  63. package/core/constraints/wcag.ts +70 -70
  64. package/core/cross-axis-config.d.ts +29 -0
  65. package/core/cross-axis-config.d.ts.map +1 -1
  66. package/core/cross-axis-config.js +29 -0
  67. package/core/cross-axis-config.ts +181 -151
  68. package/core/engine.d.ts +95 -0
  69. package/core/engine.d.ts.map +1 -1
  70. package/core/engine.js +22 -0
  71. package/core/engine.ts +167 -65
  72. package/core/flatten.ts +116 -116
  73. package/core/image-export.ts +48 -48
  74. package/core/index.d.ts +9 -30
  75. package/core/index.d.ts.map +1 -1
  76. package/core/index.js +7 -54
  77. package/core/index.ts +10 -72
  78. package/core/patch.ts +134 -134
  79. package/core/poset.ts +311 -311
  80. package/core/why.ts +63 -63
  81. package/package.json +96 -90
  82. package/themes/color.lg.order.json +15 -15
  83. package/themes/color.md.order.json +15 -15
  84. package/themes/color.order.json +15 -15
  85. package/themes/color.sm.order.json +15 -15
  86. package/themes/cross-axis.rules.json +35 -35
  87. package/themes/cross-axis.sm.rules.json +12 -12
  88. package/themes/layout.lg.order.json +18 -18
  89. package/themes/layout.md.order.json +18 -18
  90. package/themes/layout.order.json +18 -18
  91. package/themes/layout.sm.order.json +18 -18
  92. package/themes/spacing.order.json +14 -14
  93. package/themes/typography.lg.order.json +15 -15
  94. package/themes/typography.md.order.json +15 -15
  95. package/themes/typography.order.json +15 -15
  96. package/themes/typography.sm.order.json +15 -15
  97. package/dist/test-overrides-removal.json +0 -4
  98. package/dist/tmp.patch.json +0 -35
  99. package/tokens/overrides/base.json +0 -22
  100. package/tokens/overrides/lg.json +0 -20
  101. package/tokens/overrides/md.json +0 -16
  102. package/tokens/overrides/sm.json +0 -16
  103. package/tokens/overrides/viol.color.json +0 -6
  104. package/tokens/overrides/viol.typography.json +0 -6
  105. package/tokens/tokens.demo-violations.json +0 -116
  106. package/tokens/tokens.example.json +0 -128
  107. package/tokens/tokens.json +0 -67
  108. package/tokens/tokens.multi-violations.json +0 -21
  109. package/tokens/tokens.schema.d.ts +0 -2298
  110. package/tokens/tokens.schema.d.ts.map +0 -1
  111. package/tokens/tokens.schema.js +0 -148
  112. package/tokens/tokens.schema.ts +0 -196
  113. package/tokens/tokens.test.json +0 -38
  114. package/tokens/tokens.touch-violation.json +0 -8
  115. package/tokens/typography.classes.css +0 -11
  116. package/tokens/typography.css +0 -20
@@ -1,22 +1,22 @@
1
- import type { TokenNode } from '../../core/flatten.js';
2
- import { loadTokens, outputResult } from './utils.js';
3
- import { buildPatch } from '../../core/patch.js';
4
- import type { PatchOptions } from '../types.js';
5
-
6
- export async function patchCommand(opts: PatchOptions): Promise<void> {
7
- const tokens: TokenNode = loadTokens(opts.tokens || 'tokens/tokens.example.json');
8
- // For now just accept a flat overrides JSON file if provided
9
- let overrides: Record<string, any> | undefined;
10
- if (opts.overrides) {
11
- const fs = await import('node:fs');
12
- if (fs.existsSync(opts.overrides)) {
13
- overrides = JSON.parse(fs.readFileSync(opts.overrides, 'utf8'));
14
- } else if (opts.overrides.startsWith('{')) {
15
- overrides = JSON.parse(opts.overrides);
16
- } else {
17
- throw new Error(`Overrides not found: ${opts.overrides}`);
18
- }
19
- }
20
- const patchDoc = buildPatch({ tokens, overrides, baseFile: opts.tokens });
21
- outputResult(patchDoc, opts.format || 'json', opts.output);
22
- }
1
+ import type { TokenNode } from '../../core/flatten.js';
2
+ import { loadTokens, outputResult } from './utils.js';
3
+ import { buildPatch } from '../../core/patch.js';
4
+ import type { PatchOptions } from '../types.js';
5
+
6
+ export async function patchCommand(opts: PatchOptions): Promise<void> {
7
+ const tokens: TokenNode = loadTokens(opts.tokens || 'tokens/tokens.example.json');
8
+ // For now just accept a flat overrides JSON file if provided
9
+ let overrides: Record<string, any> | undefined;
10
+ if (opts.overrides) {
11
+ const fs = await import('node:fs');
12
+ if (fs.existsSync(opts.overrides)) {
13
+ overrides = JSON.parse(fs.readFileSync(opts.overrides, 'utf8'));
14
+ } else if (opts.overrides.startsWith('{')) {
15
+ overrides = JSON.parse(opts.overrides);
16
+ } else {
17
+ throw new Error(`Overrides not found: ${opts.overrides}`);
18
+ }
19
+ }
20
+ const patchDoc = buildPatch({ tokens, overrides, baseFile: opts.tokens });
21
+ outputResult(patchDoc, opts.format || 'json', opts.output);
22
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"set.d.ts","sourceRoot":"","sources":["set.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAiB,UAAU,EAAe,MAAM,aAAa,CAAC;AAkE1E,wBAAsB,UAAU,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAyJnE"}
1
+ {"version":3,"file":"set.d.ts","sourceRoot":"","sources":["set.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAiB,UAAU,EAAe,MAAM,aAAa,CAAC;AAmE1E,wBAAsB,UAAU,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAsKnE"}
@@ -1,9 +1,10 @@
1
1
  import { join } from 'node:path';
2
2
  import { readFileSync, existsSync } from 'node:fs';
3
3
  import { loadConfig } from '../config.js';
4
- import { createEngine } from '../engine-helpers.js';
4
+ import { Engine } from '../../core/engine.js';
5
5
  import { flattenTokens } from '../../core/flatten.js';
6
6
  import { loadTokens, outputResult } from './utils.js';
7
+ import { setupConstraints } from '../constraint-registry.js';
7
8
  // Lightweight suggestion helpers (kept local – why command uses core formatter instead)
8
9
  function levenshtein(a, b) {
9
10
  const al = a.length, bl = b.length;
@@ -81,9 +82,16 @@ export async function setCommand(options) {
81
82
  }
82
83
  const config = cfgRes.value;
83
84
  const tokens = loadTokens(tokensPath);
84
- const engine = createEngine(tokens, config);
85
- const { flat: flatAll } = flattenTokens(tokens);
86
- const knownIds = new Set(Object.keys(flatAll));
85
+ // Create engine with flattened tokens
86
+ const { flat, edges } = flattenTokens(tokens);
87
+ const init = {};
88
+ for (const t of Object.values(flat)) {
89
+ init[t.id] = t.value;
90
+ }
91
+ const engine = new Engine(init, edges);
92
+ const knownIds = new Set(Object.keys(init));
93
+ // Discover and attach all constraints via centralized registry
94
+ setupConstraints(engine, { config, constraintsDir: 'themes' }, { knownIds });
87
95
  function ensureKnownOrSuggest(id) {
88
96
  if (!knownIds.has(id)) {
89
97
  const suggestions = suggestIds(id, Array.from(knownIds));
@@ -1,225 +1,239 @@
1
- import { join } from 'node:path';
2
- import { readFileSync, existsSync } from 'node:fs';
3
- import { loadConfig } from '../config.js';
4
- import { createEngine } from '../engine-helpers.js';
5
- import { flattenTokens } from '../../core/flatten.js';
6
- import type { OverridesTree, SetOptions, ValuesPatch } from '../types.js';
7
- import { loadTokens, outputResult } from './utils.js';
8
-
9
- // Lightweight suggestion helpers (kept local – why command uses core formatter instead)
10
- function levenshtein(a: string, b: string): number {
11
- const al = a.length, bl = b.length;
12
- const dp: number[] = Array(bl + 1).fill(0).map((_, i) => i);
13
- for (let i = 1; i <= al; i++) {
14
- let prev = dp[0];
15
- dp[0] = i;
16
- for (let j = 1; j <= bl; j++) {
17
- const tmp = dp[j];
18
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
19
- dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + cost);
20
- prev = tmp;
21
- }
22
- }
23
- return dp[bl];
24
- }
25
- function suggestIds(id: string, candidates: string[], k = 3): { id: string; d: number }[] {
26
- return candidates.map(c => ({ id: c, d: levenshtein(id, c) }))
27
- .sort((a, b) => a.d - b.d).slice(0, k);
28
- }
29
-
30
- function parseSetExpression(expr: string): { id: string; value: string | number } {
31
- const match = expr.match(/^([^=]+)=(.+)$/);
32
- if (!match) throw new Error(`Invalid set expression: ${expr}. Use format: token.id=value`);
33
- const [, id, rawValue] = match;
34
- const numValue = Number(rawValue);
35
- const value = !isNaN(numValue) && isFinite(numValue) ? numValue : rawValue;
36
- return { id: id.trim(), value };
37
- }
38
-
39
- // Batch parsing helpers (scoped to set command)
40
- type BatchEntry = { id: string; value?: unknown; unset?: boolean };
41
- function isPlainObject(x: unknown) { return x && typeof x === 'object' && !Array.isArray(x); }
42
- function collectDeep(obj: unknown, prefix: string[] = [], out: BatchEntry[] = []): BatchEntry[] {
43
- if (!isPlainObject(obj)) { if (prefix.length) out.push({ id: prefix.join('.'), value: obj, unset: obj === null }); return out; }
44
- const hasValue = Object.prototype.hasOwnProperty.call(obj, '$value');
45
- const hasUnset = Object.prototype.hasOwnProperty.call(obj, '$unset');
46
- if (hasValue || hasUnset) {
47
- const rec = obj as { [k: string]: unknown; $value?: unknown; $unset?: boolean };
48
- const v = rec.$value; const u = rec.$unset === true || v === null;
49
- if (prefix.length) out.push({ id: prefix.join('.'), value: v, unset: u });
50
- return out;
51
- }
52
- for (const k of Object.keys(obj as object)) {
53
- collectDeep((obj as Record<string, unknown>)[k], [...prefix, k], out);
54
- }
55
- return out;
56
- }
57
- function normalizeBatch(raw: unknown): BatchEntry[] {
58
- if (Array.isArray(raw)) return raw.map(e => ({ id: e.id, value: Object.prototype.hasOwnProperty.call(e, 'value') ? e.value : (Object.prototype.hasOwnProperty.call(e, '$value') ? e.$value : undefined), unset: e.unset === true || e.$unset === true || e.value === null || e.$value === null }));
59
- if (isPlainObject(raw)) {
60
- const hasNested = Object.values(raw as Record<string, unknown>).some(v => isPlainObject(v));
61
- if (hasNested) {
62
- const entries = collectDeep(raw).filter(e => e.id && (e.unset || typeof e.value !== 'undefined'));
63
- if (entries.length) return entries;
64
- }
65
- const r = raw as Record<string, unknown>;
66
- return Object.keys(r).map(k => ({ id: k, value: r[k], unset: r[k] === null }));
67
- }
68
- return [];
69
- }
70
- function parseValue(v: string): string | number { const num = Number(v); return !isNaN(num) && isFinite(num) ? num : v; }
71
-
72
- export async function setCommand(options: SetOptions): Promise<void> {
73
- const debugSet = process.env.DCV_DEBUG_SET === '1' || process.argv.includes('--debug-set');
74
- const tokensPath = options.tokens || 'tokens/tokens.json';
75
- const cfgRes = loadConfig(options.config);
76
- if (!cfgRes.ok) { console.error(cfgRes.error); process.exit(2); }
77
- const config = cfgRes.value;
78
- const tokens = loadTokens(tokensPath);
79
- const engine = createEngine(tokens, config);
80
- const { flat: flatAll } = flattenTokens(tokens);
81
- const knownIds = new Set(Object.keys(flatAll));
82
- function ensureKnownOrSuggest(id: string) {
83
- if (!knownIds.has(id)) {
84
- const suggestions = suggestIds(id, Array.from(knownIds));
85
- console.error(`Unknown id: ${id}`);
86
- if (suggestions.length) {
87
- console.error('Did you mean:');
88
- suggestions.forEach(s => console.error(` - ${s.id} (d=${s.d})`));
89
- }
90
- process.exit(1);
91
- }
92
- }
93
-
94
- if (options.theme) {
95
- const themePath = join('tokens/themes', `${options.theme}.json`);
96
- if (existsSync(themePath)) {
97
- const themeTokens = JSON.parse(readFileSync(themePath, 'utf8'));
98
- for (const [id, value] of Object.entries(themeTokens)) {
99
- engine.commit(id, value as string | number);
100
- }
101
- } else {
102
- console.warn(`Theme file not found: ${themePath}`);
103
- }
104
- }
105
-
106
- let finalResult: ValuesPatch = {};
107
-
108
- function setDeep(obj: OverridesTree, parts: string[], v: unknown) {
109
- let cur: OverridesTree = obj;
110
- for (let i = 0; i < parts.length; i++) {
111
- const k = parts[i];
112
- const leaf = i === parts.length - 1;
113
- if (leaf) {
114
- const existing = (cur[k] && typeof cur[k] === 'object') ? cur[k] as OverridesTree : {} as OverridesTree;
115
- cur[k] = { ...existing, $value: v as string | number | null | undefined };
116
- } else {
117
- if (!cur[k] || typeof cur[k] !== 'object') cur[k] = {} as OverridesTree;
118
- cur = cur[k] as OverridesTree;
119
- }
120
- }
121
- }
122
- function deleteDeep(obj: OverridesTree, parts: string[]): boolean {
123
- if (!obj || typeof obj !== 'object') return false;
124
- const [k, ...rest] = parts;
125
- if (!(k in obj)) return false;
126
- if (rest.length === 0) {
127
- delete obj[k];
128
- } else {
129
- const child = obj[k];
130
- const removed = child && typeof child === 'object' ? deleteDeep(child as OverridesTree, rest) : false;
131
- if (removed || (child && typeof child === 'object' && Object.keys(child).length === 0)) delete obj[k];
132
- }
133
- return Object.keys(obj).length === 0;
134
- }
135
-
136
- // Batch JSON mode
137
- const rawArgv = process.argv.slice(2);
138
- const jsonFlagIdx = rawArgv.indexOf('--json');
139
- let jsonSource: string | undefined = options.json;
140
- if (!jsonSource && jsonFlagIdx !== -1) {
141
- const candidate = rawArgv[jsonFlagIdx + 1];
142
- if (candidate && !candidate.startsWith('--')) jsonSource = candidate;
143
- if (!jsonSource && rawArgv[jsonFlagIdx].includes('=')) {
144
- const eq = rawArgv[jsonFlagIdx].split('=')[1];
145
- if (eq) jsonSource = eq;
146
- }
147
- }
148
- if (!jsonSource && options.expressions?.includes('-')) {
149
- jsonSource = '-';
150
- options.expressions = options.expressions.filter(e => e !== '-');
151
- }
152
- if (jsonSource) {
153
- const fs = await import('node:fs');
154
- const rawText = jsonSource === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(jsonSource, 'utf8');
155
- let parsed: unknown;
156
- try { parsed = JSON.parse(rawText); } catch (e) { const msg = e instanceof Error ? e.message : String(e); console.error('Failed to parse JSON batch:', msg); process.exit(2); }
157
- if (debugSet) {
158
- console.log('[set:batch] raw length:', rawText.length);
159
- if (Array.isArray(parsed)) console.log('[set:batch] parsed top-level: (array)');
160
- else if (parsed && typeof parsed === 'object') console.log('[set:batch] parsed top-level keys:', Object.keys(parsed as Record<string, unknown>));
161
- else console.log('[set:batch] parsed value non-object');
162
- }
163
- const batchEntries = normalizeBatch(parsed);
164
- for (const expr of options.expressions || []) { const { id, value } = parseSetExpression(expr); batchEntries.push({ id, value }); }
165
- for (const u of (options.unset as unknown as string[] || [])) batchEntries.push({ id: u, unset: true });
166
- const map = new Map<string, BatchEntry>();
167
- for (const ent of batchEntries) { if (!ent.id) continue; map.set(ent.id, ent); }
168
- const entries = Array.from(map.values());
169
- for (const ent of entries) ensureKnownOrSuggest(ent.id);
170
- const debug = process.argv.includes('--debug-set') || process.env.DCV_DEBUG_SET === '1';
171
- if (debug) { console.log('[set:batch] parsed entries:'); for (const e of entries) console.log(' ', e); }
172
- const dryRun = process.argv.includes('--dry-run');
173
- for (const { id, value, unset } of entries) {
174
- if (unset) { if (!options.quiet) console.log(`preview: unset ${id}`); }
175
- else {
176
- const commitVal = parseValue(String(value));
177
- if (!options.quiet) console.log(`preview: ${id} = ${commitVal}`);
178
- if (!dryRun) { const result = engine.commit(id, commitVal); Object.assign(finalResult, result.patch); }
179
- }
180
- }
181
- const format = options.format || 'json';
182
- outputResult(finalResult, format, options.output);
183
- if (options.write && !dryRun) {
184
- const path = 'tokens/overrides/local.json';
185
- let local: OverridesTree = {} as OverridesTree;
186
- try { local = JSON.parse(fs.readFileSync(path, 'utf8')); } catch { /* new */ }
187
- for (const { id, value, unset } of entries) { if (unset) deleteDeep(local, id.split('.')); else setDeep(local, id.split('.'), value); }
188
- fs.mkdirSync('tokens/overrides', { recursive: true });
189
- fs.writeFileSync(path, JSON.stringify(local, null, 2) + '\n');
190
- console.log(`✓ Applied ${entries.length} change(s) to ${path}`);
191
- } else if (dryRun && options.write) { console.log('Dry-run: changes not written'); }
192
- return;
193
- }
194
-
195
- // Positional expressions path
196
- for (const expr of options.expressions) {
197
- const { id, value } = parseSetExpression(expr);
198
- ensureKnownOrSuggest(id);
199
- const result = engine.commit(id, value);
200
- if (!options.quiet) {
201
- console.log(`Set ${id} = ${value}`);
202
- if (result.affected.length > 0) console.log(`Affected tokens: ${result.affected.join(', ')}`);
203
- if (result.issues.length > 0) console.warn(`Issues: ${result.issues.map(i => i.message).join(', ')}`);
204
- }
205
- Object.assign(finalResult, result.patch);
206
- }
207
- const format = options.format || 'json';
208
- outputResult(finalResult, format, options.output);
209
- if (options.write || (options.unset && options.unset.length)) {
210
- const fs = await import('node:fs');
211
- const path = 'tokens/overrides/local.json';
212
- let local: OverridesTree = {} as OverridesTree;
213
- try { local = JSON.parse(fs.readFileSync(path, 'utf8')); } catch { /* new */ }
214
- if (options.write) {
215
- for (const expr of options.expressions) { const { id, value } = parseSetExpression(expr); setDeep(local, id.split('.'), value); }
216
- }
217
- if (options.unset) { for (const id of options.unset) deleteDeep(local, id.split('.')); }
218
- const total = (options.write ? options.expressions.length : 0) + (options.unset?.length || 0);
219
- if (total) {
220
- fs.mkdirSync('tokens/overrides', { recursive: true });
221
- fs.writeFileSync(path, JSON.stringify(local, null, 2) + '\n', 'utf8');
222
- console.log(`Persisted override update (${options.write ? options.expressions.length : 0} set, ${options.unset?.length || 0} unset) to ${path}`);
223
- }
224
- }
225
- }
1
+ import { join } from 'node:path';
2
+ import { readFileSync, existsSync } from 'node:fs';
3
+ import { loadConfig } from '../config.js';
4
+ import { Engine } from '../../core/engine.js';
5
+ import { flattenTokens, type FlatToken } from '../../core/flatten.js';
6
+ import type { OverridesTree, SetOptions, ValuesPatch } from '../types.js';
7
+ import { loadTokens, outputResult } from './utils.js';
8
+ import { setupConstraints } from '../constraint-registry.js';
9
+
10
+ // Lightweight suggestion helpers (kept local why command uses core formatter instead)
11
+ function levenshtein(a: string, b: string): number {
12
+ const al = a.length, bl = b.length;
13
+ const dp: number[] = Array(bl + 1).fill(0).map((_, i) => i);
14
+ for (let i = 1; i <= al; i++) {
15
+ let prev = dp[0];
16
+ dp[0] = i;
17
+ for (let j = 1; j <= bl; j++) {
18
+ const tmp = dp[j];
19
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
20
+ dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + cost);
21
+ prev = tmp;
22
+ }
23
+ }
24
+ return dp[bl];
25
+ }
26
+ function suggestIds(id: string, candidates: string[], k = 3): { id: string; d: number }[] {
27
+ return candidates.map(c => ({ id: c, d: levenshtein(id, c) }))
28
+ .sort((a, b) => a.d - b.d).slice(0, k);
29
+ }
30
+
31
+ function parseSetExpression(expr: string): { id: string; value: string | number } {
32
+ const match = expr.match(/^([^=]+)=(.+)$/);
33
+ if (!match) throw new Error(`Invalid set expression: ${expr}. Use format: token.id=value`);
34
+ const [, id, rawValue] = match;
35
+ const numValue = Number(rawValue);
36
+ const value = !isNaN(numValue) && isFinite(numValue) ? numValue : rawValue;
37
+ return { id: id.trim(), value };
38
+ }
39
+
40
+ // Batch parsing helpers (scoped to set command)
41
+ type BatchEntry = { id: string; value?: unknown; unset?: boolean };
42
+ function isPlainObject(x: unknown) { return x && typeof x === 'object' && !Array.isArray(x); }
43
+ function collectDeep(obj: unknown, prefix: string[] = [], out: BatchEntry[] = []): BatchEntry[] {
44
+ if (!isPlainObject(obj)) { if (prefix.length) out.push({ id: prefix.join('.'), value: obj, unset: obj === null }); return out; }
45
+ const hasValue = Object.prototype.hasOwnProperty.call(obj, '$value');
46
+ const hasUnset = Object.prototype.hasOwnProperty.call(obj, '$unset');
47
+ if (hasValue || hasUnset) {
48
+ const rec = obj as { [k: string]: unknown; $value?: unknown; $unset?: boolean };
49
+ const v = rec.$value; const u = rec.$unset === true || v === null;
50
+ if (prefix.length) out.push({ id: prefix.join('.'), value: v, unset: u });
51
+ return out;
52
+ }
53
+ for (const k of Object.keys(obj as object)) {
54
+ collectDeep((obj as Record<string, unknown>)[k], [...prefix, k], out);
55
+ }
56
+ return out;
57
+ }
58
+ function normalizeBatch(raw: unknown): BatchEntry[] {
59
+ if (Array.isArray(raw)) return raw.map(e => ({ id: e.id, value: Object.prototype.hasOwnProperty.call(e, 'value') ? e.value : (Object.prototype.hasOwnProperty.call(e, '$value') ? e.$value : undefined), unset: e.unset === true || e.$unset === true || e.value === null || e.$value === null }));
60
+ if (isPlainObject(raw)) {
61
+ const hasNested = Object.values(raw as Record<string, unknown>).some(v => isPlainObject(v));
62
+ if (hasNested) {
63
+ const entries = collectDeep(raw).filter(e => e.id && (e.unset || typeof e.value !== 'undefined'));
64
+ if (entries.length) return entries;
65
+ }
66
+ const r = raw as Record<string, unknown>;
67
+ return Object.keys(r).map(k => ({ id: k, value: r[k], unset: r[k] === null }));
68
+ }
69
+ return [];
70
+ }
71
+ function parseValue(v: string): string | number { const num = Number(v); return !isNaN(num) && isFinite(num) ? num : v; }
72
+
73
+ export async function setCommand(options: SetOptions): Promise<void> {
74
+ const debugSet = process.env.DCV_DEBUG_SET === '1' || process.argv.includes('--debug-set');
75
+ const tokensPath = options.tokens || 'tokens/tokens.json';
76
+ const cfgRes = loadConfig(options.config);
77
+ if (!cfgRes.ok) { console.error(cfgRes.error); process.exit(2); }
78
+ const config = cfgRes.value;
79
+ const tokens = loadTokens(tokensPath);
80
+
81
+ // Create engine with flattened tokens
82
+ const { flat, edges } = flattenTokens(tokens);
83
+ const init: Record<string, string | number> = {};
84
+ for (const t of Object.values(flat)) {
85
+ init[(t as FlatToken).id] = (t as FlatToken).value;
86
+ }
87
+ const engine = new Engine(init, edges);
88
+ const knownIds = new Set(Object.keys(init));
89
+
90
+ // Discover and attach all constraints via centralized registry
91
+ setupConstraints(
92
+ engine,
93
+ { config, constraintsDir: 'themes' },
94
+ { knownIds },
95
+ );
96
+ function ensureKnownOrSuggest(id: string) {
97
+ if (!knownIds.has(id)) {
98
+ const suggestions = suggestIds(id, Array.from(knownIds));
99
+ console.error(`Unknown id: ${id}`);
100
+ if (suggestions.length) {
101
+ console.error('Did you mean:');
102
+ suggestions.forEach(s => console.error(` - ${s.id} (d=${s.d})`));
103
+ }
104
+ process.exit(1);
105
+ }
106
+ }
107
+
108
+ if (options.theme) {
109
+ const themePath = join('tokens/themes', `${options.theme}.json`);
110
+ if (existsSync(themePath)) {
111
+ const themeTokens = JSON.parse(readFileSync(themePath, 'utf8'));
112
+ for (const [id, value] of Object.entries(themeTokens)) {
113
+ engine.commit(id, value as string | number);
114
+ }
115
+ } else {
116
+ console.warn(`Theme file not found: ${themePath}`);
117
+ }
118
+ }
119
+
120
+ let finalResult: ValuesPatch = {};
121
+
122
+ function setDeep(obj: OverridesTree, parts: string[], v: unknown) {
123
+ let cur: OverridesTree = obj;
124
+ for (let i = 0; i < parts.length; i++) {
125
+ const k = parts[i];
126
+ const leaf = i === parts.length - 1;
127
+ if (leaf) {
128
+ const existing = (cur[k] && typeof cur[k] === 'object') ? cur[k] as OverridesTree : {} as OverridesTree;
129
+ cur[k] = { ...existing, $value: v as string | number | null | undefined };
130
+ } else {
131
+ if (!cur[k] || typeof cur[k] !== 'object') cur[k] = {} as OverridesTree;
132
+ cur = cur[k] as OverridesTree;
133
+ }
134
+ }
135
+ }
136
+ function deleteDeep(obj: OverridesTree, parts: string[]): boolean {
137
+ if (!obj || typeof obj !== 'object') return false;
138
+ const [k, ...rest] = parts;
139
+ if (!(k in obj)) return false;
140
+ if (rest.length === 0) {
141
+ delete obj[k];
142
+ } else {
143
+ const child = obj[k];
144
+ const removed = child && typeof child === 'object' ? deleteDeep(child as OverridesTree, rest) : false;
145
+ if (removed || (child && typeof child === 'object' && Object.keys(child).length === 0)) delete obj[k];
146
+ }
147
+ return Object.keys(obj).length === 0;
148
+ }
149
+
150
+ // Batch JSON mode
151
+ const rawArgv = process.argv.slice(2);
152
+ const jsonFlagIdx = rawArgv.indexOf('--json');
153
+ let jsonSource: string | undefined = options.json;
154
+ if (!jsonSource && jsonFlagIdx !== -1) {
155
+ const candidate = rawArgv[jsonFlagIdx + 1];
156
+ if (candidate && !candidate.startsWith('--')) jsonSource = candidate;
157
+ if (!jsonSource && rawArgv[jsonFlagIdx].includes('=')) {
158
+ const eq = rawArgv[jsonFlagIdx].split('=')[1];
159
+ if (eq) jsonSource = eq;
160
+ }
161
+ }
162
+ if (!jsonSource && options.expressions?.includes('-')) {
163
+ jsonSource = '-';
164
+ options.expressions = options.expressions.filter(e => e !== '-');
165
+ }
166
+ if (jsonSource) {
167
+ const fs = await import('node:fs');
168
+ const rawText = jsonSource === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(jsonSource, 'utf8');
169
+ let parsed: unknown;
170
+ try { parsed = JSON.parse(rawText); } catch (e) { const msg = e instanceof Error ? e.message : String(e); console.error('Failed to parse JSON batch:', msg); process.exit(2); }
171
+ if (debugSet) {
172
+ console.log('[set:batch] raw length:', rawText.length);
173
+ if (Array.isArray(parsed)) console.log('[set:batch] parsed top-level: (array)');
174
+ else if (parsed && typeof parsed === 'object') console.log('[set:batch] parsed top-level keys:', Object.keys(parsed as Record<string, unknown>));
175
+ else console.log('[set:batch] parsed value non-object');
176
+ }
177
+ const batchEntries = normalizeBatch(parsed);
178
+ for (const expr of options.expressions || []) { const { id, value } = parseSetExpression(expr); batchEntries.push({ id, value }); }
179
+ for (const u of (options.unset as unknown as string[] || [])) batchEntries.push({ id: u, unset: true });
180
+ const map = new Map<string, BatchEntry>();
181
+ for (const ent of batchEntries) { if (!ent.id) continue; map.set(ent.id, ent); }
182
+ const entries = Array.from(map.values());
183
+ for (const ent of entries) ensureKnownOrSuggest(ent.id);
184
+ const debug = process.argv.includes('--debug-set') || process.env.DCV_DEBUG_SET === '1';
185
+ if (debug) { console.log('[set:batch] parsed entries:'); for (const e of entries) console.log(' ', e); }
186
+ const dryRun = process.argv.includes('--dry-run');
187
+ for (const { id, value, unset } of entries) {
188
+ if (unset) { if (!options.quiet) console.log(`preview: unset ${id}`); }
189
+ else {
190
+ const commitVal = parseValue(String(value));
191
+ if (!options.quiet) console.log(`preview: ${id} = ${commitVal}`);
192
+ if (!dryRun) { const result = engine.commit(id, commitVal); Object.assign(finalResult, result.patch); }
193
+ }
194
+ }
195
+ const format = options.format || 'json';
196
+ outputResult(finalResult, format, options.output);
197
+ if (options.write && !dryRun) {
198
+ const path = 'tokens/overrides/local.json';
199
+ let local: OverridesTree = {} as OverridesTree;
200
+ try { local = JSON.parse(fs.readFileSync(path, 'utf8')); } catch { /* new */ }
201
+ for (const { id, value, unset } of entries) { if (unset) deleteDeep(local, id.split('.')); else setDeep(local, id.split('.'), value); }
202
+ fs.mkdirSync('tokens/overrides', { recursive: true });
203
+ fs.writeFileSync(path, JSON.stringify(local, null, 2) + '\n');
204
+ console.log(`✓ Applied ${entries.length} change(s) to ${path}`);
205
+ } else if (dryRun && options.write) { console.log('Dry-run: changes not written'); }
206
+ return;
207
+ }
208
+
209
+ // Positional expressions path
210
+ for (const expr of options.expressions) {
211
+ const { id, value } = parseSetExpression(expr);
212
+ ensureKnownOrSuggest(id);
213
+ const result = engine.commit(id, value);
214
+ if (!options.quiet) {
215
+ console.log(`Set ${id} = ${value}`);
216
+ if (result.affected.length > 0) console.log(`Affected tokens: ${result.affected.join(', ')}`);
217
+ if (result.issues.length > 0) console.warn(`Issues: ${result.issues.map(i => i.message).join(', ')}`);
218
+ }
219
+ Object.assign(finalResult, result.patch);
220
+ }
221
+ const format = options.format || 'json';
222
+ outputResult(finalResult, format, options.output);
223
+ if (options.write || (options.unset && options.unset.length)) {
224
+ const fs = await import('node:fs');
225
+ const path = 'tokens/overrides/local.json';
226
+ let local: OverridesTree = {} as OverridesTree;
227
+ try { local = JSON.parse(fs.readFileSync(path, 'utf8')); } catch { /* new */ }
228
+ if (options.write) {
229
+ for (const expr of options.expressions) { const { id, value } = parseSetExpression(expr); setDeep(local, id.split('.'), value); }
230
+ }
231
+ if (options.unset) { for (const id of options.unset) deleteDeep(local, id.split('.')); }
232
+ const total = (options.write ? options.expressions.length : 0) + (options.unset?.length || 0);
233
+ if (total) {
234
+ fs.mkdirSync('tokens/overrides', { recursive: true });
235
+ fs.writeFileSync(path, JSON.stringify(local, null, 2) + '\n', 'utf8');
236
+ console.log(`Persisted override update (${options.write ? options.expressions.length : 0} set, ${options.unset?.length || 0} unset) to ${path}`);
237
+ }
238
+ }
239
+ }