@bamboocss/token-dictionary 1.11.1 → 1.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,1324 +1,1281 @@
1
- // src/dictionary.ts
2
- import {
3
- capitalize,
4
- compact,
5
- cssVar,
6
- esc as esc3,
7
- isString as isString2,
8
- mapObject,
9
- memo,
10
- BambooError as BambooError3,
11
- walkObject as walkObject2
12
- } from "@bamboocss/shared";
13
- import { isMatching as isMatching2, match as match2 } from "ts-pattern";
14
-
15
- // src/is-composite.ts
16
- import { P, isMatching } from "ts-pattern";
17
- var isCompositeShadow = isMatching({
18
- inset: P.optional(P.boolean),
19
- offsetX: P.union(P.number, P.string),
20
- offsetY: P.union(P.number, P.string),
21
- blur: P.union(P.number, P.string),
22
- spread: P.union(P.number, P.string),
23
- color: P.string
1
+ import { BambooError, calc, capitalize, compact, cssVar, esc, isBaseCondition, isCssUnit, isObject, isString, mapObject, memo, toHash, toPx, walkObject } from "@bamboocss/shared";
2
+ import { P, isMatching, match } from "ts-pattern";
3
+ import { logger } from "@bamboocss/logger";
4
+ import picomatch from "picomatch";
5
+ //#region src/is-composite.ts
6
+ const isCompositeShadow = isMatching({
7
+ inset: P.optional(P.boolean),
8
+ offsetX: P.union(P.number, P.string),
9
+ offsetY: P.union(P.number, P.string),
10
+ blur: P.union(P.number, P.string),
11
+ spread: P.union(P.number, P.string),
12
+ color: P.string
24
13
  });
25
- var isCompositeGradient = isMatching({
26
- type: P.string,
27
- placement: P.string,
28
- stops: P.union(
29
- P.array(P.string),
30
- P.array({
31
- color: P.string,
32
- position: P.number
33
- })
34
- )
14
+ const isCompositeGradient = isMatching({
15
+ type: P.string,
16
+ placement: P.string,
17
+ stops: P.union(P.array(P.string), P.array({
18
+ color: P.string,
19
+ position: P.number
20
+ }))
35
21
  });
36
- var isCompositeBorder = isMatching({
37
- color: P.string,
38
- width: P.union(P.string, P.number),
39
- style: P.string
22
+ const isCompositeBorder = isMatching({
23
+ color: P.string,
24
+ width: P.union(P.string, P.number),
25
+ style: P.string
40
26
  });
41
- var isCompositeAsset = isMatching({
42
- type: P.union("url", "svg"),
43
- value: P.string
27
+ const isCompositeAsset = isMatching({
28
+ type: P.union("url", "svg"),
29
+ value: P.string
44
30
  });
45
- var isCompositeTokenValue = (value) => {
46
- return isCompositeGradient(value) || isCompositeShadow(value) || isCompositeBorder(value) || isCompositeAsset(value) || Array.isArray(value);
31
+ const isCompositeTokenValue = (value) => {
32
+ return isCompositeGradient(value) || isCompositeShadow(value) || isCompositeBorder(value) || isCompositeAsset(value) || Array.isArray(value);
47
33
  };
48
-
49
- // src/middleware.ts
50
- import { calc, toPx } from "@bamboocss/shared";
51
-
52
- // src/token.ts
53
- import { isBaseCondition, toHash, walkObject } from "@bamboocss/shared";
54
-
55
- // src/utils.ts
56
- import { logger } from "@bamboocss/logger";
57
- import { BambooError, esc, isObject } from "@bamboocss/shared";
58
- var REFERENCE_REGEX = /({([^}]*)})/g;
59
- var curlyBracketRegex = /[{}]/g;
34
+ //#endregion
35
+ //#region src/utils.ts
36
+ /**
37
+ * Regex for matching a tokenized reference.
38
+ */
39
+ const REFERENCE_REGEX = /({([^}]*)})/g;
40
+ const curlyBracketRegex = /[{}]/g;
41
+ /**
42
+ * Returns all references in a string
43
+ *
44
+ * @example
45
+ *
46
+ * `{colors.red.300} {sizes.sm}` => ['colors.red.300', 'sizes.sm']
47
+ */
60
48
  function getReferences(value) {
61
- if (typeof value !== "string") return [];
62
- const matches = value.match(REFERENCE_REGEX);
63
- if (!matches) return [];
64
- return matches.map((match3) => match3.replace(curlyBracketRegex, "")).map((value2) => value2.trim());
49
+ if (typeof value !== "string") return [];
50
+ const matches = value.match(REFERENCE_REGEX);
51
+ if (!matches) return [];
52
+ return matches.map((match) => match.replace(curlyBracketRegex, "")).map((value) => value.trim());
65
53
  }
66
- var hasReference = (value) => getReferences(value).length > 0;
67
- var tokenFunctionRegex = /token\(([^)]+)\)/g;
68
- var closingParenthesisRegex = /\)$/g;
69
- var hasTokenReference = (str) => str.includes("token(");
70
- var tokenReplacer = (a, b) => b ? a.endsWith(")") ? a.replace(closingParenthesisRegex, `, ${b})`) : `var(${a}, ${b})` : a;
71
- var notFoundMessage = (key, value) => `Reference not found: \`${key}\` in "${value}"`;
72
- var isTokenReference = (v) => hasReference(v) || hasTokenReference(v);
54
+ const hasReference = (value) => getReferences(value).length > 0;
55
+ const tokenFunctionRegex = /token\(([^)]+)\)/g;
56
+ const closingParenthesisRegex = /\)$/g;
57
+ const hasTokenReference = (str) => str.includes("token(");
58
+ const tokenReplacer = (a, b) => b ? a.endsWith(")") ? a.replace(closingParenthesisRegex, `, ${b})`) : `var(${a}, ${b})` : a;
59
+ const notFoundMessage = (key, value) => `Reference not found: \`${key}\` in "${value}"`;
60
+ const isTokenReference = (v) => hasReference(v) || hasTokenReference(v);
73
61
  function expandReferences(value, fn) {
74
- if (!isTokenReference(value)) return value;
75
- const references = getReferences(value);
76
- const expanded = references.reduce((valueStr, key) => {
77
- const resolved = fn(key);
78
- if (!resolved) {
79
- logger.warn("token", notFoundMessage(key, value));
80
- }
81
- const expandedValue = resolved ?? esc(key);
82
- return valueStr.replaceAll(`{${key}}`, expandedValue);
83
- }, value);
84
- if (!expanded.includes(`token(`)) return expanded;
85
- return expanded.replace(tokenFunctionRegex, (_, token) => {
86
- const [tokenValue, tokenFallback] = token.split(",").map((s) => s.trim());
87
- const result = [tokenValue, tokenFallback].filter(Boolean).map((key) => {
88
- const resolved = fn(key);
89
- if (!resolved && isTokenReference(key)) {
90
- logger.warn("token", notFoundMessage(key, value));
91
- }
92
- return resolved ?? esc(key);
93
- });
94
- if (result.length > 1) {
95
- const [a, b] = result;
96
- return tokenReplacer(a, b);
97
- }
98
- return tokenReplacer(result[0]);
99
- });
62
+ if (!isTokenReference(value)) return value;
63
+ const expanded = getReferences(value).reduce((valueStr, key) => {
64
+ const resolved = fn(key);
65
+ if (!resolved) logger.warn("token", notFoundMessage(key, value));
66
+ const expandedValue = resolved ?? esc(key);
67
+ return valueStr.replaceAll(`{${key}}`, expandedValue);
68
+ }, value);
69
+ if (!expanded.includes(`token(`)) return expanded;
70
+ return expanded.replace(tokenFunctionRegex, (_, token) => {
71
+ const [tokenValue, tokenFallback] = token.split(",").map((s) => s.trim());
72
+ const result = [tokenValue, tokenFallback].filter(Boolean).map((key) => {
73
+ const resolved = fn(key);
74
+ if (!resolved && isTokenReference(key)) logger.warn("token", notFoundMessage(key, value));
75
+ return resolved ?? esc(key);
76
+ });
77
+ if (result.length > 1) {
78
+ const [a, b] = result;
79
+ return tokenReplacer(a, b);
80
+ }
81
+ return tokenReplacer(result[0]);
82
+ });
100
83
  }
84
+ /**
85
+ * Converts a JS Map to an object
86
+ */
101
87
  function mapToJson(map) {
102
- const obj = {};
103
- map.forEach((value, key) => {
104
- if (value instanceof Map) {
105
- obj[key] = Object.fromEntries(value);
106
- } else {
107
- obj[key] = value;
108
- }
109
- });
110
- return obj;
88
+ const obj = {};
89
+ map.forEach((value, key) => {
90
+ if (value instanceof Map) obj[key] = Object.fromEntries(value);
91
+ else obj[key] = value;
92
+ });
93
+ return obj;
111
94
  }
112
- var isToken = (value) => {
113
- return isObject(value) && "value" in value;
95
+ const isToken = (value) => {
96
+ return isObject(value) && "value" in value;
114
97
  };
115
98
  function assertTokenFormat(token) {
116
- if (!isToken(token)) {
117
- throw new BambooError("INVALID_TOKEN", `Invalid token format: ${JSON.stringify(token)}`);
118
- }
99
+ if (!isToken(token)) throw new BambooError("INVALID_TOKEN", `Invalid token format: ${JSON.stringify(token)}`);
119
100
  }
120
-
121
- // src/token.ts
122
- var Token = class _Token {
123
- name;
124
- value;
125
- originalValue;
126
- path;
127
- type;
128
- description;
129
- deprecated;
130
- extensions;
131
- constructor(input) {
132
- this.name = input.name;
133
- this.value = input.value;
134
- this.originalValue = input.value;
135
- this.path = input.path ?? [];
136
- if (input.type) {
137
- this.type = input.type;
138
- }
139
- if (input.description) {
140
- this.description = input.description;
141
- }
142
- this.extensions = input.extensions ?? {};
143
- this.extensions.condition = input.extensions?.condition ?? "base";
144
- this.deprecated = input.deprecated;
145
- this.setType();
146
- }
147
- /**
148
- * The unique identifier of the token.
149
- */
150
- get id() {
151
- return toHash(`${this.name}-${this.extensions.condition}-${this.value}`);
152
- }
153
- /**
154
- * Whether the token is a conditional token.
155
- * Conditional tokens are tokens that have multiple values based on a condition.
156
- */
157
- get isConditional() {
158
- return !!this.extensions?.conditions;
159
- }
160
- /**
161
- * Whether the token has a reference in its value.
162
- * e.g. {color.gray.100}
163
- */
164
- get hasReference() {
165
- return !!this.extensions?.references;
166
- }
167
- /**
168
- * Whether the token is a complex or composite token.
169
- */
170
- get isComposite() {
171
- return isCompositeTokenValue(this.originalValue);
172
- }
173
- /**
174
- * Returns the token value with the references expanded.
175
- * e.g. {color.gray.100} => var(--colors-gray-100)
176
- *
177
- */
178
- expandReferences() {
179
- if (!this.hasReference) return this.extensions.varRef ?? this.value;
180
- const references = this.extensions.references ?? {};
181
- this.value = Object.keys(references).reduce((valueStr, key) => {
182
- const referenceToken = references[key];
183
- if (referenceToken.isConditional) {
184
- return valueStr;
185
- }
186
- const value = referenceToken.expandReferences();
187
- return valueStr.replaceAll(`{${key}}`, value);
188
- }, this.value);
189
- delete this.extensions.references;
190
- return this.value;
191
- }
192
- /**
193
- * Whether this token has a reference to another token
194
- */
195
- get isReference() {
196
- return hasReference(this.originalValue);
197
- }
198
- /**
199
- * Returns the list of references in the token value
200
- */
201
- get references() {
202
- return getReferences(this.originalValue);
203
- }
204
- clone() {
205
- return new _Token({
206
- name: this.name,
207
- value: this.value,
208
- type: this.type,
209
- path: [...this.path],
210
- description: this.description,
211
- extensions: cloneDeep(this.extensions)
212
- });
213
- }
214
- /**
215
- * Returns an array of tokens per conditions.
216
- * It is commonly used in semantic tokens, and can have multiple values based on a condition.
217
- * e.g. primary: { light: '#000', dark: '#fff' }
218
- */
219
- getConditionTokens() {
220
- if (!this.isConditional) return;
221
- const conditions = this.extensions.conditions ?? {};
222
- const conditionalTokens = [];
223
- walkObject(conditions, (value, path) => {
224
- const newPath = path.filter((v) => !isBaseCondition(v));
225
- if (!newPath.length) return;
226
- const token = this.clone();
227
- token.value = value;
228
- token.extensions.condition = newPath.join(":");
229
- conditionalTokens.push(token);
230
- });
231
- return conditionalTokens;
232
- }
233
- /**
234
- * Add more extensions to the token
235
- */
236
- setExtensions(extensions) {
237
- this.extensions = { ...this.extensions, ...extensions };
238
- this.setType();
239
- return this;
240
- }
241
- setType() {
242
- if (this.type) return;
243
- if (this.extensions.category) {
244
- this.type = TOKEN_TYPES[this.extensions.category];
245
- }
246
- }
101
+ //#endregion
102
+ //#region src/token.ts
103
+ /**
104
+ * Represents a design token in the dictionary
105
+ */
106
+ var Token = class Token {
107
+ name;
108
+ value;
109
+ originalValue;
110
+ path;
111
+ type;
112
+ description;
113
+ deprecated;
114
+ extensions;
115
+ constructor(input) {
116
+ this.name = input.name;
117
+ this.value = input.value;
118
+ this.originalValue = input.value;
119
+ this.path = input.path ?? [];
120
+ if (input.type) this.type = input.type;
121
+ if (input.description) this.description = input.description;
122
+ this.extensions = input.extensions ?? {};
123
+ this.extensions.condition = input.extensions?.condition ?? "base";
124
+ this.deprecated = input.deprecated;
125
+ this.setType();
126
+ }
127
+ /**
128
+ * The unique identifier of the token.
129
+ */
130
+ get id() {
131
+ return toHash(`${this.name}-${this.extensions.condition}-${this.value}`);
132
+ }
133
+ /**
134
+ * Whether the token is a conditional token.
135
+ * Conditional tokens are tokens that have multiple values based on a condition.
136
+ */
137
+ get isConditional() {
138
+ return !!this.extensions?.conditions;
139
+ }
140
+ /**
141
+ * Whether the token has a reference in its value.
142
+ * e.g. {color.gray.100}
143
+ */
144
+ get hasReference() {
145
+ return !!this.extensions?.references;
146
+ }
147
+ /**
148
+ * Whether the token is a complex or composite token.
149
+ */
150
+ get isComposite() {
151
+ return isCompositeTokenValue(this.originalValue);
152
+ }
153
+ /**
154
+ * Returns the token value with the references expanded.
155
+ * e.g. {color.gray.100} => var(--colors-gray-100)
156
+ *
157
+ */
158
+ expandReferences() {
159
+ if (!this.hasReference) return this.extensions.varRef ?? this.value;
160
+ const references = this.extensions.references ?? {};
161
+ this.value = Object.keys(references).reduce((valueStr, key) => {
162
+ const referenceToken = references[key];
163
+ if (referenceToken.isConditional) return valueStr;
164
+ const value = referenceToken.expandReferences();
165
+ return valueStr.replaceAll(`{${key}}`, value);
166
+ }, this.value);
167
+ delete this.extensions.references;
168
+ return this.value;
169
+ }
170
+ /**
171
+ * Whether this token has a reference to another token
172
+ */
173
+ get isReference() {
174
+ return hasReference(this.originalValue);
175
+ }
176
+ /**
177
+ * Returns the list of references in the token value
178
+ */
179
+ get references() {
180
+ return getReferences(this.originalValue);
181
+ }
182
+ clone() {
183
+ return new Token({
184
+ name: this.name,
185
+ value: this.value,
186
+ type: this.type,
187
+ path: [...this.path],
188
+ description: this.description,
189
+ extensions: cloneDeep(this.extensions)
190
+ });
191
+ }
192
+ /**
193
+ * Returns an array of tokens per conditions.
194
+ * It is commonly used in semantic tokens, and can have multiple values based on a condition.
195
+ * e.g. primary: { light: '#000', dark: '#fff' }
196
+ */
197
+ getConditionTokens() {
198
+ if (!this.isConditional) return;
199
+ const conditions = this.extensions.conditions ?? {};
200
+ const conditionalTokens = [];
201
+ walkObject(conditions, (value, path) => {
202
+ const newPath = path.filter((v) => !isBaseCondition(v));
203
+ if (!newPath.length) return;
204
+ const token = this.clone();
205
+ token.value = value;
206
+ token.extensions.condition = newPath.join(":");
207
+ conditionalTokens.push(token);
208
+ });
209
+ return conditionalTokens;
210
+ }
211
+ /**
212
+ * Add more extensions to the token
213
+ */
214
+ setExtensions(extensions) {
215
+ this.extensions = {
216
+ ...this.extensions,
217
+ ...extensions
218
+ };
219
+ this.setType();
220
+ return this;
221
+ }
222
+ setType() {
223
+ if (this.type) return;
224
+ if (this.extensions.category) this.type = TOKEN_TYPES[this.extensions.category];
225
+ }
247
226
  };
248
227
  function cloneDeep(value) {
249
- if (value instanceof Token) {
250
- return value.clone();
251
- }
252
- if (Array.isArray(value)) {
253
- return value.map((child) => cloneDeep(child));
254
- }
255
- if (typeof value === "object" && value !== null) {
256
- return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, cloneDeep(v)]));
257
- }
258
- return value;
228
+ if (value instanceof Token) return value.clone();
229
+ if (Array.isArray(value)) return value.map((child) => cloneDeep(child));
230
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, cloneDeep(v)]));
231
+ return value;
259
232
  }
260
- var TOKEN_TYPES = {
261
- colors: "color",
262
- spacing: "dimension",
263
- sizes: "dimension",
264
- shadows: "shadow",
265
- fonts: "fontFamily",
266
- fontSizes: "fontSize",
267
- fontWeights: "fontWeight",
268
- letterSpacings: "letterSpacing",
269
- lineHeights: "lineHeight",
270
- durations: "duration",
271
- transitions: "transition",
272
- radii: "borderRadius",
273
- gradients: "gradient",
274
- easings: "cubicBezier",
275
- borders: "border",
276
- borderWidths: "borderWidth",
277
- zIndex: "zIndex",
278
- opacity: "opacity",
279
- blurs: "blur",
280
- aspectRatios: "aspectRatio",
281
- cursor: "cursor",
282
- assets: "asset"
283
- };
284
- var TOKEN_CATEGORIES = Object.keys(TOKEN_TYPES);
285
-
286
- // src/middleware.ts
287
- var addNegativeTokens = {
288
- enforce: "pre",
289
- transform(dictionary) {
290
- const { prefix, hash } = dictionary;
291
- const tokens = dictionary.filter({
292
- extensions: { category: "spacing" }
293
- });
294
- tokens.forEach((token) => {
295
- const originalPath = [...token.path];
296
- const originalVar = dictionary.formatCssVar(originalPath, { prefix, hash });
297
- if (token.value === "0rem") {
298
- return;
299
- }
300
- const node = token.clone();
301
- node.setExtensions({
302
- isNegative: true,
303
- prop: `-${token.extensions.prop}`,
304
- originalPath
305
- });
306
- node.value = calc.negate(originalVar);
307
- const last = node.path.at(-1);
308
- if (last != null) {
309
- node.path[node.path.length - 1] = `-${last}`;
310
- }
311
- if (node.path) {
312
- node.name = dictionary.formatTokenName(node.path);
313
- }
314
- dictionary.registerToken(node);
315
- });
316
- }
317
- };
318
- var units = /* @__PURE__ */ new Set(["spacing", "sizes", "borderWidths", "fontSizes", "radii"]);
319
- var addPixelUnit = {
320
- enforce: "post",
321
- transform(dictionary) {
322
- const tokens = dictionary.filter((token) => {
323
- return units.has(token.extensions.category) && !token.extensions.isNegative;
324
- });
325
- tokens.forEach((token) => {
326
- token.setExtensions({
327
- pixelValue: toPx(token.value)
328
- });
329
- });
330
- }
233
+ const TOKEN_TYPES = {
234
+ colors: "color",
235
+ spacing: "dimension",
236
+ sizes: "dimension",
237
+ shadows: "shadow",
238
+ fonts: "fontFamily",
239
+ fontSizes: "fontSize",
240
+ fontWeights: "fontWeight",
241
+ letterSpacings: "letterSpacing",
242
+ lineHeights: "lineHeight",
243
+ durations: "duration",
244
+ transitions: "transition",
245
+ radii: "borderRadius",
246
+ gradients: "gradient",
247
+ easings: "cubicBezier",
248
+ borders: "border",
249
+ borderWidths: "borderWidth",
250
+ zIndex: "zIndex",
251
+ opacity: "opacity",
252
+ blurs: "blur",
253
+ aspectRatios: "aspectRatio",
254
+ cursor: "cursor",
255
+ assets: "asset"
331
256
  };
332
- var addVirtualPalette = {
333
- enforce: "post",
334
- transform(dictionary) {
335
- const colorPaletteConfig = dictionary.colorPalette;
336
- const enabled = colorPaletteConfig?.enabled ?? true;
337
- if (!enabled) return;
338
- const tokens = dictionary.filter({ extensions: { category: "colors" } });
339
- const keys = /* @__PURE__ */ new Map();
340
- const colorPalettes = /* @__PURE__ */ new Map();
341
- tokens.forEach((token) => {
342
- const { colorPalette, colorPaletteRoots, colorPaletteTokenKeys } = token.extensions;
343
- if (!colorPalette) return;
344
- colorPaletteTokenKeys.forEach((keyPath) => {
345
- keys.set(dictionary.formatTokenName(keyPath), keyPath);
346
- });
347
- colorPaletteRoots.forEach((colorPaletteRoot) => {
348
- const formated = dictionary.formatTokenName(colorPaletteRoot);
349
- const colorPaletteList = colorPalettes.get(formated) || [];
350
- colorPaletteList.push(token);
351
- colorPalettes.set(formated, colorPaletteList);
352
- if (token.extensions.isDefault && colorPaletteRoot.length === 1) {
353
- const keyPath = colorPaletteTokenKeys[0]?.filter(Boolean);
354
- if (!keyPath.length) return;
355
- const path = colorPaletteRoot.concat(keyPath);
356
- keys.set(dictionary.formatTokenName(path), []);
357
- }
358
- });
359
- });
360
- keys.forEach((segments) => {
361
- const node = new Token({
362
- name: dictionary.formatTokenName(["colors", "colorPalette", ...segments].filter(Boolean)),
363
- value: dictionary.formatTokenName(["colors", "colorPalette", ...segments].filter(Boolean)),
364
- path: ["colors", "colorPalette", ...segments]
365
- });
366
- node.setExtensions({
367
- category: "colors",
368
- prop: dictionary.formatTokenName(["colorPalette", ...segments].filter(Boolean)),
369
- isVirtual: true
370
- });
371
- dictionary.registerToken(node, "pre");
372
- });
373
- }
257
+ const TOKEN_CATEGORIES = Object.keys(TOKEN_TYPES);
258
+ //#endregion
259
+ //#region src/middleware.ts
260
+ const addNegativeTokens = {
261
+ enforce: "pre",
262
+ transform(dictionary) {
263
+ const { prefix, hash } = dictionary;
264
+ dictionary.filter({ extensions: { category: "spacing" } }).forEach((token) => {
265
+ const originalPath = [...token.path];
266
+ const originalVar = dictionary.formatCssVar(originalPath, {
267
+ prefix,
268
+ hash
269
+ });
270
+ if (token.value === "0rem") return;
271
+ const node = token.clone();
272
+ node.setExtensions({
273
+ isNegative: true,
274
+ prop: `-${token.extensions.prop}`,
275
+ originalPath
276
+ });
277
+ node.value = calc.negate(originalVar);
278
+ const last = node.path.at(-1);
279
+ if (last != null) node.path[node.path.length - 1] = `-${last}`;
280
+ if (node.path) node.name = dictionary.formatTokenName(node.path);
281
+ dictionary.registerToken(node);
282
+ });
283
+ }
374
284
  };
375
- var removeEmptyTokens = {
376
- enforce: "post",
377
- transform(dictionary) {
378
- dictionary.allTokens = dictionary.allTokens.filter((token) => token.value !== "");
379
- }
380
- };
381
- var middlewares = [addNegativeTokens, addVirtualPalette, removeEmptyTokens, addPixelUnit];
382
-
383
- // src/transform.ts
384
- import { isCssUnit, isString, BambooError as BambooError2 } from "@bamboocss/shared";
385
- import picomatch from "picomatch";
386
- import { P as P2, match } from "ts-pattern";
387
-
388
- // src/mini-svg-uri.ts
389
- var shorterNames = {
390
- aqua: /#00ffff(ff)?(?!\w)|#0ff(f)?(?!\w)/gi,
391
- azure: /#f0ffff(ff)?(?!\w)/gi,
392
- beige: /#f5f5dc(ff)?(?!\w)/gi,
393
- bisque: /#ffe4c4(ff)?(?!\w)/gi,
394
- black: /#000000(ff)?(?!\w)|#000(f)?(?!\w)/gi,
395
- blue: /#0000ff(ff)?(?!\w)|#00f(f)?(?!\w)/gi,
396
- brown: /#a52a2a(ff)?(?!\w)/gi,
397
- coral: /#ff7f50(ff)?(?!\w)/gi,
398
- cornsilk: /#fff8dc(ff)?(?!\w)/gi,
399
- crimson: /#dc143c(ff)?(?!\w)/gi,
400
- cyan: /#00ffff(ff)?(?!\w)|#0ff(f)?(?!\w)/gi,
401
- darkblue: /#00008b(ff)?(?!\w)/gi,
402
- darkcyan: /#008b8b(ff)?(?!\w)/gi,
403
- darkgrey: /#a9a9a9(ff)?(?!\w)/gi,
404
- darkred: /#8b0000(ff)?(?!\w)/gi,
405
- deeppink: /#ff1493(ff)?(?!\w)/gi,
406
- dimgrey: /#696969(ff)?(?!\w)/gi,
407
- gold: /#ffd700(ff)?(?!\w)/gi,
408
- green: /#008000(ff)?(?!\w)/gi,
409
- grey: /#808080(ff)?(?!\w)/gi,
410
- honeydew: /#f0fff0(ff)?(?!\w)/gi,
411
- hotpink: /#ff69b4(ff)?(?!\w)/gi,
412
- indigo: /#4b0082(ff)?(?!\w)/gi,
413
- ivory: /#fffff0(ff)?(?!\w)/gi,
414
- khaki: /#f0e68c(ff)?(?!\w)/gi,
415
- lavender: /#e6e6fa(ff)?(?!\w)/gi,
416
- lime: /#00ff00(ff)?(?!\w)|#0f0(f)?(?!\w)/gi,
417
- linen: /#faf0e6(ff)?(?!\w)/gi,
418
- maroon: /#800000(ff)?(?!\w)/gi,
419
- moccasin: /#ffe4b5(ff)?(?!\w)/gi,
420
- navy: /#000080(ff)?(?!\w)/gi,
421
- oldlace: /#fdf5e6(ff)?(?!\w)/gi,
422
- olive: /#808000(ff)?(?!\w)/gi,
423
- orange: /#ffa500(ff)?(?!\w)/gi,
424
- orchid: /#da70d6(ff)?(?!\w)/gi,
425
- peru: /#cd853f(ff)?(?!\w)/gi,
426
- pink: /#ffc0cb(ff)?(?!\w)/gi,
427
- plum: /#dda0dd(ff)?(?!\w)/gi,
428
- purple: /#800080(ff)?(?!\w)/gi,
429
- red: /#ff0000(ff)?(?!\w)|#f00(f)?(?!\w)/gi,
430
- salmon: /#fa8072(ff)?(?!\w)/gi,
431
- seagreen: /#2e8b57(ff)?(?!\w)/gi,
432
- seashell: /#fff5ee(ff)?(?!\w)/gi,
433
- sienna: /#a0522d(ff)?(?!\w)/gi,
434
- silver: /#c0c0c0(ff)?(?!\w)/gi,
435
- skyblue: /#87ceeb(ff)?(?!\w)/gi,
436
- snow: /#fffafa(ff)?(?!\w)/gi,
437
- tan: /#d2b48c(ff)?(?!\w)/gi,
438
- teal: /#008080(ff)?(?!\w)/gi,
439
- thistle: /#d8bfd8(ff)?(?!\w)/gi,
440
- tomato: /#ff6347(ff)?(?!\w)/gi,
441
- violet: /#ee82ee(ff)?(?!\w)/gi,
442
- wheat: /#f5deb3(ff)?(?!\w)/gi,
443
- white: /#ffffff(ff)?(?!\w)|#fff(f)?(?!\w)/gi
285
+ const units = new Set([
286
+ "spacing",
287
+ "sizes",
288
+ "borderWidths",
289
+ "fontSizes",
290
+ "radii"
291
+ ]);
292
+ const middlewares = [
293
+ addNegativeTokens,
294
+ {
295
+ enforce: "post",
296
+ transform(dictionary) {
297
+ if (!(dictionary.colorPalette?.enabled ?? true)) return;
298
+ const tokens = dictionary.filter({ extensions: { category: "colors" } });
299
+ const keys = /* @__PURE__ */ new Map();
300
+ const colorPalettes = /* @__PURE__ */ new Map();
301
+ tokens.forEach((token) => {
302
+ const { colorPalette, colorPaletteRoots, colorPaletteTokenKeys } = token.extensions;
303
+ if (!colorPalette) return;
304
+ colorPaletteTokenKeys.forEach((keyPath) => {
305
+ keys.set(dictionary.formatTokenName(keyPath), keyPath);
306
+ });
307
+ /**
308
+ * Assign nested tokens to their respective color palette list.
309
+ *
310
+ * Iteration 1:
311
+ * If `colorPaletteRoots` is this array ['button']
312
+ * and the token name is 'colors.button.light' it will be added to the 'button' color palette list.
313
+ * ```
314
+ * const colorPalettes = {
315
+ * 'button': ['colors.button.light'],
316
+ * }
317
+ *
318
+ * Itteration 2:
319
+ * If `colorPaletteRoots` is this array ['button', 'button.light']
320
+ * and the token name is 'colors.button.light.accent' it will be added to the 'button' and 'button.light' color palette lists.
321
+ * ```
322
+ * const colorPalettes = {
323
+ * 'button': ['colors.button.light', 'colors.button.light.accent'],
324
+ * 'button.light': ['colors.button.light.accent'],
325
+ * }
326
+ *
327
+ * Itteration 3:
328
+ * If `colorPaletteRoots` is this array ['button', 'button.light', 'button.light.accent']
329
+ * and the token name is 'colors.button.light.accent.secondary' it will be added to the 'button', 'button.light' and 'button.light.accent' color palette lists.
330
+ * ```
331
+ * const colorPalettes = {
332
+ * 'button': ['colors.button.light', 'colors.button.light.accent', 'colors.button.light.accent.secondary'],
333
+ * 'button.light': ['colors.button.light.accent', 'colors.button.light.accent.secondary'],
334
+ * 'button.light.accent': ['colors.button.light.accent.secondary'],
335
+ * }
336
+ */
337
+ colorPaletteRoots.forEach((colorPaletteRoot) => {
338
+ const formated = dictionary.formatTokenName(colorPaletteRoot);
339
+ const colorPaletteList = colorPalettes.get(formated) || [];
340
+ colorPaletteList.push(token);
341
+ colorPalettes.set(formated, colorPaletteList);
342
+ if (token.extensions.isDefault && colorPaletteRoot.length === 1) {
343
+ const keyPath = colorPaletteTokenKeys[0]?.filter(Boolean);
344
+ if (!keyPath.length) return;
345
+ const path = colorPaletteRoot.concat(keyPath);
346
+ keys.set(dictionary.formatTokenName(path), []);
347
+ }
348
+ });
349
+ });
350
+ keys.forEach((segments) => {
351
+ const node = new Token({
352
+ name: dictionary.formatTokenName([
353
+ "colors",
354
+ "colorPalette",
355
+ ...segments
356
+ ].filter(Boolean)),
357
+ value: dictionary.formatTokenName([
358
+ "colors",
359
+ "colorPalette",
360
+ ...segments
361
+ ].filter(Boolean)),
362
+ path: [
363
+ "colors",
364
+ "colorPalette",
365
+ ...segments
366
+ ]
367
+ });
368
+ node.setExtensions({
369
+ category: "colors",
370
+ prop: dictionary.formatTokenName(["colorPalette", ...segments].filter(Boolean)),
371
+ isVirtual: true
372
+ });
373
+ dictionary.registerToken(node, "pre");
374
+ });
375
+ }
376
+ },
377
+ {
378
+ enforce: "post",
379
+ transform(dictionary) {
380
+ dictionary.allTokens = dictionary.allTokens.filter((token) => token.value !== "");
381
+ }
382
+ },
383
+ {
384
+ enforce: "post",
385
+ transform(dictionary) {
386
+ dictionary.filter((token) => {
387
+ return units.has(token.extensions.category) && !token.extensions.isNegative;
388
+ }).forEach((token) => {
389
+ token.setExtensions({ pixelValue: toPx(token.value) });
390
+ });
391
+ }
392
+ }
393
+ ];
394
+ //#endregion
395
+ //#region src/mini-svg-uri.ts
396
+ const shorterNames = {
397
+ aqua: /#00ffff(ff)?(?!\w)|#0ff(f)?(?!\w)/gi,
398
+ azure: /#f0ffff(ff)?(?!\w)/gi,
399
+ beige: /#f5f5dc(ff)?(?!\w)/gi,
400
+ bisque: /#ffe4c4(ff)?(?!\w)/gi,
401
+ black: /#000000(ff)?(?!\w)|#000(f)?(?!\w)/gi,
402
+ blue: /#0000ff(ff)?(?!\w)|#00f(f)?(?!\w)/gi,
403
+ brown: /#a52a2a(ff)?(?!\w)/gi,
404
+ coral: /#ff7f50(ff)?(?!\w)/gi,
405
+ cornsilk: /#fff8dc(ff)?(?!\w)/gi,
406
+ crimson: /#dc143c(ff)?(?!\w)/gi,
407
+ cyan: /#00ffff(ff)?(?!\w)|#0ff(f)?(?!\w)/gi,
408
+ darkblue: /#00008b(ff)?(?!\w)/gi,
409
+ darkcyan: /#008b8b(ff)?(?!\w)/gi,
410
+ darkgrey: /#a9a9a9(ff)?(?!\w)/gi,
411
+ darkred: /#8b0000(ff)?(?!\w)/gi,
412
+ deeppink: /#ff1493(ff)?(?!\w)/gi,
413
+ dimgrey: /#696969(ff)?(?!\w)/gi,
414
+ gold: /#ffd700(ff)?(?!\w)/gi,
415
+ green: /#008000(ff)?(?!\w)/gi,
416
+ grey: /#808080(ff)?(?!\w)/gi,
417
+ honeydew: /#f0fff0(ff)?(?!\w)/gi,
418
+ hotpink: /#ff69b4(ff)?(?!\w)/gi,
419
+ indigo: /#4b0082(ff)?(?!\w)/gi,
420
+ ivory: /#fffff0(ff)?(?!\w)/gi,
421
+ khaki: /#f0e68c(ff)?(?!\w)/gi,
422
+ lavender: /#e6e6fa(ff)?(?!\w)/gi,
423
+ lime: /#00ff00(ff)?(?!\w)|#0f0(f)?(?!\w)/gi,
424
+ linen: /#faf0e6(ff)?(?!\w)/gi,
425
+ maroon: /#800000(ff)?(?!\w)/gi,
426
+ moccasin: /#ffe4b5(ff)?(?!\w)/gi,
427
+ navy: /#000080(ff)?(?!\w)/gi,
428
+ oldlace: /#fdf5e6(ff)?(?!\w)/gi,
429
+ olive: /#808000(ff)?(?!\w)/gi,
430
+ orange: /#ffa500(ff)?(?!\w)/gi,
431
+ orchid: /#da70d6(ff)?(?!\w)/gi,
432
+ peru: /#cd853f(ff)?(?!\w)/gi,
433
+ pink: /#ffc0cb(ff)?(?!\w)/gi,
434
+ plum: /#dda0dd(ff)?(?!\w)/gi,
435
+ purple: /#800080(ff)?(?!\w)/gi,
436
+ red: /#ff0000(ff)?(?!\w)|#f00(f)?(?!\w)/gi,
437
+ salmon: /#fa8072(ff)?(?!\w)/gi,
438
+ seagreen: /#2e8b57(ff)?(?!\w)/gi,
439
+ seashell: /#fff5ee(ff)?(?!\w)/gi,
440
+ sienna: /#a0522d(ff)?(?!\w)/gi,
441
+ silver: /#c0c0c0(ff)?(?!\w)/gi,
442
+ skyblue: /#87ceeb(ff)?(?!\w)/gi,
443
+ snow: /#fffafa(ff)?(?!\w)/gi,
444
+ tan: /#d2b48c(ff)?(?!\w)/gi,
445
+ teal: /#008080(ff)?(?!\w)/gi,
446
+ thistle: /#d8bfd8(ff)?(?!\w)/gi,
447
+ tomato: /#ff6347(ff)?(?!\w)/gi,
448
+ violet: /#ee82ee(ff)?(?!\w)/gi,
449
+ wheat: /#f5deb3(ff)?(?!\w)/gi,
450
+ white: /#ffffff(ff)?(?!\w)|#fff(f)?(?!\w)/gi
444
451
  };
445
- var REGEX = {
446
- whitespace: /\s+/g,
447
- urlHexPairs: /%[\dA-F]{2}/g,
448
- quotes: /"/g
452
+ const REGEX = {
453
+ whitespace: /\s+/g,
454
+ urlHexPairs: /%[\dA-F]{2}/g,
455
+ quotes: /"/g
449
456
  };
450
457
  function collapseWhitespace(str) {
451
- return str.trim().replace(REGEX.whitespace, " ");
458
+ return str.trim().replace(REGEX.whitespace, " ");
452
459
  }
453
460
  function dataURIPayload(string) {
454
- return encodeURIComponent(string).replace(REGEX.urlHexPairs, specialHexEncode);
461
+ return encodeURIComponent(string).replace(REGEX.urlHexPairs, specialHexEncode);
455
462
  }
456
463
  function colorCodeToShorterNames(string) {
457
- objectKeys(shorterNames).forEach((key) => {
458
- if (shorterNames[key].test(string)) {
459
- string = string.replace(shorterNames[key], key);
460
- }
461
- });
462
- return string;
464
+ objectKeys(shorterNames).forEach((key) => {
465
+ if (shorterNames[key].test(string)) string = string.replace(shorterNames[key], key);
466
+ });
467
+ return string;
463
468
  }
464
- function specialHexEncode(match3) {
465
- switch (match3) {
466
- case "%20":
467
- return " ";
468
- case "%3D":
469
- return "=";
470
- case "%3A":
471
- return ":";
472
- case "%2F":
473
- return "/";
474
- default:
475
- return match3.toLowerCase();
476
- }
469
+ function specialHexEncode(match) {
470
+ switch (match) {
471
+ case "%20": return " ";
472
+ case "%3D": return "=";
473
+ case "%3A": return ":";
474
+ case "%2F": return "/";
475
+ default: return match.toLowerCase();
476
+ }
477
477
  }
478
478
  function svgToDataUri(svgString) {
479
- if (typeof svgString !== "string") {
480
- throw new TypeError("Expected a string, but received " + typeof svgString);
481
- }
482
- if (svgString.charCodeAt(0) === 65279) {
483
- svgString = svgString.slice(1);
484
- }
485
- const body = colorCodeToShorterNames(collapseWhitespace(svgString)).replace(REGEX.quotes, "'");
486
- return "data:image/svg+xml," + dataURIPayload(body);
479
+ if (typeof svgString !== "string") throw new TypeError("Expected a string, but received " + typeof svgString);
480
+ if (svgString.charCodeAt(0) === 65279) svgString = svgString.slice(1);
481
+ return "data:image/svg+xml," + dataURIPayload(colorCodeToShorterNames(collapseWhitespace(svgString)).replace(REGEX.quotes, "'"));
487
482
  }
488
- var objectKeys = (obj) => Object.keys(obj);
489
-
490
- // src/transform.ts
483
+ const objectKeys = (obj) => Object.keys(obj);
484
+ //#endregion
485
+ //#region src/transform.ts
491
486
  function toUnit(v) {
492
- return isCssUnit(v) || hasReference(v.toString()) ? v : `${v}px`;
487
+ return isCssUnit(v) || hasReference(v.toString()) ? v : `${v}px`;
493
488
  }
494
489
  function px(v) {
495
- return isString(v) ? v : `${v}px`;
490
+ return isString(v) ? v : `${v}px`;
496
491
  }
497
- var transformShadow = {
498
- name: "tokens/shadow",
499
- match: (token) => token.extensions.category === "shadows",
500
- transform(token, dict) {
501
- if (isString(token.value)) {
502
- return token.value;
503
- }
504
- if (Array.isArray(token.value)) {
505
- return token.value.map((value) => this.transform({ value }, dict)).join(", ");
506
- }
507
- if (isCompositeShadow(token.value)) {
508
- const { offsetX, offsetY, blur, spread, color, inset } = token.value;
509
- return [inset ? "inset " : "", px(offsetX), px(offsetY), px(blur), px(spread), color].filter(Boolean).join(" ");
510
- }
511
- return token.value;
512
- }
513
- };
514
- var transformGradient = {
515
- name: "tokens/gradient",
516
- match: (token) => token.extensions.category === "gradients",
517
- transform(token) {
518
- if (isString(token.value)) {
519
- return token.value;
520
- }
521
- if (isCompositeGradient(token.value)) {
522
- const { type, stops, placement } = token.value;
523
- const rawStops = stops.map((stop) => {
524
- if (isString(stop)) return stop;
525
- const { color, position } = stop;
526
- return `${color} ${position}px`;
527
- });
528
- return `${type}-gradient(${placement}, ${rawStops.join(", ")})`;
529
- }
530
- return token.value;
531
- }
532
- };
533
- var transformFonts = {
534
- name: "tokens/fonts",
535
- match: (token) => token.extensions.category === "fonts",
536
- transform(token) {
537
- if (Array.isArray(token.value)) {
538
- return token.value.join(", ");
539
- }
540
- return token.value;
541
- }
542
- };
543
- var transformEasings = {
544
- name: "tokens/easings",
545
- match: (token) => token.extensions.category === "easings",
546
- transform(token) {
547
- if (isString(token.value)) {
548
- return token.value;
549
- }
550
- if (Array.isArray(token.value)) {
551
- return `cubic-bezier(${token.value.join(", ")})`;
552
- }
553
- return token.value;
554
- }
555
- };
556
- var transformBorders = {
557
- name: "tokens/borders",
558
- match: (token) => token.extensions.category === "borders",
559
- transform(token) {
560
- if (isString(token.value)) {
561
- return token.value;
562
- }
563
- if (isCompositeBorder(token.value)) {
564
- const { width, style, color } = token.value;
565
- return `${toUnit(width)} ${style} ${color}`;
566
- }
567
- return token.value;
568
- }
569
- };
570
- var transformAssets = {
571
- name: "tokens/assets",
572
- match: (token) => token.extensions.category === "assets",
573
- transform(token) {
574
- const raw = token.value;
575
- return match(raw).with(P2.string, (value) => value).with({ type: "url" }, ({ value }) => `url("${value}")`).with({ type: "svg" }, ({ value }) => `url("${svgToDataUri(value)}")`).exhaustive();
576
- }
577
- };
578
- var transformColorMix = {
579
- name: "tokens/color-mix",
580
- match: (token) => {
581
- return token.extensions.category === "colors" && token.value.includes("/");
582
- },
583
- transform(token, dict) {
584
- if (!token.value.includes("/")) return token;
585
- return expandReferences(token.value, (path) => {
586
- const tokenFn = (tokenPath) => {
587
- const token2 = dict.getByName(tokenPath);
588
- return token2?.extensions.varRef;
589
- };
590
- const mix = dict.colorMix(path, tokenFn);
591
- if (mix.invalid) {
592
- throw new BambooError2("INVALID_TOKEN", "Invalid color mix at " + path + ": " + mix.value);
593
- }
594
- return mix.value;
595
- });
596
- }
597
- };
598
- var addCssVariables = {
599
- type: "extensions",
600
- name: "tokens/css-var",
601
- transform(token, dictionary) {
602
- const { prefix, hash } = dictionary;
603
- const { isNegative, originalPath } = token.extensions;
604
- const pathValue = isNegative ? originalPath : token.path;
605
- const variable = dictionary.formatCssVar(pathValue.filter(Boolean), { prefix, hash });
606
- return {
607
- var: variable.var,
608
- varRef: variable.ref
609
- };
610
- }
611
- };
612
- var addConditionalCssVariables = {
613
- enforce: "post",
614
- name: "tokens/conditionals",
615
- transform(token, dictionary) {
616
- const { prefix, hash } = dictionary;
617
- const refs = getReferences(token.value);
618
- if (!refs.length) return token.value;
619
- const modifier = refs.some((ref) => ref.includes("/"));
620
- if (!modifier) {
621
- refs.forEach((ref) => {
622
- const variable = dictionary.formatCssVar(ref.split("."), { prefix, hash }).ref;
623
- token.value = token.value.replaceAll(`{${ref}}`, variable);
624
- });
625
- } else {
626
- const tokenFn = (name) => {
627
- const token2 = dictionary.getByName(name);
628
- return token2?.extensions.varRef;
629
- };
630
- token.value = expandReferences(token.value, (path) => {
631
- const mix = dictionary.colorMix(path, tokenFn);
632
- if (mix.invalid) {
633
- throw new BambooError2("INVALID_TOKEN", "Invalid color mix at " + path + ": " + mix.value);
634
- }
635
- return mix.value;
636
- });
637
- }
638
- return token.value;
639
- }
640
- };
641
- var addColorPalette = {
642
- type: "extensions",
643
- name: "tokens/colors/colorPalette",
644
- match(token) {
645
- return token.extensions.category === "colors" && !token.extensions.isVirtual;
646
- },
647
- transform(token, dict) {
648
- const colorPaletteConfig = dict.colorPalette;
649
- const enabled = colorPaletteConfig?.enabled ?? true;
650
- const include = colorPaletteConfig?.include;
651
- const exclude = colorPaletteConfig?.exclude;
652
- if (!enabled) return {};
653
- let colorPath = token.path.slice(1, -1);
654
- if (colorPath.length === 0) {
655
- colorPath = token.path.slice(1);
656
- if (colorPath.length === 0) {
657
- return {};
658
- }
659
- }
660
- const colorPathString = colorPath.join(".");
661
- if (exclude?.length) {
662
- const excludeMatchers = exclude.map((pattern) => picomatch(pattern));
663
- if (excludeMatchers.some((matcher) => matcher(colorPathString))) {
664
- return {};
665
- }
666
- }
667
- if (include?.length) {
668
- const includeMatchers = include.map((pattern) => picomatch(pattern));
669
- if (!includeMatchers.some((matcher) => matcher(colorPathString))) {
670
- return {};
671
- }
672
- }
673
- const colorPaletteRoots = [];
674
- for (let i = 0; i < colorPath.length; i++) {
675
- colorPaletteRoots.push(colorPath.slice(0, i + 1));
676
- }
677
- const colorPaletteRoot = colorPath[0];
678
- const colorPalette = dict.formatTokenName(colorPath);
679
- const startIndex = token.path.indexOf(colorPaletteRoot) + 1;
680
- const remainingPath = token.path.slice(startIndex);
681
- const colorPaletteTokenKeys = [];
682
- for (let i = 0; i < remainingPath.length; i++) {
683
- colorPaletteTokenKeys.push(remainingPath.slice(i));
684
- }
685
- if (colorPaletteTokenKeys.length === 0) {
686
- colorPaletteTokenKeys.push([""]);
687
- }
688
- return {
689
- colorPalette,
690
- colorPaletteRoots,
691
- colorPaletteTokenKeys
692
- };
693
- }
694
- };
695
- var transforms = [
696
- transformShadow,
697
- transformGradient,
698
- transformFonts,
699
- transformEasings,
700
- transformBorders,
701
- transformAssets,
702
- addCssVariables,
703
- transformColorMix,
704
- // depends on `addCssVariables`
705
- addConditionalCssVariables,
706
- addColorPalette
492
+ const transforms = [
493
+ {
494
+ name: "tokens/shadow",
495
+ match: (token) => token.extensions.category === "shadows",
496
+ transform(token, dict) {
497
+ if (isString(token.value)) return token.value;
498
+ if (Array.isArray(token.value)) return token.value.map((value) => this.transform({ value }, dict)).join(", ");
499
+ if (isCompositeShadow(token.value)) {
500
+ const { offsetX, offsetY, blur, spread, color, inset } = token.value;
501
+ return [
502
+ inset ? "inset " : "",
503
+ px(offsetX),
504
+ px(offsetY),
505
+ px(blur),
506
+ px(spread),
507
+ color
508
+ ].filter(Boolean).join(" ");
509
+ }
510
+ return token.value;
511
+ }
512
+ },
513
+ {
514
+ name: "tokens/gradient",
515
+ match: (token) => token.extensions.category === "gradients",
516
+ transform(token) {
517
+ if (isString(token.value)) return token.value;
518
+ if (isCompositeGradient(token.value)) {
519
+ const { type, stops, placement } = token.value;
520
+ return `${type}-gradient(${placement}, ${stops.map((stop) => {
521
+ if (isString(stop)) return stop;
522
+ const { color, position } = stop;
523
+ return `${color} ${position}px`;
524
+ }).join(", ")})`;
525
+ }
526
+ return token.value;
527
+ }
528
+ },
529
+ {
530
+ name: "tokens/fonts",
531
+ match: (token) => token.extensions.category === "fonts",
532
+ transform(token) {
533
+ if (Array.isArray(token.value)) return token.value.join(", ");
534
+ return token.value;
535
+ }
536
+ },
537
+ {
538
+ name: "tokens/easings",
539
+ match: (token) => token.extensions.category === "easings",
540
+ transform(token) {
541
+ if (isString(token.value)) return token.value;
542
+ if (Array.isArray(token.value)) return `cubic-bezier(${token.value.join(", ")})`;
543
+ return token.value;
544
+ }
545
+ },
546
+ {
547
+ name: "tokens/borders",
548
+ match: (token) => token.extensions.category === "borders",
549
+ transform(token) {
550
+ if (isString(token.value)) return token.value;
551
+ if (isCompositeBorder(token.value)) {
552
+ const { width, style, color } = token.value;
553
+ return `${toUnit(width)} ${style} ${color}`;
554
+ }
555
+ return token.value;
556
+ }
557
+ },
558
+ {
559
+ name: "tokens/assets",
560
+ match: (token) => token.extensions.category === "assets",
561
+ transform(token) {
562
+ const raw = token.value;
563
+ return match(raw).with(P.string, (value) => value).with({ type: "url" }, ({ value }) => `url("${value}")`).with({ type: "svg" }, ({ value }) => `url("${svgToDataUri(value)}")`).exhaustive();
564
+ }
565
+ },
566
+ {
567
+ type: "extensions",
568
+ name: "tokens/css-var",
569
+ transform(token, dictionary) {
570
+ const { prefix, hash } = dictionary;
571
+ const { isNegative, originalPath } = token.extensions;
572
+ const pathValue = isNegative ? originalPath : token.path;
573
+ const variable = dictionary.formatCssVar(pathValue.filter(Boolean), {
574
+ prefix,
575
+ hash
576
+ });
577
+ return {
578
+ var: variable.var,
579
+ varRef: variable.ref
580
+ };
581
+ }
582
+ },
583
+ {
584
+ name: "tokens/color-mix",
585
+ match: (token) => {
586
+ return token.extensions.category === "colors" && token.value.includes("/");
587
+ },
588
+ transform(token, dict) {
589
+ if (!token.value.includes("/")) return token;
590
+ return expandReferences(token.value, (path) => {
591
+ const tokenFn = (tokenPath) => {
592
+ return dict.getByName(tokenPath)?.extensions.varRef;
593
+ };
594
+ const mix = dict.colorMix(path, tokenFn);
595
+ if (mix.invalid) throw new BambooError("INVALID_TOKEN", "Invalid color mix at " + path + ": " + mix.value);
596
+ return mix.value;
597
+ });
598
+ }
599
+ },
600
+ {
601
+ enforce: "post",
602
+ name: "tokens/conditionals",
603
+ transform(token, dictionary) {
604
+ const { prefix, hash } = dictionary;
605
+ const refs = getReferences(token.value);
606
+ if (!refs.length) return token.value;
607
+ if (!refs.some((ref) => ref.includes("/"))) refs.forEach((ref) => {
608
+ const variable = dictionary.formatCssVar(ref.split("."), {
609
+ prefix,
610
+ hash
611
+ }).ref;
612
+ token.value = token.value.replaceAll(`{${ref}}`, variable);
613
+ });
614
+ else {
615
+ const tokenFn = (name) => {
616
+ return dictionary.getByName(name)?.extensions.varRef;
617
+ };
618
+ token.value = expandReferences(token.value, (path) => {
619
+ const mix = dictionary.colorMix(path, tokenFn);
620
+ if (mix.invalid) throw new BambooError("INVALID_TOKEN", "Invalid color mix at " + path + ": " + mix.value);
621
+ return mix.value;
622
+ });
623
+ }
624
+ return token.value;
625
+ }
626
+ },
627
+ {
628
+ type: "extensions",
629
+ name: "tokens/colors/colorPalette",
630
+ match(token) {
631
+ return token.extensions.category === "colors" && !token.extensions.isVirtual;
632
+ },
633
+ transform(token, dict) {
634
+ const colorPaletteConfig = dict.colorPalette;
635
+ const enabled = colorPaletteConfig?.enabled ?? true;
636
+ const include = colorPaletteConfig?.include;
637
+ const exclude = colorPaletteConfig?.exclude;
638
+ if (!enabled) return {};
639
+ let colorPath = token.path.slice(1, -1);
640
+ if (colorPath.length === 0) {
641
+ colorPath = token.path.slice(1);
642
+ if (colorPath.length === 0) return {};
643
+ }
644
+ const colorPathString = colorPath.join(".");
645
+ if (exclude?.length) {
646
+ if (exclude.map((pattern) => picomatch(pattern)).some((matcher) => matcher(colorPathString))) return {};
647
+ }
648
+ if (include?.length) {
649
+ if (!include.map((pattern) => picomatch(pattern)).some((matcher) => matcher(colorPathString))) return {};
650
+ }
651
+ /**
652
+ * Generate all possible color palette roots from the color path.
653
+ *
654
+ * For ['button', 'light', 'accent']:
655
+ * - ['button']
656
+ * - ['button', 'light']
657
+ * - ['button', 'light', 'accent']
658
+ *
659
+ * These represent all possible values you can pass to the css `colorPalette` property.
660
+ */
661
+ const colorPaletteRoots = [];
662
+ for (let i = 0; i < colorPath.length; i++) colorPaletteRoots.push(colorPath.slice(0, i + 1));
663
+ const colorPaletteRoot = colorPath[0];
664
+ const colorPalette = dict.formatTokenName(colorPath);
665
+ /**
666
+ * If this is the nested color palette:
667
+ * ```json
668
+ * {
669
+ * "colors": {
670
+ * "button": {
671
+ * "light": {
672
+ * "accent": {
673
+ * "secondary": {
674
+ * value: 'blue',
675
+ * },
676
+ * },
677
+ * },
678
+ * },
679
+ * },
680
+ * },
681
+ * ```
682
+ *
683
+ * The `colorPaletteTokenKeys` will be `['light.accent.secondary', 'accent.secondary', 'secondary']`
684
+ * It is used by the `addVirtualPalette` middleware to build the virtual `colorPalette` token for each color pattern root.
685
+ *
686
+ * Examples:
687
+ *
688
+ * If the `colorPalette` is `button` then the virtual token will be `colorPalette.light.accent.secondary`.
689
+ * ```jsx
690
+ * <button
691
+ * className={css({
692
+ * colorPalette: 'button',
693
+ * color: 'colorPalette.light.accent.secondary',
694
+ * })}
695
+ * />
696
+ * ```
697
+ *
698
+ * If the `colorPalette` is `button.light` then the virtual token will be `colorPalette.accent.secondary`.
699
+ * ```jsx
700
+ * <button
701
+ * className={css({
702
+ * colorPalette: 'button.light',
703
+ * color: 'colorPalette.accent.secondary',
704
+ * })}
705
+ * />
706
+ * ```
707
+ *
708
+ * If the `colorPalette` is `button.light.accent` then the virtual token will be `colorPalette.secondary`.
709
+ * ```jsx
710
+ * <button
711
+ * className={css({
712
+ * colorPalette: 'button.light.accent',
713
+ * color: 'colorPalette.secondary',
714
+ * })}
715
+ * />
716
+ */
717
+ const startIndex = token.path.indexOf(colorPaletteRoot) + 1;
718
+ const remainingPath = token.path.slice(startIndex);
719
+ const colorPaletteTokenKeys = [];
720
+ for (let i = 0; i < remainingPath.length; i++) colorPaletteTokenKeys.push(remainingPath.slice(i));
721
+ if (colorPaletteTokenKeys.length === 0) colorPaletteTokenKeys.push([""]);
722
+ return {
723
+ colorPalette,
724
+ colorPaletteRoots,
725
+ colorPaletteTokenKeys
726
+ };
727
+ }
728
+ }
707
729
  ];
708
-
709
- // src/expand-token-references.ts
710
- import { esc as esc2 } from "@bamboocss/shared";
711
- var expandTokenReferences = (str, resolve) => {
712
- let expanded = "";
713
- let index = 0;
714
- let state = "char";
715
- let tokenPath = "";
716
- let fallback = "";
717
- const currentStates = [];
718
- while (index < str.length) {
719
- const char = str[index];
720
- if (char === "{") {
721
- const endIndex = str.indexOf("}", index);
722
- if (endIndex === -1) {
723
- break;
724
- }
725
- const path = str.slice(index + 1, endIndex);
726
- const resolved = resolve(path);
727
- expanded += resolved ?? path;
728
- index = endIndex + 1;
729
- continue;
730
- }
731
- if (state === "token") {
732
- if (char === ",") {
733
- if (str[index] === "") {
734
- index++;
735
- }
736
- state = "fallback";
737
- currentStates.push(state);
738
- const resolved = resolve(tokenPath);
739
- if (resolved?.endsWith(")")) {
740
- expanded += resolved.slice(0, -1);
741
- }
742
- tokenPath = "";
743
- fallback = "";
744
- continue;
745
- }
746
- }
747
- if (state === "fallback") {
748
- const nextFallback = fallback + char;
749
- if (nextFallback === ", var(") {
750
- const innerEndIndex = cssVarParser(str.slice(index + 1));
751
- const endIndex = innerEndIndex + index + 1;
752
- const cssVar2 = str.slice(index + 1, endIndex);
753
- if (endIndex === -1) {
754
- break;
755
- }
756
- expanded += ", var(" + cssVar2 + ")";
757
- index = endIndex + 1;
758
- state = currentStates.pop() ?? state;
759
- fallback = "";
760
- continue;
761
- }
762
- }
763
- if (state === "token" || state === "fallback") {
764
- index++;
765
- if (char === ")") {
766
- state = currentStates.pop() ?? state ?? "char";
767
- fallback += char;
768
- const resolved = tokenPath ? resolve(tokenPath) ?? esc2(tokenPath) : tokenPath;
769
- if (fallback) {
770
- fallback = fallback.slice(1).trim();
771
- if (!fallback.startsWith("token(") && fallback.endsWith(")")) {
772
- fallback = fallback.slice(0, -1);
773
- }
774
- if (fallback.includes("token(")) {
775
- const parsed = expandTokenReferences(fallback, resolve);
776
- if (parsed) {
777
- fallback = parsed.slice(0, -1);
778
- }
779
- } else if (fallback) {
780
- const resolvedFallback = resolve(fallback);
781
- if (resolvedFallback) {
782
- fallback = resolvedFallback;
783
- }
784
- }
785
- }
786
- const lastChar = expanded.at(-1);
787
- if (fallback) {
788
- if (lastChar?.trim()) {
789
- expanded += resolved.slice(0, -1) + (", " + fallback + ")");
790
- } else {
791
- expanded += fallback;
792
- }
793
- } else {
794
- expanded += resolved || ")";
795
- }
796
- tokenPath = "";
797
- fallback = "";
798
- state = "char";
799
- continue;
800
- }
801
- if (state === "token") {
802
- tokenPath += char;
803
- }
804
- if (state === "fallback") {
805
- fallback += char;
806
- }
807
- continue;
808
- }
809
- const tokenIndex = str.indexOf("token(", index);
810
- if (tokenIndex !== -1) {
811
- const innerTokenIndex = tokenIndex + "token(".length;
812
- expanded += str.slice(index, tokenIndex);
813
- index = innerTokenIndex;
814
- state = "token";
815
- currentStates.push(state);
816
- continue;
817
- }
818
- expanded += char;
819
- index++;
820
- }
821
- return expanded;
730
+ //#endregion
731
+ //#region src/expand-token-references.ts
732
+ /**
733
+ * Recursively parse a string to extract Bamboo token references (curly or with the `token` function syntax)
734
+ * Allows nested token references, e.g. `token(colors.xxx.yyy, token(colors.aaa.bbb, blue))`
735
+ * Properly ignore CSS vars in fallback syntax, e.g. `token(colors.xxx.yyy, var(--some-var, var(--can-be-nested, blue)))`
736
+ */
737
+ const expandTokenReferences = (str, resolve) => {
738
+ let expanded = "";
739
+ let index = 0;
740
+ let state = "char";
741
+ let tokenPath = "";
742
+ let fallback = "";
743
+ const currentStates = [];
744
+ while (index < str.length) {
745
+ const char = str[index];
746
+ if (char === "{") {
747
+ const endIndex = str.indexOf("}", index);
748
+ if (endIndex === -1) break;
749
+ const path = str.slice(index + 1, endIndex);
750
+ const resolved = resolve(path);
751
+ expanded += resolved ?? path;
752
+ index = endIndex + 1;
753
+ continue;
754
+ }
755
+ if (state === "token") {
756
+ if (char === ",") {
757
+ if (str[index] === "") index++;
758
+ state = "fallback";
759
+ currentStates.push(state);
760
+ const resolved = resolve(tokenPath);
761
+ if (resolved?.endsWith(")")) expanded += resolved.slice(0, -1);
762
+ tokenPath = "";
763
+ fallback = "";
764
+ continue;
765
+ }
766
+ }
767
+ if (state === "fallback") {
768
+ if (fallback + char === ", var(") {
769
+ const endIndex = cssVarParser(str.slice(index + 1)) + index + 1;
770
+ const cssVar = str.slice(index + 1, endIndex);
771
+ if (endIndex === -1) break;
772
+ expanded += ", var(" + cssVar + ")";
773
+ index = endIndex + 1;
774
+ state = currentStates.pop() ?? state;
775
+ fallback = "";
776
+ continue;
777
+ }
778
+ }
779
+ if (state === "token" || state === "fallback") {
780
+ index++;
781
+ if (char === ")") {
782
+ state = currentStates.pop() ?? state ?? "char";
783
+ fallback += char;
784
+ const resolved = tokenPath ? resolve(tokenPath) ?? esc(tokenPath) : tokenPath;
785
+ if (fallback) {
786
+ fallback = fallback.slice(1).trim();
787
+ if (!fallback.startsWith("token(") && fallback.endsWith(")")) fallback = fallback.slice(0, -1);
788
+ if (fallback.includes("token(")) {
789
+ const parsed = expandTokenReferences(fallback, resolve);
790
+ if (parsed) fallback = parsed.slice(0, -1);
791
+ } else if (fallback) {
792
+ const resolvedFallback = resolve(fallback);
793
+ if (resolvedFallback) fallback = resolvedFallback;
794
+ }
795
+ }
796
+ const lastChar = expanded.at(-1);
797
+ if (fallback) if (lastChar?.trim()) expanded += resolved.slice(0, -1) + (", " + fallback + ")");
798
+ else expanded += fallback;
799
+ else expanded += resolved || ")";
800
+ tokenPath = "";
801
+ fallback = "";
802
+ state = "char";
803
+ continue;
804
+ }
805
+ if (state === "token") tokenPath += char;
806
+ if (state === "fallback") fallback += char;
807
+ continue;
808
+ }
809
+ const tokenIndex = str.indexOf("token(", index);
810
+ if (tokenIndex !== -1) {
811
+ const innerTokenIndex = tokenIndex + 6;
812
+ expanded += str.slice(index, tokenIndex);
813
+ index = innerTokenIndex;
814
+ state = "token";
815
+ currentStates.push(state);
816
+ continue;
817
+ }
818
+ expanded += char;
819
+ index++;
820
+ }
821
+ return expanded;
822
822
  };
823
- var cssVarParser = (str) => {
824
- let index = 0;
825
- const openedParenthesises = ["("];
826
- while (index < str.length) {
827
- const char = str[index];
828
- if (char === "(") {
829
- openedParenthesises.push(char);
830
- } else if (char === ")") {
831
- openedParenthesises.pop();
832
- if (openedParenthesises.length === 0) {
833
- return index;
834
- }
835
- }
836
- index++;
837
- }
838
- return index;
823
+ /**
824
+ * Finds the closing parenthesis index in a string starting from the start of a CSS var
825
+ * @example cssVarParser('--colors-red-100, var(--colors-blue-200, var(--fallback)))')
826
+ */
827
+ const cssVarParser = (str) => {
828
+ let index = 0;
829
+ const openedParenthesises = ["("];
830
+ while (index < str.length) {
831
+ const char = str[index];
832
+ if (char === "(") openedParenthesises.push(char);
833
+ else if (char === ")") {
834
+ openedParenthesises.pop();
835
+ if (openedParenthesises.length === 0) return index;
836
+ }
837
+ index++;
838
+ }
839
+ return index;
839
840
  };
840
-
841
- // src/dictionary.ts
841
+ //#endregion
842
+ //#region src/dictionary.ts
842
843
  function expandBreakpoints(breakpoints) {
843
- if (!breakpoints) return { breakpoints: {}, sizes: {} };
844
- return {
845
- breakpoints: mapObject(breakpoints, (value) => ({ value })),
846
- sizes: Object.fromEntries(Object.entries(breakpoints).map(([key, value]) => [`breakpoint-${key}`, { value }]))
847
- };
844
+ if (!breakpoints) return {
845
+ breakpoints: {},
846
+ sizes: {}
847
+ };
848
+ return {
849
+ breakpoints: mapObject(breakpoints, (value) => ({ value })),
850
+ sizes: Object.fromEntries(Object.entries(breakpoints).map(([key, value]) => [`breakpoint-${key}`, { value }]))
851
+ };
848
852
  }
849
853
  function filterDefault(path) {
850
- if (path[0] === "DEFAULT") return path;
851
- return path.filter((item) => item !== "DEFAULT");
854
+ if (path[0] === "DEFAULT") return path;
855
+ return path.filter((item) => item !== "DEFAULT");
852
856
  }
853
857
  var TokenDictionary = class {
854
- constructor(options) {
855
- this.options = options;
856
- }
857
- allTokens = [];
858
- byName = /* @__PURE__ */ new Map();
859
- deprecated = /* @__PURE__ */ new Set();
860
- init() {
861
- this.registerTokens();
862
- this.registerTransform(...transforms);
863
- this.registerMiddleware(...middlewares);
864
- this.build();
865
- return this;
866
- }
867
- get prefix() {
868
- return this.options.prefix;
869
- }
870
- get hash() {
871
- return this.options.hash;
872
- }
873
- get colorPalette() {
874
- return this.options.colorPalette;
875
- }
876
- getByName = (path) => {
877
- return this.byName.get(path);
878
- };
879
- formatTokenName = (path) => path.join(".");
880
- formatCssVar = (path, options) => cssVar(path.join("-"), options);
881
- registerTokens() {
882
- const { tokens = {}, semanticTokens = {}, breakpoints, themes = {} } = this.options;
883
- const breakpointTokens = expandBreakpoints(breakpoints);
884
- const computedTokens = compact({
885
- ...tokens,
886
- breakpoints: breakpointTokens.breakpoints,
887
- sizes: {
888
- ...tokens.sizes,
889
- ...breakpointTokens.sizes
890
- }
891
- });
892
- const processToken = (token, path) => {
893
- const isDefault = path.includes("DEFAULT");
894
- path = filterDefault(path);
895
- assertTokenFormat(token);
896
- const category = path[0];
897
- const name = this.formatTokenName(path);
898
- const node = new Token({ ...token, name, path });
899
- node.setExtensions({
900
- category,
901
- prop: this.formatTokenName(path.slice(1))
902
- });
903
- if (isDefault) {
904
- node.setExtensions({ isDefault });
905
- }
906
- return node;
907
- };
908
- const processSemantic = (token, path) => {
909
- const isDefault = path.includes("DEFAULT");
910
- path = filterDefault(path);
911
- assertTokenFormat(token);
912
- const category = path[0];
913
- const name = this.formatTokenName(path);
914
- const normalizedToken = isString2(token.value) || isCompositeTokenValue(token.value) ? { value: { base: token.value } } : token;
915
- const { value, ...restData } = normalizedToken;
916
- const node = new Token({
917
- ...restData,
918
- name,
919
- value: value.base || "",
920
- path
921
- });
922
- node.setExtensions({
923
- category,
924
- conditions: value,
925
- rawValue: value,
926
- prop: this.formatTokenName(path.slice(1))
927
- });
928
- if (isDefault) {
929
- node.setExtensions({ isDefault });
930
- }
931
- return node;
932
- };
933
- walkObject2(
934
- computedTokens,
935
- (token, path) => {
936
- const node = processToken(token, path);
937
- this.registerToken(node);
938
- },
939
- { stop: isToken }
940
- );
941
- walkObject2(
942
- semanticTokens,
943
- (token, path) => {
944
- const node = processSemantic(token, path);
945
- this.registerToken(node);
946
- },
947
- { stop: isToken }
948
- );
949
- Object.entries(themes).forEach(([theme, themeVariant]) => {
950
- const condName = "_theme" + capitalize(theme);
951
- walkObject2(
952
- themeVariant.tokens ?? {},
953
- (token, path) => {
954
- const themeToken = { value: { [condName]: token.value } };
955
- const node = processSemantic(themeToken, path);
956
- node.setExtensions({ theme, isVirtual: true });
957
- this.registerToken(node);
958
- },
959
- { stop: isToken }
960
- );
961
- walkObject2(
962
- themeVariant.semanticTokens ?? {},
963
- (token, path) => {
964
- const themeToken = { value: { [condName]: token.value } };
965
- const node = processSemantic(themeToken, path);
966
- node.setExtensions({ theme, isSemantic: true, isVirtual: true });
967
- this.registerToken(node);
968
- },
969
- { stop: isToken }
970
- );
971
- });
972
- return this;
973
- }
974
- registerToken = (token, transformPhase) => {
975
- this.allTokens.push(token);
976
- this.byName.set(token.name, token);
977
- if (token.deprecated) {
978
- this.deprecated.add(token.name);
979
- }
980
- if (transformPhase) {
981
- this.transforms.forEach((transform) => {
982
- if (transform.enforce === transformPhase) {
983
- this.execTransformOnToken(transform, token);
984
- }
985
- });
986
- }
987
- };
988
- transforms = /* @__PURE__ */ new Map();
989
- registerTransform(...transforms2) {
990
- transforms2.forEach((transform) => {
991
- transform.type ||= "value";
992
- transform.enforce ||= "pre";
993
- this.transforms.set(transform.name, transform);
994
- });
995
- return this;
996
- }
997
- execTransform(name) {
998
- const transform = this.transforms.get(name);
999
- if (!transform) return;
1000
- this.allTokens.forEach((token) => {
1001
- this.execTransformOnToken(transform, token);
1002
- });
1003
- }
1004
- execTransformOnToken(transform, token) {
1005
- if (token.extensions.hasReference) return;
1006
- if (typeof transform.match === "function" && !transform.match(token)) return;
1007
- const exec = (v) => transform.transform(v, this);
1008
- const transformed = exec(token);
1009
- match2(transform).with({ type: "extensions" }, () => {
1010
- token.setExtensions(transformed);
1011
- }).with({ type: "value" }, () => {
1012
- token.value = transformed;
1013
- if (token.isComposite) {
1014
- token.originalValue = transformed;
1015
- }
1016
- if (token.extensions.conditions) {
1017
- const conditions = token.extensions.conditions;
1018
- const transformedConditions = walkObject2(conditions, (value) => exec({ value }), {
1019
- stop: isCompositeTokenValue
1020
- });
1021
- token.setExtensions({
1022
- conditions: transformedConditions
1023
- });
1024
- }
1025
- }).otherwise(() => {
1026
- token[transform.type] = transformed;
1027
- });
1028
- }
1029
- transformTokens(enforce) {
1030
- this.transforms.forEach((transform) => {
1031
- if (transform.enforce === enforce) {
1032
- this.execTransform(transform.name);
1033
- }
1034
- });
1035
- return this;
1036
- }
1037
- middlewares = [];
1038
- registerMiddleware(...middlewares2) {
1039
- for (const middleware of middlewares2) {
1040
- middleware.enforce ||= "pre";
1041
- this.middlewares.push(middleware);
1042
- }
1043
- return this;
1044
- }
1045
- applyMiddlewares(enforce) {
1046
- this.middlewares.forEach((middleware) => {
1047
- if (middleware.enforce === enforce) {
1048
- middleware.transform(this);
1049
- }
1050
- });
1051
- }
1052
- getReferences(value) {
1053
- const refs = getReferences(value);
1054
- return refs.map((ref) => this.getByName(ref)).filter(Boolean);
1055
- }
1056
- usesReference(value) {
1057
- if (!isString2(value)) return false;
1058
- return this.getReferences(value).length > 0;
1059
- }
1060
- addReferences() {
1061
- this.allTokens.forEach((token) => {
1062
- if (!this.usesReference(token.value)) return;
1063
- const references = this.getReferences(token.value);
1064
- token.setExtensions({
1065
- references: references.reduce(
1066
- (object, reference) => {
1067
- object[reference.name] = reference;
1068
- return object;
1069
- },
1070
- {}
1071
- )
1072
- });
1073
- });
1074
- return this;
1075
- }
1076
- filter(pattern) {
1077
- const predicate = typeof pattern === "function" ? pattern : isMatching2(pattern);
1078
- return this.allTokens.filter(predicate);
1079
- }
1080
- addConditionalTokens() {
1081
- this.allTokens.forEach((token) => {
1082
- const conditionalTokens = token.getConditionTokens();
1083
- if (conditionalTokens && conditionalTokens.length > 0) {
1084
- conditionalTokens.forEach((token2) => {
1085
- this.registerToken(token2);
1086
- });
1087
- }
1088
- });
1089
- return this;
1090
- }
1091
- expandTokenReferences() {
1092
- this.allTokens.forEach((token) => {
1093
- token.expandReferences();
1094
- });
1095
- return this;
1096
- }
1097
- colorMix = (value, tokenFn) => {
1098
- if (!value || typeof value !== "string") return { invalid: true, value };
1099
- const [colorPath, rawOpacity] = value.split("/");
1100
- if (!colorPath || !rawOpacity) {
1101
- return { invalid: true, value: colorPath };
1102
- }
1103
- const colorToken = tokenFn(colorPath);
1104
- const opacityToken = this.getByName(`opacity.${rawOpacity}`)?.value;
1105
- if (!opacityToken && isNaN(Number(rawOpacity))) {
1106
- return { invalid: true, value: colorPath };
1107
- }
1108
- const percent = opacityToken ? Number(opacityToken) * 100 + "%" : `${rawOpacity}%`;
1109
- const color = colorToken ?? colorPath;
1110
- return {
1111
- invalid: false,
1112
- color,
1113
- value: `color-mix(in srgb, ${color} ${percent}, transparent)`
1114
- };
1115
- };
1116
- /**
1117
- * Expand token references to their CSS variable
1118
- */
1119
- expandReferenceInValue(value) {
1120
- return expandTokenReferences(value, (path) => {
1121
- if (!path) return;
1122
- if (path.includes("/")) {
1123
- const mix = this.colorMix(path, this.view.getVar.bind(this.view));
1124
- if (mix.invalid) {
1125
- throw new BambooError3("INVALID_TOKEN", "Invalid color mix at " + path + ": " + mix.value);
1126
- }
1127
- return mix.value;
1128
- }
1129
- const resolved = this.view.getVar(path);
1130
- if (resolved) return resolved;
1131
- return tokenPathRegex.test(path) ? esc3(path) : path;
1132
- });
1133
- }
1134
- /**
1135
- * Get the value of a token reference
1136
- */
1137
- resolveReference(value) {
1138
- return expandReferences(value, (key) => this.getByName(key)?.value);
1139
- }
1140
- /**
1141
- * Resolve token references to their actual raw value (recursively resolves references)
1142
- */
1143
- deepResolveReference(originalValue) {
1144
- const stack = [originalValue];
1145
- while (stack.length) {
1146
- const next = stack.pop();
1147
- if (next.startsWith("{")) {
1148
- stack.push(this.resolveReference(next));
1149
- continue;
1150
- }
1151
- if (next.startsWith("var(")) {
1152
- const ref = this.view.nameByVar.get(next);
1153
- if (ref) {
1154
- stack.push(this.resolveReference(`{${ref}}`));
1155
- continue;
1156
- }
1157
- }
1158
- return next;
1159
- }
1160
- }
1161
- isDeprecated(name) {
1162
- return this.deprecated.has(name);
1163
- }
1164
- build() {
1165
- this.applyMiddlewares("pre");
1166
- this.transformTokens("pre");
1167
- this.addConditionalTokens();
1168
- this.addReferences();
1169
- this.expandTokenReferences();
1170
- this.applyMiddlewares("post");
1171
- this.transformTokens("post");
1172
- this.setComputedView();
1173
- return this;
1174
- }
1175
- get isEmpty() {
1176
- return this.allTokens.length === 0;
1177
- }
1178
- view;
1179
- setComputedView() {
1180
- this.view = new TokenDictionaryView(this).getTokensView();
1181
- return this;
1182
- }
858
+ options;
859
+ allTokens = [];
860
+ byName = /* @__PURE__ */ new Map();
861
+ deprecated = /* @__PURE__ */ new Set();
862
+ constructor(options) {
863
+ this.options = options;
864
+ }
865
+ init() {
866
+ this.registerTokens();
867
+ this.registerTransform(...transforms);
868
+ this.registerMiddleware(...middlewares);
869
+ this.build();
870
+ return this;
871
+ }
872
+ get prefix() {
873
+ return this.options.prefix;
874
+ }
875
+ get hash() {
876
+ return this.options.hash;
877
+ }
878
+ get colorPalette() {
879
+ return this.options.colorPalette;
880
+ }
881
+ getByName = (path) => {
882
+ return this.byName.get(path);
883
+ };
884
+ formatTokenName = (path) => path.join(".");
885
+ formatCssVar = (path, options) => cssVar(path.join("-"), options);
886
+ registerTokens() {
887
+ const { tokens = {}, semanticTokens = {}, breakpoints, themes = {} } = this.options;
888
+ const breakpointTokens = expandBreakpoints(breakpoints);
889
+ const computedTokens = compact({
890
+ ...tokens,
891
+ breakpoints: breakpointTokens.breakpoints,
892
+ sizes: {
893
+ ...tokens.sizes,
894
+ ...breakpointTokens.sizes
895
+ }
896
+ });
897
+ const processToken = (token, path) => {
898
+ const isDefault = path.includes("DEFAULT");
899
+ path = filterDefault(path);
900
+ assertTokenFormat(token);
901
+ const category = path[0];
902
+ const name = this.formatTokenName(path);
903
+ const node = new Token({
904
+ ...token,
905
+ name,
906
+ path
907
+ });
908
+ node.setExtensions({
909
+ category,
910
+ prop: this.formatTokenName(path.slice(1))
911
+ });
912
+ if (isDefault) node.setExtensions({ isDefault });
913
+ return node;
914
+ };
915
+ const processSemantic = (token, path) => {
916
+ const isDefault = path.includes("DEFAULT");
917
+ path = filterDefault(path);
918
+ assertTokenFormat(token);
919
+ const category = path[0];
920
+ const name = this.formatTokenName(path);
921
+ const { value, ...restData } = isString(token.value) || isCompositeTokenValue(token.value) ? { value: { base: token.value } } : token;
922
+ const node = new Token({
923
+ ...restData,
924
+ name,
925
+ value: value.base || "",
926
+ path
927
+ });
928
+ node.setExtensions({
929
+ category,
930
+ conditions: value,
931
+ rawValue: value,
932
+ prop: this.formatTokenName(path.slice(1))
933
+ });
934
+ if (isDefault) node.setExtensions({ isDefault });
935
+ return node;
936
+ };
937
+ walkObject(computedTokens, (token, path) => {
938
+ const node = processToken(token, path);
939
+ this.registerToken(node);
940
+ }, { stop: isToken });
941
+ walkObject(semanticTokens, (token, path) => {
942
+ const node = processSemantic(token, path);
943
+ this.registerToken(node);
944
+ }, { stop: isToken });
945
+ Object.entries(themes).forEach(([theme, themeVariant]) => {
946
+ const condName = "_theme" + capitalize(theme);
947
+ walkObject(themeVariant.tokens ?? {}, (token, path) => {
948
+ const node = processSemantic({ value: { [condName]: token.value } }, path);
949
+ node.setExtensions({
950
+ theme,
951
+ isVirtual: true
952
+ });
953
+ this.registerToken(node);
954
+ }, { stop: isToken });
955
+ walkObject(themeVariant.semanticTokens ?? {}, (token, path) => {
956
+ const node = processSemantic({ value: { [condName]: token.value } }, path);
957
+ node.setExtensions({
958
+ theme,
959
+ isSemantic: true,
960
+ isVirtual: true
961
+ });
962
+ this.registerToken(node);
963
+ }, { stop: isToken });
964
+ });
965
+ return this;
966
+ }
967
+ registerToken = (token, transformPhase) => {
968
+ this.allTokens.push(token);
969
+ this.byName.set(token.name, token);
970
+ if (token.deprecated) this.deprecated.add(token.name);
971
+ if (transformPhase) this.transforms.forEach((transform) => {
972
+ if (transform.enforce === transformPhase) this.execTransformOnToken(transform, token);
973
+ });
974
+ };
975
+ transforms = /* @__PURE__ */ new Map();
976
+ registerTransform(...transforms) {
977
+ transforms.forEach((transform) => {
978
+ transform.type ||= "value";
979
+ transform.enforce ||= "pre";
980
+ this.transforms.set(transform.name, transform);
981
+ });
982
+ return this;
983
+ }
984
+ execTransform(name) {
985
+ const transform = this.transforms.get(name);
986
+ if (!transform) return;
987
+ this.allTokens.forEach((token) => {
988
+ this.execTransformOnToken(transform, token);
989
+ });
990
+ }
991
+ execTransformOnToken(transform, token) {
992
+ if (token.extensions.hasReference) return;
993
+ if (typeof transform.match === "function" && !transform.match(token)) return;
994
+ const exec = (v) => transform.transform(v, this);
995
+ const transformed = exec(token);
996
+ match(transform).with({ type: "extensions" }, () => {
997
+ token.setExtensions(transformed);
998
+ }).with({ type: "value" }, () => {
999
+ token.value = transformed;
1000
+ if (token.isComposite) token.originalValue = transformed;
1001
+ if (token.extensions.conditions) {
1002
+ const conditions = token.extensions.conditions;
1003
+ const transformedConditions = walkObject(conditions, (value) => exec({ value }), { stop: isCompositeTokenValue });
1004
+ token.setExtensions({ conditions: transformedConditions });
1005
+ }
1006
+ }).otherwise(() => {
1007
+ token[transform.type] = transformed;
1008
+ });
1009
+ }
1010
+ transformTokens(enforce) {
1011
+ this.transforms.forEach((transform) => {
1012
+ if (transform.enforce === enforce) this.execTransform(transform.name);
1013
+ });
1014
+ return this;
1015
+ }
1016
+ middlewares = [];
1017
+ registerMiddleware(...middlewares) {
1018
+ for (const middleware of middlewares) {
1019
+ middleware.enforce ||= "pre";
1020
+ this.middlewares.push(middleware);
1021
+ }
1022
+ return this;
1023
+ }
1024
+ applyMiddlewares(enforce) {
1025
+ this.middlewares.forEach((middleware) => {
1026
+ if (middleware.enforce === enforce) middleware.transform(this);
1027
+ });
1028
+ }
1029
+ getReferences(value) {
1030
+ return getReferences(value).map((ref) => this.getByName(ref)).filter(Boolean);
1031
+ }
1032
+ usesReference(value) {
1033
+ if (!isString(value)) return false;
1034
+ return this.getReferences(value).length > 0;
1035
+ }
1036
+ addReferences() {
1037
+ this.allTokens.forEach((token) => {
1038
+ if (!this.usesReference(token.value)) return;
1039
+ const references = this.getReferences(token.value);
1040
+ token.setExtensions({ references: references.reduce((object, reference) => {
1041
+ object[reference.name] = reference;
1042
+ return object;
1043
+ }, {}) });
1044
+ });
1045
+ return this;
1046
+ }
1047
+ filter(pattern) {
1048
+ const predicate = typeof pattern === "function" ? pattern : isMatching(pattern);
1049
+ return this.allTokens.filter(predicate);
1050
+ }
1051
+ addConditionalTokens() {
1052
+ this.allTokens.forEach((token) => {
1053
+ const conditionalTokens = token.getConditionTokens();
1054
+ if (conditionalTokens && conditionalTokens.length > 0) conditionalTokens.forEach((token) => {
1055
+ this.registerToken(token);
1056
+ });
1057
+ });
1058
+ return this;
1059
+ }
1060
+ expandTokenReferences() {
1061
+ this.allTokens.forEach((token) => {
1062
+ token.expandReferences();
1063
+ });
1064
+ return this;
1065
+ }
1066
+ colorMix = (value, tokenFn) => {
1067
+ if (!value || typeof value !== "string") return {
1068
+ invalid: true,
1069
+ value
1070
+ };
1071
+ const [colorPath, rawOpacity] = value.split("/");
1072
+ if (!colorPath || !rawOpacity) return {
1073
+ invalid: true,
1074
+ value: colorPath
1075
+ };
1076
+ const colorToken = tokenFn(colorPath);
1077
+ const opacityToken = this.getByName(`opacity.${rawOpacity}`)?.value;
1078
+ if (!opacityToken && isNaN(Number(rawOpacity))) return {
1079
+ invalid: true,
1080
+ value: colorPath
1081
+ };
1082
+ const percent = opacityToken ? Number(opacityToken) * 100 + "%" : `${rawOpacity}%`;
1083
+ const color = colorToken ?? colorPath;
1084
+ return {
1085
+ invalid: false,
1086
+ color,
1087
+ value: `color-mix(in srgb, ${color} ${percent}, transparent)`
1088
+ };
1089
+ };
1090
+ /**
1091
+ * Expand token references to their CSS variable
1092
+ */
1093
+ expandReferenceInValue(value) {
1094
+ return expandTokenReferences(value, (path) => {
1095
+ if (!path) return;
1096
+ if (path.includes("/")) {
1097
+ const mix = this.colorMix(path, this.view.getVar.bind(this.view));
1098
+ if (mix.invalid) throw new BambooError("INVALID_TOKEN", "Invalid color mix at " + path + ": " + mix.value);
1099
+ return mix.value;
1100
+ }
1101
+ const resolved = this.view.getVar(path);
1102
+ if (resolved) return resolved;
1103
+ return tokenPathRegex.test(path) ? esc(path) : path;
1104
+ });
1105
+ }
1106
+ /**
1107
+ * Get the value of a token reference
1108
+ */
1109
+ resolveReference(value) {
1110
+ return expandReferences(value, (key) => this.getByName(key)?.value);
1111
+ }
1112
+ /**
1113
+ * Resolve token references to their actual raw value (recursively resolves references)
1114
+ */
1115
+ deepResolveReference(originalValue) {
1116
+ const stack = [originalValue];
1117
+ while (stack.length) {
1118
+ const next = stack.pop();
1119
+ if (next.startsWith("{")) {
1120
+ stack.push(this.resolveReference(next));
1121
+ continue;
1122
+ }
1123
+ if (next.startsWith("var(")) {
1124
+ const ref = this.view.nameByVar.get(next);
1125
+ if (ref) {
1126
+ stack.push(this.resolveReference(`{${ref}}`));
1127
+ continue;
1128
+ }
1129
+ }
1130
+ return next;
1131
+ }
1132
+ }
1133
+ isDeprecated(name) {
1134
+ return this.deprecated.has(name);
1135
+ }
1136
+ build() {
1137
+ this.applyMiddlewares("pre");
1138
+ this.transformTokens("pre");
1139
+ this.addConditionalTokens();
1140
+ this.addReferences();
1141
+ this.expandTokenReferences();
1142
+ this.applyMiddlewares("post");
1143
+ this.transformTokens("post");
1144
+ this.setComputedView();
1145
+ return this;
1146
+ }
1147
+ get isEmpty() {
1148
+ return this.allTokens.length === 0;
1149
+ }
1150
+ view;
1151
+ setComputedView() {
1152
+ this.view = new TokenDictionaryView(this).getTokensView();
1153
+ return this;
1154
+ }
1183
1155
  };
1184
1156
  var TokenDictionaryView = class {
1185
- constructor(dictionary) {
1186
- this.dictionary = dictionary;
1187
- this.dictionary = dictionary;
1188
- }
1189
- getTokensView() {
1190
- const conditionMap = /* @__PURE__ */ new Map();
1191
- const categoryMap = /* @__PURE__ */ new Map();
1192
- const colorPalettes = /* @__PURE__ */ new Map();
1193
- const colorPaletteTokens = /* @__PURE__ */ new Map();
1194
- const valuesByCategory = /* @__PURE__ */ new Map();
1195
- const flatValues = /* @__PURE__ */ new Map();
1196
- const rawValues = /* @__PURE__ */ new Map();
1197
- const nameByVar = /* @__PURE__ */ new Map();
1198
- const vars = /* @__PURE__ */ new Map();
1199
- this.dictionary.allTokens.forEach((token) => {
1200
- this.processCondition(token, conditionMap);
1201
- this.processColorPalette(token, colorPalettes, colorPaletteTokens, this.dictionary.byName);
1202
- this.processCategory(token, categoryMap);
1203
- this.processValue(token, valuesByCategory, flatValues, rawValues, nameByVar);
1204
- this.processVars(token, vars);
1205
- });
1206
- const json = mapToJson(valuesByCategory);
1207
- return {
1208
- conditionMap,
1209
- categoryMap,
1210
- colorPalettes,
1211
- vars,
1212
- values: flatValues,
1213
- nameByVar,
1214
- json,
1215
- valuesByCategory,
1216
- get: memo((path, fallback) => {
1217
- return rawValues.get(path) ?? fallback;
1218
- }),
1219
- getVar: memo((path, fallback) => {
1220
- return flatValues.get(path) ?? fallback;
1221
- }),
1222
- getCategoryValues: memo((category) => {
1223
- const result = json[category];
1224
- if (result != null) {
1225
- return result;
1226
- }
1227
- }),
1228
- getColorPaletteValues: memo((palette) => {
1229
- const tokens = colorPaletteTokens.get(palette);
1230
- if (!tokens) return [];
1231
- return Array.from(tokens).sort();
1232
- })
1233
- };
1234
- }
1235
- processCondition(token, group) {
1236
- const { condition } = token.extensions;
1237
- if (!condition) return;
1238
- if (!group.has(condition)) group.set(condition, /* @__PURE__ */ new Set());
1239
- group.get(condition).add(token);
1240
- }
1241
- processColorPalette(token, group, tokenPaths, byName) {
1242
- const extensions = token.extensions;
1243
- const { colorPalette, colorPaletteRoots, isVirtual } = extensions;
1244
- if (!colorPalette || isVirtual) return;
1245
- colorPaletteRoots.forEach((colorPaletteRoot) => {
1246
- const formated = this.dictionary.formatTokenName(colorPaletteRoot);
1247
- if (!group.has(formated)) {
1248
- group.set(formated, /* @__PURE__ */ new Map());
1249
- }
1250
- if (!tokenPaths.has(formated)) {
1251
- tokenPaths.set(formated, /* @__PURE__ */ new Set());
1252
- }
1253
- const virtualPath = replaceRootWithColorPalette([...token.path], [...colorPaletteRoot]);
1254
- const virtualName = this.dictionary.formatTokenName(virtualPath);
1255
- const virtualToken = byName.get(virtualName);
1256
- if (!virtualToken) return;
1257
- const virtualVar = virtualToken.extensions.var;
1258
- group.get(formated).set(virtualVar, token.extensions.varRef);
1259
- const tokenPath = this.dictionary.formatTokenName(virtualPath.slice(1));
1260
- tokenPaths.get(formated).add(tokenPath);
1261
- if (extensions.isDefault && colorPaletteRoot.length === 1) {
1262
- const colorPaletteName = this.dictionary.formatTokenName(["colors", "colorPalette"]);
1263
- const colorPaletteToken = byName.get(colorPaletteName);
1264
- if (!colorPaletteToken) return;
1265
- const name = this.dictionary.formatTokenName(token.path);
1266
- const virtualToken2 = byName.get(name);
1267
- if (!virtualToken2) return;
1268
- const keyPath = extensions.colorPaletteTokenKeys[0]?.filter(Boolean);
1269
- if (!keyPath.length) return;
1270
- const formated2 = this.dictionary.formatTokenName(colorPaletteRoot.concat(keyPath));
1271
- if (!group.has(formated2)) {
1272
- group.set(formated2, /* @__PURE__ */ new Map());
1273
- }
1274
- group.get(formated2).set(colorPaletteToken.extensions.var, virtualToken2.extensions.varRef);
1275
- }
1276
- });
1277
- }
1278
- processCategory(token, group) {
1279
- const { category, prop } = token.extensions;
1280
- if (!category) return;
1281
- if (!group.has(category)) group.set(category, /* @__PURE__ */ new Map());
1282
- group.get(category).set(prop, token);
1283
- }
1284
- processValue(token, byCategory, flatValues, rawValues, nameByVar) {
1285
- const { category, prop, varRef, isNegative, isVirtual, condition } = token.extensions;
1286
- if (!category) return;
1287
- if (!byCategory.has(category)) byCategory.set(category, /* @__PURE__ */ new Map());
1288
- const value = isNegative ? token.extensions.condition !== "base" ? token.originalValue : token.value : varRef;
1289
- byCategory.get(category).set(prop, value);
1290
- flatValues.set(token.name, value);
1291
- nameByVar.set(value, token.name);
1292
- const rawValue = isVirtual || condition !== "base" ? varRef : token.value;
1293
- rawValues.set(token.name, rawValue);
1294
- }
1295
- processVars(token, group) {
1296
- const { condition, isNegative, isVirtual, var: varName, theme } = token.extensions;
1297
- if (isNegative || !theme && isVirtual || !condition) return;
1298
- if (!group.has(condition)) group.set(condition, /* @__PURE__ */ new Map());
1299
- group.get(condition).set(varName, token.value);
1300
- }
1157
+ dictionary;
1158
+ constructor(dictionary) {
1159
+ this.dictionary = dictionary;
1160
+ this.dictionary = dictionary;
1161
+ }
1162
+ getTokensView() {
1163
+ const conditionMap = /* @__PURE__ */ new Map();
1164
+ const categoryMap = /* @__PURE__ */ new Map();
1165
+ const colorPalettes = /* @__PURE__ */ new Map();
1166
+ const colorPaletteTokens = /* @__PURE__ */ new Map();
1167
+ const valuesByCategory = /* @__PURE__ */ new Map();
1168
+ const flatValues = /* @__PURE__ */ new Map();
1169
+ const rawValues = /* @__PURE__ */ new Map();
1170
+ const nameByVar = /* @__PURE__ */ new Map();
1171
+ const vars = /* @__PURE__ */ new Map();
1172
+ this.dictionary.allTokens.forEach((token) => {
1173
+ this.processCondition(token, conditionMap);
1174
+ this.processColorPalette(token, colorPalettes, colorPaletteTokens, this.dictionary.byName);
1175
+ this.processCategory(token, categoryMap);
1176
+ this.processValue(token, valuesByCategory, flatValues, rawValues, nameByVar);
1177
+ this.processVars(token, vars);
1178
+ });
1179
+ const json = mapToJson(valuesByCategory);
1180
+ return {
1181
+ conditionMap,
1182
+ categoryMap,
1183
+ colorPalettes,
1184
+ vars,
1185
+ values: flatValues,
1186
+ nameByVar,
1187
+ json,
1188
+ valuesByCategory,
1189
+ get: memo((path, fallback) => {
1190
+ return rawValues.get(path) ?? fallback;
1191
+ }),
1192
+ getVar: memo((path, fallback) => {
1193
+ return flatValues.get(path) ?? fallback;
1194
+ }),
1195
+ getCategoryValues: memo((category) => {
1196
+ const result = json[category];
1197
+ if (result != null) return result;
1198
+ }),
1199
+ getColorPaletteValues: memo((palette) => {
1200
+ const tokens = colorPaletteTokens.get(palette);
1201
+ if (!tokens) return [];
1202
+ return Array.from(tokens).sort();
1203
+ })
1204
+ };
1205
+ }
1206
+ processCondition(token, group) {
1207
+ const { condition } = token.extensions;
1208
+ if (!condition) return;
1209
+ if (!group.has(condition)) group.set(condition, /* @__PURE__ */ new Set());
1210
+ group.get(condition).add(token);
1211
+ }
1212
+ processColorPalette(token, group, tokenPaths, byName) {
1213
+ const extensions = token.extensions;
1214
+ const { colorPalette, colorPaletteRoots, isVirtual } = extensions;
1215
+ if (!colorPalette || isVirtual) return;
1216
+ colorPaletteRoots.forEach((colorPaletteRoot) => {
1217
+ const formated = this.dictionary.formatTokenName(colorPaletteRoot);
1218
+ if (!group.has(formated)) group.set(formated, /* @__PURE__ */ new Map());
1219
+ if (!tokenPaths.has(formated)) tokenPaths.set(formated, /* @__PURE__ */ new Set());
1220
+ const virtualPath = replaceRootWithColorPalette([...token.path], [...colorPaletteRoot]);
1221
+ const virtualName = this.dictionary.formatTokenName(virtualPath);
1222
+ const virtualToken = byName.get(virtualName);
1223
+ if (!virtualToken) return;
1224
+ const virtualVar = virtualToken.extensions.var;
1225
+ group.get(formated).set(virtualVar, token.extensions.varRef);
1226
+ const tokenPath = this.dictionary.formatTokenName(virtualPath.slice(1));
1227
+ tokenPaths.get(formated).add(tokenPath);
1228
+ if (extensions.isDefault && colorPaletteRoot.length === 1) {
1229
+ const colorPaletteName = this.dictionary.formatTokenName(["colors", "colorPalette"]);
1230
+ const colorPaletteToken = byName.get(colorPaletteName);
1231
+ if (!colorPaletteToken) return;
1232
+ const name = this.dictionary.formatTokenName(token.path);
1233
+ const virtualToken = byName.get(name);
1234
+ if (!virtualToken) return;
1235
+ const keyPath = extensions.colorPaletteTokenKeys[0]?.filter(Boolean);
1236
+ if (!keyPath.length) return;
1237
+ const formated = this.dictionary.formatTokenName(colorPaletteRoot.concat(keyPath));
1238
+ if (!group.has(formated)) group.set(formated, /* @__PURE__ */ new Map());
1239
+ group.get(formated).set(colorPaletteToken.extensions.var, virtualToken.extensions.varRef);
1240
+ }
1241
+ });
1242
+ }
1243
+ processCategory(token, group) {
1244
+ const { category, prop } = token.extensions;
1245
+ if (!category) return;
1246
+ if (!group.has(category)) group.set(category, /* @__PURE__ */ new Map());
1247
+ group.get(category).set(prop, token);
1248
+ }
1249
+ processValue(token, byCategory, flatValues, rawValues, nameByVar) {
1250
+ const { category, prop, varRef, isNegative, isVirtual, condition } = token.extensions;
1251
+ if (!category) return;
1252
+ if (!byCategory.has(category)) byCategory.set(category, /* @__PURE__ */ new Map());
1253
+ const value = isNegative ? token.extensions.condition !== "base" ? token.originalValue : token.value : varRef;
1254
+ byCategory.get(category).set(prop, value);
1255
+ flatValues.set(token.name, value);
1256
+ nameByVar.set(value, token.name);
1257
+ const rawValue = isVirtual || condition !== "base" ? varRef : token.value;
1258
+ rawValues.set(token.name, rawValue);
1259
+ }
1260
+ processVars(token, group) {
1261
+ const { condition, isNegative, isVirtual, var: varName, theme } = token.extensions;
1262
+ if (isNegative || !theme && isVirtual || !condition) return;
1263
+ if (!group.has(condition)) group.set(condition, /* @__PURE__ */ new Map());
1264
+ group.get(condition).set(varName, token.value);
1265
+ }
1301
1266
  };
1267
+ /**
1268
+ * Replaces the colorPaletteRoot in token.path with 'colorPalette'
1269
+ * @example replaceRootWithColorPalette(['colors', 'button', 'red', '500'], ['button', 'red'])
1270
+ * // => ["colors", "colorPalette", "500"]
1271
+ */
1302
1272
  function replaceRootWithColorPalette(path, colorPaletteRoot) {
1303
- const startIndex = path.findIndex(
1304
- (element, index) => colorPaletteRoot.every((rootElement, rootIndex) => path[index + rootIndex] === rootElement)
1305
- );
1306
- if (startIndex === -1) {
1307
- return path;
1308
- }
1309
- path.splice(startIndex, colorPaletteRoot.length);
1310
- path.splice(startIndex, 0, "colorPalette");
1311
- return path;
1273
+ const startIndex = path.findIndex((element, index) => colorPaletteRoot.every((rootElement, rootIndex) => path[index + rootIndex] === rootElement));
1274
+ if (startIndex === -1) return path;
1275
+ path.splice(startIndex, colorPaletteRoot.length);
1276
+ path.splice(startIndex, 0, "colorPalette");
1277
+ return path;
1312
1278
  }
1313
- var tokenPathRegex = /\w+\.\w+/;
1314
- export {
1315
- TOKEN_CATEGORIES,
1316
- Token,
1317
- TokenDictionary,
1318
- assertTokenFormat,
1319
- expandReferences,
1320
- getReferences,
1321
- hasReference,
1322
- isToken,
1323
- mapToJson
1324
- };
1279
+ const tokenPathRegex = /\w+\.\w+/;
1280
+ //#endregion
1281
+ export { TOKEN_CATEGORIES, Token, TokenDictionary, assertTokenFormat, expandReferences, getReferences, hasReference, isToken, mapToJson };