@luci-dev/format 0.7.0 → 0.8.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 (61) hide show
  1. package/dist/capture/check.d.ts +44 -2
  2. package/dist/capture/check.d.ts.map +1 -1
  3. package/dist/capture/check.js +381 -23
  4. package/dist/capture/check.js.map +1 -1
  5. package/dist/capture/collection.d.ts +240 -6
  6. package/dist/capture/collection.d.ts.map +1 -1
  7. package/dist/capture/format.d.ts +1 -1
  8. package/dist/capture/format.d.ts.map +1 -1
  9. package/dist/capture/format.js +31 -14
  10. package/dist/capture/format.js.map +1 -1
  11. package/dist/capture/layout.js +1 -1
  12. package/dist/capture/layout.js.map +1 -1
  13. package/dist/capture/merge.d.ts +7 -0
  14. package/dist/capture/merge.d.ts.map +1 -1
  15. package/dist/capture/merge.js +24 -0
  16. package/dist/capture/merge.js.map +1 -1
  17. package/dist/capture/read.d.ts +16 -1
  18. package/dist/capture/read.d.ts.map +1 -1
  19. package/dist/capture/read.js +82 -9
  20. package/dist/capture/read.js.map +1 -1
  21. package/dist/capture/schema.d.ts +256 -8
  22. package/dist/capture/schema.d.ts.map +1 -1
  23. package/dist/capture/schema.js +21 -8
  24. package/dist/capture/schema.js.map +1 -1
  25. package/dist/capture/spec.d.ts +35 -5
  26. package/dist/capture/spec.d.ts.map +1 -1
  27. package/dist/capture/spec.js +71 -16
  28. package/dist/capture/spec.js.map +1 -1
  29. package/dist/capture/values.d.ts +11 -0
  30. package/dist/capture/values.d.ts.map +1 -1
  31. package/dist/capture/values.js +58 -1
  32. package/dist/capture/values.js.map +1 -1
  33. package/dist/feedback/prompt.js +1 -1
  34. package/dist/feedback/prompt.js.map +1 -1
  35. package/dist/feedback/review.js +1 -1
  36. package/dist/feedback/review.js.map +1 -1
  37. package/dist/figma/diff.d.ts +13 -0
  38. package/dist/figma/diff.d.ts.map +1 -0
  39. package/dist/figma/diff.js +454 -0
  40. package/dist/figma/diff.js.map +1 -0
  41. package/dist/figma/index.d.ts +10 -0
  42. package/dist/figma/index.d.ts.map +1 -0
  43. package/dist/figma/index.js +10 -0
  44. package/dist/figma/index.js.map +1 -0
  45. package/dist/figma/match.d.ts +56 -0
  46. package/dist/figma/match.d.ts.map +1 -0
  47. package/dist/figma/match.js +329 -0
  48. package/dist/figma/match.js.map +1 -0
  49. package/dist/figma/normalize.d.ts +62 -0
  50. package/dist/figma/normalize.d.ts.map +1 -0
  51. package/dist/figma/normalize.js +932 -0
  52. package/dist/figma/normalize.js.map +1 -0
  53. package/dist/figma/schema.d.ts +1662 -0
  54. package/dist/figma/schema.d.ts.map +1 -0
  55. package/dist/figma/schema.js +545 -0
  56. package/dist/figma/schema.js.map +1 -0
  57. package/dist/figma/tokens.d.ts +32 -0
  58. package/dist/figma/tokens.d.ts.map +1 -0
  59. package/dist/figma/tokens.js +391 -0
  60. package/dist/figma/tokens.js.map +1 -0
  61. package/package.json +5 -1
@@ -0,0 +1,932 @@
1
+ /**
2
+ * Normalizes validated Figma import payloads into standard `@luci-dev/format/capture` structures
3
+ * (`ComponentCapture`, `SectionCapture`, `TypographySystem`, `ColorSystem`, `SpacingSystem`).
4
+ * Pure and browser-safe.
5
+ */
6
+ import {} from '../capture/schema.js';
7
+ import { toCaptureName } from '../capture/format.js';
8
+ import { pairPartsByPositionAndKind, summarizeVariantDifferences } from '../capture/check.js';
9
+ import { formatColor, isNothingStyleValue, round } from '../capture/values.js';
10
+ import { computeStructureSignature, figmaNodeUrl, layerIdentityKey, normalizeFrameNodeId, sanitizeFigmaLabel, tokenIdentityKey } from './schema.js';
11
+ const FIGMA_DESIGN_SOURCE_BASE = 'https://www.figma.com/design';
12
+ export function figmaCaptureSource(fileKey) {
13
+ return `${FIGMA_DESIGN_SOURCE_BASE}/${fileKey}`;
14
+ }
15
+ export function figmaCaptureFileName(scope, name) {
16
+ return `figma-com.${scope}.${name}.design.md`;
17
+ }
18
+ export function figmaColorToCss(c, paintOpacity) {
19
+ const a = (c.a ?? 1) * (paintOpacity ?? 1);
20
+ const r = Math.round(c.r * 255);
21
+ const g = Math.round(c.g * 255);
22
+ const b = Math.round(c.b * 255);
23
+ const raw = a < 0.999 ? `rgba(${r}, ${g}, ${b}, ${round(a, 3)})` : `rgb(${r}, ${g}, ${b})`;
24
+ return formatColor(raw, { colors: 'hex' });
25
+ }
26
+ function visibleSolid(paints) {
27
+ return paints?.find(p => p.visible !== false && p.type === 'SOLID' && p.color);
28
+ }
29
+ const PRIMARY_ALIGN_MAP = {
30
+ MIN: 'flex-start',
31
+ CENTER: 'center',
32
+ MAX: 'flex-end',
33
+ SPACE_BETWEEN: 'space-between'
34
+ };
35
+ const COUNTER_ALIGN_MAP = {
36
+ MIN: 'flex-start',
37
+ CENTER: 'center',
38
+ MAX: 'flex-end',
39
+ BASELINE: 'baseline'
40
+ };
41
+ const WEIGHT_WORD_MAP = {
42
+ thin: 100,
43
+ hairline: 100,
44
+ extralight: 200,
45
+ 'extra light': 200,
46
+ ultralight: 200,
47
+ light: 300,
48
+ regular: 400,
49
+ normal: 400,
50
+ medium: 500,
51
+ semibold: 600,
52
+ 'semi bold': 600,
53
+ demibold: 600,
54
+ bold: 700,
55
+ extrabold: 800,
56
+ 'extra bold': 800,
57
+ ultrabold: 800,
58
+ black: 900,
59
+ heavy: 900
60
+ };
61
+ export function resolveFigmaWeightNumber(weight, style) {
62
+ if (typeof weight === 'number' && Number.isFinite(weight))
63
+ return Math.round(weight);
64
+ if (!style)
65
+ return undefined;
66
+ const normalized = style.toLowerCase().replace(/italic/g, '').trim();
67
+ return WEIGHT_WORD_MAP[normalized];
68
+ }
69
+ function resolveBoundToken(payload, node, fields, tokensFile) {
70
+ if (!tokensFile || !node.bound)
71
+ return undefined;
72
+ for (const field of fields) {
73
+ const ids = node.bound[field];
74
+ if (!ids?.length)
75
+ continue;
76
+ for (const id of ids) {
77
+ const v = payload.variables.find(x => x.id === id);
78
+ if (!v)
79
+ continue;
80
+ const entry = tokensFile.tokens[tokenIdentityKey(payload.figma.fileKey, v)];
81
+ if (entry?.status === 'mapped' && entry.code?.token) {
82
+ return entry.code.token;
83
+ }
84
+ }
85
+ }
86
+ return undefined;
87
+ }
88
+ /** Resolve the leaf value of a Figma variable through up to 16 aliases. */
89
+ export function resolveVariableChain(variables, id) {
90
+ const byId = new Map(variables.map(v => [v.id, v]));
91
+ const start = byId.get(id);
92
+ if (!start)
93
+ return null;
94
+ let curr = start;
95
+ let immediateAlias = null;
96
+ const seen = new Set([curr.id]);
97
+ while (typeof curr.value === 'object' && curr.value !== null && 'aliasOf' in curr.value) {
98
+ const next = byId.get(curr.value.aliasOf);
99
+ if (!next || seen.has(next.id))
100
+ break;
101
+ if (!immediateAlias)
102
+ immediateAlias = next;
103
+ seen.add(next.id);
104
+ curr = next;
105
+ }
106
+ return { resolved: curr, aliasOf: immediateAlias };
107
+ }
108
+ export function formatVariableValue(v, all) {
109
+ const chain = resolveVariableChain(all, v.id);
110
+ const val = chain ? chain.resolved.value : v.value;
111
+ if (typeof val === 'object' && val !== null && 'r' in val) {
112
+ return figmaColorToCss(val);
113
+ }
114
+ if (typeof val === 'number') {
115
+ return v.type === 'FLOAT' && !/weight|opacity|ratio/i.test(v.name) ? `${round(val)}px` : round(val);
116
+ }
117
+ return typeof val === 'string' ? val : String(val);
118
+ }
119
+ function nodeElementLabel(node) {
120
+ switch (node.type) {
121
+ case 'TEXT':
122
+ return 'span (text)';
123
+ case 'FRAME':
124
+ case 'COMPONENT':
125
+ case 'INSTANCE':
126
+ case 'SECTION':
127
+ return node.layout && node.layout.mode !== 'NONE' ? 'div (flex)' : 'div (box)';
128
+ default:
129
+ return `div (${node.type.toLowerCase()})`;
130
+ }
131
+ }
132
+ function formatBoxPadding(pad) {
133
+ const [t, r, b, l] = pad.map(v => `${round(v)}px`);
134
+ if (t === r && r === b && b === l)
135
+ return t;
136
+ if (t === b && r === l)
137
+ return `${t} ${r}`;
138
+ return `${t} ${r} ${b} ${l}`;
139
+ }
140
+ function formatBoxRadius(radius) {
141
+ const [tl, tr, br, bl] = radius.map(v => `${round(v)}px`);
142
+ if (tl === tr && tr === br && br === bl)
143
+ return tl;
144
+ return `${tl} ${tr} ${br} ${bl}`;
145
+ }
146
+ function nodeStyles(node, payload, tokensFile) {
147
+ const styles = [];
148
+ const push = (property, computed, tokenFields) => {
149
+ const token = resolveBoundToken(payload, node, tokenFields, tokensFile);
150
+ styles.push({ property, value: token ? { computed, token } : { computed } });
151
+ };
152
+ if (node.layout && node.layout.mode !== 'NONE') {
153
+ if (node.layout.mode === 'GRID') {
154
+ push('display', 'grid', []);
155
+ }
156
+ else {
157
+ push('display', 'flex', []);
158
+ push('flex-direction', node.layout.mode === 'HORIZONTAL' ? 'row' : 'column', []);
159
+ }
160
+ if (node.layout.primaryAlign !== 'SPACE_BETWEEN' && typeof node.layout.gap === 'number' && node.layout.gap > 0) {
161
+ push('gap', `${round(node.layout.gap)}px`, ['itemSpacing']);
162
+ }
163
+ if (node.layout.wrap) {
164
+ push('flex-wrap', 'wrap', []);
165
+ }
166
+ if (node.layout.primaryAlign && PRIMARY_ALIGN_MAP[node.layout.primaryAlign]) {
167
+ const justify = PRIMARY_ALIGN_MAP[node.layout.primaryAlign];
168
+ if (!isNothingStyleValue('justify-content', justify)) {
169
+ push('justify-content', justify, []);
170
+ }
171
+ }
172
+ if (node.layout.counterAlign && COUNTER_ALIGN_MAP[node.layout.counterAlign]) {
173
+ push('align-items', COUNTER_ALIGN_MAP[node.layout.counterAlign], []);
174
+ }
175
+ if (node.layout.padding && node.layout.padding.some(p => p > 0)) {
176
+ push('padding', formatBoxPadding(node.layout.padding), ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft']);
177
+ }
178
+ }
179
+ // Informational sizes (check.ts skips width/height when origin === 'figma' so responsive builds never drift falsely)
180
+ if (node.size) {
181
+ if (node.size.sizingH === 'FIXED')
182
+ push('width', `${round(node.size.width)}px`, ['width']);
183
+ if (node.size.sizingV === 'FIXED')
184
+ push('height', `${round(node.size.height)}px`, ['height']);
185
+ }
186
+ const fill = visibleSolid(node.style?.fills);
187
+ if (fill?.color) {
188
+ const hex = figmaColorToCss(fill.color, fill.opacity);
189
+ push(node.type === 'TEXT' ? 'color' : 'background-color', hex, ['fills']);
190
+ }
191
+ const stroke = visibleSolid(node.style?.strokes);
192
+ if (stroke?.color && (node.style?.strokeWeight ?? 0) > 0) {
193
+ const hex = figmaColorToCss(stroke.color, stroke.opacity);
194
+ push('border', `${round(node.style.strokeWeight)}px solid ${hex}`, ['strokes', 'strokeWeight']);
195
+ }
196
+ if (node.style?.radius && node.style.radius.some(r => r > 0)) {
197
+ push('border-radius', formatBoxRadius(node.style.radius), ['topLeftRadius', 'topRightRadius', 'bottomRightRadius', 'bottomLeftRadius']);
198
+ }
199
+ if (typeof node.style?.opacity === 'number' && node.style.opacity < 1) {
200
+ push('opacity', round(node.style.opacity, 2), ['opacity']);
201
+ }
202
+ const shadows = (node.style?.effects ?? []).filter(e => e.visible !== false && (e.type === 'DROP_SHADOW' || e.type === 'INNER_SHADOW'));
203
+ if (shadows.length > 0) {
204
+ const shadowText = shadows
205
+ .map(s => {
206
+ const inset = s.type === 'INNER_SHADOW' ? 'inset ' : '';
207
+ const x = `${round(s.offset?.x ?? 0)}px`;
208
+ const y = `${round(s.offset?.y ?? 0)}px`;
209
+ const blur = `${round(s.radius ?? 0)}px`;
210
+ const spread = s.spread ? ` ${round(s.spread)}px` : '';
211
+ const col = s.color ? ` ${figmaColorToCss(s.color)}` : '';
212
+ return `${inset}${x} ${y} ${blur}${spread}${col}`.trim();
213
+ })
214
+ .join(', ');
215
+ push('box-shadow', shadowText, ['effects']);
216
+ }
217
+ if (node.text) {
218
+ if (node.text.fontFamily) {
219
+ const cleanFam = sanitizeFigmaLabel(node.text.fontFamily, 120).replace(/[;,"\\]/g, ' ').replace(/\s+/g, ' ').trim();
220
+ push('font-family', `"${cleanFam}"`, ['fontFamily']);
221
+ }
222
+ if (typeof node.text.fontSize === 'number')
223
+ push('font-size', `${round(node.text.fontSize)}px`, ['fontSize']);
224
+ const w = resolveFigmaWeightNumber(node.text.fontWeight, node.text.fontStyle);
225
+ if (w !== undefined)
226
+ push('font-weight', String(w), ['fontStyle', 'fontWeight']);
227
+ if (node.text.lineHeight) {
228
+ if (node.text.lineHeight.unit === 'AUTO') {
229
+ push('line-height', 'normal', ['lineHeight']);
230
+ }
231
+ else if (typeof node.text.lineHeight.value === 'number') {
232
+ const lh = node.text.lineHeight.unit === 'PERCENT'
233
+ ? round(node.text.lineHeight.value / 100, 3)
234
+ : `${round(node.text.lineHeight.value)}px`;
235
+ push('line-height', lh, ['lineHeight']);
236
+ }
237
+ }
238
+ if (node.text.letterSpacing && node.text.letterSpacing.value !== 0) {
239
+ const ls = node.text.letterSpacing.unit === 'PERCENT'
240
+ ? `${round(node.text.letterSpacing.value / 100, 4)}em`
241
+ : `${round(node.text.letterSpacing.value)}px`;
242
+ push('letter-spacing', ls, ['letterSpacing']);
243
+ }
244
+ if (node.text.textCase === 'UPPER')
245
+ push('text-transform', 'uppercase', []);
246
+ else if (node.text.textCase === 'LOWER')
247
+ push('text-transform', 'lowercase', []);
248
+ else if (node.text.textCase === 'TITLE')
249
+ push('text-transform', 'capitalize', []);
250
+ if (node.text.decoration === 'UNDERLINE')
251
+ push('text-decoration', 'underline', []);
252
+ else if (node.text.decoration === 'STRIKETHROUGH')
253
+ push('text-decoration', 'line-through', []);
254
+ if (node.text.textAlign === 'CENTER')
255
+ push('text-align', 'center', []);
256
+ else if (node.text.textAlign === 'RIGHT')
257
+ push('text-align', 'right', []);
258
+ else if (node.text.textAlign === 'JUSTIFIED')
259
+ push('text-align', 'justify', []);
260
+ else if (node.text.textAlign === 'LEFT')
261
+ push('text-align', 'left', []);
262
+ }
263
+ return styles;
264
+ }
265
+ function collectDescendants(nodes, rootId) {
266
+ const byParent = new Map();
267
+ for (const n of nodes) {
268
+ if (!n.parentId)
269
+ continue;
270
+ const list = byParent.get(n.parentId) ?? [];
271
+ list.push(n);
272
+ byParent.set(n.parentId, list);
273
+ }
274
+ const out = [];
275
+ const walk = (id, depth) => {
276
+ if (depth > 8)
277
+ return;
278
+ for (const child of byParent.get(id) ?? []) {
279
+ out.push(child);
280
+ walk(child.id, depth + 1);
281
+ }
282
+ };
283
+ walk(rootId, 0);
284
+ return out;
285
+ }
286
+ function collectUsedTokens(payload, nodes, tokensFile) {
287
+ if (!tokensFile)
288
+ return [];
289
+ const acc = new Map();
290
+ for (const n of nodes) {
291
+ if (!n.bound)
292
+ continue;
293
+ for (const [field, ids] of Object.entries(n.bound)) {
294
+ if (field === 'itemSpacing' && n.layout?.primaryAlign === 'SPACE_BETWEEN')
295
+ continue;
296
+ for (const id of ids) {
297
+ const v = payload.variables.find(x => x.id === id);
298
+ if (!v)
299
+ continue;
300
+ const entry = tokensFile.tokens[tokenIdentityKey(payload.figma.fileKey, v)];
301
+ if (entry?.status !== 'mapped' || !entry.code?.token)
302
+ continue;
303
+ const tok = acc.get(entry.code.token) ?? { value: entry.value, usedFor: new Set() };
304
+ tok.usedFor.add(field);
305
+ acc.set(entry.code.token, tok);
306
+ }
307
+ }
308
+ }
309
+ return [...acc.entries()].map(([token, info]) => ({
310
+ token,
311
+ value: info.value,
312
+ usedFor: [...info.usedFor]
313
+ }));
314
+ }
315
+ const INITIAL_UNSET_VALUE = {
316
+ gap: '0px',
317
+ 'row-gap': '0px',
318
+ 'column-gap': '0px',
319
+ 'flex-wrap': 'nowrap',
320
+ 'justify-content': 'normal',
321
+ 'align-items': 'normal',
322
+ 'flex-direction': 'row',
323
+ 'background-color': 'transparent',
324
+ border: 'none',
325
+ 'border-radius': '0px',
326
+ opacity: '1',
327
+ 'box-shadow': 'none',
328
+ 'text-decoration': 'none',
329
+ 'text-align': 'start',
330
+ 'text-transform': 'none'
331
+ };
332
+ function buildComponentCapture(payload, representative, variantNodes, ruleSlug, meta, selector, tokensFile, responsive) {
333
+ const buildNodeAnatomy = (rootNode) => {
334
+ const desc = collectDescendants(payload.nodes, rootNode.id);
335
+ const usedNames = new Set(['container']);
336
+ const partName = (label) => {
337
+ let base = toCaptureName(sanitizeFigmaLabel(label));
338
+ if (base === 'container')
339
+ base = 'container-inner';
340
+ let candidate = base;
341
+ let n = 2;
342
+ while (usedNames.has(candidate)) {
343
+ candidate = `${base}-${n++}`;
344
+ }
345
+ usedNames.add(candidate);
346
+ return candidate;
347
+ };
348
+ const partForNode = (n, isRoot) => ({
349
+ part: isRoot ? 'container' : partName(n.name),
350
+ element: nodeElementLabel(n),
351
+ styles: nodeStyles(n, payload, tokensFile)
352
+ });
353
+ return {
354
+ descendants: desc,
355
+ anatomy: [
356
+ partForNode(rootNode, true),
357
+ ...desc.slice(0, 24).map(d => partForNode(d, false))
358
+ ]
359
+ };
360
+ };
361
+ const { descendants, anatomy } = buildNodeAnatomy(representative);
362
+ // If multiple sibling frames/instances were grouped as one component, capture container & child-part differences as Variants
363
+ let variants;
364
+ if (variantNodes.length > 1) {
365
+ const formatVariantProps = (vn) => {
366
+ if (!vn.component?.variant)
367
+ return '';
368
+ return Object.entries(vn.component.variant)
369
+ .filter(([k, v]) => k.trim() && String(v).trim())
370
+ .map(([k, v]) => `${sanitizeFigmaLabel(k, 60)}=${sanitizeFigmaLabel(String(v), 60)}`)
371
+ .join(', ');
372
+ };
373
+ const variantPropsNames = variantNodes.map(formatVariantProps);
374
+ const propsDiffer = variantPropsNames.every(Boolean) && new Set(variantPropsNames).size > 1;
375
+ const rawNames = variantNodes.map(vn => sanitizeFigmaLabel(vn.name, 80));
376
+ const namesDiffer = new Set(rawNames).size > 1;
377
+ const usedVariantNames = new Set();
378
+ const variantAnatomies = variantNodes.map(vn => buildNodeAnatomy(vn).anatomy);
379
+ // Properties present on `anatomy` where at least one variant falls back to CSS default (unset / nothing)
380
+ // must not be baked into shared `## Anatomy`; hoist them to only the variants that actually set them
381
+ // so CSS defaults (e.g. `justify-content flex-start`) never appear in variant labels or Differences.
382
+ const variantPairs = variantAnatomies.map(vnAnatomy => pairPartsByPositionAndKind(anatomy, vnAnatomy).pairs);
383
+ for (const basePart of anatomy) {
384
+ basePart.styles = basePart.styles.filter(bs => {
385
+ if (bs.property === 'width' || bs.property === 'height')
386
+ return true;
387
+ if (isNothingStyleValue(bs.property, bs.value.computed) && !bs.value.token)
388
+ return false;
389
+ const everyVariantSetsNonDefault = variantPairs.every(pairs => {
390
+ const pair = pairs.find(p => p.want === basePart);
391
+ if (!pair)
392
+ return true;
393
+ const match = pair.have.styles.find(s => s.property === bs.property);
394
+ return Boolean(match && (Boolean(match.value.token) || !isNothingStyleValue(match.property, match.value.computed)));
395
+ });
396
+ return everyVariantSetsNonDefault;
397
+ });
398
+ }
399
+ const computedDiffs = variantNodes.map((_, idx) => {
400
+ const pairs = variantPairs[idx];
401
+ const differences = [];
402
+ for (const { want: basePart, have: vnPart } of pairs) {
403
+ const prefix = basePart.part === 'container' ? '' : `${basePart.part} `;
404
+ const baseMap = new Map(basePart.styles.map(s => [s.property, s.value.computed]));
405
+ for (const s of vnPart.styles) {
406
+ if (s.property === 'width' || s.property === 'height')
407
+ continue;
408
+ if (!s.value.token && isNothingStyleValue(s.property, s.value.computed))
409
+ continue;
410
+ if (baseMap.get(s.property) !== s.value.computed) {
411
+ differences.push({ property: `${prefix}${s.property}`, value: s.value });
412
+ }
413
+ }
414
+ for (const bs of basePart.styles) {
415
+ if (bs.property === 'width' || bs.property === 'height')
416
+ continue;
417
+ const unsetVal = INITIAL_UNSET_VALUE[bs.property] ?? 'none';
418
+ if (isNothingStyleValue(bs.property, unsetVal))
419
+ continue;
420
+ if (!vnPart.styles.some(x => x.property === bs.property) && !isNothingStyleValue(bs.property, bs.value.computed)) {
421
+ differences.push({
422
+ property: `${prefix}${bs.property}`,
423
+ value: { computed: unsetVal }
424
+ });
425
+ }
426
+ }
427
+ }
428
+ return differences;
429
+ });
430
+ const pickVariantName = (idx, diffs) => {
431
+ // Label order: Figma variant properties ("Tone=Moss, Layout=Compact"); else layer names if they differ;
432
+ // else differing values (token names where they exist, up to 3 then +N more) or "the base design".
433
+ const raw = propsDiffer
434
+ ? variantPropsNames[idx]
435
+ : namesDiffer
436
+ ? rawNames[idx]
437
+ : summarizeVariantDifferences(diffs.map(d => ({ property: d.property, value: d.value.computed, token: d.value.token })));
438
+ let candidate = raw;
439
+ let n = 2;
440
+ while (usedVariantNames.has(candidate))
441
+ candidate = `${raw} (${n++})`;
442
+ usedVariantNames.add(candidate);
443
+ return candidate;
444
+ };
445
+ variants = variantNodes.map((vn, idx) => {
446
+ const differences = computedDiffs[idx];
447
+ return {
448
+ name: pickVariantName(idx, differences),
449
+ count: 1,
450
+ selector: figmaNodeUrl(payload.figma.fileKey, vn.id),
451
+ differences
452
+ };
453
+ });
454
+ }
455
+ return {
456
+ meta: {
457
+ ...meta,
458
+ name: ruleSlug,
459
+ scope: 'component',
460
+ type: toCaptureName(sanitizeFigmaLabel(representative.component?.name ?? representative.name)),
461
+ ...(selector ? { selector } : {})
462
+ },
463
+ tokens: collectUsedTokens(payload, [representative, ...descendants], tokensFile),
464
+ anatomy,
465
+ states: [],
466
+ motion: [],
467
+ ...(responsive ? { responsive } : {}),
468
+ ...(variants ? { variants } : {})
469
+ };
470
+ }
471
+ function normalizeRepeatLabel(name) {
472
+ return toCaptureName(sanitizeFigmaLabel(name)).replace(/-/g, '');
473
+ }
474
+ function selectComponentTree(payload) {
475
+ const rootId = normalizeFrameNodeId(payload.figma.frameNodeId);
476
+ const childrenByParent = new Map();
477
+ const parentById = new Map();
478
+ for (const n of payload.nodes) {
479
+ parentById.set(n.id, n.parentId);
480
+ if (!n.parentId)
481
+ continue;
482
+ const list = childrenByParent.get(n.parentId) ?? [];
483
+ list.push(n);
484
+ childrenByParent.set(n.parentId, list);
485
+ }
486
+ // Collect descendants reachable under rootId to find repeated groups across the whole imported frame
487
+ const reachable = [];
488
+ const collectReachable = (id) => {
489
+ for (const child of childrenByParent.get(id) ?? []) {
490
+ reachable.push(child);
491
+ collectReachable(child.id);
492
+ }
493
+ };
494
+ collectReachable(rootId);
495
+ // 1. Find repeated groups: repeated frames with children (same normalized label + structural signature) and repeated instances
496
+ const rawGroups = new Map();
497
+ for (const n of reachable) {
498
+ const hasChildren = (childrenByParent.get(n.id)?.length ?? 0) > 0;
499
+ if (n.type === 'INSTANCE') {
500
+ const key = n.component?.key
501
+ ? `inst-key:${n.component.key}`
502
+ : n.component?.id
503
+ ? `inst-id:${n.component.id}`
504
+ : `inst-name:${normalizeRepeatLabel(n.component?.name ?? n.name)}`;
505
+ const list = rawGroups.get(key) ?? [];
506
+ list.push(n);
507
+ rawGroups.set(key, list);
508
+ }
509
+ else if ((n.type === 'FRAME' || n.type === 'GROUP') && hasChildren && !n.component) {
510
+ const sig = computeStructureSignature(payload.nodes, n.id);
511
+ const key = `frame:${normalizeRepeatLabel(n.name)}::${sig}`;
512
+ const list = rawGroups.get(key) ?? [];
513
+ list.push(n);
514
+ rawGroups.set(key, list);
515
+ }
516
+ }
517
+ const candidateGroups = [...rawGroups.values()].filter(g => g.length >= 2);
518
+ const groupMemberSets = candidateGroups.map(g => new Set(g.map(n => n.id)));
519
+ // 2. Keep only outermost groups (ignore groups whose members all sit inside members of another group)
520
+ const hasAncestorIn = (nodeId, set) => {
521
+ let curr = parentById.get(nodeId);
522
+ let steps = 0;
523
+ while (curr && steps++ < 64) {
524
+ if (set.has(curr))
525
+ return true;
526
+ curr = parentById.get(curr);
527
+ }
528
+ return false;
529
+ };
530
+ const outermostMemberIds = new Set();
531
+ candidateGroups.forEach((group, idx) => {
532
+ const nested = candidateGroups.some((_, otherIdx) => otherIdx !== idx && group.every(m => hasAncestorIn(m.id, groupMemberSets[otherIdx])));
533
+ if (!nested) {
534
+ for (const m of group)
535
+ outermostMemberIds.add(m.id);
536
+ }
537
+ });
538
+ // 3. Mark frames that contain a member of a repeated group (at any depth) and aren't members themselves
539
+ const containsRepeatedMember = new Set();
540
+ for (const memberId of outermostMemberIds) {
541
+ let curr = parentById.get(memberId);
542
+ let steps = 0;
543
+ while (curr && curr !== rootId && steps++ < 64) {
544
+ containsRepeatedMember.add(curr);
545
+ curr = parentById.get(curr);
546
+ }
547
+ }
548
+ // Distinguish a repeated-group layout container (Metrics Grid, Metric Column) from a pure depth-0 wrapper (Content Container)
549
+ const isRepeatedContainer = (nodeId) => {
550
+ if (!containsRepeatedMember.has(nodeId) || outermostMemberIds.has(nodeId))
551
+ return false;
552
+ const kids = childrenByParent.get(nodeId) ?? [];
553
+ return kids.some(k => outermostMemberIds.has(k.id))
554
+ || kids.every(k => containsRepeatedMember.has(k.id));
555
+ };
556
+ // 4. Walk frame up to depth 3: walk into repeated-group containers & pure depth-0 wrappers; collect candidates
557
+ const candidates = [];
558
+ const walkedIntoIds = new Set();
559
+ const walk = (parentId, depth) => {
560
+ if (depth > 3)
561
+ return;
562
+ for (const child of childrenByParent.get(parentId) ?? []) {
563
+ const hasChildren = (childrenByParent.get(child.id)?.length ?? 0) > 0;
564
+ if (outermostMemberIds.has(child.id)) {
565
+ candidates.push(child);
566
+ continue;
567
+ }
568
+ if (containsRepeatedMember.has(child.id)) {
569
+ if (isRepeatedContainer(child.id) || !(depth === 0 && isPureLayoutWrapper(child, childrenByParent))) {
570
+ walkedIntoIds.add(child.id);
571
+ }
572
+ walk(child.id, depth + 1);
573
+ continue;
574
+ }
575
+ if (child.type === 'INSTANCE' || child.type === 'COMPONENT') {
576
+ candidates.push(child);
577
+ continue;
578
+ }
579
+ if ((child.type === 'FRAME' || child.type === 'GROUP') && hasChildren) {
580
+ if (depth >= 1 || !isPureLayoutWrapper(child, childrenByParent)) {
581
+ candidates.push(child);
582
+ continue;
583
+ }
584
+ }
585
+ walk(child.id, depth + 1);
586
+ }
587
+ };
588
+ walk(rootId, 0);
589
+ return { candidates, walkedIntoIds, childrenByParent };
590
+ }
591
+ /** Identify component candidates directly inside a frame (components, instances, repeated frames/groups, or child frames with children). */
592
+ export function selectComponentNodes(payload) {
593
+ return selectComponentTree(payload).candidates;
594
+ }
595
+ function isPureLayoutWrapper(node, childrenByParent) {
596
+ const hasVisual = Boolean(visibleSolid(node.style?.fills) || visibleSolid(node.style?.strokes) || (node.style?.effects?.length ?? 0) > 0);
597
+ const children = childrenByParent.get(node.id) ?? [];
598
+ return !hasVisual && children.length > 0 && children.every(c => c.type === 'FRAME' || c.type === 'INSTANCE' || c.type === 'COMPONENT');
599
+ }
600
+ function buildSystems(payload, meta, tokensFile) {
601
+ const textNodes = payload.nodes.filter(n => n.type === 'TEXT' && n.text?.fontFamily && typeof n.text.fontSize === 'number');
602
+ const familyCounts = new Map();
603
+ const sizeCounts = new Map();
604
+ const rolesMap = new Map();
605
+ for (const n of textNodes) {
606
+ const t = n.text;
607
+ const family = sanitizeFigmaLabel(t.fontFamily, 120).replace(/[;,"\\]/g, ' ').replace(/\s+/g, ' ').trim();
608
+ const size = t.fontSize;
609
+ const weight = resolveFigmaWeightNumber(t.fontWeight, t.fontStyle) ?? 400;
610
+ const lh = t.lineHeight?.unit === 'PIXELS' && t.lineHeight.value
611
+ ? `${round(t.lineHeight.value)}px`
612
+ : t.lineHeight?.unit === 'PERCENT' && t.lineHeight.value
613
+ ? round(t.lineHeight.value / 100, 3)
614
+ : 'normal';
615
+ const ls = t.letterSpacing
616
+ ? (t.letterSpacing.unit === 'PERCENT'
617
+ ? `${round(t.letterSpacing.value / 100, 4)}em`
618
+ : `${round(t.letterSpacing.value)}px`)
619
+ : '0px';
620
+ const fill = visibleSolid(n.style?.fills);
621
+ const colorHex = fill?.color ? figmaColorToCss(fill.color, fill.opacity) : '#2b2b2b';
622
+ familyCounts.set(family, (familyCounts.get(family) ?? 0) + 1);
623
+ sizeCounts.set(size, (sizeCounts.get(size) ?? 0) + 1);
624
+ const roleSlug = toCaptureName(sanitizeFigmaLabel(n.textStyle?.name ?? n.name));
625
+ const key = `${roleSlug}:${family}:${size}:${weight}`;
626
+ const existing = rolesMap.get(key);
627
+ if (existing) {
628
+ existing.count += 1;
629
+ existing.elements.add(sanitizeFigmaLabel(n.name));
630
+ }
631
+ else {
632
+ const sizeToken = resolveBoundToken(payload, n, ['fontSize'], tokensFile);
633
+ const familyToken = resolveBoundToken(payload, n, ['fontFamily'], tokensFile);
634
+ const colorToken = resolveBoundToken(payload, n, ['fills'], tokensFile);
635
+ const lhToken = resolveBoundToken(payload, n, ['lineHeight'], tokensFile);
636
+ rolesMap.set(key, {
637
+ style: {
638
+ family: familyToken ? { computed: family, token: familyToken } : { computed: family },
639
+ size: sizeToken ? { computed: `${round(size)}px`, token: sizeToken } : { computed: `${round(size)}px` },
640
+ weight: { computed: String(weight) },
641
+ lineHeight: lhToken ? { computed: lh, token: lhToken } : { computed: lh },
642
+ letterSpacing: { computed: ls },
643
+ color: colorToken ? { computed: colorHex, token: colorToken } : { computed: colorHex }
644
+ },
645
+ count: 1,
646
+ elements: new Set([sanitizeFigmaLabel(n.name)])
647
+ });
648
+ }
649
+ }
650
+ const usedRoleSlugs = new Set();
651
+ const typography = rolesMap.size
652
+ ? {
653
+ meta: { ...meta, name: 'figma-typography', scope: 'system', type: 'typography' },
654
+ roles: [...rolesMap.entries()].map(([k, v]) => {
655
+ let role = k.split(':')[0];
656
+ let i = 2;
657
+ while (usedRoleSlugs.has(role))
658
+ role = `${k.split(':')[0]}-${i++}`;
659
+ usedRoleSlugs.add(role);
660
+ return {
661
+ role,
662
+ style: v.style,
663
+ count: v.count,
664
+ elements: [...v.elements]
665
+ };
666
+ }),
667
+ families: [...familyCounts.entries()].map(([family, count]) => ({ family, count })),
668
+ scale: [...sizeCounts.entries()].sort((a, b) => b[0] - a[0]).map(([sz, count]) => ({ size: { computed: `${round(sz)}px` }, count }))
669
+ }
670
+ : null;
671
+ const colorAcc = new Map();
672
+ const addColor = (role, hex, prop, token) => {
673
+ const key = `${role}:${hex}`;
674
+ const entry = colorAcc.get(key) ?? { role, value: hex, token, count: 0, props: new Set() };
675
+ entry.count += 1;
676
+ entry.props.add(prop);
677
+ if (token && !entry.token)
678
+ entry.token = token;
679
+ colorAcc.set(key, entry);
680
+ };
681
+ for (const n of payload.nodes) {
682
+ const fill = visibleSolid(n.style?.fills);
683
+ if (fill?.color) {
684
+ const role = n.type === 'TEXT' ? 'text' : 'background';
685
+ const prop = n.type === 'TEXT' ? 'color' : 'background-color';
686
+ addColor(role, figmaColorToCss(fill.color, fill.opacity), prop, resolveBoundToken(payload, n, ['fills'], tokensFile));
687
+ }
688
+ const stroke = visibleSolid(n.style?.strokes);
689
+ if (stroke?.color) {
690
+ addColor('border', figmaColorToCss(stroke.color, stroke.opacity), 'border-color', resolveBoundToken(payload, n, ['strokes'], tokensFile));
691
+ }
692
+ }
693
+ const colorTokensList = [];
694
+ if (tokensFile) {
695
+ for (const v of payload.variables.filter(x => x.type === 'COLOR')) {
696
+ const entry = tokensFile.tokens[tokenIdentityKey(payload.figma.fileKey, v)];
697
+ if (entry?.status === 'mapped' && entry.code?.token) {
698
+ colorTokensList.push({ token: entry.code.token, value: formatVariableValue(v, payload.variables), count: 1 });
699
+ }
700
+ }
701
+ }
702
+ const color = colorAcc.size
703
+ ? {
704
+ meta: { ...meta, name: 'figma-color', scope: 'system', type: 'color' },
705
+ roles: [...colorAcc.values()].map(c => ({
706
+ role: c.role,
707
+ value: c.token ? { computed: c.value, token: c.token } : { computed: c.value },
708
+ count: c.count,
709
+ properties: [...c.props]
710
+ })),
711
+ tokens: colorTokensList
712
+ }
713
+ : null;
714
+ const spacingCounts = new Map();
715
+ const addSpace = (px, token) => {
716
+ if (!Number.isFinite(px) || px <= 0)
717
+ return;
718
+ const rounded = Number(px.toFixed(2));
719
+ const entry = spacingCounts.get(rounded) ?? { count: 0, token };
720
+ entry.count += 1;
721
+ if (token && !entry.token)
722
+ entry.token = token;
723
+ spacingCounts.set(rounded, entry);
724
+ };
725
+ for (const n of payload.nodes) {
726
+ if (n.layout?.primaryAlign !== 'SPACE_BETWEEN' && n.layout?.gap) {
727
+ addSpace(n.layout.gap, resolveBoundToken(payload, n, ['itemSpacing'], tokensFile));
728
+ }
729
+ if (n.layout?.padding) {
730
+ for (const p of n.layout.padding) {
731
+ addSpace(p, resolveBoundToken(payload, n, ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'], tokensFile));
732
+ }
733
+ }
734
+ }
735
+ const spacing = spacingCounts.size
736
+ ? {
737
+ meta: { ...meta, name: 'figma-spacing', scope: 'system', type: 'spacing' },
738
+ scale: [...spacingCounts.entries()]
739
+ .sort((a, b) => a[0] - b[0])
740
+ .map(([px, info]) => ({
741
+ value: info.token ? { computed: `${round(px)}px`, token: info.token } : { computed: `${round(px)}px` },
742
+ count: info.count
743
+ })),
744
+ baseUnit: { px: 4, share: 1 },
745
+ outliers: []
746
+ }
747
+ : null;
748
+ return {
749
+ typography: typography ? { fileName: figmaCaptureFileName('system', 'typography'), capture: typography } : null,
750
+ color: color ? { fileName: figmaCaptureFileName('system', 'color'), capture: color } : null,
751
+ spacing: spacing ? { fileName: figmaCaptureFileName('system', 'spacing'), capture: spacing } : null
752
+ };
753
+ }
754
+ /**
755
+ * Convert a validated Figma payload into Luci ComponentCapture, SectionCapture, and System captures.
756
+ * Selector is omitted on components until matched to built code (origin: 'figma' permits selector-less files).
757
+ */
758
+ export function normalizeFigmaPayload(payload, options = {}) {
759
+ const date = options.date ?? new Date().toISOString().slice(0, 10);
760
+ const metaBase = {
761
+ source: figmaCaptureSource(payload.figma.fileKey),
762
+ captured: date,
763
+ method: 'imported',
764
+ origin: 'figma'
765
+ };
766
+ const rootId = normalizeFrameNodeId(payload.figma.frameNodeId);
767
+ const root = payload.nodes.find(n => n.id === rootId);
768
+ const frameWidth = root?.size?.width && Number.isFinite(root.size.width) && Math.round(root.size.width) > 0
769
+ ? Math.round(root.size.width)
770
+ : undefined;
771
+ const frameResponsive = frameWidth
772
+ ? { widths: [frameWidth], queries: [], source: 'figma-frame', changes: [] }
773
+ : undefined;
774
+ const { candidates, walkedIntoIds, childrenByParent } = selectComponentTree(payload);
775
+ const usedFiles = new Set(options.takenFileNames ?? []);
776
+ const allocSlug = (label, scope = 'component') => {
777
+ const base = toCaptureName(sanitizeFigmaLabel(label));
778
+ let next = base;
779
+ let n = 2;
780
+ while (usedFiles.has(figmaCaptureFileName(scope, next)))
781
+ next = `${base}-${n++}`;
782
+ usedFiles.add(figmaCaptureFileName(scope, next));
783
+ return next;
784
+ };
785
+ const components = [];
786
+ const compByNodeId = new Map();
787
+ const handledNodeIds = new Set();
788
+ if (options.groups) {
789
+ for (const [groupSlug, groupNodes] of options.groups.entries()) {
790
+ if (!groupNodes.length)
791
+ continue;
792
+ for (const gn of groupNodes)
793
+ handledNodeIds.add(gn.id);
794
+ const rep = groupNodes[0];
795
+ const layerKey = layerIdentityKey(payload.figma.fileKey, rep);
796
+ const existing = options.layersFile?.layers[layerKey];
797
+ const ruleFile = existing?.match?.rule ?? figmaCaptureFileName('component', allocSlug(groupSlug));
798
+ const slug = ruleFile.replace(/^figma-com\.component\./, '').replace(/\.design\.md$/, '');
799
+ const compItem = {
800
+ fileName: ruleFile,
801
+ layerKey,
802
+ capture: buildComponentCapture(payload, rep, groupNodes, slug, metaBase, existing?.match?.code?.selector, options.tokensFile, frameResponsive)
803
+ };
804
+ components.push(compItem);
805
+ for (const gn of groupNodes)
806
+ compByNodeId.set(gn.id, compItem);
807
+ }
808
+ }
809
+ for (const node of candidates) {
810
+ if (handledNodeIds.has(node.id))
811
+ continue;
812
+ const layerKey = layerIdentityKey(payload.figma.fileKey, node);
813
+ // Skip re-emitting duplicates of the same library/local component unless it's the first occurrence
814
+ if (handledNodeIds.has(layerKey))
815
+ continue;
816
+ handledNodeIds.add(node.id);
817
+ handledNodeIds.add(layerKey);
818
+ const existing = options.layersFile?.layers[layerKey];
819
+ const ruleFile = existing?.match?.rule ?? figmaCaptureFileName('component', allocSlug(node.component?.name ?? node.name));
820
+ const slug = ruleFile.replace(/^figma-com\.component\./, '').replace(/\.design\.md$/, '');
821
+ const sameIdentity = candidates.filter(c => layerIdentityKey(payload.figma.fileKey, c) === layerKey);
822
+ const compItem = {
823
+ fileName: ruleFile,
824
+ layerKey,
825
+ capture: buildComponentCapture(payload, node, sameIdentity, slug, metaBase, existing?.match?.code?.selector, options.tokensFile, frameResponsive)
826
+ };
827
+ components.push(compItem);
828
+ for (const sn of sameIdentity)
829
+ compByNodeId.set(sn.id, compItem);
830
+ }
831
+ let section = null;
832
+ if (root) {
833
+ const existingSectionFile = options.sectionFileName
834
+ ?? options.layersFile?.files[payload.figma.fileKey]?.frames[rootId]?.sectionRule;
835
+ const sectionFile = existingSectionFile || figmaCaptureFileName('section', allocSlug(root.name, 'section'));
836
+ const frameSlug = sectionFile.replace(/^figma-com\.section\./, '').replace(/\.design\.md$/, '');
837
+ const structure = [
838
+ {
839
+ depth: 0,
840
+ part: 'container',
841
+ element: nodeElementLabel(root),
842
+ styles: nodeStyles(root, payload, options.tokensFile)
843
+ }
844
+ ];
845
+ const usedPartSlugs = new Set(['container']);
846
+ const allocPart = (label) => {
847
+ const base = toCaptureName(sanitizeFigmaLabel(label));
848
+ let next = base;
849
+ let n = 2;
850
+ while (usedPartSlugs.has(next))
851
+ next = `${base}-${n++}`;
852
+ usedPartSlugs.add(next);
853
+ return next;
854
+ };
855
+ const walkedIntoNodes = [];
856
+ const usedComponents = new Map();
857
+ const candidateIdSet = new Set(candidates.map(c => c.id));
858
+ const emitSectionChildren = (parentId, sectionDepth, parentPart) => {
859
+ const siblingRowByFile = new Map();
860
+ for (const child of childrenByParent.get(parentId) ?? []) {
861
+ if (candidateIdSet.has(child.id)) {
862
+ const comp = compByNodeId.get(child.id);
863
+ if (!comp)
864
+ continue;
865
+ const compName = comp.capture.meta.name;
866
+ const existing = usedComponents.get(comp.fileName);
867
+ if (existing) {
868
+ existing.count += 1;
869
+ }
870
+ else {
871
+ usedComponents.set(comp.fileName, {
872
+ name: compName,
873
+ type: comp.capture.meta.type,
874
+ file: comp.fileName,
875
+ count: 1,
876
+ variants: Math.max(1, comp.capture.variants?.length ?? 1)
877
+ });
878
+ }
879
+ const sib = siblingRowByFile.get(comp.fileName);
880
+ if (sib) {
881
+ sib.count = (sib.count ?? 1) + 1;
882
+ }
883
+ else {
884
+ const row = {
885
+ depth: sectionDepth,
886
+ part: compName,
887
+ parent: parentPart,
888
+ element: 'div (component)',
889
+ styles: [],
890
+ component: { name: compName, file: comp.fileName }
891
+ };
892
+ siblingRowByFile.set(comp.fileName, row);
893
+ structure.push(row);
894
+ }
895
+ }
896
+ else if (walkedIntoIds.has(child.id)) {
897
+ walkedIntoNodes.push(child);
898
+ const part = allocPart(child.name);
899
+ structure.push({
900
+ depth: sectionDepth,
901
+ part,
902
+ parent: parentPart,
903
+ element: nodeElementLabel(child),
904
+ styles: nodeStyles(child, payload, options.tokensFile)
905
+ });
906
+ emitSectionChildren(child.id, sectionDepth + 1, part);
907
+ }
908
+ else {
909
+ emitSectionChildren(child.id, sectionDepth, parentPart);
910
+ }
911
+ }
912
+ };
913
+ emitSectionChildren(rootId, 1, 'container');
914
+ section = {
915
+ fileName: sectionFile,
916
+ capture: {
917
+ meta: { ...metaBase, name: frameSlug, scope: 'section', type: 'section' },
918
+ tokens: collectUsedTokens(payload, [root, ...walkedIntoNodes], options.tokensFile),
919
+ structure,
920
+ components: [...usedComponents.values()],
921
+ ...(frameResponsive ? { responsive: frameResponsive } : {})
922
+ }
923
+ };
924
+ }
925
+ const systems = buildSystems(payload, metaBase, options.tokensFile);
926
+ return {
927
+ components,
928
+ section,
929
+ ...systems
930
+ };
931
+ }
932
+ //# sourceMappingURL=normalize.js.map