dispersa 1.2.0 → 1.3.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 (90) hide show
  1. package/README.md +1 -2
  2. package/dist/{builders.d.cts → builders-B7_pBy58.d.cts} +180 -6
  3. package/dist/{builders.d.ts → builders-BEoMaLal.d.ts} +180 -6
  4. package/dist/{types-8MLtztK3.d.ts → config-schemas-DnEBhIg0.d.cts} +1 -158
  5. package/dist/{types-BHBHRm0a.d.cts → config-schemas-DnEBhIg0.d.ts} +1 -158
  6. package/dist/dispersa-DF2ZkG2O.d.ts +567 -0
  7. package/dist/dispersa-DJeCN0cP.d.cts +567 -0
  8. package/dist/index.cjs +2117 -2098
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +7 -7
  11. package/dist/index.d.ts +7 -7
  12. package/dist/index.js +2117 -2098
  13. package/dist/index.js.map +1 -1
  14. package/dist/{lint.cjs → lint/index.cjs} +2 -2
  15. package/dist/lint/index.cjs.map +1 -0
  16. package/dist/{lint.d.ts → lint/index.d.cts} +8 -7
  17. package/dist/{lint.d.cts → lint/index.d.ts} +8 -7
  18. package/dist/{lint.js → lint/index.js} +2 -2
  19. package/dist/lint/index.js.map +1 -0
  20. package/dist/{renderers.d.ts → output-tree-BRbfWSmG.d.ts} +3 -10
  21. package/dist/{renderers.d.cts → output-tree-Hmi77EMv.d.cts} +3 -10
  22. package/dist/{builders.cjs → outputs/builders.cjs} +30 -30
  23. package/dist/outputs/builders.cjs.map +1 -0
  24. package/dist/outputs/builders.d.cts +7 -0
  25. package/dist/outputs/builders.d.ts +7 -0
  26. package/dist/{builders.js → outputs/builders.js} +30 -30
  27. package/dist/outputs/builders.js.map +1 -0
  28. package/dist/outputs/index.cjs +3750 -0
  29. package/dist/outputs/index.cjs.map +1 -0
  30. package/dist/outputs/index.d.cts +73 -0
  31. package/dist/outputs/index.d.ts +73 -0
  32. package/dist/outputs/index.js +3730 -0
  33. package/dist/outputs/index.js.map +1 -0
  34. package/dist/{filters.cjs → processing/filters/index.cjs} +24 -18
  35. package/dist/processing/filters/index.cjs.map +1 -0
  36. package/dist/processing/filters/index.d.cts +36 -0
  37. package/dist/processing/filters/index.d.ts +36 -0
  38. package/dist/{filters.js → processing/filters/index.js} +24 -18
  39. package/dist/processing/filters/index.js.map +1 -0
  40. package/dist/{preprocessors.cjs → processing/preprocessors/index.cjs} +3 -3
  41. package/dist/processing/preprocessors/index.cjs.map +1 -0
  42. package/dist/processing/preprocessors/index.d.cts +29 -0
  43. package/dist/processing/preprocessors/index.d.ts +29 -0
  44. package/dist/{preprocessors.js → processing/preprocessors/index.js} +3 -3
  45. package/dist/processing/preprocessors/index.js.map +1 -0
  46. package/dist/{transforms.cjs → processing/transforms/index.cjs} +2 -7
  47. package/dist/processing/transforms/index.cjs.map +1 -0
  48. package/dist/{transforms.d.ts → processing/transforms/index.d.cts} +2 -2
  49. package/dist/{transforms.d.cts → processing/transforms/index.d.ts} +2 -2
  50. package/dist/{transforms.js → processing/transforms/index.js} +2 -7
  51. package/dist/processing/transforms/index.js.map +1 -0
  52. package/dist/{errors.cjs → shared/errors/index.cjs} +12 -2
  53. package/dist/shared/errors/index.cjs.map +1 -0
  54. package/dist/{errors-qT4sJgSA.d.ts → shared/errors/index.d.cts} +11 -2
  55. package/dist/{errors-qT4sJgSA.d.cts → shared/errors/index.d.ts} +11 -2
  56. package/dist/{errors.js → shared/errors/index.js} +12 -3
  57. package/dist/shared/errors/index.js.map +1 -0
  58. package/dist/types-B0cI70Bt.d.cts +453 -0
  59. package/dist/types-BxDEUCos.d.ts +453 -0
  60. package/dist/types-DUc4vLZH.d.cts +36 -0
  61. package/dist/types-s3UoDRKl.d.ts +36 -0
  62. package/package.json +26 -36
  63. package/dist/android-CRDfSB3_.d.cts +0 -126
  64. package/dist/android-DANJjjPO.d.ts +0 -126
  65. package/dist/builders.cjs.map +0 -1
  66. package/dist/builders.js.map +0 -1
  67. package/dist/dispersa-BC1kDF5u.d.ts +0 -118
  68. package/dist/dispersa-DL3J_Pmz.d.cts +0 -118
  69. package/dist/errors.cjs.map +0 -1
  70. package/dist/errors.d.cts +0 -1
  71. package/dist/errors.d.ts +0 -1
  72. package/dist/errors.js.map +0 -1
  73. package/dist/filters.cjs.map +0 -1
  74. package/dist/filters.d.cts +0 -83
  75. package/dist/filters.d.ts +0 -83
  76. package/dist/filters.js.map +0 -1
  77. package/dist/index-Dajm5rvM.d.ts +0 -895
  78. package/dist/index-De6SjZYH.d.cts +0 -895
  79. package/dist/lint.cjs.map +0 -1
  80. package/dist/lint.js.map +0 -1
  81. package/dist/preprocessors.cjs.map +0 -1
  82. package/dist/preprocessors.d.cts +0 -17
  83. package/dist/preprocessors.d.ts +0 -17
  84. package/dist/preprocessors.js.map +0 -1
  85. package/dist/renderers.cjs +0 -28
  86. package/dist/renderers.cjs.map +0 -1
  87. package/dist/renderers.js +0 -24
  88. package/dist/renderers.js.map +0 -1
  89. package/dist/transforms.cjs.map +0 -1
  90. package/dist/transforms.js.map +0 -1
@@ -0,0 +1,3750 @@
1
+ 'use strict';
2
+
3
+ var culori = require('culori');
4
+ var prettier = require('prettier');
5
+ var changeCase = require('change-case');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+
9
+ var prettier__default = /*#__PURE__*/_interopDefault(prettier);
10
+
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __esm = (fn, res) => function __init() {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
+ };
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+
21
+ // src/shared/errors/index.ts
22
+ var DispersaError, ConfigurationError, BasePermutationError;
23
+ var init_errors = __esm({
24
+ "src/shared/errors/index.ts"() {
25
+ DispersaError = class extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = "DispersaError";
29
+ if (typeof Error.captureStackTrace === "function") {
30
+ Error.captureStackTrace(this, this.constructor);
31
+ }
32
+ }
33
+ };
34
+ ConfigurationError = class extends DispersaError {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "ConfigurationError";
38
+ }
39
+ };
40
+ BasePermutationError = class extends DispersaError {
41
+ constructor(message = "Base permutation determination failed. Define a default modifier in resolver.") {
42
+ super(message);
43
+ this.name = "BasePermutationError";
44
+ }
45
+ };
46
+ }
47
+ });
48
+
49
+ // src/shared/utils/token-utils.ts
50
+ function stripInternalTokenMetadata(tokens) {
51
+ const cleaned = {};
52
+ for (const [name, token] of Object.entries(tokens)) {
53
+ const { _isAlias: _alias, _sourceModifier: _source, _sourceSet, ...rest } = token;
54
+ cleaned[name] = rest;
55
+ }
56
+ return cleaned;
57
+ }
58
+ function getSortedTokenEntries(tokens) {
59
+ return Object.entries(tokens).sort(([nameA], [nameB]) => nameA.localeCompare(nameB));
60
+ }
61
+ function buildNestedTokenObject(tokens, extractValue) {
62
+ const result = {};
63
+ for (const [, token] of getSortedTokenEntries(tokens)) {
64
+ setNestedValue(result, token.path, extractValue(token));
65
+ }
66
+ return result;
67
+ }
68
+ function setNestedValue(root, path, value) {
69
+ let current = root;
70
+ for (let i = 0; i < path.length - 1; i++) {
71
+ const part = path[i];
72
+ if (part == null) {
73
+ continue;
74
+ }
75
+ if (!(part in current)) {
76
+ current[part] = {};
77
+ }
78
+ current = current[part];
79
+ }
80
+ const lastPart = path[path.length - 1];
81
+ if (lastPart != null) {
82
+ current[lastPart] = value;
83
+ }
84
+ }
85
+ function getPureAliasReferenceName(value) {
86
+ if (typeof value !== "string") {
87
+ return void 0;
88
+ }
89
+ const match = /^\{([^}]+)\}$/.exec(value);
90
+ return match?.[1]?.trim();
91
+ }
92
+ var init_token_utils = __esm({
93
+ "src/shared/utils/token-utils.ts"() {
94
+ }
95
+ });
96
+
97
+ // src/outputs/utils.ts
98
+ function sanitizeDataAttributeName(value) {
99
+ return value.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
100
+ }
101
+ function escapeCssString(value) {
102
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r?\n/g, " ");
103
+ }
104
+ function groupTokensByType(tokens, typeGroupMap) {
105
+ const groupMap = /* @__PURE__ */ new Map();
106
+ for (const [, token] of getSortedTokenEntries(tokens)) {
107
+ const groupName = typeGroupMap[token.$type ?? ""] ?? "Other";
108
+ const existing = groupMap.get(groupName) ?? [];
109
+ existing.push(token);
110
+ groupMap.set(groupName, existing);
111
+ }
112
+ return Array.from(groupMap.entries()).map(([name, groupTokens]) => ({
113
+ name,
114
+ tokens: groupTokens
115
+ }));
116
+ }
117
+ function indentStr(width, level) {
118
+ return " ".repeat(width * level);
119
+ }
120
+ function buildGeneratedFileHeader() {
121
+ return [
122
+ "// Generated by Dispersa - do not edit manually",
123
+ "// https://github.com/dispersa-core/dispersa"
124
+ ].join("\n");
125
+ }
126
+ function toSafeIdentifier(name, keywords, capitalize) {
127
+ const camel = name.replace(/[-._]+(.)/g, (_, c) => c.toUpperCase()).replace(/[-._]+$/g, "").replace(/^[-._]+/g, "");
128
+ const cased = capitalize ? camel.charAt(0).toUpperCase() + camel.slice(1) : camel.charAt(0).toLowerCase() + camel.slice(1);
129
+ const safe = /^\d/.test(cased) ? `_${cased}` : cased;
130
+ const keyCheck = capitalize ? safe.charAt(0).toLowerCase() + safe.slice(1) : safe;
131
+ return keywords.has(keyCheck) ? `\`${safe}\`` : safe;
132
+ }
133
+ function normalizeModifierInputs(inputs) {
134
+ const normalized = {};
135
+ for (const [key, value] of Object.entries(inputs)) {
136
+ normalized[key.toLowerCase()] = value.toLowerCase();
137
+ }
138
+ return normalized;
139
+ }
140
+ function assertFileRequired(buildPath, outputFile, outputName, presetLabel) {
141
+ const requiresFile = buildPath !== void 0 && buildPath !== "";
142
+ if (!outputFile && requiresFile) {
143
+ throw new ConfigurationError(
144
+ `Output "${outputName}": file is required for ${presetLabel} output`
145
+ );
146
+ }
147
+ }
148
+ function buildStablePermutationKey(modifierInputs, dimensions) {
149
+ return dimensions.map((dimension) => `${dimension}=${modifierInputs[dimension] ?? ""}`).join("|");
150
+ }
151
+ function resolveSelector(selector, modifierName, context, isBase, allModifierInputs) {
152
+ if (typeof selector === "function") {
153
+ return selector(modifierName, context, isBase, allModifierInputs);
154
+ }
155
+ if (typeof selector === "string") {
156
+ return selector;
157
+ }
158
+ if (isBase) {
159
+ return ":root";
160
+ }
161
+ const attrName = sanitizeDataAttributeName(modifierName);
162
+ const attrValue = escapeCssString(context);
163
+ return `[data-${attrName}="${attrValue}"]`;
164
+ }
165
+ function resolveMediaQuery(mediaQuery, modifierName, context, isBase, allModifierInputs) {
166
+ if (typeof mediaQuery === "function") {
167
+ return mediaQuery(modifierName, context, isBase, allModifierInputs);
168
+ }
169
+ if (typeof mediaQuery === "string") {
170
+ return mediaQuery;
171
+ }
172
+ return "";
173
+ }
174
+ function stripInternalMetadata(tokens) {
175
+ return stripInternalTokenMetadata(tokens);
176
+ }
177
+ function generatePermutationKey(modifierInputs, resolver, isBase) {
178
+ if (isBase) {
179
+ return "base";
180
+ }
181
+ const metadata = buildMetadata(resolver);
182
+ const normalizedInputs = normalizeModifierInputs(modifierInputs);
183
+ const defaults = metadata.defaults;
184
+ const differences = [];
185
+ for (const dimension of metadata.dimensions) {
186
+ const value = normalizedInputs[dimension];
187
+ if (value !== void 0 && value !== defaults[dimension]) {
188
+ differences.push({ name: dimension, value });
189
+ }
190
+ }
191
+ if (differences.length === 1 && differences[0]) {
192
+ const diff = differences[0];
193
+ return `${diff.name}-${diff.value}`;
194
+ }
195
+ return buildStablePermutationKey(normalizedInputs, metadata.dimensions);
196
+ }
197
+ function isBasePermutation(modifierInputs, defaults) {
198
+ const normalizedInputs = normalizeModifierInputs(modifierInputs);
199
+ const normalizedDefaults = normalizeModifierInputs(defaults);
200
+ return Object.entries(normalizedDefaults).every(([key, value]) => normalizedInputs[key] === value);
201
+ }
202
+ function buildInMemoryOutputKey(params) {
203
+ const { outputName, extension, modifierInputs, resolver, defaults } = params;
204
+ const permutationKey = generatePermutationKey(
205
+ modifierInputs,
206
+ resolver,
207
+ isBasePermutation(modifierInputs, defaults)
208
+ );
209
+ return `${outputName}-${permutationKey}.${extension}`;
210
+ }
211
+ function buildMetadata(resolver) {
212
+ const metadata = {
213
+ dimensions: [],
214
+ defaults: {}
215
+ };
216
+ if (resolver.modifiers) {
217
+ for (const [name, modifier] of Object.entries(resolver.modifiers)) {
218
+ const normalizedName = name.toLowerCase();
219
+ const defaultContext = modifier.default ?? Object.keys(modifier.contexts)[0] ?? "";
220
+ metadata.dimensions.push(normalizedName);
221
+ metadata.defaults[normalizedName] = defaultContext.toLowerCase();
222
+ }
223
+ }
224
+ return metadata;
225
+ }
226
+ function countModifierDifferences(currentInputs, baseInputs) {
227
+ const normalizedCurrent = normalizeModifierInputs(currentInputs);
228
+ const normalizedBase = normalizeModifierInputs(baseInputs);
229
+ let count = 0;
230
+ for (const [key, value] of Object.entries(normalizedCurrent)) {
231
+ if (value !== normalizedBase[key]) {
232
+ count++;
233
+ }
234
+ }
235
+ return count;
236
+ }
237
+ function getExpectedSource(currentInputs, baseInputs) {
238
+ const normalizedCurrent = normalizeModifierInputs(currentInputs);
239
+ const normalizedBase = normalizeModifierInputs(baseInputs);
240
+ for (const [key, value] of Object.entries(normalizedCurrent)) {
241
+ if (value !== normalizedBase[key]) {
242
+ return `${key}-${value}`;
243
+ }
244
+ }
245
+ return "base";
246
+ }
247
+ function parseModifierSource(source) {
248
+ const dashIndex = source.indexOf("-");
249
+ if (dashIndex === -1) {
250
+ return [source, ""];
251
+ }
252
+ return [source.slice(0, dashIndex), source.slice(dashIndex + 1)];
253
+ }
254
+ function filterTokensBySource(tokens, expectedSource) {
255
+ const filtered = {};
256
+ const expected = expectedSource.toLowerCase();
257
+ for (const [name, token] of Object.entries(tokens)) {
258
+ const source = typeof token._sourceModifier === "string" ? token._sourceModifier.toLowerCase() : "";
259
+ if (source !== "" && source === expected) {
260
+ filtered[name] = token;
261
+ }
262
+ }
263
+ return filtered;
264
+ }
265
+ function filterTokensFromSets(tokens) {
266
+ const filtered = {};
267
+ for (const [name, token] of Object.entries(tokens)) {
268
+ const hasModifierSource = typeof token._sourceModifier === "string" && token._sourceModifier !== "";
269
+ if (!hasModifierSource) {
270
+ filtered[name] = token;
271
+ }
272
+ }
273
+ return filtered;
274
+ }
275
+ function resolveBaseFileName(fileName, defaults) {
276
+ if (typeof fileName === "function") {
277
+ return fileName({ ...defaults, _base: "true" });
278
+ }
279
+ if (/\{.+?\}/.test(fileName)) {
280
+ const baseInputs = Object.fromEntries(Object.keys(defaults).map((k) => [k, "base"]));
281
+ return collapseBaseSegments(interpolatePattern(fileName, baseInputs));
282
+ }
283
+ const extMatch = fileName.match(/(\.[^.]+)$/);
284
+ const extension = extMatch ? extMatch[1] : "";
285
+ const baseName = extension ? fileName.slice(0, -extension.length) : fileName;
286
+ return `${baseName}-base${extension}`;
287
+ }
288
+ function collapseBaseSegments(value) {
289
+ let result = value;
290
+ let previous = "";
291
+ while (result !== previous) {
292
+ previous = result;
293
+ result = result.replace(/\bbase([/-])base\b/, "base");
294
+ }
295
+ return result;
296
+ }
297
+ function interpolatePattern(pattern, modifierInputs) {
298
+ let result = pattern;
299
+ for (const [key, value] of Object.entries(modifierInputs)) {
300
+ result = result.replaceAll(`{${key}}`, value);
301
+ }
302
+ return result;
303
+ }
304
+ function resolveFileName(fileName, modifierInputs) {
305
+ if (typeof fileName === "function") {
306
+ return fileName(modifierInputs);
307
+ }
308
+ if (/\{.+?\}/.test(fileName)) {
309
+ return interpolatePattern(fileName, modifierInputs);
310
+ }
311
+ const extMatch = fileName.match(/(\.[^.]+)$/);
312
+ const extension = extMatch ? extMatch[1] : "";
313
+ const baseName = extension ? fileName.slice(0, -extension.length) : fileName;
314
+ const modifierSuffix = Object.entries(modifierInputs).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)).map(([key, value]) => `${key}-${value}`).join("-");
315
+ if (modifierSuffix) {
316
+ return `${baseName}-${modifierSuffix}${extension}`;
317
+ }
318
+ return fileName;
319
+ }
320
+ var init_utils = __esm({
321
+ "src/outputs/utils.ts"() {
322
+ init_errors();
323
+ init_token_utils();
324
+ }
325
+ });
326
+
327
+ // src/outputs/metadata.ts
328
+ function sanitizeText(text, format) {
329
+ switch (format) {
330
+ case "css":
331
+ case "tailwind":
332
+ return text.replace(/\*\//g, "*\\/").replace(/\r?\n/g, " ").trim();
333
+ case "kotlin":
334
+ return text.replace(/\*\//g, "* /").replace(/\r?\n/g, " ").trim();
335
+ case "js":
336
+ case "swift":
337
+ return text.replace(/\r?\n/g, " ").trim();
338
+ default:
339
+ return text.trim();
340
+ }
341
+ }
342
+ function buildDeprecationText(token) {
343
+ if (token.$deprecated == null || token.$deprecated === false) {
344
+ return "";
345
+ }
346
+ const msg = typeof token.$deprecated === "string" ? token.$deprecated : "";
347
+ return msg ? `DEPRECATED: ${msg}` : "DEPRECATED";
348
+ }
349
+ function buildTokenDescriptionComment(token, format) {
350
+ if (!token.$description || token.$description === "") {
351
+ return void 0;
352
+ }
353
+ const text = sanitizeText(token.$description, format);
354
+ switch (format) {
355
+ case "css":
356
+ case "tailwind":
357
+ return `/* ${text} */`;
358
+ case "js":
359
+ return `// ${text}`;
360
+ case "swift":
361
+ return `/// ${text}`;
362
+ case "kotlin":
363
+ return `/** ${text} */`;
364
+ default:
365
+ return void 0;
366
+ }
367
+ }
368
+ function buildTokenDeprecationComment(token, format) {
369
+ const text = buildDeprecationText(token);
370
+ if (!text) {
371
+ return void 0;
372
+ }
373
+ switch (format) {
374
+ case "css":
375
+ case "tailwind":
376
+ return `/* ${text} */`;
377
+ case "js":
378
+ return `// ${text}`;
379
+ case "swift":
380
+ return `/// ${text}`;
381
+ case "kotlin":
382
+ return `/** ${text} */`;
383
+ default:
384
+ return void 0;
385
+ }
386
+ }
387
+ function buildModifierComment(modifier, context) {
388
+ return `/* Modifier: ${modifier}=${context} */`;
389
+ }
390
+ function buildSwiftDeprecationAttribute(token) {
391
+ if (token.$deprecated == null || token.$deprecated === false) {
392
+ return void 0;
393
+ }
394
+ const msg = typeof token.$deprecated === "string" ? token.$deprecated : "";
395
+ if (msg) {
396
+ return `@available(*, deprecated, message: "${sanitizeText(msg, "swift")}")`;
397
+ }
398
+ return "@available(*, deprecated)";
399
+ }
400
+ function buildKotlinDeprecationAnnotation(token) {
401
+ if (token.$deprecated == null || token.$deprecated === false) {
402
+ return void 0;
403
+ }
404
+ const msg = typeof token.$deprecated === "string" ? token.$deprecated : "";
405
+ if (msg) {
406
+ return `@Deprecated(message = "${sanitizeText(msg, "kotlin")}")`;
407
+ }
408
+ return "@Deprecated";
409
+ }
410
+ var init_metadata = __esm({
411
+ "src/outputs/metadata.ts"() {
412
+ }
413
+ });
414
+
415
+ // src/outputs/js/presets/bundle.ts
416
+ var bundle_exports = {};
417
+ __export(bundle_exports, {
418
+ bundleAsJsModule: () => bundleAsJsModule
419
+ });
420
+ function updateStringTracking(state, char) {
421
+ if (!state.escaped && (char === '"' || char === "'" || char === "`")) {
422
+ if (!state.inString) {
423
+ state.inString = true;
424
+ state.stringChar = char;
425
+ } else if (char === state.stringChar) {
426
+ state.inString = false;
427
+ state.stringChar = "";
428
+ }
429
+ }
430
+ state.escaped = !state.escaped && char === "\\";
431
+ }
432
+ function extractObjectFromJsModule(formattedJs) {
433
+ const assignmentMatch = /const\s+\w+\s*=\s*\{/.exec(formattedJs);
434
+ if (!assignmentMatch) {
435
+ return "{}";
436
+ }
437
+ const startIndex = assignmentMatch.index + assignmentMatch[0].length - 1;
438
+ const state = { inString: false, stringChar: "", escaped: false };
439
+ let braceCount = 0;
440
+ for (let i = startIndex; i < formattedJs.length; i++) {
441
+ const char = formattedJs[i];
442
+ updateStringTracking(state, char);
443
+ if (state.inString) {
444
+ continue;
445
+ }
446
+ if (char === "{") {
447
+ braceCount++;
448
+ } else if (char === "}") {
449
+ braceCount--;
450
+ if (braceCount === 0) {
451
+ return formattedJs.substring(startIndex, i + 1);
452
+ }
453
+ }
454
+ }
455
+ return "{}";
456
+ }
457
+ function toCamelKey(key) {
458
+ if (key === "") {
459
+ return "";
460
+ }
461
+ return key.split("-").filter((part) => part !== "").map((w, i) => i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)).join("");
462
+ }
463
+ function buildStableDashKey(params) {
464
+ const { modifierInputs, dimensions, defaults } = params;
465
+ const inputs = normalizeModifierInputs(modifierInputs);
466
+ return dimensions.map((dimension) => {
467
+ const value = inputs[dimension] ?? defaults[dimension] ?? "";
468
+ return String(value);
469
+ }).join("-");
470
+ }
471
+ function buildHelperFunction(dimensions) {
472
+ const dimensionOrder = dimensions.map((d) => JSON.stringify(d)).join(", ");
473
+ return [
474
+ `/**`,
475
+ ` * Get tokens for a specific modifier combination`,
476
+ ` * @param {Object} modifiers - Modifier values (e.g., { theme: 'dark', brand: 'partner-a' })`,
477
+ ` * @returns {Object} Resolved tokens for the combination`,
478
+ ` */`,
479
+ `export function getTokens(modifiers = {}) {`,
480
+ ` const key = [${dimensionOrder}]`,
481
+ ` .map(dim => modifiers[dim] ?? tokenBundle._meta.defaults[dim])`,
482
+ ` .join('-')`,
483
+ ` const camelKey = key`,
484
+ ` .split('-')`,
485
+ ` .filter(Boolean)`,
486
+ ` .map((w, i) => (i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1)))`,
487
+ ` .join('')`,
488
+ ` return tokenBundle.tokens[camelKey]`,
489
+ `}`,
490
+ ``,
491
+ ``
492
+ ].join("\n");
493
+ }
494
+ function assembleJsBundle(metadata, jsBlocks, generateHelper) {
495
+ let output = `const tokenBundle = {
496
+ `;
497
+ output += ` _meta: ${JSON.stringify(metadata, null, 2).replace(/\n/g, "\n ")},
498
+ `;
499
+ output += ` tokens: {
500
+ ${jsBlocks.join(",\n")}
501
+ }
502
+ `;
503
+ output += `}
504
+
505
+ `;
506
+ if (generateHelper) {
507
+ output += buildHelperFunction(metadata.dimensions);
508
+ }
509
+ output += `export default tokenBundle
510
+ `;
511
+ return output;
512
+ }
513
+ async function bundleAsJsModule(bundleData, resolver, options, formatTokens) {
514
+ if (!formatTokens) {
515
+ throw new ConfigurationError("JS formatter was not provided");
516
+ }
517
+ const metadata = buildMetadata(resolver);
518
+ const jsBlocks = [];
519
+ for (const { tokens, modifierInputs, isBase } of bundleData) {
520
+ const cleanTokens = stripInternalMetadata(tokens);
521
+ const key = buildStableDashKey({
522
+ modifierInputs,
523
+ dimensions: metadata.dimensions,
524
+ defaults: metadata.defaults
525
+ });
526
+ const camelKey = toCamelKey(key);
527
+ const normalizedInputs = normalizeModifierInputs(modifierInputs);
528
+ const modifierParts = [];
529
+ for (const dim of metadata.dimensions) {
530
+ const value = normalizedInputs[dim.toLowerCase()];
531
+ if (value) {
532
+ modifierParts.push(`${dim}=${value}`);
533
+ }
534
+ }
535
+ const formattedJs = await formatTokens(cleanTokens);
536
+ const tokenObject = extractObjectFromJsModule(formattedJs);
537
+ const indentedObject = tokenObject.replace(/\n/g, "\n ");
538
+ let comment;
539
+ if (modifierParts.length > 0) {
540
+ const modifierPart = modifierParts[0];
541
+ const eqIndex = modifierPart.indexOf("=");
542
+ const modifier = modifierPart.slice(0, eqIndex);
543
+ const context = modifierPart.slice(eqIndex + 1);
544
+ comment = buildModifierComment(modifier, context);
545
+ } else if (isBase) {
546
+ comment = "// Base permutation";
547
+ } else {
548
+ comment = `// ${key}`;
549
+ }
550
+ jsBlocks.push(` ${comment}
551
+ ${JSON.stringify(camelKey)}: ${indentedObject}`);
552
+ }
553
+ return assembleJsBundle(metadata, jsBlocks, options?.generateHelper ?? false);
554
+ }
555
+ var init_bundle = __esm({
556
+ "src/outputs/js/presets/bundle.ts"() {
557
+ init_errors();
558
+ init_metadata();
559
+ init_utils();
560
+ }
561
+ });
562
+
563
+ // src/outputs/json/presets/bundle.ts
564
+ var bundle_exports2 = {};
565
+ __export(bundle_exports2, {
566
+ bundleAsJson: () => bundleAsJson
567
+ });
568
+ async function bundleAsJson(bundleData, resolver, formatTokens) {
569
+ if (!formatTokens) {
570
+ throw new ConfigurationError("JSON formatter was not provided");
571
+ }
572
+ const metadata = buildMetadata(resolver);
573
+ const tokens = {};
574
+ for (const { tokens: tokenSet, modifierInputs } of bundleData) {
575
+ const cleanTokens = stripInternalMetadata(tokenSet);
576
+ const normalizedInputs = normalizeModifierInputs(modifierInputs);
577
+ const key = buildStablePermutationKey(normalizedInputs, metadata.dimensions);
578
+ const themeJson = await formatTokens(cleanTokens);
579
+ tokens[key] = JSON.parse(themeJson);
580
+ }
581
+ const bundle = { _meta: metadata, tokens };
582
+ return JSON.stringify(bundle, null, 2);
583
+ }
584
+ var init_bundle2 = __esm({
585
+ "src/outputs/json/presets/bundle.ts"() {
586
+ init_errors();
587
+ init_utils();
588
+ }
589
+ });
590
+ function isColorObject(value) {
591
+ return typeof value === "object" && value !== null && "colorSpace" in value && "components" in value;
592
+ }
593
+ function componentToCulori(component) {
594
+ return component === "none" ? void 0 : component;
595
+ }
596
+ function dtcgObjectToCulori(color) {
597
+ const [c1, c2, c3] = color.components.map(componentToCulori);
598
+ const alpha = color.alpha !== void 0 ? componentToCulori(color.alpha) : void 0;
599
+ const colorSpace = color.colorSpace.toLowerCase();
600
+ switch (colorSpace) {
601
+ // RGB-based color spaces (components are R, G, B in 0-1 range)
602
+ case "srgb":
603
+ return { mode: "rgb", r: c1, g: c2, b: c3, alpha };
604
+ case "srgb-linear":
605
+ return { mode: "lrgb", r: c1, g: c2, b: c3, alpha };
606
+ case "display-p3":
607
+ return { mode: "p3", r: c1, g: c2, b: c3, alpha };
608
+ case "a98-rgb":
609
+ return { mode: "a98", r: c1, g: c2, b: c3, alpha };
610
+ case "prophoto-rgb":
611
+ return { mode: "prophoto", r: c1, g: c2, b: c3, alpha };
612
+ case "rec2020":
613
+ return { mode: "rec2020", r: c1, g: c2, b: c3, alpha };
614
+ // Cylindrical color spaces (Hue, Saturation/Whiteness, Lightness/Blackness)
615
+ case "hsl":
616
+ return { mode: "hsl", h: c1, s: c2, l: c3, alpha };
617
+ case "hwb":
618
+ return { mode: "hwb", h: c1, w: c2, b: c3, alpha };
619
+ // Lab color spaces (Lightness, a/b or Chroma/Hue)
620
+ case "lab":
621
+ return { mode: "lab", l: c1, a: c2, b: c3, alpha };
622
+ case "lch":
623
+ return { mode: "lch", l: c1, c: c2, h: c3, alpha };
624
+ case "oklab":
625
+ return { mode: "oklab", l: c1, a: c2, b: c3, alpha };
626
+ case "oklch":
627
+ return { mode: "oklch", l: c1, c: c2, h: c3, alpha };
628
+ // XYZ color spaces
629
+ case "xyz-d65":
630
+ return { mode: "xyz65", x: c1, y: c2, z: c3, alpha };
631
+ case "xyz-d50":
632
+ return { mode: "xyz50", x: c1, y: c2, z: c3, alpha };
633
+ // Fallback to sRGB if color space is not recognized
634
+ default:
635
+ return { mode: "rgb", r: c1, g: c2, b: c3, alpha };
636
+ }
637
+ }
638
+ function colorObjectToHex(color) {
639
+ const culoriColor = dtcgObjectToCulori(color);
640
+ const alpha = color.alpha ?? 1;
641
+ if (alpha < 1) {
642
+ return culori.formatHex8(culoriColor);
643
+ }
644
+ return culori.formatHex(culoriColor);
645
+ }
646
+
647
+ // src/processing/transforms/built-in/dimension-converter.ts
648
+ function isDimensionObject(value) {
649
+ return typeof value === "object" && value !== null && "value" in value && "unit" in value;
650
+ }
651
+ function dimensionObjectToString(dimension) {
652
+ return `${dimension.value}${dimension.unit}`;
653
+ }
654
+
655
+ // src/processing/transforms/built-in/duration-converter.ts
656
+ function isDurationObject(value) {
657
+ return typeof value === "object" && value !== null && "value" in value && "unit" in value && value.unit !== void 0;
658
+ }
659
+ function durationObjectToString(duration) {
660
+ return `${duration.value}${duration.unit}`;
661
+ }
662
+
663
+ // src/outputs/css/renderer.ts
664
+ init_errors();
665
+ init_token_utils();
666
+
667
+ // src/outputs/css/presets/bundle.ts
668
+ init_errors();
669
+ init_utils();
670
+ var REF_PREFIX_SETS = "#/sets/";
671
+ var REF_PREFIX_MODIFIERS = "#/modifiers/";
672
+ var getSourceSet = (token) => {
673
+ if (typeof token !== "object" || token === null) {
674
+ return void 0;
675
+ }
676
+ return "_sourceSet" in token && typeof token._sourceSet === "string" ? token._sourceSet : void 0;
677
+ };
678
+ var getSourceModifier = (token) => {
679
+ if (typeof token !== "object" || token === null) {
680
+ return void 0;
681
+ }
682
+ return "_sourceModifier" in token && typeof token._sourceModifier === "string" ? token._sourceModifier : void 0;
683
+ };
684
+ async function bundleAsCss(bundleData, resolver, options, formatTokens) {
685
+ const baseItem = bundleData.find((item) => item.isBase);
686
+ if (!baseItem) {
687
+ throw new BasePermutationError("Base permutation not found in bundle data");
688
+ }
689
+ if (!formatTokens) {
690
+ throw new ConfigurationError("CSS formatter was not provided");
691
+ }
692
+ const orderedBundleData = orderBundleData(bundleData, resolver, baseItem);
693
+ const cssBlocks = [];
694
+ for (const item of orderedBundleData) {
695
+ if (item.isBase) {
696
+ const blocks = await formatBasePermutation(item, resolver, options, formatTokens);
697
+ cssBlocks.push(...blocks);
698
+ continue;
699
+ }
700
+ const block = await formatModifierPermutation(item, baseItem, options, formatTokens);
701
+ if (block) {
702
+ cssBlocks.push(block);
703
+ }
704
+ }
705
+ return cssBlocks.join("\n\n");
706
+ }
707
+ async function formatBasePermutation({ tokens, modifierInputs }, resolver, options, formatTokens) {
708
+ const firstModifierName = resolver.modifiers ? Object.keys(resolver.modifiers)[0] : "";
709
+ const modifier = firstModifierName ?? "";
710
+ const context = modifierInputs[modifier] ?? "";
711
+ const selector = resolveSelector(options?.selector, modifier, context, true, modifierInputs);
712
+ const mediaQuery = resolveMediaQuery(options?.mediaQuery, modifier, context, true, modifierInputs);
713
+ const referenceTokens = stripInternalMetadata(tokens);
714
+ const defaultBlocks = buildDefaultLayerBlocks(tokens, modifierInputs, resolver);
715
+ const cssBlocks = [];
716
+ for (const block of defaultBlocks) {
717
+ const cleanTokens = stripInternalMetadata(block.tokens);
718
+ const css2 = await formatTokens(cleanTokens, {
719
+ selector,
720
+ mediaQuery,
721
+ minify: options?.minify,
722
+ referenceTokens
723
+ });
724
+ const header = block.description ? `/* ${block.key} */
725
+ /* ${block.description} */` : `/* ${block.key} */`;
726
+ cssBlocks.push(`${header}
727
+ ${css2}`);
728
+ }
729
+ return cssBlocks;
730
+ }
731
+ async function formatModifierPermutation({ tokens, modifierInputs }, baseItem, options, formatTokens) {
732
+ const differenceCount = countModifierDifferences(modifierInputs, baseItem.modifierInputs);
733
+ if (differenceCount > 1) {
734
+ return void 0;
735
+ }
736
+ const expectedSource = getExpectedSource(modifierInputs, baseItem.modifierInputs);
737
+ let tokensToInclude = filterTokensBySource(tokens, expectedSource);
738
+ const hasSourceMetadata = Object.values(tokens).some(
739
+ (token) => token != null && getSourceModifier(token) !== void 0
740
+ );
741
+ if (Object.keys(tokensToInclude).length === 0 && !hasSourceMetadata) {
742
+ tokensToInclude = tokens;
743
+ }
744
+ if (Object.keys(tokensToInclude).length === 0) {
745
+ return void 0;
746
+ }
747
+ const [modifier, context] = parseModifierSource(expectedSource);
748
+ const cleanTokens = stripInternalMetadata(tokensToInclude);
749
+ const referenceTokens = stripInternalMetadata(tokens);
750
+ const selector = resolveSelector(options?.selector, modifier, context, false, modifierInputs);
751
+ const mediaQuery = resolveMediaQuery(
752
+ options?.mediaQuery,
753
+ modifier,
754
+ context,
755
+ false,
756
+ modifierInputs
757
+ );
758
+ const css2 = await formatTokens(cleanTokens, {
759
+ selector,
760
+ mediaQuery,
761
+ minify: options?.minify,
762
+ referenceTokens
763
+ });
764
+ return `/* Modifier: ${modifier}=${context} */
765
+ ${css2}`;
766
+ }
767
+ function addLayerBlock(blocks, included, key, blockTokens, description) {
768
+ if (Object.keys(blockTokens).length === 0) {
769
+ return;
770
+ }
771
+ for (const k of Object.keys(blockTokens)) {
772
+ included.add(k);
773
+ }
774
+ blocks.push({ key, description, tokens: blockTokens });
775
+ }
776
+ function collectSetTokens(tokens, setName, included) {
777
+ const result = {};
778
+ for (const [name, token] of Object.entries(tokens)) {
779
+ if (!included.has(name) && getSourceSet(token) === setName) {
780
+ result[name] = token;
781
+ }
782
+ }
783
+ return result;
784
+ }
785
+ function collectModifierTokens(tokens, expectedSource, included) {
786
+ const result = {};
787
+ for (const [name, token] of Object.entries(tokens)) {
788
+ if (!included.has(name) && (getSourceModifier(token) ?? "").toLowerCase() === expectedSource) {
789
+ result[name] = token;
790
+ }
791
+ }
792
+ return result;
793
+ }
794
+ function collectRemainder(tokens, included) {
795
+ const result = {};
796
+ for (const [name, token] of Object.entries(tokens)) {
797
+ if (!included.has(name)) {
798
+ result[name] = token;
799
+ }
800
+ }
801
+ return result;
802
+ }
803
+ function buildSetLayerBlocks(tokens, resolver) {
804
+ const blocks = [];
805
+ const included = /* @__PURE__ */ new Set();
806
+ for (const item of resolver.resolutionOrder) {
807
+ const ref = item.$ref;
808
+ if (typeof ref !== "string" || !ref.startsWith(REF_PREFIX_SETS)) {
809
+ continue;
810
+ }
811
+ const setName = ref.slice(REF_PREFIX_SETS.length);
812
+ addLayerBlock(
813
+ blocks,
814
+ included,
815
+ `Set: ${setName}`,
816
+ collectSetTokens(tokens, setName, included),
817
+ resolver.sets?.[setName]?.description
818
+ );
819
+ }
820
+ addLayerBlock(blocks, included, "Unattributed", collectRemainder(tokens, included));
821
+ return blocks;
822
+ }
823
+ function buildDefaultLayerBlocks(tokens, baseModifierInputs, resolver) {
824
+ const blocks = [];
825
+ const included = /* @__PURE__ */ new Set();
826
+ const baseInputs = normalizeModifierInputs(baseModifierInputs);
827
+ for (const item of resolver.resolutionOrder) {
828
+ const ref = item.$ref;
829
+ if (typeof ref !== "string") {
830
+ continue;
831
+ }
832
+ processResolutionOrderRef(ref, tokens, blocks, included, baseInputs, resolver);
833
+ }
834
+ addLayerBlock(blocks, included, "Unattributed", collectRemainder(tokens, included));
835
+ return blocks;
836
+ }
837
+ function processResolutionOrderRef(ref, tokens, blocks, included, baseInputs, resolver) {
838
+ if (ref.startsWith(REF_PREFIX_SETS)) {
839
+ const setName = ref.slice(REF_PREFIX_SETS.length);
840
+ addLayerBlock(
841
+ blocks,
842
+ included,
843
+ `Set: ${setName}`,
844
+ collectSetTokens(tokens, setName, included),
845
+ resolver.sets?.[setName]?.description
846
+ );
847
+ return;
848
+ }
849
+ if (!ref.startsWith(REF_PREFIX_MODIFIERS)) {
850
+ return;
851
+ }
852
+ const modifierName = ref.slice(REF_PREFIX_MODIFIERS.length);
853
+ const modifier = resolver.modifiers?.[modifierName];
854
+ const selectedContext = baseInputs[modifierName.toLowerCase()];
855
+ if (!modifier || !selectedContext) {
856
+ return;
857
+ }
858
+ const expectedSource = `${modifierName}-${selectedContext}`.toLowerCase();
859
+ addLayerBlock(
860
+ blocks,
861
+ included,
862
+ `Modifier: ${modifierName}=${selectedContext} (default)`,
863
+ collectModifierTokens(tokens, expectedSource, included),
864
+ modifier.description
865
+ );
866
+ }
867
+ function findSingleDiffPermutation(bundleData, modifierName, context, baseInputs) {
868
+ const normalizedModifier = modifierName.toLowerCase();
869
+ const normalizedContext = context.toLowerCase();
870
+ return bundleData.find((item) => {
871
+ if (item.isBase) {
872
+ return false;
873
+ }
874
+ const inputs = normalizeModifierInputs(item.modifierInputs);
875
+ if (inputs[normalizedModifier] !== normalizedContext) {
876
+ return false;
877
+ }
878
+ return Object.entries(baseInputs).every(([k, v]) => k === normalizedModifier || inputs[k] === v);
879
+ });
880
+ }
881
+ function pushUniqueBundleItem(ordered, includedKeys, item) {
882
+ if (!item) {
883
+ return;
884
+ }
885
+ const key = stableInputsKey(item.modifierInputs);
886
+ if (includedKeys.has(key)) {
887
+ return;
888
+ }
889
+ includedKeys.add(key);
890
+ ordered.push(item);
891
+ }
892
+ function appendModifierPermutations(bundleData, modifiers, orderedNames, baseInputs, ordered, includedKeys) {
893
+ for (const modifierName of orderedNames) {
894
+ const modifierDef = modifiers[modifierName];
895
+ if (!modifierDef) {
896
+ continue;
897
+ }
898
+ const defaultValue = baseInputs[modifierName.toLowerCase()] ?? "";
899
+ for (const ctx of Object.keys(modifierDef.contexts)) {
900
+ if (defaultValue === ctx.toLowerCase()) {
901
+ continue;
902
+ }
903
+ pushUniqueBundleItem(
904
+ ordered,
905
+ includedKeys,
906
+ findSingleDiffPermutation(bundleData, modifierName, ctx, baseInputs)
907
+ );
908
+ }
909
+ }
910
+ }
911
+ function orderBundleData(bundleData, resolver, baseItem) {
912
+ const modifiers = resolver.modifiers;
913
+ if (!modifiers) {
914
+ return bundleData;
915
+ }
916
+ const baseInputs = normalizeModifierInputs(baseItem.modifierInputs);
917
+ const orderedModifierNames = getOrderedModifierNames(resolver);
918
+ if (orderedModifierNames.length === 0) {
919
+ return bundleData;
920
+ }
921
+ const firstModifierDef = modifiers[orderedModifierNames[0] ?? ""];
922
+ if (!firstModifierDef) {
923
+ return bundleData;
924
+ }
925
+ const includedKeys = /* @__PURE__ */ new Set();
926
+ const ordered = [];
927
+ pushUniqueBundleItem(ordered, includedKeys, baseItem);
928
+ appendModifierPermutations(
929
+ bundleData,
930
+ modifiers,
931
+ orderedModifierNames,
932
+ baseInputs,
933
+ ordered,
934
+ includedKeys
935
+ );
936
+ return ordered.length > 0 ? ordered : bundleData;
937
+ }
938
+ function getOrderedModifierNames(resolver) {
939
+ const modifiers = resolver.modifiers ?? {};
940
+ const seen = /* @__PURE__ */ new Set();
941
+ const ordered = [];
942
+ for (const item of resolver.resolutionOrder) {
943
+ const ref = item.$ref;
944
+ if (typeof ref !== "string") {
945
+ continue;
946
+ }
947
+ if (!ref.startsWith(REF_PREFIX_MODIFIERS)) {
948
+ continue;
949
+ }
950
+ const name = ref.slice(REF_PREFIX_MODIFIERS.length);
951
+ if (seen.has(name)) {
952
+ continue;
953
+ }
954
+ if (!(name in modifiers)) {
955
+ continue;
956
+ }
957
+ ordered.push(name);
958
+ seen.add(name);
959
+ }
960
+ for (const name of Object.keys(modifiers)) {
961
+ if (seen.has(name)) {
962
+ continue;
963
+ }
964
+ ordered.push(name);
965
+ seen.add(name);
966
+ }
967
+ return ordered;
968
+ }
969
+ function stableInputsKey(modifierInputs) {
970
+ const normalized = normalizeModifierInputs(modifierInputs);
971
+ return Object.keys(normalized).sort().map((k) => `${k}=${normalized[k]}`).join("|");
972
+ }
973
+
974
+ // src/outputs/css/renderer.ts
975
+ init_utils();
976
+ init_metadata();
977
+ var CssRenderer = class _CssRenderer {
978
+ async format(context, options) {
979
+ const opts = {
980
+ preset: options?.preset ?? "bundle",
981
+ selector: options?.selector,
982
+ mediaQuery: options?.mediaQuery,
983
+ minify: options?.minify ?? false,
984
+ preserveReferences: options?.preserveReferences ?? false
985
+ };
986
+ if (opts.preset === "bundle") {
987
+ return await this.formatBundle(context, opts);
988
+ }
989
+ if (opts.preset === "modifier") {
990
+ return await this.formatModifier(context, opts);
991
+ }
992
+ return await this.formatStandalone(context, opts);
993
+ }
994
+ static PRETTIER_PRINT_WIDTH = 80;
995
+ static PRETTIER_TAB_WIDTH = 2;
996
+ /**
997
+ * Format tokens as CSS custom properties
998
+ *
999
+ * Converts resolved design tokens into CSS format with configurable selector,
1000
+ * media queries, and formatting options. Supports DTCG color and dimension objects.
1001
+ *
1002
+ * Note: This method expects selector and mediaQuery to be resolved strings.
1003
+ * Function-based selectors should be resolved before calling format().
1004
+ *
1005
+ * @param tokens - Resolved tokens to format
1006
+ * @param options - CSS formatting options (selector, media query, minify, etc.)
1007
+ * @returns Formatted CSS string with custom properties
1008
+ */
1009
+ async formatTokens(tokens, options) {
1010
+ const opts = {
1011
+ preset: "bundle",
1012
+ selector: ":root",
1013
+ mediaQuery: "",
1014
+ minify: false,
1015
+ preserveReferences: false,
1016
+ ...options,
1017
+ referenceTokens: options?.referenceTokens ?? tokens
1018
+ };
1019
+ const sortedTokens = getSortedTokenEntries(tokens).map(([, token]) => token);
1020
+ const referenceTokens = opts.referenceTokens;
1021
+ const lines = [];
1022
+ this.buildCssBlock(lines, sortedTokens, opts.selector, tokens, referenceTokens, opts);
1023
+ const cssString = lines.join("");
1024
+ return opts.minify ? cssString : await this.formatWithPrettier(cssString);
1025
+ }
1026
+ buildCssBlock(lines, groupTokens, selector, tokens, referenceTokens, opts) {
1027
+ const indent = opts.minify ? "" : " ";
1028
+ const newline = opts.minify ? "" : "\n";
1029
+ const space = opts.minify ? "" : " ";
1030
+ const hasMediaQuery = opts.mediaQuery != null && opts.mediaQuery !== "";
1031
+ const tokenIndent = hasMediaQuery ? indent + indent : indent;
1032
+ if (hasMediaQuery) {
1033
+ lines.push(`@media ${opts.mediaQuery}${space}{${newline}`);
1034
+ lines.push(`${indent}${selector}${space}{${newline}`);
1035
+ } else {
1036
+ lines.push(`${selector}${space}{${newline}`);
1037
+ }
1038
+ for (const token of groupTokens) {
1039
+ this.pushTokenLines(
1040
+ lines,
1041
+ token,
1042
+ tokens,
1043
+ referenceTokens,
1044
+ opts.preserveReferences ?? false,
1045
+ tokenIndent,
1046
+ newline,
1047
+ space
1048
+ );
1049
+ }
1050
+ if (hasMediaQuery) {
1051
+ lines.push(`${indent}}${newline}`);
1052
+ }
1053
+ lines.push(`}${newline}${newline}`);
1054
+ }
1055
+ pushTokenLines(lines, token, tokens, referenceTokens, preserveReferences, indent, newline, space) {
1056
+ const entries = this.buildCssEntries(token, tokens, referenceTokens, preserveReferences);
1057
+ const deprecationComment = buildTokenDeprecationComment(token, "css");
1058
+ if (deprecationComment) {
1059
+ lines.push(`${indent}${deprecationComment}${newline}`);
1060
+ }
1061
+ const descriptionComment = buildTokenDescriptionComment(token, "css");
1062
+ if (descriptionComment) {
1063
+ lines.push(`${indent}${descriptionComment}${newline}`);
1064
+ }
1065
+ for (const entry of entries) {
1066
+ lines.push(`${indent}--${entry.name}:${space}${entry.value};${newline}`);
1067
+ }
1068
+ }
1069
+ async formatWithPrettier(css2) {
1070
+ try {
1071
+ return await prettier__default.default.format(css2, {
1072
+ parser: "css",
1073
+ printWidth: _CssRenderer.PRETTIER_PRINT_WIDTH,
1074
+ tabWidth: _CssRenderer.PRETTIER_TAB_WIDTH,
1075
+ useTabs: false
1076
+ });
1077
+ } catch {
1078
+ return css2;
1079
+ }
1080
+ }
1081
+ buildCssEntries(token, tokens, referenceTokens, preserveReferences) {
1082
+ if (preserveReferences) {
1083
+ const refName = getPureAliasReferenceName(token.originalValue);
1084
+ if (refName !== void 0) {
1085
+ return [
1086
+ {
1087
+ name: token.name,
1088
+ value: this.buildCssVarReference(refName, referenceTokens, tokens)
1089
+ }
1090
+ ];
1091
+ }
1092
+ }
1093
+ if (!this.isCompositeToken(token)) {
1094
+ return [{ name: token.name, value: this.formatValue(token) }];
1095
+ }
1096
+ const leaves = this.collectCompositeLeaves(token.$value);
1097
+ if (leaves.length === 0) {
1098
+ return [{ name: token.name, value: this.formatLeafValue(token.$value) }];
1099
+ }
1100
+ const leafEntries = leaves.map((leaf) => ({
1101
+ name: this.buildCompositeName(token.name, leaf.path),
1102
+ value: this.formatLeafValue(
1103
+ this.resolveCompositeLeafValue(
1104
+ leaf,
1105
+ token.originalValue,
1106
+ tokens,
1107
+ referenceTokens,
1108
+ preserveReferences
1109
+ )
1110
+ )
1111
+ }));
1112
+ const wholeValue = this.buildCompositeWholeValue(token, preserveReferences);
1113
+ if (!wholeValue) {
1114
+ return leafEntries;
1115
+ }
1116
+ return [{ name: token.name, value: wholeValue }, ...leafEntries];
1117
+ }
1118
+ isCompositeToken(token) {
1119
+ const isCompositeType = [
1120
+ "shadow",
1121
+ "typography",
1122
+ "border",
1123
+ "strokeStyle",
1124
+ "transition",
1125
+ "gradient"
1126
+ ].includes(token.$type ?? "");
1127
+ if (!isCompositeType) {
1128
+ return false;
1129
+ }
1130
+ const value = token.$value;
1131
+ return typeof value === "object" && value !== null || Array.isArray(value);
1132
+ }
1133
+ buildCompositeWholeValue(token, preserveReferences) {
1134
+ if (token.$type === "shadow") {
1135
+ return preserveReferences ? this.buildShadowWholeValue(token) : this.formatValue(token);
1136
+ }
1137
+ if (token.$type === "border") {
1138
+ if (!this.hasBorderShorthandStyle(token)) {
1139
+ return void 0;
1140
+ }
1141
+ return preserveReferences ? this.buildBorderWholeValue(token) : this.formatValue(token);
1142
+ }
1143
+ if (token.$type === "transition") {
1144
+ return preserveReferences ? this.buildTransitionWholeValue(token) : this.formatValue(token);
1145
+ }
1146
+ return void 0;
1147
+ }
1148
+ hasBorderShorthandStyle(token) {
1149
+ const value = token.$value;
1150
+ if (typeof value !== "object" || value === null) {
1151
+ return false;
1152
+ }
1153
+ return typeof value.style === "string";
1154
+ }
1155
+ buildShadowWholeValue(token) {
1156
+ const value = token.$value;
1157
+ if (Array.isArray(value)) {
1158
+ return value.map((shadow, index) => this.buildShadowLayerValue(token.name, shadow, [String(index)])).join(", ");
1159
+ }
1160
+ if (typeof value === "object" && value !== null) {
1161
+ return this.buildShadowLayerValue(token.name, value, []);
1162
+ }
1163
+ return void 0;
1164
+ }
1165
+ buildShadowLayerValue(baseName, shadow, prefix) {
1166
+ if (typeof shadow !== "object" || shadow === null) {
1167
+ return String(shadow);
1168
+ }
1169
+ const shadowObj = shadow;
1170
+ const parts = [];
1171
+ if (shadowObj.inset === true) {
1172
+ parts.push("inset");
1173
+ }
1174
+ parts.push(this.buildCompositeVar(baseName, [...prefix, "offsetX"]));
1175
+ parts.push(this.buildCompositeVar(baseName, [...prefix, "offsetY"]));
1176
+ parts.push(this.buildCompositeVar(baseName, [...prefix, "blur"]));
1177
+ if (shadowObj.spread != null) {
1178
+ parts.push(this.buildCompositeVar(baseName, [...prefix, "spread"]));
1179
+ }
1180
+ parts.push(this.buildCompositeVar(baseName, [...prefix, "color"]));
1181
+ return parts.join(" ");
1182
+ }
1183
+ buildBorderWholeValue(token) {
1184
+ const value = token.$value;
1185
+ if (typeof value !== "object" || value === null) {
1186
+ return void 0;
1187
+ }
1188
+ const border = value;
1189
+ if (typeof border.style !== "string") {
1190
+ return void 0;
1191
+ }
1192
+ return [
1193
+ this.buildCompositeVar(token.name, ["width"]),
1194
+ this.buildCompositeVar(token.name, ["style"]),
1195
+ this.buildCompositeVar(token.name, ["color"])
1196
+ ].join(" ");
1197
+ }
1198
+ buildTransitionWholeValue(token) {
1199
+ const value = token.$value;
1200
+ if (typeof value !== "object" || value === null) {
1201
+ return void 0;
1202
+ }
1203
+ return [
1204
+ this.buildCompositeVar(token.name, ["duration"]),
1205
+ `cubic-bezier(${this.buildCompositeVar(token.name, ["timingFunction", "0"])}, ${this.buildCompositeVar(token.name, ["timingFunction", "1"])}, ${this.buildCompositeVar(token.name, ["timingFunction", "2"])}, ${this.buildCompositeVar(token.name, ["timingFunction", "3"])})`,
1206
+ this.buildCompositeVar(token.name, ["delay"])
1207
+ ].join(" ");
1208
+ }
1209
+ buildCompositeVar(baseName, path) {
1210
+ return `var(--${this.buildCompositeName(baseName, path)})`;
1211
+ }
1212
+ collectCompositeLeaves(value) {
1213
+ const leaves = [];
1214
+ this.collectLeafEntries(value, [], leaves);
1215
+ return leaves;
1216
+ }
1217
+ collectLeafEntries(value, path, leaves) {
1218
+ if (this.isPrimitiveValue(value)) {
1219
+ leaves.push({ path, value });
1220
+ return;
1221
+ }
1222
+ if (isColorObject(value) || isDimensionObject(value) || isDurationObject(value)) {
1223
+ leaves.push({ path, value });
1224
+ return;
1225
+ }
1226
+ if (Array.isArray(value)) {
1227
+ if (value.length === 0) {
1228
+ leaves.push({ path, value });
1229
+ return;
1230
+ }
1231
+ value.forEach((item, index) => {
1232
+ this.collectLeafEntries(item, [...path, String(index)], leaves);
1233
+ });
1234
+ return;
1235
+ }
1236
+ if (typeof value === "object" && value !== null) {
1237
+ const entries = Object.entries(value);
1238
+ if (entries.length === 0) {
1239
+ leaves.push({ path, value });
1240
+ return;
1241
+ }
1242
+ for (const [key, child] of entries) {
1243
+ this.collectLeafEntries(child, [...path, this.normalizePathSegment(key)], leaves);
1244
+ }
1245
+ return;
1246
+ }
1247
+ leaves.push({ path, value });
1248
+ }
1249
+ normalizePathSegment(segment) {
1250
+ return segment.trim().replace(/\s+/g, "-");
1251
+ }
1252
+ buildCompositeName(base, path) {
1253
+ if (path.length === 0) {
1254
+ return base;
1255
+ }
1256
+ return `${base}-${path.join("-")}`;
1257
+ }
1258
+ formatLeafValue(value) {
1259
+ if (isColorObject(value)) {
1260
+ return colorObjectToHex(value);
1261
+ }
1262
+ if (isDimensionObject(value)) {
1263
+ return dimensionObjectToString(value);
1264
+ }
1265
+ if (isDurationObject(value)) {
1266
+ return durationObjectToString(value);
1267
+ }
1268
+ if (typeof value === "string") {
1269
+ return value;
1270
+ }
1271
+ if (typeof value === "number" || typeof value === "boolean") {
1272
+ return String(value);
1273
+ }
1274
+ if (Array.isArray(value)) {
1275
+ return JSON.stringify(value);
1276
+ }
1277
+ if (typeof value === "object" && value != null) {
1278
+ return JSON.stringify(value);
1279
+ }
1280
+ return String(value);
1281
+ }
1282
+ resolveCompositeLeafValue(leaf, originalValue, tokens, referenceTokens, preserveReferences) {
1283
+ if (!preserveReferences) {
1284
+ return leaf.value;
1285
+ }
1286
+ const originalLeafValue = this.getOriginalLeafValue(originalValue, leaf.path);
1287
+ const refName = getPureAliasReferenceName(originalLeafValue);
1288
+ if (refName === void 0) {
1289
+ return leaf.value;
1290
+ }
1291
+ return this.buildCssVarReference(refName, referenceTokens, tokens);
1292
+ }
1293
+ buildCssVarReference(refName, referenceTokens, tokens) {
1294
+ const referencedToken = referenceTokens[refName] ?? tokens[refName];
1295
+ if (!referencedToken) {
1296
+ throw new ConfigurationError(
1297
+ `CSS reference "{${refName}}" could not be resolved. The referenced token is not present in the current output's token set. This usually means a filter (e.g. isAlias()) excluded the referenced token while preserveReferences is true. Either remove the filter, include the referenced token, or set preserveReferences to false.`
1298
+ );
1299
+ }
1300
+ return `var(--${referencedToken.name})`;
1301
+ }
1302
+ getOriginalLeafValue(value, path) {
1303
+ let current = value;
1304
+ for (const segment of path) {
1305
+ if (Array.isArray(current)) {
1306
+ const index = Number(segment);
1307
+ if (!Number.isInteger(index)) {
1308
+ return void 0;
1309
+ }
1310
+ current = current[index];
1311
+ continue;
1312
+ }
1313
+ if (typeof current === "object" && current !== null) {
1314
+ const entries = Object.entries(current);
1315
+ const matched = entries.find(([key]) => this.normalizePathSegment(key) === segment);
1316
+ if (!matched) {
1317
+ return void 0;
1318
+ }
1319
+ current = matched[1];
1320
+ continue;
1321
+ }
1322
+ return void 0;
1323
+ }
1324
+ return current;
1325
+ }
1326
+ isPrimitiveValue(value) {
1327
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1328
+ }
1329
+ /**
1330
+ * Format token value for CSS
1331
+ * Handles DTCG 2025.10 object formats for colors and dimensions
1332
+ */
1333
+ formatValue(token) {
1334
+ const value = token.$value;
1335
+ const typed = this.formatTypedValue(token.$type, value);
1336
+ if (typed !== void 0) {
1337
+ return typed;
1338
+ }
1339
+ return this.formatPrimitiveOrStructured(value, token.$type);
1340
+ }
1341
+ formatTypedValue(type, value) {
1342
+ if (type === "color" && isColorObject(value)) {
1343
+ return colorObjectToHex(value);
1344
+ }
1345
+ if (type === "dimension") {
1346
+ return typeof value === "string" ? value : dimensionObjectToString(value);
1347
+ }
1348
+ if (type === "duration") {
1349
+ if (isDurationObject(value)) {
1350
+ return durationObjectToString(value);
1351
+ }
1352
+ if (typeof value === "string") {
1353
+ return value;
1354
+ }
1355
+ }
1356
+ return void 0;
1357
+ }
1358
+ formatPrimitiveOrStructured(value, tokenType) {
1359
+ if (typeof value === "string") {
1360
+ return value;
1361
+ }
1362
+ if (typeof value === "number") {
1363
+ return String(value);
1364
+ }
1365
+ if (Array.isArray(value)) {
1366
+ return this.formatArrayValue(value, tokenType);
1367
+ }
1368
+ if (typeof value === "object" && value != null) {
1369
+ return this.formatCompositeValue(value, tokenType);
1370
+ }
1371
+ return String(value);
1372
+ }
1373
+ formatArrayValue(value, tokenType) {
1374
+ if (tokenType === "shadow" && value.length > 0 && typeof value[0] === "object") {
1375
+ return value.map((shadowObj) => this.formatShadow(shadowObj)).join(", ");
1376
+ }
1377
+ return value.map((v) => typeof v === "string" && v.includes(" ") ? `"${v}"` : v).join(", ");
1378
+ }
1379
+ /**
1380
+ * Format composite token values
1381
+ */
1382
+ formatCompositeValue(value, tokenType) {
1383
+ if (tokenType === "shadow") {
1384
+ return this.formatShadow(value);
1385
+ }
1386
+ if (tokenType === "border") {
1387
+ return this.formatBorder(value);
1388
+ }
1389
+ if (tokenType === "transition") {
1390
+ return this.formatTransition(value);
1391
+ }
1392
+ return JSON.stringify(value);
1393
+ }
1394
+ /**
1395
+ * Format a single shadow object to CSS box-shadow syntax
1396
+ */
1397
+ formatShadow(shadow) {
1398
+ const parts = [];
1399
+ if (shadow.inset === true) {
1400
+ parts.push("inset");
1401
+ }
1402
+ parts.push(dimensionObjectToString(shadow.offsetX));
1403
+ parts.push(dimensionObjectToString(shadow.offsetY));
1404
+ parts.push(dimensionObjectToString(shadow.blur));
1405
+ if (shadow.spread != null) {
1406
+ parts.push(dimensionObjectToString(shadow.spread));
1407
+ }
1408
+ if (isColorObject(shadow.color)) {
1409
+ parts.push(colorObjectToHex(shadow.color));
1410
+ } else {
1411
+ parts.push(String(shadow.color));
1412
+ }
1413
+ return parts.join(" ");
1414
+ }
1415
+ /**
1416
+ * Format a border object to CSS border shorthand syntax
1417
+ */
1418
+ formatBorder(value) {
1419
+ const parts = [];
1420
+ if (isDimensionObject(value.width)) {
1421
+ parts.push(dimensionObjectToString(value.width));
1422
+ } else if (value.width != null) {
1423
+ parts.push(String(value.width));
1424
+ }
1425
+ if (typeof value.style === "string") {
1426
+ parts.push(value.style);
1427
+ }
1428
+ if (isColorObject(value.color)) {
1429
+ parts.push(colorObjectToHex(value.color));
1430
+ } else if (value.color != null) {
1431
+ parts.push(String(value.color));
1432
+ }
1433
+ return parts.join(" ");
1434
+ }
1435
+ /**
1436
+ * Format a transition object to CSS transition shorthand syntax
1437
+ */
1438
+ formatTransition(value) {
1439
+ const parts = [];
1440
+ if (isDurationObject(value.duration)) {
1441
+ parts.push(durationObjectToString(value.duration));
1442
+ } else if (value.duration != null) {
1443
+ parts.push(String(value.duration));
1444
+ }
1445
+ if (Array.isArray(value.timingFunction) && value.timingFunction.length === 4) {
1446
+ parts.push(`cubic-bezier(${value.timingFunction.join(", ")})`);
1447
+ }
1448
+ if (isDurationObject(value.delay)) {
1449
+ parts.push(durationObjectToString(value.delay));
1450
+ } else if (value.delay != null) {
1451
+ parts.push(String(value.delay));
1452
+ }
1453
+ return parts.join(" ");
1454
+ }
1455
+ async formatBundle(context, options) {
1456
+ const bundleData = context.permutations.map(({ tokens, modifierInputs }) => ({
1457
+ tokens,
1458
+ modifierInputs,
1459
+ isBase: isBasePermutation(modifierInputs, context.meta.defaults)
1460
+ }));
1461
+ return await bundleAsCss(bundleData, context.resolver, options, async (tokens, resolved) => {
1462
+ return await this.formatTokens(tokens, {
1463
+ ...resolved,
1464
+ preserveReferences: options.preserveReferences ?? false
1465
+ });
1466
+ });
1467
+ }
1468
+ async formatStandalone(context, options) {
1469
+ assertFileRequired(
1470
+ context.buildPath,
1471
+ context.output.file,
1472
+ context.output.name,
1473
+ "standalone CSS"
1474
+ );
1475
+ const files = {};
1476
+ for (const { tokens, modifierInputs } of context.permutations) {
1477
+ const { fileName, content } = await this.buildStandaloneFile(
1478
+ tokens,
1479
+ modifierInputs,
1480
+ context,
1481
+ options
1482
+ );
1483
+ files[fileName] = content;
1484
+ }
1485
+ return { kind: "outputTree", files };
1486
+ }
1487
+ async buildStandaloneFile(tokens, modifierInputs, context, options) {
1488
+ const isBase = isBasePermutation(modifierInputs, context.meta.defaults);
1489
+ const { modifierName, modifierContext } = this.resolveModifierContext(
1490
+ modifierInputs,
1491
+ context,
1492
+ isBase
1493
+ );
1494
+ const selector = resolveSelector(
1495
+ options.selector,
1496
+ modifierName,
1497
+ modifierContext,
1498
+ isBase,
1499
+ modifierInputs
1500
+ );
1501
+ const mediaQuery = resolveMediaQuery(
1502
+ options.mediaQuery,
1503
+ modifierName,
1504
+ modifierContext,
1505
+ isBase,
1506
+ modifierInputs
1507
+ );
1508
+ const content = await this.formatTokens(tokens, {
1509
+ selector,
1510
+ mediaQuery,
1511
+ minify: options.minify ?? false,
1512
+ preserveReferences: options.preserveReferences ?? false,
1513
+ referenceTokens: tokens
1514
+ });
1515
+ const fileName = context.output.file ? resolveFileName(context.output.file, modifierInputs) : buildInMemoryOutputKey({
1516
+ outputName: context.output.name,
1517
+ extension: "css",
1518
+ modifierInputs,
1519
+ resolver: context.resolver,
1520
+ defaults: context.meta.defaults
1521
+ });
1522
+ return { fileName, content };
1523
+ }
1524
+ async formatModifier(context, options) {
1525
+ assertFileRequired(context.buildPath, context.output.file, context.output.name, "modifier CSS");
1526
+ if (!context.resolver.modifiers) {
1527
+ throw new ConfigurationError("Modifier preset requires modifiers to be defined in resolver");
1528
+ }
1529
+ const files = {};
1530
+ const baseResult = await this.buildModifierBaseFile(context, options);
1531
+ if (baseResult) {
1532
+ files[baseResult.fileName] = baseResult.content;
1533
+ }
1534
+ for (const [modifierName, modifierDef] of Object.entries(context.resolver.modifiers)) {
1535
+ for (const contextValue of Object.keys(modifierDef.contexts)) {
1536
+ const result = await this.buildModifierContextFile(
1537
+ modifierName,
1538
+ contextValue,
1539
+ context,
1540
+ options
1541
+ );
1542
+ if (result) {
1543
+ files[result.fileName] = result.content;
1544
+ }
1545
+ }
1546
+ }
1547
+ return { kind: "outputTree", files };
1548
+ }
1549
+ async buildModifierBaseFile(context, options) {
1550
+ const basePermutation = context.permutations.find(
1551
+ ({ modifierInputs }) => isBasePermutation(modifierInputs, context.meta.defaults)
1552
+ );
1553
+ if (!basePermutation) {
1554
+ return void 0;
1555
+ }
1556
+ const setTokens = filterTokensFromSets(basePermutation.tokens);
1557
+ if (Object.keys(setTokens).length === 0) {
1558
+ return void 0;
1559
+ }
1560
+ const setBlocks = buildSetLayerBlocks(setTokens, context.resolver);
1561
+ if (setBlocks.length === 0) {
1562
+ return void 0;
1563
+ }
1564
+ const { selector, mediaQuery } = this.resolveBaseModifierContext(context, options);
1565
+ const content = await this.formatSetBlocksCss(
1566
+ setBlocks,
1567
+ basePermutation.tokens,
1568
+ selector,
1569
+ mediaQuery,
1570
+ options
1571
+ );
1572
+ const fileName = context.output.file ? resolveBaseFileName(context.output.file, context.meta.defaults) : `${context.output.name}-base.css`;
1573
+ return { fileName, content };
1574
+ }
1575
+ resolveBaseModifierContext(context, options) {
1576
+ const modifiers = context.resolver.modifiers;
1577
+ const firstModifierName = Object.keys(modifiers)[0] ?? "";
1578
+ const firstModifierContext = context.meta.defaults[firstModifierName] ?? "";
1579
+ const baseModifierInputs = { ...context.meta.defaults };
1580
+ return {
1581
+ selector: resolveSelector(
1582
+ options.selector,
1583
+ firstModifierName,
1584
+ firstModifierContext,
1585
+ true,
1586
+ baseModifierInputs
1587
+ ),
1588
+ mediaQuery: resolveMediaQuery(
1589
+ options.mediaQuery,
1590
+ firstModifierName,
1591
+ firstModifierContext,
1592
+ true,
1593
+ baseModifierInputs
1594
+ )
1595
+ };
1596
+ }
1597
+ async formatSetBlocksCss(setBlocks, referenceTokens, selector, mediaQuery, options) {
1598
+ const cssBlocks = [];
1599
+ for (const block of setBlocks) {
1600
+ const cleanTokens = stripInternalMetadata(block.tokens);
1601
+ const css2 = await this.formatTokens(cleanTokens, {
1602
+ selector,
1603
+ mediaQuery,
1604
+ minify: options.minify ?? false,
1605
+ preserveReferences: options.preserveReferences ?? false,
1606
+ referenceTokens
1607
+ });
1608
+ const header = block.description ? `/* ${block.key} */
1609
+ /* ${block.description} */` : `/* ${block.key} */`;
1610
+ cssBlocks.push(`${header}
1611
+ ${css2}`);
1612
+ }
1613
+ return cssBlocks.join("\n");
1614
+ }
1615
+ collectTokensForModifierContext(modifierName, contextValue, permutations) {
1616
+ const expectedSource = `${modifierName}-${contextValue}`;
1617
+ let tokensFromSource = {};
1618
+ let referenceTokens = {};
1619
+ for (const { tokens, modifierInputs } of permutations) {
1620
+ if (modifierInputs[modifierName] !== contextValue) {
1621
+ continue;
1622
+ }
1623
+ tokensFromSource = { ...tokensFromSource, ...filterTokensBySource(tokens, expectedSource) };
1624
+ referenceTokens = { ...referenceTokens, ...tokens };
1625
+ }
1626
+ return { tokensFromSource, referenceTokens };
1627
+ }
1628
+ async buildModifierContextFile(modifierName, contextValue, context, options) {
1629
+ const { tokensFromSource, referenceTokens } = this.collectTokensForModifierContext(
1630
+ modifierName,
1631
+ contextValue,
1632
+ context.permutations
1633
+ );
1634
+ if (Object.keys(tokensFromSource).length === 0) {
1635
+ return void 0;
1636
+ }
1637
+ const defaults = context.meta.defaults;
1638
+ const isBase = contextValue === defaults[modifierName];
1639
+ const modifierInputs = { ...defaults, [modifierName]: contextValue };
1640
+ const selector = resolveSelector(
1641
+ options.selector,
1642
+ modifierName,
1643
+ contextValue,
1644
+ isBase,
1645
+ modifierInputs
1646
+ );
1647
+ const mediaQuery = resolveMediaQuery(
1648
+ options.mediaQuery,
1649
+ modifierName,
1650
+ contextValue,
1651
+ isBase,
1652
+ modifierInputs
1653
+ );
1654
+ const content = await this.formatTokens(tokensFromSource, {
1655
+ selector,
1656
+ mediaQuery,
1657
+ minify: options.minify ?? false,
1658
+ preserveReferences: options.preserveReferences ?? false,
1659
+ referenceTokens
1660
+ });
1661
+ const fileName = context.output.file ? resolveFileName(context.output.file, modifierInputs) : buildInMemoryOutputKey({
1662
+ outputName: context.output.name,
1663
+ extension: "css",
1664
+ modifierInputs,
1665
+ resolver: context.resolver,
1666
+ defaults: context.meta.defaults
1667
+ });
1668
+ return { fileName, content };
1669
+ }
1670
+ resolveModifierContext(modifierInputs, context, isBase) {
1671
+ if (!context.resolver.modifiers) {
1672
+ return { modifierName: "", modifierContext: "" };
1673
+ }
1674
+ const normalizedInputs = normalizeModifierInputs(modifierInputs);
1675
+ const normalizedDefaults = normalizeModifierInputs(context.meta.defaults);
1676
+ if (isBase) {
1677
+ const firstModifier = Object.keys(context.resolver.modifiers)[0] ?? "";
1678
+ return {
1679
+ modifierName: firstModifier,
1680
+ modifierContext: normalizedInputs[firstModifier] ?? ""
1681
+ };
1682
+ }
1683
+ for (const [name, value] of Object.entries(normalizedInputs)) {
1684
+ if (value !== normalizedDefaults[name]) {
1685
+ return { modifierName: name, modifierContext: value };
1686
+ }
1687
+ }
1688
+ return { modifierName: "", modifierContext: "" };
1689
+ }
1690
+ };
1691
+ function cssRenderer() {
1692
+ const rendererInstance = new CssRenderer();
1693
+ return {
1694
+ format: (context, options) => rendererInstance.format(
1695
+ context,
1696
+ options ?? context.output.options
1697
+ )
1698
+ };
1699
+ }
1700
+
1701
+ // src/outputs/js/renderer.ts
1702
+ init_utils();
1703
+ init_token_utils();
1704
+ init_metadata();
1705
+
1706
+ // src/outputs/output-tree.ts
1707
+ var outputTree = (files) => {
1708
+ return {
1709
+ kind: "outputTree",
1710
+ files
1711
+ };
1712
+ };
1713
+ var isOutputTree = (value) => {
1714
+ return typeof value === "object" && value !== null && value.kind === "outputTree";
1715
+ };
1716
+
1717
+ // src/outputs/js/renderer.ts
1718
+ var JsModuleRenderer = class {
1719
+ async format(context, options) {
1720
+ const opts = {
1721
+ preset: options?.preset ?? "standalone",
1722
+ structure: options?.structure ?? "nested",
1723
+ minify: options?.minify ?? false,
1724
+ moduleName: options?.moduleName ?? "tokens",
1725
+ generateHelper: options?.generateHelper ?? false
1726
+ };
1727
+ if (opts.preset === "bundle") {
1728
+ const { bundleAsJsModule: bundleAsJsModule2 } = await Promise.resolve().then(() => (init_bundle(), bundle_exports));
1729
+ const bundleData = context.permutations.map(({ tokens, modifierInputs }) => ({
1730
+ tokens: stripInternalMetadata(tokens),
1731
+ modifierInputs,
1732
+ isBase: isBasePermutation(modifierInputs, context.meta.defaults)
1733
+ }));
1734
+ return await bundleAsJsModule2(bundleData, context.resolver, opts, async (tokens) => {
1735
+ return await this.formatTokens(tokens, opts);
1736
+ });
1737
+ }
1738
+ assertFileRequired(context.buildPath, context.output.file, context.output.name, "JS module");
1739
+ const files = {};
1740
+ for (const { tokens, modifierInputs } of context.permutations) {
1741
+ const cleanTokens = stripInternalMetadata(tokens);
1742
+ const content = await this.formatTokens(cleanTokens, opts);
1743
+ const fileName = context.output.file ? resolveFileName(context.output.file, modifierInputs) : buildInMemoryOutputKey({
1744
+ outputName: context.output.name,
1745
+ extension: "js",
1746
+ modifierInputs,
1747
+ resolver: context.resolver,
1748
+ defaults: context.meta.defaults
1749
+ });
1750
+ files[fileName] = content;
1751
+ }
1752
+ return outputTree(files);
1753
+ }
1754
+ async formatTokens(tokens, options) {
1755
+ const lines = [];
1756
+ lines.push(...this.formatAsObject(tokens, options));
1757
+ const code = lines.join("\n");
1758
+ if (options.minify) {
1759
+ return code;
1760
+ }
1761
+ return await prettier__default.default.format(code, {
1762
+ parser: "babel",
1763
+ printWidth: 80,
1764
+ tabWidth: 2,
1765
+ useTabs: false,
1766
+ semi: false,
1767
+ singleQuote: true,
1768
+ trailingComma: "es5"
1769
+ });
1770
+ }
1771
+ formatAsObject(tokens, options) {
1772
+ const lines = [];
1773
+ const tokenMap = this.buildTokenMap(tokens);
1774
+ const varName = options.moduleName !== "" ? options.moduleName : "tokens";
1775
+ if (options.structure === "flat") {
1776
+ lines.push(`const ${varName} = {`);
1777
+ this.addFlatProperties(lines, tokens, 1);
1778
+ lines.push("}");
1779
+ } else {
1780
+ lines.push(`const ${varName} = {`);
1781
+ const tokenObj = this.tokensToPlainObject(tokens, "nested");
1782
+ this.addNestedProperties(lines, tokenObj, tokenMap, 1);
1783
+ lines.push("}");
1784
+ }
1785
+ lines.push("");
1786
+ lines.push(`export default ${varName}`);
1787
+ return lines;
1788
+ }
1789
+ buildTokenMap(tokens) {
1790
+ const map = /* @__PURE__ */ new Map();
1791
+ for (const [name, token] of Object.entries(tokens)) {
1792
+ map.set(name, token);
1793
+ }
1794
+ return map;
1795
+ }
1796
+ addFlatProperties(lines, tokens, indent) {
1797
+ const indentStr2 = " ".repeat(indent);
1798
+ const sortedEntries = getSortedTokenEntries(tokens);
1799
+ for (let i = 0; i < sortedEntries.length; i++) {
1800
+ const [name, token] = sortedEntries[i];
1801
+ const isLast = i === sortedEntries.length - 1;
1802
+ this.pushTokenComments(lines, token, indentStr2);
1803
+ lines.push(
1804
+ `${indentStr2}${this.quoteKey(name)}: ${JSON.stringify(token.$value)}${isLast ? "" : ","}`
1805
+ );
1806
+ }
1807
+ }
1808
+ pushTokenComments(lines, token, indent) {
1809
+ const deprecationComment = buildTokenDeprecationComment(token, "js");
1810
+ if (deprecationComment) {
1811
+ lines.push(`${indent}${deprecationComment}`);
1812
+ }
1813
+ const descriptionComment = buildTokenDescriptionComment(token, "js");
1814
+ if (descriptionComment) {
1815
+ lines.push(`${indent}${descriptionComment}`);
1816
+ }
1817
+ }
1818
+ tokensToPlainObject(tokens, structure) {
1819
+ if (structure === "nested") {
1820
+ return buildNestedTokenObject(tokens, (token) => token.$value);
1821
+ }
1822
+ const result = {};
1823
+ for (const [name, token] of getSortedTokenEntries(tokens)) {
1824
+ result[name] = token.$value;
1825
+ }
1826
+ return result;
1827
+ }
1828
+ addNestedProperties(lines, obj, tokenMap, indent) {
1829
+ const indentStr2 = " ".repeat(indent);
1830
+ const entries = Object.entries(obj).sort(([keyA], [keyB]) => keyA.localeCompare(keyB));
1831
+ for (let i = 0; i < entries.length; i++) {
1832
+ const entry = entries[i];
1833
+ if (entry == null) {
1834
+ continue;
1835
+ }
1836
+ const [key, value] = entry;
1837
+ const isLast = i === entries.length - 1;
1838
+ const isNestedObject = typeof value === "object" && value !== null && !Array.isArray(value);
1839
+ if (!isNestedObject) {
1840
+ const token = tokenMap.get(key);
1841
+ if (token) {
1842
+ this.pushTokenComments(lines, token, indentStr2);
1843
+ }
1844
+ lines.push(
1845
+ `${indentStr2}${this.quoteKey(key)}: ${JSON.stringify(value)}${isLast ? "" : ","}`
1846
+ );
1847
+ continue;
1848
+ }
1849
+ lines.push(`${indentStr2}${this.quoteKey(key)}: {`);
1850
+ this.addNestedProperties(lines, value, tokenMap, indent + 1);
1851
+ lines.push(`${indentStr2}}${isLast ? "" : ","}`);
1852
+ }
1853
+ }
1854
+ quoteKey(key) {
1855
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)) {
1856
+ return key;
1857
+ }
1858
+ return `"${key}"`;
1859
+ }
1860
+ };
1861
+ function jsRenderer() {
1862
+ const rendererInstance = new JsModuleRenderer();
1863
+ return {
1864
+ format: (context, options) => rendererInstance.format(
1865
+ context,
1866
+ options ?? context.output.options
1867
+ )
1868
+ };
1869
+ }
1870
+
1871
+ // src/outputs/json/renderer.ts
1872
+ init_utils();
1873
+ init_token_utils();
1874
+ var JsonRenderer = class {
1875
+ async format(context, options) {
1876
+ const opts = {
1877
+ preset: options?.preset ?? "standalone",
1878
+ structure: options?.structure ?? "nested",
1879
+ minify: options?.minify ?? false,
1880
+ includeMetadata: options?.includeMetadata ?? false
1881
+ };
1882
+ if (opts.preset === "bundle") {
1883
+ const { bundleAsJson: bundleAsJson2 } = await Promise.resolve().then(() => (init_bundle2(), bundle_exports2));
1884
+ const bundleData = context.permutations.map(({ tokens, modifierInputs }) => ({
1885
+ tokens: stripInternalMetadata(tokens),
1886
+ modifierInputs,
1887
+ isBase: isBasePermutation(modifierInputs, context.meta.defaults)
1888
+ }));
1889
+ return await bundleAsJson2(bundleData, context.resolver, async (tokens) => {
1890
+ return await this.formatTokens(tokens, opts);
1891
+ });
1892
+ }
1893
+ assertFileRequired(context.buildPath, context.output.file, context.output.name, "JSON");
1894
+ const files = {};
1895
+ for (const { tokens, modifierInputs } of context.permutations) {
1896
+ const processedTokens = stripInternalMetadata(tokens);
1897
+ const content = await this.formatTokens(processedTokens, opts);
1898
+ const fileName = context.output.file ? resolveFileName(context.output.file, modifierInputs) : buildInMemoryOutputKey({
1899
+ outputName: context.output.name,
1900
+ extension: "json",
1901
+ modifierInputs,
1902
+ resolver: context.resolver,
1903
+ defaults: context.meta.defaults
1904
+ });
1905
+ files[fileName] = content;
1906
+ }
1907
+ return outputTree(files);
1908
+ }
1909
+ async formatTokens(tokens, options) {
1910
+ const opts = {
1911
+ preset: options.preset ?? "standalone",
1912
+ structure: options.structure ?? "nested",
1913
+ minify: options.minify ?? false,
1914
+ includeMetadata: options.includeMetadata ?? false
1915
+ };
1916
+ let output;
1917
+ if (opts.structure === "flat") {
1918
+ output = opts.includeMetadata ? this.flattenTokens(tokens) : this.flattenValues(tokens);
1919
+ } else {
1920
+ output = opts.includeMetadata ? this.nestTokens(tokens) : this.nestValues(tokens);
1921
+ }
1922
+ const jsonString = JSON.stringify(output);
1923
+ if (!opts.minify) {
1924
+ return await prettier__default.default.format(jsonString, {
1925
+ parser: "json",
1926
+ printWidth: 80,
1927
+ tabWidth: 2,
1928
+ useTabs: false
1929
+ });
1930
+ }
1931
+ return jsonString;
1932
+ }
1933
+ /**
1934
+ * Flatten tokens to simple key-value pairs
1935
+ */
1936
+ flattenValues(tokens) {
1937
+ const result = {};
1938
+ for (const [name, token] of getSortedTokenEntries(tokens)) {
1939
+ result[name] = token.$value;
1940
+ }
1941
+ return result;
1942
+ }
1943
+ /**
1944
+ * Flatten tokens to metadata objects
1945
+ */
1946
+ flattenTokens(tokens) {
1947
+ const result = {};
1948
+ for (const [name, token] of getSortedTokenEntries(tokens)) {
1949
+ result[name] = this.serializeToken(token);
1950
+ }
1951
+ return result;
1952
+ }
1953
+ nestValues(tokens) {
1954
+ return buildNestedTokenObject(tokens, (token) => token.$value);
1955
+ }
1956
+ nestTokens(tokens) {
1957
+ return buildNestedTokenObject(tokens, (token) => this.serializeToken(token));
1958
+ }
1959
+ serializeToken(token) {
1960
+ return {
1961
+ $value: token.$value,
1962
+ ...typeof token.$type === "string" && { $type: token.$type },
1963
+ ...token.$description != null && token.$description !== "" && { $description: token.$description },
1964
+ ...token.$deprecated != null && token.$deprecated !== false && { $deprecated: token.$deprecated },
1965
+ ...token.$extensions != null && { $extensions: token.$extensions }
1966
+ };
1967
+ }
1968
+ };
1969
+ function jsonRenderer() {
1970
+ const rendererInstance = new JsonRenderer();
1971
+ return {
1972
+ format: (context, options) => rendererInstance.format(
1973
+ context,
1974
+ options ?? context.output.options
1975
+ )
1976
+ };
1977
+ }
1978
+
1979
+ // src/outputs/tailwind/renderer.ts
1980
+ init_token_utils();
1981
+
1982
+ // src/outputs/tailwind/presets/bundle.ts
1983
+ init_errors();
1984
+ init_utils();
1985
+ async function bundleAsTailwind(bundleData, options, formatThemeTokens, formatOverrideBlock) {
1986
+ const baseItem = bundleData.find((item) => item.isBase);
1987
+ if (!baseItem) {
1988
+ throw new BasePermutationError("Base permutation not found in bundle data");
1989
+ }
1990
+ const resolvedOpts = resolveOptions(options);
1991
+ const cssBlocks = [];
1992
+ const variantDeclarations = collectVariantDeclarations(bundleData, baseItem, resolvedOpts);
1993
+ const themeOpts = { ...resolvedOpts, variantDeclarations };
1994
+ const baseTokens = stripInternalMetadata(baseItem.tokens);
1995
+ const themeBlock = await formatThemeTokens(baseTokens, themeOpts);
1996
+ cssBlocks.push(themeBlock);
1997
+ for (const item of bundleData) {
1998
+ if (item.isBase) {
1999
+ continue;
2000
+ }
2001
+ const block = await formatModifierOverride(item, baseItem, resolvedOpts, formatOverrideBlock);
2002
+ if (block) {
2003
+ cssBlocks.push(block);
2004
+ }
2005
+ }
2006
+ return cssBlocks.join("\n");
2007
+ }
2008
+ function resolveModifierSelectorAndMedia(options, modifier, context, modifierInputs) {
2009
+ const normalized = normalizeModifierInputs(modifierInputs);
2010
+ return {
2011
+ selector: resolveSelector(options.selector, modifier, context, false, normalized),
2012
+ mediaQuery: resolveMediaQuery(options.mediaQuery, modifier, context, false, normalized)
2013
+ };
2014
+ }
2015
+ async function formatModifierOverride({ tokens, modifierInputs }, baseItem, options, formatOverrideBlock) {
2016
+ const differenceCount = countModifierDifferences(modifierInputs, baseItem.modifierInputs);
2017
+ if (differenceCount > 1) {
2018
+ return void 0;
2019
+ }
2020
+ const tokensToInclude = filterTokensByValueChange(tokens, baseItem.tokens);
2021
+ if (Object.keys(tokensToInclude).length === 0) {
2022
+ return void 0;
2023
+ }
2024
+ const expectedSource = getExpectedSource(modifierInputs, baseItem.modifierInputs);
2025
+ const [modifier, context] = parseModifierSource(expectedSource);
2026
+ const cleanTokens = stripInternalMetadata(tokensToInclude);
2027
+ const { selector, mediaQuery } = resolveModifierSelectorAndMedia(
2028
+ options,
2029
+ modifier,
2030
+ context,
2031
+ modifierInputs
2032
+ );
2033
+ const css2 = await formatOverrideBlock(cleanTokens, selector, mediaQuery, options.minify);
2034
+ return `/* Modifier: ${modifier}=${context} */
2035
+ ${css2}`;
2036
+ }
2037
+ function filterTokensByValueChange(currentTokens, baseTokens) {
2038
+ const changed = {};
2039
+ for (const [name, token] of Object.entries(currentTokens)) {
2040
+ const baseToken = baseTokens[name];
2041
+ if (!baseToken) {
2042
+ changed[name] = token;
2043
+ continue;
2044
+ }
2045
+ if (JSON.stringify(token.$value) !== JSON.stringify(baseToken.$value)) {
2046
+ changed[name] = token;
2047
+ }
2048
+ }
2049
+ return changed;
2050
+ }
2051
+ function collectVariantDeclarations(bundleData, baseItem, options) {
2052
+ const declarations = [];
2053
+ for (const item of bundleData) {
2054
+ if (item.isBase) {
2055
+ continue;
2056
+ }
2057
+ const differenceCount = countModifierDifferences(item.modifierInputs, baseItem.modifierInputs);
2058
+ if (differenceCount > 1) {
2059
+ continue;
2060
+ }
2061
+ const expectedSource = getExpectedSource(item.modifierInputs, baseItem.modifierInputs);
2062
+ const [modifier, context] = parseModifierSource(expectedSource);
2063
+ const variantName = `${modifier}-${context}`;
2064
+ const normalized = normalizeModifierInputs(item.modifierInputs);
2065
+ const mediaQuery = resolveMediaQuery(options.mediaQuery, modifier, context, false, normalized);
2066
+ if (mediaQuery !== "") {
2067
+ declarations.push(`@custom-variant ${variantName} (@media ${mediaQuery});`);
2068
+ continue;
2069
+ }
2070
+ const selector = resolveSelector(options.selector, modifier, context, false, normalized);
2071
+ declarations.push(`@custom-variant ${variantName} (&:where(${selector}, ${selector} *));`);
2072
+ }
2073
+ return declarations;
2074
+ }
2075
+ function resolveOptions(options) {
2076
+ return {
2077
+ preset: options.preset ?? "bundle",
2078
+ includeImport: options.includeImport ?? true,
2079
+ namespace: options.namespace ?? "",
2080
+ minify: options.minify ?? false,
2081
+ selector: options.selector,
2082
+ mediaQuery: options.mediaQuery,
2083
+ variantDeclarations: []
2084
+ };
2085
+ }
2086
+
2087
+ // src/outputs/tailwind/renderer.ts
2088
+ init_utils();
2089
+ init_metadata();
2090
+ var TAILWIND_NAMESPACE_MAP = {
2091
+ color: "color",
2092
+ dimension: "spacing",
2093
+ fontFamily: "font",
2094
+ fontWeight: "font-weight",
2095
+ duration: "duration",
2096
+ shadow: "shadow",
2097
+ number: "number",
2098
+ cubicBezier: "ease"
2099
+ };
2100
+ var TailwindRenderer = class {
2101
+ async format(context, options) {
2102
+ const opts = {
2103
+ preset: options?.preset ?? "bundle",
2104
+ includeImport: options?.includeImport ?? true,
2105
+ namespace: options?.namespace ?? "",
2106
+ minify: options?.minify ?? false,
2107
+ selector: options?.selector,
2108
+ mediaQuery: options?.mediaQuery,
2109
+ variantDeclarations: []
2110
+ };
2111
+ if (opts.preset === "bundle") {
2112
+ return await this.formatBundle(context, opts);
2113
+ }
2114
+ return await this.formatStandalone(context, opts);
2115
+ }
2116
+ /**
2117
+ * Format tokens as Tailwind v4 @theme CSS variables
2118
+ */
2119
+ async formatTokens(tokens, options) {
2120
+ const lines = [];
2121
+ const indent = options.minify ? "" : " ";
2122
+ const newline = options.minify ? "" : "\n";
2123
+ const space = options.minify ? "" : " ";
2124
+ if (options.includeImport) {
2125
+ lines.push(`@import "tailwindcss";${newline}`);
2126
+ }
2127
+ if (options.variantDeclarations.length > 0) {
2128
+ if (options.includeImport) {
2129
+ lines.push(newline);
2130
+ }
2131
+ for (const declaration of options.variantDeclarations) {
2132
+ lines.push(`${declaration}${newline}`);
2133
+ }
2134
+ }
2135
+ if (options.includeImport || options.variantDeclarations.length > 0) {
2136
+ lines.push(newline);
2137
+ }
2138
+ const themeDirective = options.namespace ? `@theme namespace(${options.namespace})` : "@theme";
2139
+ lines.push(`${themeDirective}${space}{${newline}`);
2140
+ for (const [, token] of getSortedTokenEntries(tokens)) {
2141
+ const varName = this.buildVariableName(token);
2142
+ const varValue = this.formatValue(token);
2143
+ const deprecationComment = buildTokenDeprecationComment(token, "tailwind");
2144
+ if (deprecationComment) {
2145
+ lines.push(`${indent}${deprecationComment}${newline}`);
2146
+ }
2147
+ const descriptionComment = buildTokenDescriptionComment(token, "tailwind");
2148
+ if (descriptionComment) {
2149
+ lines.push(`${indent}${descriptionComment}${newline}`);
2150
+ }
2151
+ lines.push(`${indent}--${varName}:${space}${varValue};${newline}`);
2152
+ }
2153
+ lines.push(`}${newline}`);
2154
+ const cssString = lines.join("");
2155
+ return options.minify ? cssString : await this.formatWithPrettier(cssString);
2156
+ }
2157
+ /**
2158
+ * Format tokens as plain CSS custom property overrides inside a selector block.
2159
+ * Used for modifier overrides (e.g., dark mode) appended after the @theme block.
2160
+ */
2161
+ async formatOverrideBlock(tokens, selector, mediaQuery, minify) {
2162
+ const indent = minify ? "" : " ";
2163
+ const newline = minify ? "" : "\n";
2164
+ const space = minify ? "" : " ";
2165
+ const hasMediaQuery = mediaQuery !== "";
2166
+ const tokenIndent = hasMediaQuery ? indent + indent : indent;
2167
+ const lines = [];
2168
+ if (hasMediaQuery) {
2169
+ lines.push(`@media ${mediaQuery}${space}{${newline}`);
2170
+ lines.push(`${indent}${selector}${space}{${newline}`);
2171
+ } else {
2172
+ lines.push(`${selector}${space}{${newline}`);
2173
+ }
2174
+ for (const [, token] of getSortedTokenEntries(tokens)) {
2175
+ const varName = this.buildVariableName(token);
2176
+ const varValue = this.formatValue(token);
2177
+ const deprecationComment = buildTokenDeprecationComment(token, "tailwind");
2178
+ if (deprecationComment) {
2179
+ lines.push(`${tokenIndent}${deprecationComment}${newline}`);
2180
+ }
2181
+ const descriptionComment = buildTokenDescriptionComment(token, "tailwind");
2182
+ if (descriptionComment) {
2183
+ lines.push(`${tokenIndent}${descriptionComment}${newline}`);
2184
+ }
2185
+ lines.push(`${tokenIndent}--${varName}:${space}${varValue};${newline}`);
2186
+ }
2187
+ if (hasMediaQuery) {
2188
+ lines.push(`${indent}}${newline}`);
2189
+ lines.push(`}${newline}`);
2190
+ } else {
2191
+ lines.push(`}${newline}`);
2192
+ }
2193
+ return lines.join("");
2194
+ }
2195
+ buildVariableName(token) {
2196
+ const prefix = TAILWIND_NAMESPACE_MAP[token.$type ?? ""];
2197
+ if (!prefix) {
2198
+ return token.name;
2199
+ }
2200
+ const nameLower = token.name.toLowerCase();
2201
+ const prefixLower = prefix.toLowerCase();
2202
+ if (nameLower.startsWith(`${prefixLower}-`) || nameLower.startsWith(`${prefixLower}.`)) {
2203
+ return token.name;
2204
+ }
2205
+ return `${prefix}-${token.name}`;
2206
+ }
2207
+ formatValue(token) {
2208
+ const value = token.$value;
2209
+ if (token.$type === "color" && isColorObject(value)) {
2210
+ return colorObjectToHex(value);
2211
+ }
2212
+ if (token.$type === "dimension" && isDimensionObject(value)) {
2213
+ return dimensionObjectToString(value);
2214
+ }
2215
+ if (token.$type === "duration" && isDurationObject(value)) {
2216
+ return durationObjectToString(value);
2217
+ }
2218
+ if (token.$type === "fontFamily") {
2219
+ if (Array.isArray(value)) {
2220
+ return value.map((v) => typeof v === "string" && v.includes(" ") ? `"${v}"` : v).join(", ");
2221
+ }
2222
+ return typeof value === "string" ? value : String(value);
2223
+ }
2224
+ if (token.$type === "shadow") {
2225
+ return this.formatShadowValue(value);
2226
+ }
2227
+ if (token.$type === "cubicBezier" && Array.isArray(value) && value.length === 4) {
2228
+ return `cubic-bezier(${value.join(", ")})`;
2229
+ }
2230
+ if (typeof value === "string") {
2231
+ return value;
2232
+ }
2233
+ if (typeof value === "number") {
2234
+ return String(value);
2235
+ }
2236
+ return String(value);
2237
+ }
2238
+ formatShadowValue(value) {
2239
+ if (Array.isArray(value) && value.length > 0 && typeof value[0] === "object") {
2240
+ return value.map((s) => this.formatSingleShadow(s)).join(", ");
2241
+ }
2242
+ if (typeof value === "object" && value !== null) {
2243
+ return this.formatSingleShadow(value);
2244
+ }
2245
+ return String(value);
2246
+ }
2247
+ formatSingleShadow(shadow) {
2248
+ const parts = [];
2249
+ if (shadow.inset === true) {
2250
+ parts.push("inset");
2251
+ }
2252
+ if (isDimensionObject(shadow.offsetX)) {
2253
+ parts.push(dimensionObjectToString(shadow.offsetX));
2254
+ }
2255
+ if (isDimensionObject(shadow.offsetY)) {
2256
+ parts.push(dimensionObjectToString(shadow.offsetY));
2257
+ }
2258
+ if (isDimensionObject(shadow.blur)) {
2259
+ parts.push(dimensionObjectToString(shadow.blur));
2260
+ }
2261
+ if (shadow.spread != null && isDimensionObject(shadow.spread)) {
2262
+ parts.push(dimensionObjectToString(shadow.spread));
2263
+ }
2264
+ if (isColorObject(shadow.color)) {
2265
+ parts.push(colorObjectToHex(shadow.color));
2266
+ } else if (shadow.color != null) {
2267
+ parts.push(String(shadow.color));
2268
+ }
2269
+ return parts.join(" ");
2270
+ }
2271
+ async formatWithPrettier(css2) {
2272
+ try {
2273
+ return await prettier__default.default.format(css2, {
2274
+ parser: "css",
2275
+ printWidth: 80,
2276
+ tabWidth: 2,
2277
+ useTabs: false
2278
+ });
2279
+ } catch {
2280
+ return css2;
2281
+ }
2282
+ }
2283
+ async formatBundle(context, options) {
2284
+ const bundleData = context.permutations.map(({ tokens, modifierInputs }) => ({
2285
+ tokens,
2286
+ modifierInputs,
2287
+ isBase: isBasePermutation(modifierInputs, context.meta.defaults)
2288
+ }));
2289
+ return await bundleAsTailwind(
2290
+ bundleData,
2291
+ options,
2292
+ async (tokens, opts) => await this.formatTokens(tokens, opts),
2293
+ async (tokens, selector, mediaQuery, minify) => await this.formatOverrideBlock(tokens, selector, mediaQuery, minify)
2294
+ );
2295
+ }
2296
+ async formatStandalone(context, options) {
2297
+ assertFileRequired(
2298
+ context.buildPath,
2299
+ context.output.file,
2300
+ context.output.name,
2301
+ "standalone Tailwind"
2302
+ );
2303
+ const files = {};
2304
+ for (const { tokens, modifierInputs } of context.permutations) {
2305
+ const processedTokens = stripInternalMetadata(tokens);
2306
+ const content = await this.formatTokens(processedTokens, options);
2307
+ const fileName = context.output.file ? resolveFileName(context.output.file, modifierInputs) : buildInMemoryOutputKey({
2308
+ outputName: context.output.name,
2309
+ extension: "css",
2310
+ modifierInputs,
2311
+ resolver: context.resolver,
2312
+ defaults: context.meta.defaults
2313
+ });
2314
+ files[fileName] = content;
2315
+ }
2316
+ return outputTree(files);
2317
+ }
2318
+ };
2319
+ function tailwindRenderer() {
2320
+ const rendererInstance = new TailwindRenderer();
2321
+ return {
2322
+ format: (context, options) => rendererInstance.format(
2323
+ context,
2324
+ options ?? context.output.options
2325
+ )
2326
+ };
2327
+ }
2328
+
2329
+ // src/shared/token-types/types.ts
2330
+ function isShadowToken(token) {
2331
+ return token.$type === "shadow";
2332
+ }
2333
+ function isTypographyToken(token) {
2334
+ return token.$type === "typography";
2335
+ }
2336
+ function isBorderToken(token) {
2337
+ return token.$type === "border";
2338
+ }
2339
+
2340
+ // src/outputs/ios/renderer.ts
2341
+ init_utils();
2342
+ init_metadata();
2343
+ var toSRGB = culori.converter("rgb");
2344
+ var toP3 = culori.converter("p3");
2345
+ var SWIFT_TYPE_GROUP_MAP = {
2346
+ color: "Colors",
2347
+ dimension: "Spacing",
2348
+ fontFamily: "Fonts",
2349
+ fontWeight: "FontWeights",
2350
+ duration: "Durations",
2351
+ shadow: "Shadows",
2352
+ typography: "Typography",
2353
+ number: "Numbers",
2354
+ cubicBezier: "Animations",
2355
+ border: "Borders",
2356
+ gradient: "Gradients"
2357
+ };
2358
+ var SWIFT_KEYWORDS = /* @__PURE__ */ new Set([
2359
+ "associatedtype",
2360
+ "class",
2361
+ "deinit",
2362
+ "enum",
2363
+ "extension",
2364
+ "fileprivate",
2365
+ "func",
2366
+ "import",
2367
+ "init",
2368
+ "inout",
2369
+ "internal",
2370
+ "let",
2371
+ "open",
2372
+ "operator",
2373
+ "private",
2374
+ "protocol",
2375
+ "public",
2376
+ "rethrows",
2377
+ "static",
2378
+ "struct",
2379
+ "subscript",
2380
+ "typealias",
2381
+ "var",
2382
+ "break",
2383
+ "case",
2384
+ "continue",
2385
+ "default",
2386
+ "defer",
2387
+ "do",
2388
+ "else",
2389
+ "fallthrough",
2390
+ "for",
2391
+ "guard",
2392
+ "if",
2393
+ "in",
2394
+ "repeat",
2395
+ "return",
2396
+ "switch",
2397
+ "where",
2398
+ "while",
2399
+ "as",
2400
+ "catch",
2401
+ "false",
2402
+ "is",
2403
+ "nil",
2404
+ "super",
2405
+ "self",
2406
+ "Self",
2407
+ "throw",
2408
+ "throws",
2409
+ "true",
2410
+ "try",
2411
+ "Type",
2412
+ "Protocol"
2413
+ ]);
2414
+ var IosRenderer = class {
2415
+ async format(context, options) {
2416
+ const opts = {
2417
+ preset: options?.preset ?? "standalone",
2418
+ accessLevel: options?.accessLevel ?? "public",
2419
+ structure: options?.structure ?? "enum",
2420
+ enumName: options?.enumName ?? "DesignTokens",
2421
+ extensionNamespace: options?.extensionNamespace ?? "DesignTokens",
2422
+ colorSpace: options?.colorSpace ?? "sRGB",
2423
+ swiftVersion: options?.swiftVersion ?? "5.9",
2424
+ indent: options?.indent ?? 4,
2425
+ frozen: options?.frozen ?? false
2426
+ };
2427
+ return await this.formatStandalone(context, opts);
2428
+ }
2429
+ formatTokens(tokens, options) {
2430
+ const access = options.accessLevel;
2431
+ const groups = groupTokensByType(tokens, SWIFT_TYPE_GROUP_MAP);
2432
+ const imports = this.collectImports(tokens);
2433
+ const staticPrefix = this.staticLetPrefix(options);
2434
+ const frozen = this.frozenPrefix(options);
2435
+ const lines = [];
2436
+ lines.push(buildGeneratedFileHeader());
2437
+ lines.push("");
2438
+ for (const imp of imports) {
2439
+ lines.push(`import ${imp}`);
2440
+ }
2441
+ lines.push(...this.buildStructDefinitions(tokens, access, options));
2442
+ this.pushTokenLayout(lines, groups, options, access, staticPrefix, frozen);
2443
+ lines.push(...this.buildViewExtensions(tokens, access, options));
2444
+ if (options.structure !== "grouped") {
2445
+ lines.push("");
2446
+ }
2447
+ return lines.join("\n");
2448
+ }
2449
+ pushTokenLayout(lines, groups, options, access, staticPrefix, frozen) {
2450
+ const i1 = indentStr(options.indent, 1);
2451
+ const i2 = indentStr(options.indent, 2);
2452
+ if (options.structure === "grouped") {
2453
+ this.pushGroupedLayout(lines, groups, options, access, i1, i2, staticPrefix, frozen);
2454
+ return;
2455
+ }
2456
+ lines.push("");
2457
+ lines.push(`${frozen}${access} enum ${options.enumName} {`);
2458
+ for (const group of groups) {
2459
+ lines.push(`${i1}${frozen}${access} enum ${group.name} {`);
2460
+ this.pushTokenDeclarations(lines, group.tokens, options, access, i2, staticPrefix);
2461
+ lines.push(`${i1}}`);
2462
+ lines.push("");
2463
+ }
2464
+ lines.push("}");
2465
+ }
2466
+ pushGroupedLayout(lines, groups, options, access, i1, i2, staticPrefix, frozen) {
2467
+ const namespace = options.extensionNamespace;
2468
+ lines.push("");
2469
+ lines.push(`${frozen}${access} enum ${namespace} {}`);
2470
+ lines.push("");
2471
+ for (const group of groups) {
2472
+ lines.push(`${access} extension ${namespace} {`);
2473
+ lines.push(`${i1}${frozen}enum ${group.name} {`);
2474
+ this.pushTokenDeclarations(lines, group.tokens, options, access, i2, staticPrefix);
2475
+ lines.push(`${i1}}`);
2476
+ lines.push("}");
2477
+ lines.push("");
2478
+ }
2479
+ }
2480
+ pushTokenDeclarations(lines, tokens, options, access, indent, staticPrefix) {
2481
+ for (const token of tokens) {
2482
+ const swiftName = this.buildQualifiedSwiftName(token);
2483
+ const swiftValue = this.formatSwiftValue(token, options);
2484
+ const typeAnnotation = this.getTypeAnnotation(token);
2485
+ const annotation = typeAnnotation ? `: ${typeAnnotation}` : "";
2486
+ const docComment = buildTokenDescriptionComment(token, "swift");
2487
+ if (docComment) {
2488
+ lines.push(`${indent}${docComment}`);
2489
+ }
2490
+ const deprecationAttr = buildSwiftDeprecationAttribute(token);
2491
+ if (deprecationAttr) {
2492
+ lines.push(`${indent}${deprecationAttr}`);
2493
+ }
2494
+ lines.push(`${indent}${access} ${staticPrefix}${swiftName}${annotation} = ${swiftValue}`);
2495
+ }
2496
+ }
2497
+ collectImports(tokens) {
2498
+ const imports = /* @__PURE__ */ new Set();
2499
+ imports.add("SwiftUI");
2500
+ for (const [, token] of Object.entries(tokens)) {
2501
+ if (token.$type === "duration") {
2502
+ imports.add("Foundation");
2503
+ }
2504
+ }
2505
+ return Array.from(imports).sort();
2506
+ }
2507
+ /**
2508
+ * Builds a qualified Swift name from a token's path, preserving parent
2509
+ * hierarchy segments to avoid duplicate identifiers.
2510
+ *
2511
+ * For example, `color.blue.400` in the `Colors` group becomes `blue400`
2512
+ * instead of just `_400`.
2513
+ */
2514
+ buildQualifiedSwiftName(token) {
2515
+ const path = token.path;
2516
+ const withoutTypePrefix = path.length > 1 ? path.slice(1) : path;
2517
+ const joined = withoutTypePrefix.join("_");
2518
+ return toSafeIdentifier(joined, SWIFT_KEYWORDS, false);
2519
+ }
2520
+ formatSwiftValue(token, options) {
2521
+ const { $type, $value: value } = token;
2522
+ switch ($type) {
2523
+ case "color":
2524
+ return this.formatColorValue(value, options);
2525
+ case "dimension":
2526
+ return this.formatDimensionValue(value);
2527
+ case "fontFamily":
2528
+ return this.formatFontFamilyValue(value);
2529
+ case "fontWeight":
2530
+ return this.formatFontWeightValue(value);
2531
+ case "duration":
2532
+ return this.formatDurationValue(value);
2533
+ case "shadow":
2534
+ return this.formatShadowValue(value, options);
2535
+ case "typography":
2536
+ return this.formatTypographyValue(value);
2537
+ case "border":
2538
+ return this.formatBorderValue(value, options);
2539
+ case "gradient":
2540
+ return this.formatGradientValue(value, options);
2541
+ case "number":
2542
+ return String(value);
2543
+ case "cubicBezier":
2544
+ if (Array.isArray(value) && value.length === 4) {
2545
+ return `UnitCurve.bezier(startControlPoint: UnitPoint(x: ${value[0]}, y: ${value[1]}), endControlPoint: UnitPoint(x: ${value[2]}, y: ${value[3]}))`;
2546
+ }
2547
+ break;
2548
+ }
2549
+ return this.formatSwiftPrimitive(value);
2550
+ }
2551
+ formatSwiftPrimitive(value) {
2552
+ if (typeof value === "string") {
2553
+ return `"${this.escapeSwiftString(value)}"`;
2554
+ }
2555
+ if (typeof value === "number") {
2556
+ return String(value);
2557
+ }
2558
+ if (typeof value === "boolean") {
2559
+ return value ? "true" : "false";
2560
+ }
2561
+ return `"${this.escapeSwiftString(String(value))}"`;
2562
+ }
2563
+ formatColorValue(value, options) {
2564
+ if (!isColorObject(value)) {
2565
+ return typeof value === "string" ? `Color("${this.escapeSwiftString(value)}")` : "Color.clear";
2566
+ }
2567
+ const colorObj = value;
2568
+ const alpha = colorObj.alpha ?? 1;
2569
+ if (options.colorSpace === "displayP3") {
2570
+ const p3 = toP3(dtcgObjectToCulori(colorObj));
2571
+ const r2 = this.roundComponent(p3?.r ?? 0);
2572
+ const g2 = this.roundComponent(p3?.g ?? 0);
2573
+ const b2 = this.roundComponent(p3?.b ?? 0);
2574
+ return alpha < 1 ? `Color(.displayP3, red: ${r2}, green: ${g2}, blue: ${b2}, opacity: ${this.roundComponent(alpha)})` : `Color(.displayP3, red: ${r2}, green: ${g2}, blue: ${b2})`;
2575
+ }
2576
+ const rgb = toSRGB(dtcgObjectToCulori(colorObj));
2577
+ const r = this.roundComponent(rgb?.r ?? 0);
2578
+ const g = this.roundComponent(rgb?.g ?? 0);
2579
+ const b = this.roundComponent(rgb?.b ?? 0);
2580
+ return alpha < 1 ? `Color(red: ${r}, green: ${g}, blue: ${b}, opacity: ${this.roundComponent(alpha)})` : `Color(red: ${r}, green: ${g}, blue: ${b})`;
2581
+ }
2582
+ formatDimensionValue(value) {
2583
+ if (isDimensionObject(value)) {
2584
+ return this.dimensionToPoints(value);
2585
+ }
2586
+ return String(value);
2587
+ }
2588
+ formatFontFamilyValue(value) {
2589
+ if (Array.isArray(value)) {
2590
+ const primary = value[0];
2591
+ return typeof primary === "string" ? `"${this.escapeSwiftString(primary)}"` : '"system"';
2592
+ }
2593
+ return typeof value === "string" ? `"${this.escapeSwiftString(value)}"` : '"system"';
2594
+ }
2595
+ formatFontWeightValue(value) {
2596
+ if (typeof value === "number") {
2597
+ return this.numericFontWeight(value);
2598
+ }
2599
+ if (typeof value === "string") {
2600
+ return this.namedFontWeight(value) ?? "Font.Weight.regular";
2601
+ }
2602
+ return "Font.Weight.regular";
2603
+ }
2604
+ numericFontWeight(weight) {
2605
+ if (weight <= 100) {
2606
+ return "Font.Weight.ultraLight";
2607
+ }
2608
+ if (weight <= 200) {
2609
+ return "Font.Weight.thin";
2610
+ }
2611
+ if (weight <= 300) {
2612
+ return "Font.Weight.light";
2613
+ }
2614
+ if (weight <= 400) {
2615
+ return "Font.Weight.regular";
2616
+ }
2617
+ if (weight <= 500) {
2618
+ return "Font.Weight.medium";
2619
+ }
2620
+ if (weight <= 600) {
2621
+ return "Font.Weight.semibold";
2622
+ }
2623
+ if (weight <= 700) {
2624
+ return "Font.Weight.bold";
2625
+ }
2626
+ if (weight <= 800) {
2627
+ return "Font.Weight.heavy";
2628
+ }
2629
+ return "Font.Weight.black";
2630
+ }
2631
+ namedFontWeight(name) {
2632
+ const map = {
2633
+ thin: "Font.Weight.thin",
2634
+ ultralight: "Font.Weight.ultraLight",
2635
+ extralight: "Font.Weight.ultraLight",
2636
+ light: "Font.Weight.light",
2637
+ regular: "Font.Weight.regular",
2638
+ normal: "Font.Weight.regular",
2639
+ medium: "Font.Weight.medium",
2640
+ semibold: "Font.Weight.semibold",
2641
+ demibold: "Font.Weight.semibold",
2642
+ bold: "Font.Weight.bold",
2643
+ heavy: "Font.Weight.heavy",
2644
+ extrabold: "Font.Weight.heavy",
2645
+ black: "Font.Weight.black",
2646
+ ultrabold: "Font.Weight.black"
2647
+ };
2648
+ return map[name.toLowerCase()];
2649
+ }
2650
+ formatDurationValue(value) {
2651
+ if (isDurationObject(value)) {
2652
+ const dur = value;
2653
+ const seconds = dur.unit === "ms" ? dur.value / 1e3 : dur.value;
2654
+ return String(seconds);
2655
+ }
2656
+ return typeof value === "number" ? String(value) : "0";
2657
+ }
2658
+ formatShadowValue(value, options) {
2659
+ if (Array.isArray(value) && value.length > 0) {
2660
+ return this.formatSingleShadow(value[0], options);
2661
+ }
2662
+ if (typeof value === "object" && value !== null) {
2663
+ return this.formatSingleShadow(value, options);
2664
+ }
2665
+ return "ShadowStyle(color: .clear, radius: 0, x: 0, y: 0, spread: 0)";
2666
+ }
2667
+ formatSingleShadow(shadow, options) {
2668
+ const color = isColorObject(shadow.color) ? this.formatColorValue(shadow.color, options) : "Color.black.opacity(0.25)";
2669
+ const radius = isDimensionObject(shadow.blur) ? this.dimensionToCGFloat(shadow.blur) : "8";
2670
+ const x = isDimensionObject(shadow.offsetX) ? this.dimensionToCGFloat(shadow.offsetX) : "0";
2671
+ const y = isDimensionObject(shadow.offsetY) ? this.dimensionToCGFloat(shadow.offsetY) : "0";
2672
+ const spread = isDimensionObject(shadow.spread) ? this.dimensionToCGFloat(shadow.spread) : "0";
2673
+ return `ShadowStyle(color: ${color}, radius: ${radius}, x: ${x}, y: ${y}, spread: ${spread})`;
2674
+ }
2675
+ formatTypographyValue(value) {
2676
+ if (typeof value !== "object" || value === null) {
2677
+ return "TypographyStyle(font: Font.body, tracking: 0, lineSpacing: 0)";
2678
+ }
2679
+ const typo = value;
2680
+ const size = isDimensionObject(typo.fontSize) ? this.dimensionToPoints(typo.fontSize) : "16";
2681
+ const weight = typo.fontWeight != null ? this.formatFontWeightValue(typo.fontWeight) : "Font.Weight.regular";
2682
+ const fontExpr = this.buildFontExpression(typo, size, weight);
2683
+ const tracking = this.extractTracking(typo);
2684
+ const lineSpacing = this.extractLineSpacing(typo);
2685
+ return `TypographyStyle(font: ${fontExpr}, tracking: ${tracking}, lineSpacing: ${lineSpacing})`;
2686
+ }
2687
+ buildFontExpression(typo, size, weight) {
2688
+ if (typo.fontFamily != null) {
2689
+ const family = Array.isArray(typo.fontFamily) ? typo.fontFamily[0] : typo.fontFamily;
2690
+ if (typeof family === "string") {
2691
+ return `Font.custom("${this.escapeSwiftString(family)}", size: ${size}).weight(${weight})`;
2692
+ }
2693
+ }
2694
+ return `Font.system(size: ${size}, weight: ${weight})`;
2695
+ }
2696
+ extractTracking(typo) {
2697
+ if (!isDimensionObject(typo.letterSpacing)) {
2698
+ return "0";
2699
+ }
2700
+ return this.dimensionToPoints(typo.letterSpacing);
2701
+ }
2702
+ extractLineSpacing(typo) {
2703
+ if (typo.lineHeight == null || typeof typo.lineHeight !== "number") {
2704
+ return "0";
2705
+ }
2706
+ if (!isDimensionObject(typo.fontSize)) {
2707
+ return "0";
2708
+ }
2709
+ const basePt = this.dimensionToNumericPoints(typo.fontSize);
2710
+ const lineHeightPt = Math.round(basePt * typo.lineHeight * 100) / 100;
2711
+ return String(lineHeightPt - basePt);
2712
+ }
2713
+ dimensionToNumericPoints(dim) {
2714
+ return dim.unit === "rem" ? dim.value * 16 : dim.value;
2715
+ }
2716
+ dimensionToPoints(dim) {
2717
+ return String(this.dimensionToNumericPoints(dim));
2718
+ }
2719
+ /** Formats a dimension as a CGFloat literal (appends `.0` for integers). */
2720
+ dimensionToCGFloat(dim) {
2721
+ const ptValue = this.dimensionToNumericPoints(dim);
2722
+ return Number.isInteger(ptValue) ? `${ptValue}.0` : String(ptValue);
2723
+ }
2724
+ getTypeAnnotation(token) {
2725
+ switch (token.$type) {
2726
+ case "dimension":
2727
+ return "CGFloat";
2728
+ case "duration":
2729
+ return "TimeInterval";
2730
+ case "number":
2731
+ return "Double";
2732
+ case "fontWeight":
2733
+ return "Font.Weight";
2734
+ case "fontFamily":
2735
+ return "String";
2736
+ default:
2737
+ return void 0;
2738
+ }
2739
+ }
2740
+ escapeSwiftString(str) {
2741
+ return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
2742
+ }
2743
+ roundComponent(value) {
2744
+ return Math.round(value * 1e4) / 1e4;
2745
+ }
2746
+ /**
2747
+ * Returns the prefix for `static let` declarations.
2748
+ * Swift 6 requires `nonisolated(unsafe)` on global stored properties.
2749
+ */
2750
+ staticLetPrefix(options) {
2751
+ return options.swiftVersion === "6.0" ? "nonisolated(unsafe) static let " : "static let ";
2752
+ }
2753
+ /** Returns `@frozen ` when the frozen option is enabled, empty string otherwise. */
2754
+ frozenPrefix(options) {
2755
+ return options.frozen ? "@frozen " : "";
2756
+ }
2757
+ /** Returns `: Sendable` when targeting Swift 6, empty string otherwise. */
2758
+ structConformances(options) {
2759
+ return options.swiftVersion === "6.0" ? ": Sendable" : "";
2760
+ }
2761
+ /** Emits all struct definitions needed by the token set. */
2762
+ buildStructDefinitions(tokens, access, options) {
2763
+ const lines = [];
2764
+ if (Object.values(tokens).some(isShadowToken)) {
2765
+ lines.push("");
2766
+ lines.push(...this.buildShadowStyleStruct(access, options));
2767
+ }
2768
+ if (Object.values(tokens).some(isTypographyToken)) {
2769
+ lines.push("");
2770
+ lines.push(...this.buildTypographyStyleStruct(access, options));
2771
+ }
2772
+ if (Object.values(tokens).some(isBorderToken)) {
2773
+ lines.push("");
2774
+ lines.push(...this.buildBorderStyleStruct(access, options));
2775
+ }
2776
+ return lines;
2777
+ }
2778
+ buildShadowStyleStruct(access, options) {
2779
+ const i1 = indentStr(options.indent, 1);
2780
+ const conformances = this.structConformances(options);
2781
+ const frozen = this.frozenPrefix(options);
2782
+ return [
2783
+ `${frozen}${access} struct ShadowStyle${conformances} {`,
2784
+ `${i1}${access} let color: Color`,
2785
+ `${i1}${access} let radius: CGFloat`,
2786
+ `${i1}${access} let x: CGFloat`,
2787
+ `${i1}${access} let y: CGFloat`,
2788
+ `${i1}${access} let spread: CGFloat`,
2789
+ "}"
2790
+ ];
2791
+ }
2792
+ buildTypographyStyleStruct(access, options) {
2793
+ const i1 = indentStr(options.indent, 1);
2794
+ const conformances = this.structConformances(options);
2795
+ const frozen = this.frozenPrefix(options);
2796
+ return [
2797
+ `${frozen}${access} struct TypographyStyle${conformances} {`,
2798
+ `${i1}${access} let font: Font`,
2799
+ `${i1}${access} let tracking: CGFloat`,
2800
+ `${i1}${access} let lineSpacing: CGFloat`,
2801
+ "}"
2802
+ ];
2803
+ }
2804
+ buildBorderStyleStruct(access, options) {
2805
+ const i1 = indentStr(options.indent, 1);
2806
+ const conformances = this.structConformances(options);
2807
+ const frozen = this.frozenPrefix(options);
2808
+ return [
2809
+ `${frozen}${access} struct BorderStyle${conformances} {`,
2810
+ `${i1}${access} let color: Color`,
2811
+ `${i1}${access} let width: CGFloat`,
2812
+ "}"
2813
+ ];
2814
+ }
2815
+ /** Emits convenience View extensions for shadow and typography application. */
2816
+ buildViewExtensions(tokens, access, options) {
2817
+ const lines = [];
2818
+ const i1 = indentStr(options.indent, 1);
2819
+ const i2 = indentStr(options.indent, 2);
2820
+ if (Object.values(tokens).some(isShadowToken)) {
2821
+ lines.push("");
2822
+ lines.push(`${access} extension View {`);
2823
+ lines.push(`${i1}func shadowStyle(_ style: ShadowStyle) -> some View {`);
2824
+ lines.push(
2825
+ `${i2}self.shadow(color: style.color, radius: style.radius, x: style.x, y: style.y)`
2826
+ );
2827
+ lines.push(`${i1}}`);
2828
+ lines.push("}");
2829
+ }
2830
+ if (Object.values(tokens).some(isTypographyToken)) {
2831
+ lines.push("");
2832
+ lines.push(`${access} extension View {`);
2833
+ lines.push(`${i1}func typographyStyle(_ style: TypographyStyle) -> some View {`);
2834
+ lines.push(
2835
+ `${i2}self.font(style.font).tracking(style.tracking).lineSpacing(style.lineSpacing)`
2836
+ );
2837
+ lines.push(`${i1}}`);
2838
+ lines.push("}");
2839
+ }
2840
+ return lines;
2841
+ }
2842
+ formatBorderValue(value, options) {
2843
+ if (typeof value !== "object" || value === null) {
2844
+ return "BorderStyle(color: .clear, width: 0)";
2845
+ }
2846
+ const border = value;
2847
+ const color = isColorObject(border.color) ? this.formatColorValue(border.color, options) : "Color.clear";
2848
+ const width = isDimensionObject(border.width) ? this.dimensionToCGFloat(border.width) : "1.0";
2849
+ return `BorderStyle(color: ${color}, width: ${width})`;
2850
+ }
2851
+ formatGradientValue(value, options) {
2852
+ if (!Array.isArray(value) || value.length === 0) {
2853
+ return "Gradient(stops: [])";
2854
+ }
2855
+ const stops = value.map((stop) => {
2856
+ const color = isColorObject(stop.color) ? this.formatColorValue(stop.color, options) : "Color.clear";
2857
+ return `.init(color: ${color}, location: ${stop.position})`;
2858
+ });
2859
+ return `Gradient(stops: [${stops.join(", ")}])`;
2860
+ }
2861
+ async formatStandalone(context, options) {
2862
+ assertFileRequired(
2863
+ context.buildPath,
2864
+ context.output.file,
2865
+ context.output.name,
2866
+ "standalone iOS"
2867
+ );
2868
+ const files = {};
2869
+ for (const { tokens, modifierInputs } of context.permutations) {
2870
+ const processedTokens = stripInternalMetadata(tokens);
2871
+ const content = this.formatTokens(processedTokens, options);
2872
+ const fileName = context.output.file ? resolveFileName(context.output.file, modifierInputs) : buildInMemoryOutputKey({
2873
+ outputName: context.output.name,
2874
+ extension: "swift",
2875
+ modifierInputs,
2876
+ resolver: context.resolver,
2877
+ defaults: context.meta.defaults
2878
+ });
2879
+ files[fileName] = content;
2880
+ }
2881
+ return outputTree(files);
2882
+ }
2883
+ };
2884
+ function iosRenderer() {
2885
+ const rendererInstance = new IosRenderer();
2886
+ return {
2887
+ format: (context, options) => rendererInstance.format(
2888
+ context,
2889
+ options ?? context.output.options
2890
+ )
2891
+ };
2892
+ }
2893
+
2894
+ // src/outputs/android/renderer.ts
2895
+ init_errors();
2896
+ init_token_utils();
2897
+ init_utils();
2898
+ init_metadata();
2899
+ var toSRGB2 = culori.converter("rgb");
2900
+ var toP32 = culori.converter("p3");
2901
+ var KOTLIN_KEYWORDS = /* @__PURE__ */ new Set([
2902
+ "val",
2903
+ "var",
2904
+ "fun",
2905
+ "class",
2906
+ "object",
2907
+ "when",
2908
+ "is",
2909
+ "in",
2910
+ "return",
2911
+ "break",
2912
+ "continue",
2913
+ "do",
2914
+ "while",
2915
+ "for",
2916
+ "if",
2917
+ "else",
2918
+ "try",
2919
+ "catch",
2920
+ "throw",
2921
+ "as",
2922
+ "this",
2923
+ "super",
2924
+ "null",
2925
+ "true",
2926
+ "false"
2927
+ ]);
2928
+ var KOTLIN_TYPE_GROUP_MAP = {
2929
+ color: "Colors",
2930
+ dimension: "Spacing",
2931
+ fontFamily: "Fonts",
2932
+ fontWeight: "FontWeights",
2933
+ duration: "Durations",
2934
+ shadow: "Shadows",
2935
+ typography: "Typography",
2936
+ number: "Numbers",
2937
+ cubicBezier: "Animations",
2938
+ border: "Borders"
2939
+ };
2940
+ function resolveColorFormat(format) {
2941
+ if (format === "argb_floats" || format === "argb_float") {
2942
+ return "argb_float";
2943
+ }
2944
+ return "argb_hex";
2945
+ }
2946
+ function escapeKotlinString(str) {
2947
+ return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\$/g, "\\$");
2948
+ }
2949
+ function formatKotlinNumber(value) {
2950
+ return Number.isInteger(value) ? `${value}.0` : String(value);
2951
+ }
2952
+ function roundComponent(value) {
2953
+ return Math.round(value * 1e3) / 1e3;
2954
+ }
2955
+ function toResourceName(family) {
2956
+ return family.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
2957
+ }
2958
+ var AndroidRenderer = class {
2959
+ async format(context, options) {
2960
+ if (!options?.packageName) {
2961
+ throw new ConfigurationError(
2962
+ `Output "${context.output.name}": packageName is required for Android output`
2963
+ );
2964
+ }
2965
+ const visibility = options?.visibility;
2966
+ const opts = {
2967
+ preset: options?.preset ?? "standalone",
2968
+ packageName: options.packageName,
2969
+ objectName: options?.objectName ?? "DesignTokens",
2970
+ colorFormat: resolveColorFormat(options?.colorFormat),
2971
+ colorSpace: options?.colorSpace ?? "sRGB",
2972
+ structure: options?.structure ?? "nested",
2973
+ visibility,
2974
+ visPrefix: visibility ? `${visibility} ` : "",
2975
+ indent: options?.indent ?? 4
2976
+ };
2977
+ if (opts.preset === "bundle") {
2978
+ return await this.formatBundle(context, opts);
2979
+ }
2980
+ return await this.formatStandalone(context, opts);
2981
+ }
2982
+ // -----------------------------------------------------------------------
2983
+ // Token tree (nested mode)
2984
+ // -----------------------------------------------------------------------
2985
+ buildTokenTree(tokens) {
2986
+ const root = { children: /* @__PURE__ */ new Map() };
2987
+ for (const [, token] of getSortedTokenEntries(tokens)) {
2988
+ let current = root;
2989
+ const segments = token.path;
2990
+ for (let i = 0; i < segments.length - 1; i++) {
2991
+ const seg = segments[i];
2992
+ if (!current.children.has(seg)) {
2993
+ current.children.set(seg, { children: /* @__PURE__ */ new Map() });
2994
+ }
2995
+ current = current.children.get(seg);
2996
+ }
2997
+ const leafName = segments[segments.length - 1] ?? token.name;
2998
+ const leaf = current.children.get(leafName) ?? { children: /* @__PURE__ */ new Map() };
2999
+ leaf.token = token;
3000
+ current.children.set(leafName, leaf);
3001
+ }
3002
+ return root;
3003
+ }
3004
+ // -----------------------------------------------------------------------
3005
+ // Flat structure grouping
3006
+ // -----------------------------------------------------------------------
3007
+ /**
3008
+ * Builds a flattened camelCase name from a token's path, stripping the
3009
+ * type prefix segment (which is already represented by the group object).
3010
+ */
3011
+ buildFlatKotlinName(token) {
3012
+ const path = token.path;
3013
+ const withoutTypePrefix = path.length > 1 ? path.slice(1) : path;
3014
+ const joined = withoutTypePrefix.join("_");
3015
+ return toSafeIdentifier(joined, KOTLIN_KEYWORDS, false);
3016
+ }
3017
+ // -----------------------------------------------------------------------
3018
+ // Rendering
3019
+ // -----------------------------------------------------------------------
3020
+ formatTokens(tokens, options) {
3021
+ if (options.structure === "flat") {
3022
+ return this.formatAsFlat(tokens, options);
3023
+ }
3024
+ return this.formatAsNested(tokens, options);
3025
+ }
3026
+ formatAsNested(tokens, options) {
3027
+ const tokenTypes = this.collectTokenTypesFromEntries(tokens);
3028
+ const tree = this.buildTokenTree(tokens);
3029
+ return this.buildFile(tokenTypes, options, (lines) => {
3030
+ lines.push(`@Suppress("unused")`);
3031
+ lines.push(`${options.visPrefix}object ${options.objectName} {`);
3032
+ this.renderTreeChildren(lines, tree, 1, options);
3033
+ lines.push("}");
3034
+ });
3035
+ }
3036
+ formatAsFlat(tokens, options) {
3037
+ const groups = groupTokensByType(tokens, KOTLIN_TYPE_GROUP_MAP);
3038
+ const tokenTypes = this.collectTokenTypesFromEntries(tokens);
3039
+ return this.buildFile(tokenTypes, options, (lines) => {
3040
+ lines.push(`@Suppress("unused")`);
3041
+ lines.push(`${options.visPrefix}object ${options.objectName} {`);
3042
+ this.renderFlatGroups(lines, groups, 1, options);
3043
+ lines.push("}");
3044
+ });
3045
+ }
3046
+ /**
3047
+ * Shared file preamble: header, package, imports, optional ShadowToken class.
3048
+ * The `renderBody` callback appends the main object(s) to `lines`.
3049
+ */
3050
+ buildFile(tokenTypes, options, renderBody) {
3051
+ const imports = this.collectImports(tokenTypes, options);
3052
+ const lines = [];
3053
+ lines.push(buildGeneratedFileHeader());
3054
+ lines.push("");
3055
+ lines.push(`package ${options.packageName}`);
3056
+ lines.push("");
3057
+ for (const imp of imports) {
3058
+ lines.push(`import ${imp}`);
3059
+ }
3060
+ if (imports.length > 0) {
3061
+ lines.push("");
3062
+ }
3063
+ if (tokenTypes.has("shadow")) {
3064
+ lines.push(...this.buildShadowTokenClass(options));
3065
+ lines.push("");
3066
+ }
3067
+ renderBody(lines);
3068
+ lines.push("");
3069
+ return lines.join("\n");
3070
+ }
3071
+ renderFlatGroups(lines, groups, baseDepth, options) {
3072
+ const groupIndent = indentStr(options.indent, baseDepth);
3073
+ const valIndent = indentStr(options.indent, baseDepth + 1);
3074
+ for (const group of groups) {
3075
+ lines.push(`${groupIndent}${options.visPrefix}object ${group.name} {`);
3076
+ for (const token of group.tokens) {
3077
+ const kotlinName = this.buildFlatKotlinName(token);
3078
+ const kotlinValue = this.formatKotlinValue(token, options, baseDepth + 1);
3079
+ const annotation = this.typeAnnotationSuffix(token);
3080
+ const descriptionComment = buildTokenDescriptionComment(token, "kotlin");
3081
+ if (descriptionComment) {
3082
+ lines.push(`${valIndent}${descriptionComment}`);
3083
+ }
3084
+ const deprecation = buildKotlinDeprecationAnnotation(token);
3085
+ if (deprecation) {
3086
+ lines.push(`${valIndent}${deprecation}`);
3087
+ }
3088
+ lines.push(
3089
+ `${valIndent}${options.visPrefix}val ${kotlinName}${annotation} = ${kotlinValue}`
3090
+ );
3091
+ }
3092
+ lines.push(`${groupIndent}}`);
3093
+ lines.push("");
3094
+ }
3095
+ }
3096
+ renderTreeChildren(lines, node, depth, options) {
3097
+ const pad = indentStr(options.indent, depth);
3098
+ const entries = Array.from(node.children.entries());
3099
+ for (let idx = 0; idx < entries.length; idx++) {
3100
+ const [key, child] = entries[idx];
3101
+ if (child.token && child.children.size === 0) {
3102
+ this.renderLeaf(lines, key, child.token, depth, options);
3103
+ } else if (child.children.size > 0 && !child.token) {
3104
+ const objectName = toSafeIdentifier(key, KOTLIN_KEYWORDS, true);
3105
+ lines.push(`${pad}${options.visPrefix}object ${objectName} {`);
3106
+ this.renderTreeChildren(lines, child, depth + 1, options);
3107
+ lines.push(`${pad}}`);
3108
+ if (idx < entries.length - 1) {
3109
+ lines.push("");
3110
+ }
3111
+ } else {
3112
+ this.renderLeaf(lines, key, child.token, depth, options);
3113
+ this.renderTreeChildren(lines, child, depth, options);
3114
+ }
3115
+ }
3116
+ }
3117
+ renderLeaf(lines, key, token, depth, options) {
3118
+ const pad = indentStr(options.indent, depth);
3119
+ const kotlinName = toSafeIdentifier(key, KOTLIN_KEYWORDS, false);
3120
+ const kotlinValue = this.formatKotlinValue(token, options, depth);
3121
+ const annotation = this.typeAnnotationSuffix(token);
3122
+ const descriptionComment = buildTokenDescriptionComment(token, "kotlin");
3123
+ if (descriptionComment) {
3124
+ lines.push(`${pad}${descriptionComment}`);
3125
+ }
3126
+ const deprecation = buildKotlinDeprecationAnnotation(token);
3127
+ if (deprecation) {
3128
+ lines.push(`${pad}${deprecation}`);
3129
+ }
3130
+ lines.push(`${pad}${options.visPrefix}val ${kotlinName}${annotation} = ${kotlinValue}`);
3131
+ }
3132
+ // -----------------------------------------------------------------------
3133
+ // Shadow data class
3134
+ // -----------------------------------------------------------------------
3135
+ buildShadowTokenClass(options) {
3136
+ const i1 = indentStr(options.indent, 1);
3137
+ return [
3138
+ "@Immutable",
3139
+ `${options.visPrefix}data class ShadowToken(`,
3140
+ `${i1}val color: Color,`,
3141
+ `${i1}val elevation: Dp,`,
3142
+ `${i1}val offsetX: Dp,`,
3143
+ `${i1}val offsetY: Dp,`,
3144
+ ")"
3145
+ ];
3146
+ }
3147
+ // -----------------------------------------------------------------------
3148
+ // Imports (tree-shaken)
3149
+ // -----------------------------------------------------------------------
3150
+ collectImports(tokenTypes, options) {
3151
+ const imports = /* @__PURE__ */ new Set();
3152
+ const ns = "androidx.compose";
3153
+ const hasColors = tokenTypes.has("color") || tokenTypes.has("shadow") || tokenTypes.has("border");
3154
+ if (hasColors) {
3155
+ imports.add(`${ns}.ui.graphics.Color`);
3156
+ }
3157
+ if (tokenTypes.has("dimension") || tokenTypes.has("shadow") || tokenTypes.has("border")) {
3158
+ imports.add(`${ns}.ui.unit.Dp`);
3159
+ imports.add(`${ns}.ui.unit.dp`);
3160
+ }
3161
+ if (tokenTypes.has("typography") || tokenTypes.has("fontFamily")) {
3162
+ imports.add(`${ns}.ui.text.TextStyle`);
3163
+ imports.add(`${ns}.ui.unit.sp`);
3164
+ }
3165
+ if (tokenTypes.has("typography") || tokenTypes.has("fontWeight")) {
3166
+ imports.add(`${ns}.ui.text.font.FontWeight`);
3167
+ }
3168
+ if (tokenTypes.has("fontFamily")) {
3169
+ imports.add(`${ns}.ui.text.font.FontFamily`);
3170
+ }
3171
+ if (tokenTypes.has("duration")) {
3172
+ imports.add("kotlin.time.Duration");
3173
+ imports.add("kotlin.time.Duration.Companion.milliseconds");
3174
+ imports.add("kotlin.time.Duration.Companion.seconds");
3175
+ }
3176
+ if (tokenTypes.has("cubicBezier")) {
3177
+ imports.add(`${ns}.animation.core.CubicBezierEasing`);
3178
+ }
3179
+ if (tokenTypes.has("shadow")) {
3180
+ imports.add(`${ns}.runtime.Immutable`);
3181
+ }
3182
+ if (tokenTypes.has("border")) {
3183
+ imports.add(`${ns}.foundation.BorderStroke`);
3184
+ }
3185
+ if (options.colorSpace === "displayP3" && hasColors) {
3186
+ imports.add(`${ns}.ui.graphics.colorspace.ColorSpaces`);
3187
+ }
3188
+ return Array.from(imports).sort();
3189
+ }
3190
+ collectTokenTypesFromEntries(tokens) {
3191
+ const types = /* @__PURE__ */ new Set();
3192
+ for (const [, token] of Object.entries(tokens)) {
3193
+ if (token.$type) {
3194
+ types.add(token.$type);
3195
+ }
3196
+ }
3197
+ return types;
3198
+ }
3199
+ // -----------------------------------------------------------------------
3200
+ // Type annotations
3201
+ // -----------------------------------------------------------------------
3202
+ getTypeAnnotation(token) {
3203
+ switch (token.$type) {
3204
+ case "color":
3205
+ return "Color";
3206
+ case "dimension":
3207
+ return "Dp";
3208
+ case "fontFamily":
3209
+ return "FontFamily";
3210
+ case "fontWeight":
3211
+ return "FontWeight";
3212
+ case "duration":
3213
+ return "Duration";
3214
+ case "shadow":
3215
+ return "ShadowToken";
3216
+ case "cubicBezier":
3217
+ return "CubicBezierEasing";
3218
+ case "number":
3219
+ return "Double";
3220
+ case "typography":
3221
+ return "TextStyle";
3222
+ case "border":
3223
+ return "BorderStroke";
3224
+ default: {
3225
+ const value = token.$value;
3226
+ if (typeof value === "string") {
3227
+ return "String";
3228
+ }
3229
+ if (typeof value === "boolean") {
3230
+ return "Boolean";
3231
+ }
3232
+ if (typeof value === "number") {
3233
+ return "Double";
3234
+ }
3235
+ return void 0;
3236
+ }
3237
+ }
3238
+ }
3239
+ typeAnnotationSuffix(token) {
3240
+ const type = this.getTypeAnnotation(token);
3241
+ return type ? `: ${type}` : "";
3242
+ }
3243
+ // -----------------------------------------------------------------------
3244
+ // Value formatting
3245
+ // -----------------------------------------------------------------------
3246
+ formatKotlinValue(token, options, depth) {
3247
+ const value = token.$value;
3248
+ if (token.$type === "color") {
3249
+ return this.formatColorValue(value, options);
3250
+ }
3251
+ if (token.$type === "dimension") {
3252
+ return this.formatDimensionValue(value);
3253
+ }
3254
+ if (token.$type === "fontFamily") {
3255
+ return this.formatFontFamilyValue(value);
3256
+ }
3257
+ if (token.$type === "fontWeight") {
3258
+ return this.formatFontWeightValue(value);
3259
+ }
3260
+ if (token.$type === "duration") {
3261
+ return this.formatDurationValue(value);
3262
+ }
3263
+ if (token.$type === "shadow") {
3264
+ return this.formatShadowValue(value, options, depth);
3265
+ }
3266
+ if (token.$type === "typography") {
3267
+ return this.formatTypographyValue(value, options, depth);
3268
+ }
3269
+ if (token.$type === "border") {
3270
+ return this.formatBorderValue(value, options);
3271
+ }
3272
+ if (token.$type === "number") {
3273
+ return typeof value === "number" ? formatKotlinNumber(value) : String(value);
3274
+ }
3275
+ if (token.$type === "cubicBezier" && Array.isArray(value) && value.length === 4) {
3276
+ return `CubicBezierEasing(${value[0]}f, ${value[1]}f, ${value[2]}f, ${value[3]}f)`;
3277
+ }
3278
+ if (typeof value === "string") {
3279
+ return `"${escapeKotlinString(value)}"`;
3280
+ }
3281
+ if (typeof value === "number") {
3282
+ return formatKotlinNumber(value);
3283
+ }
3284
+ if (typeof value === "boolean") {
3285
+ return value ? "true" : "false";
3286
+ }
3287
+ return `"${escapeKotlinString(String(value))}"`;
3288
+ }
3289
+ formatColorValue(value, options) {
3290
+ if (!isColorObject(value)) {
3291
+ if (typeof value === "string") {
3292
+ const hex = value.replace("#", "");
3293
+ if (/^[0-9a-fA-F]{6,8}$/.test(hex)) {
3294
+ const argb = hex.length === 8 ? hex : `FF${hex}`;
3295
+ return `Color(0x${argb.toUpperCase()})`;
3296
+ }
3297
+ }
3298
+ return "Color.Unspecified";
3299
+ }
3300
+ const colorObj = value;
3301
+ const alpha = colorObj.alpha ?? 1;
3302
+ if (options.colorFormat === "argb_float" || options.colorSpace === "displayP3") {
3303
+ return this.formatFloatColor(colorObj, alpha, options);
3304
+ }
3305
+ return this.formatHexColor(colorObj, alpha);
3306
+ }
3307
+ formatFloatColor(colorObj, alpha, options) {
3308
+ if (options.colorSpace === "displayP3") {
3309
+ const p3 = toP32(dtcgObjectToCulori(colorObj));
3310
+ const r2 = roundComponent(p3?.r ?? 0);
3311
+ const g2 = roundComponent(p3?.g ?? 0);
3312
+ const b2 = roundComponent(p3?.b ?? 0);
3313
+ return `Color(${r2}f, ${g2}f, ${b2}f, ${roundComponent(alpha)}f, ColorSpaces.DisplayP3)`;
3314
+ }
3315
+ const rgb = toSRGB2(dtcgObjectToCulori(colorObj));
3316
+ const r = roundComponent(rgb?.r ?? 0);
3317
+ const g = roundComponent(rgb?.g ?? 0);
3318
+ const b = roundComponent(rgb?.b ?? 0);
3319
+ return `Color(${r}f, ${g}f, ${b}f, ${roundComponent(alpha)}f)`;
3320
+ }
3321
+ formatHexColor(colorObj, alpha) {
3322
+ const hex = colorObjectToHex(colorObj);
3323
+ const hexClean = hex.replace("#", "");
3324
+ if (hexClean.length === 8) {
3325
+ const rrggbb = hexClean.slice(0, 6);
3326
+ const aa = hexClean.slice(6, 8);
3327
+ return `Color(0x${aa.toUpperCase()}${rrggbb.toUpperCase()})`;
3328
+ }
3329
+ const alphaHex = alpha < 1 ? Math.round(alpha * 255).toString(16).padStart(2, "0").toUpperCase() : "FF";
3330
+ return `Color(0x${alphaHex}${hexClean.toUpperCase()})`;
3331
+ }
3332
+ formatDimensionValue(value) {
3333
+ if (isDimensionObject(value)) {
3334
+ const dim = value;
3335
+ const dpValue = dim.unit === "rem" ? dim.value * 16 : dim.value;
3336
+ return `${dpValue}.dp`;
3337
+ }
3338
+ return typeof value === "number" ? `${value}.dp` : `0.dp`;
3339
+ }
3340
+ formatFontFamilyValue(value) {
3341
+ if (Array.isArray(value)) {
3342
+ const primary = value[0];
3343
+ if (typeof primary === "string") {
3344
+ return this.mapKotlinFontFamily(primary);
3345
+ }
3346
+ return "FontFamily.Default";
3347
+ }
3348
+ return typeof value === "string" ? this.mapKotlinFontFamily(value) : "FontFamily.Default";
3349
+ }
3350
+ mapKotlinFontFamily(family) {
3351
+ const normalized = family.toLowerCase().replace(/['"]/g, "").trim();
3352
+ const builtIn = {
3353
+ "sans-serif": "FontFamily.SansSerif",
3354
+ serif: "FontFamily.Serif",
3355
+ monospace: "FontFamily.Monospace",
3356
+ cursive: "FontFamily.Cursive"
3357
+ };
3358
+ return builtIn[normalized] ?? `FontFamily.Default // TODO: load "${family}" via Font(R.font.${toResourceName(family)})`;
3359
+ }
3360
+ formatFontWeightValue(value) {
3361
+ if (typeof value === "number") {
3362
+ return this.numericFontWeight(value);
3363
+ }
3364
+ if (typeof value === "string") {
3365
+ return this.namedFontWeight(value) ?? "FontWeight.Normal";
3366
+ }
3367
+ return "FontWeight.Normal";
3368
+ }
3369
+ numericFontWeight(weight) {
3370
+ if (weight <= 100) {
3371
+ return "FontWeight.Thin";
3372
+ }
3373
+ if (weight <= 200) {
3374
+ return "FontWeight.ExtraLight";
3375
+ }
3376
+ if (weight <= 300) {
3377
+ return "FontWeight.Light";
3378
+ }
3379
+ if (weight <= 400) {
3380
+ return "FontWeight.Normal";
3381
+ }
3382
+ if (weight <= 500) {
3383
+ return "FontWeight.Medium";
3384
+ }
3385
+ if (weight <= 600) {
3386
+ return "FontWeight.SemiBold";
3387
+ }
3388
+ if (weight <= 700) {
3389
+ return "FontWeight.Bold";
3390
+ }
3391
+ if (weight <= 800) {
3392
+ return "FontWeight.ExtraBold";
3393
+ }
3394
+ return "FontWeight.Black";
3395
+ }
3396
+ namedFontWeight(name) {
3397
+ const map = {
3398
+ thin: "FontWeight.Thin",
3399
+ extralight: "FontWeight.ExtraLight",
3400
+ ultralight: "FontWeight.ExtraLight",
3401
+ light: "FontWeight.Light",
3402
+ regular: "FontWeight.Normal",
3403
+ normal: "FontWeight.Normal",
3404
+ medium: "FontWeight.Medium",
3405
+ semibold: "FontWeight.SemiBold",
3406
+ demibold: "FontWeight.SemiBold",
3407
+ bold: "FontWeight.Bold",
3408
+ extrabold: "FontWeight.ExtraBold",
3409
+ heavy: "FontWeight.ExtraBold",
3410
+ black: "FontWeight.Black",
3411
+ ultrabold: "FontWeight.Black"
3412
+ };
3413
+ return map[name.toLowerCase()];
3414
+ }
3415
+ formatDurationValue(value) {
3416
+ if (isDurationObject(value)) {
3417
+ return value.unit === "ms" ? `${value.value}.milliseconds` : `${value.value}.seconds`;
3418
+ }
3419
+ return typeof value === "number" ? `${value}.milliseconds` : "0.milliseconds";
3420
+ }
3421
+ formatShadowValue(value, options, depth) {
3422
+ if (Array.isArray(value) && value.length > 0) {
3423
+ return this.formatSingleShadow(value[0], options, depth);
3424
+ }
3425
+ if (typeof value === "object" && value !== null) {
3426
+ return this.formatSingleShadow(value, options, depth);
3427
+ }
3428
+ return "ShadowToken(color = Color.Unspecified, elevation = 0.dp, offsetX = 0.dp, offsetY = 0.dp)";
3429
+ }
3430
+ formatSingleShadow(shadow, options, depth) {
3431
+ const color = isColorObject(shadow.color) ? this.formatColorValue(shadow.color, options) : "Color.Black";
3432
+ const elevation = isDimensionObject(shadow.blur) ? this.formatDimensionValue(shadow.blur) : "0.dp";
3433
+ const offsetX = isDimensionObject(shadow.offsetX) ? this.formatDimensionValue(shadow.offsetX) : "0.dp";
3434
+ const offsetY = isDimensionObject(shadow.offsetY) ? this.formatDimensionValue(shadow.offsetY) : "0.dp";
3435
+ const propIndent = indentStr(options.indent, depth + 1);
3436
+ const closeIndent = indentStr(options.indent, depth);
3437
+ return [
3438
+ "ShadowToken(",
3439
+ `${propIndent}color = ${color},`,
3440
+ `${propIndent}elevation = ${elevation},`,
3441
+ `${propIndent}offsetX = ${offsetX},`,
3442
+ `${propIndent}offsetY = ${offsetY},`,
3443
+ `${closeIndent})`
3444
+ ].join("\n");
3445
+ }
3446
+ formatBorderValue(value, options) {
3447
+ if (typeof value !== "object" || value === null) {
3448
+ return "BorderStroke(0.dp, Color.Unspecified)";
3449
+ }
3450
+ const border = value;
3451
+ const width = isDimensionObject(border.width) ? this.formatDimensionValue(border.width) : "0.dp";
3452
+ const color = isColorObject(border.color) ? this.formatColorValue(border.color, options) : "Color.Unspecified";
3453
+ return `BorderStroke(${width}, ${color})`;
3454
+ }
3455
+ formatTypographyValue(value, options, depth) {
3456
+ if (typeof value !== "object" || value === null) {
3457
+ return "TextStyle()";
3458
+ }
3459
+ const typo = value;
3460
+ const parts = [];
3461
+ if (isDimensionObject(typo.fontSize)) {
3462
+ const dim = typo.fontSize;
3463
+ const spValue = dim.unit === "rem" ? dim.value * 16 : dim.value;
3464
+ parts.push(`fontSize = ${spValue}.sp`);
3465
+ }
3466
+ if (typo.fontWeight != null) {
3467
+ parts.push(`fontWeight = ${this.formatFontWeightValue(typo.fontWeight)}`);
3468
+ }
3469
+ if (typo.lineHeight != null && typeof typo.lineHeight === "number") {
3470
+ if (isDimensionObject(typo.fontSize)) {
3471
+ const dim = typo.fontSize;
3472
+ const spValue = dim.unit === "rem" ? dim.value * 16 : dim.value;
3473
+ const lineHeightSp = Math.round(spValue * typo.lineHeight * 100) / 100;
3474
+ parts.push(`lineHeight = ${lineHeightSp}.sp`);
3475
+ }
3476
+ }
3477
+ if (isDimensionObject(typo.letterSpacing)) {
3478
+ const dim = typo.letterSpacing;
3479
+ const spValue = dim.unit === "rem" ? dim.value * 16 : dim.value;
3480
+ parts.push(`letterSpacing = ${spValue}.sp`);
3481
+ }
3482
+ if (parts.length === 0) {
3483
+ return "TextStyle()";
3484
+ }
3485
+ const propIndent = indentStr(options.indent, depth + 1);
3486
+ const closeIndent = indentStr(options.indent, depth);
3487
+ return `TextStyle(
3488
+ ${parts.map((p) => `${propIndent}${p}`).join(",\n")},
3489
+ ${closeIndent})`;
3490
+ }
3491
+ // -----------------------------------------------------------------------
3492
+ // Output: standalone
3493
+ // -----------------------------------------------------------------------
3494
+ async formatStandalone(context, options) {
3495
+ assertFileRequired(
3496
+ context.buildPath,
3497
+ context.output.file,
3498
+ context.output.name,
3499
+ "standalone Android"
3500
+ );
3501
+ const files = {};
3502
+ for (const { tokens, modifierInputs } of context.permutations) {
3503
+ const processedTokens = stripInternalMetadata(tokens);
3504
+ const content = this.formatTokens(processedTokens, options);
3505
+ const fileName = context.output.file ? resolveFileName(context.output.file, modifierInputs) : buildInMemoryOutputKey({
3506
+ outputName: context.output.name,
3507
+ extension: "kt",
3508
+ modifierInputs,
3509
+ resolver: context.resolver,
3510
+ defaults: context.meta.defaults
3511
+ });
3512
+ files[fileName] = content;
3513
+ }
3514
+ return outputTree(files);
3515
+ }
3516
+ // -----------------------------------------------------------------------
3517
+ // Output: bundle
3518
+ // -----------------------------------------------------------------------
3519
+ async formatBundle(context, options) {
3520
+ assertFileRequired(
3521
+ context.buildPath,
3522
+ context.output.file,
3523
+ context.output.name,
3524
+ "bundle Android"
3525
+ );
3526
+ const content = this.formatBundleContent(context, options);
3527
+ const fileName = context.output.file ? resolveFileName(context.output.file, context.meta.basePermutation) : buildInMemoryOutputKey({
3528
+ outputName: context.output.name,
3529
+ extension: "kt",
3530
+ modifierInputs: context.meta.basePermutation,
3531
+ resolver: context.resolver,
3532
+ defaults: context.meta.defaults
3533
+ });
3534
+ return outputTree({ [fileName]: content });
3535
+ }
3536
+ formatBundleContent(context, options) {
3537
+ const allTokenTypes = this.collectAllPermutationTypes(context);
3538
+ return this.buildFile(allTokenTypes, options, (lines) => {
3539
+ const i1 = indentStr(options.indent, 1);
3540
+ lines.push(`@Suppress("unused")`);
3541
+ lines.push(`${options.visPrefix}object ${options.objectName} {`);
3542
+ for (let idx = 0; idx < context.permutations.length; idx++) {
3543
+ const { tokens, modifierInputs } = context.permutations[idx];
3544
+ const processedTokens = stripInternalMetadata(tokens);
3545
+ const permName = this.buildPermutationName(modifierInputs);
3546
+ lines.push(`${i1}${options.visPrefix}object ${permName} {`);
3547
+ this.renderBundleTokens(lines, processedTokens, options, 2);
3548
+ lines.push(`${i1}}`);
3549
+ if (idx < context.permutations.length - 1) {
3550
+ lines.push("");
3551
+ }
3552
+ }
3553
+ lines.push("}");
3554
+ });
3555
+ }
3556
+ collectAllPermutationTypes(context) {
3557
+ const types = /* @__PURE__ */ new Set();
3558
+ for (const { tokens } of context.permutations) {
3559
+ for (const t of this.collectTokenTypesFromEntries(stripInternalMetadata(tokens))) {
3560
+ types.add(t);
3561
+ }
3562
+ }
3563
+ return types;
3564
+ }
3565
+ renderBundleTokens(lines, tokens, options, baseDepth) {
3566
+ if (options.structure === "flat") {
3567
+ const groups = groupTokensByType(tokens, KOTLIN_TYPE_GROUP_MAP);
3568
+ this.renderFlatGroups(lines, groups, baseDepth, options);
3569
+ return;
3570
+ }
3571
+ const tree = this.buildTokenTree(tokens);
3572
+ this.renderTreeChildren(lines, tree, baseDepth, options);
3573
+ }
3574
+ buildPermutationName(modifierInputs) {
3575
+ const values = Object.values(modifierInputs);
3576
+ if (values.length === 0) {
3577
+ return "Default";
3578
+ }
3579
+ return values.map((v) => toSafeIdentifier(v, KOTLIN_KEYWORDS, true)).join("");
3580
+ }
3581
+ };
3582
+ function androidRenderer() {
3583
+ const rendererInstance = new AndroidRenderer();
3584
+ return {
3585
+ format: (context, options) => rendererInstance.format(
3586
+ context,
3587
+ options ?? context.output.options
3588
+ )
3589
+ };
3590
+ }
3591
+
3592
+ // src/outputs/types.ts
3593
+ function defineRenderer(renderer) {
3594
+ return renderer;
3595
+ }
3596
+ function nameKebabCase() {
3597
+ return {
3598
+ transform: (token) => {
3599
+ const name = changeCase.kebabCase(token.path.join(" "));
3600
+ return {
3601
+ ...token,
3602
+ name
3603
+ };
3604
+ }
3605
+ };
3606
+ }
3607
+
3608
+ // src/outputs/builders.ts
3609
+ function css(config) {
3610
+ const {
3611
+ name,
3612
+ file,
3613
+ transforms,
3614
+ filters,
3615
+ hooks,
3616
+ preset = "bundle",
3617
+ ...rendererOptions
3618
+ } = config;
3619
+ return {
3620
+ name,
3621
+ file,
3622
+ renderer: cssRenderer(),
3623
+ options: { preset, ...rendererOptions },
3624
+ transforms: [nameKebabCase(), ...transforms ?? []],
3625
+ filters,
3626
+ hooks
3627
+ };
3628
+ }
3629
+ function json(config) {
3630
+ const {
3631
+ name,
3632
+ file,
3633
+ transforms,
3634
+ filters,
3635
+ hooks,
3636
+ preset = "standalone",
3637
+ ...rendererOptions
3638
+ } = config;
3639
+ return {
3640
+ name,
3641
+ file,
3642
+ renderer: jsonRenderer(),
3643
+ options: { preset, ...rendererOptions },
3644
+ transforms,
3645
+ filters,
3646
+ hooks
3647
+ };
3648
+ }
3649
+ function js(config) {
3650
+ const {
3651
+ name,
3652
+ file,
3653
+ transforms,
3654
+ filters,
3655
+ hooks,
3656
+ preset = "standalone",
3657
+ ...rendererOptions
3658
+ } = config;
3659
+ return {
3660
+ name,
3661
+ file,
3662
+ renderer: jsRenderer(),
3663
+ options: { preset, ...rendererOptions },
3664
+ transforms,
3665
+ filters,
3666
+ hooks
3667
+ };
3668
+ }
3669
+ function tailwind(config) {
3670
+ const { name, file, transforms, filters, hooks, preset = "bundle", ...rendererOptions } = config;
3671
+ return {
3672
+ name,
3673
+ file,
3674
+ renderer: tailwindRenderer(),
3675
+ options: { preset, ...rendererOptions },
3676
+ transforms,
3677
+ filters,
3678
+ hooks
3679
+ };
3680
+ }
3681
+ function ios(config) {
3682
+ const {
3683
+ name,
3684
+ file,
3685
+ transforms,
3686
+ filters,
3687
+ hooks,
3688
+ preset = "standalone",
3689
+ ...rendererOptions
3690
+ } = config;
3691
+ return {
3692
+ name,
3693
+ file,
3694
+ renderer: iosRenderer(),
3695
+ options: { preset, ...rendererOptions },
3696
+ transforms,
3697
+ filters,
3698
+ hooks
3699
+ };
3700
+ }
3701
+ function android(config) {
3702
+ const {
3703
+ name,
3704
+ file,
3705
+ transforms,
3706
+ filters,
3707
+ hooks,
3708
+ preset = "standalone",
3709
+ ...rendererOptions
3710
+ } = config;
3711
+ return {
3712
+ name,
3713
+ file,
3714
+ renderer: androidRenderer(),
3715
+ options: { preset, ...rendererOptions },
3716
+ transforms,
3717
+ filters,
3718
+ hooks
3719
+ };
3720
+ }
3721
+ /**
3722
+ * @license MIT
3723
+ * Copyright (c) 2025-present Dispersa Contributors
3724
+ *
3725
+ * This source code is licensed under the MIT license found in the
3726
+ * LICENSE file in the root directory of this source tree.
3727
+ */
3728
+ /**
3729
+ * @license
3730
+ * Copyright (c) 2025 Dispersa Contributors
3731
+ * SPDX-License-Identifier: MIT
3732
+ */
3733
+
3734
+ exports.android = android;
3735
+ exports.androidRenderer = androidRenderer;
3736
+ exports.css = css;
3737
+ exports.cssRenderer = cssRenderer;
3738
+ exports.defineRenderer = defineRenderer;
3739
+ exports.ios = ios;
3740
+ exports.iosRenderer = iosRenderer;
3741
+ exports.isOutputTree = isOutputTree;
3742
+ exports.js = js;
3743
+ exports.jsRenderer = jsRenderer;
3744
+ exports.json = json;
3745
+ exports.jsonRenderer = jsonRenderer;
3746
+ exports.outputTree = outputTree;
3747
+ exports.tailwind = tailwind;
3748
+ exports.tailwindRenderer = tailwindRenderer;
3749
+ //# sourceMappingURL=index.cjs.map
3750
+ //# sourceMappingURL=index.cjs.map