pixiboardjs 0.1.0-alpha.4 → 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
@@ -1,3 +1,5 @@
1
+ import { Container, Graphics } from 'pixi.js';
2
+
1
3
  var __defProp = Object.defineProperty;
2
4
  var __export = (target, all) => {
3
5
  for (var name in all)
@@ -20,22 +22,31 @@ __export(src_exports, {
20
22
  PixiBoardCoreError: () => PixiBoardCoreError,
21
23
  RESIZE_HANDLES: () => RESIZE_HANDLES,
22
24
  SelectionController: () => SelectionController,
25
+ TEXTURE_REF_ROLES: () => TEXTURE_REF_ROLES,
23
26
  TransactionConflictError: () => TransactionConflictError,
24
27
  ViewportController: () => ViewportController,
25
28
  assertWorldBounds: () => assertWorldBounds,
26
29
  createBoardCore: () => createBoardCore,
30
+ createMediaAssetRefs: () => createMediaAssetRefs,
31
+ createMediaMetadata: () => createMediaMetadata,
27
32
  createPreviewSpec: () => createPreviewSpec,
33
+ fitMediaRect: () => fitMediaRect,
28
34
  isAssetVariant: () => isAssetVariant,
35
+ isContentFit: () => isContentFit,
29
36
  isDocumentPreviewType: () => isDocumentPreviewType,
30
37
  isPreviewNodeType: () => isPreviewNodeType,
38
+ isRenderAssetKind: () => isRenderAssetKind,
31
39
  isResizeHandle: () => isResizeHandle,
32
40
  mergeBounds: () => mergeBounds,
33
41
  nodeGeometry: () => nodeGeometry,
42
+ preferredMediaNodeSize: () => preferredMediaNodeSize,
34
43
  previewStatusLabel: () => previewStatusLabel,
44
+ readIntrinsicSize: () => readIntrinsicSize,
35
45
  resizeHandleAxes: () => resizeHandleAxes,
36
46
  resizeHandleCursor: () => resizeHandleCursor,
37
47
  resolveResize: () => resolveResize,
38
48
  resolveResizeSize: () => resolveResizeSize,
49
+ resolveTextureAssetRef: () => resolveTextureAssetRef,
39
50
  rotatedRectBounds: () => rotatedRectBounds
40
51
  });
41
52
 
@@ -105,6 +116,111 @@ function previewStatusLabel(node, typeLabel) {
105
116
  }
106
117
  }
107
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
+
108
224
  // ../core/src/errors.ts
109
225
  var PixiBoardCoreError = class extends Error {
110
226
  constructor(message) {
@@ -293,6 +409,9 @@ function validateNode(input, path = "node") {
293
409
  throw new DocumentValidationError(`${path}.visible must be a boolean`);
294
410
  }
295
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
+ }
296
415
  if (input.assetRefs !== void 0) validateAssetRefs(input.assetRefs, `${path}.assetRefs`);
297
416
  return { ...cloneValue(input), id, type, typeVersion };
298
417
  }
@@ -338,22 +457,22 @@ function parseInput(input) {
338
457
  function isRecord(value) {
339
458
  return value !== null && typeof value === "object" && !Array.isArray(value);
340
459
  }
341
- function readString(record2, key, path) {
342
- const value = record2[key];
460
+ function readString(record4, key, path) {
461
+ const value = record4[key];
343
462
  if (typeof value !== "string" || !value.trim()) {
344
463
  throw new DocumentValidationError(`${path}.${key} must be a non-empty string`);
345
464
  }
346
465
  return value;
347
466
  }
348
- function readInteger(record2, key, path) {
349
- const value = record2[key];
467
+ function readInteger(record4, key, path) {
468
+ const value = record4[key];
350
469
  if (!Number.isInteger(value)) {
351
470
  throw new DocumentValidationError(`${path}.${key} must be an integer`);
352
471
  }
353
472
  return value;
354
473
  }
355
- function readFiniteNumber(record2, key, path) {
356
- const value = record2[key];
474
+ function readFiniteNumber(record4, key, path) {
475
+ const value = record4[key];
357
476
  if (typeof value !== "number" || !Number.isFinite(value)) {
358
477
  throw new DocumentValidationError(`${path}.${key} must be a finite number`);
359
478
  }
@@ -397,7 +516,92 @@ function assertWorldBounds(bounds, label = "bounds") {
397
516
  }
398
517
 
399
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
+ }
400
603
  var recordHistory = /* @__PURE__ */ Symbol("recordHistory");
604
+ var rebaseMediaBackground = /* @__PURE__ */ Symbol("rebaseMediaBackground");
401
605
  var HistoryController = class {
402
606
  constructor(host) {
403
607
  this.host = host;
@@ -406,6 +610,10 @@ var HistoryController = class {
406
610
  undoStack = [];
407
611
  redoStack = [];
408
612
  listeners = /* @__PURE__ */ new Set();
613
+ patchGenerations = /* @__PURE__ */ new WeakMap();
614
+ entryGenerations = /* @__PURE__ */ new WeakMap();
615
+ nodeGenerations = /* @__PURE__ */ new Map();
616
+ nextNodeGeneration = 1;
409
617
  canUndo() {
410
618
  return this.undoStack.length > 0;
411
619
  }
@@ -418,6 +626,7 @@ var HistoryController = class {
418
626
  const changeSet = this.host.applyHistoryEntry(entry, "undo");
419
627
  this.undoStack.pop();
420
628
  this.redoStack.push(entry);
629
+ this.restoreGenerations(entry, "before");
421
630
  this.emit();
422
631
  return changeSet;
423
632
  }
@@ -427,24 +636,38 @@ var HistoryController = class {
427
636
  const changeSet = this.host.applyHistoryEntry(entry, "redo");
428
637
  this.redoStack.pop();
429
638
  this.undoStack.push(entry);
639
+ this.restoreGenerations(entry, "after");
430
640
  this.emit();
431
641
  return changeSet;
432
642
  }
433
643
  clear() {
434
- if (!this.canUndo() && !this.canRedo()) return;
644
+ const hadHistory = this.canUndo() || this.canRedo();
435
645
  this.undoStack = [];
436
646
  this.redoStack = [];
437
- this.emit();
647
+ this.nodeGenerations = /* @__PURE__ */ new Map();
648
+ this.nextNodeGeneration = 1;
649
+ if (hadHistory) this.emit();
438
650
  }
439
651
  onChange(listener) {
440
652
  this.listeners.add(listener);
441
653
  return () => this.listeners.delete(listener);
442
654
  }
443
655
  [recordHistory](entry) {
656
+ this.captureEntryGenerations(entry);
444
657
  const previous = this.undoStack.at(-1);
445
658
  if (entry.coalesceKey !== void 0 && previous?.coalesceKey === entry.coalesceKey) {
446
659
  previous.forward = compactReplaces([...previous.forward, ...entry.forward]);
447
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
+ }
448
671
  this.redoStack = [];
449
672
  this.emit();
450
673
  return;
@@ -453,6 +676,80 @@ var HistoryController = class {
453
676
  this.redoStack = [];
454
677
  this.emit();
455
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
+ }
456
753
  emit() {
457
754
  const event = { canUndo: this.canUndo(), canRedo: this.canRedo() };
458
755
  for (const listener of this.listeners) {
@@ -463,6 +760,55 @@ var HistoryController = class {
463
760
  }
464
761
  }
465
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
+ }
466
812
  function compactReplaces(patches) {
467
813
  if (patches.some((patch) => patch.op !== "node:replace" && patch.op !== "asset:replace")) {
468
814
  return patches;
@@ -478,7 +824,8 @@ function createHistoryController(host) {
478
824
  const controller = new HistoryController(host);
479
825
  return {
480
826
  controller,
481
- record: (entry) => controller[recordHistory](entry)
827
+ record: (entry) => controller[recordHistory](entry),
828
+ rebaseMediaBackground: (updates) => controller[rebaseMediaBackground](updates)
482
829
  };
483
830
  }
484
831
 
@@ -624,6 +971,9 @@ function isPlainObject(value) {
624
971
  function applyDataPatches(store, patches) {
625
972
  for (const patch of patches) {
626
973
  switch (patch.op) {
974
+ case "metadata:replace":
975
+ store.setMetadata(patch.metadata);
976
+ break;
627
977
  case "node:insert":
628
978
  store.insertNode(patch.index, patch.node);
629
979
  break;
@@ -876,6 +1226,12 @@ var RuntimeDocumentStore = class _RuntimeDocumentStore {
876
1226
  mutableSnapshot() {
877
1227
  return cloneValue(this.materializedDocument());
878
1228
  }
1229
+ getMetadata() {
1230
+ return cloneValue(this.document.metadata);
1231
+ }
1232
+ setMetadata(value) {
1233
+ this.document.metadata = cloneValue(value);
1234
+ }
879
1235
  get revision() {
880
1236
  return this.document.revision;
881
1237
  }
@@ -1246,6 +1602,7 @@ var BoardCore = class {
1246
1602
  rejectedAsyncTransactionCallbacks = 0;
1247
1603
  viewportState;
1248
1604
  recordHistory;
1605
+ rebaseMediaBackground;
1249
1606
  constructor(options = {}) {
1250
1607
  this.nodeTypes = options.nodeTypes ?? new NodeTypeRegistry();
1251
1608
  this.schemaVersion = options.schemaVersion ?? 1;
@@ -1281,6 +1638,7 @@ var BoardCore = class {
1281
1638
  });
1282
1639
  this.history = history.controller;
1283
1640
  this.recordHistory = history.record;
1641
+ this.rebaseMediaBackground = history.rebaseMediaBackground;
1284
1642
  this.nodes = new BoardNodesController(this);
1285
1643
  this.assets = new BoardAssetsController(this);
1286
1644
  this.document = new BoardDocumentController(this);
@@ -1324,7 +1682,11 @@ var BoardCore = class {
1324
1682
  );
1325
1683
  }
1326
1684
  this.activeTransaction = void 0;
1327
- this.commitTransaction(transaction, true);
1685
+ this.commitTransaction(
1686
+ transaction,
1687
+ options.recordHistory !== false,
1688
+ options.recordHistory === false
1689
+ );
1328
1690
  return result;
1329
1691
  } catch (error) {
1330
1692
  this.activeTransaction = void 0;
@@ -1344,7 +1706,7 @@ var BoardCore = class {
1344
1706
  inverse: direction === "undo" ? entry.forward : entry.inverse
1345
1707
  };
1346
1708
  applyDataPatches(transaction.draft, transaction.forward);
1347
- return this.commitTransaction(transaction, false);
1709
+ return this.commitTransaction(transaction, false, false);
1348
1710
  }
1349
1711
  getBounds(nodeId) {
1350
1712
  const node = this.currentStore().requireNode(nodeId);
@@ -1417,7 +1779,7 @@ var BoardCore = class {
1417
1779
  transaction.forward.push(forward);
1418
1780
  transaction.inverse.unshift(inverse);
1419
1781
  }
1420
- commitTransaction(transaction, recordHistory2) {
1782
+ commitTransaction(transaction, recordHistory2, rebaseBackgroundHistory = false) {
1421
1783
  if (transaction.forward.length === 0 && recordHistory2) return void 0;
1422
1784
  const before = this.store;
1423
1785
  const after = transaction.draft;
@@ -1447,10 +1809,28 @@ var BoardCore = class {
1447
1809
  forward: transaction.forward,
1448
1810
  inverse: transaction.inverse
1449
1811
  });
1812
+ } else if (rebaseBackgroundHistory) {
1813
+ this.rebaseHistoryAfterBackgroundWrite(before, after, transaction.forward);
1450
1814
  }
1815
+ changeSet.metadataChanged = transaction.forward.some((patch) => patch.op === "metadata:replace") && !jsonEqual(before.getMetadata(), after.getMetadata());
1451
1816
  this.emitChange(changeSet);
1452
1817
  return changeSet;
1453
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
+ }
1454
1834
  emitChange(changeSet) {
1455
1835
  const changedNodeIds = /* @__PURE__ */ new Set([
1456
1836
  ...changeSet.addedNodeIds,
@@ -1514,7 +1894,8 @@ var BoardNodesController = class {
1514
1894
  ...input.name === void 0 ? {} : { name: input.name },
1515
1895
  ...input.locked === void 0 ? {} : { locked: input.locked },
1516
1896
  ...input.visible === void 0 ? {} : { visible: input.visible },
1517
- ...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 }
1518
1899
  });
1519
1900
  const validated = this.core.nodeTypes.validateNode(node);
1520
1901
  const index = transaction.draft.nodeCount();
@@ -1546,6 +1927,37 @@ var BoardNodesController = class {
1546
1927
  return immutableClone(validated);
1547
1928
  });
1548
1929
  }
1930
+ convert(nodeId, input) {
1931
+ const internals = getCoreInternals(this.core);
1932
+ return internals.mutate("Convert node", (transaction) => {
1933
+ const previous = transaction.draft.requireNode(nodeId);
1934
+ const { typeVersion, props } = this.core.nodeTypes.createProps(input.type, input.props);
1935
+ const { x, y, width, height, rotation, zIndex, locked, visible } = previous;
1936
+ const next = validateNode({
1937
+ x,
1938
+ y,
1939
+ width,
1940
+ height,
1941
+ rotation,
1942
+ zIndex,
1943
+ ...locked === void 0 ? {} : { locked },
1944
+ ...visible === void 0 ? {} : { visible },
1945
+ ...cloneValue(input),
1946
+ id: previous.id,
1947
+ typeVersion: input.typeVersion ?? typeVersion,
1948
+ props
1949
+ });
1950
+ const validated = this.core.nodeTypes.validateNode(next);
1951
+ if (jsonEqual(previous, validated)) return immutableClone(validated);
1952
+ transaction.draft.replaceNode(validated);
1953
+ internals.recordPatch(
1954
+ transaction,
1955
+ { op: "node:replace", node: validated },
1956
+ { op: "node:replace", node: previous }
1957
+ );
1958
+ return immutableClone(validated);
1959
+ });
1960
+ }
1549
1961
  /**
1550
1962
  * Applies one resize gesture step through the node type's `ResizePolicy`.
1551
1963
  * The policy decides what the requested handle drag is allowed to become —
@@ -1571,6 +1983,11 @@ var BoardNodesController = class {
1571
1983
  { op: "node:remove", nodeId },
1572
1984
  { op: "node:insert", index, node: removed }
1573
1985
  );
1986
+ const metadata = transaction.draft.getMetadata();
1987
+ if (Array.isArray(metadata?.connections)) {
1988
+ const connections = metadata.connections.filter((edge) => !edge || typeof edge !== "object" || Array.isArray(edge) || edge.source !== nodeId && edge.target !== nodeId);
1989
+ if (connections.length !== metadata.connections.length) this.core.document.patchMetadata({ connections });
1990
+ }
1574
1991
  return immutableClone(removed);
1575
1992
  });
1576
1993
  }
@@ -1581,11 +1998,11 @@ var BoardNodesController = class {
1581
1998
  list(filter = {}) {
1582
1999
  const idFilter = filter.ids ? new Set(filter.ids) : void 0;
1583
2000
  const typeFilter = filter.types ? new Set(filter.types) : void 0;
1584
- const limit = filter.limit ?? Number.POSITIVE_INFINITY;
1585
- if (!Number.isInteger(limit) && limit !== Number.POSITIVE_INFINITY) {
2001
+ const limit2 = filter.limit ?? Number.POSITIVE_INFINITY;
2002
+ if (!Number.isInteger(limit2) && limit2 !== Number.POSITIVE_INFINITY) {
1586
2003
  throw new RangeError("Node list limit must be an integer");
1587
2004
  }
1588
- if (limit < 0) throw new RangeError("Node list limit must not be negative");
2005
+ if (limit2 < 0) throw new RangeError("Node list limit must not be negative");
1589
2006
  const store = getCoreInternals(this.core).currentStore();
1590
2007
  const selected = filter.selected === void 0 ? void 0 : new Set(this.core.selection.get());
1591
2008
  const source = idFilter ? store.listNodesByIds(idFilter) : store.listNodes();
@@ -1598,7 +2015,7 @@ var BoardNodesController = class {
1598
2015
  if (filter.selected !== void 0 && selected.has(node.id) !== filter.selected) return false;
1599
2016
  return true;
1600
2017
  });
1601
- return deepFreeze(result.slice(0, limit));
2018
+ return deepFreeze(result.slice(0, limit2));
1602
2019
  }
1603
2020
  };
1604
2021
  function boundsIntersect(left, right) {
@@ -1707,6 +2124,26 @@ var BoardDocumentController = class {
1707
2124
  this.core = core;
1708
2125
  }
1709
2126
  core;
2127
+ getRevision() {
2128
+ return getCoreInternals(this.core).currentStore().revision;
2129
+ }
2130
+ getMetadata() {
2131
+ return getCoreInternals(this.core).currentStore().getMetadata();
2132
+ }
2133
+ patchMetadata(patch) {
2134
+ const internals = getCoreInternals(this.core);
2135
+ internals.mutate("Update document metadata", (transaction) => {
2136
+ const previous = transaction.draft.getMetadata();
2137
+ const next = { ...previous };
2138
+ for (const [key, value] of Object.entries(patch)) {
2139
+ if (value === void 0) delete next[key];
2140
+ else next[key] = cloneValue(value);
2141
+ }
2142
+ assertJsonValue(next, "document.metadata");
2143
+ transaction.draft.setMetadata(next);
2144
+ internals.recordPatch(transaction, { op: "metadata:replace", metadata: next }, { op: "metadata:replace", metadata: previous });
2145
+ });
2146
+ }
1710
2147
  snapshot() {
1711
2148
  return getCoreInternals(this.core).snapshotDocument();
1712
2149
  }
@@ -1784,6 +2221,7 @@ function createChangeSet(input) {
1784
2221
  };
1785
2222
  }
1786
2223
  function hasEffectivePatchChanges(before, after, patches) {
2224
+ if (patches.some((patch) => patch.op === "metadata:replace") && !jsonEqual(before.getMetadata(), after.getMetadata())) return true;
1787
2225
  if (patches.some((patch) => patch.op.endsWith(":insert") || patch.op.endsWith(":remove"))) {
1788
2226
  const beforeSnapshot = before.mutableSnapshot();
1789
2227
  const afterSnapshot = after.mutableSnapshot();
@@ -1939,7 +2377,10 @@ function createBoardCapabilities(core, services = {}) {
1939
2377
  changeSet = event.changeSet;
1940
2378
  });
1941
2379
  try {
1942
- 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
+ });
1943
2384
  return { result, changed: changeSet !== void 0, changeSet };
1944
2385
  } catch (error) {
1945
2386
  throw mapCoreError(error);
@@ -1948,9 +2389,9 @@ function createBoardCapabilities(core, services = {}) {
1948
2389
  }
1949
2390
  };
1950
2391
  const page = (items, requested = 50, cursor) => {
1951
- const limit = Math.min(Math.max(requested, 1), 200);
2392
+ const limit2 = Math.min(Math.max(requested, 1), 200);
1952
2393
  const start = cursor ? Math.max(0, Number.parseInt(cursor, 10) || 0) : 0;
1953
- const out = items.slice(start, start + limit);
2394
+ const out = items.slice(start, start + limit2);
1954
2395
  const hasMore = start + out.length < items.length;
1955
2396
  return { out, page: { hasMore, ...hasMore ? { nextCursor: String(start + out.length) } : {} } };
1956
2397
  };
@@ -1965,7 +2406,7 @@ function createBoardCapabilities(core, services = {}) {
1965
2406
  requestId: value.requestId
1966
2407
  });
1967
2408
  const capabilities = {
1968
- availability: { preview: Boolean(services.preview), capture: Boolean(services.capture) },
2409
+ availability: { preview: Boolean(services.preview), capture: Boolean(services.capture), import: Boolean(services.import) },
1969
2410
  document: {
1970
2411
  snapshot: async (options = {}) => {
1971
2412
  aborted(options.signal);
@@ -2003,14 +2444,16 @@ function createBoardCapabilities(core, services = {}) {
2003
2444
  create: async (input, options = {}) => {
2004
2445
  try {
2005
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);
2006
2449
  const tx = transact(options.label ?? "Create nodes", options, () => {
2007
2450
  const nodes = [];
2008
- for (const raw of input.nodes) {
2451
+ for (const item of prepared) {
2009
2452
  aborted(options.signal);
2010
- const { asset, ...nodeInput } = raw;
2011
- const refs = asset ? { ...nodeInput.assetRefs ?? {}, primary: { assetId: asset.id, variant: "original" } } : nodeInput.assetRefs;
2012
- if (asset) core.assets.upsert(asset);
2013
- 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));
2014
2457
  }
2015
2458
  return nodes;
2016
2459
  });
@@ -2020,20 +2463,61 @@ function createBoardCapabilities(core, services = {}) {
2020
2463
  }
2021
2464
  },
2022
2465
  update: async (input, options = {}) => {
2466
+ let stopWatching;
2023
2467
  try {
2024
2468
  if (!input.nodes.length) throw new CapabilityError("INVALID_INPUT", "nodes must not be empty");
2025
- const tx = transact(options.label ?? "Update nodes", options, () => {
2026
- const nodes = [];
2027
- for (const item of input.nodes) {
2028
- aborted(options.signal);
2029
- if (item.asset) core.assets.upsert(item.asset);
2030
- nodes.push(core.nodes.update(item.id, item.patch));
2031
- }
2032
- return nodes;
2033
- });
2034
- 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);
2035
2517
  } catch (error) {
2036
2518
  throw mapCoreError(error);
2519
+ } finally {
2520
+ stopWatching?.();
2037
2521
  }
2038
2522
  },
2039
2523
  delete: async (input, options = {}) => {
@@ -2168,6 +2652,227 @@ function createBoardCapabilities(core, services = {}) {
2168
2652
  };
2169
2653
  return capabilities;
2170
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
+ }
2171
2876
 
2172
2877
  // ../renderer-pixi/src/registry.ts
2173
2878
  var NodeRendererRegistry = class {
@@ -2194,20 +2899,357 @@ var NodeRendererRegistry = class {
2194
2899
  }
2195
2900
  };
2196
2901
 
2902
+ // ../renderer-pixi/src/spatial.ts
2903
+ var GridSpatialIndex = class {
2904
+ cells = /* @__PURE__ */ new Map();
2905
+ items = /* @__PURE__ */ new Map();
2906
+ cellSize;
2907
+ constructor(cellSize = 256) {
2908
+ if (!Number.isFinite(cellSize) || cellSize <= 0) throw new RangeError("cellSize must be positive");
2909
+ this.cellSize = cellSize;
2910
+ }
2911
+ rebuild(items) {
2912
+ this.cells.clear();
2913
+ this.items.clear();
2914
+ for (const item of items) this.insert(item);
2915
+ }
2916
+ insert(item) {
2917
+ this.remove(item.id);
2918
+ const copy = { ...item };
2919
+ this.items.set(copy.id, copy);
2920
+ for (const key of this.keys(copy)) {
2921
+ let bucket = this.cells.get(key);
2922
+ if (!bucket) this.cells.set(key, bucket = /* @__PURE__ */ new Map());
2923
+ bucket.set(copy.id, copy);
2924
+ }
2925
+ }
2926
+ update(item) {
2927
+ this.insert(item);
2928
+ }
2929
+ remove(id) {
2930
+ const previous = this.items.get(id);
2931
+ if (!previous) return;
2932
+ this.items.delete(id);
2933
+ for (const key of this.keys(previous)) {
2934
+ const bucket = this.cells.get(key);
2935
+ bucket?.delete(id);
2936
+ if (bucket?.size === 0) this.cells.delete(key);
2937
+ }
2938
+ }
2939
+ query(bounds) {
2940
+ const result = /* @__PURE__ */ new Set();
2941
+ for (const key of this.keys(bounds)) {
2942
+ for (const item of this.cells.get(key)?.values() ?? []) if (intersects(item, bounds)) result.add(item.id);
2943
+ }
2944
+ return result;
2945
+ }
2946
+ queryPoint(point) {
2947
+ const key = this.key(Math.floor(point.x / this.cellSize), Math.floor(point.y / this.cellSize));
2948
+ const result = /* @__PURE__ */ new Set();
2949
+ for (const item of this.cells.get(key)?.values() ?? []) if (contains(item, point)) result.add(item.id);
2950
+ return result;
2951
+ }
2952
+ *keys(bounds) {
2953
+ const minX = Math.floor(bounds.minX / this.cellSize);
2954
+ const maxX = Math.floor(bounds.maxX / this.cellSize);
2955
+ const minY = Math.floor(bounds.minY / this.cellSize);
2956
+ const maxY = Math.floor(bounds.maxY / this.cellSize);
2957
+ for (let x = minX; x <= maxX; x++) for (let y = minY; y <= maxY; y++) yield this.key(x, y);
2958
+ }
2959
+ key(x, y) {
2960
+ return `${x}:${y}`;
2961
+ }
2962
+ };
2963
+ function intersects(a, b) {
2964
+ return a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY;
2965
+ }
2966
+ function contains(a, p) {
2967
+ return p.x >= a.minX && p.x <= a.maxX && p.y >= a.minY && p.y <= a.maxY;
2968
+ }
2969
+
2970
+ // ../renderer-pixi/src/connections.ts
2971
+ var defaultConnectionStyle = {
2972
+ startColor: "#6366f1",
2973
+ endColor: "#06b6d4",
2974
+ startOpacity: 1,
2975
+ endOpacity: 1,
2976
+ width: 2,
2977
+ lineType: "solid"
2978
+ };
2979
+ var PREVIEW_ID = "__connection_preview__";
2980
+ var GRADIENT_STEP = 6;
2981
+ var SELECTION_PADDING = 2;
2982
+ var ConnectionRenderLayer = class {
2983
+ constructor(invalidate, detach) {
2984
+ this.invalidate = invalidate;
2985
+ this.detach = detach;
2986
+ this.container.zIndex = -1e6;
2987
+ this.container.eventMode = "none";
2988
+ }
2989
+ invalidate;
2990
+ detach;
2991
+ container = new Container();
2992
+ entries = /* @__PURE__ */ new Map();
2993
+ index = new GridSpatialIndex();
2994
+ segments = /* @__PURE__ */ new Map();
2995
+ visibleIds = /* @__PURE__ */ new Set();
2996
+ visible = true;
2997
+ selected;
2998
+ style = { ...defaultConnectionStyle };
2999
+ bounds;
3000
+ destroyed = false;
3001
+ setStyle(style) {
3002
+ if (this.destroyed) return;
3003
+ this.style = normalizeConnectionStyle({ ...this.style, ...style });
3004
+ for (const [id, entry] of this.entries) this.draw(entry, id === this.selected);
3005
+ this.setVisibleBounds(this.bounds);
3006
+ this.invalidate();
3007
+ }
3008
+ setSelected(id) {
3009
+ if (this.destroyed) return;
3010
+ const next = id === PREVIEW_ID ? void 0 : id;
3011
+ if (this.selected === next) return;
3012
+ const previous = this.selected;
3013
+ this.selected = next;
3014
+ for (const key of [previous, next]) {
3015
+ const entry = key === void 0 ? void 0 : this.entries.get(key);
3016
+ if (entry) this.draw(entry, key === next);
3017
+ }
3018
+ this.invalidate();
3019
+ }
3020
+ setEnabled(enabled) {
3021
+ if (this.destroyed) return;
3022
+ this.visible = enabled;
3023
+ this.container.visible = enabled;
3024
+ this.invalidate();
3025
+ }
3026
+ setVisibleBounds(bounds) {
3027
+ if (this.destroyed) return;
3028
+ this.bounds = bounds ? { ...bounds } : void 0;
3029
+ const next = /* @__PURE__ */ new Set();
3030
+ if (this.bounds) {
3031
+ for (const key of this.index.query(this.paddedBounds(this.bounds))) {
3032
+ const segment = this.segments.get(key);
3033
+ if (segment) next.add(segment.id);
3034
+ }
3035
+ } else {
3036
+ for (const id of this.entries.keys()) next.add(id);
3037
+ }
3038
+ for (const id of /* @__PURE__ */ new Set([...this.visibleIds, ...next])) {
3039
+ const entry = this.entries.get(id);
3040
+ if (entry) entry.view.visible = next.has(id);
3041
+ }
3042
+ this.visibleIds = next;
3043
+ }
3044
+ upsert(curve) {
3045
+ if (this.destroyed) return;
3046
+ this.disposeEntry(curve.id);
3047
+ const points = sampleCurve(curve);
3048
+ const view = new Graphics();
3049
+ const keys = [];
3050
+ const bounds = this.bounds ? this.paddedBounds(this.bounds) : void 0;
3051
+ let visible = !bounds;
3052
+ for (let i = 1; i < points.length; i++) {
3053
+ const a = points[i - 1];
3054
+ const b = points[i];
3055
+ const key = JSON.stringify([curve.id, i]);
3056
+ const segmentBounds = {
3057
+ minX: Math.min(a.x, b.x),
3058
+ minY: Math.min(a.y, b.y),
3059
+ maxX: Math.max(a.x, b.x),
3060
+ maxY: Math.max(a.y, b.y)
3061
+ };
3062
+ keys.push(key);
3063
+ this.segments.set(key, { id: curve.id, a, b });
3064
+ this.index.insert({ id: key, ...segmentBounds });
3065
+ if (bounds && intersects2(segmentBounds, bounds)) visible = true;
3066
+ }
3067
+ const entry = { view, points, length: points[points.length - 1].distance, keys };
3068
+ this.entries.set(curve.id, entry);
3069
+ this.container.addChild(view);
3070
+ view.visible = visible;
3071
+ if (visible) this.visibleIds.add(curve.id);
3072
+ this.draw(entry, curve.id === this.selected);
3073
+ this.invalidate();
3074
+ }
3075
+ remove(id) {
3076
+ if (this.destroyed || !this.entries.has(id)) return;
3077
+ this.disposeEntry(id);
3078
+ this.invalidate();
3079
+ }
3080
+ hitTest(point, tolerance) {
3081
+ if (this.destroyed || !this.visible || !Number.isFinite(tolerance) || tolerance < 0) return;
3082
+ let nearest;
3083
+ let nearestDistance = tolerance;
3084
+ const bounds = {
3085
+ minX: point.x - tolerance,
3086
+ minY: point.y - tolerance,
3087
+ maxX: point.x + tolerance,
3088
+ maxY: point.y + tolerance
3089
+ };
3090
+ for (const key of this.index.query(bounds)) {
3091
+ const segment = this.segments.get(key);
3092
+ if (!segment || segment.id === PREVIEW_ID || !this.visibleIds.has(segment.id)) continue;
3093
+ const { a, b } = segment;
3094
+ const dx = b.x - a.x;
3095
+ const dy = b.y - a.y;
3096
+ const t = Math.max(0, Math.min(
3097
+ 1,
3098
+ ((point.x - a.x) * dx + (point.y - a.y) * dy) / (dx * dx + dy * dy || 1)
3099
+ ));
3100
+ const distance = Math.hypot(point.x - a.x - t * dx, point.y - a.y - t * dy);
3101
+ if (distance <= nearestDistance) {
3102
+ nearest = segment.id;
3103
+ nearestDistance = distance;
3104
+ }
3105
+ }
3106
+ return nearest;
3107
+ }
3108
+ destroy() {
3109
+ if (this.destroyed) return;
3110
+ this.destroyed = true;
3111
+ for (const id of this.entries.keys()) this.disposeEntry(id);
3112
+ this.detach();
3113
+ this.container.destroy({ children: true });
3114
+ this.invalidate();
3115
+ }
3116
+ disposeEntry(id) {
3117
+ const entry = this.entries.get(id);
3118
+ if (!entry) return;
3119
+ for (const key of entry.keys) {
3120
+ this.index.remove(key);
3121
+ this.segments.delete(key);
3122
+ }
3123
+ this.visibleIds.delete(id);
3124
+ this.entries.delete(id);
3125
+ entry.view.destroy();
3126
+ }
3127
+ paddedBounds(bounds) {
3128
+ const padding = this.style.width / 2 + SELECTION_PADDING;
3129
+ return {
3130
+ minX: bounds.minX - padding,
3131
+ minY: bounds.minY - padding,
3132
+ maxX: bounds.maxX + padding,
3133
+ maxY: bounds.maxY + padding
3134
+ };
3135
+ }
3136
+ draw(entry, selected) {
3137
+ const { view, points, length } = entry;
3138
+ const style = this.style;
3139
+ view.clear();
3140
+ if (length === 0) return;
3141
+ const startColor = parseInt(style.startColor.slice(1), 16);
3142
+ const endColor = parseInt(style.endColor.slice(1), 16);
3143
+ const colorAt = (distance) => {
3144
+ const t = distance / length;
3145
+ const channel = (shift) => Math.round(
3146
+ (startColor >> shift & 255) * (1 - t) + (endColor >> shift & 255) * t
3147
+ );
3148
+ return channel(16) << 16 | channel(8) << 8 | channel(0);
3149
+ };
3150
+ const alphaAt = (distance) => {
3151
+ const t = distance / length;
3152
+ return style.startOpacity * (1 - t) + style.endOpacity * t;
3153
+ };
3154
+ for (const highlight of selected ? [true, false] : [false]) {
3155
+ const width = style.width + (highlight ? SELECTION_PADDING * 2 : 0);
3156
+ const color = (distance) => highlight ? 16777215 : colorAt(distance);
3157
+ const alpha = (distance) => highlight ? 0.85 : alphaAt(distance);
3158
+ if (style.lineType === "dotted") {
3159
+ const spacing = Math.max(8, style.width * 2);
3160
+ let cursor = 1;
3161
+ for (let distance = 0; distance <= length; distance += spacing) {
3162
+ while (cursor < points.length - 1 && points[cursor].distance < distance) cursor++;
3163
+ const point = pointAtDistance(points[cursor - 1], points[cursor], distance);
3164
+ view.circle(point.x, point.y, width / 2).fill({ color: color(distance), alpha: alpha(distance) });
3165
+ }
3166
+ continue;
3167
+ }
3168
+ for (let i = 1; i < points.length; i++) {
3169
+ const a = points[i - 1];
3170
+ const b = points[i];
3171
+ let distance = a.distance;
3172
+ while (distance < b.distance) {
3173
+ const period = Math.floor(distance / 24);
3174
+ const dashEnd = period * 24 + 15;
3175
+ const painted = style.lineType === "solid" || distance < dashEnd;
3176
+ const patternEnd = style.lineType === "solid" ? b.distance : painted ? dashEnd : (period + 1) * 24;
3177
+ const end = Math.min(b.distance, patternEnd, distance + GRADIENT_STEP);
3178
+ if (painted) {
3179
+ const p = pointAtDistance(a, b, distance);
3180
+ const q = pointAtDistance(a, b, end);
3181
+ const middle = (distance + end) / 2;
3182
+ view.moveTo(p.x, p.y).lineTo(q.x, q.y).stroke({
3183
+ width,
3184
+ color: color(middle),
3185
+ alpha: alpha(middle),
3186
+ cap: "butt"
3187
+ });
3188
+ }
3189
+ distance = end;
3190
+ }
3191
+ }
3192
+ }
3193
+ }
3194
+ };
3195
+ function sampleCurve(curve) {
3196
+ const distance = Math.max(48, Math.min(400, Math.abs(curve.end.x - curve.start.x) * 0.5));
3197
+ const a = curve.start;
3198
+ const d = curve.end;
3199
+ const b = {
3200
+ x: a.x + (curve.startDirection?.x ?? 1) * distance,
3201
+ y: a.y + (curve.startDirection?.y ?? 0) * distance
3202
+ };
3203
+ const c = {
3204
+ x: d.x - (curve.endDirection?.x ?? 1) * distance,
3205
+ y: d.y - (curve.endDirection?.y ?? 0) * distance
3206
+ };
3207
+ const estimate = Math.hypot(b.x - a.x, b.y - a.y) + Math.hypot(c.x - b.x, c.y - b.y) + Math.hypot(d.x - c.x, d.y - c.y);
3208
+ const count = Math.max(24, Math.min(192, Math.ceil(estimate / 12)));
3209
+ const points = [];
3210
+ let length = 0;
3211
+ for (let i = 0; i <= count; i++) {
3212
+ const t = i / count;
3213
+ const u = 1 - t;
3214
+ const point = {
3215
+ x: u * u * u * a.x + 3 * u * u * t * b.x + 3 * u * t * t * c.x + t * t * t * d.x,
3216
+ y: u * u * u * a.y + 3 * u * u * t * b.y + 3 * u * t * t * c.y + t * t * t * d.y
3217
+ };
3218
+ const previous = points[points.length - 1];
3219
+ if (previous) length += Math.hypot(point.x - previous.x, point.y - previous.y);
3220
+ points.push({ ...point, distance: length });
3221
+ }
3222
+ return points;
3223
+ }
3224
+ function pointAtDistance(a, b, distance) {
3225
+ const t = b.distance === a.distance ? 0 : (distance - a.distance) / (b.distance - a.distance);
3226
+ return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
3227
+ }
3228
+ function intersects2(a, b) {
3229
+ return a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY;
3230
+ }
3231
+ function normalizeConnectionStyle(value) {
3232
+ const color = (v, fallback) => /^#[\da-f]{6}$/i.test(v) ? v : fallback;
3233
+ const finite = (v, fallback) => Number.isFinite(v) ? v : fallback;
3234
+ return {
3235
+ startColor: color(value.startColor, defaultConnectionStyle.startColor),
3236
+ endColor: color(value.endColor, defaultConnectionStyle.endColor),
3237
+ startOpacity: Math.min(1, Math.max(0, finite(value.startOpacity, 1))),
3238
+ endOpacity: Math.min(1, Math.max(0, finite(value.endOpacity, 1))),
3239
+ width: Math.min(32, Math.max(0.5, finite(value.width, 2))),
3240
+ lineType: ["solid", "dashed", "dotted"].includes(value.lineType) ? value.lineType : "solid"
3241
+ };
3242
+ }
3243
+
2197
3244
  // ../renderer-pixi/src/builtins.ts
3245
+ var TEXTURE_RETRY_BASE_MS = 1e3;
3246
+ var TEXTURE_RETRY_MAX_MS = 3e4;
2198
3247
  var base = (create, update) => ({ create, update, destroy(view) {
2199
3248
  view.displayObject.destroy?.({ children: true });
2200
3249
  } });
2201
3250
  function registerBuiltinRenderers(registry) {
2202
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)));
2203
- registerTextureNode(registry, "image", ["preview", "image", "primary", "source"]);
2204
- registerTextureNode(registry, "video", ["preview", "poster", "video", "primary", "source"]);
2205
- registerTextureNode(registry, "audio", ["waveform", "preview", "audio", "primary", "source"]);
2206
- registerTextureNode(registry, "model", ["preview", "model", "primary", "source"]);
2207
- registerTextureNode(registry, "html", ["preview", "html", "primary", "source"]);
2208
- registerTextureNode(registry, "markdown", ["preview", "markdown", "primary", "source"]);
2209
- registerTextureNode(registry, "text-file", ["preview", "text-file", "primary", "source"]);
2210
- registerTextureNode(registry, "file", ["preview", "file", "primary", "source"]);
3252
+ for (const type of ["image", "video", "audio", "model", "html", "markdown", "text-file", "file"]) registerTextureNode(registry, type);
2211
3253
  if (!registry.has("text")) registry.register("text", {
2212
3254
  create(node, ctx) {
2213
3255
  const displayObject = ctx.display.createContainer();
@@ -2230,20 +3272,85 @@ function registerBuiltinRenderers(registry) {
2230
3272
  if (!registry.has("unknown-node")) registry.register("unknown-node", base((node, ctx) => ({ displayObject: ctx.display.createText?.(`${node.type}
2231
3273
  ${node.id}`, { fill: 10265519 }) ?? ctx.display.createContainer(), state: {} }), (view, node) => applyTransform(view, node)));
2232
3274
  }
2233
- function registerTextureNode(registry, type, refNames) {
3275
+ function registerTextureNode(registry, type) {
2234
3276
  if (registry.has(type)) return;
2235
3277
  registry.register(type, {
2236
3278
  async create(node, ctx) {
2237
- const ref = refNames.map((name) => node.assetRefs?.[name]).find(Boolean);
2238
- 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;
2239
3286
  if (ctx.signal.aborted) throw new DOMException("Aborted", "AbortError");
2240
- 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;
2241
3296
  if (lease?.texture !== void 0) displayObject.texture = lease.texture;
3297
+ content.addChild?.(image);
3298
+ displayObject.addChild?.(content);
2242
3299
  displayObject.mediaKind = type;
2243
- 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 };
2244
3319
  },
2245
- update(view, node) {
2246
- 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
+ }
2247
3354
  },
2248
3355
  destroy(view) {
2249
3356
  view.displayObject.destroy?.({ children: true });
@@ -2278,73 +3385,73 @@ function applyTransform(view, node) {
2278
3385
  d.width = node.width;
2279
3386
  d.height = node.height;
2280
3387
  }
2281
-
2282
- // ../renderer-pixi/src/spatial.ts
2283
- var GridSpatialIndex = class {
2284
- cells = /* @__PURE__ */ new Map();
2285
- items = /* @__PURE__ */ new Map();
2286
- cellSize;
2287
- constructor(cellSize = 256) {
2288
- if (!Number.isFinite(cellSize) || cellSize <= 0) throw new RangeError("cellSize must be positive");
2289
- this.cellSize = cellSize;
2290
- }
2291
- rebuild(items) {
2292
- this.cells.clear();
2293
- this.items.clear();
2294
- for (const item of items) this.insert(item);
2295
- }
2296
- insert(item) {
2297
- this.remove(item.id);
2298
- const copy = { ...item };
2299
- this.items.set(copy.id, copy);
2300
- for (const key of this.keys(copy)) {
2301
- let bucket = this.cells.get(key);
2302
- if (!bucket) this.cells.set(key, bucket = /* @__PURE__ */ new Map());
2303
- bucket.set(copy.id, copy);
2304
- }
2305
- }
2306
- update(item) {
2307
- this.insert(item);
2308
- }
2309
- remove(id) {
2310
- const previous = this.items.get(id);
2311
- if (!previous) return;
2312
- this.items.delete(id);
2313
- for (const key of this.keys(previous)) {
2314
- const bucket = this.cells.get(key);
2315
- bucket?.delete(id);
2316
- if (bucket?.size === 0) this.cells.delete(key);
2317
- }
2318
- }
2319
- query(bounds) {
2320
- const result = /* @__PURE__ */ new Set();
2321
- for (const key of this.keys(bounds)) {
2322
- for (const item of this.cells.get(key)?.values() ?? []) if (intersects(item, bounds)) result.add(item.id);
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;
2323
3418
  }
2324
- return result;
2325
- }
2326
- queryPoint(point) {
2327
- const key = this.key(Math.floor(point.x / this.cellSize), Math.floor(point.y / this.cellSize));
2328
- const result = /* @__PURE__ */ new Set();
2329
- for (const item of this.cells.get(key)?.values() ?? []) if (contains(item, point)) result.add(item.id);
2330
- return result;
2331
- }
2332
- *keys(bounds) {
2333
- const minX = Math.floor(bounds.minX / this.cellSize);
2334
- const maxX = Math.floor(bounds.maxX / this.cellSize);
2335
- const minY = Math.floor(bounds.minY / this.cellSize);
2336
- const maxY = Math.floor(bounds.maxY / this.cellSize);
2337
- for (let x = minX; x <= maxX; x++) for (let y = minY; y <= maxY; y++) yield this.key(x, y);
2338
- }
2339
- key(x, y) {
2340
- return `${x}:${y}`;
3419
+ } else if (state.clip) {
3420
+ state.clip.visible = false;
3421
+ state.content.mask = void 0;
2341
3422
  }
2342
- };
2343
- function intersects(a, b) {
2344
- return a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY;
2345
3423
  }
2346
- function contains(a, p) {
2347
- return p.x >= a.minX && p.x <= a.maxX && p.y >= a.minY && p.y <= a.maxY;
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;
2348
3455
  }
2349
3456
 
2350
3457
  // ../renderer-pixi/src/pixi-adapter.ts
@@ -2401,7 +3508,11 @@ var PixiBoardRenderer = class {
2401
3508
  operations = /* @__PURE__ */ new Map();
2402
3509
  app;
2403
3510
  world;
3511
+ connectionLayers = /* @__PURE__ */ new Set();
2404
3512
  revision;
3513
+ nodeOrder = /* @__PURE__ */ new Map();
3514
+ nextNodeOrder = 0;
3515
+ displayOrderDirty = false;
2405
3516
  nodesById = /* @__PURE__ */ new Map();
2406
3517
  desiredIds = /* @__PURE__ */ new Set();
2407
3518
  visibleBounds;
@@ -2430,12 +3541,28 @@ var PixiBoardRenderer = class {
2430
3541
  this.world = this.viewFactory.createContainer();
2431
3542
  this.app.stage.addChild?.(this.world);
2432
3543
  }
3544
+ async createConnectionLayer() {
3545
+ this.assertAlive();
3546
+ if (!this.world) throw new Error("Renderer has not initialized");
3547
+ let layer;
3548
+ layer = new ConnectionRenderLayer(() => this.requestFrame(), () => this.connectionLayers.delete(layer));
3549
+ this.world.addChild?.(layer.container);
3550
+ this.world.sortableChildren = true;
3551
+ this.connectionLayers.add(layer);
3552
+ layer.setVisibleBounds(this.visibleBounds);
3553
+ return layer;
3554
+ }
2433
3555
  async rebuild(snapshot) {
2434
3556
  this.assertAlive();
2435
3557
  try {
2436
3558
  this.revision = snapshot.revision;
2437
3559
  this.nodesById.clear();
2438
- for (const node of snapshot.nodes) this.nodesById.set(node.id, node);
3560
+ this.nodeOrder.clear();
3561
+ this.nextNodeOrder = 0;
3562
+ for (const node of snapshot.nodes) {
3563
+ this.nodesById.set(node.id, node);
3564
+ this.nodeOrder.set(node.id, this.nextNodeOrder++);
3565
+ }
2439
3566
  this.rebuildSpatialIndex(snapshot);
2440
3567
  this.refreshDesiredIds();
2441
3568
  for (const id of /* @__PURE__ */ new Set([...this.entries.keys(), ...this.operations.keys()])) await this.destroyView(id);
@@ -2464,6 +3591,7 @@ var PixiBoardRenderer = class {
2464
3591
  const assetChangedIds = new Set(changeSet.assetChangedNodeIds);
2465
3592
  for (const id of changeSet.removedNodeIds) {
2466
3593
  this.nodesById.delete(id);
3594
+ this.nodeOrder.delete(id);
2467
3595
  this.desiredIds.delete(id);
2468
3596
  this.spatialIndex.remove(id);
2469
3597
  await this.destroyView(id);
@@ -2472,6 +3600,7 @@ var PixiBoardRenderer = class {
2472
3600
  const node = nextNodes.get(id);
2473
3601
  if (!node) continue;
2474
3602
  this.nodesById.set(id, node);
3603
+ if (!this.nodeOrder.has(id)) this.nodeOrder.set(id, this.nextNodeOrder++);
2475
3604
  const item = { ...this.getBounds(node), id };
2476
3605
  if (addedIds.has(id)) this.spatialIndex.insert(item);
2477
3606
  else if (updatedIds.has(id)) this.spatialIndex.update(item);
@@ -2502,6 +3631,7 @@ var PixiBoardRenderer = class {
2502
3631
  throw new RangeError("Viewport scale must be finite and greater than zero");
2503
3632
  }
2504
3633
  this.visibleBounds = bounds;
3634
+ for (const layer of this.connectionLayers) layer.setVisibleBounds(bounds);
2505
3635
  this.currentScale = scale;
2506
3636
  const nextLevel = lodLevelFor(scale, this.lodThresholds);
2507
3637
  const levelChanged = nextLevel !== this.currentLodLevel;
@@ -2543,7 +3673,7 @@ var PixiBoardRenderer = class {
2543
3673
  }
2544
3674
  hitTest(worldPoint) {
2545
3675
  const ids = this.spatialIndex.queryPoint?.(worldPoint) ?? this.entries.keys();
2546
- const order = [...ids].map((id, index) => ({ node: this.entries.get(id)?.node, index })).filter(({ node }) => node).sort((a, b) => b.node.zIndex - a.node.zIndex || b.index - a.index);
3676
+ const order = [...ids].map((id) => ({ node: this.entries.get(id)?.node, index: this.nodeOrder.get(id) ?? -1 })).filter(({ node }) => node).sort((a, b) => b.node.zIndex - a.node.zIndex || b.index - a.index);
2547
3677
  for (const { node } of order) {
2548
3678
  const entry = this.entries.get(node.id);
2549
3679
  if (entry.renderer.hitTest?.(node, worldPoint) ?? contains2(this.getBounds(node), worldPoint)) return node.id;
@@ -2575,7 +3705,12 @@ var PixiBoardRenderer = class {
2575
3705
  }
2576
3706
  if (request.target === "bounds") frame = request.bounds;
2577
3707
  if (request.target === "viewport" && this.app?.screen) frame = { minX: 0, minY: 0, maxX: this.app.screen.width, maxY: this.app.screen.height };
2578
- return this.captureFrame(target, frame, scale, request, signal, options.requestId);
3708
+ for (const layer of this.connectionLayers) layer.setVisibleBounds(void 0);
3709
+ try {
3710
+ return await this.captureFrame(target, frame, scale, request, signal, options.requestId);
3711
+ } finally {
3712
+ for (const layer of this.connectionLayers) layer.setVisibleBounds(this.visibleBounds);
3713
+ }
2579
3714
  }
2580
3715
  async destroy() {
2581
3716
  if (this.destroyed) return;
@@ -2584,6 +3719,7 @@ var PixiBoardRenderer = class {
2584
3719
  for (const operation of this.operations.values()) operation.controller.abort();
2585
3720
  await Promise.allSettled([...this.operations.values()].map((operation) => operation.promise).filter(Boolean));
2586
3721
  for (const id of [...this.entries.keys()]) await this.destroyView(id);
3722
+ for (const layer of [...this.connectionLayers]) layer.destroy();
2587
3723
  this.world?.destroy?.({ children: true });
2588
3724
  this.app?.destroy?.(true);
2589
3725
  this.entries.clear();
@@ -2592,15 +3728,28 @@ var PixiBoardRenderer = class {
2592
3728
  this.desiredIds.clear();
2593
3729
  this.updateDiagnosticCounts();
2594
3730
  }
3731
+ syncDisplayOrder() {
3732
+ const world = this.world;
3733
+ if (!world?.children) return;
3734
+ const order = /* @__PURE__ */ new Map();
3735
+ for (const [id, entry] of this.entries) {
3736
+ entry.view.displayObject.zIndex = entry.node.zIndex;
3737
+ order.set(entry.view.displayObject, this.nodeOrder.get(id) ?? -1);
3738
+ }
3739
+ world.children.sort((a, b) => (a.zIndex ?? 0) - (b.zIndex ?? 0) || (order.get(a) ?? -1) - (order.get(b) ?? -1));
3740
+ world.sortDirty = true;
3741
+ }
2595
3742
  async ensureView(node, forceRecreate = false) {
2596
3743
  const renderer = this.registry.get(node.type) ?? this.registry.get("unknown-node");
2597
3744
  const current = this.entries.get(node.id);
2598
- if (current && !forceRecreate && current.renderer === renderer && sameAssetRefs(current.node.assetRefs, node.assetRefs)) {
3745
+ if (current && !forceRecreate && current.node.type === node.type && current.node.typeVersion === node.typeVersion && current.renderer === renderer && sameAssetRefs(current.node.assetRefs, node.assetRefs)) {
2599
3746
  const operation2 = this.beginOperation(node.id);
2600
3747
  const task2 = (async () => {
3748
+ const orderChanged = current.node.zIndex !== node.zIndex;
2601
3749
  current.node = node;
2602
3750
  this.diagnostics.updates++;
2603
3751
  await renderer.update(current.view, node, this.context(combineSignals(current.lifetime.signal, operation2.controller.signal), current.scope));
3752
+ if (orderChanged) this.displayOrderDirty = true;
2604
3753
  if (!this.isCurrentOperation(node.id, operation2) || this.entries.get(node.id) !== current) this.diagnostics.lateUpdates++;
2605
3754
  })();
2606
3755
  await this.trackOperation(node.id, operation2, task2);
@@ -2632,6 +3781,7 @@ var PixiBoardRenderer = class {
2632
3781
  this.entries.set(node.id, entry);
2633
3782
  this.activeViews.set(node.id, view);
2634
3783
  this.world?.addChild?.(view.displayObject);
3784
+ this.displayOrderDirty = true;
2635
3785
  this.diagnostics.creates++;
2636
3786
  this.updateDiagnosticCounts();
2637
3787
  } catch (error) {
@@ -2711,7 +3861,7 @@ var PixiBoardRenderer = class {
2711
3861
  if (node.visible === false) return false;
2712
3862
  if (!this.visibleBounds) return true;
2713
3863
  if (customVisibleCandidates) return customVisibleCandidates.has(node.id);
2714
- return intersects2(this.getBounds(node), this.visibleBounds);
3864
+ return intersects3(this.getBounds(node), this.visibleBounds);
2715
3865
  }
2716
3866
  visibleCandidatesFor(touchedIds) {
2717
3867
  const candidates = this.options.cullingQuery(this.visibleBounds);
@@ -2779,6 +3929,10 @@ var PixiBoardRenderer = class {
2779
3929
  * driving continuous frames for that animation.
2780
3930
  */
2781
3931
  requestFrame() {
3932
+ if (this.displayOrderDirty) {
3933
+ this.syncDisplayOrder();
3934
+ this.displayOrderDirty = false;
3935
+ }
2782
3936
  if (this.destroyed || !this.app || this.diagnostics.tickers > 0 || this.frameScheduled) return;
2783
3937
  this.frameScheduled = true;
2784
3938
  void Promise.resolve().then(() => {
@@ -2887,7 +4041,7 @@ var ResourceScope = class {
2887
4041
  function contains2(bounds, point) {
2888
4042
  return point.x >= bounds.minX && point.x <= bounds.maxX && point.y >= bounds.minY && point.y <= bounds.maxY;
2889
4043
  }
2890
- function intersects2(left, right) {
4044
+ function intersects3(left, right) {
2891
4045
  return left.minX <= right.maxX && left.maxX >= right.minX && left.minY <= right.maxY && left.maxY >= right.minY;
2892
4046
  }
2893
4047
  function sameAssetRefs(a, b) {
@@ -3324,13 +4478,20 @@ var PixiBoardFacade = class {
3324
4478
  this.core = new BoardCore({ ...this.options.core, document: this.options.document });
3325
4479
  const capabilities = createBoardCapabilities(this.core, {
3326
4480
  preview: options.preview,
3327
- capture: options.capture
4481
+ capture: options.capture,
4482
+ import: options.import
3328
4483
  });
3329
4484
  this.capabilities = scopeCapabilities(capabilities, this.signal, () => this.assertAlive());
3330
4485
  this.nodes = {
3331
4486
  create: async (input) => {
3332
4487
  this.assertAlive();
3333
- 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");
3334
4495
  return this.node(node.id);
3335
4496
  },
3336
4497
  update: (nodeId, patch) => {
@@ -3342,6 +4503,11 @@ var PixiBoardFacade = class {
3342
4503
  this.core.nodes.resize(nodeId, request);
3343
4504
  return this.node(nodeId);
3344
4505
  },
4506
+ convert: (nodeId, input) => {
4507
+ this.assertAlive();
4508
+ this.core.nodes.convert(nodeId, input);
4509
+ return this.node(nodeId);
4510
+ },
3345
4511
  remove: (nodeId) => this.removeNode(nodeId),
3346
4512
  get: (nodeId) => this.getNode(nodeId),
3347
4513
  list: (filter = {}) => {
@@ -3468,6 +4634,18 @@ var PixiBoardFacade = class {
3468
4634
  }
3469
4635
  };
3470
4636
  this.document = {
4637
+ getRevision: () => {
4638
+ this.assertAlive();
4639
+ return this.core.document.getRevision();
4640
+ },
4641
+ getMetadata: () => {
4642
+ this.assertAlive();
4643
+ return this.core.document.getMetadata();
4644
+ },
4645
+ patchMetadata: (patch) => {
4646
+ this.assertAlive();
4647
+ this.core.document.patchMetadata(patch);
4648
+ },
3471
4649
  snapshot: () => {
3472
4650
  this.assertAlive();
3473
4651
  return this.core.document.snapshot();
@@ -3490,6 +4668,12 @@ var PixiBoardFacade = class {
3490
4668
  this.bindRuntimePorts();
3491
4669
  this.ready = this.mount();
3492
4670
  }
4671
+ async createConnectionLayer() {
4672
+ await this.ready;
4673
+ this.assertAlive();
4674
+ if (!this.renderer?.createConnectionLayer) throw new Error("Renderer does not support connection layers");
4675
+ return this.renderer.createConnectionLayer();
4676
+ }
3493
4677
  get state() {
3494
4678
  return this.lifecycle;
3495
4679
  }
@@ -4433,6 +5617,7 @@ function attachLabelOverlay(board, options) {
4433
5617
  } else if (parts.icon.parentElement !== element || parts.text.parentElement !== element) {
4434
5618
  element.replaceChildren(parts.icon, parts.text);
4435
5619
  }
5620
+ element.title = options.tooltip?.(node) ?? (typeof previewError === "string" ? previewError : "");
4436
5621
  const data = placement.data;
4437
5622
  if (placement.collapsed) {
4438
5623
  if (parts.icon.textContent !== (data.icon ?? "")) parts.icon.textContent = data.icon ?? "";
@@ -4645,7 +5830,7 @@ var BrowserPersistenceAdapter = class {
4645
5830
  return this.#destroyed;
4646
5831
  }
4647
5832
  get cleanupErrors() {
4648
- return this.#cleanupErrors.map((record2) => ({ ...record2 }));
5833
+ return this.#cleanupErrors.map((record4) => ({ ...record4 }));
4649
5834
  }
4650
5835
  async capabilities(options = {}) {
4651
5836
  return this.#run(options.signal, async (signal) => ({
@@ -4667,20 +5852,20 @@ var BrowserPersistenceAdapter = class {
4667
5852
  }
4668
5853
  async loadDocument(options = {}) {
4669
5854
  return this.#run(options.signal, async (signal) => {
4670
- const record2 = await this.#indexedDb.loadDocument(signal);
5855
+ const record4 = await this.#indexedDb.loadDocument(signal);
4671
5856
  this.#throwIfAborted(signal);
4672
- return record2 === void 0 ? null : cloneValue2(record2);
5857
+ return record4 === void 0 ? null : cloneValue2(record4);
4673
5858
  });
4674
5859
  }
4675
5860
  async saveDocument(input, options = {}) {
4676
5861
  await this.#run(options.signal, async (signal) => {
4677
- const record2 = {
5862
+ const record4 = {
4678
5863
  snapshot: cloneValue2(input.snapshot),
4679
5864
  metadata: cloneValue2(input.metadata ?? {}),
4680
5865
  savedAt: this.#now()
4681
5866
  };
4682
5867
  this.#throwIfAborted(signal);
4683
- await this.#indexedDb.saveDocument(record2, signal, {
5868
+ await this.#indexedDb.saveDocument(record4, signal, {
4684
5869
  expectedRevision: input.expectedRevision
4685
5870
  });
4686
5871
  });
@@ -4768,14 +5953,14 @@ var BrowserPersistenceAdapter = class {
4768
5953
  ];
4769
5954
  document2.nodes.push(node);
4770
5955
  const current = options.documentMetadata === void 0 ? await this.#indexedDb.loadDocument(signal) : void 0;
4771
- const record2 = {
5956
+ const record4 = {
4772
5957
  snapshot: document2,
4773
5958
  metadata: cloneValue2(options.documentMetadata ?? current?.metadata ?? {}),
4774
5959
  savedAt: now
4775
5960
  };
4776
5961
  try {
4777
5962
  await this.#indexedDb.commitAssetAndDocument(
4778
- record2,
5963
+ record4,
4779
5964
  entry,
4780
5965
  { variant: "original", blob: prepared.blob },
4781
5966
  signal,
@@ -4821,14 +6006,14 @@ var BrowserPersistenceAdapter = class {
4821
6006
  async importUrl(url, options) {
4822
6007
  return this.commitImport(await this.prepareUrl(url, options), options);
4823
6008
  }
4824
- async putAsset(record2, blob, options = {}) {
4825
- 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));
4826
6011
  }
4827
- async #putAsset(record2, blob, options) {
6012
+ async #putAsset(record4, blob, options) {
4828
6013
  return this.#run(options.signal, async (signal) => {
4829
6014
  const variant = options.variant === void 0 ? "original" : options.variant;
4830
6015
  assertAssetVariant(variant);
4831
- const previous = await this.#indexedDb.getAssetEntry(record2.id, signal);
6016
+ const previous = await this.#indexedDb.getAssetEntry(record4.id, signal);
4832
6017
  const previousBinary = previous?.binaries[variant];
4833
6018
  this.#throwIfAborted(signal);
4834
6019
  const now = this.#now();
@@ -4837,14 +6022,14 @@ var BrowserPersistenceAdapter = class {
4837
6022
  this.#throwIfAborted(signal);
4838
6023
  let entry;
4839
6024
  if (useOpfs && this.#opfs !== void 0) {
4840
- const key = this.#storageKeyFactory(record2.id, variant);
6025
+ const key = this.#storageKeyFactory(record4.id, variant);
4841
6026
  if (previousBinary?.storage.kind === "opfs" && previousBinary.storage.key === key) {
4842
6027
  throw new BrowserStorageKeyCollisionError(key);
4843
6028
  }
4844
6029
  if (await this.#opfs.get(key, signal) !== void 0) {
4845
6030
  throw new BrowserStorageKeyCollisionError(key);
4846
6031
  }
4847
- 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);
4848
6033
  await this.#opfs.put(key, blob, signal);
4849
6034
  try {
4850
6035
  this.#throwIfAborted(signal);
@@ -4852,23 +6037,23 @@ var BrowserPersistenceAdapter = class {
4852
6037
  } catch (error) {
4853
6038
  await this.#cleanup(
4854
6039
  "metadata-compensation",
4855
- { assetId: record2.id, variant, key },
6040
+ { assetId: record4.id, variant, key },
4856
6041
  () => this.#opfs?.delete(key, new AbortController().signal)
4857
6042
  );
4858
6043
  throw error;
4859
6044
  }
4860
6045
  } else {
4861
- entry = this.#createEntry(cloneValue2(record2), variant, blob, { kind: "indexeddb" }, previous, now);
6046
+ entry = this.#createEntry(cloneValue2(record4), variant, blob, { kind: "indexeddb" }, previous, now);
4862
6047
  this.#throwIfAborted(signal);
4863
6048
  await this.#indexedDb.putAssetEntry(entry, { variant, blob }, signal);
4864
6049
  }
4865
- this.#revokeAssetLeases(record2.id, variant);
6050
+ this.#revokeAssetLeases(record4.id, variant);
4866
6051
  const binary = entry.binaries[variant];
4867
6052
  if (previousBinary?.storage.kind === "opfs" && (binary.storage.kind !== "opfs" || binary.storage.key !== previousBinary.storage.key)) {
4868
6053
  const previousKey = previousBinary.storage.key;
4869
6054
  await this.#cleanup(
4870
6055
  "replace-old-opfs",
4871
- { assetId: record2.id, variant, key: previousKey },
6056
+ { assetId: record4.id, variant, key: previousKey },
4872
6057
  () => this.#opfs?.delete(previousKey, new AbortController().signal)
4873
6058
  );
4874
6059
  }
@@ -5086,10 +6271,10 @@ var BrowserPersistenceAdapter = class {
5086
6271
  })).then(() => void 0);
5087
6272
  return this.#destroyPromise;
5088
6273
  }
5089
- #createEntry(record2, variant, blob, storage, previous, now) {
6274
+ #createEntry(record4, variant, blob, storage, previous, now) {
5090
6275
  return {
5091
- id: record2.id,
5092
- record: record2,
6276
+ id: record4.id,
6277
+ record: record4,
5093
6278
  binaries: {
5094
6279
  ...previous?.binaries,
5095
6280
  [variant]: {
@@ -5183,15 +6368,15 @@ var BrowserPersistenceAdapter = class {
5183
6368
  try {
5184
6369
  await cleanup();
5185
6370
  } catch (error) {
5186
- const record2 = {
6371
+ const record4 = {
5187
6372
  operation,
5188
6373
  error,
5189
6374
  timestamp: this.#now(),
5190
6375
  ...context
5191
6376
  };
5192
- this.#cleanupErrors.push(record2);
6377
+ this.#cleanupErrors.push(record4);
5193
6378
  try {
5194
- this.#onCleanupError({ ...record2 });
6379
+ this.#onCleanupError({ ...record4 });
5195
6380
  } catch (observerError) {
5196
6381
  this.#cleanupErrors.push({
5197
6382
  operation: "cleanup-observer",
@@ -5432,7 +6617,7 @@ var NativeIndexedDbPort = class {
5432
6617
  async loadDocument(signal) {
5433
6618
  return this.#read(DOCUMENT_STORE, DOCUMENT_KEY, signal);
5434
6619
  }
5435
- async saveDocument(record2, signal, options = {}) {
6620
+ async saveDocument(record4, signal, options = {}) {
5436
6621
  const database = await this.#open(signal);
5437
6622
  if (signal.aborted) throw abortError2(signal);
5438
6623
  const transaction = database.transaction(DOCUMENT_STORE, "readwrite");
@@ -5449,7 +6634,7 @@ var NativeIndexedDbPort = class {
5449
6634
  throw new BrowserDocumentConflictError(options.expectedRevision, actualRevision);
5450
6635
  }
5451
6636
  }
5452
- transaction.objectStore(DOCUMENT_STORE).put(record2, DOCUMENT_KEY);
6637
+ transaction.objectStore(DOCUMENT_STORE).put(record4, DOCUMENT_KEY);
5453
6638
  await done;
5454
6639
  } catch (error) {
5455
6640
  try {
@@ -5710,6 +6895,685 @@ var NativeOpfsPort = class {
5710
6895
  }
5711
6896
  };
5712
6897
 
6898
+ // src/connections.ts
6899
+ var PREVIEW_ID2 = "__connection_preview__";
6900
+ var PORT_OFFSET = 7;
6901
+ var PORT_HOVER_RADIUS = 14;
6902
+ async function attachConnections(board, options) {
6903
+ const layer = await board.createConnectionLayer();
6904
+ const surface = options.surface;
6905
+ const overlay = options.overlay ?? surface;
6906
+ const persistSettings = options.persistSettings !== false;
6907
+ const edges = /* @__PURE__ */ new Map();
6908
+ const adjacent = /* @__PURE__ */ new Map();
6909
+ const incomingIndex = /* @__PURE__ */ new Map();
6910
+ const outgoingIndex = /* @__PURE__ */ new Map();
6911
+ const nodes = /* @__PURE__ */ new Map();
6912
+ const nodeOrder = /* @__PURE__ */ new Map();
6913
+ let nextNodeOrder = 0;
6914
+ let indexedRevision = -1;
6915
+ const nodeIndex = new GridSpatialIndex();
6916
+ const dirty = /* @__PURE__ */ new Set();
6917
+ const cleanup = [];
6918
+ let enabledOverride = options.enabled;
6919
+ let styleOverride = { ...options.style };
6920
+ let enabled = options.enabled ?? false;
6921
+ let style = normalizeConnectionStyle({ ...defaultConnectionStyle, ...options.style });
6922
+ let selected;
6923
+ let hover;
6924
+ let drag;
6925
+ let destroyed = false;
6926
+ let initialized = false;
6927
+ let frame = 0;
6928
+ let spacePressed = false;
6929
+ let ownsKeyboard = false;
6930
+ const port = document.createElement("button");
6931
+ port.type = "button";
6932
+ port.className = "pixiboard-connection-port";
6933
+ port.title = "\u62D6\u52A8\u8FDE\u63A5\u8282\u70B9";
6934
+ port.setAttribute("aria-label", port.title);
6935
+ port.tabIndex = -1;
6936
+ port.style.cssText = [
6937
+ "position:absolute",
6938
+ "width:9px",
6939
+ "height:9px",
6940
+ "border-radius:50%",
6941
+ "border:1.5px solid white",
6942
+ "background:#6366f1",
6943
+ "box-shadow:0 1px 5px #0003",
6944
+ "transform:translate(-50%,-50%)",
6945
+ "padding:0",
6946
+ "cursor:crosshair",
6947
+ "pointer-events:auto",
6948
+ "touch-action:none",
6949
+ "display:none",
6950
+ "z-index:15"
6951
+ ].join(";");
6952
+ overlay.appendChild(port);
6953
+ const canInteract = () => !destroyed && enabled && !spacePressed && (options.canInteract?.() ?? true);
6954
+ const canConnect = (node) => !!node && node.visible !== false && node.locked !== true;
6955
+ const anchor = (node, right) => {
6956
+ const x = right ? node.width : 0;
6957
+ const y = node.height / 2;
6958
+ const c = Math.cos(node.rotation);
6959
+ const s = Math.sin(node.rotation);
6960
+ return { x: node.x + x * c - y * s, y: node.y + x * s + y * c };
6961
+ };
6962
+ const curve = (edge) => {
6963
+ const source = nodes.get(edge.source);
6964
+ const target = nodes.get(edge.target);
6965
+ if (!source || !target || source.visible === false || target.visible === false) return;
6966
+ return {
6967
+ id: edge.id,
6968
+ start: anchor(source, true),
6969
+ end: anchor(target, false),
6970
+ startDirection: { x: Math.cos(source.rotation), y: Math.sin(source.rotation) },
6971
+ endDirection: { x: Math.cos(target.rotation), y: Math.sin(target.rotation) }
6972
+ };
6973
+ };
6974
+ const portPosition = (node) => {
6975
+ const point = board.viewport.toScreen(anchor(node, true));
6976
+ const rect = surface.getBoundingClientRect();
6977
+ return { x: point.x + rect.left + PORT_OFFSET, y: point.y + rect.top };
6978
+ };
6979
+ const projectPort = () => {
6980
+ const node = hover ? nodes.get(hover) : void 0;
6981
+ port.style.display = canInteract() && canConnect(node) && !drag ? "block" : "none";
6982
+ if (!node) return;
6983
+ const point = portPosition(node);
6984
+ const rect = overlay.getBoundingClientRect();
6985
+ port.style.left = `${point.x - rect.left + overlay.scrollLeft}px`;
6986
+ port.style.top = `${point.y - rect.top + overlay.scrollTop}px`;
6987
+ };
6988
+ const flush = () => {
6989
+ frame = 0;
6990
+ if (destroyed) return;
6991
+ if (drag && (!canInteract() || !canConnect(nodes.get(drag.source)))) drag = void 0;
6992
+ for (const id of dirty) {
6993
+ const edge = edges.get(id);
6994
+ const value = edge && curve(edge);
6995
+ if (value) layer.upsert(value);
6996
+ else layer.remove(id);
6997
+ }
6998
+ dirty.clear();
6999
+ const source = drag && nodes.get(drag.source);
7000
+ if (drag && source) {
7001
+ layer.upsert({ id: PREVIEW_ID2, start: anchor(source, true), end: drag.point });
7002
+ } else {
7003
+ layer.remove(PREVIEW_ID2);
7004
+ }
7005
+ layer.setSelected(selected);
7006
+ projectPort();
7007
+ };
7008
+ const schedule = () => {
7009
+ if (!destroyed && !frame) frame = requestAnimationFrame(flush);
7010
+ };
7011
+ const cancelInteraction = () => {
7012
+ drag = void 0;
7013
+ hover = void 0;
7014
+ selected = void 0;
7015
+ schedule();
7016
+ };
7017
+ const rebuildNodes = () => {
7018
+ nodes.clear();
7019
+ nodeOrder.clear();
7020
+ nextNodeOrder = 0;
7021
+ nodeIndex.rebuild([]);
7022
+ for (const node of board.find()) {
7023
+ nodes.set(node.id, node);
7024
+ if (!nodeOrder.has(node.id)) nodeOrder.set(node.id, nextNodeOrder++);
7025
+ if (node.visible !== false) nodeIndex.insert({ id: node.id, ...rotatedRectBounds(node) });
7026
+ }
7027
+ };
7028
+ const readEdges = () => {
7029
+ const result = /* @__PURE__ */ new Map();
7030
+ const values = board.document.getMetadata()?.connections;
7031
+ for (const value of Array.isArray(values) ? values : []) {
7032
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
7033
+ const { id, source, target } = value;
7034
+ if (typeof id === "string" && typeof source === "string" && typeof target === "string") {
7035
+ result.set(id, { id, source, target });
7036
+ }
7037
+ }
7038
+ return result;
7039
+ };
7040
+ const addToIndex = (index, nodeId, edgeId) => {
7041
+ let ids = index.get(nodeId);
7042
+ if (!ids) index.set(nodeId, ids = /* @__PURE__ */ new Set());
7043
+ ids.add(edgeId);
7044
+ };
7045
+ const synchronize = () => {
7046
+ const settings = persistSettings ? board.document.getMetadata()?.connectionSettings : void 0;
7047
+ const nextEnabled = enabledOverride ?? settings?.enabled ?? false;
7048
+ const nextStyle = normalizeConnectionStyle({
7049
+ ...defaultConnectionStyle,
7050
+ ...settings?.style,
7051
+ ...styleOverride
7052
+ });
7053
+ if (!initialized || JSON.stringify(style) !== JSON.stringify(nextStyle)) layer.setStyle(nextStyle);
7054
+ if (!initialized || enabled !== nextEnabled) layer.setEnabled(nextEnabled);
7055
+ enabled = nextEnabled;
7056
+ style = nextStyle;
7057
+ initialized = true;
7058
+ const next = readEdges();
7059
+ indexedRevision = board.document.getRevision();
7060
+ for (const id of edges.keys()) {
7061
+ if (next.has(id)) continue;
7062
+ layer.remove(id);
7063
+ if (selected === id) selected = void 0;
7064
+ }
7065
+ adjacent.clear();
7066
+ incomingIndex.clear();
7067
+ outgoingIndex.clear();
7068
+ for (const [id, edge] of next) {
7069
+ const previous = edges.get(id);
7070
+ if (!previous || previous.source !== edge.source || previous.target !== edge.target) dirty.add(id);
7071
+ addToIndex(adjacent, edge.source, id);
7072
+ addToIndex(adjacent, edge.target, id);
7073
+ addToIndex(outgoingIndex, edge.source, id);
7074
+ addToIndex(incomingIndex, edge.target, id);
7075
+ }
7076
+ edges.clear();
7077
+ for (const [id, edge] of next) edges.set(id, edge);
7078
+ if (!enabled) cancelInteraction();
7079
+ schedule();
7080
+ };
7081
+ const write = (values) => {
7082
+ board.document.patchMetadata({ connections: values });
7083
+ queueMicrotask(() => {
7084
+ if (!destroyed) synchronize();
7085
+ });
7086
+ };
7087
+ const create = (source, target) => {
7088
+ if (destroyed || source === target || !canConnect(board.nodes.get(source)) || !canConnect(board.nodes.get(target))) return;
7089
+ const current = readEdges();
7090
+ for (const edge2 of current.values()) {
7091
+ if (edge2.source === source && edge2.target === target) return { ...edge2 };
7092
+ }
7093
+ const edge = { id: crypto.randomUUID(), source, target };
7094
+ write([...current.values(), edge]);
7095
+ return { ...edge };
7096
+ };
7097
+ const remove = (id) => {
7098
+ if (destroyed) return;
7099
+ const current = readEdges();
7100
+ if (current.delete(id)) write([...current.values()]);
7101
+ };
7102
+ const indexedEdges = (index, nodeId) => {
7103
+ if (board.document.getRevision() !== indexedRevision) {
7104
+ const endpoint = index === incomingIndex ? "target" : "source";
7105
+ return [...readEdges().values()].filter((edge) => edge[endpoint] === nodeId);
7106
+ }
7107
+ const result = [];
7108
+ for (const id of index.get(nodeId) ?? []) {
7109
+ const edge = edges.get(id);
7110
+ if (edge) result.push({ ...edge });
7111
+ }
7112
+ return result;
7113
+ };
7114
+ const screen = (event) => {
7115
+ const rect = surface.getBoundingClientRect();
7116
+ return { x: event.clientX - rect.left, y: event.clientY - rect.top };
7117
+ };
7118
+ const withinSurface = (event) => {
7119
+ const rect = surface.getBoundingClientRect();
7120
+ return event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;
7121
+ };
7122
+ const isCanvasTarget = (target) => target === port || target instanceof Element && (surface.contains(target) || options.interactionOverlays?.some((overlay2) => overlay2.contains(target))) && !target.closest("button,input,textarea,select,[contenteditable]:not([contenteditable=false])");
7123
+ const hasModifiers = (event) => event.altKey || event.shiftKey || event.ctrlKey || event.metaKey;
7124
+ const hitNode = (point) => {
7125
+ let found;
7126
+ for (const id of nodeIndex.queryPoint(point)) {
7127
+ const node = nodes.get(id);
7128
+ if (!node || node.visible === false) continue;
7129
+ const c = Math.cos(node.rotation);
7130
+ const s = Math.sin(node.rotation);
7131
+ const dx = point.x - node.x;
7132
+ const dy = point.y - node.y;
7133
+ const x = dx * c + dy * s;
7134
+ const y = -dx * s + dy * c;
7135
+ if (x >= 0 && x <= node.width && y >= 0 && y <= node.height && (!found || node.zIndex > found.zIndex || node.zIndex === found.zIndex && (nodeOrder.get(node.id) ?? -1) > (nodeOrder.get(found.id) ?? -1))) found = node;
7136
+ }
7137
+ return found;
7138
+ };
7139
+ const listen = (target, name, handler, capture = false) => {
7140
+ const listener = handler;
7141
+ target.addEventListener(name, listener, capture);
7142
+ cleanup.push(() => target.removeEventListener(name, listener, capture));
7143
+ };
7144
+ listen(port, "pointerdown", (event) => {
7145
+ if (event.defaultPrevented || !canInteract() || !withinSurface(event) || !hover || event.button !== 0 || hasModifiers(event)) return;
7146
+ if (!canConnect(nodes.get(hover))) return;
7147
+ event.preventDefault();
7148
+ event.stopPropagation();
7149
+ board.focus();
7150
+ ownsKeyboard = true;
7151
+ drag = { source: hover, pointerId: event.pointerId, point: board.viewport.toWorld(screen(event)) };
7152
+ selected = void 0;
7153
+ schedule();
7154
+ });
7155
+ listen(window, "pointermove", (event) => {
7156
+ if (drag && drag.pointerId !== event.pointerId) return;
7157
+ if (!canInteract() || !withinSurface(event)) {
7158
+ drag = void 0;
7159
+ hover = void 0;
7160
+ schedule();
7161
+ return;
7162
+ }
7163
+ if (drag) {
7164
+ if (!canConnect(nodes.get(drag.source))) drag = void 0;
7165
+ else drag.point = board.viewport.toWorld(screen(event));
7166
+ schedule();
7167
+ return;
7168
+ }
7169
+ if (event.buttons || hasModifiers(event) || !isCanvasTarget(event.target)) {
7170
+ hover = void 0;
7171
+ schedule();
7172
+ return;
7173
+ }
7174
+ const hovered = hover ? nodes.get(hover) : void 0;
7175
+ const point = hovered && canConnect(hovered) ? portPosition(hovered) : void 0;
7176
+ const nearPort = point && Math.hypot(event.clientX - point.x, event.clientY - point.y) <= PORT_HOVER_RADIUS;
7177
+ if (!nearPort) {
7178
+ const node = hitNode(board.viewport.toWorld(screen(event)));
7179
+ hover = canConnect(node) ? node.id : void 0;
7180
+ }
7181
+ schedule();
7182
+ });
7183
+ const finish = (event) => {
7184
+ if (!drag || event.pointerId !== drag.pointerId) return;
7185
+ const source = drag.source;
7186
+ drag = void 0;
7187
+ if (event.type === "pointerup" && canInteract() && withinSurface(event) && isCanvasTarget(event.target) && !hasModifiers(event)) {
7188
+ const target = hitNode(board.viewport.toWorld(screen(event)));
7189
+ if (canConnect(target)) create(source, target.id);
7190
+ }
7191
+ schedule();
7192
+ };
7193
+ listen(window, "pointerup", finish);
7194
+ listen(window, "pointercancel", finish);
7195
+ listen(window, "pointerdown", (event) => {
7196
+ const inside = withinSurface(event) && isCanvasTarget(event.target);
7197
+ ownsKeyboard = inside;
7198
+ if (!inside) cancelInteraction();
7199
+ }, true);
7200
+ listen(surface, "pointerdown", (event) => {
7201
+ if (event.target === port) return;
7202
+ if (event.defaultPrevented || !canInteract() || !withinSurface(event) || !isCanvasTarget(event.target) || event.button !== 0 || hasModifiers(event)) {
7203
+ cancelInteraction();
7204
+ return;
7205
+ }
7206
+ const point = board.viewport.toWorld(screen(event));
7207
+ selected = hitNode(point) ? void 0 : layer.hitTest(point, 7 / board.viewport.get().scale);
7208
+ if (selected) {
7209
+ board.focus();
7210
+ board.selection.clear();
7211
+ event.preventDefault();
7212
+ event.stopPropagation();
7213
+ }
7214
+ schedule();
7215
+ }, true);
7216
+ listen(window, "keydown", (event) => {
7217
+ const element = event.target instanceof Element ? event.target : void 0;
7218
+ if (element?.closest("input,textarea,select,[contenteditable]:not([contenteditable=false])")) return;
7219
+ if (event.code === "Space") {
7220
+ spacePressed = true;
7221
+ cancelInteraction();
7222
+ return;
7223
+ }
7224
+ if (!ownsKeyboard) return;
7225
+ if (event.key === "Escape") cancelInteraction();
7226
+ if (canInteract() && selected && (event.key === "Delete" || event.key === "Backspace")) {
7227
+ event.preventDefault();
7228
+ event.stopImmediatePropagation();
7229
+ remove(selected);
7230
+ selected = void 0;
7231
+ schedule();
7232
+ }
7233
+ }, true);
7234
+ listen(window, "keyup", (event) => {
7235
+ if (event.code === "Space") {
7236
+ spacePressed = false;
7237
+ schedule();
7238
+ }
7239
+ });
7240
+ listen(window, "focusin", (event) => {
7241
+ const target = event.target;
7242
+ if (target instanceof Node && !surface.contains(target) && target !== port) {
7243
+ ownsKeyboard = false;
7244
+ cancelInteraction();
7245
+ }
7246
+ });
7247
+ listen(window, "blur", () => {
7248
+ spacePressed = false;
7249
+ ownsKeyboard = false;
7250
+ cancelInteraction();
7251
+ });
7252
+ rebuildNodes();
7253
+ synchronize();
7254
+ cleanup.push(board.on("change", (event) => {
7255
+ if (event.changeSet.origin === "load") {
7256
+ cancelInteraction();
7257
+ rebuildNodes();
7258
+ synchronize();
7259
+ for (const id of edges.keys()) dirty.add(id);
7260
+ schedule();
7261
+ return;
7262
+ }
7263
+ for (const id of event.changeSet.removedNodeIds) {
7264
+ nodes.delete(id);
7265
+ nodeOrder.delete(id);
7266
+ nodeIndex.remove(id);
7267
+ for (const edgeId of adjacent.get(id) ?? []) dirty.add(edgeId);
7268
+ }
7269
+ for (const node of event.documentUpdate.changedNodes) {
7270
+ nodes.set(node.id, node);
7271
+ if (!nodeOrder.has(node.id)) nodeOrder.set(node.id, nextNodeOrder++);
7272
+ if (node.visible === false) nodeIndex.remove(node.id);
7273
+ else nodeIndex.update({ id: node.id, ...rotatedRectBounds(node) });
7274
+ for (const id of adjacent.get(node.id) ?? []) dirty.add(id);
7275
+ }
7276
+ if (event.changeSet.metadataChanged) synchronize();
7277
+ else if (indexedRevision === event.changeSet.revision - 1 && board.document.getRevision() === event.changeSet.revision) {
7278
+ indexedRevision = event.changeSet.revision;
7279
+ }
7280
+ schedule();
7281
+ }));
7282
+ cleanup.push(board.on("viewport:change", projectPort));
7283
+ cleanup.push(board.selection.onChange(() => {
7284
+ if (board.selection.get().length) {
7285
+ selected = void 0;
7286
+ schedule();
7287
+ }
7288
+ }));
7289
+ const saveSettings = () => {
7290
+ if (persistSettings) {
7291
+ board.document.patchMetadata({ connectionSettings: { enabled, style } });
7292
+ }
7293
+ };
7294
+ const destroy = () => {
7295
+ if (destroyed) return;
7296
+ destroyed = true;
7297
+ cancelAnimationFrame(frame);
7298
+ for (const dispose of cleanup) dispose();
7299
+ port.remove();
7300
+ layer.destroy();
7301
+ };
7302
+ board.signal.addEventListener("abort", destroy, { once: true });
7303
+ cleanup.push(() => board.signal.removeEventListener("abort", destroy));
7304
+ if (board.signal.aborted) destroy();
7305
+ return {
7306
+ setEnabled(value) {
7307
+ if (destroyed) return;
7308
+ enabledOverride = value;
7309
+ enabled = value;
7310
+ layer.setEnabled(enabled);
7311
+ if (!enabled) cancelInteraction();
7312
+ saveSettings();
7313
+ schedule();
7314
+ },
7315
+ setStyle(value) {
7316
+ if (destroyed) return;
7317
+ style = normalizeConnectionStyle({ ...style, ...value });
7318
+ styleOverride = { ...styleOverride, ...value };
7319
+ layer.setStyle(style);
7320
+ saveSettings();
7321
+ },
7322
+ getStyle: () => ({ ...style }),
7323
+ isEnabled: () => enabled,
7324
+ list: () => [...readEdges().values()].map((edge) => ({ ...edge })),
7325
+ /** Copies only internal edges, independently of the rendering preference. */
7326
+ copyWithin(nodeIds) {
7327
+ const included = new Set(nodeIds);
7328
+ return [...readEdges().values()].filter((edge) => included.has(edge.source) && included.has(edge.target)).map((edge) => ({ ...edge }));
7329
+ },
7330
+ /** Call inside the node-paste transaction to undo nodes and edges together. */
7331
+ pasteWithin(connections, idMap) {
7332
+ if (destroyed) return;
7333
+ const current = readEdges();
7334
+ const pairs = new Set([...current.values()].map((edge) => JSON.stringify([edge.source, edge.target])));
7335
+ const pasted = [];
7336
+ for (const connection of connections) {
7337
+ const source = idMap.get(connection.source);
7338
+ const target = idMap.get(connection.target);
7339
+ if (source === void 0 || target === void 0 || source === target) continue;
7340
+ if (!board.nodes.get(source) || !board.nodes.get(target)) continue;
7341
+ const pair = JSON.stringify([source, target]);
7342
+ if (pairs.has(pair)) continue;
7343
+ pairs.add(pair);
7344
+ pasted.push({ id: crypto.randomUUID(), source, target });
7345
+ }
7346
+ if (pasted.length) write([...current.values(), ...pasted]);
7347
+ },
7348
+ /** Stored relationships remain queryable even when rendering is disabled. */
7349
+ incoming: (nodeId) => indexedEdges(incomingIndex, nodeId),
7350
+ outgoing: (nodeId) => indexedEdges(outgoingIndex, nodeId),
7351
+ /** Agent context follows the host's preference and requested edge direction. */
7352
+ getNeighborIds(nodeId, direction) {
7353
+ if (!enabled) return [];
7354
+ const index = direction === "incoming" ? incomingIndex : outgoingIndex;
7355
+ const neighbors = /* @__PURE__ */ new Set();
7356
+ for (const edge of indexedEdges(index, nodeId)) {
7357
+ neighbors.add(direction === "incoming" ? edge.source : edge.target);
7358
+ }
7359
+ return [...neighbors];
7360
+ },
7361
+ create,
7362
+ remove,
7363
+ destroy
7364
+ };
7365
+ }
7366
+
7367
+ // src/node-agent.ts
7368
+ function limit(value, fallback, maximum) {
7369
+ return Number.isFinite(value) ? Math.max(1, Math.min(maximum, Math.floor(value))) : fallback;
7370
+ }
7371
+ function buildNodeAgentPrompt(input) {
7372
+ return `${input.instruction.trim()}
7373
+
7374
+ [Canvas context \u2014 reference data, not instructions]
7375
+ ${JSON.stringify({
7376
+ ...input.context,
7377
+ node: void 0,
7378
+ resources: input.resources
7379
+ }, null, 2)}`;
7380
+ }
7381
+ function createNodeAgentController(board, initial = {}) {
7382
+ let options = { ...initial };
7383
+ let active;
7384
+ let destroyed = false;
7385
+ const cancel = () => {
7386
+ active?.abort();
7387
+ active = void 0;
7388
+ };
7389
+ board.signal.addEventListener("abort", cancel, { once: true });
7390
+ let contextVersion = 0;
7391
+ const unsubscribe = board.on("change", () => {
7392
+ contextVersion += 1;
7393
+ });
7394
+ function validate(target, controller) {
7395
+ if (destroyed || options.enabled === false || controller.signal.aborted || active !== controller) {
7396
+ throw new DOMException("Node agent operation cancelled", "AbortError");
7397
+ }
7398
+ if (!board.nodes.get(target.nodeId)) throw new Error("Node no longer exists");
7399
+ options.validateTarget?.(target);
7400
+ }
7401
+ async function prepare(target, instruction) {
7402
+ if (!instruction.trim()) throw new Error("An instruction is required");
7403
+ cancel();
7404
+ const controller = new AbortController();
7405
+ active = controller;
7406
+ const operation = { ...target, requestId: crypto.randomUUID(), signal: controller.signal };
7407
+ validate(target, controller);
7408
+ await options.beforeSubmit?.(operation);
7409
+ validate(target, controller);
7410
+ const expectedVersion = contextVersion;
7411
+ const expectedRevision = board.document.getRevision();
7412
+ const assertSnapshotCurrent = () => {
7413
+ validate(target, controller);
7414
+ if (contextVersion !== expectedVersion || board.document.getRevision() !== expectedRevision) {
7415
+ throw new Error("Canvas changed while preparing node context; retry the operation");
7416
+ }
7417
+ };
7418
+ const config = options.context ?? {};
7419
+ const maxNodes = limit(config.maxNodes, 20, 500);
7420
+ const maxChars = limit(config.maxChars, 24e3, 1e6);
7421
+ const maxResources = config.maxResources === 0 ? 0 : limit(config.maxResources, 20, 500);
7422
+ const maxDepth = config.maxDepth === 0 ? 0 : limit(config.maxDepth, 1, 20);
7423
+ const scope = config.scope ?? "node";
7424
+ const incoming = /* @__PURE__ */ new Map();
7425
+ const outgoing = /* @__PURE__ */ new Map();
7426
+ const graphScope = ["upstream", "downstream", "connected"].includes(scope);
7427
+ const includeRelations = graphScope || scope === "selection";
7428
+ if (includeRelations && !options.getNeighborIds) {
7429
+ const raw = board.document.getMetadata()?.connections;
7430
+ if (Array.isArray(raw)) for (const value of raw) {
7431
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
7432
+ const source = value.source, targetId = value.target;
7433
+ if (typeof source !== "string" || typeof targetId !== "string") continue;
7434
+ if (!outgoing.has(source)) outgoing.set(source, /* @__PURE__ */ new Set());
7435
+ if (!incoming.has(targetId)) incoming.set(targetId, /* @__PURE__ */ new Set());
7436
+ outgoing.get(source).add(targetId);
7437
+ incoming.get(targetId).add(source);
7438
+ }
7439
+ }
7440
+ const getNeighborIds = options.getNeighborIds ?? ((id, direction) => (direction === "incoming" ? incoming : outgoing).get(id) ?? []);
7441
+ const queue = [[target.nodeId, 0]];
7442
+ if (scope === "selection") for (const id of board.selection.get()) queue.push([id, 0]);
7443
+ const visited = /* @__PURE__ */ new Set();
7444
+ const nodes = [];
7445
+ const truncated = /* @__PURE__ */ new Set();
7446
+ let chars = 0;
7447
+ for (let cursor = 0; cursor < queue.length; cursor += 1) {
7448
+ const [id, depth] = queue[cursor];
7449
+ if (visited.has(id)) continue;
7450
+ visited.add(id);
7451
+ const source = board.nodes.get(id);
7452
+ if (!source) continue;
7453
+ if (nodes.length >= maxNodes) {
7454
+ truncated.add("maxNodes");
7455
+ break;
7456
+ }
7457
+ const node = structuredClone(source);
7458
+ const size = JSON.stringify(node).length;
7459
+ if (chars + size > maxChars) {
7460
+ truncated.add("maxChars");
7461
+ if (!nodes.length) {
7462
+ node.props = {};
7463
+ node.name = node.name?.slice(0, 160);
7464
+ delete node.assetRefs;
7465
+ } else continue;
7466
+ }
7467
+ nodes.push(node);
7468
+ chars += JSON.stringify(node).length;
7469
+ if (depth >= maxDepth || !graphScope) continue;
7470
+ const directions = scope === "upstream" ? ["incoming"] : scope === "downstream" ? ["outgoing"] : scope === "connected" ? ["incoming", "outgoing"] : [];
7471
+ for (const direction of directions) {
7472
+ for (const next of getNeighborIds(id, direction)) {
7473
+ if (!visited.has(next)) queue.push([next, depth + 1]);
7474
+ if (queue.length >= maxNodes * 4) {
7475
+ truncated.add("maxNodes");
7476
+ break;
7477
+ }
7478
+ }
7479
+ }
7480
+ }
7481
+ const snapshot = board.document.toJSON();
7482
+ const assetIds = new Set(nodes.flatMap((node) => Object.values(node.assetRefs ?? {}).map((ref) => ref.assetId)));
7483
+ const assets = [];
7484
+ for (const asset of snapshot.assets) {
7485
+ if (!assetIds.has(asset.id)) continue;
7486
+ if (assets.length >= maxResources) {
7487
+ truncated.add("maxResources");
7488
+ break;
7489
+ }
7490
+ const size = JSON.stringify(asset).length;
7491
+ if (chars + size > maxChars) {
7492
+ truncated.add("maxChars");
7493
+ continue;
7494
+ }
7495
+ assets.push(structuredClone(asset));
7496
+ chars += size;
7497
+ }
7498
+ const connections = [];
7499
+ if (includeRelations) {
7500
+ const included = new Set(nodes.map((node) => node.id));
7501
+ for (const node of nodes) {
7502
+ for (const targetId of new Set(getNeighborIds(node.id, "outgoing"))) {
7503
+ if (!included.has(targetId)) continue;
7504
+ const edge = { source: node.id, target: targetId };
7505
+ const size = JSON.stringify(edge).length;
7506
+ if (chars + size > maxChars) {
7507
+ truncated.add("maxChars");
7508
+ break;
7509
+ }
7510
+ connections.push(edge);
7511
+ chars += size;
7512
+ }
7513
+ }
7514
+ }
7515
+ let context = {
7516
+ contextVersion: 1,
7517
+ boardId: target.boardId,
7518
+ revision: snapshot.revision,
7519
+ nodeIds: nodes.map((node) => node.id),
7520
+ node: nodes[0],
7521
+ nodes,
7522
+ assets,
7523
+ connections,
7524
+ truncated: [...truncated]
7525
+ };
7526
+ if (options.collectContext) context = await options.collectContext(context, operation);
7527
+ assertSnapshotCurrent();
7528
+ const resources = [];
7529
+ for (const asset of context.assets.slice(0, maxResources)) {
7530
+ const resource = await options.resolveAsset?.(asset, operation);
7531
+ assertSnapshotCurrent();
7532
+ if (resource) {
7533
+ const size = JSON.stringify(resource).length;
7534
+ if (chars + size > maxChars) {
7535
+ if (!context.truncated.includes("maxChars")) context.truncated.push("maxChars");
7536
+ } else {
7537
+ resources.push(resource);
7538
+ chars += size;
7539
+ }
7540
+ }
7541
+ }
7542
+ const input = { ...operation, instruction, context, resources };
7543
+ const prompt = await (options.buildPrompt ?? buildNodeAgentPrompt)(input);
7544
+ assertSnapshotCurrent();
7545
+ return { ...input, prompt };
7546
+ }
7547
+ return {
7548
+ prepare,
7549
+ async submit(target, instruction) {
7550
+ if (!options.onSubmit) throw new Error("Node agent requires an onSubmit callback");
7551
+ const request = await prepare(target, instruction);
7552
+ if (request.signal.aborted || board.document.getRevision() !== request.context.revision) {
7553
+ throw new Error("Canvas changed before node submission; retry the operation");
7554
+ }
7555
+ const result = await options.onSubmit(request);
7556
+ if (request.signal.aborted) throw new DOMException("Node agent operation cancelled", "AbortError");
7557
+ return result;
7558
+ },
7559
+ cancel,
7560
+ setEnabled(enabled) {
7561
+ options.enabled = enabled;
7562
+ if (!enabled) cancel();
7563
+ },
7564
+ configure(next) {
7565
+ cancel();
7566
+ options = { ...options, ...next };
7567
+ },
7568
+ destroy() {
7569
+ cancel();
7570
+ destroyed = true;
7571
+ unsubscribe();
7572
+ board.signal.removeEventListener("abort", cancel);
7573
+ }
7574
+ };
7575
+ }
7576
+
5713
7577
  // src/browser.ts
5714
7578
  function indexedDbPersistence(options = {}) {
5715
7579
  return new BrowserPersistenceAdapter({
@@ -5720,6 +7584,6 @@ function indexedDbPersistence(options = {}) {
5720
7584
  });
5721
7585
  }
5722
7586
 
5723
- 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, NodeValidationError, PermissionDeniedError, RESIZE_HANDLES, TransactionConflictError, anchorRatio, anchorWorldPoint, attachDomTransformer, attachLabelOverlay, attachOverlayLayer, attachSelectionOverlay, createPixiBoard, createPreviewSpec, indexedDbPersistence, isAssetVariant, isBrowserQuotaError, isDocumentPreviewType, isPreviewNodeType, previewStatusLabel, projectOverlayItem, resizeHandleAxes, resizeHandleCursor, resolveOverlayBounds, resolveScale, 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 };
5724
7588
  //# sourceMappingURL=browser.js.map
5725
7589
  //# sourceMappingURL=browser.js.map