@sugarcube-org/core 0.0.1-alpha.1 → 0.0.1-alpha.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +473 -142
  2. package/dist/index.js +12 -6
  3. package/package.json +16 -4
package/dist/index.d.ts CHANGED
@@ -1,31 +1,180 @@
1
+ type ColorFormat = "hex" | "rgb" | "rgba" | "hsl" | "hsla" | "oklch" | "p3";
2
+ type ColorConfig = {
3
+ format?: ColorFormat;
4
+ };
5
+ type FluidConfig = {
6
+ min: number;
7
+ max: number;
8
+ };
9
+ type TokenCollection = {
10
+ source: string[];
11
+ type: "starter-kit" | "custom";
12
+ themes?: Record<string, string[]>;
13
+ };
14
+ type TokenCollections = Record<string, TokenCollection>;
15
+ type OptionsConfig = {
16
+ fluid?: FluidConfig;
17
+ prefix?: string;
18
+ color?: ColorFormat;
19
+ };
20
+ type DirectoriesConfig = {
21
+ tokens: string;
22
+ components?: string;
23
+ css: string;
24
+ };
25
+ type CSSOutputConfig = {
26
+ separate: boolean;
27
+ manageIndex?: boolean;
28
+ format?: "css" | "scss" | "less";
29
+ };
30
+ type OutputConfig = {
31
+ directories: DirectoriesConfig;
32
+ css: CSSOutputConfig;
33
+ };
34
+ interface SugarcubeConfig {
35
+ tokens: TokenCollection | TokenCollections;
36
+ options?: OptionsConfig;
37
+ output: OutputConfig;
38
+ }
39
+
40
+ /**
41
+ * Represents a single CSS file output with its name and content
42
+ */
43
+ type CSSFile = {
44
+ name: string;
45
+ content: string;
46
+ };
47
+ /**
48
+ * Represents the output from generateCSS which always returns exactly one file
49
+ */
50
+ type SingleFileOutput = [CSSFile];
51
+ /**
52
+ * Represents multiple CSS file outputs from generateSeparateFiles or generateSingleFile
53
+ */
54
+ type CSSFileOutput = CSSFile[];
55
+ /**
56
+ * Result of the CSS generation process
57
+ * For generateCSS: Contains exactly one file
58
+ * For generate: Contains one or more files
59
+ */
60
+ type CSSGenerationResult = {
61
+ output: SingleFileOutput | CSSFileOutput;
62
+ };
63
+
64
+ /**
65
+ * A token value that can either be a raw value or a reference
66
+ */
67
+ type TokenValue<T extends TokenType> = RawTokenValue<T> | Reference<T>;
68
+ /**
69
+ * The actual value of a token without references
70
+ */
71
+ type RawTokenValue<T extends TokenType> = T extends SimpleTokenType ? SimpleTokenValue<T> : T extends CompositeTokenType ? CompositeTokenValue<T> : never;
72
+ /**
73
+ * A reference to another token, with optional type checking
74
+ */
75
+ type Reference<T extends TokenType = TokenType> = string & {
76
+ __tokenType?: T;
77
+ };
78
+ /**
79
+ * Metadata that can be attached to any node in the token tree
80
+ */
81
+ type NodeMetadata = {
82
+ $description?: string;
83
+ $extensions?: {
84
+ [key: string]: unknown;
85
+ };
86
+ };
87
+ /**
88
+ * A single token with its value and metadata
89
+ */
90
+ type Token = NodeMetadata & {
91
+ $value: TokenValue<TokenType>;
92
+ $type?: TokenType;
93
+ };
94
+ /**
95
+ * A group of tokens that can be nested
96
+ */
97
+ type TokenGroup = {
98
+ [key: string]: Token | TokenGroup;
99
+ } & NodeMetadata & {
100
+ $type?: TokenType;
101
+ };
102
+ /**
103
+ * All possible token types, either simple or composite
104
+ */
105
+ type TokenType = SimpleTokenType | CompositeTokenType;
106
+ /**
107
+ * Token types that contain a single value
108
+ */
109
+ type SimpleTokenType = "color" | "dimension" | "fluidDimension" | "duration" | "cubicBezier" | "fontFamily" | "fontWeight" | "number";
110
+ /**
111
+ * Values for simple token types
112
+ */
113
+ type SimpleTokenValue<T extends SimpleTokenType = SimpleTokenType> = T extends "color" ? Color : T extends "dimension" ? Dimension : T extends "fluidDimension" ? FluidDimension : T extends "duration" ? Duration : T extends "cubicBezier" ? CubicBezier : T extends "fontFamily" ? FontFamily : T extends "fontWeight" ? FontWeight : T extends "number" ? number : never;
114
+ /**
115
+ * Token types that contain multiple values or are structurally complex
116
+ */
117
+ type CompositeTokenType = AlwaysDecomposedType | "border" | "shadow" | "gradient" | "transition" | StructuralCompositeType;
118
+ /**
119
+ * Token types that must always be broken down into their constituent parts
120
+ */
121
+ type AlwaysDecomposedType = "typography";
122
+ /**
123
+ * Token types that define structural patterns
124
+ */
125
+ type StructuralCompositeType = "strokeStyle";
126
+ /**
127
+ * Values for composite token types
128
+ */
129
+ type CompositeTokenValue<T extends CompositeTokenType = CompositeTokenType> = T extends "typography" ? Typography : T extends "border" ? Border : T extends "shadow" ? Shadow : T extends "gradient" ? Gradient : T extends "transition" ? Transition : T extends "strokeStyle" ? StrokeStyle : never;
130
+ /**
131
+ * A color value in any valid CSS color format
132
+ */
1
133
  type Color = string;
134
+ /**
135
+ * A dimensional value with a numeric value and unit
136
+ */
2
137
  type Dimension = {
3
138
  value: number;
4
139
  unit: "px" | "rem";
5
140
  };
141
+ /**
142
+ * A fluid dimension that scales between min and max values
143
+ */
6
144
  type FluidDimension = {
7
145
  min: Dimension;
8
146
  max: Dimension;
9
147
  };
10
- type Duration = string;
148
+ /**
149
+ * A duration value with a numeric value and time unit
150
+ */
151
+ type Duration = {
152
+ value: number;
153
+ unit: "ms" | "s";
154
+ };
155
+ /**
156
+ * A cubic bezier curve defined by four control points
157
+ */
11
158
  type CubicBezier = [number, number, number, number];
159
+ /**
160
+ * A font family name or list of fallback fonts
161
+ */
12
162
  type FontFamily = string | string[];
163
+ /**
164
+ * A font weight value as either a number or semantic string
165
+ */
13
166
  type FontWeight = number | FontWeightString;
167
+ /**
168
+ * Semantic font weight names
169
+ */
14
170
  type FontWeightString = "thin" | "hairline" | "extra-light" | "ultra-light" | "light" | "normal" | "regular" | "book" | "medium" | "semi-bold" | "demi-bold" | "bold" | "extra-bold" | "ultra-bold" | "black" | "heavy" | "extra-black" | "ultra-black";
171
+ /**
172
+ * Line cap style for strokes
173
+ */
15
174
  type LineCap = "round" | "butt" | "square";
16
- type TokenType = SimpleTokenType | CompositeTokenType;
17
- type SimpleTokenType = "color" | "dimension" | "fluidDimension" | "duration" | "cubicBezier" | "fontFamily" | "fontWeight" | "number";
18
- type CompositeTokenType = AlwaysDecomposedType | OptionallyDecomposedType | StructuralCompositeType;
19
- type AlwaysDecomposedType = "typography";
20
- type OptionallyDecomposedType = "border" | "shadow" | "gradient" | "transition";
21
- type StructuralCompositeType = "strokeStyle";
22
- type Reference<T extends TokenType = TokenType> = string & {
23
- __tokenType?: T;
24
- };
25
- type TokenValue<T extends TokenType> = RawTokenValue<T> | Reference<T>;
26
- type RawTokenValue<T extends TokenType> = T extends SimpleTokenType ? SimpleTokenValue<T> : T extends CompositeTokenType ? CompositeTokenValue<T> : never;
27
- type SimpleTokenValue<T extends SimpleTokenType = SimpleTokenType> = T extends "color" ? Color : T extends "dimension" ? Dimension : T extends "fluidDimension" ? FluidDimension : T extends "duration" ? Duration : T extends "cubicBezier" ? CubicBezier : T extends "fontFamily" ? FontFamily : T extends "fontWeight" ? FontWeight : T extends "number" ? number : never;
28
- type CompositeTokenValue<T extends CompositeTokenType = CompositeTokenType> = T extends "typography" ? Typography : T extends "border" ? Border : T extends "shadow" ? Shadow : T extends "gradient" ? Gradient : T extends "transition" ? Transition : T extends "strokeStyle" ? StrokeStyle : never;
175
+ /**
176
+ * Typography token combining font properties
177
+ */
29
178
  type Typography = {
30
179
  fontFamily: TokenValue<"fontFamily">;
31
180
  fontSize: TokenValue<"dimension">;
@@ -33,22 +182,40 @@ type Typography = {
33
182
  letterSpacing?: TokenValue<"dimension">;
34
183
  lineHeight?: TokenValue<"number">;
35
184
  };
185
+ /**
186
+ * Transition token defining animation properties
187
+ */
36
188
  type Transition = {
37
189
  duration: TokenValue<"duration">;
38
190
  delay?: TokenValue<"duration">;
39
191
  timingFunction: TokenValue<"cubicBezier">;
40
192
  };
193
+ /**
194
+ * Predefined stroke style keywords
195
+ */
41
196
  type StrokeStyleKeyword = "solid" | "dashed" | "dotted" | "double" | "groove" | "ridge" | "outset" | "inset";
197
+ /**
198
+ * Custom stroke style definition
199
+ */
42
200
  type StrokeStyleCustom = {
43
201
  dashArray: Array<TokenValue<"dimension">>;
44
202
  lineCap: LineCap;
45
203
  };
204
+ /**
205
+ * A stroke style that can be either a keyword or custom definition
206
+ */
46
207
  type StrokeStyle = StrokeStyleKeyword | StrokeStyleCustom;
208
+ /**
209
+ * Border token combining color, width, and style
210
+ */
47
211
  type Border = {
48
212
  color: TokenValue<"color">;
49
213
  width: TokenValue<"dimension">;
50
- style: StrokeStyle;
214
+ style: StrokeStyle | Reference<"strokeStyle">;
51
215
  };
216
+ /**
217
+ * Individual shadow definition
218
+ */
52
219
  type ShadowObject = {
53
220
  color: TokenValue<"color">;
54
221
  offsetX: TokenValue<"dimension">;
@@ -57,137 +224,242 @@ type ShadowObject = {
57
224
  spread: TokenValue<"dimension">;
58
225
  inset?: boolean;
59
226
  };
227
+ /**
228
+ * Shadow token that can be single or multiple shadows
229
+ */
60
230
  type Shadow = ShadowObject | ShadowObject[];
231
+ /**
232
+ * Color stop in a gradient
233
+ */
61
234
  type GradientStop = {
62
235
  color: TokenValue<"color">;
63
- position: number;
236
+ position: number | Reference<"number">;
64
237
  };
238
+ /**
239
+ * Gradient defined as a list of color stops
240
+ */
65
241
  type Gradient = GradientStop[];
66
- type TokenMetadata = {
67
- $description?: string;
68
- $extensions?: SugarcubeExtensions;
242
+
243
+ /**
244
+ * Source information for a token, tracking its collection and theme
245
+ */
246
+ type TokenSource = {
247
+ collection: string;
248
+ theme?: string;
249
+ sourcePath: string;
69
250
  };
70
- type SugarcubeExtensions = {
71
- "com.sugarcube": {
72
- color?: ColorMetadata;
73
- fluid?: FluidMetadata;
74
- };
251
+ /**
252
+ * A complete token tree with collection and theme information
253
+ */
254
+ type TokenTree = {
255
+ collection: string;
256
+ theme?: string;
257
+ tokens: TokenGroup;
258
+ sourcePath: string;
75
259
  };
76
- type ColorMetadata = {
77
- format: ColorFormatName;
260
+
261
+ /**
262
+ * Base error type that all other error types extend from.
263
+ * Used as the foundation for all error types in the system.
264
+ */
265
+ type BaseError = {
266
+ message: string;
78
267
  };
79
- type FluidMetadata = {
80
- viewports: {
81
- min: Dimension;
82
- max: Dimension;
83
- };
268
+
269
+ /**
270
+ * A flattened token with its source information and path
271
+ */
272
+ type FlattenedToken<T extends TokenType = TokenType> = NodeMetadata & {
273
+ $type: T;
274
+ $value: TokenValue<T>;
275
+ $path: string;
276
+ $source: TokenSource;
277
+ $originalPath: string;
84
278
  };
85
- type ColorFormatName = "hex" | "rgb" | "hsl" | "p3";
86
- type MetadataMap = {
87
- root: TokenMetadata;
88
- groups: Record<string, TokenMetadata>;
89
- tokens: Record<string, TokenMetadata>;
279
+ /**
280
+ * A map of flattened tokens and metadata by their lookup path
281
+ */
282
+ type FlattenedTokens = {
283
+ [lookupKey: string]: FlattenedToken | NodeMetadata;
90
284
  };
91
- type CSSProperties<T extends TokenType> = T extends SimpleTokenType ? SimpleCSSProperties : T extends AlwaysDecomposedType ? AlwaysDecomposedProperties : T extends OptionallyDecomposedType ? OptionallyDecomposedProperties<T> : T extends StructuralCompositeType ? SimpleCSSProperties : never;
92
- type SimpleCSSProperties = {
93
- value: string | number;
94
- featureValues?: Array<{
95
- query: string;
96
- value: string;
97
- }>;
285
+ /**
286
+ * An error that occurred during token flattening
287
+ */
288
+ type FlattenError = BaseError & {
289
+ path: string;
290
+ source: TokenSource;
98
291
  };
99
- type AlwaysDecomposedProperties = CSSTypographyProperties;
100
- type CSSTypographyProperties = {
101
- "font-family": string;
102
- "font-size": string;
103
- "font-weight"?: number | string;
104
- "letter-spacing"?: string;
105
- "line-height"?: number | string;
292
+
293
+ /**
294
+ * An error that occurred during token validation
295
+ */
296
+ type ValidationError = BaseError & {
297
+ path: string;
298
+ source: TokenSource;
106
299
  };
107
- type OptionallyDecomposedProperties<T extends OptionallyDecomposedType> = T extends "border" ? CSSBorderProperties : T extends "shadow" ? CSSShadowProperties : T extends "gradient" ? CSSGradientProperties : T extends "transition" ? CSSTransitionProperties : never;
108
- type CSSBorderProperties = {
109
- value: string;
110
- split?: {
111
- width: string;
112
- style: string;
113
- color: string;
114
- };
300
+
301
+ /**
302
+ * A resolved token with its final value
303
+ */
304
+ type ResolvedToken<T extends TokenType = TokenType> = NodeMetadata & {
305
+ $type: T;
306
+ $value: RawTokenValue<T>;
307
+ $path: string;
308
+ $source: TokenSource;
309
+ $originalPath: string;
310
+ $resolvedValue: RawTokenValue<T>;
115
311
  };
116
- type CSSShadowProperties = {
117
- value: string;
118
- split?: CSSShadowSplitProperties | CSSShadowSplitProperties[];
312
+ /**
313
+ * A map of resolved tokens by their lookup path
314
+ */
315
+ type ResolvedTokens = {
316
+ [lookupKey: string]: ResolvedToken | NodeMetadata;
119
317
  };
120
- type CSSShadowSplitProperties = {
121
- "offset-x": string;
122
- "offset-y": string;
123
- "blur": string;
124
- "spread": string;
125
- "color": string;
126
- "inset"?: "inset";
318
+ /**
319
+ * Type of resolution error that occurred
320
+ */
321
+ type ResolutionErrorType = "circular" | "missing" | "type-mismatch";
322
+ /**
323
+ * An error that occurred during token resolution
324
+ */
325
+ type ResolutionError = BaseError & {
326
+ type: ResolutionErrorType;
327
+ path: string;
328
+ source: TokenSource;
127
329
  };
128
- type CSSGradientProperties = {
129
- value: string;
130
- split?: {
131
- stops: Array<{
132
- color: string;
133
- position: string;
134
- }>;
135
- };
330
+
331
+ /**
332
+ * A warning that occurred during token normalization
333
+ */
334
+ type NormalizationWarning = {
335
+ type: "warning";
336
+ message: string;
337
+ file: string;
338
+ collection: string;
339
+ theme?: string;
136
340
  };
137
- type CSSTransitionProperties = {
138
- value: string;
139
- split?: {
140
- "duration": string;
141
- "timing-function": string;
142
- "delay"?: string;
143
- };
341
+ /**
342
+ * An error that occurred during token normalization
343
+ */
344
+ type NormalizationError = ValidationError & {
345
+ collection: string;
346
+ theme: string;
144
347
  };
145
- type BaseToken = TokenMetadata & {
146
- $value: TokenValue<TokenType>;
348
+ /**
349
+ * A set of tokens for a theme, including metadata nodes
350
+ */
351
+ type ThemeTokenSet = {
352
+ default: ResolvedTokens;
353
+ [theme: string]: ResolvedTokens;
147
354
  };
148
- type SelfTypedToken<T extends TokenType = TokenType> = BaseToken & {
149
- $type: T;
355
+ /**
356
+ * Normalized tokens organized by collection and theme
357
+ */
358
+ type NormalizedTokens = {
359
+ [collection: string]: ThemeTokenSet;
150
360
  };
151
- type InheritedTypeToken = BaseToken;
152
- type Token<T extends TokenType = TokenType> = SelfTypedToken<T> | InheritedTypeToken;
153
- type UnresolvedToken<T extends TokenType = TokenType> = (SelfTypedToken<T> & {
154
- $path: string;
155
- }) | (InheritedTypeToken & {
156
- $path: string;
157
- });
158
- type ResolvedToken<T extends TokenType = TokenType> = UnresolvedToken<T> & {
159
- $resolvedValue: RawTokenValue<T>;
361
+ /**
362
+ * Result of the normalization process
363
+ */
364
+ type NormalizeResult = {
365
+ tokens: NormalizedTokens;
366
+ errors: NormalizationError[];
367
+ warnings: NormalizationWarning[];
160
368
  };
161
- type ConvertedToken<T extends TokenType = TokenType> = ResolvedToken<T> & {
162
- $type: T;
163
- cssProperties: CSSProperties<T>;
369
+
370
+ /**
371
+ * Result of loading token trees from files or memory
372
+ */
373
+ type LoadResult = {
374
+ trees: TokenTree[];
375
+ errors: LoadError[];
164
376
  };
165
- type DesignTokens = TokenGroup;
166
- type TokenGroup = {
167
- [key: string]: Token | TokenGroup | string | undefined;
168
- } & TokenMetadata;
169
- type FlattenedTokens = {
170
- [path: string]: UnresolvedToken;
377
+ /**
378
+ * Data structure for loading tokens from memory
379
+ */
380
+ type TokenMemoryData = Record<string, {
381
+ collection: string;
382
+ theme?: string;
383
+ content: string;
384
+ }>;
385
+ /**
386
+ * An error that occurred during token loading
387
+ */
388
+ type LoadError = BaseError & {
389
+ file: string;
171
390
  };
172
- type ResolvedTokens = {
173
- [path: string]: ResolvedToken;
391
+
392
+ /**
393
+ * Result of running the tokens-to-CSS pipeline
394
+ */
395
+ type TokensToCSSPipelineResult = {
396
+ output: CSSFileOutput;
397
+ trees: TokenTree[];
398
+ errors: PipelineErrors;
399
+ warnings: PipelineWarnings;
174
400
  };
175
- type ConvertedTokens = {
176
- [path: string]: ConvertedToken;
401
+ /**
402
+ * Common error types that can occur during pipeline execution
403
+ */
404
+ type PipelineErrors = {
405
+ load: LoadError[];
406
+ flatten: FlattenError[];
407
+ validation: ValidationError[];
408
+ resolution: ResolutionError[];
177
409
  };
178
- type ValidationError = {
179
- path: string;
180
- message: string;
410
+ /**
411
+ * Common warning types that can occur during pipeline execution
412
+ */
413
+ type PipelineWarnings = {
414
+ normalization: NormalizationWarning[];
181
415
  };
182
- type ResolutionError = {
183
- type: "circular" | "missing" | "type-mismatch";
184
- path: string;
185
- message: string;
416
+ /**
417
+ * Result of running the validation pipeline
418
+ */
419
+ type ValidationPipelineResult = {
420
+ trees: TokenTree[];
421
+ flattenedTokens: FlattenedTokens;
422
+ resolved: ResolvedTokens;
423
+ errors: PipelineErrors;
424
+ };
425
+ /**
426
+ * Options for loading tokens in the validation pipeline
427
+ */
428
+ type TokenLoader = {
429
+ type: "files";
430
+ paths: SugarcubeConfig;
431
+ } | {
432
+ type: "memory";
433
+ data: TokenMemoryData;
434
+ };
435
+ /**
436
+ * Options for configuring the validation pipeline
437
+ */
438
+ type ValidationPipelineOptions = {
439
+ loader: TokenLoader;
186
440
  };
441
+ /**
442
+ * Result of running the generation pipeline
443
+ */
444
+ type GenerationPipelineResult = {
445
+ output: CSSFileOutput;
446
+ warnings: PipelineWarnings;
447
+ };
448
+
449
+ declare function tokensToCSSPipeline(config: SugarcubeConfig): Promise<TokensToCSSPipelineResult>;
450
+
451
+ declare function validationPipeline(config: SugarcubeConfig, options: ValidationPipelineOptions): Promise<ValidationPipelineResult>;
187
452
 
188
- declare function flatten(tree: DesignTokens): {
453
+ declare function generationPipeline(trees: TokenTree[], resolved: ResolvedTokens, configState: SugarcubeConfig): Promise<GenerationPipelineResult>;
454
+
455
+ declare function loadTreesFromConfig(config: SugarcubeConfig): Promise<LoadResult>;
456
+ declare function loadTreesFromMemory(data: TokenMemoryData): Promise<LoadResult>;
457
+
458
+ declare function validate(tokens: FlattenedTokens): ValidationError[];
459
+
460
+ declare function flatten(trees: TokenTree[]): {
189
461
  tokens: FlattenedTokens;
190
- errors: ValidationError[];
462
+ errors: FlattenError[];
191
463
  };
192
464
 
193
465
  declare function resolve(tokens: FlattenedTokens): {
@@ -196,35 +468,94 @@ declare function resolve(tokens: FlattenedTokens): {
196
468
  };
197
469
 
198
470
  /**
199
- * Converts a set of resolved tokens to CSS-ready converted tokens
200
- * @param tokens - The resolved tokens to convert
201
- * @param metadataMap - Metadata for the token conversion process
202
- * @returns A record of converted tokens with kebab-case keys
203
- * @throws If any token has an unsupported type or is missing required properties
471
+ * A processed token tree that has been filtered to only include tokens
472
+ * from its specific collection and theme, with resolved values
204
473
  */
205
- declare function convert(tokens: ResolvedTokens, metadataMap: MetadataMap): ConvertedTokens;
474
+ type ProcessedTree = {
475
+ collection: string;
476
+ theme?: string;
477
+ tokens: ResolvedTokens;
478
+ };
206
479
 
207
- declare function generateCSS(tokens: ConvertedTokens, options?: {
208
- splitTypes?: OptionallyDecomposedType[];
209
- }): Promise<string>;
480
+ declare function processTrees(trees: TokenTree[], resolved: ResolvedTokens): ProcessedTree[];
210
481
 
211
- type MetadataResult = {
212
- metadata: MetadataMap;
213
- errors: ValidationError[];
482
+ /**
483
+ * A token that has been converted to CSS properties
484
+ */
485
+ type ConvertedToken<T extends TokenType = TokenType> = ResolvedToken<T> & {
486
+ $cssProperties: CSSProperties<T>;
487
+ };
488
+ /**
489
+ * A collection of converted tokens
490
+ */
491
+ type ConvertedTokens = {
492
+ [lookupKey: string]: ConvertedToken | NodeMetadata;
493
+ };
494
+ /**
495
+ * A collection of converted tokens organized by theme
496
+ */
497
+ type ConvertedThemeTokenSet = {
498
+ default: ConvertedTokens;
499
+ [theme: string]: ConvertedTokens;
500
+ };
501
+ /**
502
+ * A collection of converted tokens organized by collection and theme
503
+ */
504
+ type NormalizedConvertedTokens = {
505
+ [collection: string]: ConvertedThemeTokenSet;
214
506
  };
215
- declare function collectMetadata(tree: DesignTokens): MetadataResult;
216
-
217
507
  /**
218
- * This function takes a JSON string representation of a token tree and converts it
219
- * into a DesignTokens object.
220
- *
221
- * @param {string} json - A JSON string representing a token tree structure.
222
- * @returns {DesignTokens} A DesignTokens object representing the parsed token structure.
223
- * @throws {SyntaxError} If the provided JSON string is not valid JSON.
224
- * @throws {TypeError} If the JSON structure doesn't match the expected DesignTokens format.
508
+ * CSS property types for different token types
225
509
  */
226
- declare function parseJson(json: string): DesignTokens;
510
+ type CSSProperties<T extends TokenType> = T extends SimpleTokenType ? SimpleCSSProperties : T extends AlwaysDecomposedType ? AlwaysDecomposedProperties : T extends "border" ? CSSBorderProperties : T extends "shadow" ? CSSShadowProperties : T extends "gradient" ? CSSGradientProperties : T extends "transition" ? CSSTransitionProperties : T extends StructuralCompositeType ? SimpleCSSProperties : never;
511
+ /**
512
+ * Simple CSS properties with a single value
513
+ */
514
+ type SimpleCSSProperties = {
515
+ value: string | number;
516
+ featureValues?: Array<{
517
+ query: string;
518
+ value: string;
519
+ }>;
520
+ };
521
+ /**
522
+ * CSS properties that are always broken down into multiple properties
523
+ */
524
+ type AlwaysDecomposedProperties = CSSTypographyProperties;
525
+ /**
526
+ * CSS properties specific to typography tokens
527
+ */
528
+ type CSSTypographyProperties = {
529
+ "font-family": string;
530
+ "font-size": string;
531
+ "font-weight"?: number | string;
532
+ "letter-spacing"?: string;
533
+ "line-height"?: number | string;
534
+ };
535
+ /**
536
+ * CSS properties for specific token types
537
+ */
538
+ type CSSBorderProperties = {
539
+ value: string;
540
+ };
541
+ type CSSShadowProperties = {
542
+ value: string;
543
+ };
544
+ type CSSGradientProperties = {
545
+ value: string;
546
+ };
547
+ type CSSTransitionProperties = {
548
+ value: string;
549
+ };
227
550
 
228
- declare function validate(tokens: FlattenedTokens, metadata: MetadataMap): ValidationError[];
551
+ declare function convert(tokens: NormalizedTokens, config: SugarcubeConfig): NormalizedConvertedTokens;
552
+
553
+ declare function normalizeTokens(trees: ProcessedTree[]): NormalizeResult;
554
+
555
+ /**
556
+ * Generates CSS variable files from normalized and converted design tokens.
557
+ * Can output either a single combined file or separate files based on configuration.
558
+ */
559
+ declare function generate(tokens: NormalizedConvertedTokens, config: SugarcubeConfig): Promise<CSSGenerationResult>;
229
560
 
230
- export { type MetadataMap, type OptionallyDecomposedType, type ResolutionError, type ResolvedTokens, type ValidationError, collectMetadata, convert, flatten, generateCSS, parseJson, resolve, validate };
561
+ export { type CSSFileOutput, type CSSGenerationResult, type CSSOutputConfig, type ColorConfig, type ColorFormat, type DirectoriesConfig, type FluidConfig, type LoadError, type LoadResult, type OptionsConfig, type OutputConfig, type ResolutionError, type ResolvedToken, type ResolvedTokens, type SugarcubeConfig, type TokenCollection, type TokenCollections, type TokenLoader, type TokenMemoryData, type TokenSource, type TokenTree, type ValidationError, convert, flatten, generate, generationPipeline, loadTreesFromConfig, loadTreesFromMemory, normalizeTokens, processTrees, resolve, tokensToCSSPipeline, validate, validationPipeline };
package/dist/index.js CHANGED
@@ -1,7 +1,13 @@
1
- var K=Object.defineProperty;var n=(e,t)=>K(e,"name",{value:t,configurable:!0});const c={PARSE:{INVALID_INPUT_TYPE:n(e=>`Invalid input: expected string, got ${e}`,"INVALID_INPUT_TYPE"),JSON_PARSE_ERROR:n(e=>`JSON parsing error: ${e}`,"JSON_PARSE_ERROR")},FLATTEN:{INVALID_TOKEN_NAME:n(e=>`Invalid token name '${e}': cannot contain '.', '{', or '}'`,"INVALID_TOKEN_NAME"),INVALID_NODE_STRUCTURE:n(e=>`Invalid node structure at '${e}': expected object`,"INVALID_NODE_STRUCTURE"),MISSING_INHERITED_TYPE:n(e=>`Token at '${e}' has no type (neither explicit nor inherited)`,"MISSING_INHERITED_TYPE"),UNEXPECTED_ERROR:n(e=>`Unexpected error during flattening: ${e}`,"UNEXPECTED_ERROR")},METADATA:{COLLECTION_ERROR:n(e=>`Error collecting metadata: ${e}`,"COLLECTION_ERROR"),INVALID_EXTENSIONS:n(e=>`Invalid extensions at '${e}': expected object, got ${typeof e}`,"INVALID_EXTENSIONS"),INVALID_DESCRIPTION:n(e=>`Invalid description at '${e}': expected string, got ${typeof e}`,"INVALID_DESCRIPTION")},VALIDATE:{INVALID_TOKEN_STRUCTURE:n(e=>`Invalid token at '${e}'. Each token should have "$type" and "$value" properties`,"INVALID_TOKEN_STRUCTURE"),MISSING_TYPE:n(e=>`Token at '${e}' is missing the "$type" property`,"MISSING_TYPE"),MISSING_VALUE:n(e=>`Token at '${e}' is missing the "$value" property`,"MISSING_VALUE"),UNKNOWN_TOKEN_TYPE:n((e,t)=>`Unknown token type '${e}' at '${t}'. Valid types are: color, dimension, fontFamily, fontWeight, duration, cubicBezier, strokeStyle, border, transition, shadow, gradient, typography`,"UNKNOWN_TOKEN_TYPE"),INVALID_COLOR:n((e,t)=>`Invalid color at '${t}': '${e}'. Color should be a valid hex value`,"INVALID_COLOR"),INVALID_DIMENSION:n((e,t)=>`Invalid dimension at '${t}': ${e}. Dimensions should have a numeric value and unit, like { "value": 16, "unit": "px" }`,"INVALID_DIMENSION"),INVALID_DIMENSION_UNIT:n((e,t)=>`Invalid unit at '${t}': ${e}. Unit must be either "px" or "rem"`,"INVALID_DIMENSION_UNIT"),INVALID_FONT_FAMILY:n((e,t)=>`Invalid font family at '${t}': ${e}. Should be a string or array of strings, like "Arial" or ["Arial", "sans-serif"]`,"INVALID_FONT_FAMILY"),INVALID_FONT_WEIGHT:n((e,t)=>`Invalid font weight at '${t}': ${e}. Should be a number between 1-1000 or a keyword like "thin", "light", "normal", "bold"`,"INVALID_FONT_WEIGHT"),INVALID_DURATION:n((e,t)=>`Invalid duration at '${t}': ${e}. Should be like { "value": 300, "unit": "ms" }`,"INVALID_DURATION"),INVALID_DURATION_UNIT:n((e,t)=>`Invalid unit at '${t}': ${e}. Unit must be "ms" or "s"`,"INVALID_DURATION_UNIT"),INVALID_CUBIC_BEZIER:n((e,t)=>`Invalid cubic bezier at '${t}': ${e}. Should be an array of 4 numbers between 0 and 1`,"INVALID_CUBIC_BEZIER"),INVALID_CUBIC_BEZIER_RANGE:n((e,t)=>`Invalid cubic bezier control points at '${t}': ${e}. X values must be between 0 and 1`,"INVALID_CUBIC_BEZIER_RANGE"),INVALID_STROKE_STYLE:n((e,t)=>`Invalid stroke style at '${t}': ${e}. Should be "solid", "dashed", "dotted", etc.`,"INVALID_STROKE_STYLE"),INVALID_STROKE_LINE_CAP:n((e,t)=>`Invalid line cap at '${t}': ${e}. Should be one of: round, butt, square`,"INVALID_STROKE_LINE_CAP"),INVALID_BORDER:n((e,t)=>`Invalid border at '${t}': ${e}. Should have color, width, and style properties`,"INVALID_BORDER"),INVALID_SHADOW:n((e,t)=>`Invalid shadow at '${t}': ${e}. Should have color, offsetX, offsetY properties (blur and spread are optional)`,"INVALID_SHADOW"),INVALID_SHADOW_INSET:n((e,t)=>`Invalid inset value at '${t}': ${e}. Should be true or false`,"INVALID_SHADOW_INSET"),INVALID_TRANSITION:n((e,t)=>`Invalid transition at '${t}': ${e}. Should have duration, delay, and timingFunction properties`,"INVALID_TRANSITION"),INVALID_GRADIENT:n((e,t)=>`Invalid gradient at '${t}': ${e}. Should be an array of color stops with position values between 0 and 1`,"INVALID_GRADIENT"),INVALID_GRADIENT_STOP_POSITION:n((e,t)=>`Invalid gradient stop position at '${t}': ${e}. Position must be between 0 and 1`,"INVALID_GRADIENT_STOP_POSITION"),INVALID_TYPOGRAPHY:n((e,t)=>`Invalid typography at '${t}': ${e}. Should have fontFamily and fontSize (fontWeight, letterSpacing, and lineHeight are optional)`,"INVALID_TYPOGRAPHY"),MISSING_REQUIRED_PROPERTY:n((e,t)=>`Missing required property '${e}' at '${t}'`,"MISSING_REQUIRED_PROPERTY"),INVALID_NUMBER:n((e,t)=>`Invalid number at '${t}': ${e}. Expected a number value`,"INVALID_NUMBER"),INVALID_ARRAY:n((e,t)=>`Invalid array at '${t}': ${e}. Expected an array value`,"INVALID_ARRAY"),MISSING_FLUID_CONFIG:n(e=>`Missing fluid configuration at root level. Token at '${e}' requires fluid viewport settings`,"MISSING_FLUID_CONFIG"),INVALID_FLUID_DIMENSION:n((e,t)=>`Invalid fluid dimension at '${t}': ${e}. Fluid dimensions should have min and max values, like { "min": { "value": 16, "unit": "px" }, "max": { "value": 24, "unit": "px" } }`,"INVALID_FLUID_DIMENSION"),INVALID_VIEWPORT_CONFIG:n((e,t)=>`Invalid viewport configuration at '${t}': ${e}. Viewport config should have min and max dimension values`,"INVALID_VIEWPORT_CONFIG"),MISMATCHED_UNITS:n((e,t,r)=>`Mismatched units at '${r}': min uses '${e}', max uses '${t}'. Both values must use the same unit`,"MISMATCHED_UNITS"),INVALID_FLUID_VALUE_RANGE:n(e=>`Invalid fluid value range at '${e}': min value must be less than max value`,"INVALID_FLUID_VALUE_RANGE"),INVALID_TOKEN_TYPE:n((e,t,r)=>`Invalid token type at '${r}': expected ${e}, got ${t}`,"INVALID_TOKEN_TYPE"),INVALID_TYPE:n((e,t,r)=>`Expected ${e}, received ${typeof t} at '${r}'`,"INVALID_TYPE"),INVALID_ENUM_VALUE:n((e,t,r)=>`Expected value to be one of [${e.join(", ")}], but got ${String(t)} at ${r}`,"INVALID_ENUM_VALUE")},CONVERT:{UNSUPPORTED_TOKEN_TYPE:n(e=>`Unsupported token type: ${e}. Valid types are: color, dimension, fontFamily, fontWeight, duration, cubicBezier, strokeStyle, border, transition, shadow, gradient, typography`,"UNSUPPORTED_TOKEN_TYPE"),MISSING_FLUID_CONFIG:n(e=>`Missing fluid configuration for token at path: ${e}`,"MISSING_FLUID_CONFIG")},RESOLVE:{CIRCULAR_REFERENCE:n((e,t)=>`Circular reference detected: ${e} -> ${t}`,"CIRCULAR_REFERENCE"),REFERENCE_NOT_FOUND:n((e,t)=>`Reference not found: ${t} in ${e}`,"REFERENCE_NOT_FOUND"),TYPE_MISMATCH:n(e=>`Type mismatch in reference resolution at ${e}`,"TYPE_MISMATCH")},GENERATE:{INVALID_CSS_VALUE:n((e,t)=>`Invalid CSS value for property '${e}': ${t}`,"INVALID_CSS_VALUE")}};function X(e){return O(e)}n(X,"flatten");function O(e,t="",r){const o={},i=[];for(const[s,a]of Object.entries(e)){if(s.startsWith("$"))continue;const u=t?`${t}.${s}`:s;if(s.includes(".")||s.includes("{")||s.includes("}")){i.push({path:s,message:c.FLATTEN.INVALID_TOKEN_NAME(s)});continue}if(typeof a!="object"||a===null){i.push({path:u,message:c.FLATTEN.INVALID_NODE_STRUCTURE(u)});continue}const f="$type"in a?a.$type:r;if("$value"in a){if(!f){i.push({path:u,message:c.FLATTEN.MISSING_INHERITED_TYPE(u)});continue}o[u]={$type:f,$value:a.$value,$path:u}}else{const I=O(a,u,f);Object.assign(o,I.tokens),i.push(...I.errors)}}return{tokens:o,errors:i}}n(O,"processTokens");function l(e){return typeof e=="string"&&e.startsWith("{")&&e.endsWith("}")}n(l,"isReference");function m(e,t,r,o){return typeof t=="string"&&l(t)?Q(e,t,r,o):Array.isArray(t)?t.map(i=>m(e,i,r,o)):typeof t=="object"&&t!==null?Object.entries(t).reduce((s,[a,u])=>({...s,[a]:m(`${e}.${a}`,u,r,o)}),{}):t}n(m,"resolveValue");function Z(e){const t={},r=new Set,o=[];for(const[i,s]of Object.entries(e))try{if(!s.$path)continue;t[s.$path]={...s,$resolvedValue:m(s.$path,s.$value,e,r)}}catch(a){const u=a instanceof Error?a.message:String(a);let f,I;u.includes("Circular reference detected")?(f="circular",I=u):u.includes("Reference not found")?(f="missing",I=u):(f="type-mismatch",I=c.RESOLVE.TYPE_MISMATCH(s.$path)),o.push({type:f,path:s.$path,message:I})}return{resolved:t,errors:o}}n(Z,"resolve");function Q(e,t,r,o){const i=t.slice(1,-1);if(o.has(i))throw new Error(`Circular reference detected: ${e} -> ${i}`);const s=r[i];if(!s)throw new Error(`Reference not found: ${i} in ${e}`);o.add(i);const a=m(i,s.$value,r,o);return o.delete(i),a}n(Q,"resolveReferenceChain");function y(e){return["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"].includes(e.toLowerCase())?e:/[\s'"!@#$%^&*()=+[\]{};:|\\/,.<>?~]/.test(e)?`"${e}"`:e}n(y,"quoteFont");const J={thin:100,hairline:100,"extra-light":200,"ultra-light":200,light:300,normal:400,regular:400,book:400,medium:500,"semi-bold":600,"demi-bold":600,bold:700,"extra-bold":800,"ultra-bold":800,black:900,heavy:900,"extra-black":950,"ultra-black":950};function v(e){return l(e)?{value:e}:typeof e=="number"?{value:e}:{value:J[e.toLowerCase()]??e}}n(v,"convertFontWeightToken");function ee(e){if(l(e))return{"font-family":e,"font-size":e};const t={"font-family":l(e.fontFamily)?e.fontFamily:Array.isArray(e.fontFamily)?e.fontFamily.map(r=>y(r)).join(", "):y(e.fontFamily),"font-size":l(e.fontSize)?e.fontSize:`${e.fontSize.value}${e.fontSize.unit}`};return e.fontWeight&&(t["font-weight"]=l(e.fontWeight)?e.fontWeight:v(e.fontWeight).value),e.letterSpacing&&(t["letter-spacing"]=l(e.letterSpacing)?e.letterSpacing:`${e.letterSpacing.value}${e.letterSpacing.unit}`),e.lineHeight&&(t["line-height"]=(l(e.lineHeight),e.lineHeight)),t}n(ee,"convertTypographyToken");function te(e){if(l(e))return{value:e};const t=(l(e.duration),e.duration),r=l(e.timingFunction)?e.timingFunction:`cubic-bezier(${e.timingFunction.join(", ")})`,o=e.delay&&(l(e.delay),e.delay),i={duration:t,"timing-function":r,...o&&{delay:o}};return{value:[t,r,o].filter(Boolean).join(" "),split:i}}n(te,"convertTransitionToken");function re(e){return l(e)?{value:e}:{value:`cubic-bezier(${e.join(", ")})`}}n(re,"convertCubicBezierToken");function ne(e){return l(e)?{value:e}:{value:e}}n(ne,"convertNumberToken");function oe(e){return l(e)?{value:e}:{value:e.toString()}}n(oe,"convertDurationToken");function R(e){return l(e)?{value:e}:typeof e=="string"?{value:e}:{value:`${e.dashArray.map(r=>l(r)?r:`${r.value}${r.unit}`).join(" ")} ${e.lineCap}`}}n(R,"convertStrokeStyleToken");function ie(e){if(l(e))return{value:e};const t=l(e.width)?e.width:`${e.width.value}${e.width.unit}`,r=(l(e.color),e.color);let o;return typeof e.style=="string"?o=e.style:o=R(e.style).value,{value:`${t} ${o} ${r}`,split:{width:t,style:o,color:r}}}n(ie,"convertBorderToken");function C(e){const t=l(e.offsetX)?e.offsetX:`${e.offsetX.value}${e.offsetX.unit}`,r=l(e.offsetY)?e.offsetY:`${e.offsetY.value}${e.offsetY.unit}`,o=l(e.blur)?e.blur:`${e.blur.value}${e.blur.unit}`,i=l(e.spread)?e.spread:`${e.spread.value}${e.spread.unit}`,s=(l(e.color),e.color),a={color:s,"offset-x":t,"offset-y":r,blur:o,spread:i,...e.inset&&{inset:"inset"}};return{value:`${e.inset?"inset ":""}${t} ${r} ${o} ${i} ${s}`,split:a}}n(C,"convertSingleShadow");function se(e){if(l(e))return{value:e};if(!Array.isArray(e)){const r=C(e);return{value:r.value,split:[r.split]}}const t=e.map(C);return{value:t.map(r=>r.value).join(", "),split:t.map(r=>r.split)}}n(se,"convertShadowToken");function ae(e){if(l(e))return{value:e};const t=e.map(r=>({color:(l(r.color),r.color),position:`${r.position}%`}));return{value:`linear-gradient(${t.map(r=>`${r.color} ${r.position}`).join(", ")})`,split:{stops:t}}}n(ae,"convertGradientToken");function ce(e){return l(e)?{value:e}:{value:Array.isArray(e)?e.map(r=>y(r)).join(", "):y(e)}}n(ce,"convertFontFamilyToken");function ue(e){return l(e)?{value:e}:{value:`${e.value}${e.unit}`}}n(ue,"convertDimensionToken");function le(e,t,r){if(e in r.tokens&&r.tokens[e]?.[t]!==void 0)return r.tokens[e][t];const o=e.split(".");for(;o.length>0;){const i=o.join(".");if(i in r.groups&&r.groups[i]&&t in r.groups[i])return r.groups[i][t];o.pop()}return r.root[t]}n(le,"getMetadataValue");function F(e,t){return le(e,"$extensions",t)?.["com.sugarcube"]}n(F,"getExtensions");function M(e,t){return F(e,t)?.fluid}n(M,"getFluidConfig");function fe(e,t){return F(e,t)?.color?.format}n(fe,"getColorFormat");function A(e,t=16){switch(e.unit){case"px":return e.value;case"rem":return e.value*t;default:throw new Error(`Unsupported unit: ${e.unit}. Fluid dimensions must use 'px' or 'rem'`)}}n(A,"normalizeToPixels");function de(e,t){if(!t?.viewports)throw new Error("Fluid metadata is required for fluid dimensions");const{min:r,max:o}=e,{viewports:i}=t,s=16,a=A(r,s),u=A(o,s),f=A(i.min,s),I=A(i.max,s);if(a===u)return{value:`${a/s}rem`};const S=a/s,V=u/s,b=f/s,q=I/s,L=(V-S)/(q-b),H=-1*b*L+S;return{value:`clamp(${S}rem, ${H.toFixed(2)}rem + ${(L*100).toFixed(2)}vw, ${V}rem)`}}n(de,"convertFluidDimension");function Ie(e,t){if(l(e))return{value:e};const r=M(t.path,t.metadataMap);if(!r)throw new Error(c.CONVERT.MISSING_FLUID_CONFIG(t.path));return de(e,r)}n(Ie,"convertFluidDimensionToken");function pe(e,t,r){const o=Math.max(e,t,r),i=Math.min(e,t,r);let s=0,a=0;const u=(o+i)/2;if(o!==i){const f=o-i;switch(a=u>.5?f/(2-o-i):f/(o+i),o){case e:s=(t-r)/f+(t<r?6:0);break;case t:s=(r-e)/f+2;break;case r:s=(e-t)/f+4;break}s*=60}return[Math.round(s),Math.round(a*100),Math.round(u*100)]}n(pe,"rgbToHsl");const g=n(e=>Number.isInteger(e)?e.toString():Number(e.toFixed(3)).toString(),"formatNumber"),$e={hex:{type:"standard",convert:n((e,t,r,o)=>{const i=n(s=>Math.round(s*255).toString(16).padStart(2,"0"),"toHex");return`#${i(e)}${i(t)}${i(r)}${o<1?i(o):""}`},"convert")},rgb:{type:"standard",convert:n((e,t,r,o)=>{const i=[e,t,r].map(s=>Math.round(s*255));return o===1?`rgb(${i.join(", ")})`:`rgba(${i.join(", ")}, ${g(o)})`},"convert")},hsl:{type:"standard",convert:n((e,t,r,o)=>{const[i,s,a]=pe(e,t,r);return o===1?`hsl(${i}, ${s}%, ${a}%)`:`hsla(${i}, ${s}%, ${a}%, ${g(o)})`},"convert")},p3:{type:"conditional",featureQuery:"@supports (color: color(display-p3 1 1 1))",convert:n((e,t,r,o)=>{const i=[e,t,r].map(g).join(" ");return o===1?`color(display-p3 ${i})`:`color(display-p3 ${i} / ${g(o)})`},"convert")}};function me(e,t){if(l(e))return{value:e};const r=fe(t.path,t.metadataMap)||"hex";if(r==="hex")return{value:e};const o=$e[r];if(!o)return{value:e};const i=e.substring(1),s=parseInt(i.substring(0,2),16)/255,a=parseInt(i.substring(2,4),16)/255,u=parseInt(i.substring(4,6),16)/255,f=i.length===8?parseInt(i.substring(6,8),16)/255:1;return o.type==="conditional"?{value:e,featureValues:[{query:o.featureQuery,value:o.convert(s,a,u,f)}]}:{value:o.convert(s,a,u,f)}}n(me,"convertColorToken");const ye={duration:oe,number:ne,cubicBezier:re,color:me,dimension:ue,fluidDimension:Ie,typography:ee,border:ie,shadow:se,gradient:ae,transition:te,strokeStyle:R,fontFamily:ce,fontWeight:v},Ae=new Set(["$description","$extensions"]),k=new Map;function x(e){const t=k.get(e);if(t)return t;const r=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase();return k.set(e,r),r}n(x,"toKebabCase");function ge(e,t){const r=ye[e.$type];if(!r)throw new Error(c.CONVERT.UNSUPPORTED_TOKEN_TYPE(e.$type));return{$type:e.$type,$value:e.$value,$path:e.$path,$resolvedValue:e.$resolvedValue,cssProperties:r(e.$value,t)}}n(ge,"convertSingleToken");function Te(e,t){const r={};for(const[o,i]of Object.entries(e)){if(Ae.has(o)||i===void 0)continue;const s={metadataMap:t,path:o};if(!("$type"in i))throw new Error(`Token at path ${o} is missing $type property`);if(i.$type==="fluidDimension"&&!t)throw new Error(c.CONVERT.MISSING_FLUID_CONFIG(o));const a=o.split(".").map(x).join("-");r[a]=ge(i,s)}return r}n(Te,"convert");function Ee(e){return typeof e=="object"&&e!==null&&typeof e.query=="string"&&typeof e.value=="string"}n(Ee,"isFeatureValue");function Se(e){return typeof e!="object"||e===null||!("value"in e)||typeof e.value!="string"&&typeof e.value!="number"?!1:"featureValues"in e?Array.isArray(e.featureValues)?e.featureValues.every(Ee):!1:!0}n(Se,"isSimpleCSSProperties");function Ne(e){return!!(typeof e=="string"||typeof e=="number"||Se(e))}n(Ne,"isValidCSSValue");const N="(color: color(display-p3 1 1 1))",he=[{query:N,test:n(e=>e.$type!=="color"?!1:e.cssProperties.featureValues?.some(r=>r.query===N)??!1,"test"),convertToCSSVars:n((e,t)=>{const o=t.cssProperties.featureValues?.find(i=>i.query===N);return o?[{name:`--${De(e)}`,value:o.value}]:[]},"convertToCSSVars")}];function De(e){return e.split(".").join("-")}n(De,"formatCSSVarPath");function j(e){return typeof e=="number"?e.toString():e.replace(/\{([^}]+)\}/g,(t,r)=>`var(--${r.split(".").map(x).join("-")})`)}n(j,"convertReferenceToCSSVar");function $(e,t){if(!Ne(t))throw new Error(c.GENERATE.INVALID_CSS_VALUE(e,String(t)));const r=typeof t=="object"&&"value"in t?j(t.value):j(t);return{name:`--${e}`,value:r}}n($,"createSingleCSSVar");function _e(e,t){if(!("split"in t)||!t.split)return{base:"value"in t?[$(e,t.value)]:Object.entries(t).map(([r,o])=>$(`${e}-${r}`,o))};if(Array.isArray(t.split)){const r=t.split.length>1;return{base:t.split.flatMap((o,i)=>Object.entries(o).map(([s,a])=>{const u=r?`-${i+1}-${s}`:`-${s}`;return $(`${e}${u}`,a)}))}}return{base:Object.entries(t.split).map(([r,o])=>$(`${e}-${r}`,o))}}n(_e,"convertSplitTokenToCSSVars");function Ve(e){return{name:`--${e}`,value:[`var(--${e}-width)`,`var(--${e}-style)`,`var(--${e}-color)`].join(" ")}}n(Ve,"createBorderCSSVar");function U(e,t,r){return[`var(--${e}${t?`-${r+1}`:""}-offset-x)`,`var(--${e}${t?`-${r+1}`:""}-offset-y)`,`var(--${e}${t?`-${r+1}`:""}-blur)`,`var(--${e}${t?`-${r+1}`:""}-spread)`,`var(--${e}${t?`-${r+1}`:""}-color)`].join(" ")}n(U,"createShadowCSSVar");function be(e,t,r){if("split"in r){if(e!=="shadow")return e==="border"?Ve(t):void 0;if(Array.isArray(r.split)){const o=r.split.length>1,i=r.split.map((s,a)=>U(t,o,a)).join(", ");return{name:`--${t}`,value:i}}return{name:`--${t}`,value:U(t,!1,0)}}}n(be,"createCombinedCSSVar");function Le(e,t,r){if(!(t.$type==="typography"||r.includes(t.$type)))return[$(e,t.cssProperties)];const{base:i}=_e(e,t.cssProperties),s=be(t.$type,e,t.cssProperties);return s?[...i,s]:i}n(Le,"convertTokenToCSSVarSet");function Oe(e){const t=`${e.root.selector}{${e.root.vars.map(o=>`${o.name}:${o.value}`).join(";")}}`,r=e.features.map(o=>`@supports ${o.query}{${e.root.selector}{${o.vars.map(i=>`${i.name}:${i.value}`).join(";")}}}`).join("");return t+r}n(Oe,"convertCSSVarsToString");async function ve(e,t={}){const r=Object.entries(e).filter(([s])=>s!=="$extensions").flatMap(([s,a])=>Le(s,a,t.splitTypes||[])),o=he.map(s=>{const u=Object.entries(e).filter(([f,I])=>s.test(I)).flatMap(([f,I])=>s.convertToCSSVars(f,I));return u.length>0?{query:s.query,vars:u}:null}).filter(s=>s!==null),i=Oe({root:{selector:":root",vars:r},features:o});return Re(i)}n(ve,"generateCSS");function Re(e){return e=e.replace(/{/g,`{
2
- `),e=e.replace(/([^{]);/g,`$1;
3
- `),e=e.replace(/}(?!$)/g,`
4
- }
1
+ var ae=Object.defineProperty;var o=(e,t)=>ae(e,"name",{value:t,configurable:!0});import{readFile as ce}from"node:fs/promises";import le from"fast-glob";import ue,{relative as b}from"node:path";import{converter as S,formatHex as P}from"culori";const l={LOAD:{FILE_NOT_FOUND:o(e=>`File not found: ${e}`,"FILE_NOT_FOUND"),INVALID_JSON:o((e,t)=>`Invalid JSON in file ${e}: ${t}`,"INVALID_JSON"),READ_ERROR:o((e,t)=>`Error reading file ${e}: ${t}`,"READ_ERROR"),INVALID_SOURCE:o(e=>`Invalid source: expected string or array of file descriptors, got ${typeof e}`,"INVALID_SOURCE"),NO_FILES_FOUND:o(e=>`No files found matching pattern: ${e}.`,"NO_FILES_FOUND"),GLOB_ERROR:o((e,t)=>`Error resolving glob pattern ${e}: ${t}`,"GLOB_ERROR"),EMPTY_CONFIG:o(()=>"No token files specified in sugarcube.config.json","EMPTY_CONFIG")},PARSE:{INVALID_INPUT_TYPE:o(e=>`Invalid input: expected string, got ${e}`,"INVALID_INPUT_TYPE"),JSON_PARSE_ERROR:o(e=>`JSON parsing error: ${e}`,"JSON_PARSE_ERROR"),UNEXPECTED_ERROR:o(e=>`Unexpected error during parsing: ${e}`,"UNEXPECTED_ERROR")},FLATTEN:{INVALID_TOKEN_NAME:o(e=>`Invalid token name '${e}': cannot contain '.', '{', or '}'`,"INVALID_TOKEN_NAME"),INVALID_NODE_STRUCTURE:o(e=>`Invalid node structure at ${e}: expected object`,"INVALID_NODE_STRUCTURE"),MISSING_INHERITED_TYPE:o(e=>`Token at ${e} has no $type (neither explicit nor inherited)`,"MISSING_INHERITED_TYPE"),MISSING_DOLLAR_PREFIX:o(e=>`Token at ${e} is using 'value' or 'type' without the required '$' prefix. Use '$value' and '$type' instead.`,"MISSING_DOLLAR_PREFIX")},METADATA:{COLLECTION_ERROR:o(e=>`Error collecting metadata: ${e}`,"COLLECTION_ERROR"),INVALID_EXTENSIONS:o(e=>`Invalid extensions at ${e}: expected object, got ${typeof e}`,"INVALID_EXTENSIONS"),INVALID_DESCRIPTION:o(e=>`Invalid description at ${e}: expected string, got ${typeof e}`,"INVALID_DESCRIPTION")},VALIDATE:{MISSING_TYPE:o(e=>`Token at '${e}' is missing the "$type" property`,"MISSING_TYPE"),MISSING_VALUE:o(e=>`Token at '${e}' is missing the "$value" property`,"MISSING_VALUE"),UNKNOWN_TOKEN_TYPE:o((e,t)=>`Unknown token type '${e}' at ${t}. Valid types are: color, dimension, fontFamily, fontWeight, duration, cubicBezier, strokeStyle, border, transition, shadow, gradient, typography`,"UNKNOWN_TOKEN_TYPE"),INVALID_COLOR:o((e,t)=>`Invalid color at ${t}: '${e}'. Color should be a valid hex value`,"INVALID_COLOR"),INVALID_DIMENSION:o((e,t)=>`Invalid dimension at '${t}': ${e}. Dimensions should have a numeric value and unit, like { "value": 16, "unit": "px" }`,"INVALID_DIMENSION"),INVALID_DIMENSION_UNIT:o((e,t)=>`Invalid unit at ${t}': '${e}'. Unit must be either "px" or "rem"`,"INVALID_DIMENSION_UNIT"),INVALID_FONT_FAMILY:o((e,t)=>`Invalid font family at '${t}': ${e}. Should be a string or array of strings, like "Arial" or ["Arial", "sans-serif"]`,"INVALID_FONT_FAMILY"),INVALID_FONT_WEIGHT:o((e,t)=>`Invalid font weight at '${t}': ${e}. Should be a number between 1-1000 or a keyword like "thin", "light", "normal", "bold"`,"INVALID_FONT_WEIGHT"),INVALID_DURATION:o((e,t)=>`Invalid duration at '${t}': ${e}. Should be like { "value": 300, "unit": "ms" }`,"INVALID_DURATION"),INVALID_DURATION_UNIT:o((e,t)=>`Invalid unit at ${t}: "${e}". Unit must be "ms" or "s"`,"INVALID_DURATION_UNIT"),INVALID_CUBIC_BEZIER:o((e,t)=>`Invalid cubic bezier at ${t}: "${e}". Should be an array of 4 numbers between 0 and 1`,"INVALID_CUBIC_BEZIER"),INVALID_CUBIC_BEZIER_RANGE:o((e,t)=>`Invalid cubic bezier control points at '${t}': ${e}. X values must be between 0 and 1`,"INVALID_CUBIC_BEZIER_RANGE"),INVALID_STROKE_STYLE:o((e,t)=>`Invalid stroke style at ${t}: "${e}". Should be "solid", "dashed", "dotted", etc.`,"INVALID_STROKE_STYLE"),INVALID_STROKE_LINE_CAP:o((e,t)=>`Invalid line cap at ${t}: "${e}". Should be one of: round, butt, square`,"INVALID_STROKE_LINE_CAP"),INVALID_BORDER:o((e,t)=>`Invalid border at ${t}: "${e}". Should have color, width, and style properties`,"INVALID_BORDER"),INVALID_SHADOW:o((e,t)=>`Invalid shadow at ${t}: "${e}". Should have color, offsetX, offsetY properties (blur and spread are optional)`,"INVALID_SHADOW"),INVALID_SHADOW_INSET:o((e,t)=>`Invalid inset value at ${t}: "${e}". Should be true or false`,"INVALID_SHADOW_INSET"),INVALID_TRANSITION:o((e,t)=>`Invalid transition at ${t}: "${e}". Should have duration, delay, and timingFunction properties`,"INVALID_TRANSITION"),INVALID_GRADIENT:o((e,t)=>`Invalid gradient at ${t}: "${e}". Should be an array of color stops with position values between 0 and 1`,"INVALID_GRADIENT"),INVALID_GRADIENT_STOP_POSITION:o((e,t)=>`Invalid gradient stop position at ${t}: "${e}". Position must be between 0 and 1`,"INVALID_GRADIENT_STOP_POSITION"),INVALID_TYPOGRAPHY:o((e,t)=>`Invalid typography at ${t}: "${e}". Should have fontFamily and fontSize (fontWeight, letterSpacing, and lineHeight are optional)`,"INVALID_TYPOGRAPHY"),MISSING_REQUIRED_PROPERTY:o((e,t)=>`Missing required property '${e}' at ${t}`,"MISSING_REQUIRED_PROPERTY"),INVALID_NUMBER:o((e,t)=>`Invalid number at ${t}: "${e}". Expected a number value`,"INVALID_NUMBER"),INVALID_ARRAY:o((e,t)=>`Invalid array at ${t}: "${e}". Expected an array value`,"INVALID_ARRAY"),MISSING_FLUID_CONFIG:o(e=>`Missing fluid configuration. Token at ${e} requires fluid viewport settings.`,"MISSING_FLUID_CONFIG"),INVALID_FLUID_DIMENSION:o((e,t)=>`Invalid fluid dimension at ${t}: "${e}". Fluid dimensions should have min and max values, like { "min": { "value": 16, "unit": "px" }, "max": { "value": 24, "unit": "px" } }`,"INVALID_FLUID_DIMENSION"),INVALID_VIEWPORT_CONFIG:o((e,t)=>`Invalid viewport configuration at ${t}: "${e}". Viewport config should have min and max dimension values`,"INVALID_VIEWPORT_CONFIG"),MISMATCHED_UNITS:o((e,t,n)=>`Mismatched units at ${n}: min uses '${e}', max uses '${t}'. Both values must use the same unit`,"MISMATCHED_UNITS"),INVALID_FLUID_VALUE_RANGE:o(e=>`Invalid fluid value range at ${e}: min value must be less than max value`,"INVALID_FLUID_VALUE_RANGE"),INVALID_TOKEN_TYPE:o((e,t,n)=>`Invalid token type at ${n}: expected ${e}, got ${t}`,"INVALID_TOKEN_TYPE"),INVALID_TYPE:o((e,t,n)=>`Expected ${e}, received ${typeof t} at ${n}`,"INVALID_TYPE"),INVALID_ENUM_VALUE:o((e,t,n)=>`Expected value to be one of [${e.join(", ")}], but got ${String(t)} at ${n}`,"INVALID_ENUM_VALUE")},RESOLVE:{CIRCULAR_REFERENCE:o((e,t)=>`Circular reference detected: ${e} -> ${t}`,"CIRCULAR_REFERENCE"),REFERENCE_NOT_FOUND:o((e,t)=>`Reference not found: ${t} in ${e}`,"REFERENCE_NOT_FOUND"),TYPE_MISMATCH:o(e=>`Type mismatch in reference resolution at ${e}`,"TYPE_MISMATCH")},NORMALIZE:{DUPLICATE_FILE_WARNING:o((e,t)=>`Warning: File '${e}' is assigned to multiple collections without modes (in '${t}'). This will create duplicate CSS variables in :root since collections without modes default to root scope.`,"DUPLICATE_FILE_WARNING"),DUPLICATE_MODE_WARNING:o((e,t,n)=>`Warning: File '${e}' is assigned to multiple modes in collection '${t}' (in '${n}'). This means the same token values will be duplicated across different theme selectors.`,"DUPLICATE_MODE_WARNING")},GENERATE:{INVALID_CSS_VALUE:o((e,t)=>`Invalid CSS value for property '${e}': ${t}`,"INVALID_CSS_VALUE"),INVALID_VARIABLE_NAME:o((e,t)=>`Invalid CSS variable name at '${e}': ${t}`,"INVALID_VARIABLE_NAME")}};async function U(e){const t={files:[],errors:[]};for(const n of e)try{const r=!n.includes("*")&&!n.endsWith(".json")?ue.join(n,"**/*.json"):n,i=await le(r,{absolute:!0,onlyFiles:!0});if(i.length===0){t.errors.push({pattern:n,error:l.LOAD.NO_FILES_FOUND(n)});continue}t.files.push(...i)}catch(r){t.errors.push({pattern:n,error:l.LOAD.GLOB_ERROR(n,r instanceof Error?r.message:"Unknown error")})}return t}o(U,"resolveFiles");async function G(e){try{const t=await ce(e,"utf-8");return JSON.parse(t)}catch(t){throw t instanceof Error?t instanceof SyntaxError?new Error(l.LOAD.INVALID_JSON(e,t.message)):"code"in t&&t.code==="ENOENT"?new Error(l.LOAD.FILE_NOT_FOUND(e)):new Error(l.LOAD.READ_ERROR(e,t.message)):new Error(l.LOAD.READ_ERROR(e,"Unknown error"))}}o(G,"loadTree");function fe(e){const t=new Set;return e.themes&&Object.values(e.themes).forEach(n=>{n.forEach(r=>t.add(r))}),t}o(fe,"collectThemePaths");async function _(e){const t=[],n=[],r=Array.isArray(e.tokens)?{default:{source:e.tokens,type:"custom"}}:"source"in e.tokens?{default:e.tokens}:e.tokens;for(const[i,s]of Object.entries(r)){const a=fe(s),{files:c,errors:u}=await U(Array.isArray(s.source)?s.source:[s.source]);if(u.length>0){t.push(...u.map(f=>({file:f.pattern,message:f.error})));continue}for(const f of c){const h=b(process.cwd(),f);if(!a.has(h))try{const d=await G(f),m={collection:i,tokens:d,sourcePath:h};n.push(m)}catch(d){t.push({file:f,message:d instanceof Error?d.message:"Unknown error"})}}if(s.themes)for(const[f,h]of Object.entries(s.themes))try{const{files:d,errors:m}=await U(h);if(m.length>0){t.push(...m.map(I=>({file:I.pattern,message:I.error})));continue}for(const I of d)try{const y=await G(I),A={collection:i,theme:f,tokens:y,sourcePath:b(process.cwd(),I)};n.push(A)}catch(y){t.push({file:I,message:y instanceof Error?y.message:"Unknown error"})}}catch(d){t.push({file:h.join(", "),message:d instanceof Error?d.message:"Unknown error"})}}return{trees:n,errors:t}}o(_,"loadTreesFromConfig");async function Y(e){const t=[],n=[],r=new Map;for(const[i,{collection:s,theme:a,content:c}]of Object.entries(e)){r.has(s)||r.set(s,new Map);const u=r.get(s);u.has(a)||u.set(a,[]),u.get(a).push({content:c,path:i})}for(const[i,s]of r)for(const[a,c]of s)for(const{content:u,path:f}of c)try{const h=JSON.parse(u);t.push({collection:i,theme:a,tokens:h,sourcePath:b(process.cwd(),f)})}catch(h){n.push({file:f,message:`Failed to parse JSON content: ${h.message}`})}return{trees:t,errors:n}}o(Y,"loadTreesFromMemory");function de(e){if(typeof e!="object"||e===null||"$value"in e)return!1;const t="value"in e,n="type"in e;if(t&&n)return!0;if(t){const r=e.value;return typeof r=="string"||typeof r=="number"||Array.isArray(r)}return!1}o(de,"looksLikeUnprefixedToken");function pe(e,t){const n={},r=[];function i(a=[]){const c=[t.collection];return t.theme&&c.push(t.theme),a.length>0&&c.push(a.join(".")),c.join(".")}o(i,"createLookupKey"),(e.$description||e.$extensions)&&(n[i()]={$description:e.$description,$extensions:e.$extensions});function s(a,c=[],u){if(c.length>0&&(a.$description||a.$extensions)&&(n[i(c)]={$description:a.$description,$extensions:a.$extensions}),"$value"in a)return;const f=a.$type||u,h=Object.keys(a).filter(d=>!d.startsWith("$"));for(const d of h){const m=a[d],I=[...c,d];if(de(m)){r.push({path:I.join("."),source:t,message:l.FLATTEN.MISSING_DOLLAR_PREFIX(I.join("."))});continue}if(d.includes(".")||d.includes("{")||d.includes("}")){r.push({path:I.join("."),source:t,message:l.FLATTEN.INVALID_TOKEN_NAME(d)});continue}if("$value"in m){if(!f&&!m.$type){r.push({path:I.join("."),source:t,message:l.FLATTEN.MISSING_INHERITED_TYPE(I.join("."))});continue}n[i(I)]={...m,$type:m.$type||f,$path:I.join("."),$source:{collection:t.collection,theme:t.theme,sourcePath:t.sourcePath},$originalPath:I.join(".")}}else s(m,I,f)}}return o(s,"processNode"),s(e),{tokens:n,errors:r}}o(pe,"flattenTree");function L(e){return e.reduce((t,n)=>{const{tokens:r,errors:i}=pe(n.tokens,{collection:n.collection,theme:n.theme,sourcePath:n.sourcePath});return{tokens:{...t.tokens,...r},errors:[...t.errors,...i]}},{tokens:{},errors:[]})}o(L,"flatten");const he={isObject:o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObject")};function p(e){return typeof e=="string"&&e.startsWith("{")&&e.endsWith("}")}o(p,"isReference");function $(e,t,n,r){if(p(t))return[];switch(e.type){case"object":return Ie(e,t,n,r);case"union":return $e(e,t,n,r);case"array":return ye(e,t,n,r);default:return me(e,t,n,r)}}o($,"validateSchema");function me(e,t,n,r){return typeof t!==e.type?[{path:n,message:e.errorMessage?.(t,n)||l.VALIDATE.INVALID_TYPE(e.type,t,n),source:r}]:e.validate?.(t,n,r)??[]}o(me,"validateSimpleValue");function Ie(e,t,n,r){if(!he.isObject(t))return[{path:n,message:e.errorMessage?.(t,n)||l.VALIDATE.INVALID_TYPE("object",t,n),source:r}];const i=[],s=t;if(e.required)for(const a of e.required)a in s||i.push({path:`${n}.${a}`,message:l.VALIDATE.MISSING_REQUIRED_PROPERTY(a,n),source:r});for(const[a,c]of Object.entries(e.properties))a in s&&i.push(...$(c,s[a],`${n}.${a}`,r));return i}o(Ie,"validateObject");function $e(e,t,n,r){let i=[],s=1/0;for(const a of e.oneOf){if(a.type==="string"&&typeof t!="string"||a.type==="object"&&typeof t!="object")continue;const c=$(a,t,n,r);if(c.length===0)return e.validate?.(t,n,r)??[];c.length<s&&(i=c,s=c.length)}return s===1/0?[{path:n,message:l.VALIDATE.INVALID_TYPE(e.oneOf.map(a=>a.type).join(" or "),t,n),source:r}]:i}o($e,"validateUnion");function ye(e,t,n,r){return Array.isArray(t)?e.validate?.(t,n,r)??[]:[{path:n,message:e.errorMessage?.(t,n)||l.VALIDATE.INVALID_TYPE("array",t,n),source:r}]}o(ye,"validateArray");const E={tokenType:"color",schema:{type:"string",errorMessage:o((e,t)=>l.VALIDATE.INVALID_COLOR(e,t),"errorMessage"),validate:o((e,t,n)=>/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(e)?[]:[{path:t,message:l.VALIDATE.INVALID_COLOR(e,t),source:n}],"validate")}};function ge(e,t,n){return $(E.schema,e,t,n)}o(ge,"validateColor");const T={tokenType:"number",schema:{type:"number",errorMessage:o((e,t)=>l.VALIDATE.INVALID_NUMBER(e,t),"errorMessage"),validate:o((e,t,n)=>typeof e!="number"||isNaN(e)?[{path:t,message:l.VALIDATE.INVALID_NUMBER(e,t),source:n}]:[],"validate")}};function Ae(e,t,n){return $(T.schema,e,t,n)}o(Ae,"validateNumber");const g={tokenType:"dimension",schema:{type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_DIMENSION(e,t),"errorMessage"),properties:{value:T.schema,unit:{type:"string",validate:o((e,t,n)=>typeof e!="string"||!["px","rem"].includes(e)?[{path:t,message:l.VALIDATE.INVALID_DIMENSION_UNIT(e,t),source:n}]:[],"validate")}},required:["value","unit"]}};function Ee(e,t,n){return $(g.schema,e,t,n)}o(Ee,"validateDimension");const z={tokenType:"fontFamily",schema:{type:"union",oneOf:[{type:"string",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")},{type:"array",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage"),validate:o((e,t,n)=>e.every(i=>typeof i=="string")?[]:[{path:t,message:l.VALIDATE.INVALID_FONT_FAMILY(e,t),source:n}],"validate")}],errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")}};function Te(e,t,n){return $(z.schema,e,t,n)}o(Te,"validateFontFamily");const Ne=["thin","hairline","extra-light","ultra-light","light","normal","regular","book","medium","semi-bold","demi-bold","bold","extra-bold","ultra-bold","black","heavy","extra-black","ultra-black"],W={tokenType:"fontWeight",schema:{type:"union",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),oneOf:[{type:"number",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:o((e,t,n)=>e<1||e>1e3?[{path:t,message:l.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}]:[],"validate")},{type:"string",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:o((e,t,n)=>Ne.includes(e.toLowerCase())?[]:[{path:t,message:l.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}],"validate")}]}};function De(e,t,n){return $(W.schema,e,t,n)}o(De,"validateFontWeight");const be=["ms","s"],V={tokenType:"duration",schema:{type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_DURATION(e,t),"errorMessage"),properties:{value:T.schema,unit:{type:"string",validate:o((e,t,n)=>be.includes(e)?[]:[{path:t,message:l.VALIDATE.INVALID_DURATION_UNIT(e,t),source:n}],"validate")}},required:["value","unit"]}};function Se(e,t,n){return $(V.schema,e,t,n)}o(Se,"validateDuration");const B={tokenType:"cubicBezier",schema:{type:"array",errorMessage:o((e,t)=>l.VALIDATE.INVALID_CUBIC_BEZIER(e,t),"errorMessage"),validate:o((e,t,n)=>{const r=e;if(r.length!==4||!r.every(a=>typeof a=="number"))return[{path:t,message:l.VALIDATE.INVALID_CUBIC_BEZIER(e,t),source:n}];const[i,,s]=r;return i<0||i>1||s<0||s>1?[{path:t,message:l.VALIDATE.INVALID_CUBIC_BEZIER_RANGE(e,t),source:n}]:[]},"validate")}};function _e(e,t,n){return $(B.schema,e,t,n)}o(_e,"validateCubicBezier");const Le={tokenType:"typography",schema:{type:"object",properties:{fontFamily:z.schema,fontSize:g.schema,letterSpacing:g.schema,lineHeight:T.schema,fontWeight:W.schema},required:["fontFamily","fontSize"],errorMessage:o((e,t)=>l.VALIDATE.INVALID_TYPOGRAPHY(e,t),"errorMessage")}};function Ve(e,t,n){return $(Le.schema,e,t,n)}o(Ve,"validateTypography");const Oe=["solid","dashed","dotted","double","groove","ridge","outset","inset"],ve=["round","butt","square"],Fe={type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_STROKE_STYLE(e,t),"errorMessage"),properties:{dashArray:{type:"array",validate:o((e,t,n)=>{const r=e,i=[];return r.forEach((s,a)=>{typeof s!="string"&&i.push(...$(g.schema,s,`${t}.${a}`,n))}),i},"validate")},lineCap:{type:"string",validate:o((e,t,n)=>ve.includes(e)?[]:[{path:t,message:l.VALIDATE.INVALID_STROKE_LINE_CAP(e,t),source:n}],"validate")}},required:["dashArray","lineCap"]},H={tokenType:"strokeStyle",schema:{type:"union",oneOf:[{type:"string",validate:o((e,t,n)=>!Oe.includes(e)&&typeof e=="string"?[{path:t,message:l.VALIDATE.INVALID_STROKE_STYLE(e,t),source:n}]:[],"validate")},Fe]}};function ke(e,t,n){return $(H.schema,e,t,n)}o(ke,"validateStrokeStyle");const Re={tokenType:"border",schema:{type:"object",properties:{color:E.schema,width:g.schema,style:H.schema},required:["color","width","style"],errorMessage:o((e,t)=>l.VALIDATE.INVALID_BORDER(e,t),"errorMessage")}};function we(e,t,n){return $(Re.schema,e,t,n)}o(we,"validateBorder");const Ce={tokenType:"transition",schema:{type:"object",properties:{duration:V.schema,delay:V.schema,timingFunction:B.schema},required:["duration","delay","timingFunction"],errorMessage:o((e,t)=>l.VALIDATE.INVALID_TRANSITION(e,t),"errorMessage")}};function xe(e,t,n){return $(Ce.schema,e,t,n)}o(xe,"validateTransition");const q={tokenType:"shadow",schema:{type:"object",properties:{color:E.schema,offsetX:g.schema,offsetY:g.schema,blur:g.schema,spread:g.schema,inset:{type:"boolean",errorMessage:o((e,t)=>l.VALIDATE.INVALID_SHADOW_INSET(e,t),"errorMessage")}},required:["color","offsetX","offsetY","blur","spread"],errorMessage:o((e,t)=>l.VALIDATE.INVALID_SHADOW(e,t),"errorMessage")}};function Me(e,t,n){const r=[];return Array.isArray(e)?(e.forEach((i,s)=>{r.push(...$(q.schema,i,`${t}[${s}]`,n))}),r):$(q.schema,e,t,n)}o(Me,"validateShadow");const je={type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_GRADIENT(e,t),"errorMessage"),properties:{color:{type:"string",validate:E.schema.validate},position:{type:"number",validate:o((e,t,n)=>e<0||e>1?[{path:t,message:l.VALIDATE.INVALID_GRADIENT_STOP_POSITION(e,t),source:n}]:[],"validate")}},required:["color","position"]},Pe={tokenType:"gradient",schema:{type:"array",errorMessage:o((e,t)=>l.VALIDATE.INVALID_ARRAY(e,t),"errorMessage"),validate:o((e,t,n)=>{const r=e,i=[];return r.forEach((s,a)=>{i.push(...$(je,s,`${t}[${a}]`,n))}),i},"validate")}};function Ue(e,t,n){return $(Pe.schema,e,t,n)}o(Ue,"validateGradient");const Ge={tokenType:"fluidDimension",schema:{type:"object",errorMessage:o((e,t)=>l.VALIDATE.INVALID_FLUID_DIMENSION(e,t),"errorMessage"),properties:{min:g.schema,max:g.schema},required:["min","max"]}};function Ye(e,t,n){return $(Ge.schema,e,t,n)}o(Ye,"validateFluidDimension");const ze={color:ge,dimension:Ee,fluidDimension:Ye,duration:Se,cubicBezier:_e,fontFamily:Te,fontWeight:De,number:Ae,strokeStyle:ke,typography:Ve,border:we,shadow:Me,gradient:Ue,transition:xe};function O(e){const t=[];for(const[n,r]of Object.entries(e)){if(typeof r!="object"||r===null||!("$type"in r)||!("$path"in r)||r.$path.startsWith("$"))continue;const i=ze[r.$type];if(!i){t.push({path:r.$path,message:l.VALIDATE.UNKNOWN_TOKEN_TYPE(r.$type,r.$path),source:r.$source});continue}t.push(...i(r.$value,r.$path,r.$source))}return t}o(O,"validate");function N(e,t,n,r){return typeof t=="string"&&p(t)?We(e,t,n,r):Array.isArray(t)?t.map(i=>N(e,i,n,r)):typeof t=="object"&&t!==null?Object.entries(t).reduce((s,[a,c])=>({...s,[a]:N(`${e}.${a}`,c,n,r)}),{}):t}o(N,"resolveValue");function v(e){const t={},n=new Set,r=[];for(const[i,s]of Object.entries(e))try{if(!("$value"in s)){t[i]=s;continue}const a=s;t[i]={...a,$resolvedValue:N(a.$path,a.$value,e,n)}}catch(a){const c=a instanceof Error?a.message:String(a),u=s,f=u.$path,h=u.$source;let d,m;c.includes("Circular reference detected")?(d="circular",m=c):c.includes("Reference not found")?(d="missing",m=c):(d="type-mismatch",m=l.RESOLVE.TYPE_MISMATCH(f)),r.push({type:d,path:f,source:h,message:m})}return{resolved:t,errors:r}}o(v,"resolve");function We(e,t,n,r){const i=t.slice(1,-1),s=Object.keys(n).find(u=>{const f=n[u];return f?"$originalPath"in f&&f.$originalPath===i:!1});if(!s)throw new Error(`Reference not found: ${i} in ${e}`);if(r.has(s))throw new Error(`Circular reference detected: ${e} -> ${s}`);const a=n[s];if(!a||!("$value"in a))throw new Error(`Reference not found: ${i} in ${e}`);r.add(s);const c=N(s,a.$value,n,r);return r.delete(s),c}o(We,"resolveReferenceChain");function F(e,t){return e.map(n=>({collection:n.collection,theme:n.theme,tokens:Object.entries(t).reduce((r,[i,s])=>("$source"in s&&(s.$source.collection!==n.collection||n.theme&&s.$source.theme!==n.theme||s.$source.theme&&s.$source.theme!==n.theme)||(!("$type"in s)||s.$source.collection===n.collection&&(!n.theme||s.$source.theme===n.theme))&&(r[i]=s),r),{})}))}o(F,"processTrees");function D(e){return["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"].includes(e.toLowerCase())?e:/[\s'"!@#$%^&*()=+[\]{};:|\\/,.<>?~]/.test(e)?`"${e}"`:e}o(D,"quoteFont");const Be={thin:100,hairline:100,"extra-light":200,"ultra-light":200,light:300,normal:400,regular:400,book:400,medium:500,"semi-bold":600,"demi-bold":600,bold:700,"extra-bold":800,"ultra-bold":800,black:900,heavy:900,"extra-black":950,"ultra-black":950};function K(e){return p(e)?{value:e}:typeof e=="number"?{value:e}:{value:Be[e.toLowerCase()]??e}}o(K,"convertFontWeightToken");function He(e){if(p(e))return{"font-family":e,"font-size":e};const t={"font-family":p(e.fontFamily)?e.fontFamily:Array.isArray(e.fontFamily)?e.fontFamily.map(n=>D(n)).join(", "):D(e.fontFamily),"font-size":p(e.fontSize)?e.fontSize:`${e.fontSize.value}${e.fontSize.unit}`};return e.fontWeight&&(t["font-weight"]=p(e.fontWeight)?e.fontWeight:K(e.fontWeight).value),e.letterSpacing&&(t["letter-spacing"]=p(e.letterSpacing)?e.letterSpacing:`${e.letterSpacing.value}${e.letterSpacing.unit}`),e.lineHeight&&(t["line-height"]=(p(e.lineHeight),e.lineHeight)),t}o(He,"convertTypographyToken");function X(e){return e?`${e.value}${e.unit}`:"0ms"}o(X,"formatDuration");function qe(e){if(p(e))return{value:e};const t=p(e.duration)?e.duration:X(e.duration),n=p(e.timingFunction)?e.timingFunction:`cubic-bezier(${e.timingFunction.join(", ")})`,r=e.delay&&(p(e.delay)?e.delay:X(e.delay));return{value:[t,n,r].filter(Boolean).join(" ")}}o(qe,"convertTransitionToken");function Ke(e){return p(e)?{value:e}:{value:`cubic-bezier(${e.join(", ")})`}}o(Ke,"convertCubicBezierToken");function Xe(e){return p(e)?{value:e}:{value:e}}o(Xe,"convertNumberToken");function Ze(e){return p(e)?{value:e}:{value:`${e.value}${e.unit}`}}o(Ze,"convertDurationToken");function Z(e){return p(e)?{value:e}:typeof e=="string"?{value:e}:{value:`${e.dashArray.map(n=>p(n)?n:`${n.value}${n.unit}`).join(" ")} ${e.lineCap}`}}o(Z,"convertStrokeStyleToken");function Je(e){if(p(e))return{value:e};const t=p(e.width)?e.width:`${e.width.value}${e.width.unit}`,n=(p(e.color),e.color),r=typeof e.style=="string"?e.style:Z(e.style).value;return{value:`${t} ${r} ${n}`}}o(Je,"convertBorderToken");function J(e){const t=p(e.offsetX)?e.offsetX:`${e.offsetX.value}${e.offsetX.unit}`,n=p(e.offsetY)?e.offsetY:`${e.offsetY.value}${e.offsetY.unit}`,r=p(e.blur)?e.blur:`${e.blur.value}${e.blur.unit}`,i=p(e.spread)?e.spread:`${e.spread.value}${e.spread.unit}`,s=(p(e.color),e.color);return`${e.inset?"inset ":""}${t} ${n} ${r} ${i} ${s}`}o(J,"convertSingleShadow");function Qe(e){return p(e)?{value:e}:Array.isArray(e)?{value:e.map(J).join(", ")}:{value:J(e)}}o(Qe,"convertShadowToken");function et(e){return p(e)?{value:e}:{value:`linear-gradient(${e.map(n=>{const r=(p(n.color),n.color),i=p(n.position)?n.position:`${n.position*100}`;return`${r} ${i}%`}).join(", ")})`}}o(et,"convertGradientToken");function tt(e){return p(e)?{value:e}:{value:Array.isArray(e)?e.map(n=>D(n)).join(", "):D(e)}}o(tt,"convertFontFamilyToken");function nt(e){return p(e)?{value:e}:{value:`${e.value}${e.unit}`}}o(nt,"convertDimensionToken");function Q(e,t=16){return e.unit==="px"?e.value:e.value*t}o(Q,"normalizeToPixels");function rt(e,t){const{min:n,max:r}=e,i=t.fluidConfig;if(!i)throw new Error(l.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));const s=16,a=Q(n,s),c=Q(r,s),u=i.min,f=i.max;if(a===c)return{value:`${a/s}rem`};const h=a/s,d=c/s,m=u/s,I=f/s,y=(d-h)/(I-m),A=-1*m*y+h;return{value:`clamp(${h}rem, ${A.toFixed(2)}rem + ${(y*100).toFixed(2)}vw, ${d}rem)`}}o(rt,"convertFluidDimension");function ot(e,t){if(p(e))return{value:e};if(!t.fluidConfig)throw new Error(l.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));return rt(e,t)}o(ot,"convertFluidDimensionToken");function k(e,t){try{const n=t==="rgba"?"rgb":t==="hsla"?"hsl":t,r=S(n==="hex"?"rgb":n)(e);if(!r)throw new Error(`Failed to convert color ${e} to ${t}`);switch(n){case"hsl":{if(r.mode!=="hsl")throw new Error("Unexpected color mode");const i=r.h??0,s=r.s??0,a=r.l??0,c=r.alpha;return c!==void 0&&c<1?`hsl(${Math.round(i)} ${Math.round(s*100)}% ${Math.round(a*100)}% / ${c.toFixed(2)})`:`hsl(${Math.round(i)} ${Math.round(s*100)}% ${Math.round(a*100)}%)`}case"oklch":{if(r.mode!=="oklch")throw new Error("Unexpected color mode");const i=r.l??0,s=r.c??0,a=r.h??0,c=r.alpha;return c!==void 0&&c<1?`oklch(${i.toFixed(3)} ${s.toFixed(3)} ${a.toFixed(1)} / ${c.toFixed(2)})`:`oklch(${i.toFixed(3)} ${s.toFixed(3)} ${a.toFixed(1)})`}case"rgb":{if(r.mode!=="rgb")throw new Error("Unexpected color mode");const i=Math.round((r.r??0)*255),s=Math.round((r.g??0)*255),a=Math.round((r.b??0)*255),c=r.alpha;return c!==void 0&&c<1?`rgb(${i} ${s} ${a} / ${c.toFixed(2)})`:`rgb(${i} ${s} ${a})`}case"p3":{if(r.mode!=="p3")throw new Error("Unexpected color mode");const i=r.r??0,s=r.g??0,a=r.b??0,c=r.alpha;return c!==void 0&&c<1?`color(display-p3 ${i.toFixed(6)} ${s.toFixed(6)} ${a.toFixed(6)} / ${c.toFixed(2)})`:`color(display-p3 ${i.toFixed(6)} ${s.toFixed(6)} ${a.toFixed(6)})`}default:{const i=S("rgb")(r);return i?P(i):e}}}catch{const r=S("rgb")(e);return console.warn(`Failed to convert color ${e} to ${t}, falling back to hex`),r?P(r):e}}o(k,"convertHexToColorString");function it(e,t){if(p(e))return{value:e};const n=t.colorFormat||"hex";try{const r=k(e,n);return n==="p3"?{value:k(e,"hex")||e,featureValues:[{query:"@supports (color: color(display-p3 1 1 1))",value:r||e}]}:{value:r||e}}catch{return console.warn(`Failed to convert color ${e} to ${n}, falling back to hex`),{value:k(e,"hex")}}}o(it,"convertColorToken");const ee={duration:Ze,number:Xe,cubicBezier:Ke,color:it,dimension:nt,fluidDimension:ot,typography:He,border:Je,shadow:Qe,gradient:et,transition:qe,strokeStyle:Z,fontFamily:tt,fontWeight:K};function st(e,t){const n=ee[e.$type];return{...e.$description?{$description:e.$description}:{},...e.$extensions?{$extensions:e.$extensions}:{},$type:e.$type,$value:e.$value,$path:e.$path,$source:e.$source,$originalPath:e.$originalPath,$resolvedValue:e.$resolvedValue,$cssProperties:n(e.$value,t)}}o(st,"convertSingleToken");function te(e,t){const n={};for(const[r,i]of Object.entries(e)){if(!i||typeof i!="object")continue;if(!("$type"in i)){n[r]={...i.$description?{$description:i.$description}:{},...i.$extensions?{$extensions:i.$extensions}:{}};continue}if(!ee[i.$type])continue;const s={fluidConfig:t.options?.fluid,colorFormat:t.options?.color,path:i.$path};n[r]=st(i,s)}return n}o(te,"convertTokens");function R(e,t){const n={};for(const[r,i]of Object.entries(e)){const s={default:te(i.default,t)};for(const[a,c]of Object.entries(i))a!=="default"&&(s[a]=te(c,t));n[r]=s}return n}o(R,"convert");const ne=new Map;function at(e){const t=ne.get(e);if(t)return t;const n=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase();return ne.set(e,n),n}o(at,"toKebabCase");function w({collection:e,filename:t,separate:n,baseDir:r}){const i=`${t}.variables.css`;return e==="default"?`${r}/${i}`:`${r}/${e}/${i}`}o(w,"getOutputPath");const re="@supports (color: color(display-p3 1 1 1))";function ct(e){return e.$type==="typography"}o(ct,"isTypographyToken");function C(e){return e.split(".").join("-")}o(C,"formatCSSVarPath");function oe(e){return typeof e=="number"?e:typeof e!="string"?(console.warn("Unexpected value type in convertReferenceToCSSVar, got:",e),String(e)):e.replace(/\{([^}]+)\}/g,(t,n)=>`var(--${n.split(".").map(at).join("-")})`)}o(oe,"convertReferenceToCSSVar");function lt(e){const t=e.$cssProperties;if("value"in t)return{name:`--${C(e.$path)}`,value:oe(t.value)}}o(lt,"generateSingleVariable");function ut(e){return Object.entries(e.$cssProperties).filter(([t,n])=>n!==void 0).map(([t,n])=>({name:`--${C(e.$path)}-${t}`,value:oe(n)}))}o(ut,"generateTypographyVariables");function ie(e){if(e.$type!=="color")return[];const t=e.$cssProperties;return"featureValues"in t?t.featureValues?.filter(n=>n.query===re).map(n=>({name:`--${C(e.$path)}`,value:n.value}))??[]:[]}o(ie,"generateFeatureVariables");function se(e){const t=[`${e.selector} {`];if(e.comment&&t.push(` /* ${e.comment} */`),e.vars.length>0){const n=e.vars.map(r=>` ${r.name}: ${r.value};`).join(`
2
+ `);t.push(n)}return t.push("}"),t.join(`
3
+ `)}o(se,"generateCSSBlock");function ft(e){const t=[];return e.root.vars.length>0&&t.push(se({selector:e.root.selector,vars:e.root.vars})),e.features.forEach(n=>{const i=se({selector:e.root.selector,vars:n.vars}).split(`
4
+ `).map(s=>` ${s}`).join(`
5
+ `);t.push(`${n.query} {
6
+ ${i}
7
+ }`)}),t.filter(Boolean).join(`
5
8
 
6
- `),e=e.replace(/}$/,`
7
- }`),e}n(Re,"formatCSSVars");function Ce(e){const t={root:{},groups:{},tokens:{}},r=[];if(D(e)){const{value:o,errors:i}=h(e,"");t.root=o,r.push(...i)}return P(e,"",t,r),{metadata:t,errors:r}}n(Ce,"collectMetadata");function P(e,t,r,o){for(const[i,s]of Object.entries(e)){if(i.startsWith("$"))continue;const a=t?`${t}.${i}`:i;if(!(typeof s!="object"||s===null)){if(!("$value"in s)&&D(s)){const{value:u,errors:f}=h(s,a);f.length>0&&o.push(...f),r.groups[a]=u}else if("$value"in s&&D(s)){const{value:u,errors:f}=h(s,a);f.length>0&&o.push(...f),r.tokens[a]=u}"$value"in s||P(s,a,r,o)}}}n(P,"collectNodeMetadata");function h(e,t){const r={},o=[];return w(e)?("$extensions"in e&&(typeof e.$extensions!="object"||e.$extensions===null?o.push({path:t,message:c.METADATA.INVALID_EXTENSIONS(t)}):r.$extensions=e.$extensions),"$description"in e&&(typeof e.$description!="string"?o.push({path:t,message:c.METADATA.INVALID_DESCRIPTION(t)}):r.$description=e.$description),{value:r,errors:o}):{value:r,errors:o}}n(h,"extractMetadata");function D(e){return w(e)&&("$extensions"in e||"$description"in e)}n(D,"hasMetadata");function w(e){return typeof e=="object"&&e!==null}n(w,"isValidNode");function Fe(e){return JSON.parse(e)}n(Fe,"parseJson");const Me={isObject:n(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObject")};function d(e,t,r){if(l(t))return[];switch(e.type){case"object":return xe(e,t,r);case"union":return je(e,t,r);case"array":return Ue(e,t,r);default:return ke(e,t,r)}}n(d,"validateSchema");function ke(e,t,r){return typeof t!==e.type?[{path:r,message:e.errorMessage?.(t,r)||c.VALIDATE.INVALID_TYPE(e.type,t,r)}]:e.validate?.(t,r)??[]}n(ke,"validateSimpleValue");function xe(e,t,r){if(!Me.isObject(t))return[{path:r,message:e.errorMessage?.(t,r)||c.VALIDATE.INVALID_TYPE("object",t,r)}];const o=[],i=t;if(e.required)for(const s of e.required)s in i||o.push({path:`${r}.${s}`,message:c.VALIDATE.MISSING_REQUIRED_PROPERTY(s,r)});for(const[s,a]of Object.entries(e.properties))s in i&&o.push(...d(a,i[s],`${r}.${s}`));return o}n(xe,"validateObject");function je(e,t,r){let o=[];for(const s of e.oneOf){const a=d(s,t,r);if(a.length===0)return e.validate?.(t,r)??[];o=o.concat(a)}return[o.reduce((s,a)=>a.path.length>s.path.length?a:s)]}n(je,"validateUnion");function Ue(e,t,r){return Array.isArray(t)?e.validate?.(t,r)??[]:[{path:r,message:e.errorMessage?.(t,r)||c.VALIDATE.INVALID_TYPE("array",t,r)}]}n(Ue,"validateArray");const T={tokenType:"color",schema:{type:"string",errorMessage:n((e,t)=>c.VALIDATE.INVALID_COLOR(e,t),"errorMessage"),validate:n((e,t)=>/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(e)?[]:[{path:t,message:c.VALIDATE.INVALID_COLOR(e,t)}],"validate")}};function Pe(e,t){return d(T.schema,e,t)}n(Pe,"validateColor");const E={tokenType:"number",schema:{type:"number",errorMessage:n((e,t)=>c.VALIDATE.INVALID_NUMBER(e,t),"errorMessage"),validate:n((e,t)=>typeof e!="number"||isNaN(e)?[{path:t,message:c.VALIDATE.INVALID_NUMBER(e,t)}]:[],"validate")}};function we(e,t){return d(E.schema,e,t)}n(we,"validateNumber");const p={tokenType:"dimension",schema:{type:"object",errorMessage:n((e,t)=>c.VALIDATE.INVALID_DIMENSION(e,t),"errorMessage"),properties:{value:E.schema,unit:{type:"string",validate:n((e,t)=>typeof e!="string"||!["px","rem"].includes(e)?[{path:t,message:c.VALIDATE.INVALID_DIMENSION_UNIT(e,t)}]:[],"validate")}},required:["value","unit"]}};function Ye(e,t){return d(p.schema,e,t)}n(Ye,"validateDimension");const Y={tokenType:"fontFamily",schema:{type:"union",errorMessage:n((e,t)=>c.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage"),oneOf:[{type:"string",errorMessage:n((e,t)=>c.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")},{type:"array",validate:n((e,t)=>e.every(o=>typeof o=="string")?[]:[{path:t,message:c.VALIDATE.INVALID_FONT_FAMILY(e,t)}],"validate")}]}};function Ge(e,t){return d(Y.schema,e,t)}n(Ge,"validateFontFamily");const We=["thin","hairline","extra-light","ultra-light","light","normal","regular","book","medium","semi-bold","demi-bold","bold","extra-bold","ultra-bold","black","heavy","extra-black","ultra-black"],G={tokenType:"fontWeight",schema:{type:"union",errorMessage:n((e,t)=>c.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),oneOf:[{type:"number",errorMessage:n((e,t)=>c.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:n((e,t)=>e<1||e>1e3?[{path:t,message:c.VALIDATE.INVALID_FONT_WEIGHT(e,t)}]:[],"validate")},{type:"string",errorMessage:n((e,t)=>c.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:n((e,t)=>We.includes(e.toLowerCase())?[]:[{path:t,message:c.VALIDATE.INVALID_FONT_WEIGHT(e,t)}],"validate")}]}};function Be(e,t){return d(G.schema,e,t)}n(Be,"validateFontWeight");const ze=["ms","s"],_={tokenType:"duration",schema:{type:"object",errorMessage:n((e,t)=>c.VALIDATE.INVALID_DURATION(e,t),"errorMessage"),properties:{value:E.schema,unit:{type:"string",validate:n((e,t)=>(console.log("value",e),ze.includes(e)?[]:[{path:t,message:c.VALIDATE.INVALID_DURATION_UNIT(e,t)}]),"validate")}},required:["value","unit"]}};function qe(e,t){return d(_.schema,e,t)}n(qe,"validateDuration");const W={tokenType:"cubicBezier",schema:{type:"array",errorMessage:n((e,t)=>c.VALIDATE.INVALID_CUBIC_BEZIER(e,t),"errorMessage"),validate:n((e,t)=>{const r=e;if(r.length!==4||!r.every(s=>typeof s=="number"))return[{path:t,message:c.VALIDATE.INVALID_CUBIC_BEZIER(e,t)}];const[o,,i]=r;return o<0||o>1||i<0||i>1?[{path:t,message:c.VALIDATE.INVALID_CUBIC_BEZIER_RANGE(e,t)}]:[]},"validate")}};function He(e,t){return d(W.schema,e,t)}n(He,"validateCubicBezier");const Ke={tokenType:"typography",schema:{type:"object",properties:{fontFamily:Y.schema,fontSize:p.schema,letterSpacing:p.schema,lineHeight:E.schema,fontWeight:G.schema},required:["fontFamily","fontSize"],errorMessage:n((e,t)=>c.VALIDATE.INVALID_TYPOGRAPHY(e,t),"errorMessage")}};function Xe(e,t){return d(Ke.schema,e,t)}n(Xe,"validateTypography");const Ze=["solid","dashed","dotted","double","groove","ridge","outset","inset"],Qe=["round","butt","square"],Je={type:"object",errorMessage:n((e,t)=>c.VALIDATE.INVALID_STROKE_STYLE(e,t),"errorMessage"),properties:{dashArray:{type:"array",validate:n((e,t)=>{const r=e,o=[];return r.forEach((i,s)=>{typeof i!="string"&&o.push(...d(p.schema,i,`${t}[${s}]`))}),o},"validate")},lineCap:{type:"string",validate:n((e,t)=>Qe.includes(e)?[]:[{path:t,message:c.VALIDATE.INVALID_STROKE_LINE_CAP(e,t)}],"validate")}},required:["dashArray","lineCap"]},B={tokenType:"strokeStyle",schema:{type:"union",oneOf:[{type:"string",errorMessage:n((e,t)=>c.VALIDATE.INVALID_STROKE_STYLE(e,t),"errorMessage"),validate:n((e,t)=>Ze.includes(e)?[]:[{path:t,message:c.VALIDATE.INVALID_STROKE_STYLE(e,t)}],"validate")},Je]}};function et(e,t){return d(B.schema,e,t)}n(et,"validateStrokeStyle");const tt={tokenType:"border",schema:{type:"object",properties:{color:T.schema,width:p.schema,style:B.schema},required:["color","width","style"],errorMessage:n((e,t)=>c.VALIDATE.INVALID_BORDER(e,t),"errorMessage")}};function rt(e,t){return d(tt.schema,e,t)}n(rt,"validateBorder");const nt={tokenType:"transition",schema:{type:"object",properties:{duration:_.schema,delay:_.schema,timingFunction:W.schema},required:["duration","delay","timingFunction"],errorMessage:n((e,t)=>c.VALIDATE.INVALID_TRANSITION(e,t),"errorMessage")}};function ot(e,t){return d(nt.schema,e,t)}n(ot,"validateTransition");const z={tokenType:"shadow",schema:{type:"object",properties:{color:T.schema,offsetX:p.schema,offsetY:p.schema,blur:p.schema,spread:p.schema,inset:{type:"boolean",errorMessage:n((e,t)=>c.VALIDATE.INVALID_SHADOW_INSET(e,t),"errorMessage")}},required:["color","offsetX","offsetY","blur","spread"],errorMessage:n((e,t)=>c.VALIDATE.INVALID_SHADOW(e,t),"errorMessage")}};function it(e,t){const r=[];return Array.isArray(e)?(e.forEach((o,i)=>{r.push(...d(z.schema,o,`${t}[${i}]`))}),r):d(z.schema,e,t)}n(it,"validateShadow");const st={type:"object",errorMessage:n((e,t)=>c.VALIDATE.INVALID_GRADIENT(e,t),"errorMessage"),properties:{color:{type:"string",validate:T.schema.validate},position:{type:"number",validate:n((e,t)=>e<0||e>1?[{path:t,message:c.VALIDATE.INVALID_GRADIENT_STOP_POSITION(e,t)}]:[],"validate")}},required:["color","position"]},at={tokenType:"gradient",schema:{type:"array",errorMessage:n((e,t)=>c.VALIDATE.INVALID_ARRAY(e,t),"errorMessage"),validate:n((e,t)=>{const r=e,o=[];return r.forEach((i,s)=>{o.push(...d(st,i,`${t}[${s}]`))}),o},"validate")}};function ct(e,t){return d(at.schema,e,t)}n(ct,"validateGradient");const ut={tokenType:"fluidDimension",schema:{type:"object",errorMessage:n((e,t)=>c.VALIDATE.INVALID_FLUID_DIMENSION(e,t),"errorMessage"),properties:{min:p.schema,max:p.schema},required:["min","max"]}};function lt(e,t){return d(ut.schema,e,t)}n(lt,"validateFluidDimension");const ft={color:n((e,t)=>Pe(e,t),"color"),dimension:n((e,t)=>Ye(e,t),"dimension"),fluidDimension:n((e,t)=>lt(e,t),"fluidDimension"),duration:n((e,t)=>qe(e,t),"duration"),cubicBezier:n((e,t)=>He(e,t),"cubicBezier"),fontFamily:n((e,t)=>Ge(e,t),"fontFamily"),fontWeight:n((e,t)=>Be(e,t),"fontWeight"),number:n((e,t)=>we(e,t),"number"),strokeStyle:n((e,t)=>et(e,t),"strokeStyle"),typography:n((e,t)=>Xe(e,t),"typography"),border:n((e,t)=>rt(e,t),"border"),shadow:n((e,t)=>it(e,t),"shadow"),gradient:n((e,t)=>ct(e,t),"gradient"),transition:n((e,t)=>ot(e,t),"transition")};function dt(e,t,r){const o=[];if(!("$type"in e))return[{path:t,message:c.VALIDATE.MISSING_TYPE(t)}];if(!("$value"in e))return[{path:t,message:c.VALIDATE.MISSING_VALUE(t)}];const i=ft[e.$type];return i?(e.$type==="fluidDimension"&&(M(t,r)?.viewports||o.push({path:t,message:c.VALIDATE.MISSING_FLUID_CONFIG(t)})),[...o,...i(e.$value,t)]):[{path:t,message:c.VALIDATE.UNKNOWN_TOKEN_TYPE(e.$type,t)}]}n(dt,"validateTokenNode");function It(e,t){const r=[];for(const[o,i]of Object.entries(e))if(!(typeof i!="object"||i===null)&&!(!i.$path||i.$path.startsWith("$"))){if(typeof i!="object"||i===null){r.push({path:o,message:c.VALIDATE.INVALID_TOKEN_STRUCTURE(o)});continue}r.push(...dt(i,i.$path,t))}return r}n(It,"validate");export{Ce as collectMetadata,Te as convert,X as flatten,ve as generateCSS,Fe as parseJson,Z as resolve,It as validate};
9
+ `)}o(ft,"convertCSSVarsToString");function dt(e){if(ct(e))return{vars:ut(e),features:ie(e)};const t=lt(e);return{vars:t?[t]:[],features:ie(e)}}o(dt,"generateVariablesForToken");async function x(e,t={}){const n=Object.entries(e).filter(([c,u])=>c!=="$extensions"&&"$type"in u).map(([c,u])=>dt(u));let r=":root";t.theme&&t.theme!=="default"&&(r=`[data-theme="${t.theme}"]`);const i=n.flatMap(c=>c.vars),s=n.flatMap(c=>c.features||[]),a=ft({root:{selector:r,vars:i},features:s.length?[{query:re,vars:s}]:[]});return{output:[{name:"tokens.variables.css",content:pt(a)}]}}o(x,"generateCSS");function pt(e){return e.endsWith(`
10
+ `)?e:e+`
11
+ `}o(pt,"formatCSSVars");async function M(e,t){const n={};for(const[r,i]of Object.entries(e)){n[r]={default:{}},i.default&&(n[r].default=i.default);for(const[s,a]of Object.entries(i))s!=="default"&&a&&(n[r][s]=a);Object.keys(n[r].default).length===0&&Object.keys(n[r]).length===1&&delete n[r]}return t.output.css.separate?{output:await mt(n,t)}:{output:await ht(n,t)}}o(M,"generate");async function ht(e,t){const n=`${t.output.directories.css}/global/variables`,r=[];for(const[i,s]of Object.entries(e)){const a=[];for(const[c,u]of Object.entries(s)){const f=await x(u,{theme:c!=="default"?c:void 0,collection:i!=="default"?i:void 0});a.push(f.output[0].content)}a.length>0&&r.push({name:w({collection:i,filename:"tokens",separate:!1,baseDir:n}),content:a.filter(Boolean).join(`
12
+ `).trim()+`
13
+ `})}return r}o(ht,"generateSingleFile");async function mt(e,t){const n=`${t.output.directories.css}/global/variables`,r=[];for(const[i,s]of Object.entries(e))if(Object.keys(s).length!==0){for(const[a,c]of Object.entries(s))if(Object.keys(c).length!==0)if(a==="default"){const u=new Map;for(const[f,h]of Object.entries(c)){if(!("$type"in h))continue;const m=h.$source.sourcePath;u.has(m)||u.set(m,{}),u.get(m)[f]=h}for(const[f,h]of u){if(Object.keys(h).length===0)continue;const d=f.split("/").pop()?.replace(/\.json$/,"")??"tokens",I=(await x(h,{collection:i==="default"?void 0:i})).output[0].content;I&&r.push({name:w({collection:i,filename:d,separate:!0,baseDir:n}),content:I})}}else{const f=(await x(c,{theme:a,collection:i==="default"?void 0:i})).output[0].content;f&&r.push({name:w({collection:i,filename:a,separate:!0,baseDir:n}),content:f})}}return r}o(mt,"generateSeparateFiles");function j(e){const t=[],n=[],r=new Set,i=new Map;e.forEach(c=>{const{collection:u,theme:f="default"}=c;r.add(u),i.has(u)||i.set(u,new Set),i.get(u).add(f)});const s={};function a(c){const u={default:{}};s[c]=u;const f=i.get(c);return f&&f.forEach(h=>{u[h]={}}),u}return o(a,"addCollection"),r.forEach(c=>{a(c)}),e.forEach(c=>{const{collection:u,theme:f="default",tokens:h}=c,d=s[u]||a(u),m=d[f]||(d[f]={});Object.entries(h).forEach(([I,y])=>{const A=I.replace(`${u}.`,"");m[A]=y})}),{tokens:s,errors:n,warnings:t}}o(j,"normalizeTokens");async function It(e){const t={load:[],flatten:[],validation:[],resolution:[]},n={normalization:[]},{trees:r,errors:i}=await _(e);t.load.push(...i);const{tokens:s,errors:a}=L(r);t.flatten.push(...a);const c=O(s);if(t.validation.push(...c),c.length>0)return{output:[],trees:r,errors:t,warnings:n};const{resolved:u,errors:f}=v(s);t.resolution.push(...f);const h=F(r,u),{tokens:d,warnings:m}=j(h);n.normalization.push(...m);const I=R(d,e),{output:y}=await M(I,e);return{output:y,trees:r,errors:t,warnings:n}}o(It,"tokensToCSSPipeline");async function $t(e,t){const{trees:n,errors:r}=await(t.loader.type==="memory"?Y(t.loader.data):_(t.loader.paths)),{tokens:i,errors:s}=L(n),a=O(i),{resolved:c,errors:u}=v(i);return{trees:n,flattenedTokens:i,resolved:c,errors:{load:r,flatten:s,validation:a,resolution:u}}}o($t,"validationPipeline");async function yt(e,t,n){const r={normalization:[]},i=F(e,t),{tokens:s,warnings:a}=j(i);r.normalization.push(...a);const c=R(s,n),{output:u}=await M(c,n);return{output:u,warnings:r}}o(yt,"generationPipeline");export{R as convert,L as flatten,M as generate,yt as generationPipeline,_ as loadTreesFromConfig,Y as loadTreesFromMemory,j as normalizeTokens,F as processTrees,v as resolve,It as tokensToCSSPipeline,O as validate,$t as validationPipeline};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sugarcube-org/core",
3
- "version": "0.0.1-alpha.1",
3
+ "version": "0.0.1-alpha.3",
4
4
  "publishConfig": {
5
5
  "access": "restricted"
6
6
  },
@@ -12,12 +12,24 @@
12
12
  "README.md"
13
13
  ],
14
14
  "devDependencies": {
15
- "pkgroll": "^2.5.1"
15
+ "pkgroll": "^2.5.1",
16
+ "tsx": "^4.19.2"
17
+ },
18
+ "dependencies": {
19
+ "@types/culori": "^2.1.1",
20
+ "@types/picomatch": "^3.0.1",
21
+ "culori": "^4.0.1",
22
+ "fast-glob": "^3.3.2",
23
+ "globby": "^14.0.2",
24
+ "picomatch": "^4.0.2",
25
+ "zod": "^3.21.4"
16
26
  },
17
27
  "scripts": {
18
28
  "build": "pkgroll --minify",
19
29
  "dev": "pkgroll --watch",
20
- "test": "vitest",
21
- "type-check": "tsc --noEmit"
30
+ "test": "vitest run",
31
+ "test:watch": "vitest",
32
+ "type-check": "tsc --noEmit",
33
+ "ci": "pnpm type-check && pnpm test"
22
34
  }
23
35
  }