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