@moondraft/import 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.5.0 — 2026-11-30
6
+
7
+ - Saved Figma files stream into newline-delimited JSON and split into lazy bundles. `serializeImportNdjson(document)` yields NDJSON lines (`meta`, `shared`, `asset`, `model`): pages first, then component subtrees in dependency order, then page layers, so a streaming reader never creates an instance before its main. `createLazyBundle(document, { assets })` yields a `moondraft-lazy-v2` bundle: an `index.json` manifest, `shared.ndjson`, one file per component subtree under `components/` (main components and variant sets on public pages included, grouped into strongly connected components in topological order, whose index is each subtree's `scc`), one file per non-empty page under `pages/`, and base64 data-URL media sources as files under `assets/`. A video's poster stays an embedded data URL, the only poster the editor takes. Layers may come in any order; a layer whose parent is missing, or parents that form a cycle, make it throw. Swap property defaults, preferred lists and swap values count as dependencies alongside instances and swapped overrides (`componentRefsOf`). Subtree and page files are named by `bundleFileName(id)`, which is one to one and has no `%`, so IDs such as `12:34` (`12_3A34`) survive servers that decode request paths.
8
+ - `openFigmaFile` and `readFigmaFile` accept `pages` (the public page names to import) and `limits` (node, depth and vector-command ceilings), and `figmaImporter({ limits })` passes its limits on, on the calling thread and to the module worker. Progress callbacks also report the `walk`, `pages`, `components`, `resources` and `derive` stages.
9
+ - `FigmaImportLimits` (the `nodes`, `depth` and `vectorCommands` ceilings) is exported, to type a `limits` option.
10
+ - Corrupt values in large saved files no longer abort the whole import. A frame, group, instance or other layer with a non-finite size or transform (`NaN` or infinity) keeps its children: a non-finite width, height or position reads as 0, a non-finite rotation or scale as none, and the layer is reported as approximated. A vector with a non-finite transform is left out. A non-finite colour drops only that paint, gradient stop, shadow, text fill or variable mode value; a non-finite shadow offset, spread or radius, or blur radius, drops only that effect; a non-finite font size takes the size beneath it (the text style's or the layer's), else the default, and is reported as approximated. A variable mode entry without a `variableModeID` is skipped, so the layer inherits its parent's mode.
11
+ - Variables that share a name inside one Figma collection import as `Name`, `Name 2`, `Name 3`, … (IDs, so aliases, unchanged), and components and variant sets that share a `componentKey` keep it on the first in the file while the others take their `figma-<id>` fallback key, so the editor no longer refuses the document. The import report lists each rename and replaced key.
12
+ - Import report entries have an optional `sources` list (`ImportReportSource[]`) naming the source-file layers they are about by ID and name. The Figma importer fills it for the entries above, so a layer left out of a large file can be found there.
13
+
5
14
  ## 0.4.0 — 2026-11-28
6
15
 
7
16
  - The peer dependency on `@moondraft/editor` is now `>=0.6.0 <0.7.0`. Install the editor 0.6.0 or later in the
package/README.md CHANGED
@@ -32,6 +32,31 @@ await writeFile('design.json', serializeImportDocument(document))
32
32
  console.log(report)
33
33
  ```
34
34
 
35
+ For very large files whose JSON would exceed the JavaScript string limit, write newline-delimited JSON with
36
+ `serializeImportNdjson(document)` instead, or split the document into a lazy bundle with `createLazyBundle(document)`:
37
+
38
+ ```js
39
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
40
+ import { dirname, join } from 'node:path'
41
+ import { createLazyBundle, openFigmaFile } from '@moondraft/import'
42
+
43
+ const { document } = await openFigmaFile(await readFile('design.fig'), {
44
+ limits: { nodes: 1_000_000 }, // optional: raise the reader's node cap (also depth, vectorCommands)
45
+ pages: ['Page 1', 'Page 2'], // optional: import only these public pages
46
+ })
47
+ const bundle = createLazyBundle(document) // pass { assets: false } to keep data URLs inline
48
+ for (const file of bundle.files()) {
49
+ const path = join('out', file.path)
50
+ await mkdir(dirname(path), { recursive: true })
51
+ await writeFile(path, file.content, { flag: file.append ? 'a' : 'w' })
52
+ }
53
+ ```
54
+
55
+ A lazy bundle (`index.json`, `shared.ndjson`, `components/*.ndjson`, `pages/*.ndjson`, `assets/*`) lists every page up
56
+ front and groups component subtrees — including mains living on public pages — in topological order, so a host can
57
+ load only the page being viewed and fetch each referenced main component before inserting the instances that use it.
58
+ Subtree and page files are named `bundleFileName(id)`; `componentRefsOf(layer)` lists the mains a layer can name.
59
+
35
60
  In Node, `runImport` from `@moondraft/editor/core` can also select a registered importer. Supply `svgImporter({ parseSvg })` with an XML parser that returns the SVG root element. Host importers can use `payloadFromSyntax(text)` to create paste payloads from the agent build tool's layer syntax.
36
61
 
37
62
  See [CHANGELOG.md](CHANGELOG.md) for releases, [SOURCE.md](SOURCE.md) for reader provenance and [LICENSE](LICENSE) for licensing.
package/SOURCE.md CHANGED
@@ -529,3 +529,29 @@ this, marked "Moondraft patch 0053".
529
529
  of an expanded instance (`src/adapter/file-resources.ts`) as an override is converted for a linked one: a field the
530
530
  override sets drops the main's binding of it, and the override's bindings replace only the main's of the same fields.
531
531
  The functions themselves are unchanged.
532
+
533
+ ### `patches/0055-non-finite-numbers-and-stale-modes.patch`
534
+
535
+ Large saved files can carry isolated corrupt numbers or stale references that should not abort every page of the
536
+ import. `readNumbers` reads a non-finite number (`NaN` or infinity) like a missing field instead of refusing the
537
+ message with `not-node-changes`; a field of the wrong type (a string, say) still refuses it. Where that would drop
538
+ more than the corrupt value, the readers say what they keep:
539
+
540
+ - `frameGeometry` reads a non-finite width, height or position (`m02`, `m12`) as 0, and a rotation or scale part
541
+ (`m00`, `m01`, `m10`, `m11`) with a non-finite number as no rotation and no scale, so a frame, group, instance or
542
+ other framed layer keeps its children; `framedBase` reports it as approximated. `pathTransform` still leaves out a
543
+ vector whose transform has a non-finite number.
544
+ - A paint, shadow or text fill with a non-finite colour, or a gradient stop with a non-finite colour or position,
545
+ drops only itself, and a colour variable value with a non-finite channel drops only that mode's value. A shadow
546
+ with a non-finite offset, spread or radius, or a blur with a non-finite radius, drops only that effect. Each is
547
+ reported, naming the non-finite number (`NON_FINITE`).
548
+ - `styleFields` passes over a non-finite `fontSize` to the next size beneath it (the text style's, then the node's),
549
+ or leaves it absent so the default applies; `runStyle` reports it as approximated.
550
+ - The adapter places gradient stop bindings (`src/adapter/file-resources.ts`) without the stops the reader left out.
551
+ - `readFigmaVariables` skips a `variableModeBySetMap` or explicit-mode entry that has no `variableModeID`, so the layer
552
+ inherits its parent's mode; a `variableModeID` that is present but not a GUID still refuses the message.
553
+ - The walk reports a component whose repeated `componentKey` the file's key source replaced (`DUPLICATE_KEY`), as the
554
+ adapter does for variant sets. The adapter names the Figma node (ID and name, `sources`) in every entry whose reason
555
+ `namesNode` matches.
556
+
557
+ Covered in `convert-vector.test.ts` and `convert-variables.test.ts`, marked "Moondraft patch 0055".
@@ -1451,6 +1451,8 @@ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
1451
1451
  }
1452
1452
  }
1453
1453
  appearance(m, style, 'frame', n.metadata?.figma);
1454
+ if (n.type === 'frame' && n.metadata?.figma?.section === true)
1455
+ m.section = true;
1454
1456
  if (n.metadata?.figma?.strokesIncluded === true && (eff.layout && eff.layout.kind !== 'absolute')) {
1455
1457
  eff.layout = { ...eff.layout, strokesIncluded: true };
1456
1458
  }
@@ -2823,6 +2825,20 @@ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
2823
2825
  const out = { leading: 'half', ...(!explicit && { page: pages[0].name }), ...(options.source !== undefined ? { source: options.source } : {}), models, ...(used.size ? { assets } : {}) };
2824
2826
  return { out, affected, nestedBooleans, counts: { dropped, expressionErrors, notes, approximations, weights }, depth: depthMax, files };
2825
2827
  }
2828
+ /** A section stays one only on a page or inside another section, the editor's rule and Figma's: anywhere else (a
2829
+ * clipboard selection pasted whole, a layer the conversion re-parented) it imports as the plain frame it draws as.
2830
+ * Parents precede their children in the models. */
2831
+ function keepSections(models) {
2832
+ const holds = new Set(models.filter((m) => m.kind === 'page').map((m) => m.id));
2833
+ for (const m of models) {
2834
+ if (m.kind !== 'frame' || m.section !== true)
2835
+ continue;
2836
+ if (!m.parent || holds.has(m.parent))
2837
+ holds.add(m.id);
2838
+ else
2839
+ delete m.section;
2840
+ }
2841
+ }
2826
2842
  function convert(doc, pages, options, explicit, file, deferHyperlinks = false) {
2827
2843
  // Drop the resolver, trial layouts and pre-layout geometry before indexing linked layers.
2828
2844
  const { out, affected, nestedBooleans, counts, depth, files } = expand(doc, pages, options, explicit, file, deferHyperlinks);
@@ -2905,6 +2921,7 @@ function convert(doc, pages, options, explicit, file, deferHyperlinks = false) {
2905
2921
  if (options.link === false && !options.markers)
2906
2922
  for (const m of out.models)
2907
2923
  unmark(m);
2924
+ keepSections(out.models);
2908
2925
  const remaining = new Set(out.models.map((m) => m.id));
2909
2926
  function affectedIds(id) {
2910
2927
  const aliases = linked?.aliases.get(id) ?? [];
@@ -1,5 +1,6 @@
1
1
  import { definitions as propertyDefinitions, effectiveRecord, isInstance, ownerOf, resolveVirtual, splitVirtual } from '@moondraft/editor/core';
2
2
  import { guidText } from '../taco/figma-import/import/fields.js';
3
+ import { DUPLICATE_KEY } from '../taco/figma-import/import/converters/shared.js';
3
4
  import { formatExpressionName, layerPathKey, parseLayerPath } from '../taco/model/index.js';
4
5
  import { keepDescription } from './figma-descriptions.js';
5
6
  import { withOverrideFields } from './file-resources.js';
@@ -95,6 +96,7 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
95
96
  const importedSets = new Map(result.sources.imported.filter(({ figma }) => figma.change.isStateGroup === true)
96
97
  .map(({ node, figma }) => [figma.id, node.id]));
97
98
  const setSources = new Map();
99
+ const setKeys = new Set();
98
100
  for (const [guid, { plan, properties }] of result.sources.variants) {
99
101
  const members = plan.variants;
100
102
  const sourceId = importedSets.get(guid);
@@ -107,7 +109,14 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
107
109
  models.push(set);
108
110
  byId.set(set.id, set);
109
111
  }
110
- set.key = plan.set.change.componentKey || 'figma-' + guid;
112
+ // The editor refuses two sets of one key. The first set in the file's node order keeps a repeated Figma key; the
113
+ // others take their fallback key, so library links by that key reach only the first.
114
+ const authored = plan.set.change.componentKey;
115
+ set.key = typeof authored === 'string' && authored !== '' && !setKeys.has(authored) ? authored : 'figma-' + guid;
116
+ if (set.key !== authored && typeof authored === 'string' && authored !== '') {
117
+ report.push({ kind: 'approximated', what: DUPLICATE_KEY, count: 1, ids: [set.id], sources: [{ id: guid, name: plan.set.name }] });
118
+ }
119
+ setKeys.add(set.key);
111
120
  keepDescription(plan.set, set, report);
112
121
  const variantDefs = new Map(plan.set.change.componentPropDefs.map(d => ['figma-' + guidText(d.id, guid), d]));
113
122
  const orders = new Map((plan.set.change.stateGroupPropertyValueOrders ?? []).map(o => [o.property, o.values]));
@@ -1,4 +1,4 @@
1
- import type { ImportReportEntry } from '@moondraft/editor/core';
1
+ import { type ImportReportEntry } from '@moondraft/editor/core';
2
2
  import { type DocumentJSON } from '@moondraft/editor/schema';
3
3
  import { type FigmaObject } from '../taco/figma-import/import/fields.ts';
4
4
  import type { FileMessage } from './file-components.ts';
@@ -1,7 +1,9 @@
1
+ import { resolveVirtual } from '@moondraft/editor/core';
1
2
  import * as editorSchema from '@moondraft/editor/schema';
2
3
  import { STYLES, VARIABLES } from '@moondraft/editor/schema';
3
4
  import { typographyVariable } from '../taco/figma-import/import/variables.js';
4
5
  import { TEXT_VARIABLE_FIELDS, textColor } from '../taco/figma-import/import/converters/text.js';
6
+ import { hasNonFinite } from '../taco/figma-import/import/converters/shared.js';
5
7
  import { applyFileTypography, supportsTextField, supportsTypographyBindings } from './file-typography.js';
6
8
  import { variableResolver } from './variables.js';
7
9
  import { styleAtOf, supportsRunPaint } from './link.js';
@@ -55,12 +57,22 @@ function fileVariables(result, shared, identity, report) {
55
57
  for (const [id, c] of Object.entries(result.variableCollections)) {
56
58
  shared.push({ ...identity(variables.sources.get(id)), id, parent: VARIABLES, kind: 'collection', name: c.name,
57
59
  modes: c.modeOrder.map(id => ({ id, name: c.modes[id].name })), defaultMode: c.defaultModeId });
60
+ // The editor refuses two variables of one name in a collection, which Figma allows: an authored name is kept and
61
+ // each repeat takes the first free `Name 2`, `Name 3`, …; its ID, so aliases to it, is unchanged.
62
+ const authored = new Set(Object.values(c.variables).map(v => v.name)), taken = new Set();
58
63
  for (const [varId, v] of Object.entries(c.variables)) {
59
64
  const node = variables.sources.get(varId);
65
+ let name = v.name;
66
+ if (taken.has(name)) {
67
+ for (let n = 2; authored.has(name) || taken.has(name); n++)
68
+ name = `${v.name} ${n}`;
69
+ report.push({ kind: 'approximated', what: `variable renamed from ${v.name} to ${name}`, count: 1, ids: [varId], sources: [{ id: node.id, name: v.name }] });
70
+ }
71
+ taken.add(name);
60
72
  const values = Object.fromEntries(Object.entries(v.values).map(([mode, value]) => [mode, v.type === 'color' ? rgba(value) : value]));
61
73
  for (const [mode, alias] of variables.aliases.get(varId) ?? [])
62
74
  values[mode] = { alias };
63
- const record = { ...identity(node), id: varId, parent: id, name: v.name, kind: 'variable', type: v.type, values };
75
+ const record = { ...identity(node), id: varId, parent: id, name, kind: 'variable', type: v.type, values };
64
76
  keepDescription(node, record, report);
65
77
  keepVariableMetadata(node, record, report);
66
78
  shared.push(record);
@@ -109,8 +121,10 @@ function paintsAndEffects(change, m, bind, indices) {
109
121
  bind(undefined, paint.opacityVar, 'number');
110
122
  if (!paint.stopsVar)
111
123
  return;
112
- // The reader sorts the stops and samples a new endpoint for stops beyond the paint's range.
113
- const sorted = (paint.stops ?? []).map((stop, source) => ({ at: stop.position, source }))
124
+ // The reader sorts the stops and samples a new endpoint for stops beyond the paint's range. It leaves out a stop
125
+ // with a non-finite colour or position (Moondraft patch 0055), so that stop takes no place here either.
126
+ const sorted = (paint.stops ?? []).map((stop, source) => ({ at: stop.position, source, stop }))
127
+ .filter(({ stop }) => !(isObject(stop) && (hasNonFinite(stop, ['position']) || isObject(stop.color) && hasNonFinite(stop.color, ['r', 'g', 'b', 'a']))))
114
128
  .sort((a, b) => a.at - b.at);
115
129
  const inside = sorted.filter((stop) => stop.at >= 0 && stop.at <= 1);
116
130
  const first = Number(sorted[0]?.at < 0);
@@ -274,9 +288,27 @@ function variantFields(change, m, into, records, bind, lost) {
274
288
  }
275
289
  }
276
290
  }
291
+ /** A layer's fill list or stroke paint as the renderer draws it (a compact colour is one solid paint). */
292
+ function paintOf(m, key) {
293
+ if (key === 'look.fills')
294
+ return m.look?.fills ?? (m.fill ? [{ k: 'solid', c: m.fill }] : []);
295
+ return m.look?.stroke?.paint ?? (m.stroke ? { k: 'solid', c: m.stroke } : undefined);
296
+ }
297
+ /** Whether two paint values are equal everywhere except at the bound paths below `path` (a missing opacity is 1). */
298
+ function sameExceptBound(a, b, path, bound) {
299
+ if (bound.has(path) || a === b)
300
+ return true;
301
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) !== Array.isArray(b))
302
+ return false;
303
+ if (Array.isArray(a) && a.length !== b.length)
304
+ return false;
305
+ return Object.keys({ ...a, ...b }).every(k => k === 'o' && !Array.isArray(a)
306
+ ? (a.o ?? 1) === (b.o ?? 1) : sameExceptBound(a[k], b[k], path + '.' + k, bound));
307
+ }
277
308
  // Linking compares painted instances with their mains. A mode difference in that comparison is derived:
278
309
  // leaving it as an authored paint override would mask the binding when the mode changes again.
279
- function inheritedLiterals(entry, template, change, expanded, rootBindings) {
310
+ // rootBindings: the instance root bindings `change` repeats from the main; `occurrence` when `entry` is not the node's own.
311
+ function inheritedLiterals(entry, template, change, expanded, rootBindings, occurrence = false, dropped) {
280
312
  const sources = Object.keys(template.vars ?? {});
281
313
  const inherited = (key) => sources.some(path => path === key || path.startsWith(key + '.'));
282
314
  const formatting = [
@@ -289,11 +321,31 @@ function inheritedLiterals(entry, template, change, expanded, rootBindings) {
289
321
  for (const [key, style, list, ref] of formatting) {
290
322
  if (!template[style] && !inherited(key))
291
323
  continue;
292
- if (!(list in change || ref in change))
293
- delete entry[key];
294
- else if (!(key in entry) && list in change && !(ref in change)) {
324
+ // An instance's own record writes a removed fill or effect list as no field; an occurrence entry omits what
325
+ // it inherits. (A removed stroke keeps the instance expanded.)
326
+ const value = entry[key], removed = rootBindings && !occurrence && key !== 'look.stroke.paint' && value !== undefined
327
+ && (Array.isArray(value) ? !value.length : !value.radius);
328
+ if (!(list in change || ref in change)) {
329
+ if (!removed)
330
+ delete entry[key];
331
+ }
332
+ else if (list in change && !(ref in change)) {
295
333
  const bound = sources.filter(path => path.startsWith(key + '.'));
296
- if (bound.length && rootBindings && bound.every(path => rootBindings.has(path)))
334
+ const rebound = bound.length > 0 && rootBindings !== undefined && bound.every(path => rootBindings.has(path));
335
+ if (key in entry) {
336
+ // An instance root keeps its main's binding, so its paint resolved in an explicit mode is no override; any other
337
+ // difference (another opacity, an added paint) still is, and the editor cannot hold the binding next to it.
338
+ if (rebound && (key === 'look.fills' || key === 'look.stroke.paint')) {
339
+ if (sameExceptBound(entry[key], paintOf(template, key), key, new Set(bound)))
340
+ delete entry[key];
341
+ else
342
+ dropped?.();
343
+ }
344
+ continue;
345
+ }
346
+ // A layer the instance does not show (an occurrence of the component it was swapped from) has no expanded record
347
+ // and takes no literal.
348
+ if (rebound || !expanded)
297
349
  continue;
298
350
  // The link pass omits equal literals. An authored value still masks the main's source.
299
351
  if (key === 'look.fills')
@@ -310,7 +362,7 @@ function inheritedLiterals(entry, template, change, expanded, rootBindings) {
310
362
  const authored = key === 'content' ? change.textData?.characters !== undefined : field in change;
311
363
  if (!authored)
312
364
  delete entry[key];
313
- else if (!(key in entry))
365
+ else if (!(key in entry) && (expanded || key !== 'content'))
314
366
  entry[key] = key === 'content' ? expanded.content : change[field];
315
367
  }
316
368
  }
@@ -808,7 +860,7 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
808
860
  }
809
861
  function install(change, m, into, id, virtual = false) {
810
862
  const instance = isInstance(m);
811
- const root = instance ? records.get(m.component) : m;
863
+ const root = instance ? records.get(virtual ? shownMain(id, into, m) : m.component) : m; // an enclosing instance may switch the main
812
864
  const rootBindings = instance ? new Set() : undefined;
813
865
  const paint = instance ? appearance(root, m.overrides?.['']) : virtual ? appearance(m, into) : m;
814
866
  const lists = { fillPaints: change.fillPaints, strokePaints: change.strokePaints, effects: change.effects };
@@ -907,9 +959,9 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
907
959
  lost('variable binding', id);
908
960
  }
909
961
  }
910
- if (rootBindings && !virtual) {
911
- inheritedLiterals(rootEntry, root, change, expanded.get(id), rootBindings);
912
- if (Object.keys(rootEntry).length)
962
+ if (rootBindings) {
963
+ inheritedLiterals(rootEntry, root, change, expanded.get(id), rootBindings, virtual, () => lost('instance paint binding kept as plain paint', id));
964
+ if (!virtual && Object.keys(rootEntry).length)
913
965
  (m.overrides ??= {})[''] = rootEntry;
914
966
  }
915
967
  const chosen = new Set();
@@ -1009,6 +1061,13 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
1009
1061
  if (source)
1010
1062
  install(expandedFields(m, source.figma.change), m, m, m.id);
1011
1063
  }
1064
+ // The main an inner instance occurrence shows: a switch by the outer instance or by a main in between wins.
1065
+ const kids = new Map();
1066
+ for (const m of layers)
1067
+ if (m.parent !== undefined)
1068
+ kids.get(m.parent)?.push(m.id) ?? kids.set(m.parent, [m.id]);
1069
+ const lookup = (id) => { const m = records.get(id); return m && isInstance(m) ? { ...m, children: kids.get(id) ?? [] } : m; };
1070
+ const shownMain = (id, entry, target) => entry.component ?? resolveVirtual(lookup, id, true)?.component ?? target.component;
1012
1071
  const nestedPalettes = [];
1013
1072
  for (const m of layers) {
1014
1073
  const authored = occurrences.get(m.id);
@@ -1057,6 +1116,8 @@ export function fileResources(result, doc, occurrences, expanded, expandedRadii,
1057
1116
  if (!change && Object.keys(target.vars ?? {}).some(key => key.startsWith('radius.')))
1058
1117
  delete entry.radius;
1059
1118
  }
1119
+ else if (path && target && !change)
1120
+ inheritedLiterals(entry, records.get(shownMain(id, entry, target)), {}, expanded.get(id)); // an inner instance's root, shown after enclosing switches
1060
1121
  if (change && target)
1061
1122
  install(change, target, path ? entry : m, path ? id : m.id, !!path);
1062
1123
  if (Object.keys(entry).length)
@@ -1,4 +1,5 @@
1
- import type { ImportDocument, ImportEnv, ImportSignal } from '@moondraft/editor/core';
1
+ import type { ImportDocument, ImportSignal } from '@moondraft/editor/core';
2
+ import type { ReadFigmaOptions } from './figma.ts';
2
3
  /** The subset of a module worker used to read a .fig file. */
3
4
  export interface WorkerLike {
4
5
  /**
@@ -22,7 +23,7 @@ export interface WorkerLike {
22
23
  terminate(): void;
23
24
  }
24
25
  /** Options for reading a .fig file. */
25
- export interface OpenFigmaOptions extends Pick<ImportEnv, 'signal' | 'progress'> {
26
+ export interface OpenFigmaOptions extends Pick<ReadFigmaOptions, 'signal' | 'progress' | 'limits' | 'pages'> {
26
27
  /** Factory for a dedicated worker. Defaults to a module worker when available. Pass null to read on this thread. */
27
28
  worker?: (() => WorkerLike) | null;
28
29
  }
@@ -24,7 +24,9 @@ export async function openFigmaFile(bytes, options = {}) {
24
24
  }
25
25
  if (!worker) {
26
26
  const { readFigmaFile } = await import('./figma.js');
27
- return readFigmaFile(bytes, { signal, progress });
27
+ return readFigmaFile(bytes, {
28
+ signal, progress, ...(options.limits && { limits: options.limits }), ...(options.pages && { pages: options.pages }),
29
+ });
28
30
  }
29
31
  const own = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
30
32
  try {
@@ -53,8 +55,11 @@ export async function openFigmaFile(bytes, options = {}) {
53
55
  });
54
56
  worker.addEventListener('messageerror', () => { finish(); reject(new Error('the Figma importer sent a reply that could not be read')); });
55
57
  worker.addEventListener('error', ({ message }) => { finish(); reject(new Error(`the Figma importer failed to run: ${message ?? 'worker error'}`)); });
58
+ const request = {
59
+ bytes: own, ...(options.limits && { limits: options.limits }), ...(options.pages && { pages: options.pages }),
60
+ };
56
61
  try {
57
- worker.postMessage(own, [own.buffer]);
62
+ worker.postMessage(request, [own.buffer]);
58
63
  }
59
64
  catch (error) {
60
65
  finish();
@@ -1,4 +1,5 @@
1
1
  import type { ImportDocument, ImportProgress } from '@moondraft/editor/core';
2
+ import { type ReadFigmaOptions } from './figma.ts';
2
3
  /** Replies sent by the module worker after it is ready. */
3
4
  export type FigmaWorkerReply = {
4
5
  progress: ImportProgress;
@@ -9,3 +10,7 @@ export type FigmaWorkerReply = {
9
10
  ok: false;
10
11
  error: string;
11
12
  };
13
+ /** A .fig file read request sent to the module worker. */
14
+ export type FigmaWorkerRequest = {
15
+ bytes: Uint8Array;
16
+ } & Pick<ReadFigmaOptions, 'limits' | 'pages'>;
@@ -2,7 +2,12 @@ import { readFigmaFile } from './figma.js';
2
2
  const scope = globalThis;
3
3
  scope.onmessage = ({ data }) => {
4
4
  try {
5
- const value = readFigmaFile(data, { progress: (progress) => scope.postMessage({ progress }) });
5
+ const request = data instanceof Uint8Array ? { bytes: data } : data;
6
+ const value = readFigmaFile(request.bytes, {
7
+ progress: (progress) => scope.postMessage({ progress }),
8
+ ...(request.limits && { limits: request.limits }),
9
+ ...(request.pages && { pages: request.pages }),
10
+ });
6
11
  scope.postMessage({ ok: true, value });
7
12
  }
8
13
  catch (error) {
package/dist/figma.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type ImportDocument, type ImportEnv, type ImportPayload } from '@moondraft/editor/core';
2
+ import type { FigmaImportLimits } from './taco/figma-import/import/types.ts';
2
3
  /**
3
4
  * Checks for the markers Figma adds to clipboard HTML.
4
5
  * @param html - Clipboard HTML to inspect.
@@ -15,7 +16,12 @@ export declare const MISSING_IMAGES = "Unresolved images (shown as placeholders)
15
16
  */
16
17
  export declare function readFigmaClipboard(html: string): ImportPayload;
17
18
  /** Options for reading a Figma file synchronously. */
18
- export type ReadFigmaOptions = Pick<ImportEnv, 'signal' | 'progress'>;
19
+ export interface ReadFigmaOptions extends Pick<ImportEnv, 'signal' | 'progress'> {
20
+ /** Overrides the reader's node, depth and vector-command limits. */
21
+ limits?: Partial<FigmaImportLimits>;
22
+ /** Imports only public pages whose names appear here (defaults to every public page). */
23
+ pages?: readonly string[];
24
+ }
19
25
  /**
20
26
  * Reads a saved Figma design file on the calling thread.
21
27
  * Values in the result may be shared between layers; copy before mutating in place.
package/dist/figma.js CHANGED
@@ -10,6 +10,7 @@ import { isObject } from './taco/figma-import/import/fields.js';
10
10
  import { sha256Hex } from './taco/model/sha256.js';
11
11
  import { expandedRadiusRoots, fileResources } from './adapter/file-resources.js';
12
12
  import { readFileMessage, walkMessage } from './taco/figma-import/import/walk.js';
13
+ import { namesNode } from './taco/figma-import/import/converters/shared.js';
13
14
  import { allPages, figmaClipboardPage } from './adapter/convert.js';
14
15
  import { convertEntries, droppedFeatures, figmaReportLayers, fontEntries, grouped, leftOutIds, readerCount } from './report.js';
15
16
  import { checkAbort } from './figma-file.js';
@@ -24,7 +25,7 @@ export const holdsFigmaData = (html) => html.includes('(figmeta)') && html.inclu
24
25
  export const MISSING_IMAGES = clipboard.MISSING_IMAGE_REPORT;
25
26
  const STAND_IN = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
26
27
  const ids = () => { let next = 0; return () => `f${++next}`; };
27
- function reportOf(result, converted, features, extra, file = false) {
28
+ function reportOf(result, converted, features, extra, nodes, file = false) {
28
29
  const { bySource, pages, derive } = figmaReportLayers(converted.doc, file);
29
30
  const dropped = [];
30
31
  for (const { figmaId, what, leftOut } of features) {
@@ -43,7 +44,10 @@ function reportOf(result, converted, features, extra, file = false) {
43
44
  const layer = result.layerIds[entry.nodeId];
44
45
  const pageId = pageIds.get(entry.nodeId);
45
46
  const ids = pageId ? [pageId] : layer === undefined ? undefined : bySource.get(layer);
46
- return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', ...readerCount(entry), ...(ids && { ids }) };
47
+ // Moondraft patch 0055: an entry about a corrupt number or a replaced key names its Figma node, which a left-out
48
+ // node has no layer in the result to show.
49
+ const named = namesNode(entry.reason) ? [{ id: entry.nodeId, name: nodes.get(entry.nodeId)?.name ?? '' }] : undefined;
50
+ return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', ...readerCount(entry), ...(ids && { ids }), ...(named && { sources: named }) };
47
51
  });
48
52
  return { report: [...reader, ...dropped, ...convertEntries(converted.report, true), ...extra], derive };
49
53
  }
@@ -88,7 +92,7 @@ export function readFigmaClipboard(html) {
88
92
  delete payload.assets[id];
89
93
  if (assetIds.length)
90
94
  extra.push({ kind: 'left-out', what: MISSING_IMAGES, count: assetIds.length, assetIds });
91
- return { payload, report: grouped(reportOf(result, converted, droppedFeatures(message.nodeChanges, leftOut), extra).report) };
95
+ return { payload, report: grouped(reportOf(result, converted, droppedFeatures(message.nodeChanges, leftOut), extra, sources.tree.nodes).report) };
92
96
  }
93
97
  /**
94
98
  * Reads a saved Figma design file on the calling thread.
@@ -109,7 +113,7 @@ export function readFigmaFile(bytes, options = {}) {
109
113
  const { doc, images, report, total, derive } = convertFile(bytes, () => {
110
114
  checkpoint('decode', 1, 1);
111
115
  checkpoint('convert', 0);
112
- });
116
+ }, options);
113
117
  // Use the same derived pass as editor.load so saved literals include mode choices and nested property assignments.
114
118
  let document = doc;
115
119
  if (derive) {
@@ -125,6 +129,7 @@ export function readFigmaFile(bytes, options = {}) {
125
129
  for (const field of fields)
126
130
  report.push({ kind: 'approximated', what: `typography binding kept as value for text field "${field}"`, count: 1, ids: [id] });
127
131
  document = core.releaseJSON();
132
+ checkpoint('derive', 1, 1);
128
133
  }
129
134
  // Only surviving assets need data URLs. Keep their encoded strings out of the layout and linking passes.
130
135
  for (const [id, asset] of Object.entries(document.assets ?? {})) {
@@ -176,17 +181,28 @@ function compactFileRecord(field, change) {
176
181
  change.derivedTextData = metrics;
177
182
  }
178
183
  }
179
- function readFileSource(bytes, decoded) {
184
+ function readFileSource(bytes, decoded, options) {
180
185
  const file = readFigFile(bytes, { onRootArrayItem: compactFileRecord });
181
186
  decoded();
182
- const result = readFileMessage(file.message, {
183
- idSource: ids(), roots: 'pages',
187
+ let message = file.message;
188
+ // Pages left out of `pages` are read as internal ones, so their layers never reach the walk.
189
+ if (options.pages !== undefined && isObject(message) && Array.isArray(message.nodeChanges)) {
190
+ const wanted = new Set(options.pages);
191
+ const nodeChanges = message.nodeChanges.map((change) => isObject(change) && change.type === 'CANVAS' && change.internalOnly !== true && !wanted.has(String(change.name ?? ''))
192
+ ? { ...change, internalOnly: true }
193
+ : change);
194
+ message = { ...message, nodeChanges };
195
+ }
196
+ const result = readFileMessage(message, {
197
+ idSource: ids(), roots: 'pages', ...(options.limits && { limits: options.limits }),
184
198
  images: (hash) => { const bytes = file.images.get(hash); return bytes ? { bytes } : undefined; },
185
199
  });
186
200
  return { result, key: file.meta?.fileKey || file.message.fileKey };
187
201
  }
188
- function convertFile(bytes, decoded) {
189
- const { result, key } = readFileSource(bytes, decoded);
202
+ function convertFile(bytes, decoded, options = {}) {
203
+ const stage = (name) => options.progress?.({ stage: name, done: 1 });
204
+ const { result, key } = readFileSource(bytes, decoded, options);
205
+ stage('walk');
190
206
  // Geometry and overrides now live on the converted nodes. Release their wire
191
207
  // representations while collecting diagnostics in source order. Resource and
192
208
  // metadata adapters still see the original paint lists and all other fields.
@@ -218,15 +234,18 @@ function convertFile(bytes, decoded) {
218
234
  const converted = allPages(geometry, {
219
235
  assetSrc: (_id, asset) => `data:${asset.mimeType};base64,`,
220
236
  });
237
+ stage('pages');
221
238
  const extra = [];
222
239
  // Roots that bind their own radii stay expanded before linking (convert.ts leaves them unmarked).
223
240
  for (const m of converted.doc.models)
224
241
  if (m.fileInstance !== undefined && expandedRadii.has(m.fileInstance))
225
242
  converted.expandedReasons.set(m.id, 'root radius bindings');
226
243
  const { occurrences, setSources } = fileComponents(result, converted.doc, converted.nestedBooleans, extra, converted.expandedReasons);
244
+ stage('components');
227
245
  let fileKey = key;
228
246
  const fileId = () => String(fileKey ||= sha256Hex(bytes));
229
247
  fileResources(result, converted.doc, occurrences, converted.expanded, expandedRadii, extra, fileId);
248
+ stage('resources');
230
249
  for (const layer of converted.doc.models) {
231
250
  if (layer.kind !== 'frame')
232
251
  continue;
@@ -243,7 +262,7 @@ function convertFile(bytes, decoded) {
243
262
  for (const entry of figmaLayoutGrids(result.sources, converted.doc, { setSources, fileId }))
244
263
  extra.push(entry);
245
264
  const reader = result.report.filter(e => !e.reason.startsWith('variable bindings left out, their values kept:'));
246
- const { report, derive } = reportOf({ ...result, report: reader }, converted, features, extra, true);
265
+ const { report, derive } = reportOf({ ...result, report: reader }, converted, features, extra, result.sources.tree.nodes, true);
247
266
  const images = result.assets;
248
267
  for (const id of Object.keys(images))
249
268
  if (!Object.hasOwn(converted.doc.assets ?? {}, id))
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import type { Importer } from '@moondraft/editor/core';
2
2
  import { type SvgParse } from './taco/svg-import/public-types.ts';
3
+ import type { FigmaImportLimits } from './taco/figma-import/import/types.ts';
3
4
  import type { OpenFigmaOptions } from './figma-file.ts';
4
5
  export type { ImportDocument, ImportEnv, ImportInput, ImportPayload, ImportProgress, ImportRead, ImportReportEntry, Importer } from '@moondraft/editor/core';
5
6
  export { openFigmaFile, type OpenFigmaOptions, type WorkerLike } from './figma-file.ts';
7
+ export type { FigmaImportLimits } from './taco/figma-import/import/types.ts';
6
8
  /** Options for registering an SVG importer. */
7
9
  export interface SvgImporterOptions {
8
10
  /** Parses markup into an element tree (default: the browser's DOMParser). */
@@ -18,6 +20,8 @@ export declare function svgImporter(options?: SvgImporterOptions): Importer;
18
20
  export interface FigmaImporterOptions {
19
21
  /** Factory for a dedicated worker. Defaults to a module worker when available. Pass null to read on this thread. */
20
22
  worker?: OpenFigmaOptions['worker'];
23
+ /** Overrides the reader's node, depth and vector-command limits. */
24
+ limits?: Partial<FigmaImportLimits>;
21
25
  }
22
26
  /**
23
27
  * Imports Figma clipboard HTML as editable layers and .fig files as full documents.
@@ -26,4 +30,5 @@ export interface FigmaImporterOptions {
26
30
  */
27
31
  export declare function figmaImporter(options?: FigmaImporterOptions): Importer;
28
32
  export { payloadFromSyntax } from './syntax.ts';
29
- export { serializeImportDocument } from './serialize.ts';
33
+ export { serializeImportDocument, serializeImportNdjson } from './serialize.ts';
34
+ export { bundleFileName, componentRefsOf, createLazyBundle, type LazyBundle, type LazyBundleComponent, type LazyBundleFile, type LazyBundleIndex, type LazyBundleOptions, type LazyBundlePage } from './lazy.ts';
package/dist/index.js CHANGED
@@ -42,9 +42,11 @@ export function figmaImporter(options = {}) {
42
42
  const { openFigmaFile } = await import('./figma-file.js');
43
43
  return openFigmaFile(await bytesOf(input.file), {
44
44
  signal: env.signal, progress: env.progress, ...(options.worker !== undefined ? { worker: options.worker } : {}),
45
+ ...(options.limits !== undefined ? { limits: options.limits } : {}),
45
46
  });
46
47
  },
47
48
  };
48
49
  }
49
50
  export { payloadFromSyntax } from './syntax.js';
50
- export { serializeImportDocument } from './serialize.js';
51
+ export { serializeImportDocument, serializeImportNdjson } from './serialize.js';
52
+ export { bundleFileName, componentRefsOf, createLazyBundle } from './lazy.js';