pixiboardjs 0.1.0-alpha.5 → 0.1.0-alpha.6

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/dist/browser.js CHANGED
@@ -22,22 +22,31 @@ __export(src_exports, {
22
22
  PixiBoardCoreError: () => PixiBoardCoreError,
23
23
  RESIZE_HANDLES: () => RESIZE_HANDLES,
24
24
  SelectionController: () => SelectionController,
25
+ TEXTURE_REF_ROLES: () => TEXTURE_REF_ROLES,
25
26
  TransactionConflictError: () => TransactionConflictError,
26
27
  ViewportController: () => ViewportController,
27
28
  assertWorldBounds: () => assertWorldBounds,
28
29
  createBoardCore: () => createBoardCore,
30
+ createMediaAssetRefs: () => createMediaAssetRefs,
31
+ createMediaMetadata: () => createMediaMetadata,
29
32
  createPreviewSpec: () => createPreviewSpec,
33
+ fitMediaRect: () => fitMediaRect,
30
34
  isAssetVariant: () => isAssetVariant,
35
+ isContentFit: () => isContentFit,
31
36
  isDocumentPreviewType: () => isDocumentPreviewType,
32
37
  isPreviewNodeType: () => isPreviewNodeType,
38
+ isRenderAssetKind: () => isRenderAssetKind,
33
39
  isResizeHandle: () => isResizeHandle,
34
40
  mergeBounds: () => mergeBounds,
35
41
  nodeGeometry: () => nodeGeometry,
42
+ preferredMediaNodeSize: () => preferredMediaNodeSize,
36
43
  previewStatusLabel: () => previewStatusLabel,
44
+ readIntrinsicSize: () => readIntrinsicSize,
37
45
  resizeHandleAxes: () => resizeHandleAxes,
38
46
  resizeHandleCursor: () => resizeHandleCursor,
39
47
  resolveResize: () => resolveResize,
40
48
  resolveResizeSize: () => resolveResizeSize,
49
+ resolveTextureAssetRef: () => resolveTextureAssetRef,
41
50
  rotatedRectBounds: () => rotatedRectBounds
42
51
  });
43
52
 
@@ -107,6 +116,111 @@ function previewStatusLabel(node, typeLabel) {
107
116
  }
108
117
  }
109
118
 
119
+ // ../core/src/media-assets.ts
120
+ var TEXTURE_REF_ROLES = {
121
+ image: ["preview", "image", "primary", "original", "source"],
122
+ video: ["poster", "preview"],
123
+ audio: ["waveform", "preview"],
124
+ model: ["preview"],
125
+ html: ["preview"],
126
+ markdown: ["preview"],
127
+ "text-file": ["preview"],
128
+ file: ["preview"]
129
+ };
130
+ function isRenderAssetKind(value) {
131
+ return Object.hasOwn(TEXTURE_REF_ROLES, value);
132
+ }
133
+ function resolveTextureAssetRef(node, kind = node.type) {
134
+ if (!isRenderAssetKind(kind)) return void 0;
135
+ for (const role of TEXTURE_REF_ROLES[kind]) {
136
+ const ref = node.assetRefs?.[role];
137
+ if (ref) return ref;
138
+ }
139
+ return Object.entries(node.assetRefs ?? {}).find(([role]) => /^preview-[a-f0-9]{64}$/.test(role))?.[1];
140
+ }
141
+ function createMediaAssetRefs(kind, assetId, available = {}) {
142
+ const refs = {
143
+ primary: { assetId, variant: "original" }
144
+ };
145
+ if (kind === "image" && available.preview) {
146
+ refs.preview = { assetId, variant: "preview" };
147
+ }
148
+ if (kind === "video" && available.poster) {
149
+ refs.poster = { assetId, variant: "preview" };
150
+ }
151
+ if (kind === "audio" && available.waveform) {
152
+ refs.waveform = { assetId, variant: "waveform" };
153
+ }
154
+ if (["model", "html", "markdown", "text-file", "file"].includes(kind) && available.preview) {
155
+ refs.preview = { assetId, variant: "preview" };
156
+ }
157
+ return refs;
158
+ }
159
+ function readIntrinsicSize(value, fallback) {
160
+ const source = record2(value);
161
+ const width = positiveFinite(
162
+ source.intrinsicWidth ?? source.naturalWidth ?? source.mediaWidth ?? source.textureWidth ?? fallback?.width
163
+ );
164
+ const height = positiveFinite(
165
+ source.intrinsicHeight ?? source.naturalHeight ?? source.mediaHeight ?? source.textureHeight ?? fallback?.height
166
+ );
167
+ return width !== void 0 && height !== void 0 ? { width, height } : void 0;
168
+ }
169
+ function fitMediaRect(frame, intrinsic, fit = "contain") {
170
+ const width = positiveFinite(frame.width) ?? 0;
171
+ const height = positiveFinite(frame.height) ?? 0;
172
+ const sourceWidth = positiveFinite(intrinsic?.width);
173
+ const sourceHeight = positiveFinite(intrinsic?.height);
174
+ if (width === 0 || height === 0) return { x: 0, y: 0, width, height };
175
+ if (!sourceWidth || !sourceHeight || fit === "stretch") {
176
+ return { x: 0, y: 0, width, height };
177
+ }
178
+ const scale = fit === "cover" ? Math.max(width / sourceWidth, height / sourceHeight) : Math.min(width / sourceWidth, height / sourceHeight);
179
+ const fittedWidth = sourceWidth * scale;
180
+ const fittedHeight = sourceHeight * scale;
181
+ return {
182
+ x: (width - fittedWidth) / 2,
183
+ y: (height - fittedHeight) / 2,
184
+ width: fittedWidth,
185
+ height: fittedHeight
186
+ };
187
+ }
188
+ function preferredMediaNodeSize(intrinsic, maxWidth = 320, maxHeight = 320) {
189
+ const width = positiveFinite(intrinsic?.width) ?? maxWidth;
190
+ const height = positiveFinite(intrinsic?.height) ?? maxHeight;
191
+ const scale = Math.min(maxWidth / width, maxHeight / height, 1);
192
+ return {
193
+ width: Math.max(1, Math.round(width * scale)),
194
+ height: Math.max(1, Math.round(height * scale))
195
+ };
196
+ }
197
+ function createMediaMetadata(input) {
198
+ const output = { version: 1 };
199
+ for (const key of ["contentHash", "mimeType", "relativePath", "rootId", "baseUrl"]) {
200
+ const value = input[key];
201
+ if (typeof value === "string" && value.length > 0) output[key] = value;
202
+ }
203
+ for (const key of ["width", "height", "duration", "orientation"]) {
204
+ const value = positiveFinite(input[key]);
205
+ if (value !== void 0) output[key] = value;
206
+ }
207
+ return output;
208
+ }
209
+ function isContentFit(value) {
210
+ return value === "contain" || value === "cover" || value === "stretch";
211
+ }
212
+ function record2(value) {
213
+ const candidate = value && typeof value === "object" && !Array.isArray(value) ? value : {};
214
+ return recordProps(candidate);
215
+ }
216
+ function recordProps(value) {
217
+ return value.props && typeof value.props === "object" && !Array.isArray(value.props) ? value.props : value;
218
+ }
219
+ function positiveFinite(value) {
220
+ const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
221
+ return Number.isFinite(number) && number > 0 ? number : void 0;
222
+ }
223
+
110
224
  // ../core/src/errors.ts
111
225
  var PixiBoardCoreError = class extends Error {
112
226
  constructor(message) {
@@ -295,6 +409,9 @@ function validateNode(input, path = "node") {
295
409
  throw new DocumentValidationError(`${path}.visible must be a boolean`);
296
410
  }
297
411
  if (!("props" in input)) throw new DocumentValidationError(`${path}.props is required`);
412
+ if (input.fit !== void 0 && !isContentFit(input.fit)) {
413
+ throw new DocumentValidationError(`${path}.fit must be contain, cover, or stretch`);
414
+ }
298
415
  if (input.assetRefs !== void 0) validateAssetRefs(input.assetRefs, `${path}.assetRefs`);
299
416
  return { ...cloneValue(input), id, type, typeVersion };
300
417
  }
@@ -340,22 +457,22 @@ function parseInput(input) {
340
457
  function isRecord(value) {
341
458
  return value !== null && typeof value === "object" && !Array.isArray(value);
342
459
  }
343
- function readString(record2, key, path) {
344
- const value = record2[key];
460
+ function readString(record4, key, path) {
461
+ const value = record4[key];
345
462
  if (typeof value !== "string" || !value.trim()) {
346
463
  throw new DocumentValidationError(`${path}.${key} must be a non-empty string`);
347
464
  }
348
465
  return value;
349
466
  }
350
- function readInteger(record2, key, path) {
351
- const value = record2[key];
467
+ function readInteger(record4, key, path) {
468
+ const value = record4[key];
352
469
  if (!Number.isInteger(value)) {
353
470
  throw new DocumentValidationError(`${path}.${key} must be an integer`);
354
471
  }
355
472
  return value;
356
473
  }
357
- function readFiniteNumber(record2, key, path) {
358
- const value = record2[key];
474
+ function readFiniteNumber(record4, key, path) {
475
+ const value = record4[key];
359
476
  if (typeof value !== "number" || !Number.isFinite(value)) {
360
477
  throw new DocumentValidationError(`${path}.${key} must be a finite number`);
361
478
  }
@@ -399,7 +516,92 @@ function assertWorldBounds(bounds, label = "bounds") {
399
516
  }
400
517
 
401
518
  // ../core/src/history.ts
519
+ var MEDIA_BACKGROUND_PROP_KEYS = [
520
+ "previewStatus",
521
+ "previewError",
522
+ "previewSpec",
523
+ "previewKey",
524
+ "pageCount",
525
+ "previewWarnings",
526
+ "previewQuality",
527
+ "fileExtension",
528
+ "previewJobId",
529
+ "intrinsicWidth",
530
+ "intrinsicHeight",
531
+ "duration",
532
+ "mediaContentHash",
533
+ "mediaPreparationStatus",
534
+ "mediaPreparationError",
535
+ "mediaAutoSize",
536
+ "mediaAutoSizeBaseline"
537
+ ];
538
+ var MEDIA_BACKGROUND_ASSET_REF_ROLES = /* @__PURE__ */ new Set([
539
+ "preview",
540
+ "poster",
541
+ "waveform"
542
+ ]);
543
+ var PREVIEW_REQUEST_PROP_KEYS = /* @__PURE__ */ new Set([
544
+ "previewRequestId",
545
+ "previewStatus",
546
+ "previewError",
547
+ "previewSpec",
548
+ "previewKey",
549
+ "pageCount",
550
+ "previewWarnings",
551
+ "previewQuality",
552
+ "previewJobId"
553
+ ]);
554
+ function sourceRefs(node) {
555
+ const refs = /* @__PURE__ */ new Set();
556
+ for (const [role, ref] of Object.entries(node.assetRefs ?? {})) {
557
+ if (!isMediaBackgroundAssetRefRole(role)) {
558
+ refs.add(JSON.stringify([role, ref.assetId, ref.variant ?? null]));
559
+ }
560
+ }
561
+ return refs;
562
+ }
563
+ function isMediaBackgroundAssetRefRole(role) {
564
+ return MEDIA_BACKGROUND_ASSET_REF_ROLES.has(role) || role.startsWith("_documentPreview") || /^preview-[a-f0-9]{64}$/.test(role);
565
+ }
566
+ function createHistoryMediaBackgroundUpdate(before, after) {
567
+ const beforeSources = sourceRefs(before);
568
+ const afterSources = sourceRefs(after);
569
+ if (before.type !== after.type || beforeSources.size !== afterSources.size || [...beforeSources].some((id) => !afterSources.has(id))) {
570
+ return void 0;
571
+ }
572
+ const beforeProps = record3(before.props);
573
+ const afterProps = record3(after.props);
574
+ const props = {};
575
+ for (const key of MEDIA_BACKGROUND_PROP_KEYS) {
576
+ if (!jsonEqual(beforeProps[key], afterProps[key])) props[key] = afterProps[key];
577
+ }
578
+ if (!jsonEqual(beforeProps.previewRequestId, afterProps.previewRequestId)) {
579
+ props.previewRequestId = afterProps.previewRequestId;
580
+ props.previewStatus = afterProps.previewStatus;
581
+ }
582
+ const assetRefs = {};
583
+ const beforeRefs = before.assetRefs ?? {};
584
+ const afterRefs = after.assetRefs ?? {};
585
+ for (const role of /* @__PURE__ */ new Set([...Object.keys(beforeRefs), ...Object.keys(afterRefs)])) {
586
+ if (!isMediaBackgroundAssetRefRole(role)) continue;
587
+ if (!jsonEqual(beforeRefs[role], afterRefs[role])) {
588
+ assetRefs[role] = afterRefs[role];
589
+ }
590
+ }
591
+ if (Object.keys(assetRefs).length === 0 && Object.keys(props).length === 0) {
592
+ return void 0;
593
+ }
594
+ return {
595
+ nodeId: after.id,
596
+ sourceType: before.type,
597
+ sourceRefs: afterSources,
598
+ previewRequestIdBefore: beforeProps.previewRequestId,
599
+ assetRefs,
600
+ props
601
+ };
602
+ }
402
603
  var recordHistory = /* @__PURE__ */ Symbol("recordHistory");
604
+ var rebaseMediaBackground = /* @__PURE__ */ Symbol("rebaseMediaBackground");
403
605
  var HistoryController = class {
404
606
  constructor(host) {
405
607
  this.host = host;
@@ -408,6 +610,10 @@ var HistoryController = class {
408
610
  undoStack = [];
409
611
  redoStack = [];
410
612
  listeners = /* @__PURE__ */ new Set();
613
+ patchGenerations = /* @__PURE__ */ new WeakMap();
614
+ entryGenerations = /* @__PURE__ */ new WeakMap();
615
+ nodeGenerations = /* @__PURE__ */ new Map();
616
+ nextNodeGeneration = 1;
411
617
  canUndo() {
412
618
  return this.undoStack.length > 0;
413
619
  }
@@ -420,6 +626,7 @@ var HistoryController = class {
420
626
  const changeSet = this.host.applyHistoryEntry(entry, "undo");
421
627
  this.undoStack.pop();
422
628
  this.redoStack.push(entry);
629
+ this.restoreGenerations(entry, "before");
423
630
  this.emit();
424
631
  return changeSet;
425
632
  }
@@ -429,24 +636,38 @@ var HistoryController = class {
429
636
  const changeSet = this.host.applyHistoryEntry(entry, "redo");
430
637
  this.redoStack.pop();
431
638
  this.undoStack.push(entry);
639
+ this.restoreGenerations(entry, "after");
432
640
  this.emit();
433
641
  return changeSet;
434
642
  }
435
643
  clear() {
436
- if (!this.canUndo() && !this.canRedo()) return;
644
+ const hadHistory = this.canUndo() || this.canRedo();
437
645
  this.undoStack = [];
438
646
  this.redoStack = [];
439
- this.emit();
647
+ this.nodeGenerations = /* @__PURE__ */ new Map();
648
+ this.nextNodeGeneration = 1;
649
+ if (hadHistory) this.emit();
440
650
  }
441
651
  onChange(listener) {
442
652
  this.listeners.add(listener);
443
653
  return () => this.listeners.delete(listener);
444
654
  }
445
655
  [recordHistory](entry) {
656
+ this.captureEntryGenerations(entry);
446
657
  const previous = this.undoStack.at(-1);
447
658
  if (entry.coalesceKey !== void 0 && previous?.coalesceKey === entry.coalesceKey) {
448
659
  previous.forward = compactReplaces([...previous.forward, ...entry.forward]);
449
660
  previous.inverse = compactReplaces([...entry.inverse, ...previous.inverse]);
661
+ const generationState = this.entryGenerations.get(previous);
662
+ const nextGenerationState = this.entryGenerations.get(entry);
663
+ if (generationState && nextGenerationState) {
664
+ for (const [id, change] of nextGenerationState) {
665
+ const existing = generationState.get(id);
666
+ const before = existing ? existing.before : change.before;
667
+ if (before === change.after) generationState.delete(id);
668
+ else generationState.set(id, { before, after: change.after });
669
+ }
670
+ }
450
671
  this.redoStack = [];
451
672
  this.emit();
452
673
  return;
@@ -455,6 +676,80 @@ var HistoryController = class {
455
676
  this.redoStack = [];
456
677
  this.emit();
457
678
  }
679
+ [rebaseMediaBackground](updates) {
680
+ if (updates.length === 0) return;
681
+ const updatesByNode = new Map(updates.map((update) => [update.nodeId, update]));
682
+ const rebase = (stack) => {
683
+ for (const entry of stack) {
684
+ const forward = this.rebasePatches(entry.forward, updatesByNode);
685
+ const inverse = this.rebasePatches(entry.inverse, updatesByNode);
686
+ if (forward !== entry.forward) entry.forward = forward;
687
+ if (inverse !== entry.inverse) entry.inverse = inverse;
688
+ }
689
+ };
690
+ rebase(this.undoStack);
691
+ rebase(this.redoStack);
692
+ }
693
+ rebasePatches(patches, updatesByNode) {
694
+ let changed = false;
695
+ const rebased = patches.map((patch) => {
696
+ if (!hasNodeSnapshot(patch)) return patch;
697
+ const update = updatesByNode.get(patch.node.id);
698
+ if (!update) return patch;
699
+ const generation = this.nodeGenerations.get(patch.node.id);
700
+ if (generation === void 0) return patch;
701
+ if (this.patchGenerations.get(patch) !== generation) {
702
+ return patch;
703
+ }
704
+ if (patch.node.type !== update.sourceType || !sameSourceRefs(patch.node, update)) {
705
+ return patch;
706
+ }
707
+ const node = rebaseNodeMediaFields(patch.node, update);
708
+ if (node === patch.node) return patch;
709
+ changed = true;
710
+ const rebasedPatch = { ...patch, node };
711
+ this.patchGenerations.set(rebasedPatch, generation);
712
+ return rebasedPatch;
713
+ });
714
+ return changed ? rebased : patches;
715
+ }
716
+ captureEntryGenerations(entry) {
717
+ const before = /* @__PURE__ */ new Map();
718
+ entry.forward.forEach((patch, forwardIndex) => {
719
+ const inverse = entry.inverse[entry.forward.length - 1 - forwardIndex];
720
+ if (patch.op === "node:insert") {
721
+ if (!before.has(patch.node.id)) before.set(patch.node.id, this.nodeGenerations.get(patch.node.id));
722
+ const generation = this.nextNodeGeneration++;
723
+ this.nodeGenerations.set(patch.node.id, generation);
724
+ this.patchGenerations.set(patch, generation);
725
+ if (inverse && hasNodeSnapshot(inverse)) this.patchGenerations.set(inverse, generation);
726
+ } else if (patch.op === "node:replace") {
727
+ const generation = this.nodeGenerations.get(patch.node.id) ?? 0;
728
+ if (!before.has(patch.node.id)) before.set(patch.node.id, generation);
729
+ this.nodeGenerations.set(patch.node.id, generation);
730
+ this.patchGenerations.set(patch, generation);
731
+ if (inverse?.op === "node:replace") this.patchGenerations.set(inverse, generation);
732
+ } else if (patch.op === "node:remove") {
733
+ const generation = this.nodeGenerations.get(patch.nodeId) ?? 0;
734
+ if (!before.has(patch.nodeId)) before.set(patch.nodeId, generation);
735
+ this.nodeGenerations.delete(patch.nodeId);
736
+ if (inverse?.op === "node:insert") this.patchGenerations.set(inverse, generation);
737
+ }
738
+ });
739
+ const changes = /* @__PURE__ */ new Map();
740
+ for (const [id, previous] of before) {
741
+ const after = this.nodeGenerations.get(id);
742
+ if (previous !== after) changes.set(id, { before: previous, after });
743
+ }
744
+ this.entryGenerations.set(entry, changes);
745
+ }
746
+ restoreGenerations(entry, side) {
747
+ for (const [id, change] of this.entryGenerations.get(entry) ?? []) {
748
+ const generation = change[side];
749
+ if (generation === void 0) this.nodeGenerations.delete(id);
750
+ else this.nodeGenerations.set(id, generation);
751
+ }
752
+ }
458
753
  emit() {
459
754
  const event = { canUndo: this.canUndo(), canRedo: this.canRedo() };
460
755
  for (const listener of this.listeners) {
@@ -465,6 +760,55 @@ var HistoryController = class {
465
760
  }
466
761
  }
467
762
  };
763
+ function sameSourceRefs(node, update) {
764
+ const refs = sourceRefs(node);
765
+ return refs.size === update.sourceRefs.size && [...update.sourceRefs].every((ref) => refs.has(ref));
766
+ }
767
+ function hasNodeSnapshot(patch) {
768
+ return patch.op === "node:insert" || patch.op === "node:replace";
769
+ }
770
+ function rebaseNodeMediaFields(node, update) {
771
+ let next = node;
772
+ const sameRequest = jsonEqual(record3(node.props).previewRequestId, update.previewRequestIdBefore);
773
+ const roles = Object.keys(update.assetRefs);
774
+ if (sameRequest && roles.length > 0) {
775
+ const refs = { ...next.assetRefs ?? {} };
776
+ let refsChanged = false;
777
+ for (const role of roles) {
778
+ if (jsonEqual(refs[role], update.assetRefs[role])) continue;
779
+ refsChanged = true;
780
+ if (update.assetRefs[role] === void 0) delete refs[role];
781
+ else refs[role] = cloneValue(update.assetRefs[role]);
782
+ }
783
+ if (refsChanged) {
784
+ next = Object.keys(refs).length === 0 ? withoutAssetRefs(next) : { ...next, assetRefs: refs };
785
+ }
786
+ }
787
+ const propKeys = Object.keys(update.props);
788
+ if (propKeys.length > 0) {
789
+ const props = {};
790
+ for (const [key, value] of Object.entries(record3(next.props))) {
791
+ if (value !== void 0) props[key] = value;
792
+ }
793
+ let propsChanged = false;
794
+ for (const key of propKeys) {
795
+ if (!sameRequest && PREVIEW_REQUEST_PROP_KEYS.has(key)) continue;
796
+ if (jsonEqual(props[key], update.props[key])) continue;
797
+ propsChanged = true;
798
+ if (update.props[key] === void 0) delete props[key];
799
+ else props[key] = cloneValue(update.props[key]);
800
+ }
801
+ if (propsChanged) next = { ...next, props };
802
+ }
803
+ return next;
804
+ }
805
+ function withoutAssetRefs(node) {
806
+ const { assetRefs: _assetRefs, ...rest } = node;
807
+ return rest;
808
+ }
809
+ function record3(value) {
810
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
811
+ }
468
812
  function compactReplaces(patches) {
469
813
  if (patches.some((patch) => patch.op !== "node:replace" && patch.op !== "asset:replace")) {
470
814
  return patches;
@@ -480,7 +824,8 @@ function createHistoryController(host) {
480
824
  const controller = new HistoryController(host);
481
825
  return {
482
826
  controller,
483
- record: (entry) => controller[recordHistory](entry)
827
+ record: (entry) => controller[recordHistory](entry),
828
+ rebaseMediaBackground: (updates) => controller[rebaseMediaBackground](updates)
484
829
  };
485
830
  }
486
831
 
@@ -1257,6 +1602,7 @@ var BoardCore = class {
1257
1602
  rejectedAsyncTransactionCallbacks = 0;
1258
1603
  viewportState;
1259
1604
  recordHistory;
1605
+ rebaseMediaBackground;
1260
1606
  constructor(options = {}) {
1261
1607
  this.nodeTypes = options.nodeTypes ?? new NodeTypeRegistry();
1262
1608
  this.schemaVersion = options.schemaVersion ?? 1;
@@ -1292,6 +1638,7 @@ var BoardCore = class {
1292
1638
  });
1293
1639
  this.history = history.controller;
1294
1640
  this.recordHistory = history.record;
1641
+ this.rebaseMediaBackground = history.rebaseMediaBackground;
1295
1642
  this.nodes = new BoardNodesController(this);
1296
1643
  this.assets = new BoardAssetsController(this);
1297
1644
  this.document = new BoardDocumentController(this);
@@ -1335,7 +1682,11 @@ var BoardCore = class {
1335
1682
  );
1336
1683
  }
1337
1684
  this.activeTransaction = void 0;
1338
- this.commitTransaction(transaction, true);
1685
+ this.commitTransaction(
1686
+ transaction,
1687
+ options.recordHistory !== false,
1688
+ options.recordHistory === false
1689
+ );
1339
1690
  return result;
1340
1691
  } catch (error) {
1341
1692
  this.activeTransaction = void 0;
@@ -1355,7 +1706,7 @@ var BoardCore = class {
1355
1706
  inverse: direction === "undo" ? entry.forward : entry.inverse
1356
1707
  };
1357
1708
  applyDataPatches(transaction.draft, transaction.forward);
1358
- return this.commitTransaction(transaction, false);
1709
+ return this.commitTransaction(transaction, false, false);
1359
1710
  }
1360
1711
  getBounds(nodeId) {
1361
1712
  const node = this.currentStore().requireNode(nodeId);
@@ -1428,7 +1779,7 @@ var BoardCore = class {
1428
1779
  transaction.forward.push(forward);
1429
1780
  transaction.inverse.unshift(inverse);
1430
1781
  }
1431
- commitTransaction(transaction, recordHistory2) {
1782
+ commitTransaction(transaction, recordHistory2, rebaseBackgroundHistory = false) {
1432
1783
  if (transaction.forward.length === 0 && recordHistory2) return void 0;
1433
1784
  const before = this.store;
1434
1785
  const after = transaction.draft;
@@ -1458,11 +1809,28 @@ var BoardCore = class {
1458
1809
  forward: transaction.forward,
1459
1810
  inverse: transaction.inverse
1460
1811
  });
1812
+ } else if (rebaseBackgroundHistory) {
1813
+ this.rebaseHistoryAfterBackgroundWrite(before, after, transaction.forward);
1461
1814
  }
1462
1815
  changeSet.metadataChanged = transaction.forward.some((patch) => patch.op === "metadata:replace") && !jsonEqual(before.getMetadata(), after.getMetadata());
1463
1816
  this.emitChange(changeSet);
1464
1817
  return changeSet;
1465
1818
  }
1819
+ rebaseHistoryAfterBackgroundWrite(before, after, patches) {
1820
+ const updates = [];
1821
+ const seen = /* @__PURE__ */ new Set();
1822
+ for (const patch of patches) {
1823
+ if (patch.op !== "node:replace") continue;
1824
+ if (seen.has(patch.node.id)) continue;
1825
+ const afterNode = after.getNodeReference(patch.node.id);
1826
+ const beforeNode = before.getNodeReference(patch.node.id);
1827
+ if (!afterNode || !beforeNode) continue;
1828
+ seen.add(patch.node.id);
1829
+ const update = createHistoryMediaBackgroundUpdate(beforeNode, afterNode);
1830
+ if (update) updates.push(update);
1831
+ }
1832
+ this.rebaseMediaBackground(updates);
1833
+ }
1466
1834
  emitChange(changeSet) {
1467
1835
  const changedNodeIds = /* @__PURE__ */ new Set([
1468
1836
  ...changeSet.addedNodeIds,
@@ -1526,7 +1894,8 @@ var BoardNodesController = class {
1526
1894
  ...input.name === void 0 ? {} : { name: input.name },
1527
1895
  ...input.locked === void 0 ? {} : { locked: input.locked },
1528
1896
  ...input.visible === void 0 ? {} : { visible: input.visible },
1529
- ...input.assetRefs === void 0 ? {} : { assetRefs: cloneValue(input.assetRefs) }
1897
+ ...input.assetRefs === void 0 ? {} : { assetRefs: cloneValue(input.assetRefs) },
1898
+ ...input.fit === void 0 ? {} : { fit: input.fit }
1530
1899
  });
1531
1900
  const validated = this.core.nodeTypes.validateNode(node);
1532
1901
  const index = transaction.draft.nodeCount();
@@ -2008,7 +2377,10 @@ function createBoardCapabilities(core, services = {}) {
2008
2377
  changeSet = event.changeSet;
2009
2378
  });
2010
2379
  try {
2011
- const result = core.transaction(label, operation, { origin: options.origin ?? "api" });
2380
+ const result = core.transaction(label, operation, {
2381
+ origin: options.origin ?? "api",
2382
+ recordHistory: options.recordHistory
2383
+ });
2012
2384
  return { result, changed: changeSet !== void 0, changeSet };
2013
2385
  } catch (error) {
2014
2386
  throw mapCoreError(error);
@@ -2034,7 +2406,7 @@ function createBoardCapabilities(core, services = {}) {
2034
2406
  requestId: value.requestId
2035
2407
  });
2036
2408
  const capabilities = {
2037
- availability: { preview: Boolean(services.preview), capture: Boolean(services.capture) },
2409
+ availability: { preview: Boolean(services.preview), capture: Boolean(services.capture), import: Boolean(services.import) },
2038
2410
  document: {
2039
2411
  snapshot: async (options = {}) => {
2040
2412
  aborted(options.signal);
@@ -2072,14 +2444,16 @@ function createBoardCapabilities(core, services = {}) {
2072
2444
  create: async (input, options = {}) => {
2073
2445
  try {
2074
2446
  if (!input.nodes.length) throw new CapabilityError("INVALID_INPUT", "nodes must not be empty");
2447
+ const prepared = input.nodes.some((item) => item.source) ? await Promise.all(input.nodes.map((item) => prepareWrite(core, services, item, options))) : input.nodes.map(prepareDirectCreate);
2448
+ aborted(options.signal);
2075
2449
  const tx = transact(options.label ?? "Create nodes", options, () => {
2076
2450
  const nodes = [];
2077
- for (const raw of input.nodes) {
2451
+ for (const item of prepared) {
2078
2452
  aborted(options.signal);
2079
- const { asset, ...nodeInput } = raw;
2080
- const refs = asset ? { ...nodeInput.assetRefs ?? {}, primary: { assetId: asset.id, variant: "original" } } : nodeInput.assetRefs;
2081
- if (asset) core.assets.upsert(asset);
2082
- nodes.push(core.nodes.create({ rotation: 0, zIndex: 0, ...nodeInput, x: nodeInput.x ?? 0, y: nodeInput.y ?? 0, width: nodeInput.width ?? 100, height: nodeInput.height ?? 100, ...refs ? { assetRefs: refs } : {} }));
2453
+ if (item.sourceToken !== void 0) assertLatestSourceRequest(core, item.sourceNodeId, item.sourceToken);
2454
+ if (item.asset) core.assets.upsert(item.asset);
2455
+ const { asset: _asset, sourceToken: _token, sourceNodeId: _nodeId, ...nodeInput } = item;
2456
+ nodes.push(core.nodes.create(nodeInput));
2083
2457
  }
2084
2458
  return nodes;
2085
2459
  });
@@ -2089,20 +2463,61 @@ function createBoardCapabilities(core, services = {}) {
2089
2463
  }
2090
2464
  },
2091
2465
  update: async (input, options = {}) => {
2466
+ let stopWatching;
2092
2467
  try {
2093
2468
  if (!input.nodes.length) throw new CapabilityError("INVALID_INPUT", "nodes must not be empty");
2094
- const tx = transact(options.label ?? "Update nodes", options, () => {
2095
- const nodes = [];
2096
- for (const item of input.nodes) {
2097
- aborted(options.signal);
2098
- if (item.asset) core.assets.upsert(item.asset);
2099
- nodes.push(core.nodes.update(item.id, item.patch));
2100
- }
2101
- return nodes;
2102
- });
2103
- return writeResult({ ...tx, nodes: tx.result, requestId: options.requestId });
2469
+ aborted(options.signal);
2470
+ const sourceIds = new Set(input.nodes.filter((item) => item.source).map((item) => item.id));
2471
+ const sourceIdentity = /* @__PURE__ */ new Map();
2472
+ const invalidated = /* @__PURE__ */ new Set();
2473
+ for (const id of sourceIds) sourceIdentity.set(id, readSourceIdentity(core, id));
2474
+ if (sourceIds.size) {
2475
+ stopWatching = core.on("change", ({ changeSet }) => {
2476
+ for (const id of sourceIds) {
2477
+ if (changeSet.origin === "load" || changeSet.removedNodeIds.includes(id) || changeSet.addedNodeIds.includes(id)) {
2478
+ invalidated.add(id);
2479
+ } else if ((changeSet.updatedNodeIds.includes(id) || changeSet.assetChangedNodeIds.includes(id)) && !jsonEqual2(sourceIdentity.get(id), readSourceIdentity(core, id))) {
2480
+ invalidated.add(id);
2481
+ }
2482
+ }
2483
+ });
2484
+ }
2485
+ const commit = (prepared2) => {
2486
+ const tx = transact(options.label ?? "Update nodes", options, () => {
2487
+ const nodes = [];
2488
+ for (const item of prepared2) {
2489
+ aborted(options.signal);
2490
+ if (item.kind === "source") {
2491
+ assertLatestSourceRequest(core, item.id, item.token);
2492
+ const latest = core.nodes.get(item.id);
2493
+ if (!latest || invalidated.has(item.id) || !jsonEqual2(sourceIdentity.get(item.id), readSourceIdentity(core, item.id))) {
2494
+ throw new CapabilityError("TRANSACTION_CONFLICT", "Node or source changed while source import was pending", { nodeId: item.id });
2495
+ }
2496
+ core.assets.upsert(item.imported.asset);
2497
+ nodes.push(core.nodes.update(item.id, importedUpdatePatch(item.raw, item.initial, latest, item.imported)));
2498
+ } else {
2499
+ const patch = { ...item.patch };
2500
+ if (item.asset) {
2501
+ const latest = core.nodes.get(item.id);
2502
+ if (!latest) throw new CapabilityError("NODE_NOT_FOUND", `Node not found: ${item.id}`, { nodeId: item.id });
2503
+ patch.assetRefs ??= { ...latest.assetRefs ?? {}, primary: { assetId: item.asset.id, variant: "original" } };
2504
+ core.assets.upsert(item.asset);
2505
+ }
2506
+ nodes.push(core.nodes.update(item.id, patch));
2507
+ }
2508
+ }
2509
+ return nodes;
2510
+ });
2511
+ return writeResult({ ...tx, nodes: tx.result, requestId: options.requestId });
2512
+ };
2513
+ if (!sourceIds.size) return commit(input.nodes.map(prepareDirectUpdate));
2514
+ const prepared = await Promise.all(input.nodes.map((item) => prepareWrite(core, services, item, options)));
2515
+ aborted(options.signal);
2516
+ return commit(prepared);
2104
2517
  } catch (error) {
2105
2518
  throw mapCoreError(error);
2519
+ } finally {
2520
+ stopWatching?.();
2106
2521
  }
2107
2522
  },
2108
2523
  delete: async (input, options = {}) => {
@@ -2237,6 +2652,227 @@ function createBoardCapabilities(core, services = {}) {
2237
2652
  };
2238
2653
  return capabilities;
2239
2654
  }
2655
+ function readSourceIdentity(core, nodeId) {
2656
+ const node = core.nodes.get(nodeId);
2657
+ if (!node) return void 0;
2658
+ const refs = Object.fromEntries(Object.entries(node.assetRefs ?? {}).filter(([role]) => !isPreviewRefRole(role)).sort(([left], [right]) => left.localeCompare(right)));
2659
+ const ids = [...new Set(Object.values(refs).map((ref) => ref.assetId))].sort();
2660
+ return { type: node.type, typeVersion: node.typeVersion, assetRefs: refs, assets: ids.map((id) => sourceAssetIdentity(core.assets.get(id))) };
2661
+ }
2662
+ function isPreviewRefRole(role) {
2663
+ return role === "preview" || role === "poster" || role === "waveform" || role.startsWith("_documentPreview") || /^preview-[a-f0-9]{64}$/.test(role);
2664
+ }
2665
+ function sourceAssetIdentity(asset) {
2666
+ if (!asset) return void 0;
2667
+ const identity = { ...asset };
2668
+ for (const key of Object.keys(identity)) {
2669
+ if (isPreviewAssetField(key)) delete identity[key];
2670
+ }
2671
+ for (const key of ["metadata", "variants", "binaries"]) {
2672
+ const value = jsonObject(identity[key]);
2673
+ if (!value) continue;
2674
+ const filtered = { ...value };
2675
+ for (const entry of Object.keys(filtered)) {
2676
+ if (isPreviewAssetField(entry)) delete filtered[entry];
2677
+ }
2678
+ if (key === "metadata") {
2679
+ for (const nestedKey of ["variants", "binaries"]) {
2680
+ const nested = jsonObject(filtered[nestedKey]);
2681
+ if (!nested) continue;
2682
+ const remaining = { ...nested };
2683
+ for (const entry of Object.keys(remaining)) {
2684
+ if (isPreviewAssetField(entry)) delete remaining[entry];
2685
+ }
2686
+ if (Object.keys(remaining).length) filtered[nestedKey] = remaining;
2687
+ else delete filtered[nestedKey];
2688
+ }
2689
+ }
2690
+ if (Object.keys(filtered).length) identity[key] = filtered;
2691
+ else delete identity[key];
2692
+ }
2693
+ return identity;
2694
+ }
2695
+ function isPreviewAssetField(key) {
2696
+ return /^(?:preview|poster|waveform)(?:$|[A-Z_-])/.test(key) || key.startsWith("_documentPreview");
2697
+ }
2698
+ var sourceRequestStates = /* @__PURE__ */ new WeakMap();
2699
+ function sourceRequests(core) {
2700
+ let state = sourceRequestStates.get(core);
2701
+ if (!state) {
2702
+ state = { nextToken: 0, latestByNode: /* @__PURE__ */ new Map() };
2703
+ sourceRequestStates.set(core, state);
2704
+ }
2705
+ return state;
2706
+ }
2707
+ function beginSourceRequest(core, nodeId) {
2708
+ const state = sourceRequests(core);
2709
+ const token = ++state.nextToken;
2710
+ state.latestByNode.set(nodeId, token);
2711
+ return token;
2712
+ }
2713
+ function assertLatestSourceRequest(core, nodeId, token) {
2714
+ const state = sourceRequests(core);
2715
+ if (state.latestByNode.get(nodeId) !== token) {
2716
+ throw new CapabilityError("TRANSACTION_CONFLICT", "Source import was superseded by a newer request", { nodeId });
2717
+ }
2718
+ }
2719
+ async function prepareWrite(core, services, raw, options) {
2720
+ const nodeId = "id" in raw ? raw.id : void 0;
2721
+ const current = nodeId ? core.nodes.get(nodeId) : void 0;
2722
+ const nodeType = "type" in raw ? raw.type : current?.type;
2723
+ if (!nodeType && raw.source) throw new CapabilityError("INVALID_INPUT", "source update requires an existing node type");
2724
+ if (raw.source) {
2725
+ if (!services.import) throw new CapabilityUnavailableError("import");
2726
+ if (raw.asset) throw new CapabilityError("INVALID_INPUT", "source and asset are mutually exclusive");
2727
+ aborted(options.signal);
2728
+ const request = {
2729
+ source: raw.source,
2730
+ nodeType,
2731
+ ..."name" in raw && raw.name ? { name: raw.name } : {},
2732
+ ...raw.source.mimeType ? { mimeType: raw.source.mimeType } : {}
2733
+ };
2734
+ const sourceId = "id" in raw ? raw.id : void 0;
2735
+ const token = sourceId === void 0 ? void 0 : beginSourceRequest(core, sourceId);
2736
+ const imported = await services.import(request, options);
2737
+ aborted(options.signal);
2738
+ if ("type" in raw) {
2739
+ const prepared = importedCreateInput(raw, imported);
2740
+ return token === void 0 ? prepared : { ...prepared, sourceToken: token, sourceNodeId: sourceId };
2741
+ }
2742
+ if (!current || token === void 0) throw new CapabilityError("INVALID_INPUT", "source update requires an existing node type");
2743
+ return { kind: "source", id: raw.id, initial: current, raw, imported, token };
2744
+ }
2745
+ if ("type" in raw) {
2746
+ return prepareDirectCreate(raw);
2747
+ }
2748
+ return prepareDirectUpdate(raw);
2749
+ }
2750
+ function prepareDirectCreate(raw) {
2751
+ const asset = raw.asset;
2752
+ return {
2753
+ ...raw,
2754
+ x: raw.x ?? 0,
2755
+ y: raw.y ?? 0,
2756
+ width: raw.width ?? 100,
2757
+ height: raw.height ?? 100,
2758
+ ...asset ? {
2759
+ asset,
2760
+ assetRefs: raw.assetRefs ?? createMediaAssetRefs(raw.type, asset.id),
2761
+ fit: raw.fit ?? "contain"
2762
+ } : {}
2763
+ };
2764
+ }
2765
+ function prepareDirectUpdate(raw) {
2766
+ return { kind: "update", id: raw.id, patch: raw.patch, ...raw.asset ? { asset: raw.asset } : {} };
2767
+ }
2768
+ function importedMetadata(imported) {
2769
+ return {
2770
+ ...imported.props,
2771
+ ...imported.width ? { intrinsicWidth: imported.width } : {},
2772
+ ...imported.height ? { intrinsicHeight: imported.height } : {},
2773
+ ...imported.duration ? { duration: imported.duration } : {},
2774
+ ...imported.previewStatus ? { previewStatus: imported.previewStatus } : {}
2775
+ };
2776
+ }
2777
+ function importedCreateInput(raw, imported) {
2778
+ const nodeType = "type" in raw ? raw.type : void 0;
2779
+ if (!nodeType) throw new CapabilityError("INVALID_INPUT", "Imported source has no target node type");
2780
+ const assetRefs = imported.assetRefs ?? createMediaAssetRefs(nodeType, imported.asset.id);
2781
+ const size = preferredMediaNodeSize(
2782
+ imported.width && imported.height ? { width: imported.width, height: imported.height } : void 0
2783
+ );
2784
+ return {
2785
+ ...raw,
2786
+ asset: imported.asset,
2787
+ assetRefs,
2788
+ fit: raw.fit ?? imported.fit ?? "contain",
2789
+ x: raw.x ?? 0,
2790
+ y: raw.y ?? 0,
2791
+ width: raw.width ?? size.width,
2792
+ height: raw.height ?? size.height,
2793
+ props: { ...importedMetadata(imported), ...raw.props && typeof raw.props === "object" && !Array.isArray(raw.props) ? raw.props : {} }
2794
+ };
2795
+ }
2796
+ var SOURCE_OWNED_PROP_KEYS = /* @__PURE__ */ new Set([
2797
+ "previewRequestId",
2798
+ "previewStatus",
2799
+ "previewError",
2800
+ "previewSpec",
2801
+ "previewKey",
2802
+ "pageCount",
2803
+ "previewWarnings",
2804
+ "previewQuality",
2805
+ "fileExtension",
2806
+ "previewJobId",
2807
+ "intrinsicWidth",
2808
+ "intrinsicHeight",
2809
+ "duration",
2810
+ "mediaContentHash",
2811
+ "mediaPreparationStatus",
2812
+ "mediaPreparationError",
2813
+ "mediaAutoSize",
2814
+ "mediaAutoSizeBaseline"
2815
+ ]);
2816
+ function importedUpdatePatch(raw, initial, latest, imported) {
2817
+ const nodeType = latest.type;
2818
+ const assetRefs = imported.assetRefs ?? createMediaAssetRefs(nodeType, imported.asset.id);
2819
+ const initialProps = jsonObject(initial.props);
2820
+ const latestProps = jsonObject(latest.props);
2821
+ const requestedProps = jsonObject(raw.patch.props);
2822
+ const patch = { ...raw.patch };
2823
+ const importedProps = importedMetadata(imported);
2824
+ const userChangedProps = latestProps ? changedKeys(initialProps, latestProps).filter((key) => !SOURCE_OWNED_PROP_KEYS.has(key)) : [];
2825
+ const sourceOwnedKeys = [...SOURCE_OWNED_PROP_KEYS];
2826
+ for (const key of Object.keys(patch)) {
2827
+ if (key === "props" || key === "assetRefs" || key === "fit") continue;
2828
+ if (nodeFieldChanged(initial, latest, key)) delete patch[key];
2829
+ }
2830
+ if (latestProps) {
2831
+ const props = {
2832
+ ...withoutKeys(latestProps, sourceOwnedKeys),
2833
+ ...withoutKeys(importedProps, userChangedProps),
2834
+ ...withoutKeys(requestedProps ?? {}, sourceOwnedKeys)
2835
+ };
2836
+ for (const key of userChangedProps) {
2837
+ if (Object.hasOwn(latestProps, key)) props[key] = latestProps[key];
2838
+ else delete props[key];
2839
+ }
2840
+ patch.props = props;
2841
+ } else if (nodeFieldChanged(initial, latest, "props")) {
2842
+ delete patch.props;
2843
+ } else {
2844
+ patch.props = { ...importedProps, ...withoutKeys(requestedProps ?? {}, sourceOwnedKeys) };
2845
+ }
2846
+ if (nodeFieldChanged(initial, latest, "fit")) delete patch.fit;
2847
+ else patch.fit = raw.patch.fit ?? imported.fit ?? "contain";
2848
+ patch.assetRefs = assetRefs;
2849
+ return patch;
2850
+ }
2851
+ function withoutKeys(value, keys) {
2852
+ const result = { ...value };
2853
+ for (const key of keys) delete result[key];
2854
+ return result;
2855
+ }
2856
+ function jsonObject(value) {
2857
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2858
+ }
2859
+ function changedKeys(before, after) {
2860
+ const keys = /* @__PURE__ */ new Set([...Object.keys(before ?? {}), ...Object.keys(after)]);
2861
+ return [...keys].filter((key) => {
2862
+ const hadBefore = before !== void 0 && Object.hasOwn(before, key);
2863
+ const hasAfter = Object.hasOwn(after, key);
2864
+ return hadBefore !== hasAfter || !jsonEqual2(before?.[key], after[key]);
2865
+ });
2866
+ }
2867
+ function nodeFieldChanged(before, after, key) {
2868
+ const previous = before;
2869
+ const current = after;
2870
+ if (Object.hasOwn(previous, key) !== Object.hasOwn(current, key)) return true;
2871
+ return !jsonEqual2(previous[key], current[key]);
2872
+ }
2873
+ function jsonEqual2(left, right) {
2874
+ return JSON.stringify(left) === JSON.stringify(right);
2875
+ }
2240
2876
 
2241
2877
  // ../renderer-pixi/src/registry.ts
2242
2878
  var NodeRendererRegistry = class {
@@ -2606,19 +3242,14 @@ function normalizeConnectionStyle(value) {
2606
3242
  }
2607
3243
 
2608
3244
  // ../renderer-pixi/src/builtins.ts
3245
+ var TEXTURE_RETRY_BASE_MS = 1e3;
3246
+ var TEXTURE_RETRY_MAX_MS = 3e4;
2609
3247
  var base = (create, update) => ({ create, update, destroy(view) {
2610
3248
  view.displayObject.destroy?.({ children: true });
2611
3249
  } });
2612
3250
  function registerBuiltinRenderers(registry) {
2613
3251
  if (!registry.has("rect")) registry.register("rect", base((node, ctx) => ({ displayObject: ctx.display.createRect?.(node.width, node.height, node.props?.fill ?? 8162552) ?? ctx.display.createContainer(), state: {} }), (view, node) => applyTransform(view, node)));
2614
- registerTextureNode(registry, "image", ["preview", "image", "primary", "source"]);
2615
- registerTextureNode(registry, "video", ["preview", "poster", "video", "primary", "source"]);
2616
- registerTextureNode(registry, "audio", ["waveform", "preview", "audio", "primary", "source"]);
2617
- registerTextureNode(registry, "model", ["preview", "model", "primary", "source"]);
2618
- registerTextureNode(registry, "html", ["preview", "html", "primary", "source"]);
2619
- registerTextureNode(registry, "markdown", ["preview", "markdown", "primary", "source"]);
2620
- registerTextureNode(registry, "text-file", ["preview", "text-file", "primary", "source"]);
2621
- registerTextureNode(registry, "file", ["preview", "file", "primary", "source"]);
3252
+ for (const type of ["image", "video", "audio", "model", "html", "markdown", "text-file", "file"]) registerTextureNode(registry, type);
2622
3253
  if (!registry.has("text")) registry.register("text", {
2623
3254
  create(node, ctx) {
2624
3255
  const displayObject = ctx.display.createContainer();
@@ -2641,20 +3272,85 @@ function registerBuiltinRenderers(registry) {
2641
3272
  if (!registry.has("unknown-node")) registry.register("unknown-node", base((node, ctx) => ({ displayObject: ctx.display.createText?.(`${node.type}
2642
3273
  ${node.id}`, { fill: 10265519 }) ?? ctx.display.createContainer(), state: {} }), (view, node) => applyTransform(view, node)));
2643
3274
  }
2644
- function registerTextureNode(registry, type, refNames) {
3275
+ function registerTextureNode(registry, type) {
2645
3276
  if (registry.has(type)) return;
2646
3277
  registry.register(type, {
2647
3278
  async create(node, ctx) {
2648
- const ref = refNames.map((name) => node.assetRefs?.[name]).find(Boolean);
2649
- const lease = ref ? await ctx.assets.acquireTexture(ref, { kind: type }) : void 0;
3279
+ const ref = resolveTextureAssetRef(node, type);
3280
+ let retryAt;
3281
+ const lease = ref ? await ctx.assets.acquireTexture(ref, { kind: type }).catch((error) => {
3282
+ if (ctx.signal.aborted) throw error;
3283
+ retryAt = 0;
3284
+ return void 0;
3285
+ }) : void 0;
2650
3286
  if (ctx.signal.aborted) throw new DOMException("Aborted", "AbortError");
2651
- const displayObject = await ctx.display.createImage?.(ref, node) ?? ctx.display.createContainer();
3287
+ const displayObject = ctx.display.createContainer();
3288
+ const surface = ctx.display.createRect?.(node.width, node.height, 0);
3289
+ if (surface) {
3290
+ surface.alpha = 0;
3291
+ displayObject.addChild?.(surface);
3292
+ }
3293
+ const content = ctx.display.createContainer();
3294
+ const image = await ctx.display.createImage?.(ref, node) ?? ctx.display.createContainer();
3295
+ if (lease?.texture !== void 0) image.texture = lease.texture;
2652
3296
  if (lease?.texture !== void 0) displayObject.texture = lease.texture;
3297
+ content.addChild?.(image);
3298
+ displayObject.addChild?.(content);
2653
3299
  displayObject.mediaKind = type;
2654
- return { displayObject, state: { lease, ref } };
3300
+ const dimensions = textureDimensions(image, lease);
3301
+ const clip = ctx.display.createRect?.(1, 1, 16777215);
3302
+ if (clip) {
3303
+ clip.visible = true;
3304
+ content.addChild?.(clip);
3305
+ }
3306
+ const state = {
3307
+ surface,
3308
+ content,
3309
+ image,
3310
+ clip,
3311
+ lease,
3312
+ ref,
3313
+ naturalWidth: dimensions.width,
3314
+ naturalHeight: dimensions.height,
3315
+ retryAt
3316
+ };
3317
+ applyMediaGeometry(displayObject, state, node);
3318
+ return { displayObject, state };
2655
3319
  },
2656
- update(view, node) {
2657
- applyTransform(view, node);
3320
+ async update(view, node, ctx) {
3321
+ const state = view.state;
3322
+ applyMediaGeometry(view.displayObject, state, node);
3323
+ if (!state.ref || state.lease || state.retryAt === void 0 || Date.now() < state.retryAt || ctx.signal.aborted) return;
3324
+ if (state.retry) await state.retry;
3325
+ if (ctx.signal.aborted || state.lease || state.retryAt === void 0 || Date.now() < state.retryAt) return;
3326
+ const retry = (async () => {
3327
+ try {
3328
+ const lease = await ctx.assets.acquireTexture(state.ref, { kind: type });
3329
+ if (ctx.signal.aborted) {
3330
+ lease.release?.();
3331
+ return;
3332
+ }
3333
+ state.lease = lease;
3334
+ state.retryAt = void 0;
3335
+ state.retryAttempt = void 0;
3336
+ if (lease.texture !== void 0) {
3337
+ state.image.texture = lease.texture;
3338
+ view.displayObject.texture = lease.texture;
3339
+ }
3340
+ const dimensions = textureDimensions(state.image, lease);
3341
+ state.naturalWidth = dimensions.width;
3342
+ state.naturalHeight = dimensions.height;
3343
+ applyMediaGeometry(view.displayObject, state, node);
3344
+ } catch {
3345
+ if (!ctx.signal.aborted) scheduleTextureRetry(state);
3346
+ }
3347
+ })();
3348
+ state.retry = retry;
3349
+ try {
3350
+ await retry;
3351
+ } finally {
3352
+ state.retry = void 0;
3353
+ }
2658
3354
  },
2659
3355
  destroy(view) {
2660
3356
  view.displayObject.destroy?.({ children: true });
@@ -2689,6 +3385,74 @@ function applyTransform(view, node) {
2689
3385
  d.width = node.width;
2690
3386
  d.height = node.height;
2691
3387
  }
3388
+ function applyMediaGeometry(displayObject, state, node) {
3389
+ displayObject.x = node.x;
3390
+ displayObject.y = node.y;
3391
+ displayObject.rotation = node.rotation;
3392
+ displayObject.zIndex = node.zIndex;
3393
+ const boxWidth = positiveDimension(node.width);
3394
+ const boxHeight = positiveDimension(node.height);
3395
+ const fit = mediaFit(node);
3396
+ const intrinsic = readIntrinsicSize(node.props) ?? (state.naturalWidth && state.naturalHeight ? { width: state.naturalWidth, height: state.naturalHeight } : void 0);
3397
+ const naturalWidth = positiveDimension(intrinsic?.width);
3398
+ const naturalHeight = positiveDimension(intrinsic?.height);
3399
+ const layout = mediaLayout(fit, boxWidth, boxHeight, naturalWidth, naturalHeight);
3400
+ const surface = state.surface;
3401
+ if (surface) {
3402
+ surface.x = 0;
3403
+ surface.y = 0;
3404
+ surface.width = boxWidth;
3405
+ surface.height = boxHeight;
3406
+ }
3407
+ state.image.visible = Boolean(state.ref) && boxWidth > 0 && boxHeight > 0;
3408
+ state.image.x = layout.x;
3409
+ state.image.y = layout.y;
3410
+ state.image.width = layout.width;
3411
+ state.image.height = layout.height;
3412
+ if (layout.clip) {
3413
+ if (state.clip) {
3414
+ state.clip.width = boxWidth;
3415
+ state.clip.height = boxHeight;
3416
+ state.clip.visible = true;
3417
+ state.content.mask = state.clip;
3418
+ }
3419
+ } else if (state.clip) {
3420
+ state.clip.visible = false;
3421
+ state.content.mask = void 0;
3422
+ }
3423
+ }
3424
+ function mediaFit(node) {
3425
+ const props = node.props;
3426
+ const value = node.fit ?? props.fit ?? props.mediaFit;
3427
+ return value === "cover" || value === "stretch" || value === "contain" ? value : "contain";
3428
+ }
3429
+ function mediaLayout(fit, boxWidth, boxHeight, naturalWidth, naturalHeight) {
3430
+ if (boxWidth <= 0 || boxHeight <= 0) return { x: 0, y: 0, width: 0, height: 0, clip: false };
3431
+ const rect = fitMediaRect(
3432
+ { width: boxWidth, height: boxHeight },
3433
+ naturalWidth > 0 && naturalHeight > 0 ? { width: naturalWidth, height: naturalHeight } : void 0,
3434
+ fit
3435
+ );
3436
+ return { ...rect, clip: fit === "cover" && naturalWidth > 0 && naturalHeight > 0 };
3437
+ }
3438
+ function textureDimensions(image, lease) {
3439
+ const texture = image.texture;
3440
+ const source = texture?.source;
3441
+ const width = [lease?.width, texture?.width, source?.width, image.width].find(isPositiveNumber);
3442
+ const height = [lease?.height, texture?.height, source?.height, image.height].find(isPositiveNumber);
3443
+ return typeof width === "number" && typeof height === "number" ? { width, height } : {};
3444
+ }
3445
+ function scheduleTextureRetry(state) {
3446
+ const attempt = (state.retryAttempt ?? 0) + 1;
3447
+ state.retryAttempt = attempt;
3448
+ state.retryAt = Date.now() + Math.min(TEXTURE_RETRY_BASE_MS * 2 ** Math.min(attempt - 1, 5), TEXTURE_RETRY_MAX_MS);
3449
+ }
3450
+ function positiveDimension(value) {
3451
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
3452
+ }
3453
+ function isPositiveNumber(value) {
3454
+ return positiveDimension(value) > 0;
3455
+ }
2692
3456
 
2693
3457
  // ../renderer-pixi/src/pixi-adapter.ts
2694
3458
  async function loadPixiRuntime() {
@@ -3714,13 +4478,20 @@ var PixiBoardFacade = class {
3714
4478
  this.core = new BoardCore({ ...this.options.core, document: this.options.document });
3715
4479
  const capabilities = createBoardCapabilities(this.core, {
3716
4480
  preview: options.preview,
3717
- capture: options.capture
4481
+ capture: options.capture,
4482
+ import: options.import
3718
4483
  });
3719
4484
  this.capabilities = scopeCapabilities(capabilities, this.signal, () => this.assertAlive());
3720
4485
  this.nodes = {
3721
4486
  create: async (input) => {
3722
4487
  this.assertAlive();
3723
- const node = this.core.nodes.create(input);
4488
+ if (!input.source && !input.asset) {
4489
+ const node2 = this.core.nodes.create(input);
4490
+ return this.node(node2.id);
4491
+ }
4492
+ const result = await this.capabilities.nodes.create({ nodes: [input] }, { origin: "api" });
4493
+ const node = result.nodes[0];
4494
+ if (!node) throw new Error("Imported node was not created");
3724
4495
  return this.node(node.id);
3725
4496
  },
3726
4497
  update: (nodeId, patch) => {
@@ -5059,7 +5830,7 @@ var BrowserPersistenceAdapter = class {
5059
5830
  return this.#destroyed;
5060
5831
  }
5061
5832
  get cleanupErrors() {
5062
- return this.#cleanupErrors.map((record2) => ({ ...record2 }));
5833
+ return this.#cleanupErrors.map((record4) => ({ ...record4 }));
5063
5834
  }
5064
5835
  async capabilities(options = {}) {
5065
5836
  return this.#run(options.signal, async (signal) => ({
@@ -5081,20 +5852,20 @@ var BrowserPersistenceAdapter = class {
5081
5852
  }
5082
5853
  async loadDocument(options = {}) {
5083
5854
  return this.#run(options.signal, async (signal) => {
5084
- const record2 = await this.#indexedDb.loadDocument(signal);
5855
+ const record4 = await this.#indexedDb.loadDocument(signal);
5085
5856
  this.#throwIfAborted(signal);
5086
- return record2 === void 0 ? null : cloneValue2(record2);
5857
+ return record4 === void 0 ? null : cloneValue2(record4);
5087
5858
  });
5088
5859
  }
5089
5860
  async saveDocument(input, options = {}) {
5090
5861
  await this.#run(options.signal, async (signal) => {
5091
- const record2 = {
5862
+ const record4 = {
5092
5863
  snapshot: cloneValue2(input.snapshot),
5093
5864
  metadata: cloneValue2(input.metadata ?? {}),
5094
5865
  savedAt: this.#now()
5095
5866
  };
5096
5867
  this.#throwIfAborted(signal);
5097
- await this.#indexedDb.saveDocument(record2, signal, {
5868
+ await this.#indexedDb.saveDocument(record4, signal, {
5098
5869
  expectedRevision: input.expectedRevision
5099
5870
  });
5100
5871
  });
@@ -5182,14 +5953,14 @@ var BrowserPersistenceAdapter = class {
5182
5953
  ];
5183
5954
  document2.nodes.push(node);
5184
5955
  const current = options.documentMetadata === void 0 ? await this.#indexedDb.loadDocument(signal) : void 0;
5185
- const record2 = {
5956
+ const record4 = {
5186
5957
  snapshot: document2,
5187
5958
  metadata: cloneValue2(options.documentMetadata ?? current?.metadata ?? {}),
5188
5959
  savedAt: now
5189
5960
  };
5190
5961
  try {
5191
5962
  await this.#indexedDb.commitAssetAndDocument(
5192
- record2,
5963
+ record4,
5193
5964
  entry,
5194
5965
  { variant: "original", blob: prepared.blob },
5195
5966
  signal,
@@ -5235,14 +6006,14 @@ var BrowserPersistenceAdapter = class {
5235
6006
  async importUrl(url, options) {
5236
6007
  return this.commitImport(await this.prepareUrl(url, options), options);
5237
6008
  }
5238
- async putAsset(record2, blob, options = {}) {
5239
- return this.#serializeAsset(record2.id, () => this.#putAsset(record2, blob, options));
6009
+ async putAsset(record4, blob, options = {}) {
6010
+ return this.#serializeAsset(record4.id, () => this.#putAsset(record4, blob, options));
5240
6011
  }
5241
- async #putAsset(record2, blob, options) {
6012
+ async #putAsset(record4, blob, options) {
5242
6013
  return this.#run(options.signal, async (signal) => {
5243
6014
  const variant = options.variant === void 0 ? "original" : options.variant;
5244
6015
  assertAssetVariant(variant);
5245
- const previous = await this.#indexedDb.getAssetEntry(record2.id, signal);
6016
+ const previous = await this.#indexedDb.getAssetEntry(record4.id, signal);
5246
6017
  const previousBinary = previous?.binaries[variant];
5247
6018
  this.#throwIfAborted(signal);
5248
6019
  const now = this.#now();
@@ -5251,14 +6022,14 @@ var BrowserPersistenceAdapter = class {
5251
6022
  this.#throwIfAborted(signal);
5252
6023
  let entry;
5253
6024
  if (useOpfs && this.#opfs !== void 0) {
5254
- const key = this.#storageKeyFactory(record2.id, variant);
6025
+ const key = this.#storageKeyFactory(record4.id, variant);
5255
6026
  if (previousBinary?.storage.kind === "opfs" && previousBinary.storage.key === key) {
5256
6027
  throw new BrowserStorageKeyCollisionError(key);
5257
6028
  }
5258
6029
  if (await this.#opfs.get(key, signal) !== void 0) {
5259
6030
  throw new BrowserStorageKeyCollisionError(key);
5260
6031
  }
5261
- entry = this.#createEntry(cloneValue2(record2), variant, blob, { kind: "opfs", key }, previous, now);
6032
+ entry = this.#createEntry(cloneValue2(record4), variant, blob, { kind: "opfs", key }, previous, now);
5262
6033
  await this.#opfs.put(key, blob, signal);
5263
6034
  try {
5264
6035
  this.#throwIfAborted(signal);
@@ -5266,23 +6037,23 @@ var BrowserPersistenceAdapter = class {
5266
6037
  } catch (error) {
5267
6038
  await this.#cleanup(
5268
6039
  "metadata-compensation",
5269
- { assetId: record2.id, variant, key },
6040
+ { assetId: record4.id, variant, key },
5270
6041
  () => this.#opfs?.delete(key, new AbortController().signal)
5271
6042
  );
5272
6043
  throw error;
5273
6044
  }
5274
6045
  } else {
5275
- entry = this.#createEntry(cloneValue2(record2), variant, blob, { kind: "indexeddb" }, previous, now);
6046
+ entry = this.#createEntry(cloneValue2(record4), variant, blob, { kind: "indexeddb" }, previous, now);
5276
6047
  this.#throwIfAborted(signal);
5277
6048
  await this.#indexedDb.putAssetEntry(entry, { variant, blob }, signal);
5278
6049
  }
5279
- this.#revokeAssetLeases(record2.id, variant);
6050
+ this.#revokeAssetLeases(record4.id, variant);
5280
6051
  const binary = entry.binaries[variant];
5281
6052
  if (previousBinary?.storage.kind === "opfs" && (binary.storage.kind !== "opfs" || binary.storage.key !== previousBinary.storage.key)) {
5282
6053
  const previousKey = previousBinary.storage.key;
5283
6054
  await this.#cleanup(
5284
6055
  "replace-old-opfs",
5285
- { assetId: record2.id, variant, key: previousKey },
6056
+ { assetId: record4.id, variant, key: previousKey },
5286
6057
  () => this.#opfs?.delete(previousKey, new AbortController().signal)
5287
6058
  );
5288
6059
  }
@@ -5500,10 +6271,10 @@ var BrowserPersistenceAdapter = class {
5500
6271
  })).then(() => void 0);
5501
6272
  return this.#destroyPromise;
5502
6273
  }
5503
- #createEntry(record2, variant, blob, storage, previous, now) {
6274
+ #createEntry(record4, variant, blob, storage, previous, now) {
5504
6275
  return {
5505
- id: record2.id,
5506
- record: record2,
6276
+ id: record4.id,
6277
+ record: record4,
5507
6278
  binaries: {
5508
6279
  ...previous?.binaries,
5509
6280
  [variant]: {
@@ -5597,15 +6368,15 @@ var BrowserPersistenceAdapter = class {
5597
6368
  try {
5598
6369
  await cleanup();
5599
6370
  } catch (error) {
5600
- const record2 = {
6371
+ const record4 = {
5601
6372
  operation,
5602
6373
  error,
5603
6374
  timestamp: this.#now(),
5604
6375
  ...context
5605
6376
  };
5606
- this.#cleanupErrors.push(record2);
6377
+ this.#cleanupErrors.push(record4);
5607
6378
  try {
5608
- this.#onCleanupError({ ...record2 });
6379
+ this.#onCleanupError({ ...record4 });
5609
6380
  } catch (observerError) {
5610
6381
  this.#cleanupErrors.push({
5611
6382
  operation: "cleanup-observer",
@@ -5846,7 +6617,7 @@ var NativeIndexedDbPort = class {
5846
6617
  async loadDocument(signal) {
5847
6618
  return this.#read(DOCUMENT_STORE, DOCUMENT_KEY, signal);
5848
6619
  }
5849
- async saveDocument(record2, signal, options = {}) {
6620
+ async saveDocument(record4, signal, options = {}) {
5850
6621
  const database = await this.#open(signal);
5851
6622
  if (signal.aborted) throw abortError2(signal);
5852
6623
  const transaction = database.transaction(DOCUMENT_STORE, "readwrite");
@@ -5863,7 +6634,7 @@ var NativeIndexedDbPort = class {
5863
6634
  throw new BrowserDocumentConflictError(options.expectedRevision, actualRevision);
5864
6635
  }
5865
6636
  }
5866
- transaction.objectStore(DOCUMENT_STORE).put(record2, DOCUMENT_KEY);
6637
+ transaction.objectStore(DOCUMENT_STORE).put(record4, DOCUMENT_KEY);
5867
6638
  await done;
5868
6639
  } catch (error) {
5869
6640
  try {
@@ -6813,6 +7584,6 @@ function indexedDbPersistence(options = {}) {
6813
7584
  });
6814
7585
  }
6815
7586
 
6816
- export { AssetUnavailableError, BoardDestroyedError, BrowserAssetBinaryMissingError, BrowserAssetNotFoundError, BrowserDocumentConflictError, BrowserPersistenceAbortError, BrowserPersistenceAdapter, BrowserPersistenceDestroyedError, BrowserPersistenceError, BrowserStorageCapabilityError, BrowserStorageKeyCollisionError, BrowserStorageQuotaError, CapabilityError, CapabilityUnavailableError, DEFAULT_OPFS_THRESHOLD_BYTES, DocumentValidationError, NativeDownloadPort, NativeIndexedDbPort, NativeObjectUrlPort, NativeOpfsPort, NodeNotFoundError, NodeTypeNotRegisteredError, NodeTypeRegistry, NodeValidationError, PermissionDeniedError, PixiBoardRenderer, RESIZE_HANDLES, TransactionConflictError, anchorRatio, anchorWorldPoint, attachConnections, attachDomTransformer, attachLabelOverlay, attachOverlayLayer, attachSelectionOverlay, buildNodeAgentPrompt, createNodeAgentController, createPixiApplicationFactory, createPixiBoard, createPreviewSpec, indexedDbPersistence, isAssetVariant, isBrowserQuotaError, isDocumentPreviewType, isPreviewNodeType, loadPixiRuntime, previewStatusLabel, projectOverlayItem, resizeHandleAxes, resizeHandleCursor, resolveOverlayBounds, resolveScale, rotatedRectBounds, runBrowserAdapterContract };
7587
+ export { AssetUnavailableError, BoardDestroyedError, BrowserAssetBinaryMissingError, BrowserAssetNotFoundError, BrowserDocumentConflictError, BrowserPersistenceAbortError, BrowserPersistenceAdapter, BrowserPersistenceDestroyedError, BrowserPersistenceError, BrowserStorageCapabilityError, BrowserStorageKeyCollisionError, BrowserStorageQuotaError, CapabilityError, CapabilityUnavailableError, DEFAULT_OPFS_THRESHOLD_BYTES, DocumentValidationError, NativeDownloadPort, NativeIndexedDbPort, NativeObjectUrlPort, NativeOpfsPort, NodeNotFoundError, NodeTypeNotRegisteredError, NodeTypeRegistry, NodeValidationError, PermissionDeniedError, PixiBoardRenderer, RESIZE_HANDLES, TransactionConflictError, anchorRatio, anchorWorldPoint, attachConnections, attachDomTransformer, attachLabelOverlay, attachOverlayLayer, attachSelectionOverlay, buildNodeAgentPrompt, createMediaAssetRefs, createMediaMetadata, createNodeAgentController, createPixiApplicationFactory, createPixiBoard, createPreviewSpec, fitMediaRect, indexedDbPersistence, isAssetVariant, isBrowserQuotaError, isContentFit, isDocumentPreviewType, isPreviewNodeType, loadPixiRuntime, preferredMediaNodeSize, previewStatusLabel, projectOverlayItem, resizeHandleAxes, resizeHandleCursor, resolveOverlayBounds, resolveScale, resolveTextureAssetRef, rotatedRectBounds, runBrowserAdapterContract };
6817
7588
  //# sourceMappingURL=browser.js.map
6818
7589
  //# sourceMappingURL=browser.js.map