@sugarcube-org/core 0.0.1-alpha.4 → 0.0.1-alpha.5

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 +486 -301
  2. package/dist/index.js +22 -16
  3. package/package.json +6 -8
package/dist/index.d.ts CHANGED
@@ -1,29 +1,60 @@
1
1
  import { z } from 'zod';
2
2
 
3
+ /**
4
+ * Supported color formats for CSS output
5
+ */
3
6
  type ColorFormat = "hex" | "rgb" | "rgba" | "hsl" | "hsla" | "oklch" | "p3";
4
- type ColorConfig = {
5
- format?: ColorFormat;
6
- };
7
+ /**
8
+ * Configuration for fluid (responsive) values
9
+ */
7
10
  type FluidConfig = {
11
+ /** Minimum viewport width in pixels */
8
12
  min: number;
13
+ /** Maximum viewport width in pixels */
9
14
  max: number;
10
15
  };
16
+ /**
17
+ * A collection of token files with shared namespace.
18
+ * Represents either a starter kit or custom token collection.
19
+ */
11
20
  type TokenCollection = {
21
+ /** Array of source file paths for this collection */
12
22
  source: string[];
23
+ /** Whether this is a starter kit or custom collection */
13
24
  type: "starter-kit" | "custom";
25
+ /** Optional theme-specific source files */
14
26
  themes?: Record<string, string[]>;
15
27
  };
28
+ /**
29
+ * Multiple named collections of tokens.
30
+ * Each key is a collection name (e.g., "base", "ui", "marketing").
31
+ */
16
32
  type TokenCollections = Record<string, TokenCollection>;
33
+ /**
34
+ * Global options for token processing and output
35
+ */
17
36
  type OptionsConfig = {
37
+ /** Configuration for fluid (responsive) values */
18
38
  fluid?: FluidConfig;
39
+ /** Prefix to add to all CSS variable names */
19
40
  prefix?: string;
41
+ /** Default color format for all color tokens */
20
42
  color?: ColorFormat;
21
43
  };
44
+ /**
45
+ * Configuration for output directories
46
+ */
22
47
  type DirectoriesConfig = {
48
+ /** Directory containing token source files */
23
49
  tokens: string;
50
+ /** Optional directory for component files */
24
51
  components?: string;
52
+ /** Directory where CSS files will be written */
25
53
  css: string;
26
54
  };
55
+ /**
56
+ * Configuration for CSS output generation
57
+ */
27
58
  type CSSOutputConfig = {
28
59
  /**
29
60
  * Controls how CSS variables are organized in output files:
@@ -34,412 +65,532 @@ type CSSOutputConfig = {
34
65
  * @default false
35
66
  */
36
67
  separate: boolean;
68
+ /** Whether to generate and manage an index.css file */
37
69
  manageIndex?: boolean;
70
+ /** The format of the output CSS files */
38
71
  format?: "css" | "scss" | "less";
39
72
  };
73
+ /**
74
+ * Configuration for all output generation
75
+ */
40
76
  type OutputConfig = {
77
+ /** Directory configuration for all output files */
41
78
  directories: DirectoriesConfig;
79
+ /** CSS-specific output configuration */
42
80
  css: CSSOutputConfig;
43
81
  };
82
+ /**
83
+ * The main configuration type for Sugarcube.
84
+ * Defines all settings for token processing and output generation.
85
+ */
44
86
  interface SugarcubeConfig {
87
+ /** Token source configuration, either a single collection or multiple named collections */
45
88
  tokens: TokenCollection | TokenCollections;
89
+ /** Optional global processing options */
46
90
  options?: OptionsConfig;
91
+ /** Output configuration for generated files */
47
92
  output: OutputConfig;
48
93
  }
49
94
 
50
95
  /**
51
- * Represents a single CSS file output with its name and content
52
- */
53
- type CSSFile = {
54
- path: string;
55
- css: string;
56
- };
57
- /**
58
- * Represents the output from generateCSS which always returns exactly one file
59
- */
60
- type SingleFileOutput = [CSSFile];
61
- /**
62
- * Represents multiple CSS file outputs from generateSeparateFiles or generateSingleFile
63
- */
64
- type CSSFileOutput = CSSFile[];
65
- /**
66
- * Result of the CSS generation process
67
- * For generateCSS: Contains exactly one file
68
- * For generate: Contains one or more files
96
+ * Base error type that all other error types extend from.
97
+ * Used as the foundation for all error types in the system.
98
+ * Provides a consistent structure for error messages across the codebase.
69
99
  */
70
- type CSSGenerationResult = {
71
- output: SingleFileOutput | CSSFileOutput;
100
+ type BaseError = {
101
+ /** A human-readable error message describing what went wrong */
102
+ message: string;
72
103
  };
73
104
 
74
105
  /**
75
- * A token value that can either be a raw value or a reference
106
+ * A token value that can either be a raw value or a reference.
107
+ * This is the base type for all token values in the W3C Design Token Format.
108
+ * @template T - The type of token (e.g., "color", "dimension", etc.)
76
109
  */
77
110
  type TokenValue<T extends TokenType> = RawTokenValue<T> | Reference<T>;
78
111
  /**
79
- * The actual value of a token without references
112
+ * The actual value of a token without references.
113
+ * This represents the concrete value that will be used in the final output.
114
+ * @template T - The type of token (e.g., "color", "dimension", etc.)
80
115
  */
81
116
  type RawTokenValue<T extends TokenType> = T extends SimpleTokenType ? SimpleTokenValue<T> : T extends CompositeTokenType ? CompositeTokenValue<T> : never;
82
117
  /**
83
- * A reference to another token, with optional type checking
118
+ * A reference to another token, with optional type checking.
119
+ * References are strings that point to other tokens in the token tree.
120
+ * The phantom type parameter ensures type safety when resolving references.
121
+ * @template T - The type of token being referenced
84
122
  */
85
123
  type Reference<T extends TokenType = TokenType> = string & {
124
+ /** Phantom type for type safety during reference resolution */
86
125
  __tokenType?: T;
87
126
  };
88
127
  /**
89
- * Metadata that can be attached to any node in the token tree
128
+ * Metadata that can be attached to any node in the token tree.
129
+ * This includes descriptions and custom extensions as defined in the W3C spec.
90
130
  */
91
131
  type NodeMetadata = {
132
+ /** Optional description of the token or group */
92
133
  $description?: string;
134
+ /** Optional custom extensions as defined in the W3C spec */
93
135
  $extensions?: {
94
136
  [key: string]: unknown;
95
137
  };
96
138
  };
97
139
  /**
98
- * A single token with its value and metadata
140
+ * A single token with its value and metadata.
141
+ * This is the basic building block of the token system.
99
142
  */
100
143
  type Token = NodeMetadata & {
144
+ /** The value of the token, which can be a raw value or a reference */
101
145
  $value: TokenValue<TokenType>;
146
+ /** Optional type specification, can be inherited from parent groups */
102
147
  $type?: TokenType;
103
148
  };
104
149
  /**
105
- * A group of tokens that can be nested. The type allows for:
150
+ * A group of tokens that can be nested.
151
+ * The type allows for:
106
152
  * - Regular token properties (non-$ prefixed) which must be Token | TokenGroup
107
153
  * - Metadata properties from NodeMetadata (like $description, $extensions)
108
154
  * - $type property for type inheritance as specified in the W3C spec
109
155
  * - undefined to support optional metadata properties
110
156
  */
111
157
  type TokenGroup = NodeMetadata & {
158
+ /** Optional type specification for the group, can be inherited by child tokens */
112
159
  $type?: TokenType;
160
+ /** Dynamic properties that can be either tokens, token groups, or undefined */
113
161
  [key: string]: Token | TokenGroup | TokenType | undefined;
114
162
  };
115
163
  /**
116
- * All possible token types, either simple or composite
164
+ * All possible token types, either simple or composite.
165
+ * This is the union of all supported token types in the system.
117
166
  */
118
167
  type TokenType = SimpleTokenType | CompositeTokenType;
119
168
  /**
120
- * Token types that contain a single value
169
+ * Token types that contain a single value.
170
+ * These are the basic building blocks of the token system.
121
171
  */
122
172
  type SimpleTokenType = "color" | "dimension" | "fluidDimension" | "duration" | "cubicBezier" | "fontFamily" | "fontWeight" | "number";
123
173
  /**
124
- * Values for simple token types
174
+ * Values for simple token types.
175
+ * Maps each simple token type to its corresponding value type.
176
+ * @template T - The type of token (e.g., "color", "dimension", etc.)
125
177
  */
126
178
  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;
127
179
  /**
128
- * Token types that contain multiple values or are structurally complex
180
+ * Token types that contain multiple values or are structurally complex.
181
+ * These types combine multiple simple types to create more complex tokens.
129
182
  */
130
183
  type CompositeTokenType = AlwaysDecomposedType | "border" | "shadow" | "gradient" | "transition" | StructuralCompositeType;
131
184
  /**
132
- * Token types that must always be broken down into their constituent parts
185
+ * Token types that must always be broken down into their constituent parts.
186
+ * These types are never used directly in CSS output.
133
187
  */
134
188
  type AlwaysDecomposedType = "typography";
135
189
  /**
136
- * Token types that define structural patterns
190
+ * Token types that define structural patterns.
191
+ * These types are used to define reusable patterns in the token system.
137
192
  */
138
193
  type StructuralCompositeType = "strokeStyle";
139
194
  /**
140
- * Values for composite token types
195
+ * Values for composite token types.
196
+ * Maps each composite token type to its corresponding value type.
197
+ * @template T - The type of token (e.g., "typography", "border", etc.)
141
198
  */
142
199
  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;
143
200
  /**
144
- * A color value in any valid CSS color format
201
+ * A color value in any valid CSS color format.
202
+ * This can be any string that is valid in CSS color contexts.
145
203
  */
146
204
  type Color = string;
147
205
  /**
148
- * A dimensional value with a numeric value and unit
206
+ * A dimensional value with a numeric value and unit.
207
+ * Used for measurements like width, height, spacing, etc.
149
208
  */
150
209
  type Dimension = {
210
+ /** The numeric value of the dimension */
151
211
  value: number;
212
+ /** The unit of measurement (px or rem) */
152
213
  unit: "px" | "rem";
153
214
  };
154
215
  /**
155
- * A fluid dimension that scales between min and max values
216
+ * A fluid dimension that scales between min and max values.
217
+ * Used for responsive design tokens that need to scale with viewport size.
156
218
  */
157
219
  type FluidDimension = {
220
+ /** The minimum value at the smallest viewport size */
158
221
  min: Dimension;
222
+ /** The maximum value at the largest viewport size */
159
223
  max: Dimension;
160
224
  };
161
225
  /**
162
- * A duration value with a numeric value and time unit
226
+ * A duration value with a numeric value and time unit.
227
+ * Used for animations, transitions, and other time-based values.
163
228
  */
164
229
  type Duration = {
230
+ /** The numeric value of the duration */
165
231
  value: number;
232
+ /** The unit of time (milliseconds or seconds) */
166
233
  unit: "ms" | "s";
167
234
  };
168
235
  /**
169
- * A cubic bezier curve defined by four control points
236
+ * A cubic bezier curve defined by four control points.
237
+ * Used for defining custom easing functions in animations and transitions.
238
+ * The four numbers represent the x,y coordinates of the two control points.
170
239
  */
171
240
  type CubicBezier = [number, number, number, number];
172
241
  /**
173
- * A font family name or list of fallback fonts
242
+ * A font family name or list of fallback fonts.
243
+ * Can be a single font name or an array of fonts in order of preference.
174
244
  */
175
245
  type FontFamily = string | string[];
176
246
  /**
177
- * A font weight value as either a number or semantic string
247
+ * A font weight value as either a number or semantic string.
248
+ * Numbers range from 100-900, strings are semantic names for common weights.
178
249
  */
179
250
  type FontWeight = number | FontWeightString;
180
251
  /**
181
- * Semantic font weight names
252
+ * Semantic font weight names.
253
+ * These are standardized names for common font weights.
182
254
  */
183
255
  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";
184
256
  /**
185
- * Line cap style for strokes
257
+ * Line cap style for strokes.
258
+ * Defines how the end of a stroke should be rendered.
186
259
  */
187
260
  type LineCap = "round" | "butt" | "square";
188
261
  /**
189
- * Typography token combining font properties
262
+ * Typography token combining font properties.
263
+ * This is a composite type that combines multiple font-related properties.
190
264
  */
191
265
  type Typography = {
266
+ /** The font family to use */
192
267
  fontFamily: TokenValue<"fontFamily">;
268
+ /** The size of the font */
193
269
  fontSize: TokenValue<"dimension">;
270
+ /** Optional font weight */
194
271
  fontWeight?: TokenValue<"fontWeight">;
272
+ /** Optional letter spacing */
195
273
  letterSpacing?: TokenValue<"dimension">;
274
+ /** Optional line height as a multiplier */
196
275
  lineHeight?: TokenValue<"number">;
197
276
  };
198
277
  /**
199
- * Transition token defining animation properties
278
+ * Transition token defining animation properties.
279
+ * Used to define how properties should animate between states.
200
280
  */
201
281
  type Transition = {
282
+ /** How long the transition should take */
202
283
  duration: TokenValue<"duration">;
284
+ /** Optional delay before the transition starts */
203
285
  delay?: TokenValue<"duration">;
286
+ /** The easing function to use for the transition */
204
287
  timingFunction: TokenValue<"cubicBezier">;
205
288
  };
206
289
  /**
207
- * Predefined stroke style keywords
290
+ * Predefined stroke style keywords.
291
+ * These are the standard stroke styles available in CSS.
208
292
  */
209
293
  type StrokeStyleKeyword = "solid" | "dashed" | "dotted" | "double" | "groove" | "ridge" | "outset" | "inset";
210
294
  /**
211
- * Custom stroke style definition
295
+ * Custom stroke style definition.
296
+ * Used when the predefined stroke styles are not sufficient.
212
297
  */
213
298
  type StrokeStyleCustom = {
299
+ /** Array of dimensions defining the dash pattern */
214
300
  dashArray: Array<TokenValue<"dimension">>;
301
+ /** How the ends of the stroke should be rendered */
215
302
  lineCap: LineCap;
216
303
  };
217
304
  /**
218
- * A stroke style that can be either a keyword or custom definition
305
+ * A stroke style can be either a predefined keyword or a custom definition.
306
+ * This allows for both simple and complex stroke styles.
219
307
  */
220
308
  type StrokeStyle = StrokeStyleKeyword | StrokeStyleCustom;
221
309
  /**
222
- * Border token combining color, width, and style
310
+ * Border token combining color, width, and style.
311
+ * This is a composite type that defines a complete border.
223
312
  */
224
313
  type Border = {
314
+ /** The color of the border */
225
315
  color: TokenValue<"color">;
316
+ /** The width of the border */
226
317
  width: TokenValue<"dimension">;
318
+ /** The style of the border, either a stroke style or a reference to one */
227
319
  style: StrokeStyle | Reference<"strokeStyle">;
228
320
  };
229
321
  /**
230
- * Individual shadow definition
322
+ * A single shadow definition.
323
+ * This is the basic building block for shadow tokens.
231
324
  */
232
325
  type ShadowObject = {
326
+ /** The color of the shadow */
233
327
  color: TokenValue<"color">;
328
+ /** Horizontal offset of the shadow */
234
329
  offsetX: TokenValue<"dimension">;
330
+ /** Vertical offset of the shadow */
235
331
  offsetY: TokenValue<"dimension">;
332
+ /** How much the shadow should blur */
236
333
  blur: TokenValue<"dimension">;
334
+ /** How much the shadow should spread */
237
335
  spread: TokenValue<"dimension">;
336
+ /** Whether the shadow should be inset */
238
337
  inset?: boolean;
239
338
  };
240
339
  /**
241
- * Shadow token that can be single or multiple shadows
340
+ * A shadow can be either a single shadow or multiple shadows.
341
+ * Multiple shadows are rendered in order, with later shadows appearing on top.
242
342
  */
243
343
  type Shadow = ShadowObject | ShadowObject[];
244
344
  /**
245
- * Color stop in a gradient
345
+ * A single stop in a gradient.
346
+ * Defines the color and position of a point in the gradient.
246
347
  */
247
348
  type GradientStop = {
349
+ /** The color at this point in the gradient */
248
350
  color: TokenValue<"color">;
351
+ /** The position of this point in the gradient (0-1) */
249
352
  position: number | Reference<"number">;
250
353
  };
251
354
  /**
252
- * Gradient defined as a list of color stops
355
+ * A gradient is defined by a series of stops.
356
+ * The stops define how the gradient transitions between colors.
253
357
  */
254
358
  type Gradient = GradientStop[];
255
359
 
256
360
  /**
257
- * Source information for a token, tracking its collection and theme
361
+ * Source information for a token, tracking its collection and theme.
362
+ * This metadata helps with error reporting and token organization.
258
363
  */
259
364
  type TokenSource = {
365
+ /** The collection this token belongs to (e.g., "base", "ui", "marketing") */
260
366
  collection: string;
367
+ /** Optional theme name (e.g., "dark", "light", "high-contrast") */
261
368
  theme?: string;
369
+ /** The path to the source file containing this token */
262
370
  sourcePath: string;
263
371
  };
264
372
  /**
265
- * A complete token tree with collection and theme information
373
+ * A complete token tree with collection and theme information.
374
+ * This represents a single token file's contents with its metadata.
266
375
  */
267
376
  type TokenTree = {
377
+ /** The collection this token tree belongs to (e.g., "base", "ui", "marketing") */
268
378
  collection: string;
379
+ /** Optional theme name (e.g., "dark", "light", "high-contrast") */
269
380
  theme?: string;
381
+ /** The actual token data following the W3C design tokens format */
270
382
  tokens: TokenGroup;
383
+ /** The path to the source file containing these tokens */
271
384
  sourcePath: string;
272
385
  };
273
386
 
274
387
  /**
275
- * Base error type that all other error types extend from.
276
- * Used as the foundation for all error types in the system.
277
- */
278
- type BaseError = {
279
- message: string;
280
- };
281
-
282
- /**
283
- * A flattened token with its source information and path
388
+ * A flattened token with its source information and path.
389
+ * Represents a token after it has been flattened from a nested structure into a flat key-value map.
390
+ * @template T - The type of token (e.g., "color", "dimension", etc.)
284
391
  */
285
392
  type FlattenedToken<T extends TokenType = TokenType> = NodeMetadata & {
393
+ /** The type of the token */
286
394
  $type: T;
395
+ /** The value of the token */
287
396
  $value: TokenValue<T>;
397
+ /** The path to this token in the flattened structure */
288
398
  $path: string;
399
+ /** Information about where this token was loaded from */
289
400
  $source: TokenSource;
401
+ /** The original path before flattening */
290
402
  $originalPath: string;
291
403
  };
292
404
  /**
293
- * A map of flattened tokens and metadata by their lookup path, with an index for quick reference lookups
405
+ * A map of flattened tokens and metadata by their lookup path, with an index for quick reference lookups.
406
+ * Used to store the flattened state of all tokens in a collection.
407
+ * Contains both the token map and a path index for efficient lookups.
294
408
  */
295
409
  type FlattenedTokens = {
410
+ /** Map of token paths to their flattened tokens or metadata */
296
411
  tokens: {
412
+ /** Token path as key, flattened token or metadata as value */
297
413
  [lookupKey: string]: FlattenedToken | NodeMetadata;
298
414
  };
415
+ /** Index mapping original paths to their namespaced keys for quick lookups */
299
416
  pathIndex: Map<string, string>;
300
417
  };
301
418
  /**
302
- * An error that occurred during token flattening
419
+ * An error that occurred during token flattening.
420
+ * Extends the base error type with flattening-specific information.
303
421
  */
304
422
  type FlattenError = BaseError & {
423
+ /** The path to the token that failed flattening */
305
424
  path: string;
425
+ /** Source information about where the token was loaded from */
306
426
  source: TokenSource;
307
427
  };
308
428
 
309
429
  /**
310
- * An error that occurred during token validation
430
+ * Represents a single CSS file output with its path and content
311
431
  */
312
- type ValidationError = BaseError & {
432
+ type CSSFile = {
433
+ /** The path where the CSS file will be written */
313
434
  path: string;
314
- source: TokenSource;
435
+ /** The CSS content to write to the file */
436
+ css: string;
437
+ };
438
+ /**
439
+ * Represents multiple CSS file outputs from generateSeparateFiles or generateSingleFile
440
+ */
441
+ type CSSFileOutput = CSSFile[];
442
+
443
+ /**
444
+ * Data structure for loading tokens from memory.
445
+ * Maps file paths to their token content and metadata.
446
+ * Used for programmatic token loading.
447
+ */
448
+ type TokenMemoryData = Record<string, {
449
+ /** The collection name this token belongs to */
450
+ collection: string;
451
+ /** Optional theme name for themed tokens */
452
+ theme?: string;
453
+ /** The raw token content as a string */
454
+ content: string;
455
+ }>;
456
+ /**
457
+ * An error that occurred during token loading.
458
+ * Extends the base error type with file-specific information.
459
+ */
460
+ type LoadError = BaseError & {
461
+ /** The file path where the error occurred */
462
+ file: string;
315
463
  };
316
464
 
317
465
  /**
318
- * A resolved token with its final value
466
+ * A resolved token with its final value.
467
+ * Contains both the original token data and its resolved value after reference resolution.
468
+ * @template T - The type of token (e.g., "color", "dimension", etc.)
319
469
  */
320
470
  type ResolvedToken<T extends TokenType = TokenType> = NodeMetadata & {
471
+ /** The type of the token */
321
472
  $type: T;
473
+ /** The original value of the token, which may contain references */
322
474
  $value: RawTokenValue<T>;
475
+ /** The path to this token in the token tree */
323
476
  $path: string;
477
+ /** Information about where this token was loaded from */
324
478
  $source: TokenSource;
479
+ /** The original path before any resolution */
325
480
  $originalPath: string;
481
+ /** The final resolved value after all references are resolved */
326
482
  $resolvedValue: RawTokenValue<T>;
327
483
  };
328
484
  /**
329
- * A map of resolved tokens by their lookup path
485
+ * A map of resolved tokens by their lookup path.
486
+ * Used to store the final resolved state of all tokens in a collection.
487
+ * Keys are token paths, values are either resolved tokens or node metadata.
330
488
  */
331
489
  type ResolvedTokens = {
490
+ /** Token path as key, resolved token or metadata as value */
332
491
  [lookupKey: string]: ResolvedToken | NodeMetadata;
333
492
  };
334
493
  /**
335
- * Type of resolution error that occurred
494
+ * Type of resolution error that occurred.
495
+ * - "circular": A circular reference was detected
496
+ * - "missing": A referenced token could not be found
497
+ * - "type-mismatch": A referenced token's type doesn't match the expected type
336
498
  */
337
499
  type ResolutionErrorType = "circular" | "missing" | "type-mismatch";
338
500
  /**
339
- * An error that occurred during token resolution
501
+ * An error that occurred during token resolution.
502
+ * Extends the base error type with resolution-specific information.
340
503
  */
341
504
  type ResolutionError = BaseError & {
505
+ /** The type of resolution error that occurred */
342
506
  type: ResolutionErrorType;
507
+ /** The path to the token that failed resolution */
343
508
  path: string;
509
+ /** Source information about where the token was loaded from */
344
510
  source: TokenSource;
345
511
  };
346
512
 
347
513
  /**
348
- * A warning that occurred during token normalization
349
- */
350
- type NormalizationWarning = {
351
- type: "warning";
352
- message: string;
353
- file: string;
354
- collection: string;
355
- theme?: string;
356
- };
357
- /**
358
- * An error that occurred during token normalization
359
- */
360
- type NormalizationError = ValidationError & {
361
- collection: string;
362
- theme: string;
363
- };
364
- /**
365
- * A set of tokens for a theme, including metadata nodes
366
- */
367
- type ThemeTokenSet = {
368
- default: ResolvedTokens;
369
- [theme: string]: ResolvedTokens;
370
- };
371
- /**
372
- * Normalized tokens organized by collection and theme
373
- */
374
- type NormalizedTokens = {
375
- [collection: string]: ThemeTokenSet;
376
- };
377
- /**
378
- * Result of the normalization process
514
+ * An error that occurred during token validation.
515
+ * Extends the base error type with token-specific information.
379
516
  */
380
- type NormalizeResult = {
381
- tokens: NormalizedTokens;
382
- errors: NormalizationError[];
383
- warnings: NormalizationWarning[];
517
+ type ValidationError = BaseError & {
518
+ /** The path to the token that failed validation */
519
+ path: string;
520
+ /** Source information about where the token was loaded from */
521
+ source: TokenSource;
384
522
  };
385
523
 
386
524
  /**
387
- * Result of loading token trees from files or memory
388
- */
389
- type LoadResult = {
390
- trees: TokenTree[];
391
- errors: LoadError[];
392
- };
393
- /**
394
- * Data structure for loading tokens from memory
525
+ * A warning that occurred during token normalization.
526
+ * Provides information about non-critical issues during the normalization process.
395
527
  */
396
- type TokenMemoryData = Record<string, {
528
+ type NormalizationWarning = {
529
+ /** The type of the warning */
530
+ type: "warning";
531
+ /** A human-readable message describing the warning */
532
+ message: string;
533
+ /** The file where the warning occurred */
534
+ file: string;
535
+ /** The collection where the warning occurred */
397
536
  collection: string;
537
+ /** The theme where the warning occurred, if applicable */
398
538
  theme?: string;
399
- content: string;
400
- }>;
401
- /**
402
- * An error that occurred during token loading
403
- */
404
- type LoadError = BaseError & {
405
- file: string;
406
539
  };
407
540
 
408
541
  /**
409
- * Result of running the tokens-to-CSS pipeline
542
+ * Result of running the tokens-to-CSS pipeline.
543
+ * Contains the generated CSS files, token trees, and any errors or warnings.
410
544
  */
411
545
  type TokensToCSSPipelineResult = {
546
+ /** The generated CSS files */
412
547
  output: CSSFileOutput;
548
+ /** The loaded token trees */
413
549
  trees: TokenTree[];
550
+ /** Any errors that occurred during pipeline execution */
414
551
  errors: PipelineErrors;
552
+ /** Any warnings that occurred during pipeline execution */
415
553
  warnings: PipelineWarnings;
416
554
  };
417
555
  /**
418
- * Common error types that can occur during pipeline execution
556
+ * Common error types that can occur during pipeline execution.
557
+ * Organizes errors by the pipeline stage where they occurred.
419
558
  */
420
559
  type PipelineErrors = {
560
+ /** Errors that occurred during token loading */
421
561
  load: LoadError[];
562
+ /** Errors that occurred during token flattening */
422
563
  flatten: FlattenError[];
564
+ /** Errors that occurred during token validation */
423
565
  validation: ValidationError[];
566
+ /** Errors that occurred during token resolution */
424
567
  resolution: ResolutionError[];
425
568
  };
426
569
  /**
427
- * Common warning types that can occur during pipeline execution
570
+ * Common warning types that can occur during pipeline execution.
571
+ * Organizes warnings by the pipeline stage where they occurred.
428
572
  */
429
573
  type PipelineWarnings = {
574
+ /** Warnings that occurred during token normalization */
430
575
  normalization: NormalizationWarning[];
431
576
  };
432
577
  /**
433
- * Result of running the validation pipeline
578
+ * Result of running the validation pipeline.
579
+ * Contains the validated token trees, flattened tokens, and resolved tokens.
434
580
  */
435
581
  type ValidationPipelineResult = {
582
+ /** The loaded token trees */
436
583
  trees: TokenTree[];
584
+ /** The flattened tokens */
437
585
  flattenedTokens: FlattenedTokens;
586
+ /** The resolved tokens */
438
587
  resolved: ResolvedTokens;
588
+ /** Any errors that occurred during pipeline execution */
439
589
  errors: PipelineErrors;
440
590
  };
441
591
  /**
442
- * Options for loading tokens in the validation pipeline
592
+ * Options for loading tokens in the validation pipeline.
593
+ * Specifies whether to load tokens from files or memory.
443
594
  */
444
595
  type TokenLoader = {
445
596
  type: "files";
@@ -449,210 +600,244 @@ type TokenLoader = {
449
600
  data: TokenMemoryData;
450
601
  };
451
602
  /**
452
- * Options for configuring the validation pipeline
603
+ * Options for configuring the validation pipeline.
604
+ * Controls how tokens are loaded and processed.
453
605
  */
454
606
  type ValidationPipelineOptions = {
607
+ /** The token loader configuration */
455
608
  loader: TokenLoader;
456
609
  };
457
610
  /**
458
- * Result of running the generation pipeline
611
+ * Result of running the generation pipeline.
612
+ * Contains the generated CSS files and any warnings.
459
613
  */
460
614
  type GenerationPipelineResult = {
615
+ /** The generated CSS files */
461
616
  output: CSSFileOutput;
617
+ /** Any warnings that occurred during pipeline execution */
462
618
  warnings: PipelineWarnings;
463
619
  };
464
620
 
621
+ /**
622
+ * The main pipeline that transforms design tokens into CSS output.
623
+ *
624
+ * This pipeline orchestrates the entire token processing flow:
625
+ * 1. Loads token trees from config or memory
626
+ * 2. Flattens trees into a single structure with source information
627
+ * 3. Validates tokens for correctness
628
+ * 4. Resolves all token references
629
+ * 5. Processes trees into collections and themes
630
+ * 6. Normalizes tokens into a standard format
631
+ * 7. Converts tokens into CSS-ready format
632
+ * 8. Generates final CSS output
633
+ *
634
+ * Each stage can produce errors or warnings, which are collected and returned
635
+ * in the result. The pipeline stops at validation if any errors are found.
636
+ *
637
+ * @param config - The sugarcube configuration
638
+ * @param options - Optional pipeline configuration including a custom token loader
639
+ * @returns The pipeline result containing CSS output, trees, and any errors/warnings
640
+ *
641
+ * @example
642
+ * const result = await tokensToCSSPipeline(config);
643
+ * if (result.errors.validation.length > 0) {
644
+ * console.error("Validation failed:", result.errors.validation);
645
+ * } else {
646
+ * // Use the generated CSS
647
+ * console.log(result.output);
648
+ * }
649
+ */
465
650
  declare function tokensToCSSPipeline(config: SugarcubeConfig, options?: {
466
651
  loader?: TokenLoader;
467
652
  }): Promise<TokensToCSSPipelineResult>;
468
653
 
469
- declare function validationPipeline(config: SugarcubeConfig, options: ValidationPipelineOptions): Promise<ValidationPipelineResult>;
470
-
471
- declare function generationPipeline(trees: TokenTree[], resolved: ResolvedTokens, configState: SugarcubeConfig): Promise<GenerationPipelineResult>;
472
-
473
- declare function loadTreesFromConfig(config: SugarcubeConfig): Promise<LoadResult>;
474
- declare function loadTreesFromMemory(data: TokenMemoryData): Promise<LoadResult>;
475
-
476
- declare function validate(tokens: FlattenedTokens): ValidationError[];
477
-
478
- declare function flatten(trees: TokenTree[]): {
479
- tokens: FlattenedTokens;
480
- errors: FlattenError[];
481
- };
482
-
483
- declare function resolve(tokens: FlattenedTokens): {
484
- resolved: ResolvedTokens;
485
- errors: ResolutionError[];
486
- };
487
-
488
654
  /**
489
- * A processed token tree that has been filtered to only include tokens
490
- * from its specific collection and theme, with resolved values
655
+ * A pipeline that validates design tokens without generating CSS output.
656
+ *
657
+ * This pipeline performs the initial stages of token processing:
658
+ * 1. Loads token trees from config or memory
659
+ * 2. Flattens trees into a single structure with source information
660
+ * 3. Validates tokens for correctness
661
+ * 4. Resolves all token references
662
+ *
663
+ * Unlike the main pipeline, this one doesn't generate CSS output.
664
+ * It's useful for:
665
+ * - Validating tokens before full processing
666
+ * - Checking token references
667
+ * - Debugging token structure issues
668
+ *
669
+ * @param config - The sugarcube configuration
670
+ * @param options - Pipeline options including the token loader configuration
671
+ * @returns The validation result containing trees, tokens, and any errors
672
+ *
673
+ * @example
674
+ * const result = await validationPipeline(config, {
675
+ * loader: { type: "config" }
676
+ * });
677
+ *
678
+ * if (result.errors.validation.length > 0) {
679
+ * console.error("Token validation failed:", result.errors.validation);
680
+ * } else {
681
+ * console.log("All tokens are valid!");
682
+ * }
491
683
  */
492
- type ProcessedTree = {
493
- collection: string;
494
- theme?: string;
495
- tokens: ResolvedTokens;
496
- };
684
+ declare function validationPipeline(config: SugarcubeConfig, options: ValidationPipelineOptions): Promise<ValidationPipelineResult>;
497
685
 
498
686
  /**
499
- * Process token trees by filtering resolved tokens based on collection and theme.
500
- * Uses a two-level index (collection -> theme) for O(1) lookups.
687
+ * A pipeline that generates CSS from pre-validated tokens.
688
+ *
689
+ * This pipeline handles the final stages of token processing:
690
+ * 1. Processes trees into collections and themes
691
+ * 2. Normalizes tokens into a standard format
692
+ * 3. Converts tokens into CSS-ready format
693
+ * 4. Generates final CSS output
694
+ *
695
+ * This pipeline exists to support workflows where you want to:
696
+ * - Validate tokens, then generate CSS
697
+ *
698
+ * @param trees - The token trees to process
699
+ * @param resolved - The resolved tokens to convert
700
+ * @param configState - The sugarcube configuration
701
+ * @returns The generation result containing CSS output and any warnings
702
+ *
703
+ * @example
704
+ * // First validate tokens once
705
+ * const validationResult = await validationPipeline(config, options);
706
+ * if (validationResult.errors.validation.length > 0) {
707
+ * throw new Error("Tokens failed validation");
708
+ * }
709
+ *
710
+ * // Generate CSS with different configs
711
+ * const lightThemeConfig = { ...config, options: { color: "hex" } };
712
+ * const darkThemeConfig = { ...config, options: { color: "rgb" } };
713
+ *
714
+ * const lightResult = await generationPipeline(
715
+ * validationResult.trees,
716
+ * validationResult.resolved,
717
+ * lightThemeConfig
718
+ * );
719
+ *
720
+ * const darkResult = await generationPipeline(
721
+ * validationResult.trees,
722
+ * validationResult.resolved,
723
+ * darkThemeConfig
724
+ * );
501
725
  */
502
- declare function processTrees(trees: TokenTree[], resolved: ResolvedTokens): ProcessedTree[];
726
+ declare function generationPipeline(trees: TokenTree[], resolved: ResolvedTokens, configState: SugarcubeConfig): Promise<GenerationPipelineResult>;
503
727
 
504
728
  /**
505
- * A token that has been converted to CSS properties
506
- */
507
- type ConvertedToken<T extends TokenType = TokenType> = ResolvedToken<T> & {
508
- $cssProperties: CSSProperties<T>;
509
- };
510
- /**
511
- * A collection of converted tokens
512
- */
513
- type ConvertedTokens = {
514
- [lookupKey: string]: ConvertedToken | NodeMetadata;
515
- };
516
- /**
517
- * A collection of converted tokens organized by theme
518
- */
519
- type ConvertedThemeTokenSet = {
520
- default: ConvertedTokens;
521
- [theme: string]: ConvertedTokens;
522
- };
523
- /**
524
- * A collection of converted tokens organized by collection and theme
525
- */
526
- type NormalizedConvertedTokens = {
527
- [collection: string]: ConvertedThemeTokenSet;
528
- };
529
- /**
530
- * CSS property types for different token types
531
- */
532
- 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;
533
- /**
534
- * Simple CSS properties with a single value
535
- */
536
- type SimpleCSSProperties = {
537
- value: string | number;
538
- featureValues?: Array<{
539
- query: string;
540
- value: string;
541
- }>;
542
- };
543
- /**
544
- * CSS properties that are always broken down into multiple properties
545
- */
546
- type AlwaysDecomposedProperties = CSSTypographyProperties;
547
- /**
548
- * CSS properties specific to typography tokens
549
- */
550
- type CSSTypographyProperties = {
551
- "font-family": string;
552
- "font-size": string;
553
- "font-weight"?: number | string;
554
- "letter-spacing"?: string;
555
- "line-height"?: number | string;
556
- };
557
- /**
558
- * CSS properties for specific token types
729
+ * Loads and validates the sugarcube configuration file from disk.
730
+ *
731
+ * This function:
732
+ * 1. Reads the config file from the specified path
733
+ * 2. Parses and validates the configuration
734
+ * 3. Returns the validated configuration object
735
+ *
736
+ * @param configPath - Path to the config file (default: "sugarcube.config.json")
737
+ * @returns A promise that resolves to the validated configuration
738
+ * @throws Error if the config file is not found or invalid
739
+ *
740
+ * @example
741
+ * // Load default config file
742
+ * const config = await loadConfig();
743
+ *
744
+ * // Load custom config file
745
+ * const config = await loadConfig("./config/sugarcube.json");
559
746
  */
560
- type CSSBorderProperties = {
561
- value: string;
562
- };
563
- type CSSShadowProperties = {
564
- value: string;
565
- };
566
- type CSSGradientProperties = {
567
- value: string;
568
- };
569
- type CSSTransitionProperties = {
570
- value: string;
571
- };
572
-
573
- declare function convert(tokens: NormalizedTokens, config: SugarcubeConfig): NormalizedConvertedTokens;
747
+ declare function loadConfig(configPath?: string): Promise<SugarcubeConfig>;
574
748
 
575
749
  /**
576
- * Normalizes processed token trees into a collection-theme-token structure.
750
+ * Validates a sugarcube configuration object against the schema.
577
751
  *
578
- * This stage:
579
- * 1. Organizes tokens by collection and theme
580
- * 2. Removes collection prefixes from token keys (e.g., "default.color.primary" -> "color.primary")
581
- * 3. Preserves metadata nodes
582
- * 4. Maintains theme isolation (tokens only appear in their specified theme)
752
+ * This function:
753
+ * 1. Validates the configuration structure using the schema
754
+ * 2. Checks for duplicate filenames across collections
755
+ * 3. Returns the validated configuration if successful
583
756
  *
584
- * The output structure is:
585
- * {
586
- * [collection]: {
587
- * [theme]: {
588
- * [tokenKey]: Token
589
- * }
590
- * }
591
- * }
757
+ * @param config - The configuration object to validate
758
+ * @returns The validated configuration
759
+ * @throws Error if the configuration is invalid or contains duplicate filenames
592
760
  *
593
- * For example:
594
- * {
595
- * default: {
596
- * default: { "color.primary": { $value: "#FF0000" } },
597
- * dark: { "color.primary": { $value: "#000000" } }
598
- * },
599
- * components: {
600
- * default: { "button.primary": { $value: "#00FF00" } }
761
+ * @example
762
+ * const config = {
763
+ * tokens: {
764
+ * source: ["tokens.json"],
765
+ * type: "custom"
601
766
  * }
602
- * }
767
+ * };
768
+ * const validatedConfig = validateConfig(config);
603
769
  */
604
- declare function normalizeTokens(trees: ProcessedTree[]): NormalizeResult;
605
-
770
+ declare function validateConfig(config: Partial<SugarcubeConfig>): SugarcubeConfig;
606
771
  /**
607
- * Generates CSS variable files from normalized and converted design tokens.
608
- * Output organization is controlled by config.output.css.separate:
772
+ * Parses and validates a JSON configuration string.
609
773
  *
610
- * When separate=false (default):
611
- * - Generates one file per collection
612
- * - Each collection's tokens are combined into a single file named 'tokens.variables.css'
613
- * - Example for collections 'base' and 'ui':
614
- * - base/tokens.variables.css
615
- * - ui/tokens.variables.css
774
+ * This function:
775
+ * 1. Parses the JSON string into a configuration object
776
+ * 2. Validates the configuration using validateConfig
777
+ * 3. Returns the validated configuration if successful
616
778
  *
617
- * When separate=true:
618
- * - Generates multiple files per collection, based on source filenames
619
- * - Files are organized in directories by collection name
620
- * - Example for collection 'base' with source 'base.json' and collection 'ui' with source 'ui.json':
621
- * - base/base.variables.css
622
- * - ui/ui.variables.css
779
+ * @param configString - The JSON configuration string to parse and validate
780
+ * @returns The validated configuration
781
+ * @throws Error if the JSON is invalid or the configuration is invalid
623
782
  *
624
- * Note: Each collection gets its own directory regardless of the 'separate' setting.
625
- * This maintains a clear separation between different token collections.
783
+ * @example
784
+ * const configString = `{
785
+ * "tokens": {
786
+ * "source": ["tokens.json"],
787
+ * "type": "custom"
788
+ * }
789
+ * }`;
790
+ * const config = parseAndValidateConfig(configString);
626
791
  */
627
- declare function generate(tokens: NormalizedConvertedTokens, config: SugarcubeConfig): Promise<CSSGenerationResult>;
792
+ declare function parseAndValidateConfig(configString: string): SugarcubeConfig;
628
793
 
629
794
  /**
630
- * Adds a warning banner to generated CSS content
631
- */
632
- declare function addWarningBanner(cssContent: string): string;
633
- /**
634
- * Gets the token file paths from config for use in warning banners
795
+ * Gets all token source file paths from the configuration.
796
+ *
797
+ * This function handles both single and multiple collection configurations:
798
+ * - Single collection: Returns the source array directly
799
+ * - Multiple collections: Flattens and returns all source paths from all collections
800
+ *
801
+ * @param config - The sugarcube configuration
802
+ * @returns An array of all token source file paths
803
+ *
804
+ * @example
805
+ * // Single collection
806
+ * getTokenPathsFromConfig({ tokens: { source: ["tokens.json"] } })
807
+ * // Returns: ["tokens.json"]
808
+ *
809
+ * // Multiple collections
810
+ * getTokenPathsFromConfig({
811
+ * tokens: {
812
+ * base: { source: ["base.json"] },
813
+ * ui: { source: ["ui.json"] }
814
+ * }
815
+ * })
816
+ * // Returns: ["base.json", "ui.json"]
635
817
  */
636
818
  declare function getTokenPathsFromConfig(config: SugarcubeConfig): string[];
637
819
  /**
638
- * Writes CSS files to disk with directory creation
820
+ * Writes CSS files to disk, creating directories as needed.
821
+ *
822
+ * This function:
823
+ * 1. Creates any missing directories in the file path
824
+ * 2. Optionally adds a warning banner to prevent direct edits
825
+ * 3. Only writes files if the content has changed
826
+ * 4. Handles both single and multiple CSS file outputs
827
+ *
828
+ * @param output - Array of CSS file outputs to write
829
+ * @param addBanner - Whether to add the warning banner (default: true)
830
+ * @param tokenPaths - Optional array of token source paths for the warning banner
831
+ * @returns The original output array
832
+ * @throws Error if file writing fails
833
+ *
834
+ * @example
835
+ * await writeCSSFilesToDisk([
836
+ * { path: "styles/tokens.css", css: "body { color: red; }" }
837
+ * ]);
639
838
  */
640
839
  declare function writeCSSFilesToDisk(output: CSSFileOutput, addBanner?: boolean, tokenPaths?: string[]): Promise<CSSFileOutput>;
641
840
 
642
- /**
643
- * Validates the configuration object against the schema
644
- */
645
- declare function validateConfig(config: Partial<SugarcubeConfig>): SugarcubeConfig;
646
- /**
647
- * Parses and validates a JSON configuration string
648
- */
649
- declare function parseAndValidateConfig(configString: string): SugarcubeConfig;
650
-
651
- /**
652
- * Loads and validates the config file from disk
653
- */
654
- declare function loadConfig(configPath?: string): Promise<SugarcubeConfig>;
655
-
656
841
  /**
657
842
  * Manages the CSS index file that imports all CSS files.
658
843
  * @param options.cssOutputDirectory - Directory where the index.css will be created/updated
@@ -673,24 +858,24 @@ declare const configSchema: z.ZodObject<{
673
858
  type: z.ZodEnum<["starter-kit", "custom"]>;
674
859
  themes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodString, "many">>>;
675
860
  }, "strip", z.ZodTypeAny, {
676
- source: string[];
677
861
  type: "starter-kit" | "custom";
862
+ source: string[];
678
863
  themes?: Record<string, string[]> | undefined;
679
864
  }, {
680
- source: string[];
681
865
  type: "starter-kit" | "custom";
866
+ source: string[];
682
867
  themes?: Record<string, string[]> | undefined;
683
868
  }>, z.ZodRecord<z.ZodString, z.ZodObject<{
684
869
  source: z.ZodArray<z.ZodString, "many">;
685
870
  type: z.ZodEnum<["starter-kit", "custom"]>;
686
871
  themes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodString, "many">>>;
687
872
  }, "strip", z.ZodTypeAny, {
688
- source: string[];
689
873
  type: "starter-kit" | "custom";
874
+ source: string[];
690
875
  themes?: Record<string, string[]> | undefined;
691
876
  }, {
692
- source: string[];
693
877
  type: "starter-kit" | "custom";
878
+ source: string[];
694
879
  themes?: Record<string, string[]> | undefined;
695
880
  }>>]>;
696
881
  options: z.ZodOptional<z.ZodObject<{
@@ -773,12 +958,12 @@ declare const configSchema: z.ZodObject<{
773
958
  }>;
774
959
  }, "strip", z.ZodTypeAny, {
775
960
  tokens: {
776
- source: string[];
777
961
  type: "starter-kit" | "custom";
962
+ source: string[];
778
963
  themes?: Record<string, string[]> | undefined;
779
964
  } | Record<string, {
780
- source: string[];
781
965
  type: "starter-kit" | "custom";
966
+ source: string[];
782
967
  themes?: Record<string, string[]> | undefined;
783
968
  }>;
784
969
  output: {
@@ -803,12 +988,12 @@ declare const configSchema: z.ZodObject<{
803
988
  } | undefined;
804
989
  }, {
805
990
  tokens: {
806
- source: string[];
807
991
  type: "starter-kit" | "custom";
992
+ source: string[];
808
993
  themes?: Record<string, string[]> | undefined;
809
994
  } | Record<string, {
810
- source: string[];
811
995
  type: "starter-kit" | "custom";
996
+ source: string[];
812
997
  themes?: Record<string, string[]> | undefined;
813
998
  }>;
814
999
  output: {
@@ -833,4 +1018,4 @@ declare const configSchema: z.ZodObject<{
833
1018
  } | undefined;
834
1019
  }>;
835
1020
 
836
- 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, addWarningBanner, configSchema, convert, flatten, generate, generationPipeline, getTokenPathsFromConfig, loadConfig, loadTreesFromConfig, loadTreesFromMemory, manageCSSIndex, normalizeTokens, parseAndValidateConfig, processTrees, resolve, tokensToCSSPipeline, validate, validateConfig, validationPipeline, writeCSSFilesToDisk };
1021
+ export { type ResolvedToken, type ResolvedTokens, type SugarcubeConfig, type TokenCollection, type TokenLoader, type TokenTree, type ValidationPipelineResult, configSchema, generationPipeline, getTokenPathsFromConfig, loadConfig, manageCSSIndex, parseAndValidateConfig, tokensToCSSPipeline, validateConfig, validationPipeline, writeCSSFilesToDisk };