@link-foundation/ui-tokens 0.0.0-stage → 0.0.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/src/index.d.ts ADDED
@@ -0,0 +1,181 @@
1
+ import type { Diagnostic, RawValue, values } from '@link-foundation/ui-core';
2
+
3
+ export type { Diagnostic };
4
+
5
+ /** The token types: DTCG 2025.10 primitives and composites. */
6
+ export type TokenType =
7
+ | 'color'
8
+ | 'dimension'
9
+ | 'duration'
10
+ | 'number'
11
+ | 'fontFamily'
12
+ | 'fontWeight'
13
+ | 'cubicBezier'
14
+ | 'shadow'
15
+ | 'typography';
16
+
17
+ export type TokenRef = { type: 'token-ref'; path: string };
18
+ export type ColorValue = Extract<values.TypedValue, { type: 'color' }>;
19
+ export type DimensionValue = {
20
+ type: 'dimension';
21
+ value: number;
22
+ unit: 'px' | 'rem';
23
+ };
24
+ export type DurationValue = {
25
+ type: 'duration';
26
+ value: number;
27
+ unit: 'ms' | 's';
28
+ };
29
+
30
+ export interface ShadowLayer {
31
+ color: ColorValue | TokenRef;
32
+ offsetX: DimensionValue | TokenRef;
33
+ offsetY: DimensionValue | TokenRef;
34
+ blur: DimensionValue | TokenRef;
35
+ spread: DimensionValue | TokenRef;
36
+ inset?: boolean;
37
+ }
38
+
39
+ export interface TypographyValue {
40
+ fontFamily: FontFamilyValue | TokenRef;
41
+ fontSize: DimensionValue | TokenRef;
42
+ fontWeight: FontWeightValue | TokenRef;
43
+ letterSpacing: DimensionValue | TokenRef;
44
+ lineHeight: { type: 'number'; value: number } | TokenRef;
45
+ }
46
+
47
+ export type FontFamilyValue = { type: 'fontFamily'; value: string | string[] };
48
+ export type FontWeightValue = { type: 'fontWeight'; value: number | string };
49
+
50
+ /** A token value; after resolution no `token-ref` is left in `value`. */
51
+ export type TokenValue =
52
+ | TokenRef
53
+ | ColorValue
54
+ | DimensionValue
55
+ | DurationValue
56
+ | { type: 'number'; value: number }
57
+ | FontFamilyValue
58
+ | FontWeightValue
59
+ | { type: 'cubicBezier'; value: [number, number, number, number] }
60
+ | { type: 'shadow'; value: ShadowLayer | (ShadowLayer | TokenRef)[] }
61
+ | { type: 'typography'; value: TypographyValue };
62
+
63
+ export interface Token {
64
+ path: string;
65
+ /** `null` for an alias without `(type ...)`. */
66
+ type: TokenType | null;
67
+ value: TokenValue;
68
+ description?: string;
69
+ m3?: string;
70
+ fluent?: string;
71
+ sourceValue?: string;
72
+ mode?: string;
73
+ }
74
+
75
+ export interface TokenSet {
76
+ id: string;
77
+ extends: string[];
78
+ tokens: Token[];
79
+ modes: Record<string, Token[]>;
80
+ }
81
+
82
+ export interface ResolvedToken {
83
+ path: string;
84
+ type: TokenType;
85
+ /** Fully resolved: no alias left. */
86
+ value: TokenValue;
87
+ /** As written, aliases kept. */
88
+ raw: TokenValue;
89
+ /** The target of a whole-token alias. */
90
+ alias?: string;
91
+ description?: string;
92
+ m3?: string;
93
+ fluent?: string;
94
+ sourceValue?: string;
95
+ /** The set that defines the token. */
96
+ set: string;
97
+ /** The mode whose override defines the token. */
98
+ mode?: string;
99
+ }
100
+
101
+ export type ResolvedTokens = Map<string, ResolvedToken> & {
102
+ setId: string;
103
+ mode: string | null;
104
+ /** Per other mode, the tokens that resolve differently in it. */
105
+ modes: Map<string, Map<string, ResolvedToken>>;
106
+ diagnostics: Diagnostic[];
107
+ };
108
+
109
+ export const TOKEN_TYPES: readonly TokenType[];
110
+ export const FONT_WEIGHTS: Readonly<Record<string, number>>;
111
+ export const DIMENSION_UNITS: readonly ['px', 'rem'];
112
+ export const COMPOSITE_FIELDS: Readonly<
113
+ Record<
114
+ 'shadow' | 'typography',
115
+ readonly (readonly [string, string, TokenType])[]
116
+ >
117
+ >;
118
+ /** The `$extensions` key under which `toDtcg` writes modes. */
119
+ export const DTCG_EXTENSION: string;
120
+
121
+ /** Read every token set (`theme` element) of a Links Notation text. */
122
+ export function readTokens(text: string): {
123
+ sets: Map<string, TokenSet>;
124
+ diagnostics: Diagnostic[];
125
+ };
126
+
127
+ /** Whether `path` can name a token (DTCG 2025.10 section 5.1.1). */
128
+ export function isTokenPath(path: unknown): boolean;
129
+
130
+ /** Resolve extends, then mode overrides, then aliases. */
131
+ export function resolveTokens(
132
+ sets: Map<string, TokenSet>,
133
+ setId: string,
134
+ options?: { mode?: string | null }
135
+ ): ResolvedTokens;
136
+
137
+ export interface CssOptions {
138
+ channels?: boolean;
139
+ pack?: boolean;
140
+ paletteSelector?: (palette: string) => string;
141
+ selector?: string;
142
+ prefix?: string;
143
+ modeSelector?: (mode: string) => string;
144
+ modeMedia?: Record<string, string>;
145
+ }
146
+ export function toCss(
147
+ resolved: ResolvedTokens | Map<string, ResolvedTokens>,
148
+ options?: CssOptions
149
+ ): string;
150
+
151
+ export function toDtcg(
152
+ resolved: ResolvedTokens,
153
+ options?: { keepAliases?: boolean }
154
+ ): Record<string, unknown>;
155
+
156
+ export function fromDtcg(
157
+ json: string | Record<string, unknown>,
158
+ options?: { id?: string }
159
+ ): string;
160
+
161
+ export function toSwift(
162
+ resolved: ResolvedTokens,
163
+ options?: { name?: string }
164
+ ): string;
165
+
166
+ export function toKotlin(
167
+ resolved: ResolvedTokens,
168
+ options?: { packageName?: string; name?: string }
169
+ ): string;
170
+
171
+ /** `color.on-primary` -> `--color-on-primary` (`--PREFIX-...` with a prefix). */
172
+ export function cssVariable(path: string, prefix?: string): string;
173
+
174
+ /** Type a raw token value; `null` when it is not of the declared type. */
175
+ export function typeTokenValue(
176
+ raw: RawValue,
177
+ declared?: TokenType
178
+ ): TokenValue | null;
179
+
180
+ /** A token value as the raw Links Notation value it is written as. */
181
+ export function tokenValueRaw(value: TokenValue): RawValue;
package/src/index.js ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @link-foundation/ui-tokens: design tokens written in Links Notation,
3
+ * resolved (extends, modes, aliases) and written as CSS custom properties,
4
+ * DTCG 2025.10 JSON, SwiftUI and Jetpack Compose constants.
5
+ *
6
+ * ```js
7
+ * import { readTokens, resolveTokens, toCss } from '@link-foundation/ui-tokens';
8
+ *
9
+ * const { sets } = readTokens(text);
10
+ * const resolved = resolveTokens(sets, 'material3', { mode: null });
11
+ * toCss(resolved); // ':root {\n --color-primary: #6750a4;\n ...'
12
+ * ```
13
+ */
14
+
15
+ export { readTokens, isTokenPath } from './model.js';
16
+ export { resolveTokens } from './resolve.js';
17
+ export { toCss } from './export/css.js';
18
+ export { toDtcg, DTCG_EXTENSION } from './export/dtcg.js';
19
+ export { fromDtcg } from './import/dtcg.js';
20
+ export { toSwift } from './export/swift.js';
21
+ export { toKotlin } from './export/kotlin.js';
22
+ export { cssVariable } from './names.js';
23
+ export {
24
+ TOKEN_TYPES,
25
+ FONT_WEIGHTS,
26
+ DIMENSION_UNITS,
27
+ COMPOSITE_FIELDS,
28
+ typeTokenValue,
29
+ tokenValueRaw,
30
+ } from './values.js';
package/src/model.js ADDED
@@ -0,0 +1,216 @@
1
+ /**
2
+ * `readTokens(text)`: token sets written in Links Notation.
3
+ *
4
+ * ```lino
5
+ * (material3: theme
6
+ * (extends base)
7
+ * (token color.primary '#6750A4' (description 'Brand colour'))
8
+ * (token color.action (token color.primary))
9
+ * (token font.body Roboto Arial sans-serif)
10
+ * (token weight.strong 600 (type fontWeight))
11
+ * (mode dark
12
+ * (token color.primary '#D0BCFF')))
13
+ * ```
14
+ *
15
+ * The text is read by ui-core `parse` (the official `links-notation`
16
+ * parser plus path folding), so the one-line, multi-line and indented forms
17
+ * all give the same sets. A set is a `theme` element of the ui-dialect
18
+ * vocabulary; `mode` is added to its properties here.
19
+ */
20
+
21
+ import { defaultVocabulary, parse } from '@link-foundation/ui-core';
22
+ import { tokenDiagnostic } from './diagnostics.js';
23
+ import { TOKEN_TYPES, typeTokenValue } from './values.js';
24
+
25
+ /**
26
+ * @typedef {import('./types.js').Token} Token
27
+ * @typedef {import('./types.js').TokenSet} TokenSet
28
+ * @typedef {import('./types.js').Diagnostic} Diagnostic
29
+ */
30
+
31
+ let vocabulary;
32
+
33
+ /** The ui-dialect vocabulary with `(property mode any multi)` on `theme`. */
34
+ function tokensVocabulary() {
35
+ if (vocabulary === undefined) {
36
+ const base = defaultVocabulary();
37
+ const theme = base.kinds.get('theme');
38
+ const properties = new Map(theme.properties).set('mode', {
39
+ type: 'any',
40
+ multi: true,
41
+ });
42
+ vocabulary = {
43
+ ...base,
44
+ kinds: new Map(base.kinds).set('theme', { ...theme, properties }),
45
+ multiValued: new Set([...base.multiValued, 'mode']),
46
+ };
47
+ }
48
+ return vocabulary;
49
+ }
50
+
51
+ const META = new Set(['description', 'type', 'm3', 'fluent', 'source-value']);
52
+ const isMeta = (raw) =>
53
+ Array.isArray(raw) &&
54
+ META.has(raw[0]) &&
55
+ raw.length === 2 &&
56
+ typeof raw[1] === 'string';
57
+
58
+ /**
59
+ * Whether `path` can name a token: dot-separated, non-empty segments that
60
+ * do not start with `$` and contain no `{`, `}` or white space (DTCG
61
+ * 2025.10 section 5.1.1 "Character restrictions").
62
+ */
63
+ export const isTokenPath = (path) =>
64
+ typeof path === 'string' &&
65
+ path
66
+ .split('.')
67
+ .every(
68
+ (part) =>
69
+ part.length > 0 && !part.startsWith('$') && !/[{}\s]/u.test(part)
70
+ );
71
+
72
+ /**
73
+ * Read one `(token PATH VALUE... (description '...') (type T))` link given
74
+ * as its values after `token`.
75
+ * @returns {Token|null}
76
+ */
77
+ function readToken(values, at, diagnostics) {
78
+ const [path, ...rest] = values;
79
+ if (!isTokenPath(path)) {
80
+ diagnostics.push(tokenDiagnostic('invalid-token', 'error', at));
81
+ return null;
82
+ }
83
+ const where = { ...at, token: path };
84
+ const meta = Object.fromEntries(rest.filter(isMeta));
85
+ const parts = rest.filter((raw) => !isMeta(raw));
86
+ if (parts.length === 0) {
87
+ diagnostics.push(tokenDiagnostic('invalid-token', 'error', where));
88
+ return null;
89
+ }
90
+ if (meta.type !== undefined && !TOKEN_TYPES.includes(meta.type)) {
91
+ diagnostics.push(
92
+ tokenDiagnostic('unknown-type', 'error', { ...where, type: meta.type })
93
+ );
94
+ return null;
95
+ }
96
+ // Several values are one list: `(token font.body Roboto Arial sans-serif)`.
97
+ const raw = parts.length === 1 ? parts[0] : parts;
98
+ const value = typeTokenValue(raw, meta.type);
99
+ if (value === null) {
100
+ diagnostics.push(
101
+ tokenDiagnostic('invalid-value', 'error', {
102
+ ...where,
103
+ ...(meta.type === undefined ? {} : { type: meta.type }),
104
+ })
105
+ );
106
+ return null;
107
+ }
108
+ const token = {
109
+ path,
110
+ type: meta.type ?? (value.type === 'token-ref' ? null : value.type),
111
+ value,
112
+ };
113
+ if (meta.description !== undefined) {
114
+ token.description = meta.description;
115
+ }
116
+ if (meta['source-value'] !== undefined) {
117
+ token.sourceValue = meta['source-value'];
118
+ }
119
+ if (meta.m3 !== undefined) {
120
+ token.m3 = meta.m3;
121
+ }
122
+ if (meta.fluent !== undefined) {
123
+ token.fluent = meta.fluent;
124
+ }
125
+ if (at.mode !== undefined) {
126
+ token.mode = at.mode;
127
+ }
128
+ return token;
129
+ }
130
+
131
+ /** Add a token to a list, replacing (with a warning) an earlier one. */
132
+ function addToken(list, token, at, diagnostics) {
133
+ const i = list.findIndex((t) => t.path === token.path);
134
+ if (i === -1) {
135
+ list.push(token);
136
+ return;
137
+ }
138
+ diagnostics.push(
139
+ tokenDiagnostic('duplicate-token', 'warning', { ...at, token: token.path })
140
+ );
141
+ list[i] = token;
142
+ }
143
+
144
+ const isTokenLink = (raw) =>
145
+ Array.isArray(raw) && raw[0] === 'token' && raw.length > 1;
146
+
147
+ function readMode(set, values, diagnostics) {
148
+ const [name, ...links] = values;
149
+ if (typeof name !== 'string') {
150
+ diagnostics.push(tokenDiagnostic('invalid-mode', 'error', { set: set.id }));
151
+ return;
152
+ }
153
+ const at = { set: set.id, mode: name };
154
+ set.modes[name] ??= [];
155
+ for (const link of links) {
156
+ if (!isTokenLink(link)) {
157
+ diagnostics.push(tokenDiagnostic('invalid-token', 'error', at));
158
+ continue;
159
+ }
160
+ const token = readToken(link.slice(1), at, diagnostics);
161
+ if (token !== null) {
162
+ addToken(set.modes[name], token, at, diagnostics);
163
+ }
164
+ }
165
+ }
166
+
167
+ function readSet(node, diagnostics) {
168
+ /** @type {TokenSet} */
169
+ // `modes` has no prototype, so that a mode named `__proto__` is a mode.
170
+ const set = {
171
+ id: node.id,
172
+ extends: [],
173
+ tokens: [],
174
+ modes: Object.create(null),
175
+ };
176
+ for (const property of node.properties) {
177
+ if (property.name === 'extends') {
178
+ set.extends.push(...property.values.filter((v) => typeof v === 'string'));
179
+ } else if (property.name === 'token') {
180
+ const at = { set: set.id };
181
+ const token = readToken(property.values, at, diagnostics);
182
+ if (token !== null) {
183
+ addToken(set.tokens, token, at, diagnostics);
184
+ }
185
+ } else if (property.name === 'mode') {
186
+ readMode(set, property.values, diagnostics);
187
+ }
188
+ }
189
+ return set;
190
+ }
191
+
192
+ /**
193
+ * Read every token set (every `theme` element) of a Links Notation text.
194
+ * Never throws: problems are diagnostics (`syntax-error`, `invalid-token`,
195
+ * `invalid-value`, `unknown-type`, `duplicate-token`, ...).
196
+ * @param {string} text
197
+ * @returns {{ sets: Map<string, TokenSet>, diagnostics: Diagnostic[] }}
198
+ */
199
+ export function readTokens(text) {
200
+ const doc = parse(text, { checks: false, vocabulary: tokensVocabulary() });
201
+ const diagnostics = [...doc.diagnostics];
202
+ const sets = new Map();
203
+ for (const node of doc.roots) {
204
+ if (node.kind !== 'theme') {
205
+ continue;
206
+ }
207
+ if (node.id === null) {
208
+ diagnostics.push(tokenDiagnostic('anonymous-set', 'error', {}));
209
+ continue;
210
+ }
211
+ if (!sets.has(node.id)) {
212
+ sets.set(node.id, readSet(node, diagnostics));
213
+ }
214
+ }
215
+ return { sets, diagnostics };
216
+ }
package/src/names.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Names of a token path in the output languages: `color.on-primary` is
3
+ * `--color-on-primary` in CSS, `colorOnPrimary` in Swift and
4
+ * `ColorOnPrimary` in Kotlin.
5
+ */
6
+
7
+ /** The words of a path: `color.on-primary` -> `['color', 'on', 'primary']`. */
8
+ const words = (path) => path.split(/[.\-_\s]+/u).filter((w) => w.length > 0);
9
+
10
+ const capitalise = (w) => w.charAt(0).toUpperCase() + w.slice(1);
11
+
12
+ /** A name that starts with a digit gets a leading `_`. */
13
+ const identifier = (name) => (/^[0-9]/u.test(name) ? `_${name}` : name);
14
+
15
+ /**
16
+ * `color.on-primary` -> `--color-on-primary`; with the prefix `md`,
17
+ * `--md-color-on-primary`.
18
+ * @param {string} path
19
+ * @param {string} [prefix]
20
+ */
21
+ export const cssVariable = (path, prefix = '') =>
22
+ `--${prefix === '' ? '' : `${prefix}-`}${path.split('.').join('-')}`;
23
+
24
+ /** `color.on-primary` -> `colorOnPrimary` (Swift). */
25
+ export const lowerCamel = (path) => {
26
+ const [first = '', ...rest] = words(path);
27
+ return identifier(
28
+ first.charAt(0).toLowerCase() +
29
+ first.slice(1) +
30
+ rest.map(capitalise).join('')
31
+ );
32
+ };
33
+
34
+ /** `color.on-primary` -> `ColorOnPrimary` (Kotlin). */
35
+ export const upperCamel = (path) =>
36
+ identifier(words(path).map(capitalise).join(''));
package/src/resolve.js ADDED
@@ -0,0 +1,241 @@
1
+ /**
2
+ * `resolveTokens(sets, setId, { mode })`: the tokens one set gives after
3
+ * inheritance, modes and aliases.
4
+ *
5
+ * 1. `extends`: the chain is every set the set extends, depth first, in the
6
+ * order written, then the set itself; a later set overrides an earlier
7
+ * one, so the set's own tokens win and of two parents the later wins.
8
+ * 2. Modes: within each set of the chain, the tokens of `(mode NAME ...)`
9
+ * override the set's own tokens; a child's plain token still overrides a
10
+ * parent's mode token.
11
+ * 3. Aliases: `(token a.b)` (the whole value, a composite field or a shadow
12
+ * layer) is replaced by the resolved value of `a.b`.
13
+ *
14
+ * Problems are diagnostics, never exceptions: `unknown-set`,
15
+ * `extends-cycle`, `unknown-mode`, `unknown-alias`, `alias-cycle` and
16
+ * `type-mismatch`. A token whose alias cannot be resolved is left out.
17
+ */
18
+
19
+ import { tokenDiagnostic } from './diagnostics.js';
20
+ import { mapNestedAliases } from './values.js';
21
+
22
+ /**
23
+ * @typedef {import('./types.js').TokenSet} TokenSet
24
+ * @typedef {import('./types.js').Token} Token
25
+ * @typedef {import('./types.js').ResolvedToken} ResolvedToken
26
+ * @typedef {import('./types.js').ResolvedTokens} ResolvedTokens
27
+ */
28
+
29
+ /** The sets of the `extends` chain of `setId`, parents first. */
30
+ export function chainOf(sets, setId, diagnostics) {
31
+ const chain = [];
32
+ const done = new Set();
33
+ const visit = (id, stack, from) => {
34
+ if (stack.includes(id)) {
35
+ diagnostics.push(
36
+ tokenDiagnostic('extends-cycle', 'error', {
37
+ set: id,
38
+ cycle: [...stack.slice(stack.indexOf(id)), id],
39
+ })
40
+ );
41
+ return;
42
+ }
43
+ if (done.has(id)) {
44
+ return;
45
+ }
46
+ const set = sets.get(id);
47
+ if (set === undefined) {
48
+ diagnostics.push(
49
+ tokenDiagnostic(
50
+ 'unknown-set',
51
+ from === undefined ? 'error' : 'warning',
52
+ { ...(from === undefined ? {} : { set: from }), target: id }
53
+ )
54
+ );
55
+ return;
56
+ }
57
+ for (const parent of set.extends) {
58
+ visit(parent, [...stack, id], id);
59
+ }
60
+ done.add(id);
61
+ chain.push(set);
62
+ };
63
+ visit(setId, [], undefined);
64
+ return chain;
65
+ }
66
+
67
+ /** The definitions of every path along the chain for one mode. */
68
+ function definitions(chain, mode) {
69
+ /** @type {Map<string, { token: Token, set: string }>} */
70
+ const defs = new Map();
71
+ for (const set of chain) {
72
+ const layers = [set.tokens, mode === null ? [] : (set.modes[mode] ?? [])];
73
+ for (const token of layers.flat()) {
74
+ defs.set(token.path, { token, set: set.id });
75
+ }
76
+ }
77
+ return defs;
78
+ }
79
+
80
+ /** Resolve every definition; `null` marks a token that failed. */
81
+ function resolveAll(defs, diagnostics) {
82
+ const results = new Map();
83
+ const where = (def) => ({
84
+ set: def.set,
85
+ token: def.token.path,
86
+ ...(def.token.mode === undefined ? {} : { mode: def.token.mode }),
87
+ });
88
+
89
+ const resolveRef = (def, ref, expected, stack) => {
90
+ const target = defs.get(ref.path);
91
+ if (target === undefined) {
92
+ diagnostics.push(
93
+ tokenDiagnostic('unknown-alias', 'error', {
94
+ ...where(def),
95
+ target: ref.path,
96
+ })
97
+ );
98
+ return null;
99
+ }
100
+ if (stack.includes(ref.path)) {
101
+ // The ring of tokens, written from the token reported: b -> a -> b.
102
+ const ring = stack.slice(stack.indexOf(ref.path));
103
+ const start = Math.max(0, ring.indexOf(def.token.path));
104
+ const from = [...ring.slice(start), ...ring.slice(0, start)];
105
+ const cycle = [...from, from[0]];
106
+ diagnostics.push(
107
+ tokenDiagnostic('alias-cycle', 'error', { ...where(def), cycle })
108
+ );
109
+ for (const path of cycle) {
110
+ results.set(path, null);
111
+ }
112
+ return null;
113
+ }
114
+ const resolved = resolveOne(ref.path, stack);
115
+ if (resolved === null) {
116
+ return null;
117
+ }
118
+ if (expected !== null && resolved.type !== expected) {
119
+ diagnostics.push(
120
+ tokenDiagnostic('type-mismatch', 'error', {
121
+ ...where(def),
122
+ target: ref.path,
123
+ expected,
124
+ actual: resolved.type,
125
+ })
126
+ );
127
+ return null;
128
+ }
129
+ return resolved;
130
+ };
131
+
132
+ const resolveOne = (path, stack = []) => {
133
+ if (results.has(path)) {
134
+ return results.get(path);
135
+ }
136
+ const def = defs.get(path);
137
+ const { token } = def;
138
+ const inner = [...stack, path];
139
+ let result = null;
140
+ if (token.value.type === 'token-ref') {
141
+ const target = resolveRef(def, token.value, token.type, inner);
142
+ if (target !== null) {
143
+ result = {
144
+ type: target.type,
145
+ value: target.value,
146
+ alias: token.value.path,
147
+ };
148
+ }
149
+ } else {
150
+ let failed = false;
151
+ const value = mapNestedAliases(token.value, (ref, type) => {
152
+ const target = resolveRef(def, ref, type, inner);
153
+ failed ||= target === null;
154
+ return target?.value ?? ref;
155
+ });
156
+ result = failed ? null : { type: token.type, value };
157
+ }
158
+ if (results.get(path) === null) {
159
+ return null; // a cycle through this token was found meanwhile
160
+ }
161
+ const resolved =
162
+ result === null
163
+ ? null
164
+ : {
165
+ path,
166
+ type: result.type,
167
+ value: result.value,
168
+ raw: token.value,
169
+ ...(result.alias === undefined ? {} : { alias: result.alias }),
170
+ ...(token.description === undefined
171
+ ? {}
172
+ : { description: token.description }),
173
+ ...(token.m3 === undefined ? {} : { m3: token.m3 }),
174
+ set: def.set,
175
+ ...(token.mode === undefined ? {} : { mode: token.mode }),
176
+ };
177
+ results.set(path, resolved);
178
+ return resolved;
179
+ };
180
+
181
+ const out = new Map();
182
+ for (const path of defs.keys()) {
183
+ const resolved = resolveOne(path);
184
+ if (resolved !== null) {
185
+ out.set(path, resolved);
186
+ }
187
+ }
188
+ return out;
189
+ }
190
+
191
+ /** What makes two resolutions of a token differ (for mode overrides). */
192
+ const signature = (t) =>
193
+ JSON.stringify([t.type, t.value, t.alias ?? null, t.raw]);
194
+
195
+ /** Diagnostics without repeats (each mode resolves the shared tokens). */
196
+ const unique = (diagnostics) => [
197
+ ...new Map(
198
+ diagnostics.map((d) => [JSON.stringify([d.code, d.at]), d])
199
+ ).values(),
200
+ ];
201
+
202
+ /**
203
+ * Resolve the tokens of one set.
204
+ * @param {Map<string, TokenSet>} sets as returned by `readTokens`
205
+ * @param {string} setId
206
+ * @param {{ mode?: string|null }} [options]
207
+ * @returns {ResolvedTokens} `Map<path, ResolvedToken>` with `setId`,
208
+ * `mode`, `diagnostics` and `modes`: for every other mode of the chain,
209
+ * the tokens that resolve differently in it (or exist only in it)
210
+ */
211
+ export function resolveTokens(sets, setId, { mode = null } = {}) {
212
+ const diagnostics = [];
213
+ const chain = chainOf(sets, setId, diagnostics);
214
+ const modeNames = [
215
+ ...new Set(chain.flatMap((set) => Object.keys(set.modes))),
216
+ ];
217
+ if (mode !== null && !modeNames.includes(mode)) {
218
+ diagnostics.push(
219
+ tokenDiagnostic('unknown-mode', 'warning', { set: setId, mode })
220
+ );
221
+ }
222
+ const resolved = resolveAll(definitions(chain, mode), diagnostics);
223
+ const modes = new Map();
224
+ for (const name of modeNames.filter((m) => m !== mode)) {
225
+ const other = resolveAll(definitions(chain, name), diagnostics);
226
+ const changed = new Map(
227
+ [...other].filter(
228
+ ([path, token]) =>
229
+ !resolved.has(path) ||
230
+ signature(resolved.get(path)) !== signature(token)
231
+ )
232
+ );
233
+ modes.set(name, changed);
234
+ }
235
+ return Object.assign(resolved, {
236
+ setId,
237
+ mode,
238
+ modes,
239
+ diagnostics: unique(diagnostics),
240
+ });
241
+ }