pixiboardjs 0.1.0-alpha.5 → 0.1.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +30 -5
  3. package/VERSIONING.md +9 -7
  4. package/dist/agent-tools-schemas.d.ts +18 -0
  5. package/dist/agent-tools-schemas.js +4 -0
  6. package/dist/agent-tools-schemas.js.map +1 -0
  7. package/dist/agent-tools.d.ts +140 -0
  8. package/dist/agent-tools.js +124 -0
  9. package/dist/agent-tools.js.map +1 -0
  10. package/dist/browser.d.ts +12 -6
  11. package/dist/browser.js +57 -4405
  12. package/dist/browser.js.map +1 -1
  13. package/dist/capabilities.d.ts +14 -0
  14. package/dist/capabilities.js +5 -0
  15. package/dist/capabilities.js.map +1 -0
  16. package/dist/chunk-AYOOOEXM.js +27 -0
  17. package/dist/chunk-AYOOOEXM.js.map +1 -0
  18. package/dist/chunk-KQHR2G24.js +2257 -0
  19. package/dist/chunk-KQHR2G24.js.map +1 -0
  20. package/dist/chunk-NPEG2TBO.js +2353 -0
  21. package/dist/chunk-NPEG2TBO.js.map +1 -0
  22. package/dist/chunk-PZ5AY32C.js +9 -0
  23. package/dist/chunk-PZ5AY32C.js.map +1 -0
  24. package/dist/chunk-SNUXC33Q.js +560 -0
  25. package/dist/chunk-SNUXC33Q.js.map +1 -0
  26. package/dist/core-B_8DmBaT.d.ts +294 -0
  27. package/dist/core.d.ts +11 -0
  28. package/dist/core.js +4 -0
  29. package/dist/core.js.map +1 -0
  30. package/dist/errors-CEQ_RiJ_.d.ts +27 -0
  31. package/dist/index.d.ts +9 -73
  32. package/dist/index.js +4 -4356
  33. package/dist/index.js.map +1 -1
  34. package/dist/node.d.ts +8 -2
  35. package/dist/node.js +4 -4356
  36. package/dist/node.js.map +1 -1
  37. package/dist/plugin.d.ts +88 -0
  38. package/dist/plugin.js +37 -0
  39. package/dist/plugin.js.map +1 -0
  40. package/dist/preview-registry-BjdGxaWe.d.ts +115 -0
  41. package/dist/resize-BK1wOjTc.d.ts +120 -0
  42. package/dist/types-BEsq8g6W.d.ts +199 -0
  43. package/dist/types-BskqWTyl.d.ts +224 -0
  44. package/dist/types.d.ts +416 -1
  45. package/etc/pixiboardjs-agent-tools-schemas.api.md +29 -0
  46. package/etc/pixiboardjs-agent-tools.api.md +288 -0
  47. package/etc/pixiboardjs-browser.api.md +1913 -1755
  48. package/etc/pixiboardjs-capabilities.api.md +366 -0
  49. package/etc/pixiboardjs-core.api.md +725 -0
  50. package/etc/pixiboardjs-node.api.md +1020 -862
  51. package/etc/pixiboardjs-plugin.api.md +129 -0
  52. package/etc/pixiboardjs-types.api.md +836 -755
  53. package/etc/pixiboardjs.api.md +1020 -862
  54. package/package.json +39 -5
  55. package/src/node-media-provider.d.ts +195 -0
  56. package/src/node-media-provider.mjs +139 -0
  57. package/dist/tsdoc-metadata.json +0 -11
  58. package/dist/types-D39-tYZ8.d.ts +0 -789
package/dist/browser.js CHANGED
@@ -1,4357 +1,9 @@
1
- import { Container, Graphics } from 'pixi.js';
2
-
3
- var __defProp = Object.defineProperty;
4
- var __export = (target, all) => {
5
- for (var name in all)
6
- __defProp(target, name, { get: all[name], enumerable: true });
7
- };
8
-
9
- // ../core/src/index.ts
10
- var src_exports = {};
11
- __export(src_exports, {
12
- BoardAssetsController: () => BoardAssetsController,
13
- BoardCore: () => BoardCore,
14
- BoardDocumentController: () => BoardDocumentController,
15
- BoardNodesController: () => BoardNodesController,
16
- BoardViewportController: () => BoardViewportController,
17
- DocumentValidationError: () => DocumentValidationError,
18
- NodeNotFoundError: () => NodeNotFoundError,
19
- NodeTypeNotRegisteredError: () => NodeTypeNotRegisteredError,
20
- NodeTypeRegistry: () => NodeTypeRegistry,
21
- NodeValidationError: () => NodeValidationError,
22
- PixiBoardCoreError: () => PixiBoardCoreError,
23
- RESIZE_HANDLES: () => RESIZE_HANDLES,
24
- SelectionController: () => SelectionController,
25
- TransactionConflictError: () => TransactionConflictError,
26
- ViewportController: () => ViewportController,
27
- assertWorldBounds: () => assertWorldBounds,
28
- createBoardCore: () => createBoardCore,
29
- createPreviewSpec: () => createPreviewSpec,
30
- isAssetVariant: () => isAssetVariant,
31
- isDocumentPreviewType: () => isDocumentPreviewType,
32
- isPreviewNodeType: () => isPreviewNodeType,
33
- isResizeHandle: () => isResizeHandle,
34
- mergeBounds: () => mergeBounds,
35
- nodeGeometry: () => nodeGeometry,
36
- previewStatusLabel: () => previewStatusLabel,
37
- resizeHandleAxes: () => resizeHandleAxes,
38
- resizeHandleCursor: () => resizeHandleCursor,
39
- resolveResize: () => resolveResize,
40
- resolveResizeSize: () => resolveResizeSize,
41
- rotatedRectBounds: () => rotatedRectBounds
42
- });
43
-
44
- // ../core/src/asset-variant.ts
45
- function isAssetVariant(value) {
46
- return value === "original" || value === "preview" || value === "waveform" || typeof value === "string" && value.length === 72 && /^preview-[a-f0-9]{64}$/.test(value);
47
- }
48
-
49
- // ../core/src/asset-previews.ts
50
- function isDocumentPreviewType(type) {
51
- return type === "html" || type === "markdown" || type === "text-file" || type === "file";
52
- }
53
- function isPreviewNodeType(type) {
54
- return isDocumentPreviewType(type) || type === "model";
55
- }
56
- function record(value) {
57
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
58
- }
59
- function positiveNumber(value, fallback) {
60
- const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
61
- return Number.isFinite(number) && number > 0 ? number : fallback;
62
- }
63
- function createPreviewSpec(node, options = {}) {
64
- const saved = record(record(node.props).previewSpec);
65
- const defaultHeight = node.type === "model" ? 768 : 704;
66
- let width = positiveNumber(saved.width, 1024);
67
- let height = positiveNumber(saved.height, defaultHeight);
68
- let mode = saved.mode === "fixed-viewport" ? "fixed-viewport" : "viewport";
69
- let quality = options.quality === "detail" || options.quality === "thumbnail" ? options.quality : saved.quality === "detail" ? "detail" : "thumbnail";
70
- if (options.reason === "reset" || options.reason === "refresh") {
71
- const ratio = typeof node.width === "number" && Number.isFinite(node.width) && node.width > 0 && typeof node.height === "number" && Number.isFinite(node.height) && node.height > 0 ? node.height / node.width : defaultHeight / 1024;
72
- height = positiveNumber(width * ratio, defaultHeight);
73
- mode = "fixed-viewport";
74
- quality = options.quality === "thumbnail" ? "thumbnail" : "detail";
75
- }
76
- if (options.width !== void 0) width = positiveNumber(options.width, 1024);
77
- if (options.height !== void 0) height = positiveNumber(options.height, defaultHeight);
78
- const sideScale = Math.min(1, 4096 / width, 4096 / height);
79
- width *= sideScale;
80
- height *= sideScale;
81
- const areaScale = Math.min(1, Math.sqrt(8e6 / (width * height)));
82
- width = Math.max(1, Math.min(4096, Math.round(width * areaScale)));
83
- height = Math.max(1, Math.min(4096, Math.round(height * areaScale)));
84
- if (width * height > 8e6) height = Math.max(1, Math.floor(8e6 / width));
85
- const pageValue = options.page === void 0 ? saved.page : options.page;
86
- const page = Math.min(Number.MAX_SAFE_INTEGER, Math.max(1, Math.round(positiveNumber(pageValue, 1))));
87
- return { width, height, page, mode, quality };
88
- }
89
- function previewStatusLabel(node, typeLabel) {
90
- const props = record(node.props);
91
- const name = typeof props.name === "string" ? props.name : node.name ?? "";
92
- const isZip = typeof props.fileExtension === "string" && props.fileExtension.toLowerCase() === "zip" || /\.zip$/i.test(name);
93
- if (isZip && (node.type !== "model" || typeof props.previewError === "string" && /ZIP_NO_MODEL/.test(props.previewError))) {
94
- typeLabel = "ZIP";
95
- }
96
- switch (props.previewStatus) {
97
- case "pending":
98
- case "queued":
99
- case "running":
100
- return `${typeLabel}:\u9884\u89C8\u751F\u6210\u4E2D`;
101
- case "error":
102
- case "failed":
103
- case "unsupported":
104
- return `${typeLabel}:\u6682\u65E0\u9884\u89C8`;
105
- default:
106
- return typeLabel;
107
- }
108
- }
109
-
110
- // ../core/src/errors.ts
111
- var PixiBoardCoreError = class extends Error {
112
- constructor(message) {
113
- super(message);
114
- this.name = new.target.name;
115
- }
116
- };
117
- var NodeNotFoundError = class extends PixiBoardCoreError {
118
- constructor(nodeId) {
119
- super(`Node not found: ${nodeId}`);
120
- }
121
- };
122
- var NodeTypeNotRegisteredError = class extends PixiBoardCoreError {
123
- constructor(type) {
124
- super(`Node type is not registered: ${type}`);
125
- }
126
- };
127
- var NodeValidationError = class extends PixiBoardCoreError {
128
- nodeId;
129
- nodeType;
130
- cause;
131
- constructor(message, options = {}) {
132
- super(message);
133
- this.nodeId = options.nodeId;
134
- this.nodeType = options.nodeType;
135
- this.cause = options.cause;
136
- }
137
- };
138
- var DocumentValidationError = class extends PixiBoardCoreError {
139
- cause;
140
- constructor(message, options = {}) {
141
- super(message);
142
- this.cause = options.cause;
143
- }
144
- };
145
- var TransactionConflictError = class extends PixiBoardCoreError {
146
- };
147
-
148
- // ../core/src/json.ts
149
- function cloneValue(value) {
150
- return structuredClone(value);
151
- }
152
- function immutableClone(value) {
153
- return deepFreeze(cloneValue(value));
154
- }
155
- function deepFreeze(value) {
156
- if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
157
- Object.freeze(value);
158
- for (const child of Object.values(value)) {
159
- deepFreeze(child);
160
- }
161
- }
162
- return value;
163
- }
164
- function assertJsonValue(value, path = "value", ancestors = /* @__PURE__ */ new WeakSet()) {
165
- if (value === null || typeof value === "string" || typeof value === "boolean") {
166
- return;
167
- }
168
- if (typeof value === "number") {
169
- if (!Number.isFinite(value)) {
170
- throw new DocumentValidationError(`${path} must contain only finite numbers`);
171
- }
172
- return;
173
- }
174
- if (Array.isArray(value)) {
175
- assertNotCircular(value, path, ancestors);
176
- value.forEach((item, index) => assertJsonValue(item, `${path}[${index}]`, ancestors));
177
- ancestors.delete(value);
178
- return;
179
- }
180
- if (typeof value === "object") {
181
- const prototype = Object.getPrototypeOf(value);
182
- if (prototype !== Object.prototype && prototype !== null) {
183
- throw new DocumentValidationError(`${path} must be a plain JSON object`);
184
- }
185
- if (Reflect.ownKeys(value).some((key) => typeof key !== "string")) {
186
- throw new DocumentValidationError(`${path} must not contain symbol keys`);
187
- }
188
- assertNotCircular(value, path, ancestors);
189
- for (const [key, item] of Object.entries(value)) {
190
- assertJsonValue(item, `${path}.${key}`, ancestors);
191
- }
192
- ancestors.delete(value);
193
- return;
194
- }
195
- throw new DocumentValidationError(`${path} is not JSON-serializable`);
196
- }
197
- function assertNotCircular(value, path, ancestors) {
198
- if (ancestors.has(value)) {
199
- throw new DocumentValidationError(`${path} must not contain circular references`);
200
- }
201
- ancestors.add(value);
202
- }
203
- function jsonEqual(left, right) {
204
- return JSON.stringify(left) === JSON.stringify(right);
205
- }
206
-
207
- // ../core/src/document-validation.ts
208
- function validateDocument(input, options) {
209
- const value = parseInput(input);
210
- if (!isRecord(value)) throw new DocumentValidationError("Document must be an object");
211
- const sourceVersion = readInteger(value, "schemaVersion", "document");
212
- if (sourceVersion > options.schemaVersion) {
213
- throw new DocumentValidationError(
214
- `Document schema ${sourceVersion} is newer than supported schema ${options.schemaVersion}`
215
- );
216
- }
217
- if (sourceVersion < options.schemaVersion) {
218
- throw new DocumentValidationError(
219
- `Document schema ${sourceVersion} is older than supported schema ${options.schemaVersion}`
220
- );
221
- }
222
- assertJsonValue(value, "document");
223
- if (!isRecord(value)) throw new DocumentValidationError("Document must be an object");
224
- const schemaVersion = readInteger(value, "schemaVersion", "document");
225
- const revision = readInteger(value, "revision", "document");
226
- if (schemaVersion < 1) throw new DocumentValidationError("schemaVersion must be positive");
227
- if (revision < 0) throw new DocumentValidationError("revision must not be negative");
228
- if (!Array.isArray(value.nodes)) throw new DocumentValidationError("document.nodes must be an array");
229
- if (!Array.isArray(value.assets)) throw new DocumentValidationError("document.assets must be an array");
230
- const nodeIds = /* @__PURE__ */ new Set();
231
- const nodes = value.nodes.map((node, index) => {
232
- const validated = validateNode(node, `document.nodes[${index}]`);
233
- if (nodeIds.has(validated.id)) {
234
- throw new DocumentValidationError(`Duplicate node id: ${validated.id}`);
235
- }
236
- nodeIds.add(validated.id);
237
- try {
238
- return options.nodeTypes.validateNode(validated);
239
- } catch (cause) {
240
- if (cause instanceof NodeValidationError) throw cause;
241
- throw new NodeValidationError(`Invalid node ${validated.id}`, {
242
- nodeId: validated.id,
243
- nodeType: validated.type,
244
- cause
245
- });
246
- }
247
- });
248
- const assetIds = /* @__PURE__ */ new Set();
249
- const assets = value.assets.map((asset, index) => {
250
- const validated = validateAsset(asset, `document.assets[${index}]`);
251
- if (assetIds.has(validated.id)) {
252
- throw new DocumentValidationError(`Duplicate asset id: ${validated.id}`);
253
- }
254
- assetIds.add(validated.id);
255
- return validated;
256
- });
257
- if (value.viewport !== void 0) validateViewport(value.viewport, "document.viewport");
258
- if (value.metadata !== void 0 && !isRecord(value.metadata)) {
259
- throw new DocumentValidationError("document.metadata must be an object");
260
- }
261
- return {
262
- ...cloneValue(value),
263
- schemaVersion,
264
- revision,
265
- nodes,
266
- assets,
267
- ...value.viewport === void 0 ? {} : { viewport: cloneValue(value.viewport) }
268
- };
269
- }
270
- function validateNode(input, path = "node") {
271
- assertJsonValue(input, path);
272
- if (!isRecord(input)) throw new DocumentValidationError(`${path} must be an object`);
273
- if ("assetId" in input) {
274
- throw new DocumentValidationError(
275
- `${path}.assetId is not supported; use ${path}.assetRefs instead`
276
- );
277
- }
278
- const id = readString(input, "id", path);
279
- const type = readString(input, "type", path);
280
- const typeVersion = readInteger(input, "typeVersion", path);
281
- if (typeVersion < 1) throw new DocumentValidationError(`${path}.typeVersion must be positive`);
282
- for (const field of ["x", "y", "width", "height", "rotation", "zIndex"]) {
283
- readFiniteNumber(input, field, path);
284
- }
285
- if (input.width < 0 || input.height < 0) {
286
- throw new DocumentValidationError(`${path} width and height must not be negative`);
287
- }
288
- if (input.name !== void 0 && typeof input.name !== "string") {
289
- throw new DocumentValidationError(`${path}.name must be a string`);
290
- }
291
- if (input.locked !== void 0 && typeof input.locked !== "boolean") {
292
- throw new DocumentValidationError(`${path}.locked must be a boolean`);
293
- }
294
- if (input.visible !== void 0 && typeof input.visible !== "boolean") {
295
- throw new DocumentValidationError(`${path}.visible must be a boolean`);
296
- }
297
- if (!("props" in input)) throw new DocumentValidationError(`${path}.props is required`);
298
- if (input.assetRefs !== void 0) validateAssetRefs(input.assetRefs, `${path}.assetRefs`);
299
- return { ...cloneValue(input), id, type, typeVersion };
300
- }
301
- function validateAsset(input, path = "asset") {
302
- assertJsonValue(input, path);
303
- if (!isRecord(input)) throw new DocumentValidationError(`${path} must be an object`);
304
- const id = readString(input, "id", path);
305
- const kind = readString(input, "kind", path);
306
- if (input.metadata !== void 0 && !isRecord(input.metadata)) {
307
- throw new DocumentValidationError(`${path}.metadata must be an object`);
308
- }
309
- return { ...cloneValue(input), id, kind };
310
- }
311
- function validateViewport(input, path = "viewport") {
312
- assertJsonValue(input, path);
313
- if (!isRecord(input) || !isRecord(input.offset)) {
314
- throw new DocumentValidationError(`${path} must include an offset object`);
315
- }
316
- const scale = readFiniteNumber(input, "scale", path);
317
- const x = readFiniteNumber(input.offset, "x", `${path}.offset`);
318
- const y = readFiniteNumber(input.offset, "y", `${path}.offset`);
319
- if (scale <= 0) throw new DocumentValidationError(`${path}.scale must be greater than zero`);
320
- return { scale, offset: { x, y } };
321
- }
322
- function validateAssetRefs(input, path) {
323
- if (!isRecord(input)) throw new DocumentValidationError(`${path} must be an object`);
324
- for (const [name, ref] of Object.entries(input)) {
325
- if (!name || !isRecord(ref)) throw new DocumentValidationError(`${path}.${name} is invalid`);
326
- readString(ref, "assetId", `${path}.${name}`);
327
- if (ref.variant !== void 0 && !isAssetVariant(ref.variant)) {
328
- throw new DocumentValidationError(`${path}.${name}.variant is invalid`);
329
- }
330
- }
331
- }
332
- function parseInput(input) {
333
- if (typeof input !== "string") return cloneValue(input);
334
- try {
335
- return JSON.parse(input);
336
- } catch (cause) {
337
- throw new DocumentValidationError("Document JSON could not be parsed", { cause });
338
- }
339
- }
340
- function isRecord(value) {
341
- return value !== null && typeof value === "object" && !Array.isArray(value);
342
- }
343
- function readString(record2, key, path) {
344
- const value = record2[key];
345
- if (typeof value !== "string" || !value.trim()) {
346
- throw new DocumentValidationError(`${path}.${key} must be a non-empty string`);
347
- }
348
- return value;
349
- }
350
- function readInteger(record2, key, path) {
351
- const value = record2[key];
352
- if (!Number.isInteger(value)) {
353
- throw new DocumentValidationError(`${path}.${key} must be an integer`);
354
- }
355
- return value;
356
- }
357
- function readFiniteNumber(record2, key, path) {
358
- const value = record2[key];
359
- if (typeof value !== "number" || !Number.isFinite(value)) {
360
- throw new DocumentValidationError(`${path}.${key} must be a finite number`);
361
- }
362
- return value;
363
- }
364
-
365
- // ../core/src/geometry.ts
366
- function rotatedRectBounds(node) {
367
- const cos = Math.cos(node.rotation);
368
- const sin = Math.sin(node.rotation);
369
- const corners = [
370
- { x: 0, y: 0 },
371
- { x: node.width, y: 0 },
372
- { x: node.width, y: node.height },
373
- { x: 0, y: node.height }
374
- ].map((point) => ({
375
- x: node.x + point.x * cos - point.y * sin,
376
- y: node.y + point.x * sin + point.y * cos
377
- }));
378
- return {
379
- minX: Math.min(...corners.map(({ x }) => x)),
380
- minY: Math.min(...corners.map(({ y }) => y)),
381
- maxX: Math.max(...corners.map(({ x }) => x)),
382
- maxY: Math.max(...corners.map(({ y }) => y))
383
- };
384
- }
385
- function mergeBounds(bounds) {
386
- if (bounds.length === 0) return void 0;
387
- return {
388
- minX: Math.min(...bounds.map(({ minX }) => minX)),
389
- minY: Math.min(...bounds.map(({ minY }) => minY)),
390
- maxX: Math.max(...bounds.map(({ maxX }) => maxX)),
391
- maxY: Math.max(...bounds.map(({ maxY }) => maxY))
392
- };
393
- }
394
- function assertWorldBounds(bounds, label = "bounds") {
395
- const values = [bounds.minX, bounds.minY, bounds.maxX, bounds.maxY];
396
- if (!values.every(Number.isFinite) || bounds.maxX < bounds.minX || bounds.maxY < bounds.minY) {
397
- throw new RangeError(`${label} must be finite and normalized`);
398
- }
399
- }
400
-
401
- // ../core/src/history.ts
402
- var recordHistory = /* @__PURE__ */ Symbol("recordHistory");
403
- var HistoryController = class {
404
- constructor(host) {
405
- this.host = host;
406
- }
407
- host;
408
- undoStack = [];
409
- redoStack = [];
410
- listeners = /* @__PURE__ */ new Set();
411
- canUndo() {
412
- return this.undoStack.length > 0;
413
- }
414
- canRedo() {
415
- return this.redoStack.length > 0;
416
- }
417
- undo() {
418
- const entry = this.undoStack.at(-1);
419
- if (!entry) return void 0;
420
- const changeSet = this.host.applyHistoryEntry(entry, "undo");
421
- this.undoStack.pop();
422
- this.redoStack.push(entry);
423
- this.emit();
424
- return changeSet;
425
- }
426
- redo() {
427
- const entry = this.redoStack.at(-1);
428
- if (!entry) return void 0;
429
- const changeSet = this.host.applyHistoryEntry(entry, "redo");
430
- this.redoStack.pop();
431
- this.undoStack.push(entry);
432
- this.emit();
433
- return changeSet;
434
- }
435
- clear() {
436
- if (!this.canUndo() && !this.canRedo()) return;
437
- this.undoStack = [];
438
- this.redoStack = [];
439
- this.emit();
440
- }
441
- onChange(listener) {
442
- this.listeners.add(listener);
443
- return () => this.listeners.delete(listener);
444
- }
445
- [recordHistory](entry) {
446
- const previous = this.undoStack.at(-1);
447
- if (entry.coalesceKey !== void 0 && previous?.coalesceKey === entry.coalesceKey) {
448
- previous.forward = compactReplaces([...previous.forward, ...entry.forward]);
449
- previous.inverse = compactReplaces([...entry.inverse, ...previous.inverse]);
450
- this.redoStack = [];
451
- this.emit();
452
- return;
453
- }
454
- this.undoStack.push(entry);
455
- this.redoStack = [];
456
- this.emit();
457
- }
458
- emit() {
459
- const event = { canUndo: this.canUndo(), canRedo: this.canRedo() };
460
- for (const listener of this.listeners) {
461
- try {
462
- listener(event);
463
- } catch {
464
- }
465
- }
466
- }
467
- };
468
- function compactReplaces(patches) {
469
- if (patches.some((patch) => patch.op !== "node:replace" && patch.op !== "asset:replace")) {
470
- return patches;
471
- }
472
- const byKey = /* @__PURE__ */ new Map();
473
- for (const patch of patches) {
474
- const key = patch.op === "node:replace" ? `node:${patch.node.id}` : `asset:${patch.asset.id}`;
475
- byKey.set(key, patch);
476
- }
477
- return [...byKey.values()];
478
- }
479
- function createHistoryController(host) {
480
- const controller = new HistoryController(host);
481
- return {
482
- controller,
483
- record: (entry) => controller[recordHistory](entry)
484
- };
485
- }
486
-
487
- // ../core/src/node-type-registry.ts
488
- var NodeTypeRegistry = class {
489
- definitions = /* @__PURE__ */ new Map();
490
- development;
491
- constructor(options = {}) {
492
- this.development = options.development ?? false;
493
- }
494
- register(definition, options = {}) {
495
- assertDefinition(definition);
496
- const registered = freezeDefinition(definition);
497
- const existing = this.definitions.get(registered.type);
498
- if (existing && !options.replace) {
499
- throw new NodeValidationError(`Node type is already registered: ${registered.type}`);
500
- }
501
- if (existing && options.replace && !this.development) {
502
- throw new NodeValidationError(
503
- `Replacing node type definitions is only allowed in development: ${registered.type}`
504
- );
505
- }
506
- this.definitions.set(registered.type, registered);
507
- return () => {
508
- if (this.definitions.get(registered.type) === registered) {
509
- this.definitions.delete(registered.type);
510
- }
511
- };
512
- }
513
- has(type) {
514
- return this.definitions.has(type);
515
- }
516
- get(type) {
517
- return this.definitions.get(type);
518
- }
519
- require(type) {
520
- const definition = this.get(type);
521
- if (!definition) throw new NodeTypeNotRegisteredError(type);
522
- return definition;
523
- }
524
- list() {
525
- return [...this.definitions.values()];
526
- }
527
- createProps(type, props) {
528
- const definition = this.require(type);
529
- const input = mergeDefaults(definition.defaults, props);
530
- return {
531
- typeVersion: definition.version,
532
- props: this.runValidation(definition, input)
533
- };
534
- }
535
- validateNode(node) {
536
- const definition = this.get(node.type);
537
- if (!definition) return cloneValue(node);
538
- if (node.typeVersion !== definition.version) {
539
- throw new NodeValidationError(
540
- `Node ${node.id} uses ${node.type} typeVersion ${node.typeVersion}; registered version is ${definition.version}`,
541
- { nodeId: node.id, nodeType: node.type }
542
- );
543
- }
544
- return {
545
- ...cloneValue(node),
546
- typeVersion: node.typeVersion,
547
- props: this.runValidation(definition, node.props)
548
- };
549
- }
550
- getBounds(node) {
551
- const definition = this.require(node.type);
552
- return definition.getBounds(cloneValue(node));
553
- }
554
- runValidation(definition, value) {
555
- try {
556
- const validated = definition.validate(cloneValue(value));
557
- assertJsonValue(validated, `${definition.type}.props`);
558
- return cloneValue(validated);
559
- } catch (cause) {
560
- throw new NodeValidationError(`Invalid props for node type ${definition.type}`, {
561
- nodeType: definition.type,
562
- cause
563
- });
564
- }
565
- }
566
- };
567
- function assertDefinition(definition) {
568
- if (!definition.type.trim()) {
569
- throw new NodeValidationError("Node type must be a non-empty string");
570
- }
571
- if (!Number.isInteger(definition.version) || definition.version < 1) {
572
- throw new NodeValidationError(`Node type ${definition.type} must have a positive version`);
573
- }
574
- if (typeof definition.validate !== "function" || typeof definition.getBounds !== "function") {
575
- throw new NodeValidationError(
576
- `Node type ${definition.type} must define validate() and getBounds()`
577
- );
578
- }
579
- if (definition.defaults !== void 0) {
580
- assertJsonValue(definition.defaults, `${definition.type}.defaults`);
581
- }
582
- assertResizePolicy(definition);
583
- }
584
- function assertResizePolicy(definition) {
585
- const policy = definition.resize;
586
- if (policy === void 0) return;
587
- const modes = ["free", "aspect-ratio", "fixed", "custom"];
588
- if (!modes.includes(policy.mode)) {
589
- throw new NodeValidationError(
590
- `Node type ${definition.type} has an unknown resize mode: ${String(policy.mode)}`
591
- );
592
- }
593
- if (policy.mode === "custom" && typeof policy.resize !== "function") {
594
- throw new NodeValidationError(
595
- `Node type ${definition.type} declares resize mode "custom" without a resize() function`
596
- );
597
- }
598
- if (policy.mode === "aspect-ratio" && policy.ratio !== void 0 && (!Number.isFinite(policy.ratio) || policy.ratio <= 0)) {
599
- throw new NodeValidationError(
600
- `Node type ${definition.type} declares a non-positive aspect ratio`
601
- );
602
- }
603
- }
604
- function freezeDefinition(definition) {
605
- const registered = {
606
- ...definition,
607
- ...definition.defaults === void 0 ? {} : { defaults: deepFreeze(cloneValue(definition.defaults)) },
608
- ...definition.resize === void 0 ? {} : { resize: Object.freeze({ ...definition.resize }) }
609
- };
610
- return Object.freeze(registered);
611
- }
612
- function mergeDefaults(defaults, props) {
613
- if (isPlainObject(defaults) || isPlainObject(props)) {
614
- return {
615
- ...isPlainObject(defaults) ? cloneValue(defaults) : {},
616
- ...isPlainObject(props) ? cloneValue(props) : {}
617
- };
618
- }
619
- return props ?? defaults ?? null;
620
- }
621
- function isPlainObject(value) {
622
- return value !== null && typeof value === "object" && !Array.isArray(value);
623
- }
624
-
625
- // ../core/src/patches.ts
626
- function applyDataPatches(store, patches) {
627
- for (const patch of patches) {
628
- switch (patch.op) {
629
- case "metadata:replace":
630
- store.setMetadata(patch.metadata);
631
- break;
632
- case "node:insert":
633
- store.insertNode(patch.index, patch.node);
634
- break;
635
- case "node:replace":
636
- store.replaceNode(patch.node);
637
- break;
638
- case "node:remove":
639
- store.removeNode(patch.nodeId);
640
- break;
641
- case "asset:insert":
642
- store.insertAsset(patch.index, patch.asset);
643
- break;
644
- case "asset:replace":
645
- store.replaceAsset(patch.asset);
646
- break;
647
- case "asset:remove":
648
- store.removeAsset(patch.assetId);
649
- break;
650
- }
651
- }
652
- }
653
-
654
- // ../core/src/resize.ts
655
- var HANDLE_AXES = {
656
- nw: { horizontal: -1, vertical: -1 },
657
- n: { horizontal: 0, vertical: -1 },
658
- ne: { horizontal: 1, vertical: -1 },
659
- e: { horizontal: 1, vertical: 0 },
660
- se: { horizontal: 1, vertical: 1 },
661
- s: { horizontal: 0, vertical: 1 },
662
- sw: { horizontal: -1, vertical: 1 },
663
- w: { horizontal: -1, vertical: 0 }
664
- };
665
- var RESIZE_HANDLES = Object.freeze([
666
- "nw",
667
- "n",
668
- "ne",
669
- "e",
670
- "se",
671
- "s",
672
- "sw",
673
- "w"
674
- ]);
675
- function resizeHandleAxes(handle) {
676
- const axes = HANDLE_AXES[handle];
677
- if (!axes) throw new RangeError(`Unknown resize handle: ${String(handle)}`);
678
- return { ...axes };
679
- }
680
- var DEFAULT_MIN_SIZE = 1;
681
- function isResizeHandle(value) {
682
- return typeof value === "string" && value in HANDLE_AXES;
683
- }
684
- function nodeGeometry(node) {
685
- return { x: node.x, y: node.y, width: node.width, height: node.height, rotation: node.rotation };
686
- }
687
- function resolveResize(node, policy, request) {
688
- const axes = HANDLE_AXES[request.handle];
689
- if (!axes) throw new RangeError(`Unknown resize handle: ${String(request.handle)}`);
690
- if (!Number.isFinite(request.deltaWorld.x) || !Number.isFinite(request.deltaWorld.y)) {
691
- throw new RangeError("Resize delta must be finite");
692
- }
693
- const origin = request.origin ?? nodeGeometry(node);
694
- const localDelta = rotatePoint(request.deltaWorld, -origin.rotation);
695
- const resolved = resolveResizeSize(node, policy, {
696
- handle: request.handle,
697
- width: origin.width + axes.horizontal * localDelta.x,
698
- height: origin.height + axes.vertical * localDelta.y,
699
- origin,
700
- ...request.minWidth === void 0 ? {} : { minWidth: request.minWidth },
701
- ...request.minHeight === void 0 ? {} : { minHeight: request.minHeight }
702
- });
703
- if (!resolved) return {};
704
- const left = anchorOffset(axes.horizontal, origin.width, resolved.width);
705
- const top = anchorOffset(axes.vertical, origin.height, resolved.height);
706
- const offset = rotatePoint({ x: left, y: top }, origin.rotation);
707
- const patch = { ...resolved.patch, width: resolved.width, height: resolved.height };
708
- if (resolved.patch.x === void 0) patch.x = origin.x + offset.x;
709
- if (resolved.patch.y === void 0) patch.y = origin.y + offset.y;
710
- return patch;
711
- }
712
- function resolveResizeSize(node, policy, request) {
713
- const axes = HANDLE_AXES[request.handle];
714
- if (!axes) throw new RangeError(`Unknown resize handle: ${String(request.handle)}`);
715
- if (!Number.isFinite(request.width) || !Number.isFinite(request.height)) {
716
- throw new RangeError("Resize size must be finite");
717
- }
718
- const mode = policy?.mode ?? "free";
719
- if (mode === "fixed" || node.locked === true) return void 0;
720
- const origin = request.origin ?? nodeGeometry(node);
721
- const minWidth = Math.max(request.minWidth ?? DEFAULT_MIN_SIZE, 0);
722
- const minHeight = Math.max(request.minHeight ?? DEFAULT_MIN_SIZE, 0);
723
- let width = Math.max(request.width, minWidth);
724
- let height = Math.max(request.height, minHeight);
725
- if (mode === "aspect-ratio") {
726
- const constrained = constrainToRatio(
727
- { width, height },
728
- { width: origin.width, height: origin.height },
729
- axes,
730
- policy?.mode === "aspect-ratio" ? policy.ratio : void 0,
731
- { minWidth, minHeight }
732
- );
733
- width = constrained.width;
734
- height = constrained.height;
735
- }
736
- let patch = {};
737
- if (mode === "custom" && policy?.mode === "custom") {
738
- patch = policy.resize({ node, width, height });
739
- if (typeof patch.width === "number") width = Math.max(patch.width, 0);
740
- if (typeof patch.height === "number") height = Math.max(patch.height, 0);
741
- }
742
- return { width, height, patch };
743
- }
744
- function resizeHandleCursor(handle, rotation = 0) {
745
- const base2 = { n: 0, ne: 45, e: 90, se: 135, s: 180, sw: 225, w: 270, nw: 315 };
746
- const degrees = base2[handle] + rotation * 180 / Math.PI;
747
- const normalized = (degrees % 180 + 180) % 180;
748
- const names = ["ns", "nesw", "ew", "nwse"];
749
- return `${names[Math.round(normalized / 45) % 4]}-resize`;
750
- }
751
- function anchorOffset(axis, originSize, size) {
752
- if (axis === 1) return 0;
753
- if (axis === -1) return originSize - size;
754
- return (originSize - size) / 2;
755
- }
756
- function constrainToRatio(size, origin, axes, declaredRatio, limits) {
757
- const ratio = declaredRatio !== void 0 && Number.isFinite(declaredRatio) && declaredRatio > 0 ? declaredRatio : origin.height > 0 && origin.width > 0 ? origin.width / origin.height : 1;
758
- let { width, height } = size;
759
- if (axes.horizontal !== 0 && axes.vertical !== 0) {
760
- const widthDrives = Math.abs(width - origin.width) >= Math.abs(height - origin.height) * ratio;
761
- if (widthDrives) height = width / ratio;
762
- else width = height * ratio;
763
- } else if (axes.horizontal !== 0) {
764
- height = width / ratio;
765
- } else {
766
- width = height * ratio;
767
- }
768
- if (width < limits.minWidth) {
769
- width = limits.minWidth;
770
- height = width / ratio;
771
- }
772
- if (height < limits.minHeight) {
773
- height = limits.minHeight;
774
- width = height * ratio;
775
- }
776
- return { width, height };
777
- }
778
- function rotatePoint(point, angle) {
779
- if (!angle) return { x: point.x, y: point.y };
780
- const cos = Math.cos(angle);
781
- const sin = Math.sin(angle);
782
- return { x: point.x * cos - point.y * sin, y: point.x * sin + point.y * cos };
783
- }
784
-
785
- // ../core/src/selection.ts
786
- var SelectionController = class {
787
- constructor(nodeExists, beforeMutation = () => {
788
- }) {
789
- this.nodeExists = nodeExists;
790
- this.beforeMutation = beforeMutation;
791
- }
792
- nodeExists;
793
- beforeMutation;
794
- selected = /* @__PURE__ */ new Set();
795
- listeners = /* @__PURE__ */ new Set();
796
- get() {
797
- return [...this.selected];
798
- }
799
- set(nodeIds) {
800
- this.beforeMutation();
801
- const next = /* @__PURE__ */ new Set();
802
- for (const id of nodeIds) {
803
- if (this.nodeExists(id)) next.add(id);
804
- }
805
- this.commit(next);
806
- }
807
- toggle(nodeId) {
808
- this.beforeMutation();
809
- if (!this.nodeExists(nodeId)) return;
810
- const next = new Set(this.selected);
811
- if (next.has(nodeId)) next.delete(nodeId);
812
- else next.add(nodeId);
813
- this.commit(next);
814
- }
815
- clear() {
816
- this.beforeMutation();
817
- this.commit(/* @__PURE__ */ new Set());
818
- }
819
- onChange(listener) {
820
- this.listeners.add(listener);
821
- return () => this.listeners.delete(listener);
822
- }
823
- prune() {
824
- const next = new Set([...this.selected].filter((id) => this.nodeExists(id)));
825
- return this.commit(next);
826
- }
827
- commit(next) {
828
- const previous = [...this.selected];
829
- const current = [...next];
830
- if (sameIds(previous, current)) return false;
831
- this.selected = next;
832
- const event = { nodeIds: [...current], previousNodeIds: [...previous] };
833
- for (const listener of this.listeners) {
834
- try {
835
- listener(event);
836
- } catch {
837
- }
838
- }
839
- return true;
840
- }
841
- };
842
- function sameIds(left, right) {
843
- return left.length === right.length && left.every((id, index) => id === right[index]);
844
- }
845
-
846
- // ../core/src/store.ts
847
- var RuntimeDocumentStore = class _RuntimeDocumentStore {
848
- document;
849
- nodesById = /* @__PURE__ */ new Map();
850
- nodeOrder = /* @__PURE__ */ new Map();
851
- assetsById = /* @__PURE__ */ new Map();
852
- assetOrder = /* @__PURE__ */ new Map();
853
- nodeOverrides = /* @__PURE__ */ new Map();
854
- assetOverrides = /* @__PURE__ */ new Map();
855
- nodeOverridesShared = false;
856
- assetOverridesShared = false;
857
- nodesShared = false;
858
- assetsShared = false;
859
- constructor(document2) {
860
- this.document = cloneValue(document2);
861
- this.rebuildIndexes();
862
- }
863
- clone() {
864
- const clone = Object.create(_RuntimeDocumentStore.prototype);
865
- clone.document = { ...this.document, nodes: this.document.nodes, assets: this.document.assets };
866
- clone.nodesById = this.nodesById;
867
- clone.nodeOrder = this.nodeOrder;
868
- clone.assetsById = this.assetsById;
869
- clone.assetOrder = this.assetOrder;
870
- clone.nodeOverrides = this.nodeOverrides;
871
- clone.assetOverrides = this.assetOverrides;
872
- clone.nodeOverridesShared = true;
873
- clone.assetOverridesShared = true;
874
- clone.nodesShared = true;
875
- clone.assetsShared = true;
876
- return clone;
877
- }
878
- snapshot() {
879
- return immutableClone(this.materializedDocument());
880
- }
881
- mutableSnapshot() {
882
- return cloneValue(this.materializedDocument());
883
- }
884
- getMetadata() {
885
- return cloneValue(this.document.metadata);
886
- }
887
- setMetadata(value) {
888
- this.document.metadata = cloneValue(value);
889
- }
890
- get revision() {
891
- return this.document.revision;
892
- }
893
- set revision(value) {
894
- this.document.revision = value;
895
- }
896
- getNode(id) {
897
- const node = this.getNodeReference(id);
898
- return node ? cloneValue(node) : void 0;
899
- }
900
- getNodeReference(id) {
901
- return this.nodeOverrides.get(id) ?? this.nodesById.get(id);
902
- }
903
- requireNode(id) {
904
- const node = this.getNodeReference(id);
905
- if (!node) throw new NodeNotFoundError(id);
906
- return cloneValue(node);
907
- }
908
- getNodeIndex(id) {
909
- return this.nodeOrder.get(id);
910
- }
911
- listNodes() {
912
- return cloneValue(this.materializedNodes());
913
- }
914
- listNodesByIds(ids) {
915
- const nodes = [];
916
- for (const id of ids) {
917
- const node = this.getNodeReference(id);
918
- if (node) nodes.push(node);
919
- }
920
- nodes.sort((left, right) => (this.nodeOrder.get(left.id) ?? 0) - (this.nodeOrder.get(right.id) ?? 0));
921
- return cloneValue(nodes);
922
- }
923
- nodeCount() {
924
- return this.document.nodes.length;
925
- }
926
- forEachNodeReference(callback) {
927
- for (const node of this.document.nodes) callback(this.nodeOverrides.get(node.id) ?? node);
928
- }
929
- insertNode(index, node) {
930
- if (this.getNodeReference(node.id)) {
931
- throw new DocumentValidationError(`Duplicate node id: ${node.id}`);
932
- }
933
- if (!Number.isInteger(index) || index < 0 || index > this.document.nodes.length) {
934
- throw new RangeError(`Invalid node insertion index: ${index}`);
935
- }
936
- this.materializeNodesInPlace();
937
- this.document.nodes.splice(index, 0, cloneValue(node));
938
- this.rebuildNodeIndex();
939
- }
940
- replaceNode(node) {
941
- const index = this.nodeOrder.get(node.id);
942
- if (index === void 0) throw new NodeNotFoundError(node.id);
943
- this.ensureNodeOverridesMutable();
944
- this.nodeOverrides.set(node.id, cloneValue(node));
945
- }
946
- removeNode(id) {
947
- const index = this.getNodeIndex(id);
948
- if (index === void 0) throw new NodeNotFoundError(id);
949
- this.materializeNodesInPlace();
950
- const [removed] = this.document.nodes.splice(index, 1);
951
- this.rebuildNodeIndex();
952
- return cloneValue(removed);
953
- }
954
- getAsset(id) {
955
- const asset = this.getAssetReference(id);
956
- return asset ? cloneValue(asset) : void 0;
957
- }
958
- getAssetReference(id) {
959
- return this.assetOverrides.get(id) ?? this.assetsById.get(id);
960
- }
961
- getAssetIndex(id) {
962
- return this.assetOrder.get(id);
963
- }
964
- listAssets() {
965
- return cloneValue(this.materializedAssets());
966
- }
967
- assetCount() {
968
- return this.document.assets.length;
969
- }
970
- insertAsset(index, asset) {
971
- if (this.getAssetReference(asset.id)) {
972
- throw new DocumentValidationError(`Duplicate asset id: ${asset.id}`);
973
- }
974
- if (!Number.isInteger(index) || index < 0 || index > this.document.assets.length) {
975
- throw new RangeError(`Invalid asset insertion index: ${index}`);
976
- }
977
- this.materializeAssetsInPlace();
978
- this.document.assets.splice(index, 0, cloneValue(asset));
979
- this.rebuildAssetIndex();
980
- }
981
- replaceAsset(asset) {
982
- const index = this.assetOrder.get(asset.id);
983
- if (index === void 0) {
984
- throw new DocumentValidationError(`Asset not found: ${asset.id}`);
985
- }
986
- this.ensureAssetOverridesMutable();
987
- this.assetOverrides.set(asset.id, cloneValue(asset));
988
- }
989
- removeAsset(id) {
990
- const index = this.getAssetIndex(id);
991
- if (index === void 0) {
992
- throw new DocumentValidationError(`Asset not found: ${id}`);
993
- }
994
- this.materializeAssetsInPlace();
995
- const [removed] = this.document.assets.splice(index, 1);
996
- this.rebuildAssetIndex();
997
- return cloneValue(removed);
998
- }
999
- rebuildIndexes() {
1000
- this.rebuildNodeIndex();
1001
- this.rebuildAssetIndex();
1002
- }
1003
- rebuildNodeIndex() {
1004
- this.nodesById = /* @__PURE__ */ new Map();
1005
- this.nodeOrder = /* @__PURE__ */ new Map();
1006
- this.document.nodes.forEach((node, index) => {
1007
- if (this.nodesById.has(node.id)) {
1008
- throw new DocumentValidationError(`Duplicate node id: ${node.id}`);
1009
- }
1010
- this.nodesById.set(node.id, node);
1011
- this.nodeOrder.set(node.id, index);
1012
- });
1013
- }
1014
- rebuildAssetIndex() {
1015
- this.assetsById = /* @__PURE__ */ new Map();
1016
- this.assetOrder = /* @__PURE__ */ new Map();
1017
- this.document.assets.forEach((asset, index) => {
1018
- if (this.assetsById.has(asset.id)) {
1019
- throw new DocumentValidationError(`Duplicate asset id: ${asset.id}`);
1020
- }
1021
- this.assetsById.set(asset.id, asset);
1022
- this.assetOrder.set(asset.id, index);
1023
- });
1024
- }
1025
- ensureNodeOverridesMutable() {
1026
- if (!this.nodeOverridesShared) return;
1027
- this.nodeOverrides = new Map(this.nodeOverrides);
1028
- this.nodeOverridesShared = false;
1029
- }
1030
- ensureAssetOverridesMutable() {
1031
- if (!this.assetOverridesShared) return;
1032
- this.assetOverrides = new Map(this.assetOverrides);
1033
- this.assetOverridesShared = false;
1034
- }
1035
- materializeNodesInPlace() {
1036
- if (this.nodeOverrides.size === 0 && !this.nodesShared) return;
1037
- this.document = { ...this.document, nodes: this.materializedNodes().slice() };
1038
- this.nodeOverrides = /* @__PURE__ */ new Map();
1039
- this.nodeOverridesShared = false;
1040
- this.nodesShared = false;
1041
- this.rebuildNodeIndex();
1042
- }
1043
- materializeAssetsInPlace() {
1044
- if (this.assetOverrides.size === 0 && !this.assetsShared) return;
1045
- this.document = { ...this.document, assets: this.materializedAssets().slice() };
1046
- this.assetOverrides = /* @__PURE__ */ new Map();
1047
- this.assetOverridesShared = false;
1048
- this.assetsShared = false;
1049
- this.rebuildAssetIndex();
1050
- }
1051
- materializedNodes() {
1052
- if (this.nodeOverrides.size === 0) return this.document.nodes;
1053
- return this.document.nodes.map((node) => this.nodeOverrides.get(node.id) ?? node);
1054
- }
1055
- materializedAssets() {
1056
- if (this.assetOverrides.size === 0) return this.document.assets;
1057
- return this.document.assets.map((asset) => this.assetOverrides.get(asset.id) ?? asset);
1058
- }
1059
- materializedDocument() {
1060
- return {
1061
- ...this.document,
1062
- nodes: this.materializedNodes(),
1063
- assets: this.materializedAssets()
1064
- };
1065
- }
1066
- };
1067
-
1068
- // ../core/src/viewport.ts
1069
- var ViewportController = class {
1070
- constructor(initial = { scale: 1, offset: { x: 0, y: 0 } }, screen, beforeMutation = () => {
1071
- }) {
1072
- this.beforeMutation = beforeMutation;
1073
- assertViewport(initial);
1074
- if (screen !== void 0) assertSize(screen);
1075
- this.state = cloneViewport(initial);
1076
- this.screen = screen ? { ...screen } : { width: 1, height: 1 };
1077
- this.screenSizeKnown = screen !== void 0;
1078
- }
1079
- beforeMutation;
1080
- state;
1081
- screen;
1082
- /**
1083
- * Whether a host has told us how big the surface actually is. The
1084
- * constructor default is 1x1, which is a placeholder rather than a real
1085
- * measurement — reporting visible bounds from it would cull everything but a
1086
- * single world pixel, so visibleWorldBounds() stays undefined until a host
1087
- * calls setScreenSize().
1088
- */
1089
- screenSizeKnown;
1090
- listeners = /* @__PURE__ */ new Set();
1091
- get() {
1092
- return cloneViewport(this.state);
1093
- }
1094
- set(viewport) {
1095
- this.beforeMutation();
1096
- assertViewport(viewport);
1097
- this.commit(viewport);
1098
- }
1099
- setScreenSize(screen) {
1100
- this.beforeMutation();
1101
- assertSize(screen);
1102
- this.screen = { ...screen };
1103
- this.screenSizeKnown = true;
1104
- }
1105
- getScreenSize() {
1106
- return { ...this.screen };
1107
- }
1108
- /**
1109
- * The world rectangle the surface currently shows, grown by `padding` world
1110
- * units on every side so a renderer can keep a margin of ready views just
1111
- * outside the viewport. Returns undefined while the screen size is still
1112
- * unknown, which callers must read as "everything is visible" rather than
1113
- * "nothing is".
1114
- */
1115
- visibleWorldBounds(padding = 0) {
1116
- if (!this.screenSizeKnown) return void 0;
1117
- if (!Number.isFinite(padding) || padding < 0) {
1118
- throw new RangeError("visible bounds padding must be finite and non-negative");
1119
- }
1120
- const topLeft = this.toWorld({ x: 0, y: 0 });
1121
- const bottomRight = this.toWorld({ x: this.screen.width, y: this.screen.height });
1122
- return {
1123
- minX: topLeft.x - padding,
1124
- minY: topLeft.y - padding,
1125
- maxX: bottomRight.x + padding,
1126
- maxY: bottomRight.y + padding
1127
- };
1128
- }
1129
- panBy(deltaX, deltaY) {
1130
- this.beforeMutation();
1131
- assertFinite(deltaX, "deltaX");
1132
- assertFinite(deltaY, "deltaY");
1133
- this.commit({
1134
- scale: this.state.scale,
1135
- offset: {
1136
- x: this.state.offset.x + deltaX,
1137
- y: this.state.offset.y + deltaY
1138
- }
1139
- });
1140
- }
1141
- zoomAt(screenPoint, factor) {
1142
- this.beforeMutation();
1143
- assertPoint(screenPoint, "screenPoint");
1144
- if (!Number.isFinite(factor) || factor <= 0) {
1145
- throw new RangeError("zoom factor must be finite and greater than zero");
1146
- }
1147
- const worldPoint = this.toWorld(screenPoint);
1148
- const scale = this.state.scale * factor;
1149
- this.commit({
1150
- scale,
1151
- offset: {
1152
- x: screenPoint.x - worldPoint.x * scale,
1153
- y: screenPoint.y - worldPoint.y * scale
1154
- }
1155
- });
1156
- }
1157
- fitBounds(bounds, options = {}) {
1158
- this.beforeMutation();
1159
- assertWorldBounds(bounds);
1160
- const screen = options.screen ?? this.screen;
1161
- assertSize(screen);
1162
- const padding = options.padding ?? 72;
1163
- const maxScale = options.maxScale ?? 1;
1164
- if (!Number.isFinite(padding) || padding < 0) {
1165
- throw new RangeError("fit padding must be finite and non-negative");
1166
- }
1167
- if (!Number.isFinite(maxScale) || maxScale <= 0) {
1168
- throw new RangeError("fit maxScale must be finite and greater than zero");
1169
- }
1170
- const boundsWidth = Math.max(bounds.maxX - bounds.minX, 1);
1171
- const boundsHeight = Math.max(bounds.maxY - bounds.minY, 1);
1172
- const availableWidth = Math.max(screen.width - padding * 2, 1);
1173
- const availableHeight = Math.max(screen.height - padding * 2, 1);
1174
- const scale = Math.min(availableWidth / boundsWidth, availableHeight / boundsHeight, maxScale);
1175
- const centerX = (bounds.minX + bounds.maxX) / 2;
1176
- const centerY = (bounds.minY + bounds.maxY) / 2;
1177
- this.commit({
1178
- scale,
1179
- offset: {
1180
- x: screen.width / 2 - centerX * scale,
1181
- y: screen.height / 2 - centerY * scale
1182
- }
1183
- });
1184
- }
1185
- toWorld(screenPoint) {
1186
- assertPoint(screenPoint, "screenPoint");
1187
- return {
1188
- x: (screenPoint.x - this.state.offset.x) / this.state.scale,
1189
- y: (screenPoint.y - this.state.offset.y) / this.state.scale
1190
- };
1191
- }
1192
- toScreen(worldPoint) {
1193
- assertPoint(worldPoint, "worldPoint");
1194
- return {
1195
- x: worldPoint.x * this.state.scale + this.state.offset.x,
1196
- y: worldPoint.y * this.state.scale + this.state.offset.y
1197
- };
1198
- }
1199
- onChange(listener) {
1200
- this.listeners.add(listener);
1201
- return () => this.listeners.delete(listener);
1202
- }
1203
- commit(viewport) {
1204
- assertViewport(viewport);
1205
- const previousViewport = this.get();
1206
- if (previousViewport.scale === viewport.scale && previousViewport.offset.x === viewport.offset.x && previousViewport.offset.y === viewport.offset.y) {
1207
- return;
1208
- }
1209
- this.state = cloneViewport(viewport);
1210
- const event = { viewport: this.get(), previousViewport };
1211
- for (const listener of this.listeners) {
1212
- try {
1213
- listener(event);
1214
- } catch {
1215
- }
1216
- }
1217
- }
1218
- };
1219
- function assertViewport(viewport) {
1220
- if (!Number.isFinite(viewport.scale) || viewport.scale <= 0) {
1221
- throw new RangeError("viewport scale must be finite and greater than zero");
1222
- }
1223
- assertPoint(viewport.offset, "viewport offset");
1224
- }
1225
- function assertPoint(point, label) {
1226
- assertFinite(point.x, `${label}.x`);
1227
- assertFinite(point.y, `${label}.y`);
1228
- }
1229
- function assertSize(size) {
1230
- if (!Number.isFinite(size.width) || size.width <= 0 || !Number.isFinite(size.height) || size.height <= 0) {
1231
- throw new RangeError("screen size must be finite and greater than zero");
1232
- }
1233
- }
1234
- function assertFinite(value, label) {
1235
- if (!Number.isFinite(value)) throw new RangeError(`${label} must be finite`);
1236
- }
1237
- function cloneViewport(viewport) {
1238
- return { scale: viewport.scale, offset: { ...viewport.offset } };
1239
- }
1240
-
1241
- // ../core/src/core.ts
1242
- var coreInternals = /* @__PURE__ */ new WeakMap();
1243
- var BoardCore = class {
1244
- nodeTypes;
1245
- nodes;
1246
- assets;
1247
- selection;
1248
- viewport;
1249
- history;
1250
- document;
1251
- store;
1252
- schemaVersion;
1253
- idFactory;
1254
- now;
1255
- events = new EventHub();
1256
- activeTransaction;
1257
- rejectedAsyncTransactionCallbacks = 0;
1258
- viewportState;
1259
- recordHistory;
1260
- constructor(options = {}) {
1261
- this.nodeTypes = options.nodeTypes ?? new NodeTypeRegistry();
1262
- this.schemaVersion = options.schemaVersion ?? 1;
1263
- this.idFactory = options.idFactory ?? defaultIdFactory;
1264
- this.now = options.now ?? Date.now;
1265
- const document2 = options.document ? validateDocument(options.document, {
1266
- schemaVersion: this.schemaVersion,
1267
- nodeTypes: this.nodeTypes
1268
- }) : createEmptyDocument(this.schemaVersion);
1269
- this.store = new RuntimeDocumentStore(document2);
1270
- this.viewportState = new ViewportController(
1271
- document2.viewport ?? { scale: 1, offset: { x: 0, y: 0 } },
1272
- options.viewportSize,
1273
- () => this.assertSessionMutationAllowed()
1274
- );
1275
- coreInternals.set(this, {
1276
- mutate: (label, operation) => this.mutate(label, operation),
1277
- currentStore: () => this.currentStore(),
1278
- nextId: () => this.nextId(),
1279
- validateLoadedDocument: (input, loadOptions) => this.validateLoadedDocument(input, loadOptions),
1280
- loadDocument: (input, loadOptions) => this.loadDocument(input, loadOptions),
1281
- snapshotDocument: () => this.snapshotDocument(),
1282
- jsonDocument: () => this.jsonDocument(),
1283
- recordPatch: (transaction, forward, inverse) => this.recordPatch(transaction, forward, inverse)
1284
- });
1285
- this.selection = new SelectionController(
1286
- (id) => this.currentStore().getNode(id) !== void 0,
1287
- () => this.assertSessionMutationAllowed()
1288
- );
1289
- this.viewport = new BoardViewportController(this, this.viewportState);
1290
- const history = createHistoryController({
1291
- applyHistoryEntry: (entry, direction) => this.applyHistoryEntry(entry, direction)
1292
- });
1293
- this.history = history.controller;
1294
- this.recordHistory = history.record;
1295
- this.nodes = new BoardNodesController(this);
1296
- this.assets = new BoardAssetsController(this);
1297
- this.document = new BoardDocumentController(this);
1298
- this.selection.onChange((event) => this.events.emit("selection:change", event));
1299
- this.viewportState.onChange((event) => {
1300
- this.events.emit("viewport:change", event);
1301
- });
1302
- this.history.onChange((event) => this.events.emit("history:change", event));
1303
- }
1304
- on(eventName, listener) {
1305
- return this.events.on(eventName, listener);
1306
- }
1307
- transaction(label, operation, options = {}) {
1308
- if (this.activeTransaction) {
1309
- throw new TransactionConflictError("Nested transactions are not supported");
1310
- }
1311
- if (this.rejectedAsyncTransactionCallbacks > 0) {
1312
- throw new TransactionConflictError(
1313
- "Writes are blocked until a rejected async transaction callback settles"
1314
- );
1315
- }
1316
- const transaction = {
1317
- id: this.idFactory(),
1318
- label: label || void 0,
1319
- origin: options.origin ?? "api",
1320
- ...options.coalesceKey === void 0 ? {} : { coalesceKey: options.coalesceKey },
1321
- draft: this.store.clone(),
1322
- forward: [],
1323
- inverse: []
1324
- };
1325
- this.activeTransaction = transaction;
1326
- try {
1327
- const result = operation(this);
1328
- if (isPromiseLike(result)) {
1329
- this.rejectedAsyncTransactionCallbacks += 1;
1330
- void Promise.resolve(result).catch(() => void 0).finally(() => {
1331
- this.rejectedAsyncTransactionCallbacks -= 1;
1332
- });
1333
- throw new TransactionConflictError(
1334
- "Core transaction callbacks must be synchronous"
1335
- );
1336
- }
1337
- this.activeTransaction = void 0;
1338
- this.commitTransaction(transaction, true);
1339
- return result;
1340
- } catch (error) {
1341
- this.activeTransaction = void 0;
1342
- throw error;
1343
- }
1344
- }
1345
- applyHistoryEntry(entry, direction) {
1346
- if (this.activeTransaction || this.rejectedAsyncTransactionCallbacks > 0) {
1347
- throw new TransactionConflictError("History cannot run during a transaction");
1348
- }
1349
- const transaction = {
1350
- id: this.idFactory(),
1351
- label: `${direction === "undo" ? "Undo" : "Redo"}${entry.label ? `: ${entry.label}` : ""}`,
1352
- origin: "history",
1353
- draft: this.store.clone(),
1354
- forward: direction === "undo" ? entry.inverse : entry.forward,
1355
- inverse: direction === "undo" ? entry.forward : entry.inverse
1356
- };
1357
- applyDataPatches(transaction.draft, transaction.forward);
1358
- return this.commitTransaction(transaction, false);
1359
- }
1360
- getBounds(nodeId) {
1361
- const node = this.currentStore().requireNode(nodeId);
1362
- return this.nodeTypes.has(node.type) ? this.nodeTypes.getBounds(node) : rotatedRectBounds(node);
1363
- }
1364
- mutate(label, operation) {
1365
- if (this.rejectedAsyncTransactionCallbacks > 0) {
1366
- throw new TransactionConflictError(
1367
- "Writes are blocked until a rejected async transaction callback settles"
1368
- );
1369
- }
1370
- if (this.activeTransaction) return operation(this.activeTransaction);
1371
- let result;
1372
- this.transaction(label, () => {
1373
- result = operation(this.activeTransaction);
1374
- });
1375
- return result;
1376
- }
1377
- currentStore() {
1378
- return this.activeTransaction?.draft ?? this.store;
1379
- }
1380
- nextId() {
1381
- return this.idFactory();
1382
- }
1383
- validateLoadedDocument(input, options = {}) {
1384
- return validateDocument(input, {
1385
- schemaVersion: this.schemaVersion,
1386
- nodeTypes: this.nodeTypes
1387
- });
1388
- }
1389
- loadDocument(input, options = {}) {
1390
- if (this.activeTransaction || this.rejectedAsyncTransactionCallbacks > 0) {
1391
- throw new TransactionConflictError("A document cannot be loaded during a transaction");
1392
- }
1393
- if (options.replaceHistory === false) {
1394
- throw new DocumentValidationError(
1395
- "replaceHistory:false is not supported because history patches belong to the previous document"
1396
- );
1397
- }
1398
- const nextDocument = this.validateLoadedDocument(input, options);
1399
- const before = this.store;
1400
- const previousViewport = this.viewportState.get();
1401
- const hadSelection = this.selection.get().length > 0;
1402
- this.store = new RuntimeDocumentStore(nextDocument);
1403
- this.selection.clear();
1404
- this.viewportState.set(nextDocument.viewport ?? { scale: 1, offset: { x: 0, y: 0 } });
1405
- this.history.clear();
1406
- const viewportChanged = !jsonEqual(previousViewport, this.viewportState.get());
1407
- const changeSet = createChangeSet({
1408
- before: before.mutableSnapshot(),
1409
- after: nextDocument,
1410
- transactionId: this.idFactory(),
1411
- origin: "load",
1412
- revision: nextDocument.revision,
1413
- timestamp: this.now(),
1414
- selectionChanged: hadSelection,
1415
- viewportChanged
1416
- });
1417
- this.emitChange(changeSet);
1418
- this.emitMissingNodeTypes(nextDocument.nodes);
1419
- return changeSet;
1420
- }
1421
- snapshotDocument() {
1422
- return this.store.snapshot();
1423
- }
1424
- jsonDocument() {
1425
- return this.store.mutableSnapshot();
1426
- }
1427
- recordPatch(transaction, forward, inverse) {
1428
- transaction.forward.push(forward);
1429
- transaction.inverse.unshift(inverse);
1430
- }
1431
- commitTransaction(transaction, recordHistory2) {
1432
- if (transaction.forward.length === 0 && recordHistory2) return void 0;
1433
- const before = this.store;
1434
- const after = transaction.draft;
1435
- if (!hasEffectivePatchChanges(before, after, transaction.forward)) {
1436
- return void 0;
1437
- }
1438
- transaction.draft.revision = before.revision + 1;
1439
- this.store = after;
1440
- const selectionChanged = this.selection.prune();
1441
- const changeSet = createTransactionChangeSet({
1442
- before,
1443
- after,
1444
- patches: transaction.forward,
1445
- transactionId: transaction.id,
1446
- label: transaction.label,
1447
- origin: transaction.origin,
1448
- revision: after.revision,
1449
- timestamp: this.now(),
1450
- selectionChanged,
1451
- viewportChanged: false
1452
- });
1453
- if (recordHistory2) {
1454
- this.recordHistory({
1455
- label: transaction.label,
1456
- origin: transaction.origin,
1457
- ...transaction.coalesceKey === void 0 ? {} : { coalesceKey: transaction.coalesceKey },
1458
- forward: transaction.forward,
1459
- inverse: transaction.inverse
1460
- });
1461
- }
1462
- changeSet.metadataChanged = transaction.forward.some((patch) => patch.op === "metadata:replace") && !jsonEqual(before.getMetadata(), after.getMetadata());
1463
- this.emitChange(changeSet);
1464
- return changeSet;
1465
- }
1466
- emitChange(changeSet) {
1467
- const changedNodeIds = /* @__PURE__ */ new Set([
1468
- ...changeSet.addedNodeIds,
1469
- ...changeSet.updatedNodeIds,
1470
- ...changeSet.assetChangedNodeIds
1471
- ]);
1472
- const changedNodes = [];
1473
- for (const nodeId of changedNodeIds) {
1474
- const node = this.store.getNodeReference(nodeId);
1475
- if (node) changedNodes.push(node);
1476
- }
1477
- this.events.emit("change", {
1478
- revision: changeSet.revision,
1479
- changeSet: immutableClone(changeSet),
1480
- documentUpdate: immutableClone({
1481
- revision: changeSet.revision,
1482
- changedNodes
1483
- })
1484
- });
1485
- }
1486
- emitMissingNodeTypes(nodes) {
1487
- const missing = /* @__PURE__ */ new Map();
1488
- for (const node of nodes) {
1489
- if (this.nodeTypes.has(node.type)) continue;
1490
- const ids = missing.get(node.type) ?? [];
1491
- ids.push(node.id);
1492
- missing.set(node.type, ids);
1493
- }
1494
- for (const [type, nodeIds] of missing) {
1495
- this.events.emit("node-type:missing", { type, nodeIds: [...nodeIds] });
1496
- }
1497
- }
1498
- assertSessionMutationAllowed() {
1499
- if (this.activeTransaction || this.rejectedAsyncTransactionCallbacks > 0) {
1500
- throw new TransactionConflictError(
1501
- "Selection and viewport cannot change during a document transaction"
1502
- );
1503
- }
1504
- }
1505
- };
1506
- var BoardNodesController = class {
1507
- constructor(core) {
1508
- this.core = core;
1509
- }
1510
- core;
1511
- create(input) {
1512
- const internals = getCoreInternals(this.core);
1513
- return internals.mutate("Create node", (transaction) => {
1514
- const { typeVersion, props } = this.core.nodeTypes.createProps(input.type, input.props);
1515
- const node = validateNode({
1516
- id: input.id ?? internals.nextId(),
1517
- type: input.type,
1518
- typeVersion: input.typeVersion ?? typeVersion,
1519
- x: input.x,
1520
- y: input.y,
1521
- width: input.width,
1522
- height: input.height,
1523
- rotation: input.rotation ?? 0,
1524
- zIndex: input.zIndex ?? 0,
1525
- props,
1526
- ...input.name === void 0 ? {} : { name: input.name },
1527
- ...input.locked === void 0 ? {} : { locked: input.locked },
1528
- ...input.visible === void 0 ? {} : { visible: input.visible },
1529
- ...input.assetRefs === void 0 ? {} : { assetRefs: cloneValue(input.assetRefs) }
1530
- });
1531
- const validated = this.core.nodeTypes.validateNode(node);
1532
- const index = transaction.draft.nodeCount();
1533
- transaction.draft.insertNode(index, validated);
1534
- internals.recordPatch(
1535
- transaction,
1536
- { op: "node:insert", index, node: validated },
1537
- { op: "node:remove", nodeId: validated.id }
1538
- );
1539
- return immutableClone(validated);
1540
- });
1541
- }
1542
- update(nodeId, patch) {
1543
- const internals = getCoreInternals(this.core);
1544
- return internals.mutate("Update node", (transaction) => {
1545
- const previous = transaction.draft.requireNode(nodeId);
1546
- if ("props" in patch && !this.core.nodeTypes.has(previous.type)) {
1547
- throw new NodeTypeNotRegisteredError(previous.type);
1548
- }
1549
- const next = validateNode({ ...previous, ...cloneValue(patch), id: previous.id, type: previous.type });
1550
- const validated = this.core.nodeTypes.has(next.type) ? this.core.nodeTypes.validateNode(next) : next;
1551
- if (jsonEqual(previous, validated)) return immutableClone(previous);
1552
- transaction.draft.replaceNode(validated);
1553
- internals.recordPatch(
1554
- transaction,
1555
- { op: "node:replace", node: validated },
1556
- { op: "node:replace", node: previous }
1557
- );
1558
- return immutableClone(validated);
1559
- });
1560
- }
1561
- convert(nodeId, input) {
1562
- const internals = getCoreInternals(this.core);
1563
- return internals.mutate("Convert node", (transaction) => {
1564
- const previous = transaction.draft.requireNode(nodeId);
1565
- const { typeVersion, props } = this.core.nodeTypes.createProps(input.type, input.props);
1566
- const { x, y, width, height, rotation, zIndex, locked, visible } = previous;
1567
- const next = validateNode({
1568
- x,
1569
- y,
1570
- width,
1571
- height,
1572
- rotation,
1573
- zIndex,
1574
- ...locked === void 0 ? {} : { locked },
1575
- ...visible === void 0 ? {} : { visible },
1576
- ...cloneValue(input),
1577
- id: previous.id,
1578
- typeVersion: input.typeVersion ?? typeVersion,
1579
- props
1580
- });
1581
- const validated = this.core.nodeTypes.validateNode(next);
1582
- if (jsonEqual(previous, validated)) return immutableClone(validated);
1583
- transaction.draft.replaceNode(validated);
1584
- internals.recordPatch(
1585
- transaction,
1586
- { op: "node:replace", node: validated },
1587
- { op: "node:replace", node: previous }
1588
- );
1589
- return immutableClone(validated);
1590
- });
1591
- }
1592
- /**
1593
- * Applies one resize gesture step through the node type's `ResizePolicy`.
1594
- * The policy decides what the requested handle drag is allowed to become —
1595
- * `fixed` refuses it outright, `aspect-ratio` locks the two axes together
1596
- * and `custom` gets the last word on the resulting size — so hosts never
1597
- * need to reimplement those rules on top of `update()`.
1598
- */
1599
- resize(nodeId, request) {
1600
- const node = getCoreInternals(this.core).currentStore().requireNode(nodeId);
1601
- const policy = this.core.nodeTypes.get(node.type)?.resize;
1602
- const patch = resolveResize(node, policy, request);
1603
- if (Object.keys(patch).length === 0) return immutableClone(node);
1604
- return this.update(nodeId, patch);
1605
- }
1606
- remove(nodeId) {
1607
- const internals = getCoreInternals(this.core);
1608
- return internals.mutate("Remove node", (transaction) => {
1609
- const index = transaction.draft.getNodeIndex(nodeId);
1610
- if (index === void 0) throw new NodeNotFoundError(nodeId);
1611
- const removed = transaction.draft.removeNode(nodeId);
1612
- internals.recordPatch(
1613
- transaction,
1614
- { op: "node:remove", nodeId },
1615
- { op: "node:insert", index, node: removed }
1616
- );
1617
- const metadata = transaction.draft.getMetadata();
1618
- if (Array.isArray(metadata?.connections)) {
1619
- const connections = metadata.connections.filter((edge) => !edge || typeof edge !== "object" || Array.isArray(edge) || edge.source !== nodeId && edge.target !== nodeId);
1620
- if (connections.length !== metadata.connections.length) this.core.document.patchMetadata({ connections });
1621
- }
1622
- return immutableClone(removed);
1623
- });
1624
- }
1625
- get(nodeId) {
1626
- const node = getCoreInternals(this.core).currentStore().getNode(nodeId);
1627
- return node ? immutableClone(node) : void 0;
1628
- }
1629
- list(filter = {}) {
1630
- const idFilter = filter.ids ? new Set(filter.ids) : void 0;
1631
- const typeFilter = filter.types ? new Set(filter.types) : void 0;
1632
- const limit2 = filter.limit ?? Number.POSITIVE_INFINITY;
1633
- if (!Number.isInteger(limit2) && limit2 !== Number.POSITIVE_INFINITY) {
1634
- throw new RangeError("Node list limit must be an integer");
1635
- }
1636
- if (limit2 < 0) throw new RangeError("Node list limit must not be negative");
1637
- const store = getCoreInternals(this.core).currentStore();
1638
- const selected = filter.selected === void 0 ? void 0 : new Set(this.core.selection.get());
1639
- const source = idFilter ? store.listNodesByIds(idFilter) : store.listNodes();
1640
- const result = source.filter((node) => {
1641
- if (idFilter && !idFilter.has(node.id)) return false;
1642
- if (typeFilter && !typeFilter.has(node.type)) return false;
1643
- if (filter.type && node.type !== filter.type) return false;
1644
- if (filter.bounds && !boundsIntersect(this.core.getBounds(node.id), filter.bounds)) return false;
1645
- if (filter.visible !== void 0 && (node.visible ?? true) !== filter.visible) return false;
1646
- if (filter.selected !== void 0 && selected.has(node.id) !== filter.selected) return false;
1647
- return true;
1648
- });
1649
- return deepFreeze(result.slice(0, limit2));
1650
- }
1651
- };
1652
- function boundsIntersect(left, right) {
1653
- return left.maxX >= right.minX && left.minX <= right.maxX && left.maxY >= right.minY && left.minY <= right.maxY;
1654
- }
1655
- var BoardAssetsController = class {
1656
- constructor(core) {
1657
- this.core = core;
1658
- }
1659
- core;
1660
- upsert(assetInput) {
1661
- const internals = getCoreInternals(this.core);
1662
- return internals.mutate("Upsert asset", (transaction) => {
1663
- const asset = validateAsset(assetInput);
1664
- const previous = transaction.draft.getAsset(asset.id);
1665
- if (previous && jsonEqual(previous, asset)) return immutableClone(previous);
1666
- if (previous) {
1667
- transaction.draft.replaceAsset(asset);
1668
- internals.recordPatch(
1669
- transaction,
1670
- { op: "asset:replace", asset },
1671
- { op: "asset:replace", asset: previous }
1672
- );
1673
- } else {
1674
- const index = transaction.draft.assetCount();
1675
- transaction.draft.insertAsset(index, asset);
1676
- internals.recordPatch(
1677
- transaction,
1678
- { op: "asset:insert", index, asset },
1679
- { op: "asset:remove", assetId: asset.id }
1680
- );
1681
- }
1682
- return immutableClone(asset);
1683
- });
1684
- }
1685
- remove(assetId) {
1686
- const internals = getCoreInternals(this.core);
1687
- return internals.mutate("Remove asset", (transaction) => {
1688
- const index = transaction.draft.getAssetIndex(assetId);
1689
- if (index === void 0) throw new DocumentValidationError(`Asset not found: ${assetId}`);
1690
- const asset = transaction.draft.removeAsset(assetId);
1691
- internals.recordPatch(
1692
- transaction,
1693
- { op: "asset:remove", assetId },
1694
- { op: "asset:insert", index, asset }
1695
- );
1696
- return immutableClone(asset);
1697
- });
1698
- }
1699
- get(assetId) {
1700
- const asset = getCoreInternals(this.core).currentStore().getAsset(assetId);
1701
- return asset ? immutableClone(asset) : void 0;
1702
- }
1703
- list() {
1704
- return immutableClone(getCoreInternals(this.core).currentStore().listAssets());
1705
- }
1706
- };
1707
- var BoardViewportController = class {
1708
- constructor(core, viewport) {
1709
- this.core = core;
1710
- this.viewport = viewport;
1711
- }
1712
- core;
1713
- viewport;
1714
- get() {
1715
- return this.viewport.get();
1716
- }
1717
- set(value) {
1718
- this.viewport.set(value);
1719
- }
1720
- setScreenSize(size) {
1721
- this.viewport.setScreenSize(size);
1722
- }
1723
- getScreenSize() {
1724
- return this.viewport.getScreenSize();
1725
- }
1726
- visibleWorldBounds(padding) {
1727
- return this.viewport.visibleWorldBounds(padding);
1728
- }
1729
- panBy(deltaX, deltaY) {
1730
- this.viewport.panBy(deltaX, deltaY);
1731
- }
1732
- zoomAt(screenPoint, factor) {
1733
- this.viewport.zoomAt(screenPoint, factor);
1734
- }
1735
- fitNodes(nodeIds, options) {
1736
- const bounds = mergeBounds(nodeIds.map((nodeId) => this.core.getBounds(nodeId)));
1737
- if (!bounds) return;
1738
- this.viewport.fitBounds(bounds, options);
1739
- }
1740
- fitBounds(bounds, options) {
1741
- this.viewport.fitBounds(bounds, options);
1742
- }
1743
- toWorld(screenPoint) {
1744
- return this.viewport.toWorld(screenPoint);
1745
- }
1746
- toScreen(worldPoint) {
1747
- return this.viewport.toScreen(worldPoint);
1748
- }
1749
- onChange(listener) {
1750
- return this.viewport.onChange(listener);
1751
- }
1752
- };
1753
- var BoardDocumentController = class {
1754
- constructor(core) {
1755
- this.core = core;
1756
- }
1757
- core;
1758
- getRevision() {
1759
- return getCoreInternals(this.core).currentStore().revision;
1760
- }
1761
- getMetadata() {
1762
- return getCoreInternals(this.core).currentStore().getMetadata();
1763
- }
1764
- patchMetadata(patch) {
1765
- const internals = getCoreInternals(this.core);
1766
- internals.mutate("Update document metadata", (transaction) => {
1767
- const previous = transaction.draft.getMetadata();
1768
- const next = { ...previous };
1769
- for (const [key, value] of Object.entries(patch)) {
1770
- if (value === void 0) delete next[key];
1771
- else next[key] = cloneValue(value);
1772
- }
1773
- assertJsonValue(next, "document.metadata");
1774
- transaction.draft.setMetadata(next);
1775
- internals.recordPatch(transaction, { op: "metadata:replace", metadata: next }, { op: "metadata:replace", metadata: previous });
1776
- });
1777
- }
1778
- snapshot() {
1779
- return getCoreInternals(this.core).snapshotDocument();
1780
- }
1781
- toJSON() {
1782
- return getCoreInternals(this.core).jsonDocument();
1783
- }
1784
- stringify(space) {
1785
- return JSON.stringify(this.toJSON(), null, space);
1786
- }
1787
- load(input, options) {
1788
- return getCoreInternals(this.core).loadDocument(input, options);
1789
- }
1790
- validate(input) {
1791
- return getCoreInternals(this.core).validateLoadedDocument(input);
1792
- }
1793
- };
1794
- function createBoardCore(options) {
1795
- return new BoardCore(options);
1796
- }
1797
- function getCoreInternals(core) {
1798
- const internals = coreInternals.get(core);
1799
- if (!internals) throw new Error("BoardCore internals are unavailable");
1800
- return internals;
1801
- }
1802
- function createEmptyDocument(schemaVersion) {
1803
- if (!Number.isInteger(schemaVersion) || schemaVersion < 1) {
1804
- throw new DocumentValidationError("schemaVersion must be a positive integer");
1805
- }
1806
- return { schemaVersion, revision: 0, nodes: [], assets: [] };
1807
- }
1808
- function defaultIdFactory() {
1809
- return globalThis.crypto.randomUUID();
1810
- }
1811
- function isPromiseLike(value) {
1812
- return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
1813
- }
1814
- function createChangeSet(input) {
1815
- const beforeNodes = new Map(input.before.nodes.map((node) => [node.id, node]));
1816
- const afterNodes = new Map(input.after.nodes.map((node) => [node.id, node]));
1817
- const beforeNodeOrder = new Map(input.before.nodes.map((node, index) => [node.id, index]));
1818
- const addedNodeIds = input.after.nodes.filter((node) => !beforeNodes.has(node.id)).map((node) => node.id);
1819
- const updatedNodeIds = input.after.nodes.filter((node, index) => {
1820
- const previous = beforeNodes.get(node.id);
1821
- return previous !== void 0 && (!jsonEqual(previous, node) || beforeNodeOrder.get(node.id) !== index);
1822
- }).map((node) => node.id);
1823
- const removedNodeIds = input.before.nodes.filter((node) => !afterNodes.has(node.id)).map((node) => node.id);
1824
- const beforeAssets = new Map(input.before.assets.map((asset) => [asset.id, asset]));
1825
- const afterAssets = new Map(input.after.assets.map((asset) => [asset.id, asset]));
1826
- const changedAssetIds = /* @__PURE__ */ new Set();
1827
- for (const asset of input.before.assets) {
1828
- const next = afterAssets.get(asset.id);
1829
- if (!next || !jsonEqual(asset, next)) changedAssetIds.add(asset.id);
1830
- }
1831
- for (const asset of input.after.assets) {
1832
- const previous = beforeAssets.get(asset.id);
1833
- if (!previous || !jsonEqual(previous, asset)) changedAssetIds.add(asset.id);
1834
- }
1835
- const assetChangedNodeIds = input.after.nodes.filter((node) => {
1836
- const previous = beforeNodes.get(node.id);
1837
- if (previous && !jsonEqual(previous.assetRefs, node.assetRefs)) return true;
1838
- return Object.values(node.assetRefs ?? {}).some((ref) => changedAssetIds.has(ref.assetId));
1839
- }).map((node) => node.id);
1840
- return {
1841
- transactionId: input.transactionId,
1842
- revision: input.revision,
1843
- ...input.label ? { label: input.label } : {},
1844
- origin: input.origin,
1845
- addedNodeIds,
1846
- updatedNodeIds,
1847
- removedNodeIds,
1848
- assetChangedNodeIds,
1849
- selectionChanged: input.selectionChanged,
1850
- viewportChanged: input.viewportChanged,
1851
- timestamp: input.timestamp
1852
- };
1853
- }
1854
- function hasEffectivePatchChanges(before, after, patches) {
1855
- if (patches.some((patch) => patch.op === "metadata:replace") && !jsonEqual(before.getMetadata(), after.getMetadata())) return true;
1856
- if (patches.some((patch) => patch.op.endsWith(":insert") || patch.op.endsWith(":remove"))) {
1857
- const beforeSnapshot = before.mutableSnapshot();
1858
- const afterSnapshot = after.mutableSnapshot();
1859
- return !jsonEqual(beforeSnapshot.nodes, afterSnapshot.nodes) || !jsonEqual(beforeSnapshot.assets, afterSnapshot.assets);
1860
- }
1861
- for (const patch of patches) {
1862
- if (patch.op === "node:replace") {
1863
- if (!jsonEqual(before.getNodeReference(patch.node.id), after.getNodeReference(patch.node.id))) {
1864
- return true;
1865
- }
1866
- } else if (patch.op === "asset:replace") {
1867
- if (!jsonEqual(before.getAssetReference(patch.asset.id), after.getAssetReference(patch.asset.id))) {
1868
- return true;
1869
- }
1870
- }
1871
- }
1872
- return false;
1873
- }
1874
- function createTransactionChangeSet(input) {
1875
- const structural = input.patches.some(
1876
- (patch) => patch.op.endsWith(":insert") || patch.op.endsWith(":remove")
1877
- );
1878
- if (structural) {
1879
- return createChangeSet({
1880
- before: input.before.mutableSnapshot(),
1881
- after: input.after.mutableSnapshot(),
1882
- transactionId: input.transactionId,
1883
- label: input.label,
1884
- origin: input.origin,
1885
- revision: input.revision,
1886
- timestamp: input.timestamp,
1887
- selectionChanged: input.selectionChanged,
1888
- viewportChanged: input.viewportChanged
1889
- });
1890
- }
1891
- const updatedIds = /* @__PURE__ */ new Set();
1892
- const changedAssetIds = /* @__PURE__ */ new Set();
1893
- for (const patch of input.patches) {
1894
- if (patch.op === "node:replace") updatedIds.add(patch.node.id);
1895
- if (patch.op === "asset:replace") changedAssetIds.add(patch.asset.id);
1896
- }
1897
- const updatedNodeIds = [...updatedIds].filter((id) => {
1898
- const before = input.before.getNodeReference(id);
1899
- const after = input.after.getNodeReference(id);
1900
- return before !== void 0 && after !== void 0 && !jsonEqual(before, after);
1901
- }).sort(
1902
- (left, right) => (input.after.getNodeIndex(left) ?? Number.POSITIVE_INFINITY) - (input.after.getNodeIndex(right) ?? Number.POSITIVE_INFINITY)
1903
- );
1904
- const assetChangedNodeIds = /* @__PURE__ */ new Set();
1905
- for (const id of updatedIds) {
1906
- const before = input.before.getNodeReference(id);
1907
- const after = input.after.getNodeReference(id);
1908
- if (before && after && !jsonEqual(before.assetRefs, after.assetRefs)) {
1909
- assetChangedNodeIds.add(id);
1910
- }
1911
- }
1912
- if (changedAssetIds.size > 0) {
1913
- input.after.forEachNodeReference((node) => {
1914
- if (Object.values(node.assetRefs ?? {}).some((ref) => changedAssetIds.has(ref.assetId))) {
1915
- assetChangedNodeIds.add(node.id);
1916
- }
1917
- });
1918
- }
1919
- return {
1920
- transactionId: input.transactionId,
1921
- revision: input.revision,
1922
- ...input.label ? { label: input.label } : {},
1923
- origin: input.origin,
1924
- addedNodeIds: [],
1925
- updatedNodeIds,
1926
- removedNodeIds: [],
1927
- assetChangedNodeIds: [...assetChangedNodeIds].sort(
1928
- (left, right) => (input.after.getNodeIndex(left) ?? Number.POSITIVE_INFINITY) - (input.after.getNodeIndex(right) ?? Number.POSITIVE_INFINITY)
1929
- ),
1930
- selectionChanged: input.selectionChanged,
1931
- viewportChanged: input.viewportChanged,
1932
- timestamp: input.timestamp
1933
- };
1934
- }
1935
- var EventHub = class {
1936
- listeners = /* @__PURE__ */ new Map();
1937
- on(eventName, listener) {
1938
- const listeners = this.listeners.get(eventName) ?? /* @__PURE__ */ new Set();
1939
- listeners.add(listener);
1940
- this.listeners.set(eventName, listeners);
1941
- return () => listeners.delete(listener);
1942
- }
1943
- emit(eventName, event) {
1944
- for (const listener of this.listeners.get(eventName) ?? []) {
1945
- try {
1946
- listener(event);
1947
- } catch {
1948
- }
1949
- }
1950
- }
1951
- };
1952
-
1953
- // ../capabilities/src/errors.ts
1954
- var CAPABILITY_ERROR_BRAND = "@pixi-board/capabilities:CapabilityError";
1955
- var CapabilityError = class extends Error {
1956
- name = "CapabilityError";
1957
- brand = CAPABILITY_ERROR_BRAND;
1958
- code;
1959
- details;
1960
- constructor(code, message, details) {
1961
- super(message);
1962
- this.code = code;
1963
- this.details = details;
1964
- }
1965
- };
1966
- function isCapabilityError(value) {
1967
- return value instanceof CapabilityError || value instanceof Error && value.brand === CAPABILITY_ERROR_BRAND;
1968
- }
1969
- var CapabilityUnavailableError = class extends CapabilityError {
1970
- capability;
1971
- constructor(capability) {
1972
- super("CAPABILITY_UNAVAILABLE", `Capability unavailable: ${capability}`, { capability });
1973
- this.capability = capability;
1974
- }
1975
- };
1976
- var AssetUnavailableError = class extends CapabilityError {
1977
- constructor(assetId, variant) {
1978
- super("ASSET_UNAVAILABLE", `Asset unavailable: ${assetId}${variant ? ` (${variant})` : ""}`, { assetId, variant });
1979
- }
1980
- };
1981
- var PermissionDeniedError = class extends CapabilityError {
1982
- constructor(message = "Permission denied", details) {
1983
- super("PERMISSION_DENIED", message, details);
1984
- }
1985
- };
1986
- var BoardDestroyedError = class extends CapabilityError {
1987
- constructor(message = "Board has been destroyed") {
1988
- super("BOARD_DESTROYED", message);
1989
- }
1990
- };
1991
- function mapCoreError(error) {
1992
- if (isCapabilityError(error)) return error;
1993
- const { NodeNotFoundError: NodeNotFoundError2, NodeTypeNotRegisteredError: NodeTypeNotRegisteredError2, NodeValidationError: NodeValidationError2, DocumentValidationError: DocumentValidationError2, TransactionConflictError: TransactionConflictError2 } = src_exports;
1994
- const message = error instanceof Error ? error.message : String(error);
1995
- const code = error instanceof NodeNotFoundError2 ? "NODE_NOT_FOUND" : error instanceof NodeTypeNotRegisteredError2 ? "NODE_TYPE_NOT_REGISTERED" : error instanceof NodeValidationError2 ? "NODE_VALIDATION" : error instanceof DocumentValidationError2 ? "DOCUMENT_VALIDATION" : error instanceof TransactionConflictError2 ? "TRANSACTION_CONFLICT" : error instanceof RangeError ? "INVALID_INPUT" : error instanceof AssetUnavailableError ? "ASSET_UNAVAILABLE" : error instanceof PermissionDeniedError ? "PERMISSION_DENIED" : error instanceof BoardDestroyedError ? "BOARD_DESTROYED" : error instanceof Error && error.name === "AssetUnavailableError" ? "ASSET_UNAVAILABLE" : error instanceof Error && error.name === "PermissionDeniedError" ? "PERMISSION_DENIED" : error instanceof Error && error.name === "BoardDestroyedError" ? "BOARD_DESTROYED" : "INTERNAL_ERROR";
1996
- return new CapabilityError(code, message);
1997
- }
1998
- function aborted(signal) {
1999
- if (signal?.aborted) throw new CapabilityError("ABORTED", "The capability request was aborted");
2000
- }
2001
-
2002
- // ../capabilities/src/index.ts
2003
- function createBoardCapabilities(core, services = {}) {
2004
- const transact = (label, options, operation) => {
2005
- aborted(options.signal);
2006
- let changeSet;
2007
- const off = core.on("change", (event) => {
2008
- changeSet = event.changeSet;
2009
- });
2010
- try {
2011
- const result = core.transaction(label, operation, { origin: options.origin ?? "api" });
2012
- return { result, changed: changeSet !== void 0, changeSet };
2013
- } catch (error) {
2014
- throw mapCoreError(error);
2015
- } finally {
2016
- off();
2017
- }
2018
- };
2019
- const page = (items, requested = 50, cursor) => {
2020
- const limit2 = Math.min(Math.max(requested, 1), 200);
2021
- const start = cursor ? Math.max(0, Number.parseInt(cursor, 10) || 0) : 0;
2022
- const out = items.slice(start, start + limit2);
2023
- const hasMore = start + out.length < items.length;
2024
- return { out, page: { hasMore, ...hasMore ? { nextCursor: String(start + out.length) } : {} } };
2025
- };
2026
- const writeResult = (value) => ({
2027
- changed: value.changed,
2028
- nodes: value.nodes ?? [],
2029
- ...value.assets ? { assets: value.assets } : {},
2030
- ...value.deletedNodeIds ? { deletedNodeIds: value.deletedNodeIds } : {},
2031
- ...value.deletedAssetIds ? { deletedAssetIds: value.deletedAssetIds } : {},
2032
- revision: core.document.snapshot().revision,
2033
- ...value.changeSet ? { changeSet: value.changeSet } : {},
2034
- requestId: value.requestId
2035
- });
2036
- const capabilities = {
2037
- availability: { preview: Boolean(services.preview), capture: Boolean(services.capture) },
2038
- document: {
2039
- snapshot: async (options = {}) => {
2040
- aborted(options.signal);
2041
- return core.document.snapshot();
2042
- },
2043
- validate: async (input, options = {}) => {
2044
- try {
2045
- aborted(options.signal);
2046
- return core.document.validate(input);
2047
- } catch (error) {
2048
- throw mapCoreError(error);
2049
- }
2050
- },
2051
- load: async (input, options = {}) => {
2052
- try {
2053
- aborted(options.signal);
2054
- const changeSet = core.document.load(input, options);
2055
- aborted(options.signal);
2056
- return { changed: true, revision: changeSet.revision, changeSet, requestId: options.requestId };
2057
- } catch (error) {
2058
- throw mapCoreError(error);
2059
- }
2060
- }
2061
- },
2062
- nodes: {
2063
- read: async (input = {}, options = {}) => {
2064
- try {
2065
- aborted(options.signal);
2066
- const result = page(core.nodes.list(input.filter ?? {}), input.limit, input.cursor);
2067
- return { nodes: result.out, page: result.page, revision: core.document.snapshot().revision, requestId: options.requestId };
2068
- } catch (error) {
2069
- throw mapCoreError(error);
2070
- }
2071
- },
2072
- create: async (input, options = {}) => {
2073
- try {
2074
- if (!input.nodes.length) throw new CapabilityError("INVALID_INPUT", "nodes must not be empty");
2075
- const tx = transact(options.label ?? "Create nodes", options, () => {
2076
- const nodes = [];
2077
- for (const raw of input.nodes) {
2078
- aborted(options.signal);
2079
- const { asset, ...nodeInput } = raw;
2080
- const refs = asset ? { ...nodeInput.assetRefs ?? {}, primary: { assetId: asset.id, variant: "original" } } : nodeInput.assetRefs;
2081
- if (asset) core.assets.upsert(asset);
2082
- nodes.push(core.nodes.create({ rotation: 0, zIndex: 0, ...nodeInput, x: nodeInput.x ?? 0, y: nodeInput.y ?? 0, width: nodeInput.width ?? 100, height: nodeInput.height ?? 100, ...refs ? { assetRefs: refs } : {} }));
2083
- }
2084
- return nodes;
2085
- });
2086
- return writeResult({ ...tx, nodes: tx.result, requestId: options.requestId });
2087
- } catch (error) {
2088
- throw mapCoreError(error);
2089
- }
2090
- },
2091
- update: async (input, options = {}) => {
2092
- try {
2093
- if (!input.nodes.length) throw new CapabilityError("INVALID_INPUT", "nodes must not be empty");
2094
- const tx = transact(options.label ?? "Update nodes", options, () => {
2095
- const nodes = [];
2096
- for (const item of input.nodes) {
2097
- aborted(options.signal);
2098
- if (item.asset) core.assets.upsert(item.asset);
2099
- nodes.push(core.nodes.update(item.id, item.patch));
2100
- }
2101
- return nodes;
2102
- });
2103
- return writeResult({ ...tx, nodes: tx.result, requestId: options.requestId });
2104
- } catch (error) {
2105
- throw mapCoreError(error);
2106
- }
2107
- },
2108
- delete: async (input, options = {}) => {
2109
- try {
2110
- if (!input.nodeIds.length) throw new CapabilityError("INVALID_INPUT", "nodeIds must not be empty");
2111
- const tx = transact(options.label ?? "Delete nodes", options, () => {
2112
- const ids = [];
2113
- for (const id of [...new Set(input.nodeIds)]) {
2114
- aborted(options.signal);
2115
- core.nodes.remove(id);
2116
- ids.push(id);
2117
- }
2118
- return ids;
2119
- });
2120
- return writeResult({ ...tx, deletedNodeIds: tx.result, requestId: options.requestId });
2121
- } catch (error) {
2122
- throw mapCoreError(error);
2123
- }
2124
- }
2125
- },
2126
- assets: {
2127
- read: async (input = {}, options = {}) => {
2128
- try {
2129
- aborted(options.signal);
2130
- const assets = core.assets.list().filter((asset) => (!input.ids || input.ids.includes(asset.id)) && (!input.kinds || input.kinds.includes(asset.kind)));
2131
- const result = page(assets, input.limit, input.cursor);
2132
- return { assets: result.out, page: result.page, revision: core.document.snapshot().revision, requestId: options.requestId };
2133
- } catch (error) {
2134
- throw mapCoreError(error);
2135
- }
2136
- },
2137
- upsert: async (input, options = {}) => {
2138
- try {
2139
- if (!input.assets.length) throw new CapabilityError("INVALID_INPUT", "assets must not be empty");
2140
- const tx = transact(options.label ?? "Upsert assets", options, () => input.assets.map((asset) => {
2141
- aborted(options.signal);
2142
- return core.assets.upsert(asset);
2143
- }));
2144
- return writeResult({ ...tx, assets: tx.result, requestId: options.requestId });
2145
- } catch (error) {
2146
- throw mapCoreError(error);
2147
- }
2148
- },
2149
- remove: async (input, options = {}) => {
2150
- try {
2151
- if (!input.assetIds.length) throw new CapabilityError("INVALID_INPUT", "assetIds must not be empty");
2152
- const tx = transact(options.label ?? "Remove assets", options, () => [...new Set(input.assetIds)].map((id) => {
2153
- aborted(options.signal);
2154
- core.assets.remove(id);
2155
- return id;
2156
- }));
2157
- return writeResult({ ...tx, deletedAssetIds: tx.result, requestId: options.requestId });
2158
- } catch (error) {
2159
- throw mapCoreError(error);
2160
- }
2161
- }
2162
- },
2163
- selection: {
2164
- get: async (options = {}) => {
2165
- aborted(options.signal);
2166
- return core.selection.get();
2167
- },
2168
- set: async (nodeIds, options = {}) => {
2169
- try {
2170
- aborted(options.signal);
2171
- core.selection.set(nodeIds);
2172
- return { nodeIds: core.selection.get(), requestId: options.requestId };
2173
- } catch (error) {
2174
- throw mapCoreError(error);
2175
- }
2176
- }
2177
- },
2178
- viewport: {
2179
- get: async (options = {}) => {
2180
- aborted(options.signal);
2181
- return core.viewport.get();
2182
- },
2183
- set: async (viewport, options = {}) => {
2184
- try {
2185
- aborted(options.signal);
2186
- core.viewport.set(viewport);
2187
- return { viewport: core.viewport.get(), requestId: options.requestId };
2188
- } catch (error) {
2189
- throw mapCoreError(error);
2190
- }
2191
- }
2192
- },
2193
- history: {
2194
- canUndo: () => core.history.canUndo(),
2195
- canRedo: () => core.history.canRedo(),
2196
- clear: () => core.history.clear(),
2197
- undo: (options = {}) => {
2198
- try {
2199
- aborted(options.signal);
2200
- return core.history.undo();
2201
- } catch (error) {
2202
- throw mapCoreError(error);
2203
- }
2204
- },
2205
- redo: (options = {}) => {
2206
- try {
2207
- aborted(options.signal);
2208
- return core.history.redo();
2209
- } catch (error) {
2210
- throw mapCoreError(error);
2211
- }
2212
- }
2213
- },
2214
- preview: { get: async (input, options = {}) => {
2215
- try {
2216
- aborted(options.signal);
2217
- if (!core.nodes.get(input.nodeId)) throw new CapabilityError("NODE_NOT_FOUND", `Node not found: ${input.nodeId}`, { nodeId: input.nodeId });
2218
- if (!services.preview) throw new CapabilityUnavailableError("preview");
2219
- const value = await services.preview(input, options);
2220
- aborted(options.signal);
2221
- return { ...value, revision: core.document.snapshot().revision, requestId: options.requestId };
2222
- } catch (error) {
2223
- throw mapCoreError(error);
2224
- }
2225
- } },
2226
- capture: { available: Boolean(services.capture), capture: async (input, options = {}) => {
2227
- try {
2228
- aborted(options.signal);
2229
- if (!services.capture) throw new CapabilityUnavailableError("capture");
2230
- const value = await services.capture(input, options);
2231
- aborted(options.signal);
2232
- return { ...value, revision: core.document.snapshot().revision, requestId: options.requestId };
2233
- } catch (error) {
2234
- throw mapCoreError(error);
2235
- }
2236
- } }
2237
- };
2238
- return capabilities;
2239
- }
2240
-
2241
- // ../renderer-pixi/src/registry.ts
2242
- var NodeRendererRegistry = class {
2243
- renderers = /* @__PURE__ */ new Map();
2244
- register(type, renderer, options = {}) {
2245
- if (!type.trim()) throw new Error("Renderer type must be a non-empty string");
2246
- if (this.renderers.has(type) && !options.replace) throw new Error(`Renderer already registered: ${type}`);
2247
- this.renderers.set(type, renderer);
2248
- return () => {
2249
- if (this.renderers.get(type) === renderer) this.renderers.delete(type);
2250
- };
2251
- }
2252
- get(type) {
2253
- return this.renderers.get(type);
2254
- }
2255
- has(type) {
2256
- return this.renderers.has(type);
2257
- }
2258
- resolve(node) {
2259
- return this.get(node.type);
2260
- }
2261
- list() {
2262
- return [...this.renderers.keys()];
2263
- }
2264
- };
2265
-
2266
- // ../renderer-pixi/src/spatial.ts
2267
- var GridSpatialIndex = class {
2268
- cells = /* @__PURE__ */ new Map();
2269
- items = /* @__PURE__ */ new Map();
2270
- cellSize;
2271
- constructor(cellSize = 256) {
2272
- if (!Number.isFinite(cellSize) || cellSize <= 0) throw new RangeError("cellSize must be positive");
2273
- this.cellSize = cellSize;
2274
- }
2275
- rebuild(items) {
2276
- this.cells.clear();
2277
- this.items.clear();
2278
- for (const item of items) this.insert(item);
2279
- }
2280
- insert(item) {
2281
- this.remove(item.id);
2282
- const copy = { ...item };
2283
- this.items.set(copy.id, copy);
2284
- for (const key of this.keys(copy)) {
2285
- let bucket = this.cells.get(key);
2286
- if (!bucket) this.cells.set(key, bucket = /* @__PURE__ */ new Map());
2287
- bucket.set(copy.id, copy);
2288
- }
2289
- }
2290
- update(item) {
2291
- this.insert(item);
2292
- }
2293
- remove(id) {
2294
- const previous = this.items.get(id);
2295
- if (!previous) return;
2296
- this.items.delete(id);
2297
- for (const key of this.keys(previous)) {
2298
- const bucket = this.cells.get(key);
2299
- bucket?.delete(id);
2300
- if (bucket?.size === 0) this.cells.delete(key);
2301
- }
2302
- }
2303
- query(bounds) {
2304
- const result = /* @__PURE__ */ new Set();
2305
- for (const key of this.keys(bounds)) {
2306
- for (const item of this.cells.get(key)?.values() ?? []) if (intersects(item, bounds)) result.add(item.id);
2307
- }
2308
- return result;
2309
- }
2310
- queryPoint(point) {
2311
- const key = this.key(Math.floor(point.x / this.cellSize), Math.floor(point.y / this.cellSize));
2312
- const result = /* @__PURE__ */ new Set();
2313
- for (const item of this.cells.get(key)?.values() ?? []) if (contains(item, point)) result.add(item.id);
2314
- return result;
2315
- }
2316
- *keys(bounds) {
2317
- const minX = Math.floor(bounds.minX / this.cellSize);
2318
- const maxX = Math.floor(bounds.maxX / this.cellSize);
2319
- const minY = Math.floor(bounds.minY / this.cellSize);
2320
- const maxY = Math.floor(bounds.maxY / this.cellSize);
2321
- for (let x = minX; x <= maxX; x++) for (let y = minY; y <= maxY; y++) yield this.key(x, y);
2322
- }
2323
- key(x, y) {
2324
- return `${x}:${y}`;
2325
- }
2326
- };
2327
- function intersects(a, b) {
2328
- return a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY;
2329
- }
2330
- function contains(a, p) {
2331
- return p.x >= a.minX && p.x <= a.maxX && p.y >= a.minY && p.y <= a.maxY;
2332
- }
2333
-
2334
- // ../renderer-pixi/src/connections.ts
2335
- var defaultConnectionStyle = {
2336
- startColor: "#6366f1",
2337
- endColor: "#06b6d4",
2338
- startOpacity: 1,
2339
- endOpacity: 1,
2340
- width: 2,
2341
- lineType: "solid"
2342
- };
2343
- var PREVIEW_ID = "__connection_preview__";
2344
- var GRADIENT_STEP = 6;
2345
- var SELECTION_PADDING = 2;
2346
- var ConnectionRenderLayer = class {
2347
- constructor(invalidate, detach) {
2348
- this.invalidate = invalidate;
2349
- this.detach = detach;
2350
- this.container.zIndex = -1e6;
2351
- this.container.eventMode = "none";
2352
- }
2353
- invalidate;
2354
- detach;
2355
- container = new Container();
2356
- entries = /* @__PURE__ */ new Map();
2357
- index = new GridSpatialIndex();
2358
- segments = /* @__PURE__ */ new Map();
2359
- visibleIds = /* @__PURE__ */ new Set();
2360
- visible = true;
2361
- selected;
2362
- style = { ...defaultConnectionStyle };
2363
- bounds;
2364
- destroyed = false;
2365
- setStyle(style) {
2366
- if (this.destroyed) return;
2367
- this.style = normalizeConnectionStyle({ ...this.style, ...style });
2368
- for (const [id, entry] of this.entries) this.draw(entry, id === this.selected);
2369
- this.setVisibleBounds(this.bounds);
2370
- this.invalidate();
2371
- }
2372
- setSelected(id) {
2373
- if (this.destroyed) return;
2374
- const next = id === PREVIEW_ID ? void 0 : id;
2375
- if (this.selected === next) return;
2376
- const previous = this.selected;
2377
- this.selected = next;
2378
- for (const key of [previous, next]) {
2379
- const entry = key === void 0 ? void 0 : this.entries.get(key);
2380
- if (entry) this.draw(entry, key === next);
2381
- }
2382
- this.invalidate();
2383
- }
2384
- setEnabled(enabled) {
2385
- if (this.destroyed) return;
2386
- this.visible = enabled;
2387
- this.container.visible = enabled;
2388
- this.invalidate();
2389
- }
2390
- setVisibleBounds(bounds) {
2391
- if (this.destroyed) return;
2392
- this.bounds = bounds ? { ...bounds } : void 0;
2393
- const next = /* @__PURE__ */ new Set();
2394
- if (this.bounds) {
2395
- for (const key of this.index.query(this.paddedBounds(this.bounds))) {
2396
- const segment = this.segments.get(key);
2397
- if (segment) next.add(segment.id);
2398
- }
2399
- } else {
2400
- for (const id of this.entries.keys()) next.add(id);
2401
- }
2402
- for (const id of /* @__PURE__ */ new Set([...this.visibleIds, ...next])) {
2403
- const entry = this.entries.get(id);
2404
- if (entry) entry.view.visible = next.has(id);
2405
- }
2406
- this.visibleIds = next;
2407
- }
2408
- upsert(curve) {
2409
- if (this.destroyed) return;
2410
- this.disposeEntry(curve.id);
2411
- const points = sampleCurve(curve);
2412
- const view = new Graphics();
2413
- const keys = [];
2414
- const bounds = this.bounds ? this.paddedBounds(this.bounds) : void 0;
2415
- let visible = !bounds;
2416
- for (let i = 1; i < points.length; i++) {
2417
- const a = points[i - 1];
2418
- const b = points[i];
2419
- const key = JSON.stringify([curve.id, i]);
2420
- const segmentBounds = {
2421
- minX: Math.min(a.x, b.x),
2422
- minY: Math.min(a.y, b.y),
2423
- maxX: Math.max(a.x, b.x),
2424
- maxY: Math.max(a.y, b.y)
2425
- };
2426
- keys.push(key);
2427
- this.segments.set(key, { id: curve.id, a, b });
2428
- this.index.insert({ id: key, ...segmentBounds });
2429
- if (bounds && intersects2(segmentBounds, bounds)) visible = true;
2430
- }
2431
- const entry = { view, points, length: points[points.length - 1].distance, keys };
2432
- this.entries.set(curve.id, entry);
2433
- this.container.addChild(view);
2434
- view.visible = visible;
2435
- if (visible) this.visibleIds.add(curve.id);
2436
- this.draw(entry, curve.id === this.selected);
2437
- this.invalidate();
2438
- }
2439
- remove(id) {
2440
- if (this.destroyed || !this.entries.has(id)) return;
2441
- this.disposeEntry(id);
2442
- this.invalidate();
2443
- }
2444
- hitTest(point, tolerance) {
2445
- if (this.destroyed || !this.visible || !Number.isFinite(tolerance) || tolerance < 0) return;
2446
- let nearest;
2447
- let nearestDistance = tolerance;
2448
- const bounds = {
2449
- minX: point.x - tolerance,
2450
- minY: point.y - tolerance,
2451
- maxX: point.x + tolerance,
2452
- maxY: point.y + tolerance
2453
- };
2454
- for (const key of this.index.query(bounds)) {
2455
- const segment = this.segments.get(key);
2456
- if (!segment || segment.id === PREVIEW_ID || !this.visibleIds.has(segment.id)) continue;
2457
- const { a, b } = segment;
2458
- const dx = b.x - a.x;
2459
- const dy = b.y - a.y;
2460
- const t = Math.max(0, Math.min(
2461
- 1,
2462
- ((point.x - a.x) * dx + (point.y - a.y) * dy) / (dx * dx + dy * dy || 1)
2463
- ));
2464
- const distance = Math.hypot(point.x - a.x - t * dx, point.y - a.y - t * dy);
2465
- if (distance <= nearestDistance) {
2466
- nearest = segment.id;
2467
- nearestDistance = distance;
2468
- }
2469
- }
2470
- return nearest;
2471
- }
2472
- destroy() {
2473
- if (this.destroyed) return;
2474
- this.destroyed = true;
2475
- for (const id of this.entries.keys()) this.disposeEntry(id);
2476
- this.detach();
2477
- this.container.destroy({ children: true });
2478
- this.invalidate();
2479
- }
2480
- disposeEntry(id) {
2481
- const entry = this.entries.get(id);
2482
- if (!entry) return;
2483
- for (const key of entry.keys) {
2484
- this.index.remove(key);
2485
- this.segments.delete(key);
2486
- }
2487
- this.visibleIds.delete(id);
2488
- this.entries.delete(id);
2489
- entry.view.destroy();
2490
- }
2491
- paddedBounds(bounds) {
2492
- const padding = this.style.width / 2 + SELECTION_PADDING;
2493
- return {
2494
- minX: bounds.minX - padding,
2495
- minY: bounds.minY - padding,
2496
- maxX: bounds.maxX + padding,
2497
- maxY: bounds.maxY + padding
2498
- };
2499
- }
2500
- draw(entry, selected) {
2501
- const { view, points, length } = entry;
2502
- const style = this.style;
2503
- view.clear();
2504
- if (length === 0) return;
2505
- const startColor = parseInt(style.startColor.slice(1), 16);
2506
- const endColor = parseInt(style.endColor.slice(1), 16);
2507
- const colorAt = (distance) => {
2508
- const t = distance / length;
2509
- const channel = (shift) => Math.round(
2510
- (startColor >> shift & 255) * (1 - t) + (endColor >> shift & 255) * t
2511
- );
2512
- return channel(16) << 16 | channel(8) << 8 | channel(0);
2513
- };
2514
- const alphaAt = (distance) => {
2515
- const t = distance / length;
2516
- return style.startOpacity * (1 - t) + style.endOpacity * t;
2517
- };
2518
- for (const highlight of selected ? [true, false] : [false]) {
2519
- const width = style.width + (highlight ? SELECTION_PADDING * 2 : 0);
2520
- const color = (distance) => highlight ? 16777215 : colorAt(distance);
2521
- const alpha = (distance) => highlight ? 0.85 : alphaAt(distance);
2522
- if (style.lineType === "dotted") {
2523
- const spacing = Math.max(8, style.width * 2);
2524
- let cursor = 1;
2525
- for (let distance = 0; distance <= length; distance += spacing) {
2526
- while (cursor < points.length - 1 && points[cursor].distance < distance) cursor++;
2527
- const point = pointAtDistance(points[cursor - 1], points[cursor], distance);
2528
- view.circle(point.x, point.y, width / 2).fill({ color: color(distance), alpha: alpha(distance) });
2529
- }
2530
- continue;
2531
- }
2532
- for (let i = 1; i < points.length; i++) {
2533
- const a = points[i - 1];
2534
- const b = points[i];
2535
- let distance = a.distance;
2536
- while (distance < b.distance) {
2537
- const period = Math.floor(distance / 24);
2538
- const dashEnd = period * 24 + 15;
2539
- const painted = style.lineType === "solid" || distance < dashEnd;
2540
- const patternEnd = style.lineType === "solid" ? b.distance : painted ? dashEnd : (period + 1) * 24;
2541
- const end = Math.min(b.distance, patternEnd, distance + GRADIENT_STEP);
2542
- if (painted) {
2543
- const p = pointAtDistance(a, b, distance);
2544
- const q = pointAtDistance(a, b, end);
2545
- const middle = (distance + end) / 2;
2546
- view.moveTo(p.x, p.y).lineTo(q.x, q.y).stroke({
2547
- width,
2548
- color: color(middle),
2549
- alpha: alpha(middle),
2550
- cap: "butt"
2551
- });
2552
- }
2553
- distance = end;
2554
- }
2555
- }
2556
- }
2557
- }
2558
- };
2559
- function sampleCurve(curve) {
2560
- const distance = Math.max(48, Math.min(400, Math.abs(curve.end.x - curve.start.x) * 0.5));
2561
- const a = curve.start;
2562
- const d = curve.end;
2563
- const b = {
2564
- x: a.x + (curve.startDirection?.x ?? 1) * distance,
2565
- y: a.y + (curve.startDirection?.y ?? 0) * distance
2566
- };
2567
- const c = {
2568
- x: d.x - (curve.endDirection?.x ?? 1) * distance,
2569
- y: d.y - (curve.endDirection?.y ?? 0) * distance
2570
- };
2571
- 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);
2572
- const count = Math.max(24, Math.min(192, Math.ceil(estimate / 12)));
2573
- const points = [];
2574
- let length = 0;
2575
- for (let i = 0; i <= count; i++) {
2576
- const t = i / count;
2577
- const u = 1 - t;
2578
- const point = {
2579
- x: u * u * u * a.x + 3 * u * u * t * b.x + 3 * u * t * t * c.x + t * t * t * d.x,
2580
- y: u * u * u * a.y + 3 * u * u * t * b.y + 3 * u * t * t * c.y + t * t * t * d.y
2581
- };
2582
- const previous = points[points.length - 1];
2583
- if (previous) length += Math.hypot(point.x - previous.x, point.y - previous.y);
2584
- points.push({ ...point, distance: length });
2585
- }
2586
- return points;
2587
- }
2588
- function pointAtDistance(a, b, distance) {
2589
- const t = b.distance === a.distance ? 0 : (distance - a.distance) / (b.distance - a.distance);
2590
- return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
2591
- }
2592
- function intersects2(a, b) {
2593
- return a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY;
2594
- }
2595
- function normalizeConnectionStyle(value) {
2596
- const color = (v, fallback) => /^#[\da-f]{6}$/i.test(v) ? v : fallback;
2597
- const finite = (v, fallback) => Number.isFinite(v) ? v : fallback;
2598
- return {
2599
- startColor: color(value.startColor, defaultConnectionStyle.startColor),
2600
- endColor: color(value.endColor, defaultConnectionStyle.endColor),
2601
- startOpacity: Math.min(1, Math.max(0, finite(value.startOpacity, 1))),
2602
- endOpacity: Math.min(1, Math.max(0, finite(value.endOpacity, 1))),
2603
- width: Math.min(32, Math.max(0.5, finite(value.width, 2))),
2604
- lineType: ["solid", "dashed", "dotted"].includes(value.lineType) ? value.lineType : "solid"
2605
- };
2606
- }
2607
-
2608
- // ../renderer-pixi/src/builtins.ts
2609
- var base = (create, update) => ({ create, update, destroy(view) {
2610
- view.displayObject.destroy?.({ children: true });
2611
- } });
2612
- function registerBuiltinRenderers(registry) {
2613
- if (!registry.has("rect")) registry.register("rect", base((node, ctx) => ({ displayObject: ctx.display.createRect?.(node.width, node.height, node.props?.fill ?? 8162552) ?? ctx.display.createContainer(), state: {} }), (view, node) => applyTransform(view, node)));
2614
- registerTextureNode(registry, "image", ["preview", "image", "primary", "source"]);
2615
- registerTextureNode(registry, "video", ["preview", "poster", "video", "primary", "source"]);
2616
- registerTextureNode(registry, "audio", ["waveform", "preview", "audio", "primary", "source"]);
2617
- registerTextureNode(registry, "model", ["preview", "model", "primary", "source"]);
2618
- registerTextureNode(registry, "html", ["preview", "html", "primary", "source"]);
2619
- registerTextureNode(registry, "markdown", ["preview", "markdown", "primary", "source"]);
2620
- registerTextureNode(registry, "text-file", ["preview", "text-file", "primary", "source"]);
2621
- registerTextureNode(registry, "file", ["preview", "file", "primary", "source"]);
2622
- if (!registry.has("text")) registry.register("text", {
2623
- create(node, ctx) {
2624
- const displayObject = ctx.display.createContainer();
2625
- const text = ctx.display.createText?.(textValue(node), textStyle(node, node.width));
2626
- if (text) displayObject.addChild?.(text);
2627
- return { displayObject, state: { text } };
2628
- },
2629
- update(view, node) {
2630
- applyPlacement(view, node);
2631
- const text = view.state.text;
2632
- if (!text) return;
2633
- text.text = textValue(node);
2634
- const style = textStyle(node, node.width);
2635
- if (style) text.style = style;
2636
- },
2637
- destroy(view) {
2638
- view.displayObject.destroy?.({ children: true });
2639
- }
2640
- });
2641
- if (!registry.has("unknown-node")) registry.register("unknown-node", base((node, ctx) => ({ displayObject: ctx.display.createText?.(`${node.type}
2642
- ${node.id}`, { fill: 10265519 }) ?? ctx.display.createContainer(), state: {} }), (view, node) => applyTransform(view, node)));
2643
- }
2644
- function registerTextureNode(registry, type, refNames) {
2645
- if (registry.has(type)) return;
2646
- registry.register(type, {
2647
- async create(node, ctx) {
2648
- const ref = refNames.map((name) => node.assetRefs?.[name]).find(Boolean);
2649
- const lease = ref ? await ctx.assets.acquireTexture(ref, { kind: type }) : void 0;
2650
- if (ctx.signal.aborted) throw new DOMException("Aborted", "AbortError");
2651
- const displayObject = await ctx.display.createImage?.(ref, node) ?? ctx.display.createContainer();
2652
- if (lease?.texture !== void 0) displayObject.texture = lease.texture;
2653
- displayObject.mediaKind = type;
2654
- return { displayObject, state: { lease, ref } };
2655
- },
2656
- update(view, node) {
2657
- applyTransform(view, node);
2658
- },
2659
- destroy(view) {
2660
- view.displayObject.destroy?.({ children: true });
2661
- }
2662
- });
2663
- }
2664
- function textValue(node) {
2665
- const props = node.props;
2666
- const value = props.text ?? props.content ?? props.value ?? node.name ?? "";
2667
- return typeof value === "string" ? value : JSON.stringify(value);
2668
- }
2669
- function textStyle(node, width) {
2670
- const style = node.props.style;
2671
- const resolved = style && typeof style === "object" && !Array.isArray(style) ? { ...style } : {};
2672
- if (resolved.wordWrap !== false && Number.isFinite(width) && width > 0) {
2673
- resolved.wordWrap = true;
2674
- resolved.wordWrapWidth = width;
2675
- if (resolved.breakWords === void 0) resolved.breakWords = true;
2676
- }
2677
- return Object.keys(resolved).length > 0 ? resolved : void 0;
2678
- }
2679
- function applyPlacement(view, node) {
2680
- const d = view.displayObject;
2681
- d.x = node.x;
2682
- d.y = node.y;
2683
- d.rotation = node.rotation;
2684
- d.zIndex = node.zIndex;
2685
- }
2686
- function applyTransform(view, node) {
2687
- applyPlacement(view, node);
2688
- const d = view.displayObject;
2689
- d.width = node.width;
2690
- d.height = node.height;
2691
- }
2692
-
2693
- // ../renderer-pixi/src/pixi-adapter.ts
2694
- async function loadPixiRuntime() {
2695
- return await import('pixi.js');
2696
- }
2697
- function createPixiApplicationFactory(options = {}, runtimeLoader = loadPixiRuntime) {
2698
- return async () => {
2699
- const pixi = await runtimeLoader();
2700
- const app = new pixi.Application();
2701
- Object.defineProperty(app, "initOptions", {
2702
- // Pixi's TickerPlugin defaults to autoStart: true, which renders every
2703
- // display frame forever regardless of whether the scene changed. The
2704
- // renderer drives its own on-demand render loop (see
2705
- // PixiBoardRenderer.requestFrame), so the ticker must start stopped;
2706
- // callers can still opt back into continuous rendering explicitly.
2707
- value: { autoStart: false, sharedTicker: false, ...options },
2708
- configurable: true
2709
- });
2710
- return app;
2711
- };
2712
- }
2713
- function createPixiViewFactory(pixi) {
2714
- return {
2715
- createContainer: () => new pixi.Container({ isRenderGroup: true, sortableChildren: true }),
2716
- createRect: (width, height, fill) => {
2717
- const graphics = new pixi.Graphics();
2718
- graphics.rect?.(0, 0, width, height).fill?.(fill);
2719
- return graphics;
2720
- },
2721
- createImage: (_ref) => new pixi.Sprite(),
2722
- createText: (text, style) => new pixi.Text({ text, style })
2723
- };
2724
- }
2725
-
2726
- // ../renderer-pixi/src/renderer.ts
2727
- var DEFAULT_LOD_THRESHOLDS = [0.25, 0.5, 1];
2728
- function lodLevelFor(scale, thresholds) {
2729
- if (scale === void 0) return void 0;
2730
- let level = 0;
2731
- for (const threshold of thresholds) {
2732
- if (scale >= threshold) level++;
2733
- }
2734
- return level;
2735
- }
2736
- var PixiBoardRenderer = class {
2737
- registry;
2738
- diagnostics = { creates: 0, updates: 0, destroys: 0, lateUpdates: 0, activeViews: 0, pendingOperations: 0, textureLeases: 0, listeners: 0, tickers: 0 };
2739
- activeViews = /* @__PURE__ */ new Map();
2740
- spatialIndex;
2741
- options;
2742
- instanceAbort = new AbortController();
2743
- entries = /* @__PURE__ */ new Map();
2744
- operations = /* @__PURE__ */ new Map();
2745
- app;
2746
- world;
2747
- connectionLayers = /* @__PURE__ */ new Set();
2748
- revision;
2749
- nodeOrder = /* @__PURE__ */ new Map();
2750
- nextNodeOrder = 0;
2751
- displayOrderDirty = false;
2752
- nodesById = /* @__PURE__ */ new Map();
2753
- desiredIds = /* @__PURE__ */ new Set();
2754
- visibleBounds;
2755
- viewportEpoch = 0;
2756
- destroyed = false;
2757
- desynchronized = false;
2758
- viewFactory;
2759
- frameScheduled = false;
2760
- lodThresholds;
2761
- currentScale;
2762
- currentLodLevel;
2763
- constructor(options) {
2764
- this.options = options;
2765
- this.registry = options.registry ?? new NodeRendererRegistry();
2766
- this.spatialIndex = options.spatialIndex ?? new GridSpatialIndex();
2767
- this.lodThresholds = options.lod?.thresholds ?? DEFAULT_LOD_THRESHOLDS;
2768
- registerBuiltinRenderers(this.registry);
2769
- }
2770
- async init() {
2771
- if (this.destroyed) throw new Error("Renderer has been destroyed");
2772
- const applicationFactory = this.options.applicationFactory ?? createPixiApplicationFactory();
2773
- this.app = await applicationFactory();
2774
- await this.app.init?.({ preference: "webgl", antialias: false, powerPreference: "high-performance", autoStart: false, sharedTicker: false, ...this.app.initOptions });
2775
- const pixi = this.options.viewFactory ? void 0 : await loadPixiRuntime();
2776
- this.viewFactory = this.options.viewFactory ?? createPixiViewFactory(pixi);
2777
- this.world = this.viewFactory.createContainer();
2778
- this.app.stage.addChild?.(this.world);
2779
- }
2780
- async createConnectionLayer() {
2781
- this.assertAlive();
2782
- if (!this.world) throw new Error("Renderer has not initialized");
2783
- let layer;
2784
- layer = new ConnectionRenderLayer(() => this.requestFrame(), () => this.connectionLayers.delete(layer));
2785
- this.world.addChild?.(layer.container);
2786
- this.world.sortableChildren = true;
2787
- this.connectionLayers.add(layer);
2788
- layer.setVisibleBounds(this.visibleBounds);
2789
- return layer;
2790
- }
2791
- async rebuild(snapshot) {
2792
- this.assertAlive();
2793
- try {
2794
- this.revision = snapshot.revision;
2795
- this.nodesById.clear();
2796
- this.nodeOrder.clear();
2797
- this.nextNodeOrder = 0;
2798
- for (const node of snapshot.nodes) {
2799
- this.nodesById.set(node.id, node);
2800
- this.nodeOrder.set(node.id, this.nextNodeOrder++);
2801
- }
2802
- this.rebuildSpatialIndex(snapshot);
2803
- this.refreshDesiredIds();
2804
- for (const id of /* @__PURE__ */ new Set([...this.entries.keys(), ...this.operations.keys()])) await this.destroyView(id);
2805
- await this.reconcileActiveSet(++this.viewportEpoch);
2806
- this.desynchronized = false;
2807
- this.requestFrame();
2808
- } catch (error) {
2809
- this.desynchronized = true;
2810
- throw error;
2811
- }
2812
- }
2813
- async apply(update, changeSet) {
2814
- this.assertAlive();
2815
- if (this.desynchronized || this.revision === void 0 || changeSet.revision !== this.revision + 1 || changeSet.revision !== update.revision) {
2816
- return "rebuild-required";
2817
- }
2818
- try {
2819
- const touchedIds = /* @__PURE__ */ new Set([...changeSet.addedNodeIds, ...changeSet.updatedNodeIds, ...changeSet.assetChangedNodeIds]);
2820
- const nextNodes = /* @__PURE__ */ new Map();
2821
- for (const node of update.changedNodes) if (touchedIds.has(node.id)) nextNodes.set(node.id, node);
2822
- for (const id of touchedIds) {
2823
- if (!nextNodes.has(id)) throw new Error(`Renderer update is missing changed node: ${id}`);
2824
- }
2825
- const addedIds = new Set(changeSet.addedNodeIds);
2826
- const updatedIds = new Set(changeSet.updatedNodeIds);
2827
- const assetChangedIds = new Set(changeSet.assetChangedNodeIds);
2828
- for (const id of changeSet.removedNodeIds) {
2829
- this.nodesById.delete(id);
2830
- this.nodeOrder.delete(id);
2831
- this.desiredIds.delete(id);
2832
- this.spatialIndex.remove(id);
2833
- await this.destroyView(id);
2834
- }
2835
- for (const id of touchedIds) {
2836
- const node = nextNodes.get(id);
2837
- if (!node) continue;
2838
- this.nodesById.set(id, node);
2839
- if (!this.nodeOrder.has(id)) this.nodeOrder.set(id, this.nextNodeOrder++);
2840
- const item = { ...this.getBounds(node), id };
2841
- if (addedIds.has(id)) this.spatialIndex.insert(item);
2842
- else if (updatedIds.has(id)) this.spatialIndex.update(item);
2843
- }
2844
- const customVisibleCandidates = this.visibleBounds && this.options.cullingQuery && touchedIds.size > 0 ? this.visibleCandidatesFor(touchedIds) : void 0;
2845
- for (const id of touchedIds) {
2846
- const node = this.nodesById.get(id);
2847
- const desired = Boolean(node && this.isNodeDesired(node, customVisibleCandidates));
2848
- if (desired) this.desiredIds.add(id);
2849
- else this.desiredIds.delete(id);
2850
- if (!node || !desired) {
2851
- await this.destroyView(id);
2852
- continue;
2853
- }
2854
- await this.ensureView(node, assetChangedIds.has(id));
2855
- }
2856
- this.revision = update.revision;
2857
- this.requestFrame();
2858
- return "applied";
2859
- } catch (error) {
2860
- this.desynchronized = true;
2861
- throw error;
2862
- }
2863
- }
2864
- async setVisibleBounds(bounds, scale) {
2865
- this.assertAlive();
2866
- if (scale !== void 0 && (!Number.isFinite(scale) || scale <= 0)) {
2867
- throw new RangeError("Viewport scale must be finite and greater than zero");
2868
- }
2869
- this.visibleBounds = bounds;
2870
- for (const layer of this.connectionLayers) layer.setVisibleBounds(bounds);
2871
- this.currentScale = scale;
2872
- const nextLevel = lodLevelFor(scale, this.lodThresholds);
2873
- const levelChanged = nextLevel !== this.currentLodLevel;
2874
- this.currentLodLevel = nextLevel;
2875
- const retained = levelChanged ? new Set(this.entries.keys()) : void 0;
2876
- this.refreshDesiredIds();
2877
- const epoch = ++this.viewportEpoch;
2878
- await this.reconcileActiveSet(epoch);
2879
- if (retained) await this.refreshLodForRetainedViews(retained, epoch);
2880
- this.requestFrame();
2881
- }
2882
- setCullingQuery(query) {
2883
- this.options.cullingQuery = query;
2884
- }
2885
- /**
2886
- * The ids culling currently keeps, or undefined when nothing has narrowed
2887
- * the renderer yet. The distinction matters to callers that mirror this set
2888
- * in the DOM: undefined has to read as "no culling information", not as
2889
- * "nothing is visible", or an overlay would blank out on a renderer that
2890
- * retains everything.
2891
- *
2892
- * Returns a copy — the internal set is mutated during reconcile, and handing
2893
- * it out directly would let a caller observe a half-applied frame.
2894
- */
2895
- visibleNodeIds() {
2896
- return this.visibleBounds ? new Set(this.desiredIds) : void 0;
2897
- }
2898
- async refreshRegisteredTypes() {
2899
- this.assertAlive();
2900
- this.rebuildSpatialIndexFromCache();
2901
- this.refreshDesiredIds();
2902
- for (const id of /* @__PURE__ */ new Set([...this.entries.keys(), ...this.operations.keys()])) await this.destroyView(id);
2903
- await this.reconcileActiveSet(++this.viewportEpoch);
2904
- this.requestFrame();
2905
- }
2906
- getBounds(node) {
2907
- const definition = this.options.nodeTypes?.get(node.type);
2908
- return definition ? definition.getBounds(node) : rotatedRectBounds(node);
2909
- }
2910
- hitTest(worldPoint) {
2911
- const ids = this.spatialIndex.queryPoint?.(worldPoint) ?? this.entries.keys();
2912
- 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);
2913
- for (const { node } of order) {
2914
- const entry = this.entries.get(node.id);
2915
- if (entry.renderer.hitTest?.(node, worldPoint) ?? contains2(this.getBounds(node), worldPoint)) return node.id;
2916
- }
2917
- return void 0;
2918
- }
2919
- async capture(request, options = {}) {
2920
- this.assertAlive();
2921
- const signal = combineSignals(this.instanceAbort.signal, options.signal);
2922
- if (signal.aborted) throw abortError();
2923
- const scale = request.scale ?? 1;
2924
- if (!Number.isFinite(scale) || scale <= 0) throw new RangeError("Capture scale must be positive");
2925
- let target = this.world;
2926
- let frame;
2927
- if (request.target === "node") {
2928
- const node = this.nodesById.get(request.nodeId);
2929
- if (!node) throw new Error(`Node ${request.nodeId} does not exist`);
2930
- const temporary = !this.entries.has(node.id);
2931
- if (temporary) await this.ensureView(node);
2932
- const entry = this.entries.get(node.id);
2933
- if (!entry) throw new Error(`Node ${request.nodeId} is not available for capture`);
2934
- target = entry.view.displayObject;
2935
- frame = { minX: 0, minY: 0, maxX: node.width, maxY: node.height };
2936
- try {
2937
- return await this.captureFrame(target, frame, scale, request, signal, options.requestId);
2938
- } finally {
2939
- if (temporary) await this.destroyView(node.id);
2940
- }
2941
- }
2942
- if (request.target === "bounds") frame = request.bounds;
2943
- if (request.target === "viewport" && this.app?.screen) frame = { minX: 0, minY: 0, maxX: this.app.screen.width, maxY: this.app.screen.height };
2944
- for (const layer of this.connectionLayers) layer.setVisibleBounds(void 0);
2945
- try {
2946
- return await this.captureFrame(target, frame, scale, request, signal, options.requestId);
2947
- } finally {
2948
- for (const layer of this.connectionLayers) layer.setVisibleBounds(this.visibleBounds);
2949
- }
2950
- }
2951
- async destroy() {
2952
- if (this.destroyed) return;
2953
- this.destroyed = true;
2954
- this.instanceAbort.abort();
2955
- for (const operation of this.operations.values()) operation.controller.abort();
2956
- await Promise.allSettled([...this.operations.values()].map((operation) => operation.promise).filter(Boolean));
2957
- for (const id of [...this.entries.keys()]) await this.destroyView(id);
2958
- for (const layer of [...this.connectionLayers]) layer.destroy();
2959
- this.world?.destroy?.({ children: true });
2960
- this.app?.destroy?.(true);
2961
- this.entries.clear();
2962
- this.operations.clear();
2963
- this.activeViews.clear();
2964
- this.desiredIds.clear();
2965
- this.updateDiagnosticCounts();
2966
- }
2967
- syncDisplayOrder() {
2968
- const world = this.world;
2969
- if (!world?.children) return;
2970
- const order = /* @__PURE__ */ new Map();
2971
- for (const [id, entry] of this.entries) {
2972
- entry.view.displayObject.zIndex = entry.node.zIndex;
2973
- order.set(entry.view.displayObject, this.nodeOrder.get(id) ?? -1);
2974
- }
2975
- world.children.sort((a, b) => (a.zIndex ?? 0) - (b.zIndex ?? 0) || (order.get(a) ?? -1) - (order.get(b) ?? -1));
2976
- world.sortDirty = true;
2977
- }
2978
- async ensureView(node, forceRecreate = false) {
2979
- const renderer = this.registry.get(node.type) ?? this.registry.get("unknown-node");
2980
- const current = this.entries.get(node.id);
2981
- if (current && !forceRecreate && current.node.type === node.type && current.node.typeVersion === node.typeVersion && current.renderer === renderer && sameAssetRefs(current.node.assetRefs, node.assetRefs)) {
2982
- const operation2 = this.beginOperation(node.id);
2983
- const task2 = (async () => {
2984
- const orderChanged = current.node.zIndex !== node.zIndex;
2985
- current.node = node;
2986
- this.diagnostics.updates++;
2987
- await renderer.update(current.view, node, this.context(combineSignals(current.lifetime.signal, operation2.controller.signal), current.scope));
2988
- if (orderChanged) this.displayOrderDirty = true;
2989
- if (!this.isCurrentOperation(node.id, operation2) || this.entries.get(node.id) !== current) this.diagnostics.lateUpdates++;
2990
- })();
2991
- await this.trackOperation(node.id, operation2, task2);
2992
- return;
2993
- }
2994
- if (current || forceRecreate) await this.destroyView(node.id);
2995
- const operation = this.beginOperation(node.id);
2996
- const lifetime = new AbortController();
2997
- const scope = new ResourceScope(this);
2998
- const signal = combineSignals(this.instanceAbort.signal, lifetime.signal, operation.controller.signal);
2999
- const task = (async () => {
3000
- let view;
3001
- try {
3002
- view = await renderer.create(node, this.context(signal, scope));
3003
- if (signal.aborted || !this.isCurrentOperation(node.id, operation) || this.nodesById.get(node.id) !== node || !this.desiredIds.has(node.id)) {
3004
- this.diagnostics.lateUpdates++;
3005
- renderer.destroy(view, this.context(signal, scope));
3006
- scope.dispose();
3007
- return;
3008
- }
3009
- await renderer.update(view, node, this.context(signal, scope));
3010
- if (signal.aborted || !this.isCurrentOperation(node.id, operation) || this.nodesById.get(node.id) !== node || !this.desiredIds.has(node.id)) {
3011
- this.diagnostics.lateUpdates++;
3012
- renderer.destroy(view, this.context(signal, scope));
3013
- scope.dispose();
3014
- return;
3015
- }
3016
- const entry = { node, view, renderer, lifetime, scope };
3017
- this.entries.set(node.id, entry);
3018
- this.activeViews.set(node.id, view);
3019
- this.world?.addChild?.(view.displayObject);
3020
- this.displayOrderDirty = true;
3021
- this.diagnostics.creates++;
3022
- this.updateDiagnosticCounts();
3023
- } catch (error) {
3024
- scope.dispose();
3025
- if (signal.aborted || isAbortError(error)) {
3026
- this.diagnostics.lateUpdates++;
3027
- return;
3028
- }
3029
- throw error;
3030
- }
3031
- })();
3032
- await this.trackOperation(node.id, operation, task);
3033
- }
3034
- beginOperation(id) {
3035
- const previous = this.operations.get(id);
3036
- previous?.controller.abort();
3037
- const operation = { version: (previous?.version ?? 0) + 1, controller: new AbortController() };
3038
- this.operations.set(id, operation);
3039
- this.updateDiagnosticCounts();
3040
- return operation;
3041
- }
3042
- async trackOperation(id, operation, task) {
3043
- operation.promise = task;
3044
- try {
3045
- await task;
3046
- } finally {
3047
- if (this.operations.get(id) === operation) this.operations.delete(id);
3048
- operation.controller.abort();
3049
- this.updateDiagnosticCounts();
3050
- }
3051
- }
3052
- isCurrentOperation(id, operation) {
3053
- return this.operations.get(id) === operation;
3054
- }
3055
- async destroyView(id) {
3056
- const operation = this.operations.get(id);
3057
- operation?.controller.abort();
3058
- const entry = this.entries.get(id);
3059
- if (!entry) return;
3060
- entry.lifetime.abort();
3061
- this.entries.delete(id);
3062
- this.activeViews.delete(id);
3063
- this.world?.removeChild?.(entry.view.displayObject);
3064
- entry.renderer.destroy(entry.view, this.context(entry.lifetime.signal, entry.scope));
3065
- entry.scope.dispose();
3066
- this.diagnostics.destroys++;
3067
- this.updateDiagnosticCounts();
3068
- }
3069
- async reconcileActiveSet(epoch) {
3070
- for (const id of /* @__PURE__ */ new Set([...this.entries.keys(), ...this.operations.keys()])) {
3071
- if (!this.desiredIds.has(id)) await this.destroyView(id);
3072
- }
3073
- for (const id of this.desiredIds) {
3074
- if (epoch !== this.viewportEpoch || this.destroyed) return;
3075
- const node = this.nodesById.get(id);
3076
- if (node && !this.entries.has(id)) await this.ensureView(node);
3077
- }
3078
- }
3079
- /**
3080
- * Re-runs update() on views that outlived a level-of-detail change, so a
3081
- * node renderer can redraw itself for the new tier. Goes through ensureView,
3082
- * which already carries the operation-versioning and late-update guards that
3083
- * keep a redraw from racing an in-flight create.
3084
- */
3085
- async refreshLodForRetainedViews(retained, epoch) {
3086
- for (const id of retained) {
3087
- if (epoch !== this.viewportEpoch || this.destroyed) return;
3088
- const node = this.nodesById.get(id);
3089
- if (node && this.entries.has(id)) await this.ensureView(node);
3090
- }
3091
- }
3092
- refreshDesiredIds() {
3093
- const candidates = this.visibleBounds ? this.options.cullingQuery?.(this.visibleBounds) ?? this.spatialIndex.query(this.visibleBounds) : this.nodesById.keys();
3094
- this.desiredIds = new Set([...candidates].filter((id) => this.nodesById.get(id)?.visible !== false));
3095
- }
3096
- isNodeDesired(node, customVisibleCandidates) {
3097
- if (node.visible === false) return false;
3098
- if (!this.visibleBounds) return true;
3099
- if (customVisibleCandidates) return customVisibleCandidates.has(node.id);
3100
- return intersects3(this.getBounds(node), this.visibleBounds);
3101
- }
3102
- visibleCandidatesFor(touchedIds) {
3103
- const candidates = this.options.cullingQuery(this.visibleBounds);
3104
- const has = candidates.has;
3105
- if (typeof has === "function") {
3106
- const visibleIds2 = /* @__PURE__ */ new Set();
3107
- for (const id of touchedIds) if (has.call(candidates, id)) visibleIds2.add(id);
3108
- return visibleIds2;
3109
- }
3110
- const pending = new Set(touchedIds);
3111
- const visibleIds = /* @__PURE__ */ new Set();
3112
- for (const id of candidates) {
3113
- if (!pending.delete(id)) continue;
3114
- visibleIds.add(id);
3115
- if (pending.size === 0) break;
3116
- }
3117
- return visibleIds;
3118
- }
3119
- rebuildSpatialIndex(snapshot) {
3120
- this.spatialIndex.rebuild(snapshot.nodes.map((node) => ({ ...this.getBounds(node), id: node.id })));
3121
- }
3122
- rebuildSpatialIndexFromCache() {
3123
- const items = [...this.nodesById.values()].map((node) => ({ ...this.getBounds(node), id: node.id }));
3124
- this.spatialIndex.rebuild(items);
3125
- }
3126
- async captureFrame(target, frame, scale, request, signal, requestId) {
3127
- if (signal.aborted) throw abortError();
3128
- const value = this.options.capture ? await this.options.capture({ target, frame, scale, format: "png" }, request, signal) : await this.captureWithPixi(target, frame, scale);
3129
- if (signal.aborted) throw abortError();
3130
- return { ...value, revision: this.revision ?? 0, ...requestId ? { requestId } : {} };
3131
- }
3132
- async captureWithPixi(target, frame, scale) {
3133
- const extract = this.app?.renderer?.extract?.base64;
3134
- if (!extract) throw new Error("Capture is unavailable without a Pixi extract adapter");
3135
- const rectangle = frame ? pixiRectangle(frame) : void 0;
3136
- const dataUrl = await extract.call(this.app.renderer.extract, { target, frame: rectangle, format: "png", resolution: scale });
3137
- return {
3138
- dataUrl,
3139
- mimeType: "image/png",
3140
- ...rectangle ? { width: Math.round(rectangle.width * scale), height: Math.round(rectangle.height * scale) } : {}
3141
- };
3142
- }
3143
- context(signal, scope) {
3144
- if (!this.viewFactory) throw new Error("Renderer is not initialized");
3145
- return {
3146
- signal,
3147
- assets: { acquireTexture: (ref, options) => this.acquireTexture(scope, signal, ref, options) },
3148
- resources: scope.api,
3149
- invalidate: () => {
3150
- this.options.onInvalidate?.();
3151
- this.requestFrame();
3152
- },
3153
- lod: { level: this.currentLodLevel, scale: this.currentScale },
3154
- diagnostics: this.diagnostics,
3155
- display: this.viewFactory
3156
- };
3157
- }
3158
- /**
3159
- * Renders exactly once per idle scene change instead of relying on Pixi's
3160
- * default continuous ticker (which redraws every display frame forever,
3161
- * regardless of whether anything changed). Calls within the same
3162
- * microtask are coalesced into a single render. Skipped while a custom
3163
- * node renderer's own ticker subscription is active — see
3164
- * syncTickerState — because in that case Pixi's own ticker is already
3165
- * driving continuous frames for that animation.
3166
- */
3167
- requestFrame() {
3168
- if (this.displayOrderDirty) {
3169
- this.syncDisplayOrder();
3170
- this.displayOrderDirty = false;
3171
- }
3172
- if (this.destroyed || !this.app || this.diagnostics.tickers > 0 || this.frameScheduled) return;
3173
- this.frameScheduled = true;
3174
- void Promise.resolve().then(() => {
3175
- this.frameScheduled = false;
3176
- if (this.destroyed || !this.app || this.diagnostics.tickers > 0) return;
3177
- this.app.render?.();
3178
- });
3179
- }
3180
- /**
3181
- * A custom node renderer that subscribes via context.resources.addTicker
3182
- * wants continuous per-frame callbacks (e.g. an animated node) — that is
3183
- * the "registered animation active" case the on-demand-rendering
3184
- * invariant carves out, so Pixi's own ticker must run continuously for as
3185
- * long as at least one such subscription is active, and fall back to
3186
- * on-demand rendering once the last one is removed.
3187
- */
3188
- syncTickerState() {
3189
- if (this.destroyed || !this.app) return;
3190
- if (this.diagnostics.tickers > 0) this.app.ticker?.start?.();
3191
- else this.app.ticker?.stop?.();
3192
- }
3193
- async acquireTexture(scope, signal, ref, options) {
3194
- const lease = await (this.options.acquireTexture ?? (async () => ({})))(ref, {
3195
- lodLevel: this.currentLodLevel,
3196
- lodScale: this.currentScale,
3197
- ...options,
3198
- signal
3199
- });
3200
- if (signal.aborted) {
3201
- lease.release?.();
3202
- throw abortError();
3203
- }
3204
- let active = true;
3205
- this.diagnostics.textureLeases++;
3206
- const release = () => {
3207
- if (!active) return;
3208
- active = false;
3209
- lease.release?.();
3210
- this.diagnostics.textureLeases--;
3211
- };
3212
- scope.add(release);
3213
- return { ...lease, release };
3214
- }
3215
- updateDiagnosticCounts() {
3216
- this.diagnostics.activeViews = this.activeViews.size;
3217
- this.diagnostics.pendingOperations = this.operations.size;
3218
- }
3219
- assertAlive() {
3220
- if (this.destroyed) throw new Error("Renderer has been destroyed");
3221
- if (!this.app) throw new Error("Renderer is not initialized");
3222
- }
3223
- };
3224
- var ResourceScope = class {
3225
- constructor(owner) {
3226
- this.owner = owner;
3227
- this.api = {
3228
- onCleanup: (cleanup) => this.add(cleanup),
3229
- listen: (target, type, listener, options) => {
3230
- target.addEventListener(type, listener, options);
3231
- this.owner.diagnostics.listeners++;
3232
- return this.add(() => {
3233
- target.removeEventListener(type, listener, options);
3234
- this.owner.diagnostics.listeners--;
3235
- });
3236
- },
3237
- addTicker: (listener) => {
3238
- const ticker = this.owner.app?.ticker;
3239
- ticker?.add?.(listener);
3240
- this.owner.diagnostics.tickers++;
3241
- this.owner.syncTickerState();
3242
- return this.add(() => {
3243
- ticker?.remove?.(listener);
3244
- this.owner.diagnostics.tickers--;
3245
- this.owner.syncTickerState();
3246
- });
3247
- }
3248
- };
3249
- }
3250
- owner;
3251
- cleanups = /* @__PURE__ */ new Set();
3252
- disposed = false;
3253
- api;
3254
- add(cleanup) {
3255
- if (this.disposed) {
3256
- cleanup();
3257
- return () => {
3258
- };
3259
- }
3260
- let active = true;
3261
- const wrapped = () => {
3262
- if (!active) return;
3263
- active = false;
3264
- this.cleanups.delete(wrapped);
3265
- cleanup();
3266
- };
3267
- this.cleanups.add(wrapped);
3268
- return wrapped;
3269
- }
3270
- dispose() {
3271
- if (this.disposed) return;
3272
- this.disposed = true;
3273
- for (const cleanup of [...this.cleanups].reverse()) cleanup();
3274
- this.cleanups.clear();
3275
- }
3276
- };
3277
- function contains2(bounds, point) {
3278
- return point.x >= bounds.minX && point.x <= bounds.maxX && point.y >= bounds.minY && point.y <= bounds.maxY;
3279
- }
3280
- function intersects3(left, right) {
3281
- return left.minX <= right.maxX && left.maxX >= right.minX && left.minY <= right.maxY && left.maxY >= right.minY;
3282
- }
3283
- function sameAssetRefs(a, b) {
3284
- return JSON.stringify(a ?? {}) === JSON.stringify(b ?? {});
3285
- }
3286
- function abortError() {
3287
- return new DOMException("Aborted", "AbortError");
3288
- }
3289
- function isAbortError(error) {
3290
- return error instanceof DOMException && error.name === "AbortError";
3291
- }
3292
- function pixiRectangle(frame) {
3293
- const rectangle = {
3294
- x: frame.minX,
3295
- y: frame.minY,
3296
- width: frame.maxX - frame.minX,
3297
- height: frame.maxY - frame.minY,
3298
- copyTo(target) {
3299
- target.x = rectangle.x;
3300
- target.y = rectangle.y;
3301
- target.width = rectangle.width;
3302
- target.height = rectangle.height;
3303
- return target;
3304
- }
3305
- };
3306
- return rectangle;
3307
- }
3308
- function combineSignals(...values) {
3309
- const signals = values.filter(Boolean);
3310
- const any = AbortSignal.any;
3311
- if (any) return any(signals);
3312
- const controller = new AbortController();
3313
- const abort = () => controller.abort();
3314
- for (const signal of signals) {
3315
- if (signal.aborted) controller.abort();
3316
- else signal.addEventListener("abort", abort, { once: true });
3317
- }
3318
- return controller.signal;
3319
- }
3320
-
3321
- // src/transform.ts
3322
- var DEFAULT_MIN_SIZE2 = 8;
3323
- var TransformController = class {
3324
- constructor(host, options = {}) {
3325
- this.host = host;
3326
- this.options = options;
3327
- }
3328
- host;
3329
- options;
3330
- session;
3331
- bounds() {
3332
- const nodes = this.selectedNodes();
3333
- if (nodes.length === 0) return void 0;
3334
- if (nodes.length === 1) {
3335
- const [node] = nodes;
3336
- return {
3337
- x: node.x,
3338
- y: node.y,
3339
- width: node.width,
3340
- height: node.height,
3341
- rotation: node.rotation,
3342
- nodeIds: [node.id]
3343
- };
3344
- }
3345
- let minX = Infinity;
3346
- let minY = Infinity;
3347
- let maxX = -Infinity;
3348
- let maxY = -Infinity;
3349
- for (const node of nodes) {
3350
- for (const corner of rotatedCorners(node)) {
3351
- minX = Math.min(minX, corner.x);
3352
- minY = Math.min(minY, corner.y);
3353
- maxX = Math.max(maxX, corner.x);
3354
- maxY = Math.max(maxY, corner.y);
3355
- }
3356
- }
3357
- return {
3358
- x: minX,
3359
- y: minY,
3360
- width: maxX - minX,
3361
- height: maxY - minY,
3362
- rotation: 0,
3363
- nodeIds: nodes.map((node) => node.id)
3364
- };
3365
- }
3366
- handles() {
3367
- const bounds = this.bounds();
3368
- if (!bounds) return [];
3369
- const cos = Math.cos(bounds.rotation);
3370
- const sin = Math.sin(bounds.rotation);
3371
- const allowed = new Set(this.options.handles ?? RESIZE_HANDLES);
3372
- return RESIZE_HANDLES.filter((handle) => allowed.has(handle)).map((handle) => {
3373
- const local = handleLocalPoint(handle, bounds.width, bounds.height);
3374
- return {
3375
- handle,
3376
- world: {
3377
- x: bounds.x + local.x * cos - local.y * sin,
3378
- y: bounds.y + local.x * sin + local.y * cos
3379
- },
3380
- cursor: resizeHandleCursor(handle, bounds.rotation)
3381
- };
3382
- });
3383
- }
3384
- begin(handle) {
3385
- this.session?.commit();
3386
- const nodes = this.selectedNodes();
3387
- const bounds = this.bounds();
3388
- if (nodes.length === 0 || !bounds) return void 0;
3389
- const session = new ActiveSession(
3390
- this.host,
3391
- handle,
3392
- nodes,
3393
- bounds,
3394
- `resize:${this.host.nextId()}`,
3395
- {
3396
- minWidth: this.options.minWidth ?? DEFAULT_MIN_SIZE2,
3397
- minHeight: this.options.minHeight ?? DEFAULT_MIN_SIZE2
3398
- },
3399
- () => {
3400
- if (this.session === session) this.session = void 0;
3401
- }
3402
- );
3403
- this.session = session;
3404
- return session;
3405
- }
3406
- active() {
3407
- return this.session !== void 0;
3408
- }
3409
- /** Ends any live gesture; called when the board is destroyed. */
3410
- dispose() {
3411
- this.session?.commit();
3412
- }
3413
- selectedNodes() {
3414
- return this.host.selection().map((id) => this.host.getNode(id)).filter((node) => node !== void 0);
3415
- }
3416
- };
3417
- var ActiveSession = class {
3418
- constructor(host, handle, nodes, groupOrigin, coalesceKey, limits, onEnd) {
3419
- this.host = host;
3420
- this.handle = handle;
3421
- this.groupOrigin = groupOrigin;
3422
- this.coalesceKey = coalesceKey;
3423
- this.limits = limits;
3424
- this.onEnd = onEnd;
3425
- this.origins = nodes.map((node) => ({ id: node.id, type: node.type, geometry: nodeGeometry(node) }));
3426
- }
3427
- host;
3428
- handle;
3429
- groupOrigin;
3430
- coalesceKey;
3431
- limits;
3432
- onEnd;
3433
- done = false;
3434
- origins;
3435
- update(deltaWorld, options = {}) {
3436
- if (this.done) return;
3437
- if (!Number.isFinite(deltaWorld.x) || !Number.isFinite(deltaWorld.y)) return;
3438
- this.host.transaction(
3439
- "Resize selection",
3440
- () => {
3441
- if (this.origins.length === 1) {
3442
- const [only] = this.origins;
3443
- const policy = this.host.resizePolicy(only.type);
3444
- const adjustedDelta = options.preserveAspectRatio ? preserveAspectDelta(deltaWorld, this.handle, only.geometry) : deltaWorld;
3445
- const limits = options.preserveAspectRatio && (!policy || policy.mode === "free") ? proportionalMinimums(only.geometry, this.limits) : this.limits;
3446
- this.host.resize(only.id, {
3447
- handle: this.handle,
3448
- deltaWorld: adjustedDelta,
3449
- origin: only.geometry,
3450
- minWidth: limits.minWidth,
3451
- minHeight: limits.minHeight
3452
- });
3453
- return;
3454
- }
3455
- this.scaleGroup(deltaWorld, options.preserveAspectRatio === true);
3456
- },
3457
- { origin: "ui", coalesceKey: this.coalesceKey }
3458
- );
3459
- }
3460
- commit() {
3461
- if (this.done) return;
3462
- this.done = true;
3463
- this.onEnd();
3464
- }
3465
- cancel() {
3466
- if (this.done) return;
3467
- this.done = true;
3468
- this.host.transaction(
3469
- "Resize selection",
3470
- () => {
3471
- for (const { id, geometry } of this.origins) {
3472
- this.host.update(id, {
3473
- x: geometry.x,
3474
- y: geometry.y,
3475
- width: geometry.width,
3476
- height: geometry.height
3477
- });
3478
- }
3479
- },
3480
- { origin: "ui", coalesceKey: this.coalesceKey }
3481
- );
3482
- this.onEnd();
3483
- }
3484
- /**
3485
- * Scales the shared group box by the handle drag, then maps every node into
3486
- * the new box: its offset from the anchored corner and its size both scale
3487
- * by the same factor, so the selection resizes as one rigid unit.
3488
- *
3489
- * Each node's size still goes through its own ResizePolicy, so a fixed node
3490
- * inside a multi-selection keeps its size (and its scaled position) while
3491
- * its neighbours grow. Placement is computed here rather than by
3492
- * nodes.resize(), which would re-anchor each node against its own origin
3493
- * and tear the group apart.
3494
- */
3495
- scaleGroup(deltaWorld, preserveAspectRatio) {
3496
- const box = this.groupOrigin;
3497
- const axes = resizeHandleAxes(this.handle);
3498
- const gestureDelta = preserveAspectRatio ? preserveAspectDelta(deltaWorld, this.handle, { x: box.x, y: box.y, width: box.width, height: box.height, rotation: 0 }) : deltaWorld;
3499
- const width = Math.max(box.width + axes.horizontal * gestureDelta.x, this.limits.minWidth);
3500
- const height = Math.max(box.height + axes.vertical * gestureDelta.y, this.limits.minHeight);
3501
- let scaleX = box.width > 0 ? width / box.width : 1;
3502
- let scaleY = box.height > 0 ? height / box.height : 1;
3503
- if (preserveAspectRatio && axes.horizontal !== 0 && axes.vertical !== 0) {
3504
- let minimumScale = Math.max(
3505
- box.width > 0 ? this.limits.minWidth / box.width : 1,
3506
- box.height > 0 ? this.limits.minHeight / box.height : 1
3507
- );
3508
- for (const { type, geometry } of this.origins) {
3509
- const policy = this.host.resizePolicy(type);
3510
- if (policy && policy.mode !== "free") continue;
3511
- if (geometry.width <= 0 || geometry.height <= 0) {
3512
- minimumScale = Math.max(
3513
- minimumScale,
3514
- geometry.width > 0 ? this.limits.minWidth / geometry.width : 0,
3515
- geometry.height > 0 ? this.limits.minHeight / geometry.height : 0
3516
- );
3517
- continue;
3518
- }
3519
- const minimums = proportionalMinimums(geometry, this.limits);
3520
- minimumScale = Math.max(
3521
- minimumScale,
3522
- minimums.minWidth / geometry.width,
3523
- minimums.minHeight / geometry.height
3524
- );
3525
- }
3526
- const scale = Math.max(scaleX, scaleY, minimumScale);
3527
- scaleX = scale;
3528
- scaleY = scale;
3529
- }
3530
- const anchorX = axes.horizontal === -1 ? box.x + box.width : box.x;
3531
- const anchorY = axes.vertical === -1 ? box.y + box.height : box.y;
3532
- for (const { id, type, geometry } of this.origins) {
3533
- const node = this.host.getNode(id);
3534
- if (!node) continue;
3535
- const policy = this.host.resizePolicy(type);
3536
- const limits = preserveAspectRatio && (!policy || policy.mode === "free") ? geometry.width <= 0 || geometry.height <= 0 ? {
3537
- minWidth: geometry.width > 0 ? this.limits.minWidth : 0,
3538
- minHeight: geometry.height > 0 ? this.limits.minHeight : 0
3539
- } : proportionalMinimums(geometry, this.limits) : this.limits;
3540
- const resolved = resolveResizeSize(node, policy, {
3541
- handle: this.handle,
3542
- width: geometry.width * scaleX,
3543
- height: geometry.height * scaleY,
3544
- origin: geometry,
3545
- minWidth: limits.minWidth,
3546
- minHeight: limits.minHeight
3547
- });
3548
- if (!resolved) continue;
3549
- this.host.update(id, {
3550
- ...resolved.patch,
3551
- x: anchorX + (geometry.x - anchorX) * scaleX,
3552
- y: anchorY + (geometry.y - anchorY) * scaleY,
3553
- width: resolved.width,
3554
- height: resolved.height
3555
- });
3556
- }
3557
- }
3558
- };
3559
- function proportionalMinimums(geometry, limits) {
3560
- const ratio = geometry.width / geometry.height;
3561
- if (!Number.isFinite(ratio) || ratio <= 0) return limits;
3562
- return {
3563
- minWidth: Math.max(limits.minWidth, limits.minHeight * ratio),
3564
- minHeight: Math.max(limits.minHeight, limits.minWidth / ratio)
3565
- };
3566
- }
3567
- function preserveAspectDelta(deltaWorld, handle, origin) {
3568
- const axes = resizeHandleAxes(handle);
3569
- if (axes.horizontal === 0 || axes.vertical === 0 || origin.width <= 0 || origin.height <= 0) return deltaWorld;
3570
- const ratio = origin.width / origin.height;
3571
- const cos = Math.cos(origin.rotation);
3572
- const sin = Math.sin(origin.rotation);
3573
- const localDelta = { x: deltaWorld.x * cos + deltaWorld.y * sin, y: -deltaWorld.x * sin + deltaWorld.y * cos };
3574
- const widthDelta = axes.horizontal * localDelta.x;
3575
- const heightDelta = axes.vertical * localDelta.y;
3576
- let localResult;
3577
- if (Math.abs(widthDelta) >= Math.abs(heightDelta) * ratio) {
3578
- localResult = { x: localDelta.x, y: axes.vertical * (widthDelta / ratio) };
3579
- } else {
3580
- localResult = { x: axes.horizontal * (heightDelta * ratio), y: localDelta.y };
3581
- }
3582
- return { x: localResult.x * cos - localResult.y * sin, y: localResult.x * sin + localResult.y * cos };
3583
- }
3584
- function handleLocalPoint(handle, width, height) {
3585
- const axes = resizeHandleAxes(handle);
3586
- return {
3587
- x: axes.horizontal === -1 ? 0 : axes.horizontal === 1 ? width : width / 2,
3588
- y: axes.vertical === -1 ? 0 : axes.vertical === 1 ? height : height / 2
3589
- };
3590
- }
3591
- function rotatedCorners(node) {
3592
- const cos = Math.cos(node.rotation);
3593
- const sin = Math.sin(node.rotation);
3594
- return [
3595
- { x: 0, y: 0 },
3596
- { x: node.width, y: 0 },
3597
- { x: node.width, y: node.height },
3598
- { x: 0, y: node.height }
3599
- ].map((point) => ({
3600
- x: node.x + point.x * cos - point.y * sin,
3601
- y: node.y + point.x * sin + point.y * cos
3602
- }));
3603
- }
3604
-
3605
- // src/index.ts
3606
- var focusedBoard;
3607
- var DEFAULT_VIRTUALIZATION_PADDING = 256;
3608
- var EventHub2 = class {
3609
- listeners = /* @__PURE__ */ new Map();
3610
- on(eventName, listener) {
3611
- const listeners = this.listeners.get(eventName) ?? /* @__PURE__ */ new Set();
3612
- listeners.add(listener);
3613
- this.listeners.set(eventName, listeners);
3614
- return () => listeners.delete(listener);
3615
- }
3616
- emit(eventName, event) {
3617
- for (const listener of this.listeners.get(eventName) ?? []) {
3618
- try {
3619
- listener(event);
3620
- } catch {
3621
- }
3622
- }
3623
- }
3624
- clear() {
3625
- this.listeners.clear();
3626
- }
3627
- };
3628
- var PublicNodeHandle = class {
3629
- constructor(board, id) {
3630
- this.board = board;
3631
- this.id = id;
3632
- }
3633
- board;
3634
- id;
3635
- getAttrs() {
3636
- const node = this.board.getNode(this.id);
3637
- if (!node) throw new NodeNotFoundError(this.id);
3638
- return node;
3639
- }
3640
- setAttrs(patch) {
3641
- this.board.setNodeAttrs(this.id, patch);
3642
- return this;
3643
- }
3644
- x(value) {
3645
- return this.attr("x", value);
3646
- }
3647
- y(value) {
3648
- return this.attr("y", value);
3649
- }
3650
- width(value) {
3651
- return this.attr("width", value);
3652
- }
3653
- height(value) {
3654
- return this.attr("height", value);
3655
- }
3656
- rotation(value) {
3657
- return this.attr("rotation", value);
3658
- }
3659
- visible(value) {
3660
- if (value === void 0) return this.getAttrs().visible ?? true;
3661
- this.setAttrs({ visible: value });
3662
- return this;
3663
- }
3664
- remove() {
3665
- this.board.removeNode(this.id);
3666
- }
3667
- on(eventName, listener) {
3668
- return this.board.onNode(this.id, eventName, listener);
3669
- }
3670
- attr(key, value) {
3671
- if (value === void 0) return this.getAttrs()[key];
3672
- this.setAttrs({ [key]: value });
3673
- return this;
3674
- }
3675
- };
3676
- var PixiBoardFacade = class {
3677
- ready;
3678
- signal;
3679
- capabilities;
3680
- nodes;
3681
- nodeTypes;
3682
- transform;
3683
- selection;
3684
- viewport;
3685
- history;
3686
- document;
3687
- lifecycle = "created";
3688
- abortController = new AbortController();
3689
- core;
3690
- events = new EventHub2();
3691
- nodeEvents = new EventHub2();
3692
- cleanup = /* @__PURE__ */ new Set();
3693
- options;
3694
- rendererRegistry;
3695
- transformController;
3696
- renderer;
3697
- renderedRevision = 0;
3698
- frameId = 0;
3699
- pendingRuntimeWork = Promise.resolve();
3700
- destroyPromise;
3701
- transactionDepth = 0;
3702
- transformSequence = 0;
3703
- constructor(options) {
3704
- const rendererRegistry = options.renderer?.registry ?? new NodeRendererRegistry();
3705
- this.rendererRegistry = rendererRegistry;
3706
- this.options = {
3707
- ...options,
3708
- renderer: {
3709
- ...options.renderer,
3710
- registry: rendererRegistry
3711
- }
3712
- };
3713
- this.signal = this.abortController.signal;
3714
- this.core = new BoardCore({ ...this.options.core, document: this.options.document });
3715
- const capabilities = createBoardCapabilities(this.core, {
3716
- preview: options.preview,
3717
- capture: options.capture
3718
- });
3719
- this.capabilities = scopeCapabilities(capabilities, this.signal, () => this.assertAlive());
3720
- this.nodes = {
3721
- create: async (input) => {
3722
- this.assertAlive();
3723
- const node = this.core.nodes.create(input);
3724
- return this.node(node.id);
3725
- },
3726
- update: (nodeId, patch) => {
3727
- this.updateNode(nodeId, patch);
3728
- return this.node(nodeId);
3729
- },
3730
- resize: (nodeId, request) => {
3731
- this.assertAlive();
3732
- this.core.nodes.resize(nodeId, request);
3733
- return this.node(nodeId);
3734
- },
3735
- convert: (nodeId, input) => {
3736
- this.assertAlive();
3737
- this.core.nodes.convert(nodeId, input);
3738
- return this.node(nodeId);
3739
- },
3740
- remove: (nodeId) => this.removeNode(nodeId),
3741
- get: (nodeId) => this.getNode(nodeId),
3742
- list: (filter = {}) => {
3743
- this.assertAlive();
3744
- return this.core.nodes.list(filter);
3745
- }
3746
- };
3747
- this.nodeTypes = {
3748
- register: (definition, registrationOptions = {}) => this.registerNodeType(definition, registrationOptions),
3749
- has: (type) => {
3750
- this.assertAlive();
3751
- return this.core.nodeTypes.has(type);
3752
- },
3753
- get: (type) => {
3754
- this.assertAlive();
3755
- return this.core.nodeTypes.get(type);
3756
- },
3757
- list: () => {
3758
- this.assertAlive();
3759
- return this.core.nodeTypes.list();
3760
- }
3761
- };
3762
- this.transformController = new TransformController({
3763
- selection: () => this.core.selection.get(),
3764
- getNode: (nodeId) => this.core.nodes.get(nodeId),
3765
- resizePolicy: (type) => this.core.nodeTypes.get(type)?.resize,
3766
- resize: (nodeId, request) => {
3767
- this.core.nodes.resize(nodeId, request);
3768
- },
3769
- update: (nodeId, patch) => {
3770
- this.core.nodes.update(nodeId, patch);
3771
- },
3772
- transaction: (label, operation, transactionOptions) => this.transaction(label, operation, transactionOptions),
3773
- nextId: () => `${++this.transformSequence}`
3774
- }, this.options.transform ?? {});
3775
- this.transform = {
3776
- handles: () => {
3777
- this.assertAlive();
3778
- return this.transformController.handles();
3779
- },
3780
- bounds: () => {
3781
- this.assertAlive();
3782
- return this.transformController.bounds();
3783
- },
3784
- begin: (handle) => {
3785
- this.assertAlive();
3786
- return this.transformController.begin(handle);
3787
- },
3788
- active: () => this.transformController.active()
3789
- };
3790
- this.selection = {
3791
- get: () => {
3792
- this.assertAlive();
3793
- return this.core.selection.get();
3794
- },
3795
- set: (ids) => {
3796
- this.assertAlive();
3797
- this.core.selection.set(ids);
3798
- },
3799
- toggle: (id) => {
3800
- this.assertAlive();
3801
- this.core.selection.toggle(id);
3802
- },
3803
- clear: () => {
3804
- this.assertAlive();
3805
- this.core.selection.clear();
3806
- },
3807
- onChange: (listener) => this.on("selection:change", listener)
3808
- };
3809
- this.viewport = {
3810
- get: () => {
3811
- this.assertAlive();
3812
- return this.core.viewport.get();
3813
- },
3814
- set: (value) => {
3815
- this.assertAlive();
3816
- this.core.viewport.set(value);
3817
- },
3818
- panBy: (x, y) => {
3819
- this.assertAlive();
3820
- this.core.viewport.panBy(x, y);
3821
- },
3822
- zoomAt: (point, factor) => {
3823
- this.assertAlive();
3824
- this.core.viewport.zoomAt(point, factor);
3825
- },
3826
- fitNodes: (ids) => {
3827
- this.assertAlive();
3828
- this.core.viewport.fitNodes(ids);
3829
- },
3830
- fitBounds: (bounds) => {
3831
- this.assertAlive();
3832
- this.core.viewport.fitBounds(bounds);
3833
- },
3834
- toWorld: (point) => {
3835
- this.assertAlive();
3836
- return this.core.viewport.toWorld(point);
3837
- },
3838
- toScreen: (point) => {
3839
- this.assertAlive();
3840
- return this.core.viewport.toScreen(point);
3841
- }
3842
- };
3843
- this.history = {
3844
- canUndo: () => {
3845
- this.assertAlive();
3846
- return this.core.history.canUndo();
3847
- },
3848
- canRedo: () => {
3849
- this.assertAlive();
3850
- return this.core.history.canRedo();
3851
- },
3852
- undo: () => {
3853
- this.assertAlive();
3854
- return this.core.history.undo();
3855
- },
3856
- redo: () => {
3857
- this.assertAlive();
3858
- return this.core.history.redo();
3859
- },
3860
- clear: () => {
3861
- this.assertAlive();
3862
- this.core.history.clear();
3863
- }
3864
- };
3865
- this.document = {
3866
- getRevision: () => {
3867
- this.assertAlive();
3868
- return this.core.document.getRevision();
3869
- },
3870
- getMetadata: () => {
3871
- this.assertAlive();
3872
- return this.core.document.getMetadata();
3873
- },
3874
- patchMetadata: (patch) => {
3875
- this.assertAlive();
3876
- this.core.document.patchMetadata(patch);
3877
- },
3878
- snapshot: () => {
3879
- this.assertAlive();
3880
- return this.core.document.snapshot();
3881
- },
3882
- toJSON: () => {
3883
- this.assertAlive();
3884
- return this.core.document.toJSON();
3885
- },
3886
- load: async (input, loadOptions) => {
3887
- this.assertAlive();
3888
- this.core.document.load(input, loadOptions);
3889
- await this.pendingRuntimeWork;
3890
- },
3891
- validate: (input) => {
3892
- this.assertAlive();
3893
- return this.core.document.validate(input);
3894
- }
3895
- };
3896
- this.bindCoreEvents();
3897
- this.bindRuntimePorts();
3898
- this.ready = this.mount();
3899
- }
3900
- async createConnectionLayer() {
3901
- await this.ready;
3902
- this.assertAlive();
3903
- if (!this.renderer?.createConnectionLayer) throw new Error("Renderer does not support connection layers");
3904
- return this.renderer.createConnectionLayer();
3905
- }
3906
- get state() {
3907
- return this.lifecycle;
3908
- }
3909
- node(nodeId) {
3910
- this.assertAlive();
3911
- return new PublicNodeHandle(this, nodeId);
3912
- }
3913
- find(filter = {}) {
3914
- this.assertAlive();
3915
- return this.core.nodes.list(filter);
3916
- }
3917
- findOne(selector) {
3918
- this.assertAlive();
3919
- const nodeId = selector.startsWith("#") ? selector.slice(1) : selector;
3920
- if (!nodeId) return void 0;
3921
- return this.core.nodes.get(nodeId);
3922
- }
3923
- visibleNodeIds() {
3924
- this.assertAlive();
3925
- return this.renderer?.visibleNodeIds?.();
3926
- }
3927
- transaction(label, operation, options = {}) {
3928
- this.assertAlive();
3929
- return this.core.transaction(label, () => {
3930
- this.transactionDepth += 1;
3931
- try {
3932
- return operation();
3933
- } finally {
3934
- this.transactionDepth -= 1;
3935
- }
3936
- }, options);
3937
- }
3938
- on(eventName, listener) {
3939
- this.assertAlive();
3940
- return this.events.on(eventName, listener);
3941
- }
3942
- focus() {
3943
- this.assertAlive();
3944
- focusedBoard = this;
3945
- const container = this.options.container;
3946
- container?.focus?.();
3947
- }
3948
- async capture(input, options = {}) {
3949
- this.assertAlive();
3950
- if (!this.capabilities.capture.available) throw new CapabilityUnavailableError("capture");
3951
- const signal = mergeSignals(this.signal, options.signal);
3952
- return this.capabilities.capture.capture(input, { ...options, signal });
3953
- }
3954
- getNode(nodeId) {
3955
- this.assertAlive();
3956
- return this.core.nodes.get(nodeId);
3957
- }
3958
- updateNode(nodeId, patch) {
3959
- this.assertAlive();
3960
- this.core.nodes.update(nodeId, patch);
3961
- }
3962
- setNodeAttrs(nodeId, patch) {
3963
- if (this.transactionDepth > 0) this.updateNode(nodeId, patch);
3964
- else this.transaction("Update node attrs", () => this.updateNode(nodeId, patch));
3965
- }
3966
- removeNode(nodeId) {
3967
- this.assertAlive();
3968
- this.core.nodes.remove(nodeId);
3969
- }
3970
- async registerNodeType(definition, registrationOptions) {
3971
- this.assertAlive();
3972
- if (registrationOptions.replace) {
3973
- throw new Error("Public node type replacement is not supported; unregister the current definition first");
3974
- }
3975
- const { renderer, ...dataDefinition } = definition;
3976
- const unregisterData = this.core.nodeTypes.register(
3977
- dataDefinition,
3978
- registrationOptions
3979
- );
3980
- let unregisterRenderer;
3981
- try {
3982
- if (renderer) {
3983
- unregisterRenderer = this.rendererRegistry.register(
3984
- definition.type,
3985
- renderer,
3986
- registrationOptions
3987
- );
3988
- }
3989
- await this.refreshRendererTypes();
3990
- } catch (error) {
3991
- unregisterRenderer?.();
3992
- unregisterData();
3993
- try {
3994
- await this.refreshRendererTypes();
3995
- } catch (rollbackError) {
3996
- throw new AggregateError([error, rollbackError], "Node type registration and renderer rollback both failed");
3997
- }
3998
- throw error;
3999
- }
4000
- let active = true;
4001
- return async () => {
4002
- if (!active) return;
4003
- unregisterRenderer?.();
4004
- unregisterData();
4005
- await this.refreshRendererTypes();
4006
- active = false;
4007
- };
4008
- }
4009
- refreshRendererTypes() {
4010
- const renderer = this.renderer;
4011
- if (!renderer?.refreshRegisteredTypes) return Promise.resolve();
4012
- const work = this.pendingRuntimeWork.then(async () => {
4013
- if (!this.signal.aborted) await renderer.refreshRegisteredTypes?.();
4014
- });
4015
- this.pendingRuntimeWork = work.catch(() => void 0);
4016
- return work;
4017
- }
4018
- onNode(nodeId, eventName, listener) {
4019
- this.assertAlive();
4020
- return this.nodeEvents.on(`${nodeId}:${eventName}`, listener);
4021
- }
4022
- async destroy() {
4023
- if (this.destroyPromise) return this.destroyPromise;
4024
- this.destroyPromise = this.performDestroy();
4025
- return this.destroyPromise;
4026
- }
4027
- async mount() {
4028
- this.lifecycle = "mounting";
4029
- const persistence = this.options.persistence;
4030
- if (persistence?.load) {
4031
- const loaded = await persistence.load({ signal: this.signal });
4032
- if (loaded && !this.signal.aborted) this.core.document.load(loaded);
4033
- }
4034
- if (this.signal.aborted) return;
4035
- if (!this.options.headless && this.options.container) {
4036
- const factory = this.options.rendererFactory ?? ((rendererOptions) => new PixiBoardRenderer(rendererOptions));
4037
- const renderer = factory({ ...this.options.renderer, nodeTypes: this.core.nodeTypes });
4038
- await renderer.init();
4039
- if (this.signal.aborted) {
4040
- await renderer.destroy();
4041
- return;
4042
- }
4043
- this.renderer = renderer;
4044
- await this.syncVisibleBounds();
4045
- const snapshot = this.core.document.snapshot();
4046
- await renderer.rebuild(snapshot);
4047
- this.renderedRevision = snapshot.revision;
4048
- }
4049
- if (!this.signal.aborted) this.lifecycle = "ready";
4050
- }
4051
- bindCoreEvents() {
4052
- this.cleanup.add(this.core.on("change", (event) => this.queueChange(event)));
4053
- this.cleanup.add(this.core.on("selection:change", (event) => {
4054
- if (!this.signal.aborted) this.events.emit("selection:change", event);
4055
- }));
4056
- this.cleanup.add(this.core.on("viewport:change", (event) => {
4057
- if (!this.signal.aborted) this.events.emit("viewport:change", event);
4058
- this.queueVisibleBoundsSync();
4059
- }));
4060
- this.cleanup.add(this.core.on("history:change", (event) => {
4061
- if (!this.signal.aborted) this.events.emit("history:change", event);
4062
- }));
4063
- }
4064
- bindRuntimePorts() {
4065
- const eventPort = this.options.ports?.events;
4066
- if (eventPort && this.options.interactions?.keyboard) {
4067
- const listener = (event) => {
4068
- if (focusedBoard === this) this.options.ports?.onKeyboardEvent?.(event);
4069
- };
4070
- eventPort.addEventListener("keydown", listener);
4071
- this.cleanup.add(() => eventPort.removeEventListener("keydown", listener));
4072
- }
4073
- if (eventPort && this.options.interactions?.clipboard) {
4074
- for (const type of ["copy", "cut", "paste"]) {
4075
- const listener = (event) => {
4076
- if (focusedBoard === this) this.options.ports?.onClipboardEvent?.(event);
4077
- };
4078
- eventPort.addEventListener(type, listener);
4079
- this.cleanup.add(() => eventPort.removeEventListener(type, listener));
4080
- }
4081
- }
4082
- const pointerTarget = this.options.container;
4083
- if (pointerTarget && this.options.interactions?.pointer) {
4084
- const listener = () => {
4085
- focusedBoard = this;
4086
- };
4087
- pointerTarget.addEventListener("pointerdown", listener);
4088
- this.cleanup.add(() => pointerTarget.removeEventListener("pointerdown", listener));
4089
- }
4090
- const focusTarget = this.options.container;
4091
- if (focusTarget && typeof focusTarget.addEventListener === "function" && (this.options.interactions?.keyboard || this.options.interactions?.clipboard)) {
4092
- const listener = () => {
4093
- focusedBoard = this;
4094
- };
4095
- focusTarget.addEventListener("focusin", listener);
4096
- this.cleanup.add(() => focusTarget.removeEventListener("focusin", listener));
4097
- if (typeof HTMLElement !== "undefined" && focusTarget instanceof HTMLElement && !focusTarget.hasAttribute("tabindex")) {
4098
- focusTarget.tabIndex = -1;
4099
- this.cleanup.add(() => focusTarget.removeAttribute("tabindex"));
4100
- }
4101
- }
4102
- const container = this.options.container;
4103
- const createObserver = this.options.ports?.createResizeObserver;
4104
- if (container && createObserver) {
4105
- const observer = createObserver((entries) => {
4106
- if (this.signal.aborted) return;
4107
- const rect = entries[0]?.contentRect;
4108
- if (rect?.width && rect?.height) {
4109
- this.core.viewport.setScreenSize({ width: rect.width, height: rect.height });
4110
- this.queueVisibleBoundsSync();
4111
- }
4112
- });
4113
- observer.observe(container);
4114
- this.cleanup.add(() => observer.disconnect());
4115
- }
4116
- const ticker = this.options.ports?.ticker;
4117
- if (ticker) {
4118
- const listener = () => void 0;
4119
- ticker.add(listener);
4120
- this.cleanup.add(() => ticker.remove(listener));
4121
- }
4122
- }
4123
- /**
4124
- * Pushes the current visible rectangle to the renderer. Runs inside the
4125
- * runtime queue so it can never interleave with an in-flight apply/rebuild,
4126
- * which would leave the renderer culling against one revision while
4127
- * reconciling another.
4128
- */
4129
- async syncVisibleBounds() {
4130
- const renderer = this.renderer;
4131
- if (!renderer?.setVisibleBounds || this.signal.aborted) return;
4132
- const virtualization = this.options.virtualization;
4133
- if (virtualization?.enabled === false) {
4134
- await renderer.setVisibleBounds(void 0);
4135
- return;
4136
- }
4137
- const padding = virtualization?.padding ?? DEFAULT_VIRTUALIZATION_PADDING;
4138
- const bounds = this.core.viewport.visibleWorldBounds(padding);
4139
- await renderer.setVisibleBounds(bounds, this.core.viewport.get().scale);
4140
- }
4141
- queueVisibleBoundsSync() {
4142
- if (this.signal.aborted || !this.renderer?.setVisibleBounds) return;
4143
- this.pendingRuntimeWork = this.pendingRuntimeWork.then(async () => {
4144
- await this.syncVisibleBounds();
4145
- if (this.signal.aborted) return;
4146
- this.events.emit("render:complete", {
4147
- revision: this.renderedRevision,
4148
- frameId: ++this.frameId
4149
- });
4150
- }).catch((error) => {
4151
- if (!this.signal.aborted) queueMicrotask(() => {
4152
- throw error;
4153
- });
4154
- });
4155
- }
4156
- queueChange(event) {
4157
- this.pendingRuntimeWork = this.pendingRuntimeWork.then(async () => {
4158
- if (this.signal.aborted) return;
4159
- if (this.lifecycle === "mounting" && event.changeSet.origin === "load") return;
4160
- if (this.renderer) {
4161
- try {
4162
- const result = await waitForAbort(this.renderer.apply(event.documentUpdate, event.changeSet), this.signal);
4163
- if (result === "rebuild-required" && !this.signal.aborted) {
4164
- await waitForAbort(this.renderer.rebuild(this.core.document.snapshot()), this.signal);
4165
- }
4166
- } catch (error) {
4167
- if (!this.signal.aborted) {
4168
- await waitForAbort(this.renderer.rebuild(this.core.document.snapshot()), this.signal);
4169
- }
4170
- throw error;
4171
- }
4172
- if (this.signal.aborted) return;
4173
- this.renderedRevision = event.revision;
4174
- this.events.emit("render:complete", {
4175
- revision: event.revision,
4176
- frameId: ++this.frameId
4177
- });
4178
- }
4179
- if (this.signal.aborted) return;
4180
- const persistence = this.options.persistence;
4181
- if (persistence?.save) {
4182
- await waitForAbort(persistence.save(this.core.document.toJSON(), { signal: this.signal }), this.signal);
4183
- }
4184
- if (this.signal.aborted) return;
4185
- this.events.emit("change", event);
4186
- if (event.changeSet.assetChangedNodeIds.length) this.events.emit("assets:change", event);
4187
- for (const nodeId of [
4188
- ...event.changeSet.addedNodeIds,
4189
- ...event.changeSet.updatedNodeIds,
4190
- ...event.changeSet.removedNodeIds
4191
- ]) {
4192
- this.nodeEvents.emit(`${nodeId}:change`, event);
4193
- }
4194
- }).catch((error) => {
4195
- if (!this.signal.aborted) queueMicrotask(() => {
4196
- throw error;
4197
- });
4198
- });
4199
- }
4200
- async performDestroy() {
4201
- if (this.lifecycle === "destroyed") return;
4202
- this.lifecycle = "destroying";
4203
- this.transformController.dispose();
4204
- if (focusedBoard === this) focusedBoard = void 0;
4205
- this.abortController.abort(new BoardDestroyedError());
4206
- for (const dispose of this.cleanup) dispose();
4207
- this.cleanup.clear();
4208
- await this.renderer?.destroy();
4209
- await this.pendingRuntimeWork.catch(() => void 0);
4210
- await this.options.persistence?.destroy?.();
4211
- this.events.clear();
4212
- this.nodeEvents.clear();
4213
- this.lifecycle = "destroyed";
4214
- }
4215
- assertAlive() {
4216
- if (this.lifecycle === "destroying" || this.lifecycle === "destroyed") {
4217
- throw new BoardDestroyedError();
4218
- }
4219
- }
4220
- };
4221
- async function createPixiBoard(options = {}) {
4222
- return new PixiBoardFacade(options);
4223
- }
4224
- function mergeSignals(instanceSignal, externalSignal) {
4225
- if (!externalSignal) return instanceSignal;
4226
- const controller = new AbortController();
4227
- const abort = (signal) => controller.abort(signal.reason);
4228
- if (instanceSignal.aborted) abort(instanceSignal);
4229
- else instanceSignal.addEventListener("abort", () => abort(instanceSignal), { once: true });
4230
- if (externalSignal.aborted) abort(externalSignal);
4231
- else externalSignal.addEventListener("abort", () => abort(externalSignal), { once: true });
4232
- return controller.signal;
4233
- }
4234
- function waitForAbort(operation, signal) {
4235
- if (signal.aborted) {
4236
- void operation.catch(() => void 0);
4237
- return Promise.resolve(void 0);
4238
- }
4239
- const aborted2 = new Promise((resolve) => {
4240
- signal.addEventListener("abort", () => resolve(void 0), { once: true });
4241
- });
4242
- void operation.catch(() => void 0);
4243
- return Promise.race([operation, aborted2]);
4244
- }
4245
- function scopeCapabilities(capabilities, instanceSignal, assertAlive) {
4246
- const options = (value) => ({
4247
- ...value ?? {},
4248
- signal: mergeSignals(instanceSignal, value?.signal)
4249
- });
4250
- return {
4251
- availability: capabilities.availability,
4252
- document: {
4253
- snapshot: (value) => {
4254
- assertAlive();
4255
- return capabilities.document.snapshot(options(value));
4256
- },
4257
- load: (input, value) => {
4258
- assertAlive();
4259
- return capabilities.document.load(input, options(value));
4260
- },
4261
- validate: (input, value) => {
4262
- assertAlive();
4263
- return capabilities.document.validate(input, options(value));
4264
- }
4265
- },
4266
- nodes: {
4267
- read: (input, value) => {
4268
- assertAlive();
4269
- return capabilities.nodes.read(input, options(value));
4270
- },
4271
- create: (input, value) => {
4272
- assertAlive();
4273
- return capabilities.nodes.create(input, options(value));
4274
- },
4275
- update: (input, value) => {
4276
- assertAlive();
4277
- return capabilities.nodes.update(input, options(value));
4278
- },
4279
- delete: (input, value) => {
4280
- assertAlive();
4281
- return capabilities.nodes.delete(input, options(value));
4282
- }
4283
- },
4284
- assets: {
4285
- read: (input, value) => {
4286
- assertAlive();
4287
- return capabilities.assets.read(input, options(value));
4288
- },
4289
- upsert: (input, value) => {
4290
- assertAlive();
4291
- return capabilities.assets.upsert(input, options(value));
4292
- },
4293
- remove: (input, value) => {
4294
- assertAlive();
4295
- return capabilities.assets.remove(input, options(value));
4296
- }
4297
- },
4298
- selection: {
4299
- get: (value) => {
4300
- assertAlive();
4301
- return capabilities.selection.get(options(value));
4302
- },
4303
- set: (nodeIds, value) => {
4304
- assertAlive();
4305
- return capabilities.selection.set(nodeIds, options(value));
4306
- }
4307
- },
4308
- viewport: {
4309
- get: (value) => {
4310
- assertAlive();
4311
- return capabilities.viewport.get(options(value));
4312
- },
4313
- set: (viewport, value) => {
4314
- assertAlive();
4315
- return capabilities.viewport.set(viewport, options(value));
4316
- }
4317
- },
4318
- history: {
4319
- canUndo: () => {
4320
- assertAlive();
4321
- return capabilities.history.canUndo();
4322
- },
4323
- canRedo: () => {
4324
- assertAlive();
4325
- return capabilities.history.canRedo();
4326
- },
4327
- clear: () => {
4328
- assertAlive();
4329
- capabilities.history.clear();
4330
- },
4331
- undo: (value) => {
4332
- assertAlive();
4333
- return capabilities.history.undo(options(value));
4334
- },
4335
- redo: (value) => {
4336
- assertAlive();
4337
- return capabilities.history.redo(options(value));
4338
- }
4339
- },
4340
- preview: {
4341
- get: (input, value) => {
4342
- assertAlive();
4343
- return capabilities.preview.get(input, options(value));
4344
- }
4345
- },
4346
- capture: {
4347
- available: capabilities.capture.available,
4348
- capture: (input, value) => {
4349
- assertAlive();
4350
- return capabilities.capture.capture(input, options(value));
4351
- }
4352
- }
4353
- };
4354
- }
1
+ import { GridSpatialIndex, normalizeConnectionStyle, defaultConnectionStyle } from './chunk-KQHR2G24.js';
2
+ export { PixiBoardRenderer, createPixiApplicationFactory, createPixiBoard, loadPixiRuntime } from './chunk-KQHR2G24.js';
3
+ export { AssetUnavailableError, BoardDestroyedError, CapabilityError, CapabilityUnavailableError, PermissionDeniedError } from './chunk-SNUXC33Q.js';
4
+ import { rotatedRectBounds, isAssetVariant } from './chunk-NPEG2TBO.js';
5
+ export { DocumentValidationError, NodeNotFoundError, NodeTypeNotRegisteredError, NodeTypeRegistry, NodeValidationError, PreviewRendererRegistry, RESIZE_HANDLES, TransactionConflictError, createMediaAssetRefs, createMediaMetadata, createPreviewSpec, fitMediaRect, isAssetVariant, isContentFit, preferredMediaNodeSize, previewStatusLabel, resizeHandleAxes, resizeHandleCursor, resolveTextureAssetRef, rotatedRectBounds } from './chunk-NPEG2TBO.js';
6
+ import './chunk-PZ5AY32C.js';
4355
7
 
4356
8
  // src/dom-transformer.ts
4357
9
  var DEFAULT_SIZE = 9;
@@ -4962,7 +614,7 @@ function collect(values, target) {
4962
614
  if (values === void 0) return;
4963
615
  for (const value of values) target.add(value);
4964
616
  }
4965
- function cloneValue2(value) {
617
+ function cloneValue(value) {
4966
618
  return structuredClone(value);
4967
619
  }
4968
620
  function documentAssetIds(document2) {
@@ -5059,7 +711,7 @@ var BrowserPersistenceAdapter = class {
5059
711
  return this.#destroyed;
5060
712
  }
5061
713
  get cleanupErrors() {
5062
- return this.#cleanupErrors.map((record2) => ({ ...record2 }));
714
+ return this.#cleanupErrors.map((record) => ({ ...record }));
5063
715
  }
5064
716
  async capabilities(options = {}) {
5065
717
  return this.#run(options.signal, async (signal) => ({
@@ -5081,20 +733,20 @@ var BrowserPersistenceAdapter = class {
5081
733
  }
5082
734
  async loadDocument(options = {}) {
5083
735
  return this.#run(options.signal, async (signal) => {
5084
- const record2 = await this.#indexedDb.loadDocument(signal);
736
+ const record = await this.#indexedDb.loadDocument(signal);
5085
737
  this.#throwIfAborted(signal);
5086
- return record2 === void 0 ? null : cloneValue2(record2);
738
+ return record === void 0 ? null : cloneValue(record);
5087
739
  });
5088
740
  }
5089
741
  async saveDocument(input, options = {}) {
5090
742
  await this.#run(options.signal, async (signal) => {
5091
- const record2 = {
5092
- snapshot: cloneValue2(input.snapshot),
5093
- metadata: cloneValue2(input.metadata ?? {}),
743
+ const record = {
744
+ snapshot: cloneValue(input.snapshot),
745
+ metadata: cloneValue(input.metadata ?? {}),
5094
746
  savedAt: this.#now()
5095
747
  };
5096
748
  this.#throwIfAborted(signal);
5097
- await this.#indexedDb.saveDocument(record2, signal, {
749
+ await this.#indexedDb.saveDocument(record, signal, {
5098
750
  expectedRevision: input.expectedRevision
5099
751
  });
5100
752
  });
@@ -5135,7 +787,7 @@ var BrowserPersistenceAdapter = class {
5135
787
  const previous = await this.#indexedDb.getAssetEntry(prepared.asset.id, signal);
5136
788
  const previousBinary = previous?.binaries.original;
5137
789
  const now = this.#now();
5138
- const document2 = cloneValue2(options.document);
790
+ const document2 = cloneValue(options.document);
5139
791
  const nodeId = options.nodeId ?? `node-${this.#idFactory()}`;
5140
792
  if (document2.nodes.some(({ id }) => id === nodeId)) throw new Error(`Node already exists: ${nodeId}`);
5141
793
  const preferOpfs = options.preferOpfs ?? prepared.blob.size >= this.#opfsThresholdBytes;
@@ -5153,7 +805,7 @@ var BrowserPersistenceAdapter = class {
5153
805
  await this.#opfs.put(storage.key, prepared.blob, signal);
5154
806
  }
5155
807
  const entry = this.#createEntry(
5156
- cloneValue2(prepared.asset),
808
+ cloneValue(prepared.asset),
5157
809
  "original",
5158
810
  prepared.blob,
5159
811
  storage,
@@ -5178,18 +830,18 @@ var BrowserPersistenceAdapter = class {
5178
830
  document2.revision += 1;
5179
831
  document2.assets = [
5180
832
  ...document2.assets.filter(({ id }) => id !== prepared.asset.id),
5181
- cloneValue2(prepared.asset)
833
+ cloneValue(prepared.asset)
5182
834
  ];
5183
835
  document2.nodes.push(node);
5184
836
  const current = options.documentMetadata === void 0 ? await this.#indexedDb.loadDocument(signal) : void 0;
5185
- const record2 = {
837
+ const record = {
5186
838
  snapshot: document2,
5187
- metadata: cloneValue2(options.documentMetadata ?? current?.metadata ?? {}),
839
+ metadata: cloneValue(options.documentMetadata ?? current?.metadata ?? {}),
5188
840
  savedAt: now
5189
841
  };
5190
842
  try {
5191
843
  await this.#indexedDb.commitAssetAndDocument(
5192
- record2,
844
+ record,
5193
845
  entry,
5194
846
  { variant: "original", blob: prepared.blob },
5195
847
  signal,
@@ -5216,10 +868,10 @@ var BrowserPersistenceAdapter = class {
5216
868
  }
5217
869
  return {
5218
870
  sourceType: prepared.sourceType,
5219
- document: cloneValue2(document2),
5220
- asset: cloneValue2(prepared.asset),
5221
- node: cloneValue2(node),
5222
- entry: cloneValue2(entry)
871
+ document: cloneValue(document2),
872
+ asset: cloneValue(prepared.asset),
873
+ node: cloneValue(node),
874
+ entry: cloneValue(entry)
5223
875
  };
5224
876
  });
5225
877
  }
@@ -5235,14 +887,14 @@ var BrowserPersistenceAdapter = class {
5235
887
  async importUrl(url, options) {
5236
888
  return this.commitImport(await this.prepareUrl(url, options), options);
5237
889
  }
5238
- async putAsset(record2, blob, options = {}) {
5239
- return this.#serializeAsset(record2.id, () => this.#putAsset(record2, blob, options));
890
+ async putAsset(record, blob, options = {}) {
891
+ return this.#serializeAsset(record.id, () => this.#putAsset(record, blob, options));
5240
892
  }
5241
- async #putAsset(record2, blob, options) {
893
+ async #putAsset(record, blob, options) {
5242
894
  return this.#run(options.signal, async (signal) => {
5243
895
  const variant = options.variant === void 0 ? "original" : options.variant;
5244
896
  assertAssetVariant(variant);
5245
- const previous = await this.#indexedDb.getAssetEntry(record2.id, signal);
897
+ const previous = await this.#indexedDb.getAssetEntry(record.id, signal);
5246
898
  const previousBinary = previous?.binaries[variant];
5247
899
  this.#throwIfAborted(signal);
5248
900
  const now = this.#now();
@@ -5251,14 +903,14 @@ var BrowserPersistenceAdapter = class {
5251
903
  this.#throwIfAborted(signal);
5252
904
  let entry;
5253
905
  if (useOpfs && this.#opfs !== void 0) {
5254
- const key = this.#storageKeyFactory(record2.id, variant);
906
+ const key = this.#storageKeyFactory(record.id, variant);
5255
907
  if (previousBinary?.storage.kind === "opfs" && previousBinary.storage.key === key) {
5256
908
  throw new BrowserStorageKeyCollisionError(key);
5257
909
  }
5258
910
  if (await this.#opfs.get(key, signal) !== void 0) {
5259
911
  throw new BrowserStorageKeyCollisionError(key);
5260
912
  }
5261
- entry = this.#createEntry(cloneValue2(record2), variant, blob, { kind: "opfs", key }, previous, now);
913
+ entry = this.#createEntry(cloneValue(record), variant, blob, { kind: "opfs", key }, previous, now);
5262
914
  await this.#opfs.put(key, blob, signal);
5263
915
  try {
5264
916
  this.#throwIfAborted(signal);
@@ -5266,27 +918,27 @@ var BrowserPersistenceAdapter = class {
5266
918
  } catch (error) {
5267
919
  await this.#cleanup(
5268
920
  "metadata-compensation",
5269
- { assetId: record2.id, variant, key },
921
+ { assetId: record.id, variant, key },
5270
922
  () => this.#opfs?.delete(key, new AbortController().signal)
5271
923
  );
5272
924
  throw error;
5273
925
  }
5274
926
  } else {
5275
- entry = this.#createEntry(cloneValue2(record2), variant, blob, { kind: "indexeddb" }, previous, now);
927
+ entry = this.#createEntry(cloneValue(record), variant, blob, { kind: "indexeddb" }, previous, now);
5276
928
  this.#throwIfAborted(signal);
5277
929
  await this.#indexedDb.putAssetEntry(entry, { variant, blob }, signal);
5278
930
  }
5279
- this.#revokeAssetLeases(record2.id, variant);
931
+ this.#revokeAssetLeases(record.id, variant);
5280
932
  const binary = entry.binaries[variant];
5281
933
  if (previousBinary?.storage.kind === "opfs" && (binary.storage.kind !== "opfs" || binary.storage.key !== previousBinary.storage.key)) {
5282
934
  const previousKey = previousBinary.storage.key;
5283
935
  await this.#cleanup(
5284
936
  "replace-old-opfs",
5285
- { assetId: record2.id, variant, key: previousKey },
937
+ { assetId: record.id, variant, key: previousKey },
5286
938
  () => this.#opfs?.delete(previousKey, new AbortController().signal)
5287
939
  );
5288
940
  }
5289
- return cloneValue2(entry);
941
+ return cloneValue(entry);
5290
942
  });
5291
943
  }
5292
944
  async putDerivative(assetId, variant, blob, options = {}) {
@@ -5309,7 +961,7 @@ var BrowserPersistenceAdapter = class {
5309
961
  const blob = binary.storage.kind === "opfs" ? await this.#opfs?.get(binary.storage.key, signal) : await this.#indexedDb.getAssetBlob(id, variant, signal);
5310
962
  this.#throwIfAborted(signal);
5311
963
  if (blob === void 0) throw new BrowserAssetBinaryMissingError(id, variant);
5312
- const clonedEntry = cloneValue2(entry);
964
+ const clonedEntry = cloneValue(entry);
5313
965
  return { entry: clonedEntry, variant, binary: clonedEntry.binaries[variant], blob };
5314
966
  });
5315
967
  }
@@ -5320,7 +972,7 @@ var BrowserPersistenceAdapter = class {
5320
972
  return this.#run(options.signal, async (signal) => {
5321
973
  const entries = await this.#indexedDb.listAssetEntries(signal);
5322
974
  this.#throwIfAborted(signal);
5323
- return cloneValue2(entries).sort((left, right) => left.id.localeCompare(right.id));
975
+ return cloneValue(entries).sort((left, right) => left.id.localeCompare(right.id));
5324
976
  });
5325
977
  }
5326
978
  async deleteAsset(id, options = {}) {
@@ -5500,10 +1152,10 @@ var BrowserPersistenceAdapter = class {
5500
1152
  })).then(() => void 0);
5501
1153
  return this.#destroyPromise;
5502
1154
  }
5503
- #createEntry(record2, variant, blob, storage, previous, now) {
1155
+ #createEntry(record, variant, blob, storage, previous, now) {
5504
1156
  return {
5505
- id: record2.id,
5506
- record: record2,
1157
+ id: record.id,
1158
+ record,
5507
1159
  binaries: {
5508
1160
  ...previous?.binaries,
5509
1161
  [variant]: {
@@ -5597,15 +1249,15 @@ var BrowserPersistenceAdapter = class {
5597
1249
  try {
5598
1250
  await cleanup();
5599
1251
  } catch (error) {
5600
- const record2 = {
1252
+ const record = {
5601
1253
  operation,
5602
1254
  error,
5603
1255
  timestamp: this.#now(),
5604
1256
  ...context
5605
1257
  };
5606
- this.#cleanupErrors.push(record2);
1258
+ this.#cleanupErrors.push(record);
5607
1259
  try {
5608
- this.#onCleanupError({ ...record2 });
1260
+ this.#onCleanupError({ ...record });
5609
1261
  } catch (observerError) {
5610
1262
  this.#cleanupErrors.push({
5611
1263
  operation: "cleanup-observer",
@@ -5803,7 +1455,7 @@ function blobKey(id, variant) {
5803
1455
  assertAssetVariant(variant);
5804
1456
  return [id, variant];
5805
1457
  }
5806
- function abortError2(signal) {
1458
+ function abortError(signal) {
5807
1459
  return new DOMException(String(signal.reason ?? "The operation was aborted"), "AbortError");
5808
1460
  }
5809
1461
  function requestResult(request) {
@@ -5823,7 +1475,7 @@ function transactionDone(transaction, signal) {
5823
1475
  }, { once: true });
5824
1476
  transaction.addEventListener("abort", () => {
5825
1477
  cleanup();
5826
- reject(signal.aborted ? abortError2(signal) : transaction.error);
1478
+ reject(signal.aborted ? abortError(signal) : transaction.error);
5827
1479
  }, { once: true });
5828
1480
  transaction.addEventListener("error", () => {
5829
1481
  cleanup();
@@ -5846,9 +1498,9 @@ var NativeIndexedDbPort = class {
5846
1498
  async loadDocument(signal) {
5847
1499
  return this.#read(DOCUMENT_STORE, DOCUMENT_KEY, signal);
5848
1500
  }
5849
- async saveDocument(record2, signal, options = {}) {
1501
+ async saveDocument(record, signal, options = {}) {
5850
1502
  const database = await this.#open(signal);
5851
- if (signal.aborted) throw abortError2(signal);
1503
+ if (signal.aborted) throw abortError(signal);
5852
1504
  const transaction = database.transaction(DOCUMENT_STORE, "readwrite");
5853
1505
  const done = transactionDone(transaction, signal);
5854
1506
  try {
@@ -5863,7 +1515,7 @@ var NativeIndexedDbPort = class {
5863
1515
  throw new BrowserDocumentConflictError(options.expectedRevision, actualRevision);
5864
1516
  }
5865
1517
  }
5866
- transaction.objectStore(DOCUMENT_STORE).put(record2, DOCUMENT_KEY);
1518
+ transaction.objectStore(DOCUMENT_STORE).put(record, DOCUMENT_KEY);
5867
1519
  await done;
5868
1520
  } catch (error) {
5869
1521
  try {
@@ -5894,7 +1546,7 @@ var NativeIndexedDbPort = class {
5894
1546
  for (const variant of Object.keys(entry.binaries)) assertAssetVariant(variant);
5895
1547
  if (binaryWrite !== void 0) assertAssetVariant(binaryWrite.variant);
5896
1548
  const database = await this.#open(signal);
5897
- if (signal.aborted) throw abortError2(signal);
1549
+ if (signal.aborted) throw abortError(signal);
5898
1550
  const transaction = database.transaction([ASSET_STORE, BLOB_STORE], "readwrite");
5899
1551
  const done = transactionDone(transaction, signal);
5900
1552
  try {
@@ -5932,7 +1584,7 @@ var NativeIndexedDbPort = class {
5932
1584
  for (const variant of Object.keys(entry.binaries)) assertAssetVariant(variant);
5933
1585
  if (binaryWrite !== void 0) assertAssetVariant(binaryWrite.variant);
5934
1586
  const database = await this.#open(signal);
5935
- if (signal.aborted) throw abortError2(signal);
1587
+ if (signal.aborted) throw abortError(signal);
5936
1588
  const transaction = database.transaction(
5937
1589
  [DOCUMENT_STORE, ASSET_STORE, BLOB_STORE],
5938
1590
  "readwrite"
@@ -5999,14 +1651,14 @@ var NativeIndexedDbPort = class {
5999
1651
  }
6000
1652
  async #write(storeNames, signal, write) {
6001
1653
  const database = await this.#open(signal);
6002
- if (signal.aborted) throw abortError2(signal);
1654
+ if (signal.aborted) throw abortError(signal);
6003
1655
  const transaction = database.transaction(storeNames, "readwrite");
6004
1656
  const done = transactionDone(transaction, signal);
6005
1657
  write(transaction);
6006
1658
  await done;
6007
1659
  }
6008
1660
  async #open(signal) {
6009
- if (signal.aborted) throw abortError2(signal);
1661
+ if (signal.aborted) throw abortError(signal);
6010
1662
  if (this.#database === void 0) {
6011
1663
  this.#database = new Promise((resolve, reject) => {
6012
1664
  const request = this.#indexedDb.open(this.#databaseName, 1);
@@ -6032,7 +1684,7 @@ var NativeIndexedDbPort = class {
6032
1684
  if (this.#database === opening) this.#database = void 0;
6033
1685
  throw error;
6034
1686
  }
6035
- if (signal.aborted) throw abortError2(signal);
1687
+ if (signal.aborted) throw abortError(signal);
6036
1688
  return database;
6037
1689
  }
6038
1690
  };
@@ -6125,7 +1777,7 @@ var NativeOpfsPort = class {
6125
1777
  };
6126
1778
 
6127
1779
  // src/connections.ts
6128
- var PREVIEW_ID2 = "__connection_preview__";
1780
+ var PREVIEW_ID = "__connection_preview__";
6129
1781
  var PORT_OFFSET = 7;
6130
1782
  var PORT_HOVER_RADIUS = 14;
6131
1783
  async function attachConnections(board, options) {
@@ -6227,9 +1879,9 @@ async function attachConnections(board, options) {
6227
1879
  dirty.clear();
6228
1880
  const source = drag && nodes.get(drag.source);
6229
1881
  if (drag && source) {
6230
- layer.upsert({ id: PREVIEW_ID2, start: anchor(source, true), end: drag.point });
1882
+ layer.upsert({ id: PREVIEW_ID, start: anchor(source, true), end: drag.point });
6231
1883
  } else {
6232
- layer.remove(PREVIEW_ID2);
1884
+ layer.remove(PREVIEW_ID);
6233
1885
  }
6234
1886
  layer.setSelected(selected);
6235
1887
  projectPort();
@@ -6813,6 +2465,6 @@ function indexedDbPersistence(options = {}) {
6813
2465
  });
6814
2466
  }
6815
2467
 
6816
- export { AssetUnavailableError, BoardDestroyedError, BrowserAssetBinaryMissingError, BrowserAssetNotFoundError, BrowserDocumentConflictError, BrowserPersistenceAbortError, BrowserPersistenceAdapter, BrowserPersistenceDestroyedError, BrowserPersistenceError, BrowserStorageCapabilityError, BrowserStorageKeyCollisionError, BrowserStorageQuotaError, CapabilityError, CapabilityUnavailableError, DEFAULT_OPFS_THRESHOLD_BYTES, DocumentValidationError, NativeDownloadPort, NativeIndexedDbPort, NativeObjectUrlPort, NativeOpfsPort, NodeNotFoundError, NodeTypeNotRegisteredError, NodeTypeRegistry, NodeValidationError, PermissionDeniedError, PixiBoardRenderer, RESIZE_HANDLES, TransactionConflictError, anchorRatio, anchorWorldPoint, attachConnections, attachDomTransformer, attachLabelOverlay, attachOverlayLayer, attachSelectionOverlay, buildNodeAgentPrompt, createNodeAgentController, createPixiApplicationFactory, createPixiBoard, createPreviewSpec, indexedDbPersistence, isAssetVariant, isBrowserQuotaError, isDocumentPreviewType, isPreviewNodeType, loadPixiRuntime, previewStatusLabel, projectOverlayItem, resizeHandleAxes, resizeHandleCursor, resolveOverlayBounds, resolveScale, rotatedRectBounds, runBrowserAdapterContract };
2468
+ export { BrowserAssetBinaryMissingError, BrowserAssetNotFoundError, BrowserDocumentConflictError, BrowserPersistenceAbortError, BrowserPersistenceAdapter, BrowserPersistenceDestroyedError, BrowserPersistenceError, BrowserStorageCapabilityError, BrowserStorageKeyCollisionError, BrowserStorageQuotaError, DEFAULT_OPFS_THRESHOLD_BYTES, NativeDownloadPort, NativeIndexedDbPort, NativeObjectUrlPort, NativeOpfsPort, anchorRatio, anchorWorldPoint, attachConnections, attachDomTransformer, attachLabelOverlay, attachOverlayLayer, attachSelectionOverlay, buildNodeAgentPrompt, createNodeAgentController, indexedDbPersistence, isBrowserQuotaError, projectOverlayItem, resolveOverlayBounds, resolveScale, runBrowserAdapterContract };
6817
2469
  //# sourceMappingURL=browser.js.map
6818
2470
  //# sourceMappingURL=browser.js.map