pixiboardjs 0.1.0-alpha.6 → 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 (55) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/VERSIONING.md +9 -7
  3. package/dist/agent-tools-schemas.d.ts +18 -0
  4. package/dist/agent-tools-schemas.js +4 -0
  5. package/dist/agent-tools-schemas.js.map +1 -0
  6. package/dist/agent-tools.d.ts +140 -0
  7. package/dist/agent-tools.js +124 -0
  8. package/dist/agent-tools.js.map +1 -0
  9. package/dist/browser.d.ts +12 -6
  10. package/dist/browser.js +57 -5176
  11. package/dist/browser.js.map +1 -1
  12. package/dist/capabilities.d.ts +14 -0
  13. package/dist/capabilities.js +5 -0
  14. package/dist/capabilities.js.map +1 -0
  15. package/dist/chunk-AYOOOEXM.js +27 -0
  16. package/dist/chunk-AYOOOEXM.js.map +1 -0
  17. package/dist/chunk-KQHR2G24.js +2257 -0
  18. package/dist/chunk-KQHR2G24.js.map +1 -0
  19. package/dist/chunk-NPEG2TBO.js +2353 -0
  20. package/dist/chunk-NPEG2TBO.js.map +1 -0
  21. package/dist/chunk-PZ5AY32C.js +9 -0
  22. package/dist/chunk-PZ5AY32C.js.map +1 -0
  23. package/dist/chunk-SNUXC33Q.js +560 -0
  24. package/dist/chunk-SNUXC33Q.js.map +1 -0
  25. package/dist/core-B_8DmBaT.d.ts +294 -0
  26. package/dist/core.d.ts +11 -0
  27. package/dist/core.js +4 -0
  28. package/dist/core.js.map +1 -0
  29. package/dist/errors-CEQ_RiJ_.d.ts +27 -0
  30. package/dist/index.d.ts +9 -93
  31. package/dist/index.js +4 -5127
  32. package/dist/index.js.map +1 -1
  33. package/dist/node.d.ts +8 -2
  34. package/dist/node.js +4 -5127
  35. package/dist/node.js.map +1 -1
  36. package/dist/plugin.d.ts +88 -0
  37. package/dist/plugin.js +37 -0
  38. package/dist/plugin.js.map +1 -0
  39. package/dist/preview-registry-BjdGxaWe.d.ts +115 -0
  40. package/dist/resize-BK1wOjTc.d.ts +120 -0
  41. package/dist/types-BEsq8g6W.d.ts +199 -0
  42. package/dist/types-BskqWTyl.d.ts +224 -0
  43. package/dist/types.d.ts +416 -1
  44. package/etc/pixiboardjs-agent-tools-schemas.api.md +29 -0
  45. package/etc/pixiboardjs-agent-tools.api.md +288 -0
  46. package/etc/pixiboardjs-browser.api.md +1913 -1855
  47. package/etc/pixiboardjs-capabilities.api.md +366 -0
  48. package/etc/pixiboardjs-core.api.md +725 -0
  49. package/etc/pixiboardjs-node.api.md +1020 -962
  50. package/etc/pixiboardjs-plugin.api.md +129 -0
  51. package/etc/pixiboardjs-types.api.md +836 -783
  52. package/etc/pixiboardjs.api.md +1020 -962
  53. package/package.json +32 -5
  54. package/dist/tsdoc-metadata.json +0 -11
  55. package/dist/types-Cl2ogJCs.d.ts +0 -905
@@ -0,0 +1,2353 @@
1
+ import { __export } from './chunk-PZ5AY32C.js';
2
+
3
+ // ../core/src/asset-variant.ts
4
+ function isAssetVariant(value) {
5
+ return value === "original" || value === "preview" || value === "waveform" || typeof value === "string" && value.length === 72 && /^preview-[a-f0-9]{64}$/.test(value);
6
+ }
7
+
8
+ // ../core/src/asset-previews.ts
9
+ function record(value) {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
11
+ }
12
+ function positiveNumber(value, fallback) {
13
+ const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
14
+ return Number.isFinite(number) && number > 0 ? number : fallback;
15
+ }
16
+ function createPreviewSpec(node, options = {}) {
17
+ const saved = record(record(node.props).previewSpec);
18
+ const defaultHeight = positiveNumber(options.defaultHeight, 704);
19
+ let width = positiveNumber(saved.width, 1024);
20
+ let height = positiveNumber(saved.height, defaultHeight);
21
+ let mode = saved.mode === "fixed-viewport" ? "fixed-viewport" : "viewport";
22
+ let quality = options.quality === "detail" || options.quality === "thumbnail" ? options.quality : saved.quality === "detail" ? "detail" : "thumbnail";
23
+ if (options.reason === "reset" || options.reason === "refresh") {
24
+ 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;
25
+ height = positiveNumber(width * ratio, defaultHeight);
26
+ mode = "fixed-viewport";
27
+ quality = options.quality === "thumbnail" ? "thumbnail" : "detail";
28
+ }
29
+ if (options.width !== void 0) width = positiveNumber(options.width, 1024);
30
+ if (options.height !== void 0) height = positiveNumber(options.height, defaultHeight);
31
+ const sideScale = Math.min(1, 4096 / width, 4096 / height);
32
+ width *= sideScale;
33
+ height *= sideScale;
34
+ const areaScale = Math.min(1, Math.sqrt(8e6 / (width * height)));
35
+ width = Math.max(1, Math.min(4096, Math.round(width * areaScale)));
36
+ height = Math.max(1, Math.min(4096, Math.round(height * areaScale)));
37
+ if (width * height > 8e6) height = Math.max(1, Math.floor(8e6 / width));
38
+ const pageValue = options.page === void 0 ? saved.page : options.page;
39
+ const page = Math.min(Number.MAX_SAFE_INTEGER, Math.max(1, Math.round(positiveNumber(pageValue, 1))));
40
+ return { width, height, page, mode, quality };
41
+ }
42
+ function previewStatusLabel(node, typeLabel) {
43
+ const props = record(node.props);
44
+ switch (props.previewStatus) {
45
+ case "pending":
46
+ case "queued":
47
+ case "running":
48
+ return `${typeLabel}:\u9884\u89C8\u751F\u6210\u4E2D`;
49
+ case "error":
50
+ case "failed":
51
+ case "unsupported":
52
+ return `${typeLabel}:\u6682\u65E0\u9884\u89C8`;
53
+ default:
54
+ return typeLabel;
55
+ }
56
+ }
57
+
58
+ // ../core/src/errors.ts
59
+ var PixiBoardCoreError = class extends Error {
60
+ constructor(message) {
61
+ super(message);
62
+ this.name = new.target.name;
63
+ }
64
+ };
65
+ var NodeNotFoundError = class extends PixiBoardCoreError {
66
+ constructor(nodeId) {
67
+ super(`Node not found: ${nodeId}`);
68
+ }
69
+ };
70
+ var NodeTypeNotRegisteredError = class extends PixiBoardCoreError {
71
+ constructor(type) {
72
+ super(`Node type is not registered: ${type}`);
73
+ }
74
+ };
75
+ var NodeValidationError = class extends PixiBoardCoreError {
76
+ nodeId;
77
+ nodeType;
78
+ cause;
79
+ constructor(message, options = {}) {
80
+ super(message);
81
+ this.nodeId = options.nodeId;
82
+ this.nodeType = options.nodeType;
83
+ this.cause = options.cause;
84
+ }
85
+ };
86
+ var DocumentValidationError = class extends PixiBoardCoreError {
87
+ cause;
88
+ constructor(message, options = {}) {
89
+ super(message);
90
+ this.cause = options.cause;
91
+ }
92
+ };
93
+ var TransactionConflictError = class extends PixiBoardCoreError {
94
+ };
95
+
96
+ // ../core/src/preview-registry.ts
97
+ var PreviewRendererRegistry = class {
98
+ renderers = /* @__PURE__ */ new Map();
99
+ development;
100
+ counter = 0;
101
+ constructor(options = {}) {
102
+ this.development = options.development ?? false;
103
+ }
104
+ register(renderer, options = {}) {
105
+ if (typeof renderer.id !== "string" || renderer.id === "") {
106
+ throw new NodeValidationError("Preview renderer id must be a non-empty string");
107
+ }
108
+ if (typeof renderer.supports !== "function" || typeof renderer.render !== "function") {
109
+ throw new NodeValidationError(`Preview renderer must implement supports() and render(): ${renderer.id}`);
110
+ }
111
+ const existing = this.renderers.get(renderer.id);
112
+ if (existing && !options.replace) {
113
+ throw new NodeValidationError(`Preview renderer is already registered: ${renderer.id}`);
114
+ }
115
+ if (existing && !this.development) {
116
+ throw new NodeValidationError(`Replacing preview renderers is only allowed in development: ${renderer.id}`);
117
+ }
118
+ const entry = { renderer, order: existing?.order ?? this.counter++ };
119
+ this.renderers.set(renderer.id, entry);
120
+ return () => {
121
+ if (this.renderers.get(renderer.id) === entry) this.renderers.delete(renderer.id);
122
+ };
123
+ }
124
+ has(id) {
125
+ return this.renderers.has(id);
126
+ }
127
+ /** In resolution order. */
128
+ list() {
129
+ return [...this.renderers.values()].sort((a, b) => (b.renderer.priority ?? 0) - (a.renderer.priority ?? 0) || a.order - b.order).map((entry) => entry.renderer);
130
+ }
131
+ /** First renderer whose `supports()` accepts the source; a throwing probe counts as "no". */
132
+ async resolve(source) {
133
+ for (const renderer of this.list()) {
134
+ try {
135
+ if (await renderer.supports(source)) return renderer;
136
+ } catch {
137
+ }
138
+ }
139
+ return void 0;
140
+ }
141
+ };
142
+
143
+ // ../core/src/media-assets.ts
144
+ var TEXTURE_REF_ROLES = {
145
+ image: ["preview", "image", "primary", "original", "source"],
146
+ video: ["poster", "preview"],
147
+ audio: ["waveform", "preview"],
148
+ model: ["preview"],
149
+ html: ["preview"],
150
+ markdown: ["preview"],
151
+ "text-file": ["preview"],
152
+ file: ["preview"]
153
+ };
154
+ function isRenderAssetKind(value) {
155
+ return Object.hasOwn(TEXTURE_REF_ROLES, value);
156
+ }
157
+ function resolveTextureAssetRef(node, kind = node.type) {
158
+ if (!isRenderAssetKind(kind)) return void 0;
159
+ for (const role of TEXTURE_REF_ROLES[kind]) {
160
+ const ref = node.assetRefs?.[role];
161
+ if (ref) return ref;
162
+ }
163
+ return Object.entries(node.assetRefs ?? {}).find(([role]) => /^preview-[a-f0-9]{64}$/.test(role))?.[1];
164
+ }
165
+ function createMediaAssetRefs(kind, assetId, available = {}) {
166
+ const refs = {
167
+ primary: { assetId, variant: "original" }
168
+ };
169
+ if (kind === "image" && available.preview) {
170
+ refs.preview = { assetId, variant: "preview" };
171
+ }
172
+ if (kind === "video" && available.poster) {
173
+ refs.poster = { assetId, variant: "preview" };
174
+ }
175
+ if (kind === "audio" && available.waveform) {
176
+ refs.waveform = { assetId, variant: "waveform" };
177
+ }
178
+ if (["model", "html", "markdown", "text-file", "file"].includes(kind) && available.preview) {
179
+ refs.preview = { assetId, variant: "preview" };
180
+ }
181
+ return refs;
182
+ }
183
+ function readIntrinsicSize(value, fallback) {
184
+ const source = record2(value);
185
+ const width = positiveFinite(
186
+ source.intrinsicWidth ?? source.naturalWidth ?? source.mediaWidth ?? source.textureWidth ?? fallback?.width
187
+ );
188
+ const height = positiveFinite(
189
+ source.intrinsicHeight ?? source.naturalHeight ?? source.mediaHeight ?? source.textureHeight ?? fallback?.height
190
+ );
191
+ return width !== void 0 && height !== void 0 ? { width, height } : void 0;
192
+ }
193
+ function fitMediaRect(frame, intrinsic, fit = "contain") {
194
+ const width = positiveFinite(frame.width) ?? 0;
195
+ const height = positiveFinite(frame.height) ?? 0;
196
+ const sourceWidth = positiveFinite(intrinsic?.width);
197
+ const sourceHeight = positiveFinite(intrinsic?.height);
198
+ if (width === 0 || height === 0) return { x: 0, y: 0, width, height };
199
+ if (!sourceWidth || !sourceHeight || fit === "stretch") {
200
+ return { x: 0, y: 0, width, height };
201
+ }
202
+ const scale = fit === "cover" ? Math.max(width / sourceWidth, height / sourceHeight) : Math.min(width / sourceWidth, height / sourceHeight);
203
+ const fittedWidth = sourceWidth * scale;
204
+ const fittedHeight = sourceHeight * scale;
205
+ return {
206
+ x: (width - fittedWidth) / 2,
207
+ y: (height - fittedHeight) / 2,
208
+ width: fittedWidth,
209
+ height: fittedHeight
210
+ };
211
+ }
212
+ function preferredMediaNodeSize(intrinsic, maxWidth = 320, maxHeight = 320) {
213
+ const width = positiveFinite(intrinsic?.width) ?? maxWidth;
214
+ const height = positiveFinite(intrinsic?.height) ?? maxHeight;
215
+ const scale = Math.min(maxWidth / width, maxHeight / height, 1);
216
+ return {
217
+ width: Math.max(1, Math.round(width * scale)),
218
+ height: Math.max(1, Math.round(height * scale))
219
+ };
220
+ }
221
+ function createMediaMetadata(input) {
222
+ const output = { version: 1 };
223
+ for (const key of ["contentHash", "mimeType", "relativePath", "rootId", "baseUrl"]) {
224
+ const value = input[key];
225
+ if (typeof value === "string" && value.length > 0) output[key] = value;
226
+ }
227
+ for (const key of ["width", "height", "duration", "orientation"]) {
228
+ const value = positiveFinite(input[key]);
229
+ if (value !== void 0) output[key] = value;
230
+ }
231
+ return output;
232
+ }
233
+ function isContentFit(value) {
234
+ return value === "contain" || value === "cover" || value === "stretch";
235
+ }
236
+ function record2(value) {
237
+ const candidate = value && typeof value === "object" && !Array.isArray(value) ? value : {};
238
+ return recordProps(candidate);
239
+ }
240
+ function recordProps(value) {
241
+ return value.props && typeof value.props === "object" && !Array.isArray(value.props) ? value.props : value;
242
+ }
243
+ function positiveFinite(value) {
244
+ const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
245
+ return Number.isFinite(number) && number > 0 ? number : void 0;
246
+ }
247
+
248
+ // ../core/src/geometry.ts
249
+ function rotatedRectBounds(node) {
250
+ const cos = Math.cos(node.rotation);
251
+ const sin = Math.sin(node.rotation);
252
+ const corners = [
253
+ { x: 0, y: 0 },
254
+ { x: node.width, y: 0 },
255
+ { x: node.width, y: node.height },
256
+ { x: 0, y: node.height }
257
+ ].map((point) => ({
258
+ x: node.x + point.x * cos - point.y * sin,
259
+ y: node.y + point.x * sin + point.y * cos
260
+ }));
261
+ return {
262
+ minX: Math.min(...corners.map(({ x }) => x)),
263
+ minY: Math.min(...corners.map(({ y }) => y)),
264
+ maxX: Math.max(...corners.map(({ x }) => x)),
265
+ maxY: Math.max(...corners.map(({ y }) => y))
266
+ };
267
+ }
268
+ function mergeBounds(bounds) {
269
+ if (bounds.length === 0) return void 0;
270
+ return {
271
+ minX: Math.min(...bounds.map(({ minX }) => minX)),
272
+ minY: Math.min(...bounds.map(({ minY }) => minY)),
273
+ maxX: Math.max(...bounds.map(({ maxX }) => maxX)),
274
+ maxY: Math.max(...bounds.map(({ maxY }) => maxY))
275
+ };
276
+ }
277
+ function assertWorldBounds(bounds, label = "bounds") {
278
+ const values = [bounds.minX, bounds.minY, bounds.maxX, bounds.maxY];
279
+ if (!values.every(Number.isFinite) || bounds.maxX < bounds.minX || bounds.maxY < bounds.minY) {
280
+ throw new RangeError(`${label} must be finite and normalized`);
281
+ }
282
+ }
283
+
284
+ // ../core/src/json.ts
285
+ function cloneValue(value) {
286
+ return structuredClone(value);
287
+ }
288
+ function immutableClone(value) {
289
+ return deepFreeze(cloneValue(value));
290
+ }
291
+ function deepFreeze(value) {
292
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
293
+ Object.freeze(value);
294
+ for (const child of Object.values(value)) {
295
+ deepFreeze(child);
296
+ }
297
+ }
298
+ return value;
299
+ }
300
+ function assertJsonValue(value, path = "value", ancestors = /* @__PURE__ */ new WeakSet()) {
301
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
302
+ return;
303
+ }
304
+ if (typeof value === "number") {
305
+ if (!Number.isFinite(value)) {
306
+ throw new DocumentValidationError(`${path} must contain only finite numbers`);
307
+ }
308
+ return;
309
+ }
310
+ if (Array.isArray(value)) {
311
+ assertNotCircular(value, path, ancestors);
312
+ value.forEach((item, index) => assertJsonValue(item, `${path}[${index}]`, ancestors));
313
+ ancestors.delete(value);
314
+ return;
315
+ }
316
+ if (typeof value === "object") {
317
+ const prototype = Object.getPrototypeOf(value);
318
+ if (prototype !== Object.prototype && prototype !== null) {
319
+ throw new DocumentValidationError(`${path} must be a plain JSON object`);
320
+ }
321
+ if (Reflect.ownKeys(value).some((key) => typeof key !== "string")) {
322
+ throw new DocumentValidationError(`${path} must not contain symbol keys`);
323
+ }
324
+ assertNotCircular(value, path, ancestors);
325
+ for (const [key, item] of Object.entries(value)) {
326
+ assertJsonValue(item, `${path}.${key}`, ancestors);
327
+ }
328
+ ancestors.delete(value);
329
+ return;
330
+ }
331
+ throw new DocumentValidationError(`${path} is not JSON-serializable`);
332
+ }
333
+ function assertNotCircular(value, path, ancestors) {
334
+ if (ancestors.has(value)) {
335
+ throw new DocumentValidationError(`${path} must not contain circular references`);
336
+ }
337
+ ancestors.add(value);
338
+ }
339
+ function jsonEqual(left, right) {
340
+ return JSON.stringify(left) === JSON.stringify(right);
341
+ }
342
+
343
+ // ../core/src/node-type-registry.ts
344
+ var NodeTypeRegistry = class {
345
+ definitions = /* @__PURE__ */ new Map();
346
+ development;
347
+ constructor(options = {}) {
348
+ this.development = options.development ?? false;
349
+ }
350
+ register(definition, options = {}) {
351
+ assertDefinition(definition);
352
+ const registered = freezeDefinition(definition);
353
+ const existing = this.definitions.get(registered.type);
354
+ if (existing && !options.replace) {
355
+ throw new NodeValidationError(`Node type is already registered: ${registered.type}`);
356
+ }
357
+ if (existing && options.replace && !this.development) {
358
+ throw new NodeValidationError(
359
+ `Replacing node type definitions is only allowed in development: ${registered.type}`
360
+ );
361
+ }
362
+ this.definitions.set(registered.type, registered);
363
+ return () => {
364
+ if (this.definitions.get(registered.type) === registered) {
365
+ this.definitions.delete(registered.type);
366
+ }
367
+ };
368
+ }
369
+ has(type) {
370
+ return this.definitions.has(type);
371
+ }
372
+ get(type) {
373
+ return this.definitions.get(type);
374
+ }
375
+ require(type) {
376
+ const definition = this.get(type);
377
+ if (!definition) throw new NodeTypeNotRegisteredError(type);
378
+ return definition;
379
+ }
380
+ list() {
381
+ return [...this.definitions.values()];
382
+ }
383
+ createProps(type, props) {
384
+ const definition = this.require(type);
385
+ const input = mergeDefaults(definition.defaults, props);
386
+ return {
387
+ typeVersion: definition.version,
388
+ props: this.runValidation(definition, input)
389
+ };
390
+ }
391
+ validateNode(node) {
392
+ const definition = this.get(node.type);
393
+ if (!definition) return cloneValue(node);
394
+ if (node.typeVersion !== definition.version) {
395
+ throw new NodeValidationError(
396
+ `Node ${node.id} uses ${node.type} typeVersion ${node.typeVersion}; registered version is ${definition.version}`,
397
+ { nodeId: node.id, nodeType: node.type }
398
+ );
399
+ }
400
+ return {
401
+ ...cloneValue(node),
402
+ typeVersion: node.typeVersion,
403
+ props: this.runValidation(definition, node.props)
404
+ };
405
+ }
406
+ getBounds(node) {
407
+ const definition = this.require(node.type);
408
+ return definition.getBounds(cloneValue(node));
409
+ }
410
+ runValidation(definition, value) {
411
+ try {
412
+ const validated = definition.validate(cloneValue(value));
413
+ assertJsonValue(validated, `${definition.type}.props`);
414
+ return cloneValue(validated);
415
+ } catch (cause) {
416
+ throw new NodeValidationError(`Invalid props for node type ${definition.type}`, {
417
+ nodeType: definition.type,
418
+ cause
419
+ });
420
+ }
421
+ }
422
+ };
423
+ function assertDefinition(definition) {
424
+ if (!definition.type.trim()) {
425
+ throw new NodeValidationError("Node type must be a non-empty string");
426
+ }
427
+ if (!Number.isInteger(definition.version) || definition.version < 1) {
428
+ throw new NodeValidationError(`Node type ${definition.type} must have a positive version`);
429
+ }
430
+ if (typeof definition.validate !== "function" || typeof definition.getBounds !== "function") {
431
+ throw new NodeValidationError(
432
+ `Node type ${definition.type} must define validate() and getBounds()`
433
+ );
434
+ }
435
+ if (definition.defaults !== void 0) {
436
+ assertJsonValue(definition.defaults, `${definition.type}.defaults`);
437
+ }
438
+ assertResizePolicy(definition);
439
+ }
440
+ function assertResizePolicy(definition) {
441
+ const policy = definition.resize;
442
+ if (policy === void 0) return;
443
+ const modes = ["free", "aspect-ratio", "fixed", "custom"];
444
+ if (!modes.includes(policy.mode)) {
445
+ throw new NodeValidationError(
446
+ `Node type ${definition.type} has an unknown resize mode: ${String(policy.mode)}`
447
+ );
448
+ }
449
+ if (policy.mode === "custom" && typeof policy.resize !== "function") {
450
+ throw new NodeValidationError(
451
+ `Node type ${definition.type} declares resize mode "custom" without a resize() function`
452
+ );
453
+ }
454
+ if (policy.mode === "aspect-ratio" && policy.ratio !== void 0 && (!Number.isFinite(policy.ratio) || policy.ratio <= 0)) {
455
+ throw new NodeValidationError(
456
+ `Node type ${definition.type} declares a non-positive aspect ratio`
457
+ );
458
+ }
459
+ }
460
+ function freezeDefinition(definition) {
461
+ const registered = {
462
+ ...definition,
463
+ ...definition.defaults === void 0 ? {} : { defaults: deepFreeze(cloneValue(definition.defaults)) },
464
+ ...definition.resize === void 0 ? {} : { resize: Object.freeze({ ...definition.resize }) }
465
+ };
466
+ return Object.freeze(registered);
467
+ }
468
+ function mergeDefaults(defaults, props) {
469
+ if (isPlainObject(defaults) || isPlainObject(props)) {
470
+ return {
471
+ ...isPlainObject(defaults) ? cloneValue(defaults) : {},
472
+ ...isPlainObject(props) ? cloneValue(props) : {}
473
+ };
474
+ }
475
+ return props ?? defaults ?? null;
476
+ }
477
+ function isPlainObject(value) {
478
+ return value !== null && typeof value === "object" && !Array.isArray(value);
479
+ }
480
+
481
+ // ../core/src/resize.ts
482
+ var HANDLE_AXES = {
483
+ nw: { horizontal: -1, vertical: -1 },
484
+ n: { horizontal: 0, vertical: -1 },
485
+ ne: { horizontal: 1, vertical: -1 },
486
+ e: { horizontal: 1, vertical: 0 },
487
+ se: { horizontal: 1, vertical: 1 },
488
+ s: { horizontal: 0, vertical: 1 },
489
+ sw: { horizontal: -1, vertical: 1 },
490
+ w: { horizontal: -1, vertical: 0 }
491
+ };
492
+ var RESIZE_HANDLES = Object.freeze([
493
+ "nw",
494
+ "n",
495
+ "ne",
496
+ "e",
497
+ "se",
498
+ "s",
499
+ "sw",
500
+ "w"
501
+ ]);
502
+ function resizeHandleAxes(handle) {
503
+ const axes = HANDLE_AXES[handle];
504
+ if (!axes) throw new RangeError(`Unknown resize handle: ${String(handle)}`);
505
+ return { ...axes };
506
+ }
507
+ var DEFAULT_MIN_SIZE = 1;
508
+ function isResizeHandle(value) {
509
+ return typeof value === "string" && value in HANDLE_AXES;
510
+ }
511
+ function nodeGeometry(node) {
512
+ return { x: node.x, y: node.y, width: node.width, height: node.height, rotation: node.rotation };
513
+ }
514
+ function resolveResize(node, policy, request) {
515
+ const axes = HANDLE_AXES[request.handle];
516
+ if (!axes) throw new RangeError(`Unknown resize handle: ${String(request.handle)}`);
517
+ if (!Number.isFinite(request.deltaWorld.x) || !Number.isFinite(request.deltaWorld.y)) {
518
+ throw new RangeError("Resize delta must be finite");
519
+ }
520
+ const origin = request.origin ?? nodeGeometry(node);
521
+ const localDelta = rotatePoint(request.deltaWorld, -origin.rotation);
522
+ const resolved = resolveResizeSize(node, policy, {
523
+ handle: request.handle,
524
+ width: origin.width + axes.horizontal * localDelta.x,
525
+ height: origin.height + axes.vertical * localDelta.y,
526
+ origin,
527
+ ...request.minWidth === void 0 ? {} : { minWidth: request.minWidth },
528
+ ...request.minHeight === void 0 ? {} : { minHeight: request.minHeight }
529
+ });
530
+ if (!resolved) return {};
531
+ const left = anchorOffset(axes.horizontal, origin.width, resolved.width);
532
+ const top = anchorOffset(axes.vertical, origin.height, resolved.height);
533
+ const offset = rotatePoint({ x: left, y: top }, origin.rotation);
534
+ const patch = { ...resolved.patch, width: resolved.width, height: resolved.height };
535
+ if (resolved.patch.x === void 0) patch.x = origin.x + offset.x;
536
+ if (resolved.patch.y === void 0) patch.y = origin.y + offset.y;
537
+ return patch;
538
+ }
539
+ function resolveResizeSize(node, policy, request) {
540
+ const axes = HANDLE_AXES[request.handle];
541
+ if (!axes) throw new RangeError(`Unknown resize handle: ${String(request.handle)}`);
542
+ if (!Number.isFinite(request.width) || !Number.isFinite(request.height)) {
543
+ throw new RangeError("Resize size must be finite");
544
+ }
545
+ const mode = policy?.mode ?? "free";
546
+ if (mode === "fixed" || node.locked === true) return void 0;
547
+ const origin = request.origin ?? nodeGeometry(node);
548
+ const minWidth = Math.max(request.minWidth ?? DEFAULT_MIN_SIZE, 0);
549
+ const minHeight = Math.max(request.minHeight ?? DEFAULT_MIN_SIZE, 0);
550
+ let width = Math.max(request.width, minWidth);
551
+ let height = Math.max(request.height, minHeight);
552
+ if (mode === "aspect-ratio") {
553
+ const constrained = constrainToRatio(
554
+ { width, height },
555
+ { width: origin.width, height: origin.height },
556
+ axes,
557
+ policy?.mode === "aspect-ratio" ? policy.ratio : void 0,
558
+ { minWidth, minHeight }
559
+ );
560
+ width = constrained.width;
561
+ height = constrained.height;
562
+ }
563
+ let patch = {};
564
+ if (mode === "custom" && policy?.mode === "custom") {
565
+ patch = policy.resize({ node, width, height });
566
+ if (typeof patch.width === "number") width = Math.max(patch.width, 0);
567
+ if (typeof patch.height === "number") height = Math.max(patch.height, 0);
568
+ }
569
+ return { width, height, patch };
570
+ }
571
+ function resizeHandleCursor(handle, rotation = 0) {
572
+ const base = { n: 0, ne: 45, e: 90, se: 135, s: 180, sw: 225, w: 270, nw: 315 };
573
+ const degrees = base[handle] + rotation * 180 / Math.PI;
574
+ const normalized = (degrees % 180 + 180) % 180;
575
+ const names = ["ns", "nesw", "ew", "nwse"];
576
+ return `${names[Math.round(normalized / 45) % 4]}-resize`;
577
+ }
578
+ function anchorOffset(axis, originSize, size) {
579
+ if (axis === 1) return 0;
580
+ if (axis === -1) return originSize - size;
581
+ return (originSize - size) / 2;
582
+ }
583
+ function constrainToRatio(size, origin, axes, declaredRatio, limits) {
584
+ const ratio = declaredRatio !== void 0 && Number.isFinite(declaredRatio) && declaredRatio > 0 ? declaredRatio : origin.height > 0 && origin.width > 0 ? origin.width / origin.height : 1;
585
+ let { width, height } = size;
586
+ if (axes.horizontal !== 0 && axes.vertical !== 0) {
587
+ const widthDrives = Math.abs(width - origin.width) >= Math.abs(height - origin.height) * ratio;
588
+ if (widthDrives) height = width / ratio;
589
+ else width = height * ratio;
590
+ } else if (axes.horizontal !== 0) {
591
+ height = width / ratio;
592
+ } else {
593
+ width = height * ratio;
594
+ }
595
+ if (width < limits.minWidth) {
596
+ width = limits.minWidth;
597
+ height = width / ratio;
598
+ }
599
+ if (height < limits.minHeight) {
600
+ height = limits.minHeight;
601
+ width = height * ratio;
602
+ }
603
+ return { width, height };
604
+ }
605
+ function rotatePoint(point, angle) {
606
+ if (!angle) return { x: point.x, y: point.y };
607
+ const cos = Math.cos(angle);
608
+ const sin = Math.sin(angle);
609
+ return { x: point.x * cos - point.y * sin, y: point.x * sin + point.y * cos };
610
+ }
611
+
612
+ // ../core/src/selection.ts
613
+ var SelectionController = class {
614
+ constructor(nodeExists, beforeMutation = () => {
615
+ }) {
616
+ this.nodeExists = nodeExists;
617
+ this.beforeMutation = beforeMutation;
618
+ }
619
+ nodeExists;
620
+ beforeMutation;
621
+ selected = /* @__PURE__ */ new Set();
622
+ listeners = /* @__PURE__ */ new Set();
623
+ get() {
624
+ return [...this.selected];
625
+ }
626
+ set(nodeIds) {
627
+ this.beforeMutation();
628
+ const next = /* @__PURE__ */ new Set();
629
+ for (const id of nodeIds) {
630
+ if (this.nodeExists(id)) next.add(id);
631
+ }
632
+ this.commit(next);
633
+ }
634
+ toggle(nodeId) {
635
+ this.beforeMutation();
636
+ if (!this.nodeExists(nodeId)) return;
637
+ const next = new Set(this.selected);
638
+ if (next.has(nodeId)) next.delete(nodeId);
639
+ else next.add(nodeId);
640
+ this.commit(next);
641
+ }
642
+ clear() {
643
+ this.beforeMutation();
644
+ this.commit(/* @__PURE__ */ new Set());
645
+ }
646
+ onChange(listener) {
647
+ this.listeners.add(listener);
648
+ return () => this.listeners.delete(listener);
649
+ }
650
+ prune() {
651
+ const next = new Set([...this.selected].filter((id) => this.nodeExists(id)));
652
+ return this.commit(next);
653
+ }
654
+ commit(next) {
655
+ const previous = [...this.selected];
656
+ const current = [...next];
657
+ if (sameIds(previous, current)) return false;
658
+ this.selected = next;
659
+ const event = { nodeIds: [...current], previousNodeIds: [...previous] };
660
+ for (const listener of this.listeners) {
661
+ try {
662
+ listener(event);
663
+ } catch {
664
+ }
665
+ }
666
+ return true;
667
+ }
668
+ };
669
+ function sameIds(left, right) {
670
+ return left.length === right.length && left.every((id, index) => id === right[index]);
671
+ }
672
+
673
+ // ../core/src/viewport.ts
674
+ var ViewportController = class {
675
+ constructor(initial = { scale: 1, offset: { x: 0, y: 0 } }, screen, beforeMutation = () => {
676
+ }) {
677
+ this.beforeMutation = beforeMutation;
678
+ assertViewport(initial);
679
+ if (screen !== void 0) assertSize(screen);
680
+ this.state = cloneViewport(initial);
681
+ this.screen = screen ? { ...screen } : { width: 1, height: 1 };
682
+ this.screenSizeKnown = screen !== void 0;
683
+ }
684
+ beforeMutation;
685
+ state;
686
+ screen;
687
+ /**
688
+ * Whether a host has told us how big the surface actually is. The
689
+ * constructor default is 1x1, which is a placeholder rather than a real
690
+ * measurement — reporting visible bounds from it would cull everything but a
691
+ * single world pixel, so visibleWorldBounds() stays undefined until a host
692
+ * calls setScreenSize().
693
+ */
694
+ screenSizeKnown;
695
+ listeners = /* @__PURE__ */ new Set();
696
+ get() {
697
+ return cloneViewport(this.state);
698
+ }
699
+ set(viewport) {
700
+ this.beforeMutation();
701
+ assertViewport(viewport);
702
+ this.commit(viewport);
703
+ }
704
+ setScreenSize(screen) {
705
+ this.beforeMutation();
706
+ assertSize(screen);
707
+ this.screen = { ...screen };
708
+ this.screenSizeKnown = true;
709
+ }
710
+ getScreenSize() {
711
+ return { ...this.screen };
712
+ }
713
+ /**
714
+ * The world rectangle the surface currently shows, grown by `padding` world
715
+ * units on every side so a renderer can keep a margin of ready views just
716
+ * outside the viewport. Returns undefined while the screen size is still
717
+ * unknown, which callers must read as "everything is visible" rather than
718
+ * "nothing is".
719
+ */
720
+ visibleWorldBounds(padding = 0) {
721
+ if (!this.screenSizeKnown) return void 0;
722
+ if (!Number.isFinite(padding) || padding < 0) {
723
+ throw new RangeError("visible bounds padding must be finite and non-negative");
724
+ }
725
+ const topLeft = this.toWorld({ x: 0, y: 0 });
726
+ const bottomRight = this.toWorld({ x: this.screen.width, y: this.screen.height });
727
+ return {
728
+ minX: topLeft.x - padding,
729
+ minY: topLeft.y - padding,
730
+ maxX: bottomRight.x + padding,
731
+ maxY: bottomRight.y + padding
732
+ };
733
+ }
734
+ panBy(deltaX, deltaY) {
735
+ this.beforeMutation();
736
+ assertFinite(deltaX, "deltaX");
737
+ assertFinite(deltaY, "deltaY");
738
+ this.commit({
739
+ scale: this.state.scale,
740
+ offset: {
741
+ x: this.state.offset.x + deltaX,
742
+ y: this.state.offset.y + deltaY
743
+ }
744
+ });
745
+ }
746
+ zoomAt(screenPoint, factor) {
747
+ this.beforeMutation();
748
+ assertPoint(screenPoint, "screenPoint");
749
+ if (!Number.isFinite(factor) || factor <= 0) {
750
+ throw new RangeError("zoom factor must be finite and greater than zero");
751
+ }
752
+ const worldPoint = this.toWorld(screenPoint);
753
+ const scale = this.state.scale * factor;
754
+ this.commit({
755
+ scale,
756
+ offset: {
757
+ x: screenPoint.x - worldPoint.x * scale,
758
+ y: screenPoint.y - worldPoint.y * scale
759
+ }
760
+ });
761
+ }
762
+ fitBounds(bounds, options = {}) {
763
+ this.beforeMutation();
764
+ assertWorldBounds(bounds);
765
+ const screen = options.screen ?? this.screen;
766
+ assertSize(screen);
767
+ const padding = options.padding ?? 72;
768
+ const maxScale = options.maxScale ?? 1;
769
+ if (!Number.isFinite(padding) || padding < 0) {
770
+ throw new RangeError("fit padding must be finite and non-negative");
771
+ }
772
+ if (!Number.isFinite(maxScale) || maxScale <= 0) {
773
+ throw new RangeError("fit maxScale must be finite and greater than zero");
774
+ }
775
+ const boundsWidth = Math.max(bounds.maxX - bounds.minX, 1);
776
+ const boundsHeight = Math.max(bounds.maxY - bounds.minY, 1);
777
+ const availableWidth = Math.max(screen.width - padding * 2, 1);
778
+ const availableHeight = Math.max(screen.height - padding * 2, 1);
779
+ const scale = Math.min(availableWidth / boundsWidth, availableHeight / boundsHeight, maxScale);
780
+ const centerX = (bounds.minX + bounds.maxX) / 2;
781
+ const centerY = (bounds.minY + bounds.maxY) / 2;
782
+ this.commit({
783
+ scale,
784
+ offset: {
785
+ x: screen.width / 2 - centerX * scale,
786
+ y: screen.height / 2 - centerY * scale
787
+ }
788
+ });
789
+ }
790
+ toWorld(screenPoint) {
791
+ assertPoint(screenPoint, "screenPoint");
792
+ return {
793
+ x: (screenPoint.x - this.state.offset.x) / this.state.scale,
794
+ y: (screenPoint.y - this.state.offset.y) / this.state.scale
795
+ };
796
+ }
797
+ toScreen(worldPoint) {
798
+ assertPoint(worldPoint, "worldPoint");
799
+ return {
800
+ x: worldPoint.x * this.state.scale + this.state.offset.x,
801
+ y: worldPoint.y * this.state.scale + this.state.offset.y
802
+ };
803
+ }
804
+ onChange(listener) {
805
+ this.listeners.add(listener);
806
+ return () => this.listeners.delete(listener);
807
+ }
808
+ commit(viewport) {
809
+ assertViewport(viewport);
810
+ const previousViewport = this.get();
811
+ if (previousViewport.scale === viewport.scale && previousViewport.offset.x === viewport.offset.x && previousViewport.offset.y === viewport.offset.y) {
812
+ return;
813
+ }
814
+ this.state = cloneViewport(viewport);
815
+ const event = { viewport: this.get(), previousViewport };
816
+ for (const listener of this.listeners) {
817
+ try {
818
+ listener(event);
819
+ } catch {
820
+ }
821
+ }
822
+ }
823
+ };
824
+ function assertViewport(viewport) {
825
+ if (!Number.isFinite(viewport.scale) || viewport.scale <= 0) {
826
+ throw new RangeError("viewport scale must be finite and greater than zero");
827
+ }
828
+ assertPoint(viewport.offset, "viewport offset");
829
+ }
830
+ function assertPoint(point, label) {
831
+ assertFinite(point.x, `${label}.x`);
832
+ assertFinite(point.y, `${label}.y`);
833
+ }
834
+ function assertSize(size) {
835
+ if (!Number.isFinite(size.width) || size.width <= 0 || !Number.isFinite(size.height) || size.height <= 0) {
836
+ throw new RangeError("screen size must be finite and greater than zero");
837
+ }
838
+ }
839
+ function assertFinite(value, label) {
840
+ if (!Number.isFinite(value)) throw new RangeError(`${label} must be finite`);
841
+ }
842
+ function cloneViewport(viewport) {
843
+ return { scale: viewport.scale, offset: { ...viewport.offset } };
844
+ }
845
+
846
+ // ../core/src/document-validation.ts
847
+ function validateDocument(input, options) {
848
+ const value = parseInput(input);
849
+ if (!isRecord(value)) throw new DocumentValidationError("Document must be an object");
850
+ const sourceVersion = readInteger(value, "schemaVersion", "document");
851
+ if (sourceVersion > options.schemaVersion) {
852
+ throw new DocumentValidationError(
853
+ `Document schema ${sourceVersion} is newer than supported schema ${options.schemaVersion}`
854
+ );
855
+ }
856
+ if (sourceVersion < options.schemaVersion) {
857
+ throw new DocumentValidationError(
858
+ `Document schema ${sourceVersion} is older than supported schema ${options.schemaVersion}`
859
+ );
860
+ }
861
+ assertJsonValue(value, "document");
862
+ if (!isRecord(value)) throw new DocumentValidationError("Document must be an object");
863
+ const schemaVersion = readInteger(value, "schemaVersion", "document");
864
+ const revision = readInteger(value, "revision", "document");
865
+ if (schemaVersion < 1) throw new DocumentValidationError("schemaVersion must be positive");
866
+ if (revision < 0) throw new DocumentValidationError("revision must not be negative");
867
+ if (!Array.isArray(value.nodes)) throw new DocumentValidationError("document.nodes must be an array");
868
+ if (!Array.isArray(value.assets)) throw new DocumentValidationError("document.assets must be an array");
869
+ const nodeIds = /* @__PURE__ */ new Set();
870
+ const nodes = value.nodes.map((node, index) => {
871
+ const validated = validateNode(node, `document.nodes[${index}]`);
872
+ if (nodeIds.has(validated.id)) {
873
+ throw new DocumentValidationError(`Duplicate node id: ${validated.id}`);
874
+ }
875
+ nodeIds.add(validated.id);
876
+ try {
877
+ return options.nodeTypes.validateNode(validated);
878
+ } catch (cause) {
879
+ if (cause instanceof NodeValidationError) throw cause;
880
+ throw new NodeValidationError(`Invalid node ${validated.id}`, {
881
+ nodeId: validated.id,
882
+ nodeType: validated.type,
883
+ cause
884
+ });
885
+ }
886
+ });
887
+ const assetIds = /* @__PURE__ */ new Set();
888
+ const assets = value.assets.map((asset, index) => {
889
+ const validated = validateAsset(asset, `document.assets[${index}]`);
890
+ if (assetIds.has(validated.id)) {
891
+ throw new DocumentValidationError(`Duplicate asset id: ${validated.id}`);
892
+ }
893
+ assetIds.add(validated.id);
894
+ return validated;
895
+ });
896
+ if (value.viewport !== void 0) validateViewport(value.viewport, "document.viewport");
897
+ if (value.metadata !== void 0 && !isRecord(value.metadata)) {
898
+ throw new DocumentValidationError("document.metadata must be an object");
899
+ }
900
+ return {
901
+ ...cloneValue(value),
902
+ schemaVersion,
903
+ revision,
904
+ nodes,
905
+ assets,
906
+ ...value.viewport === void 0 ? {} : { viewport: cloneValue(value.viewport) }
907
+ };
908
+ }
909
+ function validateNode(input, path = "node") {
910
+ assertJsonValue(input, path);
911
+ if (!isRecord(input)) throw new DocumentValidationError(`${path} must be an object`);
912
+ if ("assetId" in input) {
913
+ throw new DocumentValidationError(
914
+ `${path}.assetId is not supported; use ${path}.assetRefs instead`
915
+ );
916
+ }
917
+ const id = readString(input, "id", path);
918
+ const type = readString(input, "type", path);
919
+ const typeVersion = readInteger(input, "typeVersion", path);
920
+ if (typeVersion < 1) throw new DocumentValidationError(`${path}.typeVersion must be positive`);
921
+ for (const field of ["x", "y", "width", "height", "rotation", "zIndex"]) {
922
+ readFiniteNumber(input, field, path);
923
+ }
924
+ if (input.width < 0 || input.height < 0) {
925
+ throw new DocumentValidationError(`${path} width and height must not be negative`);
926
+ }
927
+ if (input.name !== void 0 && typeof input.name !== "string") {
928
+ throw new DocumentValidationError(`${path}.name must be a string`);
929
+ }
930
+ if (input.locked !== void 0 && typeof input.locked !== "boolean") {
931
+ throw new DocumentValidationError(`${path}.locked must be a boolean`);
932
+ }
933
+ if (input.visible !== void 0 && typeof input.visible !== "boolean") {
934
+ throw new DocumentValidationError(`${path}.visible must be a boolean`);
935
+ }
936
+ if (!("props" in input)) throw new DocumentValidationError(`${path}.props is required`);
937
+ if (input.fit !== void 0 && !isContentFit(input.fit)) {
938
+ throw new DocumentValidationError(`${path}.fit must be contain, cover, or stretch`);
939
+ }
940
+ if (input.assetRefs !== void 0) validateAssetRefs(input.assetRefs, `${path}.assetRefs`);
941
+ return { ...cloneValue(input), id, type, typeVersion };
942
+ }
943
+ function validateAsset(input, path = "asset") {
944
+ assertJsonValue(input, path);
945
+ if (!isRecord(input)) throw new DocumentValidationError(`${path} must be an object`);
946
+ const id = readString(input, "id", path);
947
+ const kind = readString(input, "kind", path);
948
+ if (input.metadata !== void 0 && !isRecord(input.metadata)) {
949
+ throw new DocumentValidationError(`${path}.metadata must be an object`);
950
+ }
951
+ return { ...cloneValue(input), id, kind };
952
+ }
953
+ function validateViewport(input, path = "viewport") {
954
+ assertJsonValue(input, path);
955
+ if (!isRecord(input) || !isRecord(input.offset)) {
956
+ throw new DocumentValidationError(`${path} must include an offset object`);
957
+ }
958
+ const scale = readFiniteNumber(input, "scale", path);
959
+ const x = readFiniteNumber(input.offset, "x", `${path}.offset`);
960
+ const y = readFiniteNumber(input.offset, "y", `${path}.offset`);
961
+ if (scale <= 0) throw new DocumentValidationError(`${path}.scale must be greater than zero`);
962
+ return { scale, offset: { x, y } };
963
+ }
964
+ function validateAssetRefs(input, path) {
965
+ if (!isRecord(input)) throw new DocumentValidationError(`${path} must be an object`);
966
+ for (const [name, ref] of Object.entries(input)) {
967
+ if (!name || !isRecord(ref)) throw new DocumentValidationError(`${path}.${name} is invalid`);
968
+ readString(ref, "assetId", `${path}.${name}`);
969
+ if (ref.variant !== void 0 && !isAssetVariant(ref.variant)) {
970
+ throw new DocumentValidationError(`${path}.${name}.variant is invalid`);
971
+ }
972
+ }
973
+ }
974
+ function parseInput(input) {
975
+ if (typeof input !== "string") return cloneValue(input);
976
+ try {
977
+ return JSON.parse(input);
978
+ } catch (cause) {
979
+ throw new DocumentValidationError("Document JSON could not be parsed", { cause });
980
+ }
981
+ }
982
+ function isRecord(value) {
983
+ return value !== null && typeof value === "object" && !Array.isArray(value);
984
+ }
985
+ function readString(record4, key, path) {
986
+ const value = record4[key];
987
+ if (typeof value !== "string" || !value.trim()) {
988
+ throw new DocumentValidationError(`${path}.${key} must be a non-empty string`);
989
+ }
990
+ return value;
991
+ }
992
+ function readInteger(record4, key, path) {
993
+ const value = record4[key];
994
+ if (!Number.isInteger(value)) {
995
+ throw new DocumentValidationError(`${path}.${key} must be an integer`);
996
+ }
997
+ return value;
998
+ }
999
+ function readFiniteNumber(record4, key, path) {
1000
+ const value = record4[key];
1001
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1002
+ throw new DocumentValidationError(`${path}.${key} must be a finite number`);
1003
+ }
1004
+ return value;
1005
+ }
1006
+
1007
+ // ../core/src/history.ts
1008
+ var MEDIA_BACKGROUND_PROP_KEYS = [
1009
+ "previewStatus",
1010
+ "previewError",
1011
+ "previewSpec",
1012
+ "previewKey",
1013
+ "pageCount",
1014
+ "previewWarnings",
1015
+ "previewQuality",
1016
+ "fileExtension",
1017
+ "previewJobId",
1018
+ "intrinsicWidth",
1019
+ "intrinsicHeight",
1020
+ "duration",
1021
+ "mediaContentHash",
1022
+ "mediaPreparationStatus",
1023
+ "mediaPreparationError",
1024
+ "mediaAutoSize",
1025
+ "mediaAutoSizeBaseline"
1026
+ ];
1027
+ var MEDIA_BACKGROUND_ASSET_REF_ROLES = /* @__PURE__ */ new Set([
1028
+ "preview",
1029
+ "poster",
1030
+ "waveform"
1031
+ ]);
1032
+ var PREVIEW_REQUEST_PROP_KEYS = /* @__PURE__ */ new Set([
1033
+ "previewRequestId",
1034
+ "previewStatus",
1035
+ "previewError",
1036
+ "previewSpec",
1037
+ "previewKey",
1038
+ "pageCount",
1039
+ "previewWarnings",
1040
+ "previewQuality",
1041
+ "previewJobId"
1042
+ ]);
1043
+ function sourceRefs(node) {
1044
+ const refs = /* @__PURE__ */ new Set();
1045
+ for (const [role, ref] of Object.entries(node.assetRefs ?? {})) {
1046
+ if (!isMediaBackgroundAssetRefRole(role)) {
1047
+ refs.add(JSON.stringify([role, ref.assetId, ref.variant ?? null]));
1048
+ }
1049
+ }
1050
+ return refs;
1051
+ }
1052
+ function isMediaBackgroundAssetRefRole(role) {
1053
+ return MEDIA_BACKGROUND_ASSET_REF_ROLES.has(role) || role.startsWith("_documentPreview") || /^preview-[a-f0-9]{64}$/.test(role);
1054
+ }
1055
+ function createHistoryMediaBackgroundUpdate(before, after) {
1056
+ const beforeSources = sourceRefs(before);
1057
+ const afterSources = sourceRefs(after);
1058
+ if (before.type !== after.type || beforeSources.size !== afterSources.size || [...beforeSources].some((id) => !afterSources.has(id))) {
1059
+ return void 0;
1060
+ }
1061
+ const beforeProps = record3(before.props);
1062
+ const afterProps = record3(after.props);
1063
+ const props = {};
1064
+ for (const key of MEDIA_BACKGROUND_PROP_KEYS) {
1065
+ if (!jsonEqual(beforeProps[key], afterProps[key])) props[key] = afterProps[key];
1066
+ }
1067
+ if (!jsonEqual(beforeProps.previewRequestId, afterProps.previewRequestId)) {
1068
+ props.previewRequestId = afterProps.previewRequestId;
1069
+ props.previewStatus = afterProps.previewStatus;
1070
+ }
1071
+ const assetRefs = {};
1072
+ const beforeRefs = before.assetRefs ?? {};
1073
+ const afterRefs = after.assetRefs ?? {};
1074
+ for (const role of /* @__PURE__ */ new Set([...Object.keys(beforeRefs), ...Object.keys(afterRefs)])) {
1075
+ if (!isMediaBackgroundAssetRefRole(role)) continue;
1076
+ if (!jsonEqual(beforeRefs[role], afterRefs[role])) {
1077
+ assetRefs[role] = afterRefs[role];
1078
+ }
1079
+ }
1080
+ if (Object.keys(assetRefs).length === 0 && Object.keys(props).length === 0) {
1081
+ return void 0;
1082
+ }
1083
+ return {
1084
+ nodeId: after.id,
1085
+ sourceType: before.type,
1086
+ sourceRefs: afterSources,
1087
+ previewRequestIdBefore: beforeProps.previewRequestId,
1088
+ assetRefs,
1089
+ props
1090
+ };
1091
+ }
1092
+ var recordHistory = /* @__PURE__ */ Symbol("recordHistory");
1093
+ var rebaseMediaBackground = /* @__PURE__ */ Symbol("rebaseMediaBackground");
1094
+ var HistoryController = class {
1095
+ constructor(host) {
1096
+ this.host = host;
1097
+ }
1098
+ host;
1099
+ undoStack = [];
1100
+ redoStack = [];
1101
+ listeners = /* @__PURE__ */ new Set();
1102
+ patchGenerations = /* @__PURE__ */ new WeakMap();
1103
+ entryGenerations = /* @__PURE__ */ new WeakMap();
1104
+ nodeGenerations = /* @__PURE__ */ new Map();
1105
+ nextNodeGeneration = 1;
1106
+ canUndo() {
1107
+ return this.undoStack.length > 0;
1108
+ }
1109
+ canRedo() {
1110
+ return this.redoStack.length > 0;
1111
+ }
1112
+ undo() {
1113
+ const entry = this.undoStack.at(-1);
1114
+ if (!entry) return void 0;
1115
+ const changeSet = this.host.applyHistoryEntry(entry, "undo");
1116
+ this.undoStack.pop();
1117
+ this.redoStack.push(entry);
1118
+ this.restoreGenerations(entry, "before");
1119
+ this.emit();
1120
+ return changeSet;
1121
+ }
1122
+ redo() {
1123
+ const entry = this.redoStack.at(-1);
1124
+ if (!entry) return void 0;
1125
+ const changeSet = this.host.applyHistoryEntry(entry, "redo");
1126
+ this.redoStack.pop();
1127
+ this.undoStack.push(entry);
1128
+ this.restoreGenerations(entry, "after");
1129
+ this.emit();
1130
+ return changeSet;
1131
+ }
1132
+ clear() {
1133
+ const hadHistory = this.canUndo() || this.canRedo();
1134
+ this.undoStack = [];
1135
+ this.redoStack = [];
1136
+ this.nodeGenerations = /* @__PURE__ */ new Map();
1137
+ this.nextNodeGeneration = 1;
1138
+ if (hadHistory) this.emit();
1139
+ }
1140
+ onChange(listener) {
1141
+ this.listeners.add(listener);
1142
+ return () => this.listeners.delete(listener);
1143
+ }
1144
+ [recordHistory](entry) {
1145
+ this.captureEntryGenerations(entry);
1146
+ const previous = this.undoStack.at(-1);
1147
+ if (entry.coalesceKey !== void 0 && previous?.coalesceKey === entry.coalesceKey) {
1148
+ previous.forward = compactReplaces([...previous.forward, ...entry.forward]);
1149
+ previous.inverse = compactReplaces([...entry.inverse, ...previous.inverse]);
1150
+ const generationState = this.entryGenerations.get(previous);
1151
+ const nextGenerationState = this.entryGenerations.get(entry);
1152
+ if (generationState && nextGenerationState) {
1153
+ for (const [id, change] of nextGenerationState) {
1154
+ const existing = generationState.get(id);
1155
+ const before = existing ? existing.before : change.before;
1156
+ if (before === change.after) generationState.delete(id);
1157
+ else generationState.set(id, { before, after: change.after });
1158
+ }
1159
+ }
1160
+ this.redoStack = [];
1161
+ this.emit();
1162
+ return;
1163
+ }
1164
+ this.undoStack.push(entry);
1165
+ this.redoStack = [];
1166
+ this.emit();
1167
+ }
1168
+ [rebaseMediaBackground](updates) {
1169
+ if (updates.length === 0) return;
1170
+ const updatesByNode = new Map(updates.map((update) => [update.nodeId, update]));
1171
+ const rebase = (stack) => {
1172
+ for (const entry of stack) {
1173
+ const forward = this.rebasePatches(entry.forward, updatesByNode);
1174
+ const inverse = this.rebasePatches(entry.inverse, updatesByNode);
1175
+ if (forward !== entry.forward) entry.forward = forward;
1176
+ if (inverse !== entry.inverse) entry.inverse = inverse;
1177
+ }
1178
+ };
1179
+ rebase(this.undoStack);
1180
+ rebase(this.redoStack);
1181
+ }
1182
+ rebasePatches(patches, updatesByNode) {
1183
+ let changed = false;
1184
+ const rebased = patches.map((patch) => {
1185
+ if (!hasNodeSnapshot(patch)) return patch;
1186
+ const update = updatesByNode.get(patch.node.id);
1187
+ if (!update) return patch;
1188
+ const generation = this.nodeGenerations.get(patch.node.id);
1189
+ if (generation === void 0) return patch;
1190
+ if (this.patchGenerations.get(patch) !== generation) {
1191
+ return patch;
1192
+ }
1193
+ if (patch.node.type !== update.sourceType || !sameSourceRefs(patch.node, update)) {
1194
+ return patch;
1195
+ }
1196
+ const node = rebaseNodeMediaFields(patch.node, update);
1197
+ if (node === patch.node) return patch;
1198
+ changed = true;
1199
+ const rebasedPatch = { ...patch, node };
1200
+ this.patchGenerations.set(rebasedPatch, generation);
1201
+ return rebasedPatch;
1202
+ });
1203
+ return changed ? rebased : patches;
1204
+ }
1205
+ captureEntryGenerations(entry) {
1206
+ const before = /* @__PURE__ */ new Map();
1207
+ entry.forward.forEach((patch, forwardIndex) => {
1208
+ const inverse = entry.inverse[entry.forward.length - 1 - forwardIndex];
1209
+ if (patch.op === "node:insert") {
1210
+ if (!before.has(patch.node.id)) before.set(patch.node.id, this.nodeGenerations.get(patch.node.id));
1211
+ const generation = this.nextNodeGeneration++;
1212
+ this.nodeGenerations.set(patch.node.id, generation);
1213
+ this.patchGenerations.set(patch, generation);
1214
+ if (inverse && hasNodeSnapshot(inverse)) this.patchGenerations.set(inverse, generation);
1215
+ } else if (patch.op === "node:replace") {
1216
+ const generation = this.nodeGenerations.get(patch.node.id) ?? 0;
1217
+ if (!before.has(patch.node.id)) before.set(patch.node.id, generation);
1218
+ this.nodeGenerations.set(patch.node.id, generation);
1219
+ this.patchGenerations.set(patch, generation);
1220
+ if (inverse?.op === "node:replace") this.patchGenerations.set(inverse, generation);
1221
+ } else if (patch.op === "node:remove") {
1222
+ const generation = this.nodeGenerations.get(patch.nodeId) ?? 0;
1223
+ if (!before.has(patch.nodeId)) before.set(patch.nodeId, generation);
1224
+ this.nodeGenerations.delete(patch.nodeId);
1225
+ if (inverse?.op === "node:insert") this.patchGenerations.set(inverse, generation);
1226
+ }
1227
+ });
1228
+ const changes = /* @__PURE__ */ new Map();
1229
+ for (const [id, previous] of before) {
1230
+ const after = this.nodeGenerations.get(id);
1231
+ if (previous !== after) changes.set(id, { before: previous, after });
1232
+ }
1233
+ this.entryGenerations.set(entry, changes);
1234
+ }
1235
+ restoreGenerations(entry, side) {
1236
+ for (const [id, change] of this.entryGenerations.get(entry) ?? []) {
1237
+ const generation = change[side];
1238
+ if (generation === void 0) this.nodeGenerations.delete(id);
1239
+ else this.nodeGenerations.set(id, generation);
1240
+ }
1241
+ }
1242
+ emit() {
1243
+ const event = { canUndo: this.canUndo(), canRedo: this.canRedo() };
1244
+ for (const listener of this.listeners) {
1245
+ try {
1246
+ listener(event);
1247
+ } catch {
1248
+ }
1249
+ }
1250
+ }
1251
+ };
1252
+ function sameSourceRefs(node, update) {
1253
+ const refs = sourceRefs(node);
1254
+ return refs.size === update.sourceRefs.size && [...update.sourceRefs].every((ref) => refs.has(ref));
1255
+ }
1256
+ function hasNodeSnapshot(patch) {
1257
+ return patch.op === "node:insert" || patch.op === "node:replace";
1258
+ }
1259
+ function rebaseNodeMediaFields(node, update) {
1260
+ let next = node;
1261
+ const sameRequest = jsonEqual(record3(node.props).previewRequestId, update.previewRequestIdBefore);
1262
+ const roles = Object.keys(update.assetRefs);
1263
+ if (sameRequest && roles.length > 0) {
1264
+ const refs = { ...next.assetRefs ?? {} };
1265
+ let refsChanged = false;
1266
+ for (const role of roles) {
1267
+ if (jsonEqual(refs[role], update.assetRefs[role])) continue;
1268
+ refsChanged = true;
1269
+ if (update.assetRefs[role] === void 0) delete refs[role];
1270
+ else refs[role] = cloneValue(update.assetRefs[role]);
1271
+ }
1272
+ if (refsChanged) {
1273
+ next = Object.keys(refs).length === 0 ? withoutAssetRefs(next) : { ...next, assetRefs: refs };
1274
+ }
1275
+ }
1276
+ const propKeys = Object.keys(update.props);
1277
+ if (propKeys.length > 0) {
1278
+ const props = {};
1279
+ for (const [key, value] of Object.entries(record3(next.props))) {
1280
+ if (value !== void 0) props[key] = value;
1281
+ }
1282
+ let propsChanged = false;
1283
+ for (const key of propKeys) {
1284
+ if (!sameRequest && PREVIEW_REQUEST_PROP_KEYS.has(key)) continue;
1285
+ if (jsonEqual(props[key], update.props[key])) continue;
1286
+ propsChanged = true;
1287
+ if (update.props[key] === void 0) delete props[key];
1288
+ else props[key] = cloneValue(update.props[key]);
1289
+ }
1290
+ if (propsChanged) next = { ...next, props };
1291
+ }
1292
+ return next;
1293
+ }
1294
+ function withoutAssetRefs(node) {
1295
+ const { assetRefs: _assetRefs, ...rest } = node;
1296
+ return rest;
1297
+ }
1298
+ function record3(value) {
1299
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
1300
+ }
1301
+ function compactReplaces(patches) {
1302
+ if (patches.some((patch) => patch.op !== "node:replace" && patch.op !== "asset:replace")) {
1303
+ return patches;
1304
+ }
1305
+ const byKey = /* @__PURE__ */ new Map();
1306
+ for (const patch of patches) {
1307
+ const key = patch.op === "node:replace" ? `node:${patch.node.id}` : `asset:${patch.asset.id}`;
1308
+ byKey.set(key, patch);
1309
+ }
1310
+ return [...byKey.values()];
1311
+ }
1312
+ function createHistoryController(host) {
1313
+ const controller = new HistoryController(host);
1314
+ return {
1315
+ controller,
1316
+ record: (entry) => controller[recordHistory](entry),
1317
+ rebaseMediaBackground: (updates) => controller[rebaseMediaBackground](updates)
1318
+ };
1319
+ }
1320
+
1321
+ // ../core/src/patches.ts
1322
+ function applyDataPatches(store, patches) {
1323
+ for (const patch of patches) {
1324
+ switch (patch.op) {
1325
+ case "metadata:replace":
1326
+ store.setMetadata(patch.metadata);
1327
+ break;
1328
+ case "node:insert":
1329
+ store.insertNode(patch.index, patch.node);
1330
+ break;
1331
+ case "node:replace":
1332
+ store.replaceNode(patch.node);
1333
+ break;
1334
+ case "node:remove":
1335
+ store.removeNode(patch.nodeId);
1336
+ break;
1337
+ case "asset:insert":
1338
+ store.insertAsset(patch.index, patch.asset);
1339
+ break;
1340
+ case "asset:replace":
1341
+ store.replaceAsset(patch.asset);
1342
+ break;
1343
+ case "asset:remove":
1344
+ store.removeAsset(patch.assetId);
1345
+ break;
1346
+ }
1347
+ }
1348
+ }
1349
+
1350
+ // ../core/src/store.ts
1351
+ var RuntimeDocumentStore = class _RuntimeDocumentStore {
1352
+ document;
1353
+ nodesById = /* @__PURE__ */ new Map();
1354
+ nodeOrder = /* @__PURE__ */ new Map();
1355
+ assetsById = /* @__PURE__ */ new Map();
1356
+ assetOrder = /* @__PURE__ */ new Map();
1357
+ nodeOverrides = /* @__PURE__ */ new Map();
1358
+ assetOverrides = /* @__PURE__ */ new Map();
1359
+ nodeOverridesShared = false;
1360
+ assetOverridesShared = false;
1361
+ nodesShared = false;
1362
+ assetsShared = false;
1363
+ constructor(document) {
1364
+ this.document = cloneValue(document);
1365
+ this.rebuildIndexes();
1366
+ }
1367
+ clone() {
1368
+ const clone = Object.create(_RuntimeDocumentStore.prototype);
1369
+ clone.document = { ...this.document, nodes: this.document.nodes, assets: this.document.assets };
1370
+ clone.nodesById = this.nodesById;
1371
+ clone.nodeOrder = this.nodeOrder;
1372
+ clone.assetsById = this.assetsById;
1373
+ clone.assetOrder = this.assetOrder;
1374
+ clone.nodeOverrides = this.nodeOverrides;
1375
+ clone.assetOverrides = this.assetOverrides;
1376
+ clone.nodeOverridesShared = true;
1377
+ clone.assetOverridesShared = true;
1378
+ clone.nodesShared = true;
1379
+ clone.assetsShared = true;
1380
+ return clone;
1381
+ }
1382
+ snapshot() {
1383
+ return immutableClone(this.materializedDocument());
1384
+ }
1385
+ mutableSnapshot() {
1386
+ return cloneValue(this.materializedDocument());
1387
+ }
1388
+ getMetadata() {
1389
+ return cloneValue(this.document.metadata);
1390
+ }
1391
+ setMetadata(value) {
1392
+ this.document.metadata = cloneValue(value);
1393
+ }
1394
+ get revision() {
1395
+ return this.document.revision;
1396
+ }
1397
+ set revision(value) {
1398
+ this.document.revision = value;
1399
+ }
1400
+ getNode(id) {
1401
+ const node = this.getNodeReference(id);
1402
+ return node ? cloneValue(node) : void 0;
1403
+ }
1404
+ getNodeReference(id) {
1405
+ return this.nodeOverrides.get(id) ?? this.nodesById.get(id);
1406
+ }
1407
+ requireNode(id) {
1408
+ const node = this.getNodeReference(id);
1409
+ if (!node) throw new NodeNotFoundError(id);
1410
+ return cloneValue(node);
1411
+ }
1412
+ getNodeIndex(id) {
1413
+ return this.nodeOrder.get(id);
1414
+ }
1415
+ listNodes() {
1416
+ return cloneValue(this.materializedNodes());
1417
+ }
1418
+ listNodesByIds(ids) {
1419
+ const nodes = [];
1420
+ for (const id of ids) {
1421
+ const node = this.getNodeReference(id);
1422
+ if (node) nodes.push(node);
1423
+ }
1424
+ nodes.sort((left, right) => (this.nodeOrder.get(left.id) ?? 0) - (this.nodeOrder.get(right.id) ?? 0));
1425
+ return cloneValue(nodes);
1426
+ }
1427
+ nodeCount() {
1428
+ return this.document.nodes.length;
1429
+ }
1430
+ forEachNodeReference(callback) {
1431
+ for (const node of this.document.nodes) callback(this.nodeOverrides.get(node.id) ?? node);
1432
+ }
1433
+ insertNode(index, node) {
1434
+ if (this.getNodeReference(node.id)) {
1435
+ throw new DocumentValidationError(`Duplicate node id: ${node.id}`);
1436
+ }
1437
+ if (!Number.isInteger(index) || index < 0 || index > this.document.nodes.length) {
1438
+ throw new RangeError(`Invalid node insertion index: ${index}`);
1439
+ }
1440
+ this.materializeNodesInPlace();
1441
+ this.document.nodes.splice(index, 0, cloneValue(node));
1442
+ this.rebuildNodeIndex();
1443
+ }
1444
+ replaceNode(node) {
1445
+ const index = this.nodeOrder.get(node.id);
1446
+ if (index === void 0) throw new NodeNotFoundError(node.id);
1447
+ this.ensureNodeOverridesMutable();
1448
+ this.nodeOverrides.set(node.id, cloneValue(node));
1449
+ }
1450
+ removeNode(id) {
1451
+ const index = this.getNodeIndex(id);
1452
+ if (index === void 0) throw new NodeNotFoundError(id);
1453
+ this.materializeNodesInPlace();
1454
+ const [removed] = this.document.nodes.splice(index, 1);
1455
+ this.rebuildNodeIndex();
1456
+ return cloneValue(removed);
1457
+ }
1458
+ getAsset(id) {
1459
+ const asset = this.getAssetReference(id);
1460
+ return asset ? cloneValue(asset) : void 0;
1461
+ }
1462
+ getAssetReference(id) {
1463
+ return this.assetOverrides.get(id) ?? this.assetsById.get(id);
1464
+ }
1465
+ getAssetIndex(id) {
1466
+ return this.assetOrder.get(id);
1467
+ }
1468
+ listAssets() {
1469
+ return cloneValue(this.materializedAssets());
1470
+ }
1471
+ assetCount() {
1472
+ return this.document.assets.length;
1473
+ }
1474
+ insertAsset(index, asset) {
1475
+ if (this.getAssetReference(asset.id)) {
1476
+ throw new DocumentValidationError(`Duplicate asset id: ${asset.id}`);
1477
+ }
1478
+ if (!Number.isInteger(index) || index < 0 || index > this.document.assets.length) {
1479
+ throw new RangeError(`Invalid asset insertion index: ${index}`);
1480
+ }
1481
+ this.materializeAssetsInPlace();
1482
+ this.document.assets.splice(index, 0, cloneValue(asset));
1483
+ this.rebuildAssetIndex();
1484
+ }
1485
+ replaceAsset(asset) {
1486
+ const index = this.assetOrder.get(asset.id);
1487
+ if (index === void 0) {
1488
+ throw new DocumentValidationError(`Asset not found: ${asset.id}`);
1489
+ }
1490
+ this.ensureAssetOverridesMutable();
1491
+ this.assetOverrides.set(asset.id, cloneValue(asset));
1492
+ }
1493
+ removeAsset(id) {
1494
+ const index = this.getAssetIndex(id);
1495
+ if (index === void 0) {
1496
+ throw new DocumentValidationError(`Asset not found: ${id}`);
1497
+ }
1498
+ this.materializeAssetsInPlace();
1499
+ const [removed] = this.document.assets.splice(index, 1);
1500
+ this.rebuildAssetIndex();
1501
+ return cloneValue(removed);
1502
+ }
1503
+ rebuildIndexes() {
1504
+ this.rebuildNodeIndex();
1505
+ this.rebuildAssetIndex();
1506
+ }
1507
+ rebuildNodeIndex() {
1508
+ this.nodesById = /* @__PURE__ */ new Map();
1509
+ this.nodeOrder = /* @__PURE__ */ new Map();
1510
+ this.document.nodes.forEach((node, index) => {
1511
+ if (this.nodesById.has(node.id)) {
1512
+ throw new DocumentValidationError(`Duplicate node id: ${node.id}`);
1513
+ }
1514
+ this.nodesById.set(node.id, node);
1515
+ this.nodeOrder.set(node.id, index);
1516
+ });
1517
+ }
1518
+ rebuildAssetIndex() {
1519
+ this.assetsById = /* @__PURE__ */ new Map();
1520
+ this.assetOrder = /* @__PURE__ */ new Map();
1521
+ this.document.assets.forEach((asset, index) => {
1522
+ if (this.assetsById.has(asset.id)) {
1523
+ throw new DocumentValidationError(`Duplicate asset id: ${asset.id}`);
1524
+ }
1525
+ this.assetsById.set(asset.id, asset);
1526
+ this.assetOrder.set(asset.id, index);
1527
+ });
1528
+ }
1529
+ ensureNodeOverridesMutable() {
1530
+ if (!this.nodeOverridesShared) return;
1531
+ this.nodeOverrides = new Map(this.nodeOverrides);
1532
+ this.nodeOverridesShared = false;
1533
+ }
1534
+ ensureAssetOverridesMutable() {
1535
+ if (!this.assetOverridesShared) return;
1536
+ this.assetOverrides = new Map(this.assetOverrides);
1537
+ this.assetOverridesShared = false;
1538
+ }
1539
+ materializeNodesInPlace() {
1540
+ if (this.nodeOverrides.size === 0 && !this.nodesShared) return;
1541
+ this.document = { ...this.document, nodes: this.materializedNodes().slice() };
1542
+ this.nodeOverrides = /* @__PURE__ */ new Map();
1543
+ this.nodeOverridesShared = false;
1544
+ this.nodesShared = false;
1545
+ this.rebuildNodeIndex();
1546
+ }
1547
+ materializeAssetsInPlace() {
1548
+ if (this.assetOverrides.size === 0 && !this.assetsShared) return;
1549
+ this.document = { ...this.document, assets: this.materializedAssets().slice() };
1550
+ this.assetOverrides = /* @__PURE__ */ new Map();
1551
+ this.assetOverridesShared = false;
1552
+ this.assetsShared = false;
1553
+ this.rebuildAssetIndex();
1554
+ }
1555
+ materializedNodes() {
1556
+ if (this.nodeOverrides.size === 0) return this.document.nodes;
1557
+ return this.document.nodes.map((node) => this.nodeOverrides.get(node.id) ?? node);
1558
+ }
1559
+ materializedAssets() {
1560
+ if (this.assetOverrides.size === 0) return this.document.assets;
1561
+ return this.document.assets.map((asset) => this.assetOverrides.get(asset.id) ?? asset);
1562
+ }
1563
+ materializedDocument() {
1564
+ return {
1565
+ ...this.document,
1566
+ nodes: this.materializedNodes(),
1567
+ assets: this.materializedAssets()
1568
+ };
1569
+ }
1570
+ };
1571
+
1572
+ // ../core/src/core.ts
1573
+ var coreInternals = /* @__PURE__ */ new WeakMap();
1574
+ var BoardCore = class {
1575
+ nodeTypes;
1576
+ nodes;
1577
+ assets;
1578
+ selection;
1579
+ viewport;
1580
+ history;
1581
+ document;
1582
+ store;
1583
+ schemaVersion;
1584
+ idFactory;
1585
+ now;
1586
+ events = new EventHub();
1587
+ activeTransaction;
1588
+ rejectedAsyncTransactionCallbacks = 0;
1589
+ viewportState;
1590
+ recordHistory;
1591
+ rebaseMediaBackground;
1592
+ constructor(options = {}) {
1593
+ this.nodeTypes = options.nodeTypes ?? new NodeTypeRegistry();
1594
+ this.schemaVersion = options.schemaVersion ?? 1;
1595
+ this.idFactory = options.idFactory ?? defaultIdFactory;
1596
+ this.now = options.now ?? Date.now;
1597
+ const document = options.document ? validateDocument(options.document, {
1598
+ schemaVersion: this.schemaVersion,
1599
+ nodeTypes: this.nodeTypes
1600
+ }) : createEmptyDocument(this.schemaVersion);
1601
+ this.store = new RuntimeDocumentStore(document);
1602
+ this.viewportState = new ViewportController(
1603
+ document.viewport ?? { scale: 1, offset: { x: 0, y: 0 } },
1604
+ options.viewportSize,
1605
+ () => this.assertSessionMutationAllowed()
1606
+ );
1607
+ coreInternals.set(this, {
1608
+ mutate: (label, operation) => this.mutate(label, operation),
1609
+ currentStore: () => this.currentStore(),
1610
+ nextId: () => this.nextId(),
1611
+ validateLoadedDocument: (input, loadOptions) => this.validateLoadedDocument(input, loadOptions),
1612
+ loadDocument: (input, loadOptions) => this.loadDocument(input, loadOptions),
1613
+ snapshotDocument: () => this.snapshotDocument(),
1614
+ jsonDocument: () => this.jsonDocument(),
1615
+ recordPatch: (transaction, forward, inverse) => this.recordPatch(transaction, forward, inverse)
1616
+ });
1617
+ this.selection = new SelectionController(
1618
+ (id) => this.currentStore().getNode(id) !== void 0,
1619
+ () => this.assertSessionMutationAllowed()
1620
+ );
1621
+ this.viewport = new BoardViewportController(this, this.viewportState);
1622
+ const history = createHistoryController({
1623
+ applyHistoryEntry: (entry, direction) => this.applyHistoryEntry(entry, direction)
1624
+ });
1625
+ this.history = history.controller;
1626
+ this.recordHistory = history.record;
1627
+ this.rebaseMediaBackground = history.rebaseMediaBackground;
1628
+ this.nodes = new BoardNodesController(this);
1629
+ this.assets = new BoardAssetsController(this);
1630
+ this.document = new BoardDocumentController(this);
1631
+ this.selection.onChange((event) => this.events.emit("selection:change", event));
1632
+ this.viewportState.onChange((event) => {
1633
+ this.events.emit("viewport:change", event);
1634
+ });
1635
+ this.history.onChange((event) => this.events.emit("history:change", event));
1636
+ }
1637
+ on(eventName, listener) {
1638
+ return this.events.on(eventName, listener);
1639
+ }
1640
+ transaction(label, operation, options = {}) {
1641
+ if (this.activeTransaction) {
1642
+ throw new TransactionConflictError("Nested transactions are not supported");
1643
+ }
1644
+ if (this.rejectedAsyncTransactionCallbacks > 0) {
1645
+ throw new TransactionConflictError(
1646
+ "Writes are blocked until a rejected async transaction callback settles"
1647
+ );
1648
+ }
1649
+ const transaction = {
1650
+ id: this.idFactory(),
1651
+ label: label || void 0,
1652
+ origin: options.origin ?? "api",
1653
+ ...options.coalesceKey === void 0 ? {} : { coalesceKey: options.coalesceKey },
1654
+ draft: this.store.clone(),
1655
+ forward: [],
1656
+ inverse: []
1657
+ };
1658
+ this.activeTransaction = transaction;
1659
+ try {
1660
+ const result = operation(this);
1661
+ if (isPromiseLike(result)) {
1662
+ this.rejectedAsyncTransactionCallbacks += 1;
1663
+ void Promise.resolve(result).catch(() => void 0).finally(() => {
1664
+ this.rejectedAsyncTransactionCallbacks -= 1;
1665
+ });
1666
+ throw new TransactionConflictError(
1667
+ "Core transaction callbacks must be synchronous"
1668
+ );
1669
+ }
1670
+ this.activeTransaction = void 0;
1671
+ this.commitTransaction(
1672
+ transaction,
1673
+ options.recordHistory !== false,
1674
+ options.recordHistory === false
1675
+ );
1676
+ return result;
1677
+ } catch (error) {
1678
+ this.activeTransaction = void 0;
1679
+ throw error;
1680
+ }
1681
+ }
1682
+ applyHistoryEntry(entry, direction) {
1683
+ if (this.activeTransaction || this.rejectedAsyncTransactionCallbacks > 0) {
1684
+ throw new TransactionConflictError("History cannot run during a transaction");
1685
+ }
1686
+ const transaction = {
1687
+ id: this.idFactory(),
1688
+ label: `${direction === "undo" ? "Undo" : "Redo"}${entry.label ? `: ${entry.label}` : ""}`,
1689
+ origin: "history",
1690
+ draft: this.store.clone(),
1691
+ forward: direction === "undo" ? entry.inverse : entry.forward,
1692
+ inverse: direction === "undo" ? entry.forward : entry.inverse
1693
+ };
1694
+ applyDataPatches(transaction.draft, transaction.forward);
1695
+ return this.commitTransaction(transaction, false, false);
1696
+ }
1697
+ getBounds(nodeId) {
1698
+ const node = this.currentStore().requireNode(nodeId);
1699
+ return this.nodeTypes.has(node.type) ? this.nodeTypes.getBounds(node) : rotatedRectBounds(node);
1700
+ }
1701
+ mutate(label, operation) {
1702
+ if (this.rejectedAsyncTransactionCallbacks > 0) {
1703
+ throw new TransactionConflictError(
1704
+ "Writes are blocked until a rejected async transaction callback settles"
1705
+ );
1706
+ }
1707
+ if (this.activeTransaction) return operation(this.activeTransaction);
1708
+ let result;
1709
+ this.transaction(label, () => {
1710
+ result = operation(this.activeTransaction);
1711
+ });
1712
+ return result;
1713
+ }
1714
+ currentStore() {
1715
+ return this.activeTransaction?.draft ?? this.store;
1716
+ }
1717
+ nextId() {
1718
+ return this.idFactory();
1719
+ }
1720
+ validateLoadedDocument(input, options = {}) {
1721
+ return validateDocument(input, {
1722
+ schemaVersion: this.schemaVersion,
1723
+ nodeTypes: this.nodeTypes
1724
+ });
1725
+ }
1726
+ loadDocument(input, options = {}) {
1727
+ if (this.activeTransaction || this.rejectedAsyncTransactionCallbacks > 0) {
1728
+ throw new TransactionConflictError("A document cannot be loaded during a transaction");
1729
+ }
1730
+ if (options.replaceHistory === false) {
1731
+ throw new DocumentValidationError(
1732
+ "replaceHistory:false is not supported because history patches belong to the previous document"
1733
+ );
1734
+ }
1735
+ const nextDocument = this.validateLoadedDocument(input, options);
1736
+ const before = this.store;
1737
+ const previousViewport = this.viewportState.get();
1738
+ const hadSelection = this.selection.get().length > 0;
1739
+ this.store = new RuntimeDocumentStore(nextDocument);
1740
+ this.selection.clear();
1741
+ this.viewportState.set(nextDocument.viewport ?? { scale: 1, offset: { x: 0, y: 0 } });
1742
+ this.history.clear();
1743
+ const viewportChanged = !jsonEqual(previousViewport, this.viewportState.get());
1744
+ const changeSet = createChangeSet({
1745
+ before: before.mutableSnapshot(),
1746
+ after: nextDocument,
1747
+ transactionId: this.idFactory(),
1748
+ origin: "load",
1749
+ revision: nextDocument.revision,
1750
+ timestamp: this.now(),
1751
+ selectionChanged: hadSelection,
1752
+ viewportChanged
1753
+ });
1754
+ this.emitChange(changeSet);
1755
+ this.emitMissingNodeTypes(nextDocument.nodes);
1756
+ return changeSet;
1757
+ }
1758
+ snapshotDocument() {
1759
+ return this.store.snapshot();
1760
+ }
1761
+ jsonDocument() {
1762
+ return this.store.mutableSnapshot();
1763
+ }
1764
+ recordPatch(transaction, forward, inverse) {
1765
+ transaction.forward.push(forward);
1766
+ transaction.inverse.unshift(inverse);
1767
+ }
1768
+ commitTransaction(transaction, recordHistory2, rebaseBackgroundHistory = false) {
1769
+ if (transaction.forward.length === 0 && recordHistory2) return void 0;
1770
+ const before = this.store;
1771
+ const after = transaction.draft;
1772
+ if (!hasEffectivePatchChanges(before, after, transaction.forward)) {
1773
+ return void 0;
1774
+ }
1775
+ transaction.draft.revision = before.revision + 1;
1776
+ this.store = after;
1777
+ const selectionChanged = this.selection.prune();
1778
+ const changeSet = createTransactionChangeSet({
1779
+ before,
1780
+ after,
1781
+ patches: transaction.forward,
1782
+ transactionId: transaction.id,
1783
+ label: transaction.label,
1784
+ origin: transaction.origin,
1785
+ revision: after.revision,
1786
+ timestamp: this.now(),
1787
+ selectionChanged,
1788
+ viewportChanged: false
1789
+ });
1790
+ if (recordHistory2) {
1791
+ this.recordHistory({
1792
+ label: transaction.label,
1793
+ origin: transaction.origin,
1794
+ ...transaction.coalesceKey === void 0 ? {} : { coalesceKey: transaction.coalesceKey },
1795
+ forward: transaction.forward,
1796
+ inverse: transaction.inverse
1797
+ });
1798
+ } else if (rebaseBackgroundHistory) {
1799
+ this.rebaseHistoryAfterBackgroundWrite(before, after, transaction.forward);
1800
+ }
1801
+ changeSet.metadataChanged = transaction.forward.some((patch) => patch.op === "metadata:replace") && !jsonEqual(before.getMetadata(), after.getMetadata());
1802
+ this.emitChange(changeSet);
1803
+ return changeSet;
1804
+ }
1805
+ rebaseHistoryAfterBackgroundWrite(before, after, patches) {
1806
+ const updates = [];
1807
+ const seen = /* @__PURE__ */ new Set();
1808
+ for (const patch of patches) {
1809
+ if (patch.op !== "node:replace") continue;
1810
+ if (seen.has(patch.node.id)) continue;
1811
+ const afterNode = after.getNodeReference(patch.node.id);
1812
+ const beforeNode = before.getNodeReference(patch.node.id);
1813
+ if (!afterNode || !beforeNode) continue;
1814
+ seen.add(patch.node.id);
1815
+ const update = createHistoryMediaBackgroundUpdate(beforeNode, afterNode);
1816
+ if (update) updates.push(update);
1817
+ }
1818
+ this.rebaseMediaBackground(updates);
1819
+ }
1820
+ emitChange(changeSet) {
1821
+ const changedNodeIds = /* @__PURE__ */ new Set([
1822
+ ...changeSet.addedNodeIds,
1823
+ ...changeSet.updatedNodeIds,
1824
+ ...changeSet.assetChangedNodeIds
1825
+ ]);
1826
+ const changedNodes = [];
1827
+ for (const nodeId of changedNodeIds) {
1828
+ const node = this.store.getNodeReference(nodeId);
1829
+ if (node) changedNodes.push(node);
1830
+ }
1831
+ this.events.emit("change", {
1832
+ revision: changeSet.revision,
1833
+ changeSet: immutableClone(changeSet),
1834
+ documentUpdate: immutableClone({
1835
+ revision: changeSet.revision,
1836
+ changedNodes
1837
+ })
1838
+ });
1839
+ }
1840
+ emitMissingNodeTypes(nodes) {
1841
+ const missing = /* @__PURE__ */ new Map();
1842
+ for (const node of nodes) {
1843
+ if (this.nodeTypes.has(node.type)) continue;
1844
+ const ids = missing.get(node.type) ?? [];
1845
+ ids.push(node.id);
1846
+ missing.set(node.type, ids);
1847
+ }
1848
+ for (const [type, nodeIds] of missing) {
1849
+ this.events.emit("node-type:missing", { type, nodeIds: [...nodeIds] });
1850
+ }
1851
+ }
1852
+ assertSessionMutationAllowed() {
1853
+ if (this.activeTransaction || this.rejectedAsyncTransactionCallbacks > 0) {
1854
+ throw new TransactionConflictError(
1855
+ "Selection and viewport cannot change during a document transaction"
1856
+ );
1857
+ }
1858
+ }
1859
+ };
1860
+ var BoardNodesController = class {
1861
+ constructor(core) {
1862
+ this.core = core;
1863
+ }
1864
+ core;
1865
+ create(input) {
1866
+ const internals = getCoreInternals(this.core);
1867
+ return internals.mutate("Create node", (transaction) => {
1868
+ const { typeVersion, props } = this.core.nodeTypes.createProps(input.type, input.props);
1869
+ const node = validateNode({
1870
+ id: input.id ?? internals.nextId(),
1871
+ type: input.type,
1872
+ typeVersion: input.typeVersion ?? typeVersion,
1873
+ x: input.x,
1874
+ y: input.y,
1875
+ width: input.width,
1876
+ height: input.height,
1877
+ rotation: input.rotation ?? 0,
1878
+ zIndex: input.zIndex ?? 0,
1879
+ props,
1880
+ ...input.name === void 0 ? {} : { name: input.name },
1881
+ ...input.locked === void 0 ? {} : { locked: input.locked },
1882
+ ...input.visible === void 0 ? {} : { visible: input.visible },
1883
+ ...input.assetRefs === void 0 ? {} : { assetRefs: cloneValue(input.assetRefs) },
1884
+ ...input.fit === void 0 ? {} : { fit: input.fit }
1885
+ });
1886
+ const validated = this.core.nodeTypes.validateNode(node);
1887
+ const index = transaction.draft.nodeCount();
1888
+ transaction.draft.insertNode(index, validated);
1889
+ internals.recordPatch(
1890
+ transaction,
1891
+ { op: "node:insert", index, node: validated },
1892
+ { op: "node:remove", nodeId: validated.id }
1893
+ );
1894
+ return immutableClone(validated);
1895
+ });
1896
+ }
1897
+ update(nodeId, patch) {
1898
+ const internals = getCoreInternals(this.core);
1899
+ return internals.mutate("Update node", (transaction) => {
1900
+ const previous = transaction.draft.requireNode(nodeId);
1901
+ if ("props" in patch && !this.core.nodeTypes.has(previous.type)) {
1902
+ throw new NodeTypeNotRegisteredError(previous.type);
1903
+ }
1904
+ const next = validateNode({ ...previous, ...cloneValue(patch), id: previous.id, type: previous.type });
1905
+ const validated = this.core.nodeTypes.has(next.type) ? this.core.nodeTypes.validateNode(next) : next;
1906
+ if (jsonEqual(previous, validated)) return immutableClone(previous);
1907
+ transaction.draft.replaceNode(validated);
1908
+ internals.recordPatch(
1909
+ transaction,
1910
+ { op: "node:replace", node: validated },
1911
+ { op: "node:replace", node: previous }
1912
+ );
1913
+ return immutableClone(validated);
1914
+ });
1915
+ }
1916
+ convert(nodeId, input) {
1917
+ const internals = getCoreInternals(this.core);
1918
+ return internals.mutate("Convert node", (transaction) => {
1919
+ const previous = transaction.draft.requireNode(nodeId);
1920
+ const { typeVersion, props } = this.core.nodeTypes.createProps(input.type, input.props);
1921
+ const { x, y, width, height, rotation, zIndex, locked, visible } = previous;
1922
+ const next = validateNode({
1923
+ x,
1924
+ y,
1925
+ width,
1926
+ height,
1927
+ rotation,
1928
+ zIndex,
1929
+ ...locked === void 0 ? {} : { locked },
1930
+ ...visible === void 0 ? {} : { visible },
1931
+ ...cloneValue(input),
1932
+ id: previous.id,
1933
+ typeVersion: input.typeVersion ?? typeVersion,
1934
+ props
1935
+ });
1936
+ const validated = this.core.nodeTypes.validateNode(next);
1937
+ if (jsonEqual(previous, validated)) return immutableClone(validated);
1938
+ transaction.draft.replaceNode(validated);
1939
+ internals.recordPatch(
1940
+ transaction,
1941
+ { op: "node:replace", node: validated },
1942
+ { op: "node:replace", node: previous }
1943
+ );
1944
+ return immutableClone(validated);
1945
+ });
1946
+ }
1947
+ /**
1948
+ * Applies one resize gesture step through the node type's `ResizePolicy`.
1949
+ * The policy decides what the requested handle drag is allowed to become —
1950
+ * `fixed` refuses it outright, `aspect-ratio` locks the two axes together
1951
+ * and `custom` gets the last word on the resulting size — so hosts never
1952
+ * need to reimplement those rules on top of `update()`.
1953
+ */
1954
+ resize(nodeId, request) {
1955
+ const node = getCoreInternals(this.core).currentStore().requireNode(nodeId);
1956
+ const policy = this.core.nodeTypes.get(node.type)?.resize;
1957
+ const patch = resolveResize(node, policy, request);
1958
+ if (Object.keys(patch).length === 0) return immutableClone(node);
1959
+ return this.update(nodeId, patch);
1960
+ }
1961
+ remove(nodeId) {
1962
+ const internals = getCoreInternals(this.core);
1963
+ return internals.mutate("Remove node", (transaction) => {
1964
+ const index = transaction.draft.getNodeIndex(nodeId);
1965
+ if (index === void 0) throw new NodeNotFoundError(nodeId);
1966
+ const removed = transaction.draft.removeNode(nodeId);
1967
+ internals.recordPatch(
1968
+ transaction,
1969
+ { op: "node:remove", nodeId },
1970
+ { op: "node:insert", index, node: removed }
1971
+ );
1972
+ const metadata = transaction.draft.getMetadata();
1973
+ if (Array.isArray(metadata?.connections)) {
1974
+ const connections = metadata.connections.filter((edge) => !edge || typeof edge !== "object" || Array.isArray(edge) || edge.source !== nodeId && edge.target !== nodeId);
1975
+ if (connections.length !== metadata.connections.length) this.core.document.patchMetadata({ connections });
1976
+ }
1977
+ return immutableClone(removed);
1978
+ });
1979
+ }
1980
+ get(nodeId) {
1981
+ const node = getCoreInternals(this.core).currentStore().getNode(nodeId);
1982
+ return node ? immutableClone(node) : void 0;
1983
+ }
1984
+ list(filter = {}) {
1985
+ const idFilter = filter.ids ? new Set(filter.ids) : void 0;
1986
+ const typeFilter = filter.types ? new Set(filter.types) : void 0;
1987
+ const limit = filter.limit ?? Number.POSITIVE_INFINITY;
1988
+ if (!Number.isInteger(limit) && limit !== Number.POSITIVE_INFINITY) {
1989
+ throw new RangeError("Node list limit must be an integer");
1990
+ }
1991
+ if (limit < 0) throw new RangeError("Node list limit must not be negative");
1992
+ const store = getCoreInternals(this.core).currentStore();
1993
+ const selected = filter.selected === void 0 ? void 0 : new Set(this.core.selection.get());
1994
+ const source = idFilter ? store.listNodesByIds(idFilter) : store.listNodes();
1995
+ const result = source.filter((node) => {
1996
+ if (idFilter && !idFilter.has(node.id)) return false;
1997
+ if (typeFilter && !typeFilter.has(node.type)) return false;
1998
+ if (filter.type && node.type !== filter.type) return false;
1999
+ if (filter.bounds && !boundsIntersect(this.core.getBounds(node.id), filter.bounds)) return false;
2000
+ if (filter.visible !== void 0 && (node.visible ?? true) !== filter.visible) return false;
2001
+ if (filter.selected !== void 0 && selected.has(node.id) !== filter.selected) return false;
2002
+ return true;
2003
+ });
2004
+ return deepFreeze(result.slice(0, limit));
2005
+ }
2006
+ };
2007
+ function boundsIntersect(left, right) {
2008
+ return left.maxX >= right.minX && left.minX <= right.maxX && left.maxY >= right.minY && left.minY <= right.maxY;
2009
+ }
2010
+ var BoardAssetsController = class {
2011
+ constructor(core) {
2012
+ this.core = core;
2013
+ }
2014
+ core;
2015
+ upsert(assetInput) {
2016
+ const internals = getCoreInternals(this.core);
2017
+ return internals.mutate("Upsert asset", (transaction) => {
2018
+ const asset = validateAsset(assetInput);
2019
+ const previous = transaction.draft.getAsset(asset.id);
2020
+ if (previous && jsonEqual(previous, asset)) return immutableClone(previous);
2021
+ if (previous) {
2022
+ transaction.draft.replaceAsset(asset);
2023
+ internals.recordPatch(
2024
+ transaction,
2025
+ { op: "asset:replace", asset },
2026
+ { op: "asset:replace", asset: previous }
2027
+ );
2028
+ } else {
2029
+ const index = transaction.draft.assetCount();
2030
+ transaction.draft.insertAsset(index, asset);
2031
+ internals.recordPatch(
2032
+ transaction,
2033
+ { op: "asset:insert", index, asset },
2034
+ { op: "asset:remove", assetId: asset.id }
2035
+ );
2036
+ }
2037
+ return immutableClone(asset);
2038
+ });
2039
+ }
2040
+ remove(assetId) {
2041
+ const internals = getCoreInternals(this.core);
2042
+ return internals.mutate("Remove asset", (transaction) => {
2043
+ const index = transaction.draft.getAssetIndex(assetId);
2044
+ if (index === void 0) throw new DocumentValidationError(`Asset not found: ${assetId}`);
2045
+ const asset = transaction.draft.removeAsset(assetId);
2046
+ internals.recordPatch(
2047
+ transaction,
2048
+ { op: "asset:remove", assetId },
2049
+ { op: "asset:insert", index, asset }
2050
+ );
2051
+ return immutableClone(asset);
2052
+ });
2053
+ }
2054
+ get(assetId) {
2055
+ const asset = getCoreInternals(this.core).currentStore().getAsset(assetId);
2056
+ return asset ? immutableClone(asset) : void 0;
2057
+ }
2058
+ list() {
2059
+ return immutableClone(getCoreInternals(this.core).currentStore().listAssets());
2060
+ }
2061
+ };
2062
+ var BoardViewportController = class {
2063
+ constructor(core, viewport) {
2064
+ this.core = core;
2065
+ this.viewport = viewport;
2066
+ }
2067
+ core;
2068
+ viewport;
2069
+ get() {
2070
+ return this.viewport.get();
2071
+ }
2072
+ set(value) {
2073
+ this.viewport.set(value);
2074
+ }
2075
+ setScreenSize(size) {
2076
+ this.viewport.setScreenSize(size);
2077
+ }
2078
+ getScreenSize() {
2079
+ return this.viewport.getScreenSize();
2080
+ }
2081
+ visibleWorldBounds(padding) {
2082
+ return this.viewport.visibleWorldBounds(padding);
2083
+ }
2084
+ panBy(deltaX, deltaY) {
2085
+ this.viewport.panBy(deltaX, deltaY);
2086
+ }
2087
+ zoomAt(screenPoint, factor) {
2088
+ this.viewport.zoomAt(screenPoint, factor);
2089
+ }
2090
+ fitNodes(nodeIds, options) {
2091
+ const bounds = mergeBounds(nodeIds.map((nodeId) => this.core.getBounds(nodeId)));
2092
+ if (!bounds) return;
2093
+ this.viewport.fitBounds(bounds, options);
2094
+ }
2095
+ fitBounds(bounds, options) {
2096
+ this.viewport.fitBounds(bounds, options);
2097
+ }
2098
+ toWorld(screenPoint) {
2099
+ return this.viewport.toWorld(screenPoint);
2100
+ }
2101
+ toScreen(worldPoint) {
2102
+ return this.viewport.toScreen(worldPoint);
2103
+ }
2104
+ onChange(listener) {
2105
+ return this.viewport.onChange(listener);
2106
+ }
2107
+ };
2108
+ var BoardDocumentController = class {
2109
+ constructor(core) {
2110
+ this.core = core;
2111
+ }
2112
+ core;
2113
+ getRevision() {
2114
+ return getCoreInternals(this.core).currentStore().revision;
2115
+ }
2116
+ getMetadata() {
2117
+ return getCoreInternals(this.core).currentStore().getMetadata();
2118
+ }
2119
+ patchMetadata(patch) {
2120
+ const internals = getCoreInternals(this.core);
2121
+ internals.mutate("Update document metadata", (transaction) => {
2122
+ const previous = transaction.draft.getMetadata();
2123
+ const next = { ...previous };
2124
+ for (const [key, value] of Object.entries(patch)) {
2125
+ if (value === void 0) delete next[key];
2126
+ else next[key] = cloneValue(value);
2127
+ }
2128
+ assertJsonValue(next, "document.metadata");
2129
+ transaction.draft.setMetadata(next);
2130
+ internals.recordPatch(transaction, { op: "metadata:replace", metadata: next }, { op: "metadata:replace", metadata: previous });
2131
+ });
2132
+ }
2133
+ snapshot() {
2134
+ return getCoreInternals(this.core).snapshotDocument();
2135
+ }
2136
+ toJSON() {
2137
+ return getCoreInternals(this.core).jsonDocument();
2138
+ }
2139
+ stringify(space) {
2140
+ return JSON.stringify(this.toJSON(), null, space);
2141
+ }
2142
+ load(input, options) {
2143
+ return getCoreInternals(this.core).loadDocument(input, options);
2144
+ }
2145
+ validate(input) {
2146
+ return getCoreInternals(this.core).validateLoadedDocument(input);
2147
+ }
2148
+ };
2149
+ function createBoardCore(options) {
2150
+ return new BoardCore(options);
2151
+ }
2152
+ function getCoreInternals(core) {
2153
+ const internals = coreInternals.get(core);
2154
+ if (!internals) throw new Error("BoardCore internals are unavailable");
2155
+ return internals;
2156
+ }
2157
+ function createEmptyDocument(schemaVersion) {
2158
+ if (!Number.isInteger(schemaVersion) || schemaVersion < 1) {
2159
+ throw new DocumentValidationError("schemaVersion must be a positive integer");
2160
+ }
2161
+ return { schemaVersion, revision: 0, nodes: [], assets: [] };
2162
+ }
2163
+ function defaultIdFactory() {
2164
+ return globalThis.crypto.randomUUID();
2165
+ }
2166
+ function isPromiseLike(value) {
2167
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
2168
+ }
2169
+ function createChangeSet(input) {
2170
+ const beforeNodes = new Map(input.before.nodes.map((node) => [node.id, node]));
2171
+ const afterNodes = new Map(input.after.nodes.map((node) => [node.id, node]));
2172
+ const beforeNodeOrder = new Map(input.before.nodes.map((node, index) => [node.id, index]));
2173
+ const addedNodeIds = input.after.nodes.filter((node) => !beforeNodes.has(node.id)).map((node) => node.id);
2174
+ const updatedNodeIds = input.after.nodes.filter((node, index) => {
2175
+ const previous = beforeNodes.get(node.id);
2176
+ return previous !== void 0 && (!jsonEqual(previous, node) || beforeNodeOrder.get(node.id) !== index);
2177
+ }).map((node) => node.id);
2178
+ const removedNodeIds = input.before.nodes.filter((node) => !afterNodes.has(node.id)).map((node) => node.id);
2179
+ const beforeAssets = new Map(input.before.assets.map((asset) => [asset.id, asset]));
2180
+ const afterAssets = new Map(input.after.assets.map((asset) => [asset.id, asset]));
2181
+ const changedAssetIds = /* @__PURE__ */ new Set();
2182
+ for (const asset of input.before.assets) {
2183
+ const next = afterAssets.get(asset.id);
2184
+ if (!next || !jsonEqual(asset, next)) changedAssetIds.add(asset.id);
2185
+ }
2186
+ for (const asset of input.after.assets) {
2187
+ const previous = beforeAssets.get(asset.id);
2188
+ if (!previous || !jsonEqual(previous, asset)) changedAssetIds.add(asset.id);
2189
+ }
2190
+ const assetChangedNodeIds = input.after.nodes.filter((node) => {
2191
+ const previous = beforeNodes.get(node.id);
2192
+ if (previous && !jsonEqual(previous.assetRefs, node.assetRefs)) return true;
2193
+ return Object.values(node.assetRefs ?? {}).some((ref) => changedAssetIds.has(ref.assetId));
2194
+ }).map((node) => node.id);
2195
+ return {
2196
+ transactionId: input.transactionId,
2197
+ revision: input.revision,
2198
+ ...input.label ? { label: input.label } : {},
2199
+ origin: input.origin,
2200
+ addedNodeIds,
2201
+ updatedNodeIds,
2202
+ removedNodeIds,
2203
+ assetChangedNodeIds,
2204
+ selectionChanged: input.selectionChanged,
2205
+ viewportChanged: input.viewportChanged,
2206
+ timestamp: input.timestamp
2207
+ };
2208
+ }
2209
+ function hasEffectivePatchChanges(before, after, patches) {
2210
+ if (patches.some((patch) => patch.op === "metadata:replace") && !jsonEqual(before.getMetadata(), after.getMetadata())) return true;
2211
+ if (patches.some((patch) => patch.op.endsWith(":insert") || patch.op.endsWith(":remove"))) {
2212
+ const beforeSnapshot = before.mutableSnapshot();
2213
+ const afterSnapshot = after.mutableSnapshot();
2214
+ return !jsonEqual(beforeSnapshot.nodes, afterSnapshot.nodes) || !jsonEqual(beforeSnapshot.assets, afterSnapshot.assets);
2215
+ }
2216
+ for (const patch of patches) {
2217
+ if (patch.op === "node:replace") {
2218
+ if (!jsonEqual(before.getNodeReference(patch.node.id), after.getNodeReference(patch.node.id))) {
2219
+ return true;
2220
+ }
2221
+ } else if (patch.op === "asset:replace") {
2222
+ if (!jsonEqual(before.getAssetReference(patch.asset.id), after.getAssetReference(patch.asset.id))) {
2223
+ return true;
2224
+ }
2225
+ }
2226
+ }
2227
+ return false;
2228
+ }
2229
+ function createTransactionChangeSet(input) {
2230
+ const structural = input.patches.some(
2231
+ (patch) => patch.op.endsWith(":insert") || patch.op.endsWith(":remove")
2232
+ );
2233
+ if (structural) {
2234
+ return createChangeSet({
2235
+ before: input.before.mutableSnapshot(),
2236
+ after: input.after.mutableSnapshot(),
2237
+ transactionId: input.transactionId,
2238
+ label: input.label,
2239
+ origin: input.origin,
2240
+ revision: input.revision,
2241
+ timestamp: input.timestamp,
2242
+ selectionChanged: input.selectionChanged,
2243
+ viewportChanged: input.viewportChanged
2244
+ });
2245
+ }
2246
+ const updatedIds = /* @__PURE__ */ new Set();
2247
+ const changedAssetIds = /* @__PURE__ */ new Set();
2248
+ for (const patch of input.patches) {
2249
+ if (patch.op === "node:replace") updatedIds.add(patch.node.id);
2250
+ if (patch.op === "asset:replace") changedAssetIds.add(patch.asset.id);
2251
+ }
2252
+ const updatedNodeIds = [...updatedIds].filter((id) => {
2253
+ const before = input.before.getNodeReference(id);
2254
+ const after = input.after.getNodeReference(id);
2255
+ return before !== void 0 && after !== void 0 && !jsonEqual(before, after);
2256
+ }).sort(
2257
+ (left, right) => (input.after.getNodeIndex(left) ?? Number.POSITIVE_INFINITY) - (input.after.getNodeIndex(right) ?? Number.POSITIVE_INFINITY)
2258
+ );
2259
+ const assetChangedNodeIds = /* @__PURE__ */ new Set();
2260
+ for (const id of updatedIds) {
2261
+ const before = input.before.getNodeReference(id);
2262
+ const after = input.after.getNodeReference(id);
2263
+ if (before && after && !jsonEqual(before.assetRefs, after.assetRefs)) {
2264
+ assetChangedNodeIds.add(id);
2265
+ }
2266
+ }
2267
+ if (changedAssetIds.size > 0) {
2268
+ input.after.forEachNodeReference((node) => {
2269
+ if (Object.values(node.assetRefs ?? {}).some((ref) => changedAssetIds.has(ref.assetId))) {
2270
+ assetChangedNodeIds.add(node.id);
2271
+ }
2272
+ });
2273
+ }
2274
+ return {
2275
+ transactionId: input.transactionId,
2276
+ revision: input.revision,
2277
+ ...input.label ? { label: input.label } : {},
2278
+ origin: input.origin,
2279
+ addedNodeIds: [],
2280
+ updatedNodeIds,
2281
+ removedNodeIds: [],
2282
+ assetChangedNodeIds: [...assetChangedNodeIds].sort(
2283
+ (left, right) => (input.after.getNodeIndex(left) ?? Number.POSITIVE_INFINITY) - (input.after.getNodeIndex(right) ?? Number.POSITIVE_INFINITY)
2284
+ ),
2285
+ selectionChanged: input.selectionChanged,
2286
+ viewportChanged: input.viewportChanged,
2287
+ timestamp: input.timestamp
2288
+ };
2289
+ }
2290
+ var EventHub = class {
2291
+ listeners = /* @__PURE__ */ new Map();
2292
+ on(eventName, listener) {
2293
+ const listeners = this.listeners.get(eventName) ?? /* @__PURE__ */ new Set();
2294
+ listeners.add(listener);
2295
+ this.listeners.set(eventName, listeners);
2296
+ return () => listeners.delete(listener);
2297
+ }
2298
+ emit(eventName, event) {
2299
+ for (const listener of this.listeners.get(eventName) ?? []) {
2300
+ try {
2301
+ listener(event);
2302
+ } catch {
2303
+ }
2304
+ }
2305
+ }
2306
+ };
2307
+
2308
+ // ../core/src/index.ts
2309
+ var src_exports = {};
2310
+ __export(src_exports, {
2311
+ BoardAssetsController: () => BoardAssetsController,
2312
+ BoardCore: () => BoardCore,
2313
+ BoardDocumentController: () => BoardDocumentController,
2314
+ BoardNodesController: () => BoardNodesController,
2315
+ BoardViewportController: () => BoardViewportController,
2316
+ DocumentValidationError: () => DocumentValidationError,
2317
+ NodeNotFoundError: () => NodeNotFoundError,
2318
+ NodeTypeNotRegisteredError: () => NodeTypeNotRegisteredError,
2319
+ NodeTypeRegistry: () => NodeTypeRegistry,
2320
+ NodeValidationError: () => NodeValidationError,
2321
+ PixiBoardCoreError: () => PixiBoardCoreError,
2322
+ PreviewRendererRegistry: () => PreviewRendererRegistry,
2323
+ RESIZE_HANDLES: () => RESIZE_HANDLES,
2324
+ SelectionController: () => SelectionController,
2325
+ TEXTURE_REF_ROLES: () => TEXTURE_REF_ROLES,
2326
+ TransactionConflictError: () => TransactionConflictError,
2327
+ ViewportController: () => ViewportController,
2328
+ assertWorldBounds: () => assertWorldBounds,
2329
+ createBoardCore: () => createBoardCore,
2330
+ createMediaAssetRefs: () => createMediaAssetRefs,
2331
+ createMediaMetadata: () => createMediaMetadata,
2332
+ createPreviewSpec: () => createPreviewSpec,
2333
+ fitMediaRect: () => fitMediaRect,
2334
+ isAssetVariant: () => isAssetVariant,
2335
+ isContentFit: () => isContentFit,
2336
+ isRenderAssetKind: () => isRenderAssetKind,
2337
+ isResizeHandle: () => isResizeHandle,
2338
+ mergeBounds: () => mergeBounds,
2339
+ nodeGeometry: () => nodeGeometry,
2340
+ preferredMediaNodeSize: () => preferredMediaNodeSize,
2341
+ previewStatusLabel: () => previewStatusLabel,
2342
+ readIntrinsicSize: () => readIntrinsicSize,
2343
+ resizeHandleAxes: () => resizeHandleAxes,
2344
+ resizeHandleCursor: () => resizeHandleCursor,
2345
+ resolveResize: () => resolveResize,
2346
+ resolveResizeSize: () => resolveResizeSize,
2347
+ resolveTextureAssetRef: () => resolveTextureAssetRef,
2348
+ rotatedRectBounds: () => rotatedRectBounds
2349
+ });
2350
+
2351
+ export { BoardAssetsController, BoardCore, BoardDocumentController, BoardNodesController, BoardViewportController, DocumentValidationError, NodeNotFoundError, NodeTypeNotRegisteredError, NodeTypeRegistry, NodeValidationError, PixiBoardCoreError, PreviewRendererRegistry, RESIZE_HANDLES, SelectionController, TEXTURE_REF_ROLES, TransactionConflictError, ViewportController, assertWorldBounds, createBoardCore, createMediaAssetRefs, createMediaMetadata, createPreviewSpec, fitMediaRect, isAssetVariant, isContentFit, isRenderAssetKind, isResizeHandle, mergeBounds, nodeGeometry, preferredMediaNodeSize, previewStatusLabel, readIntrinsicSize, resizeHandleAxes, resizeHandleCursor, resolveResize, resolveResizeSize, resolveTextureAssetRef, rotatedRectBounds, src_exports };
2352
+ //# sourceMappingURL=chunk-NPEG2TBO.js.map
2353
+ //# sourceMappingURL=chunk-NPEG2TBO.js.map