@koobiq/tokens-builder 4.0.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,32 +12,47 @@ various output formats like SCSS, CSS, and TypeScript.
12
12
 
13
13
  ## Typography composite tokens
14
14
 
15
- Tokens builder supports usage of [composite tokens](https://design-tokens.github.io/community-group/format/#composite-design-token) for CSS platform.
16
- For now, typography token sets are supported.
15
+ Tokens builder supports DTCG-style `typography` composites and serializes their values for CSS, SCSS, and TypeScript.
16
+ The `fontSize`, `lineHeight`, and `letterSpacing` values share the dimension object shape:
17
17
 
18
- ### Example of usage
19
-
20
- ```json
18
+ ```json5
21
19
  {
22
- "<component-name>": {
23
- "font": {
24
- "type": "font",
25
- "<token-with-composite-token-reference>": "{typography.<typography-set>}"
20
+ typography: {
21
+ headline: {
22
+ $type: 'typography',
23
+ $value: {
24
+ fontSize: { value: 28, unit: 'px' },
25
+ lineHeight: { value: 32, unit: 'px' },
26
+ letterSpacing: { value: 0, unit: 'px' },
27
+ fontWeight: 700,
28
+ fontFamily: '{font.family.accent}',
29
+ textTransform: 'initial',
30
+ fontFeatureSettings: '"calt", "kern", "liga"'
31
+ }
26
32
  }
27
33
  }
28
34
  }
29
35
  ```
30
36
 
31
- where `<typography-set>` is a set from `@koobiq/design-tokens/web/properties/typography.json5`
37
+ The `kbq/expand-typography` preprocessor expands the composite before Style Dictionary resolves references.
38
+ The `kbq-value/dimension` transform serializes `{ value, unit }` for every output platform:
32
39
 
33
- "type": "font" property is **required.**
40
+ ```css
41
+ --kbq-typography-headline-font-size: 28px;
42
+ --kbq-typography-headline-line-height: 32px;
43
+ --kbq-typography-headline-letter-spacing: 0px;
44
+ ```
34
45
 
35
- output:
46
+ A composite may be aliased whole (`"$value": "{typography.headline}"`) or may reference individual sub-properties.
47
+ The preprocessor preserves those references.
36
48
 
37
- ```
38
- --kbq-<component-name>-font-<token-with-composite-token-reference>-font-size: <value>;
39
- --kbq-<component-name>-font-<token-with-composite-token-reference>-font-weight: <value>;
40
- --kbq-<component-name>-font-<token-with-composite-token-reference>-line-height: <value>;
41
- --kbq-<component-name>-font-<token-with-composite-token-reference>-font-family: <value>;
42
- // ...etc
43
- ```
49
+ ### Koobiq extensions
50
+
51
+ This is not a claim of strict DTCG conformance for the complete composite:
52
+
53
+ - `lineHeight` is an absolute dimension. DTCG `typography` instead defines it as a unitless `number` multiplier.
54
+ - `fontStyle`, `textTransform`, and `fontFeatureSettings` are Koobiq properties outside the DTCG `typography` property list.
55
+
56
+ The preprocessor accepts complete and partial composites, token references, and existing CSS dimension strings.
57
+ Invalid dimension objects fail the build with the token path instead of producing `[object Object]`.
58
+ Other Koobiq-specific sub-properties continue to expand using their property names as types.
package/build.js CHANGED
@@ -9,9 +9,12 @@ import registerThemeAttributes from './transforms/attribute/theme.js';
9
9
  import registerScssValue from './transforms/attribute/scss-value.js';
10
10
  import registerDeprecationComment from './transforms/attribute/deprecation-comment.js';
11
11
  import registerCustomKebab from './transforms/name/custom-kebab.js';
12
+ import registerDimension from './transforms/value/dimension.js';
12
13
 
13
14
  // ==== Include custom preprocessors ====
14
15
  import registerExpandTypography from './preprocessors/expand-typography.js';
16
+ import registerDropTransparentShadowLayers from './preprocessors/drop-transparent-shadow-layers.js';
17
+ import registerPrivateTokens from './preprocessors/private.js';
15
18
 
16
19
  // ==== Include custom filters ====
17
20
  import registerTypographyFilter from './filters/typography.js';
@@ -26,6 +29,7 @@ import registerTsGroup from './transformGroups/ts.js';
26
29
  import registerTypographyFormat from './formats/typography.js';
27
30
  import registerVariablesFormat from './formats/variables.js';
28
31
  import registerComponentFormat from './formats/component.js';
32
+ import registerPaletteFormat from './formats/palette.js';
29
33
 
30
34
  // ==== Include custom actions ====
31
35
  import registerCssIndex from './actions/css-index.js';
@@ -37,8 +41,11 @@ registerThemeAttributes(StyleDictionary);
37
41
  registerScssValue(StyleDictionary);
38
42
  registerDeprecationComment(StyleDictionary);
39
43
  registerCustomKebab(StyleDictionary);
44
+ registerDimension(StyleDictionary);
40
45
 
41
46
  registerExpandTypography(StyleDictionary);
47
+ registerDropTransparentShadowLayers(StyleDictionary);
48
+ registerPrivateTokens(StyleDictionary);
42
49
 
43
50
  registerTypographyFilter(StyleDictionary);
44
51
  registerMdTypographyFilter(StyleDictionary);
@@ -50,6 +57,7 @@ registerTsGroup(StyleDictionary);
50
57
  registerTypographyFormat(StyleDictionary);
51
58
  registerVariablesFormat(StyleDictionary);
52
59
  registerComponentFormat(StyleDictionary);
60
+ registerPaletteFormat(StyleDictionary);
53
61
 
54
62
  registerCssIndex(StyleDictionary);
55
63
 
package/configs/css.js CHANGED
@@ -98,7 +98,7 @@ const components = [
98
98
  const componentRoots = components.map(({ root }) => root);
99
99
 
100
100
  /**
101
- * Tokens authored under web/components — code-block syntax colours, scrollbar, skeleton.
101
+ * Tokens authored under web/components — code-block syntax colors, scrollbar, skeleton.
102
102
  *
103
103
  * Matched on the token's own path rather than its `filePath`: Style Dictionary leaves `filePath`
104
104
  * undefined on a token whose value is null, and those are exactly the deliberately-unstyled
@@ -187,7 +187,7 @@ export default {
187
187
  },
188
188
  {
189
189
  destination: sliced('typography.css'),
190
- format: 'css/variables',
190
+ format: 'kbq-css/variables',
191
191
  filter: (token) => token.attributes.category === 'typography',
192
192
  options: {
193
193
  outputReferences: true
@@ -195,7 +195,7 @@ export default {
195
195
  },
196
196
  {
197
197
  destination: sliced('md-typography.css'),
198
- format: 'css/variables',
198
+ format: 'kbq-css/variables',
199
199
  filter: (token) => token.attributes.category === 'md-typography',
200
200
  options: {
201
201
  outputReferences: true
@@ -217,7 +217,9 @@ export default {
217
217
  {
218
218
  destination: sliced('light/shadows.css'),
219
219
  format: 'kbq-css/variables',
220
- filter: (token) => token.attributes.light && token.attributes.category === 'shadow',
220
+ // Only the composite shadows; their parameters are private and ship nothing.
221
+ filter: (token) =>
222
+ token.attributes.light && token.filePath?.includes('shadows.json5') && token.$type === 'shadow',
221
223
  options: {
222
224
  selector: '.kbq-light',
223
225
  outputReferences: true
@@ -237,7 +239,8 @@ export default {
237
239
  {
238
240
  destination: sliced('dark/shadows.css'),
239
241
  format: 'kbq-css/variables',
240
- filter: (token) => token.attributes.dark && token.attributes.category === 'shadow',
242
+ filter: (token) =>
243
+ token.attributes.dark && token.filePath?.includes('shadows.json5') && token.$type === 'shadow',
241
244
  options: {
242
245
  selector: '.kbq-dark',
243
246
  outputReferences: true
@@ -252,7 +255,7 @@ export default {
252
255
  outputReferences: true
253
256
  }
254
257
  },
255
- // The three component token sets that survived v4 (code-block syntax colours,
258
+ // The three component token sets that survived v4 (code-block syntax colors,
256
259
  // scrollbar, skeleton). Only consumers of those components need them, so they are
257
260
  // opt-in: kept out of index.css and out of the css-tokens*.css aggregates, and
258
261
  // shipped as their own triple mirroring the css-tokens*.css naming.
@@ -285,7 +288,7 @@ export default {
285
288
  },
286
289
  {
287
290
  destination: 'css-tokens.css',
288
- format: 'css/variables',
291
+ format: 'kbq-css/variables',
289
292
  filter: (token) =>
290
293
  hasValue(token) &&
291
294
  !isComponent(token) &&
package/configs/index.js CHANGED
@@ -2,6 +2,7 @@ import { join } from 'node:path';
2
2
  import scssConfig from './scss.js';
3
3
  import jsConfig from './js.js';
4
4
  import cssConfig from './css.js';
5
+ import { isPrivate } from '../filters/private.js';
5
6
 
6
7
  const filterObj = {
7
8
  options: {
@@ -10,20 +11,38 @@ const filterObj = {
10
11
  }
11
12
  };
12
13
 
14
+ /**
15
+ * Composes privacy into a file's filter. Style Dictionary has no platform-level filter, so this runs
16
+ * once for every file of every platform: a private token ships in no file, on any platform.
17
+ *
18
+ * A filter has to be a function here, because a filter given by name would have to be looked up in
19
+ * the Style Dictionary instance, which this module does not have.
20
+ */
21
+ const publicOnly = (filter) => {
22
+ if (filter === undefined) return (token) => !isPrivate(token);
23
+ if (typeof filter === 'function') return (token, options) => !isPrivate(token) && filter(token, options);
24
+
25
+ throw new Error(`A file filter must be a function, so that privacy can be composed into it: ${filter}`);
26
+ };
27
+
13
28
  function filterOptions(platforms) {
14
29
  const platformObj = {};
15
30
 
16
31
  platforms.map((p) => Object.assign(platformObj, p));
17
32
 
18
33
  Object.keys(platformObj).forEach((p) => {
19
- platformObj[p].files = platformObj[p].files.map((f) => ({
20
- ...f,
21
- ...filterObj,
22
- options: {
23
- ...(f.options ?? {}),
24
- ...filterObj.options
25
- }
26
- }));
34
+ platformObj[p] = {
35
+ ...platformObj[p],
36
+ files: platformObj[p].files.map((f) => ({
37
+ ...f,
38
+ ...filterObj,
39
+ filter: publicOnly(f.filter),
40
+ options: {
41
+ ...(f.options ?? {}),
42
+ ...filterObj.options
43
+ }
44
+ }))
45
+ };
27
46
  });
28
47
 
29
48
  return platformObj;
@@ -55,8 +74,12 @@ export default (theme) => {
55
74
  // here is flat (--kbq-typography-headline-font-size, $typography-headline-font-size),
56
75
  // so they get expanded back into one token per sub-property. See the preprocessor for
57
76
  // why this isn't Style Dictionary's built-in `expand` option.
58
- // Shadows stay composite — `shadow/css/shorthand` renders them as one box-shadow.
59
- preprocessors: ['kbq/expand-typography'],
77
+ // Shadows stay composite — `shadow/css/shorthand` renders them as one box-shadow. Layers with
78
+ // a transparent color are dropped first (kbq/drop-transparent-shadow-layers).
79
+ // Typography is expanded first, so that the sub-properties of a private composite are private
80
+ // tokens of their own. Then private references are replaced with public aliases or values
81
+ // (kbq/private), before transparent layers are dropped and the standard transforms run.
82
+ preprocessors: ['kbq/expand-typography', 'kbq/private', 'kbq/drop-transparent-shadow-layers'],
60
83
  // Fail the build on transform errors instead of printing them. Without this a transform
61
84
  // that throws on a value (say a dimension transform meeting `letter-spacing: normal`)
62
85
  // is caught by Style Dictionary, quietly falls back to the untransformed value and only
package/configs/js.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { hasValue } from '../filters/has-value.js';
2
2
 
3
+ const shipped = (token) => hasValue(token);
4
+
3
5
  export default {
4
6
  js: {
5
7
  transformGroup: 'kbq/ts',
@@ -9,17 +11,17 @@ export default {
9
11
  {
10
12
  destination: 'js/index.mjs',
11
13
  format: 'javascript/es6',
12
- filter: hasValue
14
+ filter: shipped
13
15
  },
14
16
  {
15
17
  destination: 'js/index.js',
16
18
  format: 'javascript/module-flat',
17
- filter: hasValue
19
+ filter: shipped
18
20
  },
19
21
  {
20
22
  destination: 'js/index.d.ts',
21
23
  format: 'typescript/es6-declarations',
22
- filter: hasValue
24
+ filter: shipped
23
25
  }
24
26
  ]
25
27
  }
package/configs/scss.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { isTypography } from '../filters/typography.js';
2
+ import { isMdTypography } from '../filters/md-typography.js';
3
+
1
4
  export default {
2
5
  scss: {
3
6
  transformGroup: 'kbq/scss',
@@ -11,13 +14,18 @@ export default {
11
14
  destination: '_typography.scss',
12
15
  format: 'kbq-scss/typography',
13
16
  mapName: 'koobiq',
14
- filter: 'typography'
17
+ filter: isTypography
15
18
  },
16
19
  {
17
20
  destination: '_md-typography.scss',
18
21
  format: 'kbq-scss/typography',
19
22
  mapName: 'md-typography',
20
- filter: 'md-typography'
23
+ filter: isMdTypography
24
+ },
25
+ {
26
+ destination: '_palette.scss',
27
+ format: 'kbq-scss/palette',
28
+ filter: (token) => token.path[0] === 'plt'
21
29
  }
22
30
  ]
23
31
  }
@@ -1,6 +1,8 @@
1
+ export const isMdTypography = (token) => token.attributes['md-typography'];
2
+
1
3
  export default (StyleDictionary) => {
2
4
  StyleDictionary.registerFilter({
3
5
  name: 'md-typography',
4
- filter: (token) => token.attributes['md-typography']
6
+ filter: isMdTypography
5
7
  });
6
8
  };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Internal tokens: intermediate values that exist to be referenced and inherited, and that ship no
3
+ * variable of their own on any platform.
4
+ *
5
+ * They are marked in the sources with `$extensions: { 'io.koobiq': { private: true } }`, on the
6
+ * token or on its group, and normalised to a plain `private` key by preprocessors/private.js. The
7
+ * filter that keeps them out of every output is composed in configs/index.js.
8
+ */
9
+ export const isPrivate = (token) => token.private === true;
@@ -1,6 +1,8 @@
1
+ export const isTypography = (token) => token.attributes.typography;
2
+
1
3
  export default (StyleDictionary) => {
2
4
  StyleDictionary.registerFilter({
3
5
  name: 'typography',
4
- filter: (token) => token.attributes.typography
6
+ filter: isTypography
5
7
  });
6
8
  };
@@ -5,7 +5,7 @@ import { stripThemeFromNames } from './strip-theme.js';
5
5
  * The selector each slice of a component's tokens belongs under, in write order.
6
6
  *
7
7
  * `:root` holds whatever is theme-independent (scrollbar sizes, for instance); the other two
8
- * hold the light and dark colours.
8
+ * hold the light and dark colors.
9
9
  */
10
10
  const THEMES = [
11
11
  { selector: ':root', belongs: (token) => !token.attributes.light && !token.attributes.dark },
@@ -0,0 +1,36 @@
1
+ /**
2
+ * One Sass variable per top-level `plt.*` family — a map of its steps for a numbered ramp
3
+ * (`$plt-blue: (1: oklch(…), 2: oklch(…), …)`), or a plain variable for a single-value family
4
+ * (`$plt-white: oklch(…)`). Mirrors the shape v3's `_palette.scss` had for the HSL palette, so
5
+ * code written against `@each $step, $color in $plt-blue` keeps working across the v4 upgrade —
6
+ * only the values (and the step range, 1–20 instead of 0–100) changed.
7
+ */
8
+ const toKebab = (key) => key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
9
+
10
+ export default (StyleDictionary) => {
11
+ StyleDictionary.registerFormat({
12
+ name: 'kbq-scss/palette',
13
+ format: function ({ dictionary, options = {} }) {
14
+ const { usesDtcg } = options;
15
+ const valueKey = usesDtcg ? '$value' : 'value';
16
+ const families = dictionary.tokens.plt ?? {};
17
+
18
+ return Object.keys(families)
19
+ .map((family) => {
20
+ const node = families[family];
21
+ const name = `plt-${toKebab(family)}`;
22
+
23
+ if (Object.hasOwn(node, valueKey)) {
24
+ return `$${name}: ${node[valueKey]};\n`;
25
+ }
26
+
27
+ const steps = Object.keys(node)
28
+ .map((step) => ` ${step}: ${node[step][valueKey]},\n`)
29
+ .join('');
30
+
31
+ return `$${name}: (\n${steps});\n`;
32
+ })
33
+ .join('\n');
34
+ }
35
+ });
36
+ };
package/package.json CHANGED
@@ -26,5 +26,5 @@
26
26
  "default": "./*"
27
27
  }
28
28
  },
29
- "version": "4.0.1"
29
+ "version": "4.2.0"
30
30
  }
@@ -0,0 +1,61 @@
1
+ const REFERENCE = /^\{([^{}]+)\}$/;
2
+ const TRANSPARENT = /^(?:transparent|#[0-9a-f]{3}0|#[0-9a-f]{6}00)$/i;
3
+
4
+ const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
5
+
6
+ const at = (root, path) => path.split('.').reduce((node, key) => (isPlainObject(node) ? node[key] : undefined), root);
7
+
8
+ /**
9
+ * True when the color of a shadow layer is fully transparent, so the layer paints nothing.
10
+ * The color is followed through references down to its literal; `lookup` returns the `$value`
11
+ * of the token at a path.
12
+ */
13
+ export const isTransparentLayer = (layer, lookup) => {
14
+ let current = layer?.color;
15
+ const seen = new Set();
16
+ let match;
17
+
18
+ while ((match = REFERENCE.exec(current)) !== null) {
19
+ if (seen.has(match[1])) return false;
20
+
21
+ seen.add(match[1]);
22
+ current = lookup(match[1]);
23
+ }
24
+
25
+ return TRANSPARENT.test(current);
26
+ };
27
+
28
+ /**
29
+ * Every shadow is written with three layers (outline, key, ambient), as in Figma. A layer a theme
30
+ * does not use has a transparent color, and it is dropped from the shadow here, so that no output
31
+ * (CSS, Sass, JS) carries invisible layers: a theme that uses only the outline gets a one-layer
32
+ * `box-shadow`.
33
+ *
34
+ * It is a preprocessor because it has to apply to every platform before values are transformed.
35
+ */
36
+ export default (StyleDictionary) => {
37
+ StyleDictionary.registerPreprocessor({
38
+ name: 'kbq/drop-transparent-shadow-layers',
39
+ preprocessor: (tokens) => {
40
+ const lookup = (path) => at(tokens, path)?.$value;
41
+
42
+ const walk = (node, inherited) => {
43
+ if (!isPlainObject(node)) return node;
44
+
45
+ const type = node.$type ?? inherited;
46
+
47
+ if (type === 'shadow' && '$value' in node) {
48
+ if (!Array.isArray(node.$value)) return node;
49
+
50
+ const layers = node.$value.filter((layer) => !isTransparentLayer(layer, lookup));
51
+
52
+ return layers.length > 0 ? { ...node, $value: layers } : node;
53
+ }
54
+
55
+ return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, walk(value, type)]));
56
+ };
57
+
58
+ return walk(tokens, undefined);
59
+ }
60
+ });
61
+ };
@@ -1,12 +1,17 @@
1
- // DTCG sub-property → DTCG type, mirroring Style Dictionary's own DTCGTypesMap.typography.
2
- // Anything not listed keeps its own name as the type (fontFamily, fontWeight are real DTCG
3
- // types; textTransform / fontFeatureSettings are our documented extension).
1
+ import { assertDimension } from '../transforms/value/dimension.js';
2
+
3
+ // DTCG sub-property → output type. `lineHeight` deliberately stays an absolute dimension instead
4
+ // of the DTCG unitless multiplier. Other unlisted properties keep their own name as the type
5
+ // (fontFamily, fontWeight are real DTCG types; fontStyle / textTransform / fontFeatureSettings are
6
+ // our documented extensions).
4
7
  const SUBTYPES = {
5
8
  fontSize: 'dimension',
6
- letterSpacing: 'dimension',
7
- lineHeight: 'number'
9
+ lineHeight: 'dimension',
10
+ letterSpacing: 'dimension'
8
11
  };
9
12
 
13
+ const DIMENSION_PROPERTIES = ['fontSize', 'lineHeight', 'letterSpacing'];
14
+
10
15
  /** A `$value` that is nothing but a reference, e.g. `{typography.title}`. */
11
16
  const ALIAS = /^\{([^{}]+)\}$/;
12
17
 
@@ -42,6 +47,23 @@ const subProperties = (root, path) => {
42
47
  return undefined;
43
48
  };
44
49
 
50
+ const validateComposite = (node, path) => {
51
+ if (!isPlainObject(node.$value)) return;
52
+
53
+ const tokenPath = path.join('.');
54
+
55
+ for (const property of DIMENSION_PROPERTIES) {
56
+ if (!Object.hasOwn(node.$value, property)) continue;
57
+
58
+ const value = node.$value[property];
59
+
60
+ // Partial composites, references, and legacy CSS strings remain valid builder inputs.
61
+ if (typeof value === 'string') continue;
62
+
63
+ assertDimension(value, `${tokenPath}.$value.${property}`);
64
+ }
65
+ };
66
+
45
67
  /**
46
68
  * Expands `typography` composites into a group of one token per sub-property.
47
69
  *
@@ -81,12 +103,14 @@ export default (StyleDictionary) => {
81
103
  // `inherited` carries the nearest ancestor group's $type, which DTCG lets a token
82
104
  // omit. Style Dictionary applies that inheritance itself, but only after
83
105
  // preprocessors have run, so it has to be tracked here too.
84
- const walk = (node, inherited) => {
106
+ const walk = (node, inherited, path = []) => {
85
107
  if (!isPlainObject(node)) return node;
86
108
 
87
109
  const type = node.$type ?? inherited;
88
110
 
89
111
  if (type === 'typography' && isToken(node)) {
112
+ validateComposite(node, path);
113
+
90
114
  if (isPlainObject(node.$value)) return expand(node, Object.entries(node.$value));
91
115
 
92
116
  const target = aliasTarget(node);
@@ -105,7 +129,9 @@ export default (StyleDictionary) => {
105
129
  );
106
130
  }
107
131
 
108
- return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, walk(value, type)]));
132
+ return Object.fromEntries(
133
+ Object.entries(node).map(([key, value]) => [key, walk(value, type, [...path, key])])
134
+ );
109
135
  };
110
136
 
111
137
  return walk(tokens, undefined);
@@ -0,0 +1,145 @@
1
+ /** The vendor namespace of the marker, in `$extensions` (DTCG §5.2.3). */
2
+ const NS = 'io.koobiq';
3
+ const REFERENCE = /^\{([^{}]+)\}$/;
4
+
5
+ const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
6
+
7
+ const at = (root, path) => path.split('.').reduce((node, key) => (isPlainObject(node) ? node[key] : undefined), root);
8
+
9
+ /**
10
+ * The privacy a node sets for itself: true, false, a string explaining why it is internal, or
11
+ * undefined when it sets none. This mirrors `$deprecated` (DTCG §5.2.4), where `true` marks the token,
12
+ * a string marks it and explains the reason, and `false` opts out of a group's default.
13
+ *
14
+ * Anything else is refused. `'true'` and `'false'` are refused too, even though they are strings: a
15
+ * quoted boolean is a typo, and reading it as a reason would make `private: 'false'` private — the one
16
+ * trap worth keeping closed, since the filter requires `=== true`.
17
+ */
18
+ const ownPrivacy = (node, path) => {
19
+ const value = node.$extensions?.[NS]?.private;
20
+
21
+ if (value === undefined || typeof value === 'boolean') return value;
22
+
23
+ const reason = typeof value === 'string' ? value.trim() : '';
24
+
25
+ if (reason !== '' && !['true', 'false'].includes(reason.toLowerCase())) return reason;
26
+
27
+ throw new Error(
28
+ `${NS} \`private\` must be true, false, or a string explaining why, not ${JSON.stringify(value)}, at ${path.join('.')}`
29
+ );
30
+ };
31
+
32
+ /**
33
+ * Marks every private token of a raw token tree, and returns the marked tree with the paths of the
34
+ * private tokens.
35
+ *
36
+ * A token is private when it, or the group it sits in, sets `$extensions['io.koobiq'].private`
37
+ * to true or to a string explaining why; a token can opt out with `false`. Style Dictionary delegates
38
+ * only `$type` down the tree, so the flag is inherited here, a group's explanation along with it.
39
+ *
40
+ * The flag is normalised to a plain top-level `private: true`, which is what the rest of the build
41
+ * reads, and the explanation, when there is one, to `privateReason` beside it. Neither reaches an
42
+ * output: a private token ships no variable, so the reason only ever surfaces in diagnostics.
43
+ *
44
+ * @param {Object} tree a raw token tree, as read from the source files
45
+ * @returns {{ marked: Object, privates: Set<string> }}
46
+ */
47
+ export const markPrivate = (tree) => {
48
+ const privates = new Set();
49
+
50
+ const mark = (node, inherited, path) => {
51
+ if (!isPlainObject(node)) return node;
52
+
53
+ const privateHere = ownPrivacy(node, path) ?? inherited;
54
+
55
+ if ('$value' in node) {
56
+ if (!privateHere) return node;
57
+
58
+ privates.add(path.join('.'));
59
+
60
+ return typeof privateHere === 'string'
61
+ ? { ...node, private: true, privateReason: privateHere }
62
+ : { ...node, private: true };
63
+ }
64
+
65
+ return Object.fromEntries(
66
+ Object.entries(node).map(([key, child]) => [
67
+ key,
68
+ key.startsWith('$') ? child : mark(child, privateHere, [...path, key])
69
+ ])
70
+ );
71
+ };
72
+
73
+ return { marked: mark(tree, false, []), privates };
74
+ };
75
+
76
+ /**
77
+ * Stops at the first public token, keeping its reference for outputReferences. When no public
78
+ * token is reached, substitutes the private value before Style Dictionary transforms it.
79
+ */
80
+ const resolvePrivate = (path, root, privates, stack) => {
81
+ if (!privates.has(path)) return `{${path}}`;
82
+
83
+ if (stack.includes(path)) {
84
+ throw new Error(`Private reference cycle does not resolve: ${[...stack, path].join(' → ')}`);
85
+ }
86
+
87
+ return rewrite(at(root, path).$value, root, privates, [...stack, path]);
88
+ };
89
+
90
+ // Rewrites every string leaf of a $value, so composite shadows (arrays of layer objects) and
91
+ // typography presets are covered as well as plain string values.
92
+ const rewrite = (value, root, privates, stack = []) => {
93
+ if (typeof value === 'string') {
94
+ const match = REFERENCE.exec(value);
95
+
96
+ if (match) return resolvePrivate(match[1], root, privates, stack);
97
+
98
+ return value.replace(/\{([^{}]+)\}/g, (_reference, path) => {
99
+ const resolved = resolvePrivate(path, root, privates, stack);
100
+
101
+ if (resolved !== null && typeof resolved === 'object') {
102
+ throw new Error(`Cannot interpolate private composite {${path}} into string ${JSON.stringify(value)}`);
103
+ }
104
+
105
+ return String(resolved);
106
+ });
107
+ }
108
+
109
+ if (Array.isArray(value)) return value.map((item) => rewrite(item, root, privates, stack));
110
+ if (isPlainObject(value)) {
111
+ return Object.fromEntries(
112
+ Object.entries(value).map(([key, item]) => [key, rewrite(item, root, privates, stack)])
113
+ );
114
+ }
115
+
116
+ return value;
117
+ };
118
+
119
+ const collapse = (node, root, privates) => {
120
+ if (!isPlainObject(node)) return node;
121
+
122
+ if ('$value' in node) return { ...node, $value: rewrite(node.$value, root, privates) };
123
+
124
+ return Object.fromEntries(
125
+ Object.entries(node).map(([key, child]) => [key, key.startsWith('$') ? child : collapse(child, root, privates)])
126
+ );
127
+ };
128
+
129
+ /**
130
+ * Makes private tokens internal, before any reference is resolved.
131
+ *
132
+ * Nothing is deleted here. Deleting a token before references resolve fails the build with
133
+ * `Reference Errors`, because every alias to it is then dangling. Privacy is applied afterwards, per
134
+ * file, by the filter composed in configs/index.js.
135
+ */
136
+ export default (StyleDictionary) => {
137
+ StyleDictionary.registerPreprocessor({
138
+ name: 'kbq/private',
139
+ preprocessor: (tokens) => {
140
+ const { marked, privates } = markPrivate(tokens);
141
+
142
+ return privates.size > 0 ? collapse(marked, marked, privates) : marked;
143
+ }
144
+ });
145
+ };
@@ -12,6 +12,7 @@ export default (StyleDictionary) => {
12
12
  'kbq-attribute/light',
13
13
  'kbq-attribute/dark',
14
14
  'shadow/css/shorthand',
15
+ 'kbq-value/dimension',
15
16
  'name/custom-kebab',
16
17
  'kbq-attribute/comment'
17
18
  ]
@@ -7,6 +7,7 @@ export default (StyleDictionary) => {
7
7
  'kbq-attribute/md-typography',
8
8
  'name/kebab',
9
9
  'shadow/css/shorthand',
10
+ 'kbq-value/dimension',
10
11
  'kbq-scss/value',
11
12
  'kbq-attribute/comment'
12
13
  ]
@@ -8,6 +8,12 @@ export default (StyleDictionary) => {
8
8
  // - `color/hex` leaves OKLch alone (tinycolor2 cannot parse it) but rewrites
9
9
  // `transparent` / `#00000000`.
10
10
  // Values already carry their units and are valid CSS as authored.
11
- transforms: ['attribute/cti', 'name/pascal', 'shadow/css/shorthand', 'kbq-attribute/comment']
11
+ transforms: [
12
+ 'attribute/cti',
13
+ 'name/pascal',
14
+ 'shadow/css/shorthand',
15
+ 'kbq-value/dimension',
16
+ 'kbq-attribute/comment'
17
+ ]
12
18
  });
13
19
  };
@@ -13,18 +13,23 @@ const toKebab = (path) => {
13
13
  return standardKebab.replace(/-a-(\d+)$/, '-a$1');
14
14
  };
15
15
 
16
+ const THEMES = ['light', 'dark'];
17
+
18
+ // A theme is the category of a token (light.background.card) or, for the shadows, its type (shadow.light.card).
19
+ const isThemeScoped = ({ category, type }) =>
20
+ THEMES.includes(category) || (category === 'shadow' && THEMES.includes(type));
21
+
16
22
  export default (StyleDictionary) => {
17
- // Strips 'light'/'dark' when used as the category segment (e.g. shadow.light.card →
18
- // shadow-card), so theme-scoped tokens don't carry the theme in their variable name —
19
- // the theme lives in the `.kbq-light` / `.kbq-dark` selector instead.
23
+ // Strips 'light'/'dark' from a theme-scoped token (e.g. shadow.light.card → shadow-card), so the
24
+ // theme does not end up in its variable name — the theme lives in the `.kbq-light` / `.kbq-dark`
25
+ // selector instead.
20
26
  StyleDictionary.registerTransform({
21
27
  name: 'name/custom-kebab',
22
28
  type: 'name',
23
29
  transform: (token, platform) => {
24
- const path =
25
- token.attributes.category === 'light' || token.attributes.category === 'dark'
26
- ? token.path.filter((part) => part !== 'light' && part !== 'dark')
27
- : token.path;
30
+ const path = isThemeScoped(token.attributes)
31
+ ? token.path.filter((part) => !THEMES.includes(part))
32
+ : token.path;
28
33
 
29
34
  return toKebab(platform?.prefix ? [platform.prefix, ...path] : path);
30
35
  }
@@ -0,0 +1,46 @@
1
+ const ALIAS = /^\{[^{}]+\}$/;
2
+ const UNITS = new Set(['px', 'rem']);
3
+ const KEYS = 'unit,value';
4
+
5
+ const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
6
+
7
+ export const assertDimension = (value, path, { allowReference = false } = {}) => {
8
+ if (allowReference && typeof value === 'string' && ALIAS.test(value)) return;
9
+
10
+ const valid =
11
+ isPlainObject(value) &&
12
+ Object.keys(value).sort().join(',') === KEYS &&
13
+ Number.isFinite(value.value) &&
14
+ UNITS.has(value.unit);
15
+
16
+ if (!valid) {
17
+ throw new Error(
18
+ `${path}: expected dimension { value: <finite number>, unit: "px" | "rem" }` +
19
+ `${allowReference ? ' or a token reference' : ''}; received ${JSON.stringify(value)}`
20
+ );
21
+ }
22
+ };
23
+
24
+ export const serializeDimension = (value, path) => {
25
+ // Existing dimension strings remain supported. Objects must be complete and valid.
26
+ if (typeof value === 'string') return value;
27
+
28
+ assertDimension(value, path);
29
+
30
+ return `${value.value}${value.unit}`;
31
+ };
32
+
33
+ const tokenPath = (token) => token.path?.join('.') ?? token.name ?? '<unknown token>';
34
+
35
+ export default (StyleDictionary) => {
36
+ StyleDictionary.registerTransform({
37
+ name: 'kbq-value/dimension',
38
+ type: 'value',
39
+ filter: (token) => (token.$type ?? token.type) === 'dimension',
40
+ transform: (token, _config, options) => {
41
+ const value = options?.usesDtcg ? token.$value : token.value;
42
+
43
+ return serializeDimension(value, tokenPath(token));
44
+ }
45
+ });
46
+ };