rn-agent-kit 0.0.0-stage → 0.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.
Files changed (36) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +176 -2
  3. package/dist/cli.js +2916 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/scripts/figma-tokens.js +1284 -0
  6. package/dist/scripts/figma-tokens.js.map +1 -0
  7. package/dist/scripts/validate-jira-tickets.js +169 -0
  8. package/dist/scripts/validate-jira-tickets.js.map +1 -0
  9. package/package.json +64 -4
  10. package/skills/expo-cli/SKILL.md +213 -0
  11. package/skills/figma-to-tokens/SKILL.md +288 -0
  12. package/skills/github-actions-ci/SKILL.md +124 -0
  13. package/skills/maestro-e2e/SKILL.md +256 -0
  14. package/skills/prd-to-jira/SKILL.md +237 -0
  15. package/skills/rn-architecture/SKILL.md +207 -0
  16. package/skills/rn-native-android-ios/SKILL.md +195 -0
  17. package/skills/rn-sdk-integrations/SKILL.md +274 -0
  18. package/skills/rn-typescript-react/SKILL.md +247 -0
  19. package/skills/ticket-to-code/SKILL.md +192 -0
  20. package/templates/config/rn-agent-kit.json +4 -0
  21. package/templates/eslint/eslint.config.snippet.mjs +16 -0
  22. package/templates/eslint/rn-agent-kit-rules.cjs +137 -0
  23. package/templates/jira-ticket.md +78 -0
  24. package/templates/maestro/smoke.yaml +4 -0
  25. package/templates/scaffold/.husky/commit-msg +4 -0
  26. package/templates/scaffold/.husky/pre-commit +4 -0
  27. package/templates/scaffold/.prettierignore +6 -0
  28. package/templates/scaffold/.prettierrc +6 -0
  29. package/templates/scaffold/commitlint.config.cjs +4 -0
  30. package/templates/scaffold/eslint.config.js +22 -0
  31. package/templates/scaffold/jest.config.cjs +9 -0
  32. package/templates/scaffold/tsconfig.json +13 -0
  33. package/templates/workflows/ci.yml +120 -0
  34. package/templates/workflows/e2e-android.yml +158 -0
  35. package/templates/workflows/e2e-ios.yml +134 -0
  36. package/templates/workflows/eas-build.yml +94 -0
@@ -0,0 +1,1284 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/scripts/figma-tokens.ts
4
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
5
+ import { dirname as dirname2, resolve as resolve2 } from "path";
6
+ import { pathToFileURL } from "url";
7
+ import { parseArgs } from "util";
8
+
9
+ // src/tokens/fetch-figma.ts
10
+ function parseFigmaFileKey(url) {
11
+ const m = /figma\.com\/(?:file|design|make|board)\/([A-Za-z0-9]+)/.exec(url);
12
+ if (!m) throw new Error(`Not a Figma file URL: ${url}`);
13
+ return m[1];
14
+ }
15
+ async function fetchFigmaSnapshot(fileUrl, token, fetchImpl = fetch) {
16
+ const key = parseFigmaFileKey(fileUrl);
17
+ const headers = { "X-Figma-Token": token };
18
+ const get = async (path) => {
19
+ const res = await fetchImpl(`https://api.figma.com/v1${path}`, { headers });
20
+ if (!res.ok)
21
+ throw Object.assign(new Error(`Figma API ${res.status} for ${path}`), { status: res.status });
22
+ return await res.json();
23
+ };
24
+ const notes = [];
25
+ const snapshot = { source: "figma", fileUrl };
26
+ try {
27
+ const v = await get(`/files/${key}/variables/local`);
28
+ snapshot.variables = v.meta;
29
+ } catch (e) {
30
+ const status = e.status;
31
+ notes.push(
32
+ status === 403 || status === 404 ? "Variables REST API not available (requires Figma Enterprise + file_variables:read). Use the Figma MCP path for variables." : `Variables request failed: ${e.message}`
33
+ );
34
+ }
35
+ const styles = (await get(`/files/${key}/styles`)).meta?.styles ?? [];
36
+ const nodes = {};
37
+ const ids = styles.map((s) => s.node_id);
38
+ for (let i = 0; i < ids.length; i += 50) {
39
+ const chunk = ids.slice(i, i + 50);
40
+ const res = await get(`/files/${key}/nodes?ids=${chunk.map(encodeURIComponent).join(",")}`);
41
+ for (const [id, n] of Object.entries(res.nodes ?? {}))
42
+ nodes[id] = n.document;
43
+ }
44
+ const text = [];
45
+ const effect = [];
46
+ const color = [];
47
+ for (const s of styles) {
48
+ const n = nodes[s.node_id];
49
+ if (!n) continue;
50
+ if (s.style_type === "TEXT" && n.style) {
51
+ text.push({
52
+ name: s.name,
53
+ description: s.description || void 0,
54
+ fontFamily: n.style.fontFamily,
55
+ fontWeight: n.style.fontWeight,
56
+ fontSize: n.style.fontSize,
57
+ lineHeightPx: n.style.lineHeightPx,
58
+ letterSpacingPx: n.style.letterSpacing
59
+ });
60
+ } else if (s.style_type === "EFFECT" && n.effects) {
61
+ effect.push({ name: s.name, description: s.description || void 0, effects: n.effects });
62
+ } else if (s.style_type === "FILL") {
63
+ const fill = n.fills?.find((f) => f.type === "SOLID" && f.color);
64
+ if (fill?.color)
65
+ color.push({
66
+ name: s.name,
67
+ description: s.description || void 0,
68
+ color: { ...fill.color, a: (fill.color.a ?? 1) * (fill.opacity ?? 1) }
69
+ });
70
+ }
71
+ }
72
+ if (text.length) snapshot.textStyles = text;
73
+ if (effect.length) snapshot.effectStyles = effect;
74
+ if (color.length) snapshot.colorStyles = color;
75
+ return { snapshot, notes };
76
+ }
77
+
78
+ // src/tokens/tree.ts
79
+ var MODE_EXT = "mode";
80
+ var collator = (a, b) => a.localeCompare(b, "en", { numeric: true });
81
+ function isToken(node) {
82
+ return typeof node === "object" && node !== null && !Array.isArray(node) && "$value" in node;
83
+ }
84
+ function isGroup(node) {
85
+ return typeof node === "object" && node !== null && !Array.isArray(node) && !("$value" in node);
86
+ }
87
+ function flatten(tree) {
88
+ const out = [];
89
+ const walk = (node, path, inherited) => {
90
+ const groupType = node.$type ?? inherited;
91
+ for (const key of Object.keys(node).sort(collator)) {
92
+ if (key.startsWith("$")) continue;
93
+ const child = node[key];
94
+ const full = [...path, key];
95
+ if (isToken(child)) {
96
+ const type = child.$type ?? groupType;
97
+ if (!type)
98
+ throw new Error(
99
+ `Token "${full.join(".")}" has no $type (set it on the token or a parent group).`
100
+ );
101
+ out.push({
102
+ path: full.join("."),
103
+ type,
104
+ value: child.$value,
105
+ modes: {
106
+ ...child.$extensions?.[MODE_EXT] ?? {}
107
+ },
108
+ description: child.$description
109
+ });
110
+ } else if (isGroup(child)) {
111
+ walk(child, full, groupType);
112
+ }
113
+ }
114
+ };
115
+ walk(tree, []);
116
+ return out;
117
+ }
118
+ function setToken(tree, path, token) {
119
+ let node = tree;
120
+ for (const seg of path.slice(0, -1)) {
121
+ const next = node[seg];
122
+ if (next === void 0) {
123
+ const created = {};
124
+ node[seg] = created;
125
+ node = created;
126
+ } else if (isGroup(next)) {
127
+ node = next;
128
+ } else {
129
+ return false;
130
+ }
131
+ }
132
+ const leaf = path[path.length - 1];
133
+ if (node[leaf] !== void 0) return false;
134
+ node[leaf] = token;
135
+ return true;
136
+ }
137
+ function sortNode(node) {
138
+ if (Array.isArray(node)) return node.map(sortNode);
139
+ if (typeof node !== "object" || node === null) return node;
140
+ const rec2 = node;
141
+ const keys = Object.keys(rec2).sort((a, b) => {
142
+ const da = a.startsWith("$") ? 0 : 1;
143
+ const db = b.startsWith("$") ? 0 : 1;
144
+ return da !== db ? da - db : collator(a, b);
145
+ });
146
+ const out = {};
147
+ for (const k of keys) out[k] = sortNode(rec2[k]);
148
+ return out;
149
+ }
150
+ function serializeTree(tree) {
151
+ return `${JSON.stringify(sortNode(tree), null, 2)}
152
+ `;
153
+ }
154
+
155
+ // src/tokens/diff.ts
156
+ var show = (t) => JSON.stringify(t.value) + (Object.keys(t.modes).length ? ` (modes: ${JSON.stringify(t.modes)})` : "");
157
+ function diffTokens(prev, next) {
158
+ const nextFlat = new Map(flatten(next).map((t) => [t.path, t]));
159
+ if (!prev) return { initial: true, added: [...nextFlat.keys()], removed: [], changed: [] };
160
+ const prevFlat = new Map(flatten(prev).map((t) => [t.path, t]));
161
+ const added = [...nextFlat.keys()].filter((p) => !prevFlat.has(p));
162
+ const removed = [...prevFlat.keys()].filter((p) => !nextFlat.has(p));
163
+ const changed = [];
164
+ for (const [path, n] of nextFlat) {
165
+ const p = prevFlat.get(path);
166
+ if (p && (show(p) !== show(n) || p.type !== n.type))
167
+ changed.push({ path, before: show(p), after: show(n) });
168
+ }
169
+ return { initial: false, added, removed, changed };
170
+ }
171
+ var diffIsEmpty = (d) => !d.initial && !d.added.length && !d.removed.length && !d.changed.length;
172
+
173
+ // src/tokens/pipeline.ts
174
+ import { mkdir, readFile, writeFile } from "fs/promises";
175
+ import { dirname, resolve } from "path";
176
+
177
+ // src/tokens/generate-theme.ts
178
+ import { createHash } from "crypto";
179
+
180
+ // src/tokens/names.ts
181
+ function slug(input) {
182
+ const s = input.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
183
+ return s === "" ? "_" : s;
184
+ }
185
+ function splitName(name) {
186
+ return name.split("/").map((p) => p.trim()).filter(Boolean).map(slug);
187
+ }
188
+ function toThemeKey(seg) {
189
+ return /^\d+$/.test(seg) ? seg : seg.replace(/-([a-z0-9])/g, (_m, c) => c.toUpperCase());
190
+ }
191
+ function round(n, digits = 2) {
192
+ const f = 10 ** digits;
193
+ return Math.round(n * f) / f;
194
+ }
195
+
196
+ // src/tokens/color.ts
197
+ var byte = (n) => Math.round(Math.min(1, Math.max(0, n)) * 255).toString(16).padStart(2, "0");
198
+ function figmaColorToHex(c) {
199
+ const base = `#${byte(c.r)}${byte(c.g)}${byte(c.b)}`;
200
+ const a = c.a ?? 1;
201
+ return a >= 0.999 ? base : base + byte(a);
202
+ }
203
+ function normalizeHex(input) {
204
+ const m = /^#([0-9a-f]{3,8})$/i.exec(input.trim());
205
+ if (!m) return null;
206
+ let h = m[1].toLowerCase();
207
+ if (h.length === 3 || h.length === 4) h = [...h].map((c) => c + c).join("");
208
+ if (h.length !== 6 && h.length !== 8) return null;
209
+ return `#${h}`;
210
+ }
211
+ function cssColorToHex(input) {
212
+ const hex = normalizeHex(input);
213
+ if (hex) return hex;
214
+ const m = /^rgba?\(\s*([\d.]+)\s*[, ]\s*([\d.]+)\s*[, ]\s*([\d.]+)\s*(?:[,/]\s*([\d.]+)(%?))?\s*\)$/i.exec(
215
+ input.trim()
216
+ );
217
+ if (!m) return null;
218
+ const a = m[4] === void 0 ? 1 : m[5] === "%" ? Number(m[4]) / 100 : Number(m[4]);
219
+ return figmaColorToHex({
220
+ r: Number(m[1]) / 255,
221
+ g: Number(m[2]) / 255,
222
+ b: Number(m[3]) / 255,
223
+ a
224
+ });
225
+ }
226
+ function splitAlpha(hex) {
227
+ if (hex.length === 9)
228
+ return { rgb: hex.slice(0, 7), alpha: round(parseInt(hex.slice(7, 9), 16) / 255, 2) };
229
+ return { rgb: hex.slice(0, 7), alpha: 1 };
230
+ }
231
+
232
+ // src/tokens/transform.ts
233
+ var TokenError = class extends Error {
234
+ };
235
+ var ALIAS_RE = /^\{([^{}]+)\}$/;
236
+ var ROOT_KEYS = {
237
+ color: "colors",
238
+ shadow: "shadows",
239
+ "font-family": "fontFamilies",
240
+ "font-size": "fontSizes",
241
+ "line-height": "lineHeights",
242
+ "font-weight": "fontWeights"
243
+ };
244
+ function resolveDeep(value, mode, index, stack) {
245
+ if (typeof value === "string") {
246
+ const m = ALIAS_RE.exec(value);
247
+ if (!m) return value;
248
+ const target = m[1];
249
+ if (stack.includes(target))
250
+ throw new TokenError(`Circular alias: ${[...stack, target].join(" -> ")}`);
251
+ const t = index.get(target);
252
+ if (!t) throw new TokenError(`Unresolved alias {${target}} referenced from "${stack[0]}"`);
253
+ const next = mode === "dark" && "dark" in t.modes ? t.modes.dark : t.value;
254
+ return resolveDeep(next, mode, index, [...stack, target]);
255
+ }
256
+ if (Array.isArray(value)) return value.map((v) => resolveDeep(v, mode, index, stack));
257
+ if (typeof value === "object" && value !== null) {
258
+ return Object.fromEntries(
259
+ Object.entries(value).map(([k, v]) => [k, resolveDeep(v, mode, index, stack)])
260
+ );
261
+ }
262
+ return value;
263
+ }
264
+ function px(v, path) {
265
+ if (typeof v === "number") return v;
266
+ if (typeof v === "string") {
267
+ const m = /^(-?[\d.]+)\s*(px|rem|em)?$/.exec(v.trim());
268
+ if (m) return round(Number(m[1]) * (m[2] === "rem" || m[2] === "em" ? 16 : 1), 4);
269
+ }
270
+ throw new TokenError(`"${path}": expected a dimension like "16px", got ${JSON.stringify(v)}`);
271
+ }
272
+ function rec(v, path) {
273
+ if (typeof v === "object" && v !== null && !Array.isArray(v)) return v;
274
+ throw new TokenError(`"${path}": expected an object value`);
275
+ }
276
+ function family(v, path) {
277
+ const f = Array.isArray(v) ? v[0] : v;
278
+ if (typeof f !== "string" || !f) throw new TokenError(`"${path}": expected a font family string`);
279
+ return f;
280
+ }
281
+ function convertLeaf(type, v, path, warnings) {
282
+ switch (type) {
283
+ case "color": {
284
+ if (typeof v !== "string" || !/^#([0-9a-f]{6}|[0-9a-f]{8})$/i.test(v))
285
+ throw new TokenError(`"${path}": expected a #rrggbb[aa] color, got ${JSON.stringify(v)}`);
286
+ return v.toLowerCase();
287
+ }
288
+ case "dimension":
289
+ return px(v, path);
290
+ case "number":
291
+ if (typeof v !== "number") throw new TokenError(`"${path}": expected a number`);
292
+ return v;
293
+ case "fontWeight": {
294
+ const n = Number(v);
295
+ if (!Number.isFinite(n)) throw new TokenError(`"${path}": expected a numeric font weight`);
296
+ return String(n);
297
+ }
298
+ case "fontFamily":
299
+ return family(v, path);
300
+ case "duration": {
301
+ const m = /^([\d.]+)\s*(ms|s)?$/.exec(String(v));
302
+ if (!m) throw new TokenError(`"${path}": expected a duration like "200ms"`);
303
+ return round(Number(m[1]) * (m[2] === "s" ? 1e3 : 1), 2);
304
+ }
305
+ case "cubicBezier":
306
+ if (!Array.isArray(v) || v.length !== 4)
307
+ throw new TokenError(`"${path}": expected 4 numbers`);
308
+ return v.map(Number);
309
+ case "shadow": {
310
+ const layers = Array.isArray(v) ? v : [v];
311
+ if (layers.length > 1)
312
+ warnings.push(
313
+ `"${path}" has ${layers.length} shadow layers; React Native supports one, using the first.`
314
+ );
315
+ const s = rec(layers[0], path);
316
+ const color = String(s.color);
317
+ if (!/^#([0-9a-f]{6}|[0-9a-f]{8})$/i.test(color))
318
+ throw new TokenError(`"${path}": shadow.color must be hex`);
319
+ const { rgb, alpha } = splitAlpha(color.toLowerCase());
320
+ const blur = px(s.blur ?? 0, path);
321
+ return {
322
+ shadowColor: rgb,
323
+ shadowOffset: { width: px(s.offsetX ?? 0, path), height: px(s.offsetY ?? 0, path) },
324
+ shadowOpacity: alpha,
325
+ shadowRadius: round(blur / 2, 2),
326
+ elevation: Math.round(blur / 2)
327
+ };
328
+ }
329
+ case "typography": {
330
+ const t = rec(v, path);
331
+ const fontSize = px(t.fontSize, `${path}.fontSize`);
332
+ const out = {
333
+ fontFamily: family(t.fontFamily, `${path}.fontFamily`),
334
+ fontSize,
335
+ fontWeight: String(Number(t.fontWeight ?? 400))
336
+ };
337
+ if (t.lineHeight !== void 0) {
338
+ out.lineHeight = typeof t.lineHeight === "number" ? round(fontSize * t.lineHeight, 2) : px(t.lineHeight, `${path}.lineHeight`);
339
+ }
340
+ if (t.letterSpacing !== void 0)
341
+ out.letterSpacing = px(t.letterSpacing, `${path}.letterSpacing`);
342
+ return out;
343
+ }
344
+ }
345
+ }
346
+ function setNested(tree, keys, value, path) {
347
+ let node = tree;
348
+ for (const k of keys.slice(0, -1)) {
349
+ const next = node[k];
350
+ if (next === void 0) {
351
+ const created = {};
352
+ node[k] = created;
353
+ node = created;
354
+ } else if (typeof next === "object" && !Array.isArray(next)) {
355
+ node = next;
356
+ } else {
357
+ throw new TokenError(`"${path}": path conflicts with the value at "${k}"`);
358
+ }
359
+ }
360
+ const leaf = keys[keys.length - 1];
361
+ if (node[leaf] !== void 0)
362
+ throw new TokenError(
363
+ `"${path}": duplicate theme key "${keys.join(".")}" after camelCase conversion`
364
+ );
365
+ node[leaf] = value;
366
+ }
367
+ var PREFIX_KEYS = {
368
+ "font.family": "fontFamilies",
369
+ "font.size": "fontSizes",
370
+ "font.weight": "fontWeights",
371
+ "line.height": "lineHeights"
372
+ };
373
+ function themeKeys(path) {
374
+ const segs = path.split(".");
375
+ const prefix = PREFIX_KEYS[segs.slice(0, 2).join(".")];
376
+ if (prefix && segs.length > 2) return [prefix, ...segs.slice(2).map(toThemeKey)];
377
+ const [root, ...rest] = segs;
378
+ return [ROOT_KEYS[root] ?? toThemeKey(root), ...rest.map(toThemeKey)];
379
+ }
380
+ function buildThemes(tree) {
381
+ const flat = flatten(tree);
382
+ const index = new Map(flat.map((t) => [t.path, t]));
383
+ const warnings = [];
384
+ const themes = { light: {}, dark: {} };
385
+ for (const mode of ["light", "dark"]) {
386
+ for (const t of flat) {
387
+ const raw = mode === "dark" && "dark" in t.modes ? t.modes.dark : t.value;
388
+ const resolved = resolveDeep(raw, mode, index, [t.path]);
389
+ const leaf = convertLeaf(t.type, resolved, t.path, mode === "light" ? warnings : []);
390
+ setNested(themes[mode], themeKeys(t.path), leaf, t.path);
391
+ }
392
+ }
393
+ return { ...themes, hasDark: flat.some((t) => "dark" in t.modes), warnings };
394
+ }
395
+
396
+ // src/tokens/generate-theme.ts
397
+ var IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
398
+ function print(node, indent) {
399
+ const pad = " ".repeat(indent);
400
+ if (Array.isArray(node)) return `[${node.join(", ")}]`;
401
+ if (typeof node === "object") {
402
+ const entries = Object.entries(node);
403
+ if (!entries.length) return "{}";
404
+ const lines = entries.map(
405
+ ([k, v]) => `${pad} ${IDENT.test(k) ? k : JSON.stringify(k)}: ${print(v, indent + 1)},`
406
+ );
407
+ return `{
408
+ ${lines.join("\n")}
409
+ ${pad}}`;
410
+ }
411
+ return JSON.stringify(node);
412
+ }
413
+ var hashOf = (text) => createHash("sha256").update(text).digest("hex").slice(0, 12);
414
+ function renderTokensTs(themes, hash) {
415
+ return `/* eslint-disable */
416
+ // @generated by rn-agent-kit (figma-to-tokens). DO NOT EDIT BY HAND.
417
+ // Source: design/tokens.json (sha256:${hash})
418
+ // Regenerate: npx rn-agent-kit tokens generate
419
+ import type { TextStyle } from 'react-native';
420
+
421
+ export const lightTheme = ${print(themes.light, 0)} as const;
422
+
423
+ type Widen<T> = T extends string
424
+ ? string
425
+ : T extends number
426
+ ? number
427
+ : T extends boolean
428
+ ? boolean
429
+ : T extends readonly unknown[]
430
+ ? { -readonly [K in keyof T]: Widen<T[K]> }
431
+ : { -readonly [K in keyof T]: K extends 'fontWeight' ? NonNullable<TextStyle['fontWeight']> : Widen<T[K]> };
432
+
433
+ /** Shape shared by every theme. A missing/extra key in darkTheme is a compile error. */
434
+ export type Theme = Widen<typeof lightTheme>;
435
+
436
+ ${themes.hasDark ? `export const darkTheme: Theme = ${print(themes.dark, 0)};` : `// No dark values found in design/tokens.json; dark mirrors light until a Dark mode exists.
437
+ export const darkTheme: Theme = lightTheme;`}
438
+
439
+ export const themes = { light: lightTheme, dark: darkTheme } as const;
440
+ export type ThemeName = keyof typeof themes;
441
+ `;
442
+ }
443
+ function generateFromTokensJson(tokensJsonText) {
444
+ const tree = JSON.parse(tokensJsonText);
445
+ const built = buildThemes(tree);
446
+ return { ts: renderTokensTs(built, hashOf(tokensJsonText)), warnings: built.warnings };
447
+ }
448
+ var THEME_PROVIDER_TSX = `import React, { createContext, useContext, useMemo, type ReactNode } from 'react';
449
+ import { useColorScheme } from 'react-native';
450
+ import { themes, type Theme, type ThemeName } from './tokens';
451
+
452
+ interface ThemeContextValue {
453
+ theme: Theme;
454
+ name: ThemeName;
455
+ }
456
+
457
+ const ThemeContext = createContext<ThemeContextValue>({ theme: themes.light, name: 'light' });
458
+
459
+ export function ThemeProvider({ children, forcedTheme }: { children: ReactNode; forcedTheme?: ThemeName }) {
460
+ const scheme = useColorScheme();
461
+ const name: ThemeName = forcedTheme ?? (scheme === 'dark' ? 'dark' : 'light');
462
+ const value = useMemo(() => ({ theme: themes[name], name }), [name]);
463
+ return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
464
+ }
465
+
466
+ /** The only way components should read colors, spacing, radius, typography and shadows. */
467
+ export const useTheme = () => useContext(ThemeContext);
468
+ `;
469
+
470
+ // src/tokens/normalize-figma.ts
471
+ var UNNAMED_RE = /^(color|colour|fill|stroke|untitled|rectangle|frame|group|style|variable|paint|text|effect)[\s_-]*\d*$/i;
472
+ var HEXISH_RE = /^(#[0-9a-f]{3,8}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
473
+ var WEIGHTS = {
474
+ thin: 100,
475
+ extralight: 200,
476
+ ultralight: 200,
477
+ light: 300,
478
+ regular: 400,
479
+ normal: 400,
480
+ book: 400,
481
+ medium: 500,
482
+ semibold: 600,
483
+ demibold: 600,
484
+ bold: 700,
485
+ extrabold: 800,
486
+ ultrabold: 800,
487
+ black: 900,
488
+ heavy: 900
489
+ };
490
+ function weightFromStyleName(style) {
491
+ if (!style) return void 0;
492
+ const key = style.toLowerCase().replace(/italic|oblique|[\s_-]/g, "");
493
+ return key === "" ? 400 : WEIGHTS[key];
494
+ }
495
+ function put(ctx, path, token) {
496
+ if (setToken(ctx.tree, path, token)) return true;
497
+ ctx.issues.push({
498
+ severity: "error",
499
+ code: "name-collision",
500
+ token: path.join("."),
501
+ message: `"${path.join(".")}" collides with another token or group after name normalization; this one was skipped.`,
502
+ fix: 'Give the two variables/styles distinct names (names are lower-cased and non-alphanumerics become "-").'
503
+ });
504
+ return false;
505
+ }
506
+ function checkColorName(raw, ctx, tokenPath, requireGroup = true) {
507
+ const name = raw.trim();
508
+ if (UNNAMED_RE.test(name) || HEXISH_RE.test(name)) {
509
+ ctx.issues.push({
510
+ severity: "warning",
511
+ code: "unnamed-token",
512
+ token: tokenPath,
513
+ message: `Color "${raw}" has a placeholder/unnamed name, so it cannot carry meaning in code.`,
514
+ fix: 'Rename it in Figma to a semantic path, e.g. "color/brand/primary" or "color/text/muted".'
515
+ });
516
+ } else if (requireGroup && !name.includes("/")) {
517
+ ctx.issues.push({
518
+ severity: "info",
519
+ code: "ungrouped-token",
520
+ token: tokenPath,
521
+ message: `Color "${raw}" is not inside a group (no "/" in its name).`,
522
+ fix: 'Prefix it with a group, e.g. "color/neutral/white".'
523
+ });
524
+ }
525
+ }
526
+ function inferNumberType(name) {
527
+ const n = name.toLowerCase();
528
+ if (/(^|\/)(opacity|alpha)($|\/|-)/.test(n)) return "number";
529
+ if (/weight/.test(n)) return "fontWeight";
530
+ if (/(duration|delay|time)/.test(n)) return "duration";
531
+ if (/(space|spacing|gap|padding|margin|size|radius|radii|rounded|stroke|border|width|height|font|line-height|letter)/.test(
532
+ n
533
+ ))
534
+ return "dimension";
535
+ return null;
536
+ }
537
+ function colorPath(name) {
538
+ const segs = splitName(name);
539
+ if (["color", "colors", "colour", "colours"].includes(segs[0]))
540
+ return ["color", ...segs.slice(1)];
541
+ return ["color", ...segs];
542
+ }
543
+ function modeRoles(c) {
544
+ const find = (re, exclude) => c.modes.find((m) => re.test(m.name) && m.modeId !== exclude)?.modeId;
545
+ const base = find(/light/i) ?? c.defaultModeId;
546
+ const dark = find(/dark/i, base);
547
+ const ignored = c.modes.filter((m) => m.modeId !== base && m.modeId !== dark).map((m) => m.name);
548
+ return { base, dark, ignored };
549
+ }
550
+ function isAlias(v) {
551
+ return typeof v === "object" && v !== null && "type" in v && v.type === "VARIABLE_ALIAS";
552
+ }
553
+ function normalizeVariables(meta, ctx) {
554
+ const vars = Object.values(meta.variables).sort(
555
+ (a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id)
556
+ );
557
+ const pathOf = new Map(
558
+ vars.map((v) => [v.id, v.resolvedType === "COLOR" ? colorPath(v.name) : splitName(v.name)])
559
+ );
560
+ const reportedModes = /* @__PURE__ */ new Set();
561
+ const convert = (value, type, v, tokenPath) => {
562
+ if (value === void 0) return void 0;
563
+ if (isAlias(value)) {
564
+ const target = pathOf.get(value.id);
565
+ if (!target) {
566
+ ctx.issues.push({
567
+ severity: "error",
568
+ code: "unresolved-alias",
569
+ token: tokenPath,
570
+ message: `"${v.name}" aliases a variable that is not in this file (likely from an external library).`,
571
+ fix: "Publish/enable the library and re-run, or detach the alias in Figma so the variable has its own value."
572
+ });
573
+ return void 0;
574
+ }
575
+ return `{${target.join(".")}}`;
576
+ }
577
+ switch (type) {
578
+ case "color":
579
+ return typeof value === "object" && "r" in value ? figmaColorToHex(value) : void 0;
580
+ case "dimension":
581
+ return typeof value === "number" ? `${round(value)}px` : void 0;
582
+ case "duration":
583
+ return typeof value === "number" ? `${round(value)}ms` : void 0;
584
+ case "number":
585
+ case "fontWeight":
586
+ return typeof value === "number" ? value : void 0;
587
+ case "fontFamily":
588
+ return typeof value === "string" ? value : void 0;
589
+ default:
590
+ return void 0;
591
+ }
592
+ };
593
+ for (const v of vars) {
594
+ const col = meta.variableCollections[v.variableCollectionId];
595
+ if (!col) continue;
596
+ const path = pathOf.get(v.id) ?? [];
597
+ const tokenPath = path.join(".");
598
+ let type = null;
599
+ if (v.resolvedType === "COLOR") type = "color";
600
+ else if (v.resolvedType === "FLOAT") {
601
+ type = inferNumberType(v.name);
602
+ if (!type) {
603
+ type = "number";
604
+ ctx.issues.push({
605
+ severity: "info",
606
+ code: "ambiguous-type",
607
+ token: tokenPath,
608
+ message: `Number "${v.name}" has no unit hint in its name; exported as a plain number.`,
609
+ fix: 'Rename with a category, e.g. "spacing/md", "radius/lg", "opacity/disabled", "font-size/body".'
610
+ });
611
+ }
612
+ } else if (v.resolvedType === "STRING") {
613
+ type = /font|family|typeface/i.test(v.name) ? "fontFamily" : null;
614
+ }
615
+ if (!type) {
616
+ ctx.issues.push({
617
+ severity: "info",
618
+ code: "unsupported-type",
619
+ token: tokenPath,
620
+ message: `Variable "${v.name}" (${v.resolvedType}) is not exportable as a design token and was skipped.`,
621
+ fix: 'Only COLOR, FLOAT and font-family STRING variables are exported. Rename string variables with "font-family" if they are fonts.'
622
+ });
623
+ continue;
624
+ }
625
+ if (type === "color") checkColorName(v.name, ctx, tokenPath);
626
+ const roles = modeRoles(col);
627
+ if (roles.ignored.length && !reportedModes.has(col.id)) {
628
+ reportedModes.add(col.id);
629
+ ctx.issues.push({
630
+ severity: "info",
631
+ code: "ignored-mode",
632
+ token: col.name,
633
+ message: `Collection "${col.name}" has extra modes that are ignored: ${roles.ignored.join(", ")}.`,
634
+ fix: 'Only "Light"/default and "Dark" modes are exported. Rename modes accordingly if they should be included.'
635
+ });
636
+ }
637
+ const base = convert(v.valuesByMode[roles.base], type, v, tokenPath);
638
+ if (base === void 0) continue;
639
+ const token = { $type: type, $value: base };
640
+ if (v.description) token.$description = v.description;
641
+ if (roles.dark) {
642
+ const dark = convert(v.valuesByMode[roles.dark], type, v, tokenPath);
643
+ if (dark !== void 0 && JSON.stringify(dark) !== JSON.stringify(base))
644
+ token.$extensions = { mode: { dark } };
645
+ }
646
+ put(ctx, path, token);
647
+ }
648
+ }
649
+ function normalizeFlat(light, dark, ctx) {
650
+ const parse = (name, val) => {
651
+ if (typeof val === "number") {
652
+ const type = inferNumberType(name) ?? "number";
653
+ if (type === "dimension") return { type, value: `${round(val)}px` };
654
+ if (type === "duration") return { type, value: `${round(val)}ms` };
655
+ return { type, value: val };
656
+ }
657
+ const color = cssColorToHex(val);
658
+ if (color) return { type: "color", value: color };
659
+ if (/^Font\(/i.test(val)) {
660
+ const family2 = /family:\s*"([^"]+)"/.exec(val)?.[1];
661
+ const size = Number(/size:\s*([\d.]+)/.exec(val)?.[1]);
662
+ if (!family2 || !size) return null;
663
+ const weight = Number(/weight:\s*(\d+)/.exec(val)?.[1]) || weightFromStyleName(/style:\s*([A-Za-z ]+)/.exec(val)?.[1]) || 400;
664
+ const lh = Number(/lineHeight:\s*([\d.]+)/.exec(val)?.[1]);
665
+ const ls = Number(/letterSpacing:\s*(-?[\d.]+)/.exec(val)?.[1]);
666
+ const value = {
667
+ fontFamily: family2,
668
+ fontSize: `${size}px`,
669
+ fontWeight: weight
670
+ };
671
+ if (lh) value.lineHeight = round(lh / size, 4);
672
+ if (ls) value.letterSpacing = `${round(ls)}px`;
673
+ return { type: "typography", value };
674
+ }
675
+ if (/^\d+(\.\d+)?$/.test(val.trim()) === false && /font|family/i.test(name))
676
+ return { type: "fontFamily", value: val };
677
+ return null;
678
+ };
679
+ for (const name of Object.keys(light).sort()) {
680
+ const parsed = parse(name, light[name]);
681
+ const path = parsed?.type === "color" ? colorPath(name) : splitName(name);
682
+ const tokenPath = path.join(".");
683
+ if (!parsed) {
684
+ ctx.issues.push({
685
+ severity: "info",
686
+ code: "invalid-value",
687
+ token: tokenPath,
688
+ message: `Value of "${name}" could not be interpreted (${JSON.stringify(light[name])}); skipped.`,
689
+ fix: "Check the variable type in Figma, or provide full variables via the REST API / agent snapshot."
690
+ });
691
+ continue;
692
+ }
693
+ if (parsed.type === "color") checkColorName(name, ctx, tokenPath);
694
+ const token = { $type: parsed.type, $value: parsed.value };
695
+ const darkRaw = dark?.[name];
696
+ if (darkRaw !== void 0) {
697
+ const d = parse(name, darkRaw);
698
+ if (d && JSON.stringify(d.value) !== JSON.stringify(parsed.value))
699
+ token.$extensions = { mode: { dark: d.value } };
700
+ }
701
+ put(ctx, path, token);
702
+ }
703
+ if (!dark) {
704
+ ctx.issues.push({
705
+ severity: "info",
706
+ code: "single-mode-source",
707
+ message: "Variables came from a single-mode source (MCP get_variable_defs); no dark values were captured.",
708
+ fix: 'Put a frame in Dark mode, run get_variable_defs on it and store the result as "flatVariablesDark" (or use the Variables REST API on Enterprise).'
709
+ });
710
+ }
711
+ }
712
+ function stripRoot(path, roots) {
713
+ return path.length > 1 && roots.includes(path[0]) ? path.slice(1) : path;
714
+ }
715
+ function normalizeColorStyles(styles, ctx) {
716
+ for (const s of [...styles].sort((a, b) => a.name.localeCompare(b.name))) {
717
+ const path = ["color", ...stripRoot(splitName(s.name), ["color", "colour"])];
718
+ const tokenPath = path.join(".");
719
+ checkColorName(s.name, ctx, tokenPath);
720
+ const token = { $type: "color", $value: figmaColorToHex(s.color) };
721
+ if (s.description) token.$description = s.description;
722
+ if (put(ctx, path, token)) {
723
+ ctx.issues.push({
724
+ severity: "info",
725
+ code: "style-without-variable",
726
+ token: tokenPath,
727
+ message: `Color style "${s.name}" is not backed by a variable, so it has no light/dark values.`,
728
+ fix: "Convert it to a Figma variable (with Light/Dark modes) to get dark-mode support."
729
+ });
730
+ }
731
+ }
732
+ }
733
+ function normalizeTextStyles(styles, ctx) {
734
+ for (const s of [...styles].sort((a, b) => a.name.localeCompare(b.name))) {
735
+ const path = ["typography", ...stripRoot(splitName(s.name), ["typography", "text", "font"])];
736
+ const tokenPath = path.join(".");
737
+ const value = {
738
+ fontFamily: s.fontFamily,
739
+ fontSize: `${round(s.fontSize)}px`,
740
+ fontWeight: s.fontWeight ?? weightFromStyleName(s.fontStyle) ?? 400
741
+ };
742
+ const lhPx = s.lineHeightPx ?? (s.lineHeightPercent !== void 0 ? s.fontSize * s.lineHeightPercent / 100 : void 0);
743
+ if (lhPx !== void 0) value.lineHeight = round(lhPx / s.fontSize, 4);
744
+ else {
745
+ ctx.issues.push({
746
+ severity: "warning",
747
+ code: "missing-line-height",
748
+ token: tokenPath,
749
+ message: `Text style "${s.name}" has automatic line height; RN will use the font default.`,
750
+ fix: "Set an explicit line height on the text style in Figma."
751
+ });
752
+ }
753
+ const lsPx = s.letterSpacingPx ?? (s.letterSpacingPercent !== void 0 ? s.fontSize * s.letterSpacingPercent / 100 : 0);
754
+ if (lsPx) value.letterSpacing = `${round(lsPx)}px`;
755
+ const token = { $type: "typography", $value: value };
756
+ if (s.description) token.$description = s.description;
757
+ put(ctx, path, token);
758
+ }
759
+ }
760
+ function normalizeEffectStyles(styles, ctx) {
761
+ for (const s of [...styles].sort((a, b) => a.name.localeCompare(b.name))) {
762
+ const path = [
763
+ "shadow",
764
+ ...stripRoot(splitName(s.name), ["shadow", "shadows", "elevation", "effect"])
765
+ ];
766
+ const tokenPath = path.join(".");
767
+ const layers = [];
768
+ for (const e of s.effects) {
769
+ if (e.visible === false) continue;
770
+ if (e.type === "DROP_SHADOW" && e.color) {
771
+ layers.push({
772
+ color: figmaColorToHex(e.color),
773
+ offsetX: `${round(e.offset?.x ?? 0)}px`,
774
+ offsetY: `${round(e.offset?.y ?? 0)}px`,
775
+ blur: `${round(e.radius ?? 0)}px`,
776
+ spread: `${round(e.spread ?? 0)}px`
777
+ });
778
+ } else {
779
+ ctx.issues.push({
780
+ severity: "warning",
781
+ code: "unsupported-effect",
782
+ token: tokenPath,
783
+ message: `Effect "${e.type}" in "${s.name}" is not supported by React Native and was skipped.`,
784
+ fix: "Use drop shadows only for elevation. Blurs/inner shadows need a custom native or Skia implementation."
785
+ });
786
+ }
787
+ }
788
+ if (!layers.length) continue;
789
+ const token = { $type: "shadow", $value: layers.length === 1 ? layers[0] : layers };
790
+ if (s.description) token.$description = s.description;
791
+ put(ctx, path, token);
792
+ }
793
+ }
794
+
795
+ // src/tokens/normalize-stitch.ts
796
+ function cssLengthToPx(v) {
797
+ const m = /^(-?[\d.]+)\s*(px|rem|em)?$/.exec(v.trim());
798
+ if (!m) return null;
799
+ const n = Number(m[1]);
800
+ return m[2] === "rem" || m[2] === "em" ? n * 16 : n;
801
+ }
802
+ function splitTopLevel(input, sep) {
803
+ const out = [];
804
+ let depth = 0;
805
+ let cur = "";
806
+ for (const ch of input) {
807
+ if (ch === "(") depth++;
808
+ if (ch === ")") depth--;
809
+ if (ch === sep && depth === 0) {
810
+ out.push(cur);
811
+ cur = "";
812
+ } else cur += ch;
813
+ }
814
+ if (cur.trim()) out.push(cur);
815
+ return out;
816
+ }
817
+ function parseBoxShadow(css) {
818
+ const first = splitTopLevel(css, ",")[0]?.trim();
819
+ if (!first || first === "none") return null;
820
+ const parts = first.match(/[^\s(]+\([^)]*\)|\S+/g) ?? [];
821
+ if (parts.includes("inset")) return null;
822
+ const lengths = [];
823
+ let color = "#000000";
824
+ for (const p of parts) {
825
+ const px2 = cssLengthToPx(p);
826
+ if (px2 !== null) lengths.push(px2);
827
+ else {
828
+ const c = cssColorToHex(p);
829
+ if (c) color = c;
830
+ }
831
+ }
832
+ if (lengths.length < 2) return null;
833
+ const [x, y, blur = 0, spread = 0] = lengths;
834
+ return {
835
+ color,
836
+ offsetX: `${round(x)}px`,
837
+ offsetY: `${round(y)}px`,
838
+ blur: `${round(blur)}px`,
839
+ spread: `${round(spread)}px`
840
+ };
841
+ }
842
+ function colorEntries(colors, ctx) {
843
+ const out = /* @__PURE__ */ new Map();
844
+ for (const [group, val] of Object.entries(colors)) {
845
+ const entries = typeof val === "string" ? [[[slug(group)], val]] : Object.entries(val).map(([k, v]) => [[slug(group), slug(k)], v]);
846
+ for (const [path, raw] of entries) {
847
+ const hex = cssColorToHex(raw);
848
+ if (!hex) {
849
+ ctx.issues.push({
850
+ severity: "warning",
851
+ code: "invalid-value",
852
+ token: ["color", ...path].join("."),
853
+ message: `Color "${raw}" is not hex/rgb(a) and was skipped.`,
854
+ fix: "Use hex or rgb()/rgba() colors in the Stitch design (hsl, oklch and CSS variables are not converted)."
855
+ });
856
+ continue;
857
+ }
858
+ out.set(path.join("."), hex);
859
+ }
860
+ }
861
+ return out;
862
+ }
863
+ function normalizeTailwind(tw, ctx) {
864
+ if (tw.colors) {
865
+ const light = colorEntries(tw.colors, ctx);
866
+ const dark = tw.darkColors ? colorEntries(tw.darkColors, ctx) : /* @__PURE__ */ new Map();
867
+ for (const [path, hex] of [...light.entries()].sort(([a], [b]) => a.localeCompare(b))) {
868
+ const segs = ["color", ...path.split(".")];
869
+ checkColorName(path.split(".").join("/"), ctx, segs.join("."), false);
870
+ const token = { $type: "color", $value: hex };
871
+ const d = dark.get(path);
872
+ if (d && d !== hex) token.$extensions = { mode: { dark: d } };
873
+ put(ctx, segs, token);
874
+ }
875
+ for (const path of dark.keys()) {
876
+ if (!light.has(path)) {
877
+ ctx.issues.push({
878
+ severity: "warning",
879
+ code: "invalid-value",
880
+ token: `color.${path}`,
881
+ message: `Dark color "${path}" has no light counterpart and was skipped.`,
882
+ fix: "Define the same color name for both light and dark palettes."
883
+ });
884
+ }
885
+ }
886
+ if (!tw.darkColors) {
887
+ ctx.issues.push({
888
+ severity: "info",
889
+ code: "single-mode-source",
890
+ message: "Stitch export contained only one color palette; dark theme will equal light.",
891
+ fix: 'Generate a dark variant of the design in Stitch and add its palette as "tailwind.darkColors".'
892
+ });
893
+ }
894
+ }
895
+ const lengthGroup = (record, root) => {
896
+ for (const [k, v] of Object.entries(record ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
897
+ const px2 = cssLengthToPx(v);
898
+ if (px2 === null) {
899
+ ctx.issues.push({
900
+ severity: "info",
901
+ code: "invalid-value",
902
+ token: `${root}.${slug(k)}`,
903
+ message: `Length "${v}" could not be converted to px; skipped.`,
904
+ fix: "Use px or rem values."
905
+ });
906
+ continue;
907
+ }
908
+ put(ctx, [root, slug(k)], { $type: "dimension", $value: `${round(px2)}px` });
909
+ }
910
+ };
911
+ lengthGroup(tw.spacing, "spacing");
912
+ lengthGroup(tw.borderRadius, "radius");
913
+ for (const [k, v] of Object.entries(tw.fontFamily ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
914
+ const first = (Array.isArray(v) ? v[0] : v.split(",")[0])?.trim().replace(/^['"]|['"]$/g, "");
915
+ if (first) put(ctx, ["font-family", slug(k)], { $type: "fontFamily", $value: first });
916
+ }
917
+ for (const [k, v] of Object.entries(tw.fontSize ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
918
+ const size = typeof v === "string" ? v : v[0];
919
+ const px2 = cssLengthToPx(size);
920
+ if (px2 === null) continue;
921
+ put(ctx, ["font-size", slug(k)], { $type: "dimension", $value: `${round(px2)}px` });
922
+ const lh = Array.isArray(v) && typeof v[1] === "object" ? v[1].lineHeight : Array.isArray(v) ? v[1] : void 0;
923
+ if (lh) {
924
+ const lhPx = /^[\d.]+$/.test(lh) ? Number(lh) * px2 : cssLengthToPx(lh);
925
+ if (lhPx !== null)
926
+ put(ctx, ["line-height", slug(k)], { $type: "dimension", $value: `${round(lhPx)}px` });
927
+ }
928
+ }
929
+ if (tw.fontSize) {
930
+ ctx.issues.push({
931
+ severity: "info",
932
+ code: "invalid-value",
933
+ message: "Stitch/Tailwind has no text styles; only font-size/line-height/font-family tokens were created.",
934
+ fix: 'Compose "typography.*" tokens in Figma (text styles) if you need ready-made text styles.'
935
+ });
936
+ }
937
+ for (const [k, v] of Object.entries(tw.boxShadow ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
938
+ const shadow = parseBoxShadow(v);
939
+ if (!shadow) {
940
+ ctx.issues.push({
941
+ severity: "warning",
942
+ code: "unsupported-effect",
943
+ token: `shadow.${slug(k)}`,
944
+ message: `Shadow "${k}: ${v}" is inset/unparsable and was skipped.`,
945
+ fix: "RN supports outer drop shadows only."
946
+ });
947
+ continue;
948
+ }
949
+ put(ctx, ["shadow", slug(k)], { $type: "shadow", $value: shadow });
950
+ }
951
+ }
952
+
953
+ // src/tokens/normalize.ts
954
+ var RANK = { error: 0, warning: 1, info: 2 };
955
+ function sortIssues(issues) {
956
+ return [...issues].sort(
957
+ (a, b) => RANK[a.severity] - RANK[b.severity] || a.code.localeCompare(b.code) || (a.token ?? "").localeCompare(b.token ?? "") || a.message.localeCompare(b.message)
958
+ );
959
+ }
960
+ function postChecks(ctx) {
961
+ const flat = flatten(ctx.tree);
962
+ const roots = new Set(flat.map((t) => t.path.split(".")[0]));
963
+ const required = [
964
+ ["color", "colors", "warning"],
965
+ ["spacing", "spacing scale", "warning"],
966
+ ["radius", "border radius", "warning"],
967
+ ["typography", "text styles", "warning"],
968
+ ["shadow", "shadows/elevation", "info"]
969
+ ];
970
+ for (const [root, label, severity] of required) {
971
+ if (!roots.has(root)) {
972
+ ctx.issues.push({
973
+ severity,
974
+ code: "missing-category",
975
+ token: root,
976
+ message: `No "${root}.*" tokens found (${label}). Components would have to hardcode them.`,
977
+ fix: `Add ${label} as Figma variables/styles named "${root}/...", then re-run.`
978
+ });
979
+ }
980
+ }
981
+ const colors = flat.filter((t) => t.type === "color");
982
+ const aliasColors = colors.filter((t) => typeof t.value === "string" && /^\{.+\}$/.test(t.value));
983
+ const hasDark = colors.some((t) => "dark" in t.modes);
984
+ if (colors.length && !hasDark) {
985
+ ctx.issues.push({
986
+ severity: "warning",
987
+ code: "missing-dark-mode",
988
+ message: "No color token has a Dark value. darkTheme will be identical to lightTheme.",
989
+ fix: 'Add a "Dark" mode to your semantic color collection in Figma (or a dark palette in Stitch).'
990
+ });
991
+ } else if (hasDark) {
992
+ for (const t of aliasColors.filter((c) => !("dark" in c.modes))) {
993
+ ctx.issues.push({
994
+ severity: "warning",
995
+ code: "missing-dark-mode",
996
+ token: t.path,
997
+ message: `Semantic color "${t.path}" has the same value in Light and Dark.`,
998
+ fix: "If that is intentional, ignore. Otherwise set a different value for the Dark mode in Figma."
999
+ });
1000
+ }
1001
+ }
1002
+ const families = /* @__PURE__ */ new Set();
1003
+ for (const t of flat) {
1004
+ if (t.type === "fontFamily" && typeof t.value === "string") families.add(t.value);
1005
+ if (t.type === "typography" && typeof t.value === "object" && t.value) {
1006
+ const f = t.value.fontFamily;
1007
+ if (typeof f === "string") families.add(f);
1008
+ }
1009
+ }
1010
+ if (families.size) {
1011
+ ctx.issues.push({
1012
+ severity: "info",
1013
+ code: "font-loading",
1014
+ message: `Fonts used: ${[...families].sort().join(", ")}. React Native needs each family/weight loaded under the exact name used in the theme.`,
1015
+ fix: "Load fonts with expo-font (useFonts) or link them natively, and verify the registered family names."
1016
+ });
1017
+ }
1018
+ }
1019
+ function normalizeSnapshot(snap) {
1020
+ const ctx = { tree: {}, issues: [] };
1021
+ if (snap.variables) normalizeVariables(snap.variables, ctx);
1022
+ if (snap.flatVariables) normalizeFlat(snap.flatVariables, snap.flatVariablesDark, ctx);
1023
+ if (snap.colorStyles) normalizeColorStyles(snap.colorStyles, ctx);
1024
+ if (snap.textStyles) normalizeTextStyles(snap.textStyles, ctx);
1025
+ if (snap.effectStyles) normalizeEffectStyles(snap.effectStyles, ctx);
1026
+ if (snap.tailwind) normalizeTailwind(snap.tailwind, ctx);
1027
+ postChecks(ctx);
1028
+ return { tree: ctx.tree, issues: sortIssues(ctx.issues) };
1029
+ }
1030
+
1031
+ // src/tokens/report.ts
1032
+ var ICON = { error: "\u{1F534}", warning: "\u{1F7E1}", info: "\u{1F535}" };
1033
+ var LIMIT = 40;
1034
+ function list(items) {
1035
+ const shown = items.slice(0, LIMIT).map((i) => `- \`${i}\``);
1036
+ if (items.length > LIMIT) shown.push(`- \u2026 and ${items.length - LIMIT} more`);
1037
+ return shown.join("\n");
1038
+ }
1039
+ function renderReport(input) {
1040
+ const flat = flatten(input.tree);
1041
+ const byType = /* @__PURE__ */ new Map();
1042
+ for (const t of flat) byType.set(t.type, (byType.get(t.type) ?? 0) + 1);
1043
+ const count = (s) => input.issues.filter((i) => i.severity === s).length;
1044
+ const out = ["# Design tokens report", ""];
1045
+ out.push(`Source: **${input.source}**${input.fileUrl ? ` \u2014 ${input.fileUrl}` : ""}`, "");
1046
+ out.push("## Summary", "", "| Type | Tokens |", "| --- | ---: |");
1047
+ for (const [type, n] of [...byType.entries()].sort()) out.push(`| ${type} | ${n} |`);
1048
+ out.push(`| **total** | **${flat.length}** |`, "");
1049
+ out.push(
1050
+ `Issues: ${count("error")} error(s), ${count("warning")} warning(s), ${count("info")} info.`,
1051
+ ""
1052
+ );
1053
+ out.push("## Changes since last run", "");
1054
+ if (input.diff.initial)
1055
+ out.push(`Initial generation: ${input.diff.added.length} tokens created.`, "");
1056
+ else if (diffIsEmpty(input.diff)) out.push("No changes.", "");
1057
+ else {
1058
+ if (input.diff.added.length)
1059
+ out.push(`### Added (${input.diff.added.length})`, "", list(input.diff.added), "");
1060
+ if (input.diff.removed.length)
1061
+ out.push(
1062
+ `### Removed (${input.diff.removed.length})`,
1063
+ "",
1064
+ list(input.diff.removed),
1065
+ "",
1066
+ "> Removed tokens may break components that still use them \u2014 `tsc` will flag them.",
1067
+ ""
1068
+ );
1069
+ if (input.diff.changed.length) {
1070
+ out.push(`### Changed (${input.diff.changed.length})`, "");
1071
+ for (const c of input.diff.changed.slice(0, LIMIT))
1072
+ out.push(`- \`${c.path}\`: ${c.before} \u2192 ${c.after}`);
1073
+ if (input.diff.changed.length > LIMIT)
1074
+ out.push(`- \u2026 and ${input.diff.changed.length - LIMIT} more`);
1075
+ out.push("");
1076
+ }
1077
+ }
1078
+ out.push("## Needs attention in the design file", "");
1079
+ if (!input.issues.length) out.push("\u2705 Nothing to fix.", "");
1080
+ for (const sev of ["error", "warning", "info"]) {
1081
+ const items = input.issues.filter((i) => i.severity === sev);
1082
+ if (!items.length) continue;
1083
+ out.push(`### ${ICON[sev]} ${sev[0].toUpperCase()}${sev.slice(1)}s (${items.length})`, "");
1084
+ for (const i of items) {
1085
+ out.push(`- ${i.token ? `\`${i.token}\` \u2014 ` : ""}${i.message}`);
1086
+ out.push(` - **Fix:** ${i.fix}`);
1087
+ }
1088
+ out.push("");
1089
+ }
1090
+ return `${out.join("\n").trimEnd()}
1091
+ `;
1092
+ }
1093
+
1094
+ // src/tokens/snapshot.ts
1095
+ function parseSnapshot(json) {
1096
+ if (typeof json !== "object" || json === null) throw new Error("Snapshot must be a JSON object.");
1097
+ const s = json;
1098
+ const hasData = s.variables || s.flatVariables || s.colorStyles || s.textStyles || s.effectStyles || s.tailwind;
1099
+ if (!hasData) {
1100
+ throw new Error(
1101
+ "Snapshot has no data. Expected at least one of: variables, flatVariables, colorStyles, textStyles, effectStyles, tailwind."
1102
+ );
1103
+ }
1104
+ if (!s.source) s.source = s.tailwind && !s.variables && !s.flatVariables ? "stitch" : "figma";
1105
+ return s;
1106
+ }
1107
+
1108
+ // src/tokens/pipeline.ts
1109
+ var DEFAULT_PATHS = {
1110
+ snapshot: "design/source-snapshot.json",
1111
+ tokens: "design/tokens.json",
1112
+ theme: "src/shared/theme/tokens.ts",
1113
+ report: "design/tokens-report.md"
1114
+ };
1115
+ function buildArtifacts(snapshot, previousTokensJson) {
1116
+ const { tree, issues } = normalizeSnapshot(snapshot);
1117
+ const tokensJson = serializeTree(tree);
1118
+ const { ts, warnings } = generateFromTokensJson(tokensJson);
1119
+ const prev = previousTokensJson ? JSON.parse(previousTokensJson) : null;
1120
+ const diff = diffTokens(prev, JSON.parse(tokensJson));
1121
+ const report = renderReport({
1122
+ source: snapshot.source,
1123
+ fileUrl: snapshot.fileUrl,
1124
+ tree,
1125
+ issues,
1126
+ diff
1127
+ });
1128
+ return { tokensJson, tokensTs: ts, report, diff, issues, warnings };
1129
+ }
1130
+ async function readOptional(path) {
1131
+ try {
1132
+ return await readFile(path, "utf8");
1133
+ } catch {
1134
+ return null;
1135
+ }
1136
+ }
1137
+ async function writeIfChanged(path, content) {
1138
+ if (await readOptional(path) === content) return false;
1139
+ await mkdir(dirname(path), { recursive: true });
1140
+ await writeFile(path, content, "utf8");
1141
+ return true;
1142
+ }
1143
+ var abs = (cwd, p) => resolve(cwd, p);
1144
+ async function runBuild(cwd, paths) {
1145
+ const raw = await readOptional(abs(cwd, paths.snapshot));
1146
+ if (raw === null)
1147
+ throw new Error(
1148
+ `Snapshot not found: ${paths.snapshot}. Ask the agent to create it (see the figma-to-tokens skill) or run "fetch".`
1149
+ );
1150
+ const snapshot = parseSnapshot(JSON.parse(raw));
1151
+ const previous = await readOptional(abs(cwd, paths.tokens));
1152
+ const out = buildArtifacts(snapshot, previous);
1153
+ const written = {
1154
+ tokens: await writeIfChanged(abs(cwd, paths.tokens), out.tokensJson),
1155
+ theme: await writeIfChanged(abs(cwd, paths.theme), out.tokensTs),
1156
+ report: await writeIfChanged(abs(cwd, paths.report), out.report),
1157
+ provider: false
1158
+ };
1159
+ const providerPath = resolve(dirname(abs(cwd, paths.theme)), "ThemeProvider.tsx");
1160
+ if (await readOptional(providerPath) === null)
1161
+ written.provider = await writeIfChanged(providerPath, THEME_PROVIDER_TSX);
1162
+ return { ...out, written };
1163
+ }
1164
+ async function runGenerate(cwd, paths) {
1165
+ const text = await readOptional(abs(cwd, paths.tokens));
1166
+ if (text === null) throw new Error(`${paths.tokens} not found. Run "build" first.`);
1167
+ const { ts, warnings } = generateFromTokensJson(text);
1168
+ const changed = await writeIfChanged(abs(cwd, paths.theme), ts);
1169
+ return { changed, warnings };
1170
+ }
1171
+ async function runCheck(cwd, paths) {
1172
+ const problems = [];
1173
+ const tokensText = await readOptional(abs(cwd, paths.tokens));
1174
+ if (tokensText === null) return { ok: false, problems: [`${paths.tokens} is missing.`] };
1175
+ const theme = await readOptional(abs(cwd, paths.theme));
1176
+ const expectedTs = generateFromTokensJson(tokensText).ts;
1177
+ if (theme === null) problems.push(`${paths.theme} is missing. Run: tokens generate`);
1178
+ else if (theme !== expectedTs)
1179
+ problems.push(`${paths.theme} is out of date with ${paths.tokens}. Run: tokens generate`);
1180
+ const snap = await readOptional(abs(cwd, paths.snapshot));
1181
+ if (snap !== null) {
1182
+ const expectedJson = buildArtifacts(parseSnapshot(JSON.parse(snap)), null).tokensJson;
1183
+ if (expectedJson !== tokensText)
1184
+ problems.push(`${paths.tokens} does not match ${paths.snapshot}. Run: tokens build`);
1185
+ }
1186
+ return { ok: problems.length === 0, problems };
1187
+ }
1188
+
1189
+ // src/scripts/figma-tokens.ts
1190
+ var HELP = `Usage: figma-tokens <build|generate|check|fetch> [options]
1191
+
1192
+ --snapshot <file> default ${DEFAULT_PATHS.snapshot}
1193
+ --tokens <file> default ${DEFAULT_PATHS.tokens}
1194
+ --theme <file> default ${DEFAULT_PATHS.theme}
1195
+ --report <file> default ${DEFAULT_PATHS.report}
1196
+ --strict build: exit 1 if the report contains errors
1197
+ --url <figma-url> fetch: Figma file URL (token from FIGMA_TOKEN)
1198
+ `;
1199
+ async function runCli(argv, cwd = process.cwd()) {
1200
+ const { positionals, values } = parseArgs({
1201
+ args: argv,
1202
+ allowPositionals: true,
1203
+ options: {
1204
+ snapshot: { type: "string" },
1205
+ tokens: { type: "string" },
1206
+ theme: { type: "string" },
1207
+ report: { type: "string" },
1208
+ url: { type: "string" },
1209
+ strict: { type: "boolean", default: false },
1210
+ help: { type: "boolean", short: "h", default: false }
1211
+ }
1212
+ });
1213
+ const paths = {
1214
+ snapshot: values.snapshot ?? DEFAULT_PATHS.snapshot,
1215
+ tokens: values.tokens ?? DEFAULT_PATHS.tokens,
1216
+ theme: values.theme ?? DEFAULT_PATHS.theme,
1217
+ report: values.report ?? DEFAULT_PATHS.report
1218
+ };
1219
+ const cmd = positionals[0];
1220
+ if (!cmd || values.help) {
1221
+ console.log(HELP);
1222
+ return cmd ? 0 : 1;
1223
+ }
1224
+ try {
1225
+ if (cmd === "build") {
1226
+ const r = await runBuild(cwd, paths);
1227
+ const errors = r.issues.filter((i) => i.severity === "error").length;
1228
+ const warnings = r.issues.filter((i) => i.severity === "warning").length;
1229
+ console.log(
1230
+ r.diff.initial ? `\u2714 Created ${r.diff.added.length} tokens.` : diffIsEmpty(r.diff) ? "\u2714 No token changes." : `\u2714 Tokens updated: +${r.diff.added.length} \u2212${r.diff.removed.length} ~${r.diff.changed.length}`
1231
+ );
1232
+ console.log(
1233
+ ` wrote: ${paths.tokens}${r.written.tokens ? "" : " (unchanged)"}, ${paths.theme}${r.written.theme ? "" : " (unchanged)"}, ${paths.report}`
1234
+ );
1235
+ if (r.written.provider)
1236
+ console.log(" created ThemeProvider.tsx (not overwritten on later runs)");
1237
+ for (const w of r.warnings) console.warn(` ! ${w}`);
1238
+ console.log(` report: ${errors} error(s), ${warnings} warning(s) \u2192 see ${paths.report}`);
1239
+ return values.strict && errors > 0 ? 1 : 0;
1240
+ }
1241
+ if (cmd === "generate") {
1242
+ const r = await runGenerate(cwd, paths);
1243
+ console.log(r.changed ? `\u2714 Regenerated ${paths.theme}` : "\u2714 Already up to date.");
1244
+ for (const w of r.warnings) console.warn(` ! ${w}`);
1245
+ return 0;
1246
+ }
1247
+ if (cmd === "check") {
1248
+ const r = await runCheck(cwd, paths);
1249
+ if (r.ok) console.log("\u2714 Design tokens are up to date.");
1250
+ else for (const p of r.problems) console.error(`\u2716 ${p}`);
1251
+ return r.ok ? 0 : 1;
1252
+ }
1253
+ if (cmd === "fetch") {
1254
+ const token = process.env.FIGMA_TOKEN;
1255
+ if (!values.url) throw new Error("--url <figma-file-url> is required");
1256
+ if (!token)
1257
+ throw new Error(
1258
+ "FIGMA_TOKEN is not set. Create a personal access token in Figma (scopes: file_content:read, file_variables:read)."
1259
+ );
1260
+ const { snapshot, notes } = await fetchFigmaSnapshot(values.url, token);
1261
+ const file = resolve2(cwd, paths.snapshot);
1262
+ await mkdir2(dirname2(file), { recursive: true });
1263
+ await writeFile2(file, `${JSON.stringify(snapshot, null, 2)}
1264
+ `, "utf8");
1265
+ console.log(`\u2714 Wrote ${paths.snapshot}`);
1266
+ for (const n of notes) console.warn(` ! ${n}`);
1267
+ return 0;
1268
+ }
1269
+ console.error(`Unknown command "${cmd}".
1270
+ ${HELP}`);
1271
+ return 1;
1272
+ } catch (e) {
1273
+ console.error(`\u2716 ${e.message}`);
1274
+ return 1;
1275
+ }
1276
+ }
1277
+ var entryPath = process.argv[1] ?? "";
1278
+ if (/figma-tokens\.(ts|js|mjs|cjs)$/.test(entryPath) && import.meta.url === pathToFileURL(entryPath).href) {
1279
+ runCli(process.argv.slice(2)).then((code) => process.exit(code));
1280
+ }
1281
+ export {
1282
+ runCli
1283
+ };
1284
+ //# sourceMappingURL=figma-tokens.js.map