@iwsdk/vite-plugin-dev 0.4.2 → 0.5.1

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.
@@ -0,0 +1,1700 @@
1
+ import { s as sha256, c as canonicalizeJson, a as assertValidSceneDocument, S as SceneCommandHistory, h as hashSceneDocument, b as hashRuntimeSceneDocument, C as CURRENT_SCENE_VERSION, M as MAX_SCENE_RESOURCES, d as MAX_SCENE_PATTERN_EXPANSION, e as MAX_SCENE_NODES, f as MAX_SCENE_COORDINATE, g as CURRENT_SCENE_REVIEW_VERSION, i as applyScenePatch, r as resolveLookAtTransformInDocument, v as validateSceneDocument, j as serializeSceneDocument, k as SCENE_REVIEW_JSON_SCHEMA, l as SCENE_DOCUMENT_JSON_SCHEMA } from '../patch-BVc5fBs4.js';
2
+
3
+ /** Stable structural fingerprint shared by editor and runtime capabilities. */
4
+ function hashSceneComponentSchema(schema) {
5
+ return sha256(canonicalizeJson(structuralComponentSchema(schema)));
6
+ }
7
+ /** Presentation metadata does not invalidate authored component payloads. */
8
+ function structuralComponentSchema(schema) {
9
+ return {
10
+ id: schema.id,
11
+ fields: Object.fromEntries(Object.entries(schema.fields).map(([name, field]) => [
12
+ name,
13
+ {
14
+ type: field.type,
15
+ ...(field.default === undefined ? {} : { default: field.default }),
16
+ ...(field.enum == null ? {} : { enum: field.enum }),
17
+ ...(field.min == null ? {} : { min: field.min }),
18
+ ...(field.max == null ? {} : { max: field.max }),
19
+ },
20
+ ])),
21
+ };
22
+ }
23
+
24
+ /**
25
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
26
+ *
27
+ * This source code is licensed under the MIT license found in the
28
+ * LICENSE file in the root directory of this source tree.
29
+ */
30
+ function hashSceneCapabilitySnapshot(snapshot) {
31
+ return sha256(canonicalizeJson(snapshot));
32
+ }
33
+ function validateSceneCapabilities(document, snapshot, options = {}) {
34
+ assertValidSceneDocument(document, options);
35
+ const issues = [];
36
+ if (!snapshot.sceneVersions.includes(document.version)) {
37
+ addUnsupported(issues, '$.version', 'scene version', document.version);
38
+ }
39
+ const authoredCapabilityHash = document.authoring?.composition?.provenance.capabilityHash;
40
+ const activeCapabilityHash = hashSceneCapabilitySnapshot(snapshot);
41
+ if (options.validateAuthoringWorkflow !== false &&
42
+ authoredCapabilityHash != null &&
43
+ authoredCapabilityHash.toLowerCase() !== activeCapabilityHash.toLowerCase()) {
44
+ issues.push({
45
+ code: 'capability',
46
+ path: '$.authoring.composition.provenance.capabilityHash',
47
+ message: `compilation capability hash does not match the active snapshot (expected ${activeCapabilityHash})`,
48
+ });
49
+ }
50
+ const shadowMapType = document.environment?.shadowMapType;
51
+ if (shadowMapType != null &&
52
+ !(snapshot.shadowMapTypes ?? []).includes(shadowMapType)) {
53
+ addUnsupported(issues, '$.environment.shadowMapType', 'shadow map type', shadowMapType);
54
+ }
55
+ if (options.componentCatalog != null) {
56
+ validateComponentCapabilities(document.components, '$.components', snapshot, options.componentCatalog, issues);
57
+ }
58
+ walkNodes(document.nodes, '$.nodes', (node, path) => {
59
+ validateNodeCapability(node, path, snapshot, issues);
60
+ if (options.componentCatalog != null) {
61
+ validateComponentCapabilities(node.components, `${path}.components`, snapshot, options.componentCatalog, issues);
62
+ }
63
+ });
64
+ document.resources.prefabs?.forEach((prefab, index) => {
65
+ walkNodes([prefab.root], `$.resources.prefabs[${index}].root`, (node, path) => {
66
+ validateNodeCapability(node, path, snapshot, issues);
67
+ if (options.componentCatalog != null) {
68
+ validateComponentCapabilities(node.components, `${path}.components`, snapshot, options.componentCatalog, issues);
69
+ }
70
+ });
71
+ });
72
+ const nodeCount = countNodes(document.nodes) +
73
+ (document.resources.prefabs ?? []).reduce((count, prefab) => count + countNodes([prefab.root]), 0);
74
+ const resourceCount = document.resources.prefabs?.length ?? 0;
75
+ if (snapshot.limits?.maxNodes != null &&
76
+ nodeCount > snapshot.limits.maxNodes) {
77
+ issues.push({
78
+ code: 'capability-limit',
79
+ path: '$.nodes',
80
+ message: `scene has ${nodeCount} nodes; capability limit is ${snapshot.limits.maxNodes}`,
81
+ });
82
+ }
83
+ if (snapshot.limits?.maxResources != null &&
84
+ resourceCount > snapshot.limits.maxResources) {
85
+ issues.push({
86
+ code: 'capability-limit',
87
+ path: '$.resources',
88
+ message: `scene has ${resourceCount} resources; capability limit is ${snapshot.limits.maxResources}`,
89
+ });
90
+ }
91
+ return { valid: issues.length === 0, issues };
92
+ }
93
+ function validateComponentCapabilities(components, path, snapshot, catalog, issues) {
94
+ for (const componentName of Object.keys(components ?? {})) {
95
+ const componentId = stripComponentPrefix$1(componentName);
96
+ const actual = snapshot.componentSchemaHashes[componentId];
97
+ if (actual == null) {
98
+ issues.push({
99
+ code: 'capability',
100
+ path: `${path}[${JSON.stringify(componentName)}]`,
101
+ message: `component "${componentId}" is not registered`,
102
+ });
103
+ continue;
104
+ }
105
+ const schema = catalog?.[componentId] ?? catalog?.[componentName];
106
+ if (schema != null && actual !== hashSceneComponentSchema(schema)) {
107
+ issues.push({
108
+ code: 'capability',
109
+ path: `${path}[${JSON.stringify(componentName)}]`,
110
+ message: `component "${componentId}" schema does not match the active capability snapshot`,
111
+ });
112
+ }
113
+ }
114
+ }
115
+ function stripComponentPrefix$1(name) {
116
+ const prefix = 'com.iwsdk.components.';
117
+ return name.startsWith(prefix) ? name.slice(prefix.length) : name;
118
+ }
119
+ function validateNodeCapability(node, path, snapshot, issues) {
120
+ const content = node.content;
121
+ if (content != null && !snapshot.nodeContentTypes.includes(content.type)) {
122
+ addUnsupported(issues, `${path}.content.type`, 'node content', content.type);
123
+ }
124
+ if (content?.type === 'pattern' &&
125
+ !snapshot.patternTypes.includes(content.distribution.type)) {
126
+ addUnsupported(issues, `${path}.content.distribution.type`, 'pattern distribution', content.distribution.type);
127
+ }
128
+ }
129
+ function walkNodes(nodes, path, visitor) {
130
+ nodes.forEach((node, index) => {
131
+ const nodePath = nodes.length === 1 && path.endsWith('.root') ? path : `${path}[${index}]`;
132
+ visitor(node, nodePath);
133
+ walkNodes(node.children ?? [], `${nodePath}.children`, visitor);
134
+ });
135
+ }
136
+ function countNodes(nodes) {
137
+ return nodes.reduce((count, node) => count + 1 + countNodes(node.children ?? []), 0);
138
+ }
139
+ function addUnsupported(issues, path, kind, value) {
140
+ issues.push({
141
+ code: 'capability',
142
+ path,
143
+ message: `${kind} "${value}" is not supported by this capability snapshot`,
144
+ });
145
+ }
146
+
147
+ /**
148
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
149
+ *
150
+ * This source code is licensed under the MIT license found in the
151
+ * LICENSE file in the root directory of this source tree.
152
+ */
153
+ const SCENE_EDITOR_TOOL_METHODS = [
154
+ 'scene_get_capabilities',
155
+ 'scene_select',
156
+ 'scene_set_camera',
157
+ 'scene_screenshot',
158
+ 'ui_list_assets',
159
+ 'ui_render_preview',
160
+ ];
161
+ const SCENE_EDITOR_TOOL_METHOD_SET = new Set(SCENE_EDITOR_TOOL_METHODS);
162
+ const SCENE_EDITOR_WRITE_METHODS = new Set([
163
+ 'scene_select',
164
+ 'scene_add_node',
165
+ 'scene_remove_node',
166
+ 'scene_duplicate_node',
167
+ 'scene_set_transform',
168
+ 'scene_set_framing_role',
169
+ 'scene_apply_patch',
170
+ 'scene_apply_transaction',
171
+ 'scene_replace_document',
172
+ 'scene_look_at',
173
+ 'scene_save',
174
+ 'scene_undo',
175
+ 'scene_redo',
176
+ ]);
177
+ const LEVEL_COMPONENT_PREFIX = 'com.iwsdk.components.';
178
+ const SCENE_EDITOR_COMPONENT_ALIASES = {
179
+ Interactable: 'RayInteractable',
180
+ };
181
+ const DEFAULT_CAMERA = {
182
+ fov: 50,
183
+ lookAt: [0, 0, 0],
184
+ position: [4, 3, 4],
185
+ projection: 'perspective',
186
+ view: 'quarter',
187
+ };
188
+ const IWSDK_EDITOR_SDK_VERSION = '0.4.2';
189
+ const EDITOR_DOCUMENT_VALIDATION_OPTIONS = {
190
+ validateAuthoringWorkflow: false,
191
+ };
192
+ class SceneEditorSession {
193
+ constructor(options) {
194
+ this.options = options;
195
+ this.pendingReviewCaptures = new Map();
196
+ this.selection = [];
197
+ this.camera = { ...DEFAULT_CAMERA };
198
+ this.reviewLens = 'final';
199
+ this.materializationInProgress = false;
200
+ this.dirty = false;
201
+ this.logs = [];
202
+ this.reviewCaptureSessionNonce = createReviewCaptureSessionNonce();
203
+ this.reviewCaptureSequence = 0;
204
+ const document = structuredClone(options.document);
205
+ this.componentCatalog = options.componentCatalog;
206
+ assertValidSceneDocument(document, EDITOR_DOCUMENT_VALIDATION_OPTIONS);
207
+ this.history = new SceneCommandHistory(document, {
208
+ validationOptions: EDITOR_DOCUMENT_VALIDATION_OPTIONS,
209
+ });
210
+ this.registeredComponentSchemas = mergeComponentSchemas(Object.values(this.componentCatalog ?? {}));
211
+ this.knownComponents = new Set([
212
+ ...this.registeredComponentSchemas.map((schema) => schema.id),
213
+ ...(options.knownComponents ?? []),
214
+ ]);
215
+ this.savedDocumentSnapshot = snapshotSceneDocument(this.history.document);
216
+ this.log('info', 'Scene editor document loaded');
217
+ }
218
+ handles(method) {
219
+ return SCENE_EDITOR_TOOL_METHOD_SET.has(method);
220
+ }
221
+ getPendingReviewCapture(captureTokenValue) {
222
+ const captureToken = getSha256(captureTokenValue, 'captureToken');
223
+ const capture = this.pendingReviewCaptures.get(captureToken);
224
+ if (capture == null) {
225
+ throw new Error('captureToken is unknown or was invalidated by a scene revision');
226
+ }
227
+ const documentHash = hashSceneDocument(this.document);
228
+ const runtimeHash = hashRuntimeSceneDocument(this.document);
229
+ if (capture.documentHash !== documentHash ||
230
+ capture.runtimeHash !== runtimeHash) {
231
+ this.pendingReviewCaptures.delete(captureToken);
232
+ throw new Error('Review capture is stale for the active scene document revision');
233
+ }
234
+ return cloneJson(capture);
235
+ }
236
+ async dispatch(method, params = {}) {
237
+ if (this.materializationInProgress &&
238
+ SCENE_EDITOR_WRITE_METHODS.has(method)) {
239
+ throw new Error(`Cannot run ${method} while a scene materialization is in progress`);
240
+ }
241
+ switch (method) {
242
+ case 'scene_get_capabilities':
243
+ return this.getCapabilities(params);
244
+ case 'scene_list_assets':
245
+ return this.listAssets(params);
246
+ case 'scene_list_component_schemas':
247
+ return this.listComponentSchemas(params);
248
+ case 'scene_get_document':
249
+ return this.getDocumentResult();
250
+ case 'scene_get_hierarchy':
251
+ return this.getHierarchy(params);
252
+ case 'scene_get_selection':
253
+ return this.getSelection();
254
+ case 'scene_select':
255
+ return this.select(params);
256
+ case 'scene_add_node':
257
+ return this.addNode(params);
258
+ case 'scene_remove_node':
259
+ return this.removeNode(params);
260
+ case 'scene_duplicate_node':
261
+ return this.duplicateNode(params);
262
+ case 'scene_set_transform':
263
+ return this.setTransform(params);
264
+ case 'scene_set_framing_role':
265
+ return this.setFramingRole(params);
266
+ case 'scene_apply_patch':
267
+ return this.applyPatchTool(params);
268
+ case 'scene_apply_transaction':
269
+ return this.applyTransaction(params);
270
+ case 'scene_replace_document':
271
+ return this.replaceDocument(params);
272
+ case 'scene_look_at':
273
+ return this.lookAt(params);
274
+ case 'scene_validate':
275
+ return this.validate();
276
+ case 'scene_save':
277
+ return this.save();
278
+ case 'scene_undo':
279
+ return this.undo();
280
+ case 'scene_redo':
281
+ return this.redo();
282
+ case 'scene_get_logs':
283
+ return this.getLogs(params);
284
+ case 'scene_set_camera':
285
+ return this.setCamera(params);
286
+ case 'scene_screenshot':
287
+ return this.screenshot(params);
288
+ case 'scene_compare_screenshots':
289
+ return this.compareScreenshots(params);
290
+ case 'ui_list_assets':
291
+ return this.listUIAssets(params);
292
+ case 'ui_render_preview':
293
+ return this.renderUIPreview(params);
294
+ case 'scene_set_review_lens':
295
+ return this.setReviewLens(params);
296
+ case 'scene_capture_review':
297
+ return this.captureReview(params);
298
+ case 'scene_get_render_stats':
299
+ return this.getRenderStats();
300
+ default:
301
+ throw new Error(`Unsupported scene editor method "${method}"`);
302
+ }
303
+ }
304
+ get document() {
305
+ return this.history.document;
306
+ }
307
+ get isDirty() {
308
+ return this.dirty;
309
+ }
310
+ /**
311
+ * Atomically adopts a validated document read from disk without creating an
312
+ * editor command or marking the document dirty. This is intentionally not an
313
+ * MCP tool: files are the agent authoring API, while the session remains the
314
+ * human editor's local command surface.
315
+ */
316
+ async replaceFromDisk(document) {
317
+ if (this.dirty) {
318
+ throw new Error('The scene has unsaved editor changes and cannot be replaced from disk');
319
+ }
320
+ if (this.materializationInProgress) {
321
+ throw new Error('Another scene materialization is already in progress');
322
+ }
323
+ const candidate = structuredClone(document);
324
+ assertValidSceneDocument(candidate, EDITOR_DOCUMENT_VALIDATION_OPTIONS);
325
+ const previousDocument = this.document;
326
+ this.materializationInProgress = true;
327
+ try {
328
+ await this.options.preloadDocumentResources?.(cloneJson(candidate));
329
+ await this.options.instantiateDocumentPreview?.(cloneJson(candidate));
330
+ await this.options.commitDocument?.(cloneJson(candidate));
331
+ this.history = new SceneCommandHistory(candidate, {
332
+ validationOptions: EDITOR_DOCUMENT_VALIDATION_OPTIONS,
333
+ });
334
+ this.savedDocumentSnapshot = snapshotSceneDocument(candidate);
335
+ this.dirty = false;
336
+ this.pendingReviewCaptures.clear();
337
+ this.pruneSelectionToExistingNodes();
338
+ this.log('info', 'Reloaded scene document from disk');
339
+ return {
340
+ documentHash: hashSceneDocument(candidate),
341
+ runtimeHash: hashRuntimeSceneDocument(candidate),
342
+ };
343
+ }
344
+ catch (error) {
345
+ await this.options.rollbackDocument?.(cloneJson(candidate), cloneJson(previousDocument));
346
+ throw error;
347
+ }
348
+ finally {
349
+ this.materializationInProgress = false;
350
+ }
351
+ }
352
+ get componentSchemas() {
353
+ return this.registeredComponentSchemas;
354
+ }
355
+ buildCapabilities() {
356
+ const componentSchemas = this.registeredComponentSchemas.map((schema) => ({
357
+ ...schema,
358
+ schemaHash: hashSceneComponentSchema(schema),
359
+ }));
360
+ const snapshot = {
361
+ componentSchemaHashes: Object.fromEntries(componentSchemas.map((schema) => [schema.id, schema.schemaHash])),
362
+ limits: {
363
+ maxNodes: MAX_SCENE_NODES,
364
+ maxPatternExpansion: MAX_SCENE_PATTERN_EXPANSION,
365
+ maxResources: MAX_SCENE_RESOURCES,
366
+ },
367
+ nodeContentTypes: ['group', 'asset', 'instance', 'pattern'],
368
+ patternTypes: [
369
+ 'linear',
370
+ 'grid',
371
+ 'radial',
372
+ 'along-path',
373
+ 'scatter',
374
+ 'explicit',
375
+ ],
376
+ sceneVersions: [CURRENT_SCENE_VERSION],
377
+ shadowMapTypes: ['basic', 'pcf', 'pcf-soft'],
378
+ sdkVersion: IWSDK_EDITOR_SDK_VERSION,
379
+ };
380
+ const capabilities = {
381
+ schemaVersions: [CURRENT_SCENE_VERSION],
382
+ reviewVersions: [CURRENT_SCENE_REVIEW_VERSION],
383
+ sceneSchemaHash: sha256(canonicalizeJson(SCENE_DOCUMENT_JSON_SCHEMA)),
384
+ reviewSchemaHash: sha256(canonicalizeJson(SCENE_REVIEW_JSON_SCHEMA)),
385
+ ownershipModes: ['replace-new'],
386
+ assetPolicies: ['manifest-assets'],
387
+ nodeContentKinds: ['group', 'asset', 'instance', 'pattern'],
388
+ resourceKinds: ['prefab'],
389
+ shadowMapKinds: ['basic', 'pcf', 'pcf-soft'],
390
+ patternDistributionKinds: [
391
+ 'linear',
392
+ 'grid',
393
+ 'radial',
394
+ 'along-path',
395
+ 'scatter',
396
+ 'explicit',
397
+ ],
398
+ patternAlgorithms: ['pcg32-box-rejection-v1'],
399
+ patchOperations: [
400
+ 'addNode',
401
+ 'removeNode',
402
+ 'moveNode',
403
+ 'renameNode',
404
+ 'updateTransform',
405
+ 'updateFramingRole',
406
+ 'updateComponent',
407
+ 'updateRootComponent',
408
+ 'updatePlayerComponent',
409
+ 'updatePlayerTransform',
410
+ 'reorderChildren',
411
+ 'updateContent',
412
+ 'updateConstraints',
413
+ 'setNodeMetadata',
414
+ 'setAuthoring',
415
+ 'setEnvironment',
416
+ 'addPrefab',
417
+ 'updatePrefab',
418
+ 'removePrefab',
419
+ 'addAuthoringView',
420
+ 'updateAuthoringView',
421
+ 'removeAuthoringView',
422
+ ],
423
+ registeredComponents: [...this.knownComponents].sort(),
424
+ componentSchemas,
425
+ componentSchemaHash: sha256(canonicalizeJson(componentSchemas)),
426
+ safetyLimits: {
427
+ maxAbsoluteCoordinate: MAX_SCENE_COORDINATE,
428
+ maxNodes: MAX_SCENE_NODES,
429
+ maxPatternExpansion: MAX_SCENE_PATTERN_EXPANSION,
430
+ maxResources: MAX_SCENE_RESOURCES,
431
+ },
432
+ savedViewProjections: ['perspective', 'orthographic'],
433
+ uriSchemes: ['relative', 'http', 'https'],
434
+ };
435
+ return {
436
+ ...capabilities,
437
+ capabilityHash: sha256(canonicalizeJson(snapshot)),
438
+ snapshot,
439
+ };
440
+ }
441
+ getCapabilities(params = {}) {
442
+ const full = getOptionalBoolean(params.full, 'full') ?? false;
443
+ const capabilities = this.buildCapabilities();
444
+ if (full) {
445
+ return {
446
+ ...capabilities,
447
+ detail: 'full',
448
+ };
449
+ }
450
+ const { componentSchemas, ...summary } = capabilities;
451
+ return {
452
+ ...summary,
453
+ componentSchemaCount: componentSchemas.length,
454
+ detail: 'summary',
455
+ fullAvailable: true,
456
+ };
457
+ }
458
+ listAssets(params) {
459
+ const query = getOptionalString(params.query)?.toLowerCase();
460
+ const assets = [...(this.options.listAssets?.() ?? [])];
461
+ return {
462
+ assets: query
463
+ ? assets.filter((asset) => `${asset.id} ${asset.name ?? ''}`.toLowerCase().includes(query))
464
+ : assets,
465
+ };
466
+ }
467
+ listUIAssets(params) {
468
+ const query = getOptionalString(params.query)?.toLowerCase();
469
+ const assets = [...(this.options.listAssets?.() ?? [])].filter((asset) => asset.kind === 'uikitml');
470
+ return {
471
+ assets: query
472
+ ? assets.filter((asset) => `${asset.id} ${asset.name ?? ''}`.toLowerCase().includes(query))
473
+ : assets,
474
+ };
475
+ }
476
+ listComponentSchemas(params) {
477
+ const query = getOptionalString(params.query)?.toLowerCase();
478
+ const schemas = query
479
+ ? this.componentSchemas.filter((schema) => `${schema.id} ${schema.name ?? ''} ${schema.description ?? ''}`
480
+ .toLowerCase()
481
+ .includes(query))
482
+ : this.componentSchemas;
483
+ return {
484
+ componentSchemas: schemas,
485
+ };
486
+ }
487
+ getDocumentResult() {
488
+ const document = this.document;
489
+ return {
490
+ dirty: this.dirty,
491
+ document,
492
+ documentHash: hashSceneDocument(document),
493
+ runtimeHash: hashRuntimeSceneDocument(document),
494
+ };
495
+ }
496
+ getHierarchy(params) {
497
+ const parentId = getOptionalString(params.parentId);
498
+ const maxDepth = getOptionalNumber(params.maxDepth) ?? 5;
499
+ const nodes = parentId == null
500
+ ? this.document.nodes
501
+ : (findRequiredNodeLocation(this.document.nodes, parentId).node
502
+ .children ?? []);
503
+ return {
504
+ hierarchy: nodes.map((node) => serializeNodeHierarchy(node, maxDepth)),
505
+ };
506
+ }
507
+ getSelection() {
508
+ return {
509
+ nodeIds: [...this.selection],
510
+ };
511
+ }
512
+ select(params) {
513
+ const nodeIds = getStringArray(params.nodeIds, 'nodeIds');
514
+ for (const nodeId of nodeIds) {
515
+ findRequiredNodeLocation(this.document.nodes, nodeId);
516
+ }
517
+ this.selection = [...nodeIds];
518
+ this.log('info', `Selected ${nodeIds.length} node(s)`);
519
+ return this.getSelection();
520
+ }
521
+ addNode(params) {
522
+ const node = getRecord(params.node, 'node');
523
+ const patch = {
524
+ index: getOptionalNumber(params.index),
525
+ node,
526
+ op: 'addNode',
527
+ parentId: getOptionalString(params.parentId) ?? null,
528
+ };
529
+ this.applyPatch(patch);
530
+ this.selection = [node.id];
531
+ return this.mutationResult('nodeAdded', { nodeId: node.id });
532
+ }
533
+ removeNode(params) {
534
+ const nodeId = getRequiredString(params.nodeId, 'nodeId');
535
+ const removedIds = collectSubtreeIds(findRequiredNodeLocation(this.document.nodes, nodeId).node);
536
+ this.applyPatch({ nodeId, op: 'removeNode' });
537
+ this.selection = this.selection.filter((selectedId) => !removedIds.has(selectedId));
538
+ return this.mutationResult('nodeRemoved', { nodeId });
539
+ }
540
+ duplicateNode(params) {
541
+ const nodeId = getRequiredString(params.nodeId, 'nodeId');
542
+ const location = findRequiredNodeLocation(this.document.nodes, nodeId);
543
+ const newNodeId = getOptionalString(params.newNodeId) ??
544
+ createCopyId(this.document, nodeId);
545
+ const duplicate = cloneNodeWithNewIds(location.node, nodeId, newNodeId);
546
+ const parentId = getOptionalString(params.parentId) ?? location.parent?.id ?? null;
547
+ const index = parentId === (location.parent?.id ?? null)
548
+ ? location.index + 1
549
+ : undefined;
550
+ this.applyPatch({
551
+ index,
552
+ node: duplicate,
553
+ op: 'addNode',
554
+ parentId,
555
+ });
556
+ this.selection = [duplicate.id];
557
+ return this.mutationResult('nodeDuplicated', {
558
+ nodeId,
559
+ newNodeId: duplicate.id,
560
+ });
561
+ }
562
+ setTransform(params) {
563
+ const nodeId = getRequiredString(params.nodeId, 'nodeId');
564
+ const transform = getRecord(params.transform, 'transform');
565
+ this.applyPatch({ nodeId, op: 'updateTransform', transform });
566
+ return this.mutationResult('transformUpdated', { nodeId, transform });
567
+ }
568
+ setFramingRole(params) {
569
+ const nodeId = getRequiredString(params.nodeId, 'nodeId');
570
+ const framingRole = getFramingRole(params.framingRole);
571
+ this.applyPatch({ framingRole, nodeId, op: 'updateFramingRole' });
572
+ return this.mutationResult('framingRoleUpdated', {
573
+ framingRole,
574
+ nodeId,
575
+ });
576
+ }
577
+ applyPatchTool(params) {
578
+ const patch = getRecord(params.patch, 'patch');
579
+ if (patch.op === 'replaceDocument' || patch.op === 'transaction') {
580
+ throw new Error(`Use scene_${patch.op === 'replaceDocument' ? 'replace_document' : 'apply_transaction'} so document hashes and preflight are enforced`);
581
+ }
582
+ this.applyPatch(patch);
583
+ if (patch.op === 'updateComponent' ||
584
+ patch.op === 'updateRootComponent' ||
585
+ patch.op === 'updatePlayerComponent' ||
586
+ patch.op === 'updatePlayerTransform') {
587
+ const validation = this.validate(this.document, {
588
+ validateComponentLinks: false,
589
+ });
590
+ if (!validation.valid) {
591
+ this.history.undo();
592
+ this.updateDirtyState();
593
+ throw Object.assign(new Error(`Cannot apply invalid component update: ${summarizeValidationIssues(validation.issues)}`), { issues: validation.issues, lifecycle: validation.lifecycle });
594
+ }
595
+ }
596
+ if (patch.op === 'renameNode') {
597
+ this.selection = this.selection.map((nodeId) => nodeId === patch.nodeId ? patch.newNodeId : nodeId);
598
+ }
599
+ return this.mutationResult('patchApplied', { patch });
600
+ }
601
+ async applyTransaction(params) {
602
+ const ownershipMode = getOwnershipMode(params.ownershipMode);
603
+ const baseDocument = this.document;
604
+ const baseDocumentHash = hashSceneDocument(baseDocument);
605
+ assertExpectedBaseDocumentHash(params, baseDocument, baseDocumentHash);
606
+ const patchValues = params.patches;
607
+ if (!Array.isArray(patchValues) || patchValues.length === 0) {
608
+ throw new Error('patches must be a non-empty array');
609
+ }
610
+ const patches = patchValues.map((value, index) => {
611
+ const patch = getRecord(value, `patches[${index}]`);
612
+ if (patch.op === 'replaceDocument' || patch.op === 'transaction') {
613
+ throw new Error(`patches[${index}] cannot contain the control operation "${patch.op}"`);
614
+ }
615
+ return patch;
616
+ });
617
+ const transaction = { op: 'transaction', patches };
618
+ const candidate = applyScenePatch(baseDocument, transaction).document;
619
+ const candidateDocumentHash = assertCandidateDocumentHash(params.candidateDocumentHash, candidate);
620
+ const lifecycle = await this.commitStagedDocument(candidate, transaction, baseDocumentHash, {
621
+ correction: params.correction,
622
+ operation: 'transaction',
623
+ });
624
+ this.updateSelectionForPatches(patches);
625
+ return this.mutationResult('transactionApplied', {
626
+ baseDocumentHash,
627
+ candidateDocumentHash,
628
+ ownershipMode,
629
+ patchCount: patches.length,
630
+ runtimeHash: hashRuntimeSceneDocument(candidate),
631
+ lifecycle,
632
+ });
633
+ }
634
+ async replaceDocument(params) {
635
+ const ownershipMode = getOwnershipMode(params.ownershipMode);
636
+ const baseDocument = this.document;
637
+ const baseDocumentHash = hashSceneDocument(baseDocument);
638
+ assertExpectedBaseDocumentHash(params, baseDocument, baseDocumentHash);
639
+ const rawDocument = getRecord(params.document, 'document');
640
+ if (rawDocument.version !== CURRENT_SCENE_VERSION) {
641
+ throw new Error(`scene_replace_document requires ${CURRENT_SCENE_VERSION}`);
642
+ }
643
+ const candidate = cloneJson(rawDocument);
644
+ const candidateDocumentHash = assertCandidateDocumentHash(params.candidateDocumentHash, candidate);
645
+ const replacement = {
646
+ document: candidate,
647
+ op: 'replaceDocument',
648
+ };
649
+ const lifecycle = await this.commitStagedDocument(candidate, replacement, baseDocumentHash, { operation: 'replace-document' });
650
+ this.pruneSelectionToExistingNodes();
651
+ return this.mutationResult('documentReplaced', {
652
+ baseDocumentHash,
653
+ candidateDocumentHash,
654
+ ownershipMode,
655
+ runtimeHash: hashRuntimeSceneDocument(candidate),
656
+ lifecycle,
657
+ });
658
+ }
659
+ async commitStagedDocument(candidate, patch, expectedLiveHash, transition) {
660
+ const validation = this.validate(candidate);
661
+ if (!validation.valid) {
662
+ const issueSummary = summarizeValidationIssues(validation.issues);
663
+ throw Object.assign(new Error(`Cannot commit invalid scene: ${issueSummary}`), { issues: validation.issues, lifecycle: validation.lifecycle });
664
+ }
665
+ if (this.materializationInProgress) {
666
+ throw new Error('Another scene materialization is already in progress');
667
+ }
668
+ this.materializationInProgress = true;
669
+ const previousDocument = this.document;
670
+ const lifecycle = { ...validation.lifecycle };
671
+ let editorAttempted = false;
672
+ let transitionAuthorized = false;
673
+ try {
674
+ if (this.options.preloadDocumentResources != null) {
675
+ try {
676
+ await this.options.preloadDocumentResources(cloneJson(candidate));
677
+ lifecycle.resourcesReady = 'passed';
678
+ }
679
+ catch (error) {
680
+ lifecycle.resourcesReady = 'failed';
681
+ throw error;
682
+ }
683
+ }
684
+ if (this.options.instantiateDocumentPreview != null) {
685
+ editorAttempted = true;
686
+ try {
687
+ await this.options.instantiateDocumentPreview(cloneJson(candidate));
688
+ }
689
+ catch (error) {
690
+ lifecycle.editorCommitted = 'failed';
691
+ throw error;
692
+ }
693
+ }
694
+ if (this.options.authorizeDocumentTransition != null) {
695
+ await this.options.authorizeDocumentTransition({
696
+ candidate: cloneJson(candidate),
697
+ correction: transition.correction,
698
+ expectedBaseDocumentHash: expectedLiveHash,
699
+ operation: transition.operation,
700
+ patch: cloneJson(patch),
701
+ previousDocument: cloneJson(previousDocument),
702
+ });
703
+ transitionAuthorized = true;
704
+ }
705
+ assertLiveDocumentHash(this.document, expectedLiveHash);
706
+ if (this.options.commitDocument != null) {
707
+ editorAttempted = true;
708
+ try {
709
+ await this.options.commitDocument(cloneJson(candidate));
710
+ }
711
+ catch (error) {
712
+ lifecycle.editorCommitted = 'failed';
713
+ throw error;
714
+ }
715
+ }
716
+ assertLiveDocumentHash(this.document, expectedLiveHash);
717
+ this.history.replace(candidate);
718
+ if (this.options.commitDocument != null) {
719
+ lifecycle.editorCommitted = 'passed';
720
+ }
721
+ this.updateDirtyState();
722
+ this.log('info', `Committed staged scene patch ${patch.op}`);
723
+ return lifecycle;
724
+ }
725
+ catch (error) {
726
+ if (editorAttempted && lifecycle.editorCommitted !== 'passed') {
727
+ lifecycle.editorCommitted = 'failed';
728
+ }
729
+ if (transitionAuthorized) {
730
+ try {
731
+ await this.options.discardDocumentTransition?.();
732
+ }
733
+ catch (discardError) {
734
+ this.log('error', `Scene transition discard failed: ${errorMessage(discardError)}`);
735
+ }
736
+ }
737
+ try {
738
+ await this.options.rollbackDocument?.(cloneJson(candidate), cloneJson(previousDocument));
739
+ }
740
+ catch (rollbackError) {
741
+ this.log('error', `Scene materialization rollback failed: ${errorMessage(rollbackError)}`);
742
+ }
743
+ throw attachLifecycleReport(error, lifecycle);
744
+ }
745
+ finally {
746
+ this.materializationInProgress = false;
747
+ }
748
+ }
749
+ updateSelectionForPatches(patches) {
750
+ for (const patch of patches) {
751
+ if (patch.op === 'renameNode') {
752
+ this.selection = this.selection.map((nodeId) => nodeId === patch.nodeId ? patch.newNodeId : nodeId);
753
+ }
754
+ }
755
+ this.pruneSelectionToExistingNodes();
756
+ }
757
+ lookAt(params) {
758
+ const nodeId = getRequiredString(params.nodeId, 'nodeId');
759
+ const target = getVec3(params.target, 'target');
760
+ const transform = resolveLookAtTransformInDocument(this.document, nodeId, target);
761
+ this.applyPatch({ nodeId, op: 'updateTransform', transform });
762
+ return this.mutationResult('nodeOriented', { nodeId, target, transform });
763
+ }
764
+ validate(document = this.document, options = {}) {
765
+ const validationOptions = {
766
+ ...(this.componentCatalog == null
767
+ ? {}
768
+ : { componentCatalog: this.componentCatalog }),
769
+ ...(this.options.listAssets == null
770
+ ? {}
771
+ : {
772
+ knownAssetIds: this.options.listAssets().map((asset) => asset.id),
773
+ }),
774
+ validateAuthoringWorkflow: false,
775
+ validateComponentLinks: options.validateComponentLinks !== false,
776
+ };
777
+ const base = validateSceneDocument(document, validationOptions);
778
+ const schemaIssues = [
779
+ ...enrichBaseValidationIssues(document, base.issues),
780
+ ];
781
+ const capabilitySnapshot = this.buildCapabilities().snapshot;
782
+ const capabilityIssues = base.valid
783
+ ? [
784
+ ...validateSceneCapabilities(document, capabilitySnapshot, validationOptions).issues,
785
+ ...(this.componentCatalog == null
786
+ ? validateComponentTypes(document, this.knownComponents)
787
+ : []),
788
+ ]
789
+ : [];
790
+ const issues = [
791
+ ...schemaIssues,
792
+ ...capabilityIssues,
793
+ ];
794
+ const lifecycle = {
795
+ schemaValid: schemaIssues.length === 0 ? 'passed' : 'failed',
796
+ capabilityCompatible: base.valid
797
+ ? capabilityIssues.length === 0
798
+ ? 'passed'
799
+ : 'failed'
800
+ : 'not-run',
801
+ resourcesReady: 'not-run',
802
+ editorCommitted: 'not-run',
803
+ runtimeProven: 'not-run',
804
+ };
805
+ return {
806
+ valid: issues.length === 0,
807
+ issues,
808
+ lifecycle,
809
+ };
810
+ }
811
+ async save() {
812
+ if (this.options.saveDocument == null) {
813
+ throw new Error('Scene editor was not configured with a save handler');
814
+ }
815
+ const validation = this.validate();
816
+ if (!validation.valid) {
817
+ const issueSummary = summarizeValidationIssues(validation.issues);
818
+ this.log('error', `Scene save blocked: ${issueSummary}`);
819
+ throw Object.assign(new Error(`Cannot save invalid scene: ${issueSummary}`), {
820
+ issues: validation.issues,
821
+ });
822
+ }
823
+ const document = this.document;
824
+ const serialized = serializeSceneDocument(document);
825
+ const result = await this.options.saveDocument(serialized, document);
826
+ this.savedDocumentSnapshot = serialized;
827
+ this.updateDirtyState();
828
+ this.log('info', 'Scene editor document saved');
829
+ return {
830
+ ...result,
831
+ dirty: this.dirty,
832
+ documentHash: hashSceneDocument(document),
833
+ lifecycle: validation.lifecycle,
834
+ runtimeHash: hashRuntimeSceneDocument(document),
835
+ };
836
+ }
837
+ undo() {
838
+ this.history.undo();
839
+ this.pruneSelectionToExistingNodes();
840
+ this.updateDirtyState();
841
+ this.log('info', 'Undo applied');
842
+ return this.mutationResult('undone');
843
+ }
844
+ redo() {
845
+ this.history.redo();
846
+ this.pruneSelectionToExistingNodes();
847
+ this.updateDirtyState();
848
+ this.log('info', 'Redo applied');
849
+ return this.mutationResult('redone');
850
+ }
851
+ getLogs(params) {
852
+ const level = getOptionalLogLevel(params.level);
853
+ const count = getOptionalNumber(params.count);
854
+ const filtered = level == null
855
+ ? this.logs
856
+ : this.logs.filter((entry) => entry.level === level);
857
+ return {
858
+ logs: count != null && count > 0 ? filtered.slice(-count) : filtered,
859
+ };
860
+ }
861
+ setCamera(params) {
862
+ this.camera = resolveCamera(params, this.camera, this.document.authoring?.views);
863
+ this.log('info', `Camera set to ${this.camera.view}`);
864
+ return {
865
+ camera: this.camera,
866
+ };
867
+ }
868
+ async screenshot(params) {
869
+ this.camera = resolveCamera(params, this.camera, this.document.authoring?.views);
870
+ return this.captureScreenshot(this.camera, {
871
+ captureMode: getCaptureMode(params.captureMode),
872
+ height: getOptionalNumber(params.height),
873
+ width: getOptionalNumber(params.width),
874
+ });
875
+ }
876
+ async renderUIPreview(params) {
877
+ if (this.options.renderUIPreview == null) {
878
+ throw new Error('The editor runtime cannot render UIKitML previews');
879
+ }
880
+ return this.options.renderUIPreview(getRequiredString(params.assetId, 'assetId'), {
881
+ background: getOptionalString(params.background),
882
+ height: getOptionalNumber(params.height),
883
+ width: getOptionalNumber(params.width),
884
+ });
885
+ }
886
+ async compareScreenshots(params) {
887
+ const firstParams = getRecord(params.first, 'first');
888
+ const secondParams = getRecord(params.second, 'second');
889
+ const size = {
890
+ height: getOptionalNumber(params.height),
891
+ width: getOptionalNumber(params.width),
892
+ };
893
+ const firstCamera = resolveCamera(firstParams, this.camera, this.document.authoring?.views);
894
+ const secondCamera = resolveCamera(secondParams, firstCamera, this.document.authoring?.views);
895
+ const first = await this.captureScreenshot(firstCamera, {
896
+ ...size,
897
+ captureMode: getCaptureMode(firstParams.captureMode),
898
+ });
899
+ const second = await this.captureScreenshot(secondCamera, {
900
+ ...size,
901
+ captureMode: getCaptureMode(secondParams.captureMode),
902
+ });
903
+ this.camera = secondCamera;
904
+ return {
905
+ first,
906
+ firstImageDataLength: first.imageData.length,
907
+ matches: first.mimeType === second.mimeType &&
908
+ first.imageData === second.imageData,
909
+ second,
910
+ secondImageDataLength: second.imageData.length,
911
+ };
912
+ }
913
+ async setReviewLens(params) {
914
+ const lens = getReviewLens(params.lens);
915
+ await this.options.setReviewLens?.(lens);
916
+ this.reviewLens = lens;
917
+ this.log('info', `Review lens set to ${lens}`);
918
+ return {
919
+ lens,
920
+ documentHash: hashSceneDocument(this.document),
921
+ runtimeHash: hashRuntimeSceneDocument(this.document),
922
+ };
923
+ }
924
+ async captureReview(params) {
925
+ const includeImageData = getOptionalBoolean(params.includeImageData, 'includeImageData') ?? false;
926
+ if (this.reviewLens === 'layout') {
927
+ const layoutVisibilityIssues = this.validate().issues.filter((issue) => issue.code === 'review-visibility');
928
+ if (layoutVisibilityIssues.length > 0) {
929
+ const issueSummary = summarizeValidationIssues(layoutVisibilityIssues);
930
+ throw Object.assign(new Error(`Cannot capture layout review: ${issueSummary}`), { issues: layoutVisibilityIssues });
931
+ }
932
+ }
933
+ const width = getRequiredPositiveInteger(params.width, 'width');
934
+ const height = getRequiredPositiveInteger(params.height, 'height');
935
+ const camera = resolveCamera(params, this.camera, this.document.authoring?.views);
936
+ const documentHash = hashSceneDocument(this.document);
937
+ const runtimeHash = hashRuntimeSceneDocument(this.document);
938
+ const capabilities = this.buildCapabilities();
939
+ const screenshot = await this.captureScreenshot(camera, {
940
+ captureMode: 'render',
941
+ height,
942
+ width,
943
+ });
944
+ const renderStats = screenshot.renderStats == null
945
+ ? await this.getRenderStats()
946
+ : cloneRenderStatsSnapshot(screenshot.renderStats);
947
+ const currentDocumentHash = hashSceneDocument(this.document);
948
+ const currentRuntimeHash = hashRuntimeSceneDocument(this.document);
949
+ const currentCapabilityHash = this.buildCapabilities().capabilityHash;
950
+ if (currentDocumentHash !== documentHash ||
951
+ currentRuntimeHash !== runtimeHash ||
952
+ currentCapabilityHash !== capabilities.capabilityHash) {
953
+ throw new Error('Scene document or capabilities changed while review capture was in progress; retry the capture');
954
+ }
955
+ const featureState = params.featureState == null
956
+ ? {}
957
+ : getRecord(params.featureState, 'featureState');
958
+ const screenshotSha256 = screenshot.screenshotSha256 == null
959
+ ? null
960
+ : getSha256(screenshot.screenshotSha256, 'screenshotSha256');
961
+ this.camera = camera;
962
+ let captureToken = sha256(canonicalizeJson({
963
+ capabilityHash: capabilities.capabilityHash,
964
+ documentHash,
965
+ runtimeHash,
966
+ sessionNonce: this.reviewCaptureSessionNonce,
967
+ screenshotSha256,
968
+ sequence: ++this.reviewCaptureSequence,
969
+ }));
970
+ const capture = {
971
+ capabilityHash: capabilities.capabilityHash,
972
+ camera: screenshot.camera,
973
+ captureToken,
974
+ documentHash,
975
+ featureState,
976
+ height: screenshot.height ?? height,
977
+ imageData: screenshot.imageData,
978
+ lens: this.reviewLens,
979
+ logs: [...this.logs],
980
+ mimeType: screenshot.mimeType,
981
+ renderStats,
982
+ rendererEnvironment: screenshot.rendererEnvironment ??
983
+ (renderStats.available ? renderStats.environment : null),
984
+ reviewCamera: cameraAsReviewCamera(screenshot.camera),
985
+ runtimeHash,
986
+ screenshotHashAvailable: screenshotSha256 != null,
987
+ screenshotSha256,
988
+ visibilityAvailable: screenshot.visibleNodeIds != null,
989
+ visibleNodeIds: screenshot.visibleNodeIds ?? null,
990
+ nodeMaskRegions: screenshot.nodeMaskRegions ?? null,
991
+ width: screenshot.width ?? width,
992
+ };
993
+ if (this.options.registerReviewCapture != null) {
994
+ const registration = await this.options.registerReviewCapture(cloneJson(capture));
995
+ captureToken = getSha256(registration.captureToken, 'registered captureToken');
996
+ capture.captureToken = captureToken;
997
+ }
998
+ this.pendingReviewCaptures.set(captureToken, cloneJson(capture));
999
+ if (includeImageData) {
1000
+ return capture;
1001
+ }
1002
+ const { imageData: _imageData, ...metadata } = capture;
1003
+ return metadata;
1004
+ }
1005
+ async getRenderStats() {
1006
+ if (this.options.renderStats == null) {
1007
+ return {
1008
+ available: false,
1009
+ reason: 'The editor runtime has not registered a renderer statistics bridge.',
1010
+ };
1011
+ }
1012
+ const stats = await this.options.renderStats();
1013
+ assertRenderStats(stats);
1014
+ return cloneJson(stats);
1015
+ }
1016
+ async captureScreenshot(camera, options) {
1017
+ if (this.options.screenshot == null) {
1018
+ throw new Error('Scene editor was not configured with a screenshot handler');
1019
+ }
1020
+ return this.options.screenshot(camera, options);
1021
+ }
1022
+ applyPatch(patch) {
1023
+ this.history.apply(patch);
1024
+ this.updateDirtyState();
1025
+ this.log('info', `Applied scene patch ${patch.op}`);
1026
+ }
1027
+ updateDirtyState() {
1028
+ const documentHash = hashSceneDocument(this.document);
1029
+ const runtimeHash = hashRuntimeSceneDocument(this.document);
1030
+ for (const [captureToken, capture] of this.pendingReviewCaptures) {
1031
+ if (capture.documentHash !== documentHash ||
1032
+ capture.runtimeHash !== runtimeHash) {
1033
+ this.pendingReviewCaptures.delete(captureToken);
1034
+ }
1035
+ }
1036
+ this.dirty =
1037
+ snapshotSceneDocument(this.document) !== this.savedDocumentSnapshot;
1038
+ }
1039
+ pruneSelectionToExistingNodes() {
1040
+ const ids = new Set();
1041
+ visitNodes(this.document.nodes, (node) => ids.add(node.id));
1042
+ this.selection = this.selection.filter((nodeId) => ids.has(nodeId));
1043
+ }
1044
+ mutationResult(action, extra = {}) {
1045
+ const validation = this.validate();
1046
+ const document = this.document;
1047
+ return {
1048
+ action,
1049
+ dirty: this.dirty,
1050
+ documentHash: hashSceneDocument(document),
1051
+ runtimeHash: hashRuntimeSceneDocument(document),
1052
+ selection: [...this.selection],
1053
+ valid: validation.valid,
1054
+ issues: validation.issues,
1055
+ lifecycle: validation.lifecycle,
1056
+ ...extra,
1057
+ };
1058
+ }
1059
+ log(level, message) {
1060
+ this.logs.push({ level, message, timestamp: Date.now() });
1061
+ if (this.logs.length > 200) {
1062
+ this.logs.shift();
1063
+ }
1064
+ }
1065
+ }
1066
+ function serializeNodeHierarchy(node, maxDepth) {
1067
+ const children = node.children ?? [];
1068
+ const content = node.content;
1069
+ return {
1070
+ id: node.id,
1071
+ name: node.name,
1072
+ contentType: content?.type,
1073
+ ...(content?.type === 'asset' ? { asset: content.asset } : {}),
1074
+ ...(content?.type === 'instance' || content?.type === 'pattern'
1075
+ ? { prefab: content.prefab }
1076
+ : {}),
1077
+ childCount: children.length,
1078
+ ...(maxDepth > 0
1079
+ ? {
1080
+ children: children.map((child) => serializeNodeHierarchy(child, maxDepth - 1)),
1081
+ }
1082
+ : {}),
1083
+ };
1084
+ }
1085
+ function attachLifecycleReport(value, lifecycle) {
1086
+ const error = value instanceof Error ? value : new Error(String(value));
1087
+ return Object.assign(error, { lifecycle: { ...lifecycle } });
1088
+ }
1089
+ function cameraAsReviewCamera(camera) {
1090
+ const shared = {
1091
+ position: [...camera.position],
1092
+ projection: camera.projection,
1093
+ target: [...camera.lookAt],
1094
+ };
1095
+ if (camera.projection === 'orthographic') {
1096
+ return {
1097
+ ...shared,
1098
+ height: camera.height ?? 10,
1099
+ projection: 'orthographic',
1100
+ };
1101
+ }
1102
+ return {
1103
+ ...shared,
1104
+ fov: camera.fov,
1105
+ projection: 'perspective',
1106
+ };
1107
+ }
1108
+ function resolveCamera(params, current, savedViews) {
1109
+ const viewId = getOptionalString(params.viewId);
1110
+ if (viewId != null) {
1111
+ const savedView = savedViews?.find((view) => view.id === viewId);
1112
+ if (savedView == null) {
1113
+ throw new Error(`Saved authoring view "${viewId}" does not exist`);
1114
+ }
1115
+ return savedAuthoringViewCamera(savedView, current.fov);
1116
+ }
1117
+ const explicitPosition = params.position == null ? undefined : getVec3(params.position, 'position');
1118
+ const explicitLookAt = params.lookAt == null ? undefined : getVec3(params.lookAt, 'lookAt');
1119
+ const fov = getOptionalNumber(params.fov) ?? current.fov;
1120
+ const projection = getCameraProjection(params.projection) ?? current.projection;
1121
+ const orthographicHeight = getOptionalNumber(params.orthographicHeight);
1122
+ if (orthographicHeight != null && orthographicHeight <= 0) {
1123
+ throw new Error('orthographicHeight must be greater than 0');
1124
+ }
1125
+ if (explicitPosition != null ||
1126
+ explicitLookAt != null ||
1127
+ params.projection != null ||
1128
+ orthographicHeight != null) {
1129
+ return cameraWithProjection({
1130
+ fov,
1131
+ lookAt: explicitLookAt ?? current.lookAt,
1132
+ position: explicitPosition ?? current.position,
1133
+ projection,
1134
+ view: 'custom',
1135
+ }, projection, orthographicHeight ?? current.height);
1136
+ }
1137
+ const view = getOptionalString(params.view);
1138
+ if (view == null) {
1139
+ return { ...current, fov };
1140
+ }
1141
+ if (!isCameraView(view)) {
1142
+ throw new Error('view must be one of current, top, front, back, left, right, quarter, orbit');
1143
+ }
1144
+ if (view === 'current') {
1145
+ return { ...current, fov };
1146
+ }
1147
+ if (view === 'orbit') {
1148
+ return {
1149
+ ...cameraForOrbitStep(getOrbitStep(params)),
1150
+ fov,
1151
+ };
1152
+ }
1153
+ return {
1154
+ ...cameraForView(view),
1155
+ fov,
1156
+ };
1157
+ }
1158
+ function isCameraView(value) {
1159
+ return (value === 'current' ||
1160
+ value === 'top' ||
1161
+ value === 'front' ||
1162
+ value === 'back' ||
1163
+ value === 'left' ||
1164
+ value === 'right' ||
1165
+ value === 'quarter' ||
1166
+ value === 'orbit');
1167
+ }
1168
+ function cameraForView(view) {
1169
+ switch (view) {
1170
+ case 'top':
1171
+ return {
1172
+ fov: 50,
1173
+ lookAt: [0, 0, 0],
1174
+ position: [0, 8, 0],
1175
+ projection: 'perspective',
1176
+ view,
1177
+ };
1178
+ case 'front':
1179
+ return {
1180
+ fov: 50,
1181
+ lookAt: [0, 0, 0],
1182
+ position: [0, 2, 8],
1183
+ projection: 'perspective',
1184
+ view,
1185
+ };
1186
+ case 'back':
1187
+ return {
1188
+ fov: 50,
1189
+ lookAt: [0, 0, 0],
1190
+ position: [0, 2, -8],
1191
+ projection: 'perspective',
1192
+ view,
1193
+ };
1194
+ case 'left':
1195
+ return {
1196
+ fov: 50,
1197
+ lookAt: [0, 0, 0],
1198
+ position: [-8, 2, 0],
1199
+ projection: 'perspective',
1200
+ view,
1201
+ };
1202
+ case 'right':
1203
+ return {
1204
+ fov: 50,
1205
+ lookAt: [0, 0, 0],
1206
+ position: [8, 2, 0],
1207
+ projection: 'perspective',
1208
+ view,
1209
+ };
1210
+ case 'quarter':
1211
+ return {
1212
+ fov: 50,
1213
+ lookAt: [0, 0, 0],
1214
+ position: [4, 3, 4],
1215
+ projection: 'perspective',
1216
+ view,
1217
+ };
1218
+ case 'orbit':
1219
+ return cameraForOrbitStep(0);
1220
+ }
1221
+ }
1222
+ function getOrbitStep(params) {
1223
+ const explicitStep = getOptionalNumber(params.orbitStep) ?? getOptionalNumber(params.step);
1224
+ if (explicitStep == null) {
1225
+ return 0;
1226
+ }
1227
+ return Math.trunc(explicitStep);
1228
+ }
1229
+ function cameraForOrbitStep(step) {
1230
+ const angle = ((((step % 8) + 8) % 8) * Math.PI) / 4;
1231
+ const radius = 5.66;
1232
+ return {
1233
+ fov: 50,
1234
+ lookAt: [0, 0, 0],
1235
+ position: [
1236
+ roundCameraNumber(Math.cos(angle) * radius),
1237
+ 3,
1238
+ roundCameraNumber(Math.sin(angle) * radius),
1239
+ ],
1240
+ projection: 'perspective',
1241
+ view: 'orbit',
1242
+ };
1243
+ }
1244
+ function savedAuthoringViewCamera(view, fallbackFov) {
1245
+ const base = {
1246
+ fov: view.projection === 'perspective' ? view.fov : fallbackFov,
1247
+ lookAt: [...view.target],
1248
+ position: [...view.position],
1249
+ projection: view.projection,
1250
+ view: 'custom',
1251
+ viewId: view.id,
1252
+ };
1253
+ return view.projection === 'orthographic'
1254
+ ? { ...base, height: view.height }
1255
+ : base;
1256
+ }
1257
+ function cameraWithProjection(camera, projection, height) {
1258
+ if (projection === 'orthographic') {
1259
+ return { ...camera, height: height ?? 10, projection };
1260
+ }
1261
+ const { height: _height, viewId: _viewId, ...perspective } = camera;
1262
+ return { ...perspective, projection };
1263
+ }
1264
+ function getCameraProjection(value) {
1265
+ const projection = getOptionalString(value);
1266
+ if (projection == null) {
1267
+ return undefined;
1268
+ }
1269
+ if (projection !== 'perspective' && projection !== 'orthographic') {
1270
+ throw new Error('projection must be perspective or orthographic');
1271
+ }
1272
+ return projection;
1273
+ }
1274
+ function roundCameraNumber(value) {
1275
+ return Number(value.toFixed(4));
1276
+ }
1277
+ function enrichBaseValidationIssues(document, issues) {
1278
+ const nodePathToId = collectNodePathIds(document);
1279
+ return issues.map((issue) => {
1280
+ const annotationMatch = /^\$\.authoring\.nodeAnnotations\[(\d+)\]/.exec(issue.path);
1281
+ const annotationNodeId = annotationMatch == null
1282
+ ? undefined
1283
+ : document.authoring?.nodeAnnotations?.[Number(annotationMatch[1])]
1284
+ ?.node;
1285
+ return {
1286
+ ...issue,
1287
+ ...nodeMetadataForPath(nodePathToId, issue.path),
1288
+ ...(annotationNodeId == null ? {} : { nodeId: annotationNodeId }),
1289
+ suggestedFix: suggestFixForIssue(issue),
1290
+ };
1291
+ });
1292
+ }
1293
+ function validateComponentTypes(document, knownComponents) {
1294
+ const issues = [];
1295
+ const validateOwner = (components, path, owner, nodeId) => {
1296
+ for (const componentName of Object.keys(components ?? {})) {
1297
+ const componentId = normalizeComponentId(stripComponentPrefix(componentName));
1298
+ if (!knownComponents.has(componentId)) {
1299
+ issues.push({
1300
+ message: `${owner} references unknown component "${componentName}"`,
1301
+ ...(nodeId == null ? {} : { nodeId }),
1302
+ path: `${path}[${JSON.stringify(componentName)}]`,
1303
+ suggestedFix: `Register "${componentId}" as an app-specific component for the editor session or remove/rename the component payload.`,
1304
+ });
1305
+ }
1306
+ }
1307
+ };
1308
+ validateOwner(document.components, '$.components', 'scene root');
1309
+ visitNodes(document.nodes, (node, path) => {
1310
+ if (node.components == null || hasAllowUnknownComponentsFlag(node)) {
1311
+ return;
1312
+ }
1313
+ validateOwner(node.components, `${path}.components`, `node "${node.id}"`, node.id);
1314
+ });
1315
+ return issues;
1316
+ }
1317
+ function isPlainEditorRecord(value) {
1318
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1319
+ }
1320
+ function errorMessage(value) {
1321
+ return value instanceof Error ? value.message : String(value);
1322
+ }
1323
+ function mergeComponentSchemas(schemas) {
1324
+ const merged = new Map();
1325
+ for (const schema of schemas) {
1326
+ merged.set(schema.id, schema);
1327
+ }
1328
+ return [...merged.values()].sort((first, second) => first.id.localeCompare(second.id));
1329
+ }
1330
+ function summarizeValidationIssues(issues) {
1331
+ if (issues.length === 0) {
1332
+ return 'no validation issues';
1333
+ }
1334
+ const [first] = issues;
1335
+ const location = first.nodeId ? ` on node "${first.nodeId}"` : '';
1336
+ const remaining = issues.length > 1 ? ` (+${issues.length - 1} more)` : '';
1337
+ return `${first.message}${location}${remaining}`;
1338
+ }
1339
+ function collectNodePathIds(document) {
1340
+ const nodePathToId = new Map();
1341
+ visitNodes(document.nodes, (node, path) => {
1342
+ nodePathToId.set(path, node.id);
1343
+ });
1344
+ return nodePathToId;
1345
+ }
1346
+ function nodeMetadataForPath(nodePathToId, issuePath) {
1347
+ let matchedPath = '';
1348
+ let nodeId;
1349
+ for (const [path, id] of nodePathToId) {
1350
+ if (issuePath === path ||
1351
+ issuePath.startsWith(`${path}.`) ||
1352
+ issuePath.startsWith(`${path}[`)) {
1353
+ if (path.length > matchedPath.length) {
1354
+ matchedPath = path;
1355
+ nodeId = id;
1356
+ }
1357
+ }
1358
+ }
1359
+ return nodeId == null ? {} : { nodeId };
1360
+ }
1361
+ function suggestFixForIssue(issue) {
1362
+ if (issue.code === 'review-visibility') {
1363
+ return 'Add a manifest asset that resolves to the layout layer, or move the layout annotation to a subtree with visible renderable content.';
1364
+ }
1365
+ if (issue.path.endsWith('.content.asset') && issue.code === 'reference') {
1366
+ return 'Call scene_list_assets, then update the node to a registered manifest asset id.';
1367
+ }
1368
+ if (issue.message.includes('duplicate node id')) {
1369
+ return 'Rename one duplicate node id or remove the duplicate node before saving.';
1370
+ }
1371
+ if (issue.path.includes('.transform.') ||
1372
+ issue.message.includes('[x, y, z]') ||
1373
+ issue.message.includes('scale')) {
1374
+ return 'Set transform values to finite numeric tuples.';
1375
+ }
1376
+ if (issue.path.includes('.components')) {
1377
+ const missingComponent = issue.message.match(/component "([^"]+)" is not present in the active component catalog/u)?.[1];
1378
+ if (missingComponent != null) {
1379
+ return `Register "${missingComponent}" in the application component manifest or remove/rename the component payload.`;
1380
+ }
1381
+ return 'Use JSON-serializable component payloads and component names that the runtime/editor can resolve.';
1382
+ }
1383
+ return undefined;
1384
+ }
1385
+ function stripComponentPrefix(componentName) {
1386
+ return componentName.startsWith(LEVEL_COMPONENT_PREFIX)
1387
+ ? componentName.slice(LEVEL_COMPONENT_PREFIX.length)
1388
+ : componentName;
1389
+ }
1390
+ function normalizeComponentId(componentId) {
1391
+ return SCENE_EDITOR_COMPONENT_ALIASES[componentId] ?? componentId;
1392
+ }
1393
+ function hasAllowUnknownComponentsFlag(node) {
1394
+ return hasUnknownComponentFlag(node.metadata?.['iwsdk.validation']);
1395
+ }
1396
+ function hasUnknownComponentFlag(value) {
1397
+ return (typeof value === 'object' &&
1398
+ value !== null &&
1399
+ !Array.isArray(value) &&
1400
+ value.allowUnknownComponents ===
1401
+ true);
1402
+ }
1403
+ function visitNodes(nodes, visitor, path = '$.nodes') {
1404
+ nodes.forEach((node, index) => {
1405
+ const nodePath = `${path}[${index}]`;
1406
+ visitor(node, nodePath);
1407
+ visitNodes(node.children ?? [], visitor, `${nodePath}.children`);
1408
+ });
1409
+ }
1410
+ function findRequiredNodeLocation(nodes, nodeId, parent = null) {
1411
+ const index = nodes.findIndex((node) => node.id === nodeId);
1412
+ if (index !== -1) {
1413
+ return { index, node: nodes[index], parent };
1414
+ }
1415
+ for (const node of nodes) {
1416
+ const location = findNodeLocation(node.children ?? [], nodeId, node);
1417
+ if (location != null) {
1418
+ return location;
1419
+ }
1420
+ }
1421
+ throw new Error(`Unknown scene node "${nodeId}"`);
1422
+ }
1423
+ function findNodeLocation(nodes, nodeId, parent) {
1424
+ const index = nodes.findIndex((node) => node.id === nodeId);
1425
+ if (index !== -1) {
1426
+ return { index, node: nodes[index], parent };
1427
+ }
1428
+ for (const node of nodes) {
1429
+ const location = findNodeLocation(node.children ?? [], nodeId, node);
1430
+ if (location != null) {
1431
+ return location;
1432
+ }
1433
+ }
1434
+ return undefined;
1435
+ }
1436
+ function cloneNodeWithNewIds(node, originalRootId, newRootId) {
1437
+ const cloned = cloneJson(node);
1438
+ rewriteNodeIds(cloned, originalRootId, newRootId);
1439
+ return cloned;
1440
+ }
1441
+ function rewriteNodeIds(node, originalRootId, newRootId) {
1442
+ node.id = node.id === originalRootId ? newRootId : `${newRootId}-${node.id}`;
1443
+ node.children?.forEach((child) => rewriteNodeIds(child, originalRootId, newRootId));
1444
+ }
1445
+ function collectSubtreeIds(node, ids = new Set()) {
1446
+ ids.add(node.id);
1447
+ node.children?.forEach((child) => collectSubtreeIds(child, ids));
1448
+ return ids;
1449
+ }
1450
+ function createCopyId(document, nodeId) {
1451
+ const ids = new Set();
1452
+ visitNodes(document.nodes, (node) => ids.add(node.id));
1453
+ let index = 1;
1454
+ let candidate = `${nodeId}-copy`;
1455
+ while (ids.has(candidate)) {
1456
+ index += 1;
1457
+ candidate = `${nodeId}-copy-${index}`;
1458
+ }
1459
+ return candidate;
1460
+ }
1461
+ function getRecord(value, fieldName) {
1462
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
1463
+ throw new Error(`${fieldName} must be an object`);
1464
+ }
1465
+ return value;
1466
+ }
1467
+ function getRequiredString(value, fieldName) {
1468
+ if (typeof value !== 'string' || value.length === 0) {
1469
+ throw new Error(`${fieldName} must be a non-empty string`);
1470
+ }
1471
+ return value;
1472
+ }
1473
+ function getOptionalString(value) {
1474
+ if (value == null) {
1475
+ return undefined;
1476
+ }
1477
+ if (typeof value !== 'string') {
1478
+ throw new Error('Expected string value');
1479
+ }
1480
+ return value;
1481
+ }
1482
+ function getOptionalNumber(value) {
1483
+ if (value == null) {
1484
+ return undefined;
1485
+ }
1486
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
1487
+ throw new Error('Expected finite number value');
1488
+ }
1489
+ return value;
1490
+ }
1491
+ function getOptionalBoolean(value, fieldName) {
1492
+ if (value == null) {
1493
+ return undefined;
1494
+ }
1495
+ if (typeof value !== 'boolean') {
1496
+ throw new Error(`${fieldName} must be a boolean`);
1497
+ }
1498
+ return value;
1499
+ }
1500
+ function getOptionalLogLevel(value) {
1501
+ const level = getOptionalString(value);
1502
+ if (level == null) {
1503
+ return undefined;
1504
+ }
1505
+ if (level === 'info' || level === 'warn' || level === 'error') {
1506
+ return level;
1507
+ }
1508
+ throw new Error('level must be one of info, warn, error');
1509
+ }
1510
+ function getReviewLens(value) {
1511
+ if (value === 'layout' || value === 'geometry' || value === 'final') {
1512
+ return value;
1513
+ }
1514
+ throw new Error('lens must be one of layout, geometry, final');
1515
+ }
1516
+ function getCaptureMode(value) {
1517
+ if (value == null || value === 'render') {
1518
+ return 'render';
1519
+ }
1520
+ if (value === 'editor') {
1521
+ return 'editor';
1522
+ }
1523
+ throw new Error('captureMode must be one of render, editor');
1524
+ }
1525
+ function getOwnershipMode(value) {
1526
+ if (value == null || value === 'replace-new') {
1527
+ return 'replace-new';
1528
+ }
1529
+ throw new Error('ownershipMode must be "replace-new"; merge-under-root is not supported');
1530
+ }
1531
+ function assertExpectedBaseDocumentHash(params, document, actualHash) {
1532
+ if (!Object.prototype.hasOwnProperty.call(params, 'expectedBaseDocumentHash')) {
1533
+ throw new Error('expectedBaseDocumentHash is required');
1534
+ }
1535
+ const expected = params.expectedBaseDocumentHash;
1536
+ if (expected === null) {
1537
+ if (!isBlankSceneDocument(document)) {
1538
+ throw new Error(`expectedBaseDocumentHash is null but the live document is not blank (${actualHash})`);
1539
+ }
1540
+ return;
1541
+ }
1542
+ const expectedHash = getSha256(expected, 'expectedBaseDocumentHash');
1543
+ if (expectedHash !== actualHash) {
1544
+ throw new Error(`Scene document changed: expected ${expectedHash}, received ${actualHash}`);
1545
+ }
1546
+ }
1547
+ function assertCandidateDocumentHash(value, candidate) {
1548
+ const actualHash = hashSceneDocument(candidate);
1549
+ if (value === undefined) {
1550
+ return actualHash;
1551
+ }
1552
+ const suppliedHash = getSha256(value, 'candidateDocumentHash');
1553
+ if (suppliedHash !== actualHash) {
1554
+ throw new Error(`Candidate document hash mismatch: supplied ${suppliedHash}, computed ${actualHash}`);
1555
+ }
1556
+ return actualHash;
1557
+ }
1558
+ function assertLiveDocumentHash(document, expectedHash) {
1559
+ const actualHash = hashSceneDocument(document);
1560
+ if (actualHash !== expectedHash) {
1561
+ throw new Error(`Scene document changed during materialization: expected ${expectedHash}, received ${actualHash}`);
1562
+ }
1563
+ }
1564
+ function getSha256(value, fieldName) {
1565
+ if (typeof value !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(value)) {
1566
+ throw new Error(`${fieldName} must be a sha256:<64 lowercase hex> hash`);
1567
+ }
1568
+ return value;
1569
+ }
1570
+ function isBlankSceneDocument(document) {
1571
+ return (document.nodes.length === 0 &&
1572
+ (document.resources.prefabs?.length ?? 0) === 0 &&
1573
+ document.environment == null);
1574
+ }
1575
+ function createReviewCaptureSessionNonce() {
1576
+ const cryptoApi = globalThis.crypto;
1577
+ if (typeof cryptoApi?.randomUUID === 'function') {
1578
+ return cryptoApi.randomUUID();
1579
+ }
1580
+ if (typeof cryptoApi?.getRandomValues === 'function') {
1581
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
1582
+ return [...bytes]
1583
+ .map((value) => value.toString(16).padStart(2, '0'))
1584
+ .join('');
1585
+ }
1586
+ return sha256(canonicalizeJson({ createdAt: Date.now(), random: Math.random() }));
1587
+ }
1588
+ function getRequiredPositiveInteger(value, fieldName) {
1589
+ if (!Number.isInteger(value) || value <= 0) {
1590
+ throw new Error(`${fieldName} must be a positive integer`);
1591
+ }
1592
+ return value;
1593
+ }
1594
+ function assertRenderStats(value) {
1595
+ const counters = [
1596
+ 'calls',
1597
+ 'triangles',
1598
+ 'points',
1599
+ 'lines',
1600
+ 'textures',
1601
+ 'programs',
1602
+ 'shadowCasters',
1603
+ 'objectCount',
1604
+ 'nodeCount',
1605
+ 'meshCount',
1606
+ 'geometryCount',
1607
+ 'materialCount',
1608
+ ];
1609
+ if (value?.available !== true) {
1610
+ throw new Error('Renderer statistics bridge returned unavailable data');
1611
+ }
1612
+ for (const counter of counters) {
1613
+ const entry = value[counter];
1614
+ if (typeof entry !== 'number' || !Number.isFinite(entry) || entry < 0) {
1615
+ throw new Error(`Renderer statistic ${counter} must be a finite number`);
1616
+ }
1617
+ }
1618
+ if (!Array.isArray(value.frameTimeSamplesMs) ||
1619
+ value.frameTimeSamplesMs.some((entry) => typeof entry !== 'number' || !Number.isFinite(entry) || entry < 0)) {
1620
+ throw new Error('Renderer statistic frameTimeSamplesMs must contain finite non-negative numbers');
1621
+ }
1622
+ if (!isPlainEditorRecord(value.environment)) {
1623
+ throw new Error('Renderer statistic environment must be an object');
1624
+ }
1625
+ if (!Array.isArray(value.visibleNodeIds) ||
1626
+ value.visibleNodeIds.some((nodeId) => typeof nodeId !== 'string')) {
1627
+ throw new Error('Renderer statistic visibleNodeIds must be string ids');
1628
+ }
1629
+ if (value.worldBounds != null) {
1630
+ if (!isPlainEditorRecord(value.worldBounds)) {
1631
+ throw new Error('Renderer statistic worldBounds must be an object or null');
1632
+ }
1633
+ getVec3(value.worldBounds.min, 'worldBounds.min');
1634
+ getVec3(value.worldBounds.max, 'worldBounds.max');
1635
+ const size = getVec3(value.worldBounds.size, 'worldBounds.size');
1636
+ if (size.some((entry) => entry < 0)) {
1637
+ throw new Error('Renderer statistic worldBounds.size must be non-negative');
1638
+ }
1639
+ }
1640
+ if (!Object.prototype.hasOwnProperty.call(value, 'framingBounds')) {
1641
+ throw new Error('Renderer statistic framingBounds must be an object or null');
1642
+ }
1643
+ if (value.framingBounds != null) {
1644
+ if (!isPlainEditorRecord(value.framingBounds)) {
1645
+ throw new Error('Renderer statistic framingBounds must be an object or null');
1646
+ }
1647
+ getVec3(value.framingBounds.min, 'framingBounds.min');
1648
+ getVec3(value.framingBounds.max, 'framingBounds.max');
1649
+ const size = getVec3(value.framingBounds.size, 'framingBounds.size');
1650
+ if (size.some((entry) => entry < 0)) {
1651
+ throw new Error('Renderer statistic framingBounds.size must be non-negative');
1652
+ }
1653
+ }
1654
+ }
1655
+ function cloneRenderStatsSnapshot(value) {
1656
+ if (value?.available === true) {
1657
+ assertRenderStats(value);
1658
+ }
1659
+ else if (value?.available !== false ||
1660
+ typeof value.reason !== 'string' ||
1661
+ value.reason.length === 0) {
1662
+ throw new Error('Screenshot renderer statistics must be available metrics or an unavailable reason');
1663
+ }
1664
+ return cloneJson(value);
1665
+ }
1666
+ function getVec3(value, fieldName) {
1667
+ if (!Array.isArray(value) ||
1668
+ value.length !== 3 ||
1669
+ !value.every((entry) => typeof entry === 'number' && Number.isFinite(entry))) {
1670
+ throw new Error(`${fieldName} must be [x, y, z] finite numbers`);
1671
+ }
1672
+ return [value[0], value[1], value[2]];
1673
+ }
1674
+ function getStringArray(value, fieldName) {
1675
+ if (!Array.isArray(value) ||
1676
+ !value.every((entry) => typeof entry === 'string')) {
1677
+ throw new Error(`${fieldName} must be an array of strings`);
1678
+ }
1679
+ return [...value];
1680
+ }
1681
+ function getFramingRole(value) {
1682
+ if (value === 'content' || value === 'support') {
1683
+ return value;
1684
+ }
1685
+ throw new Error('framingRole must be "content" or "support"');
1686
+ }
1687
+ function snapshotSceneDocument(document) {
1688
+ try {
1689
+ return serializeSceneDocument(document);
1690
+ }
1691
+ catch {
1692
+ return JSON.stringify(document);
1693
+ }
1694
+ }
1695
+ function cloneJson(value) {
1696
+ return JSON.parse(JSON.stringify(value));
1697
+ }
1698
+
1699
+ export { SCENE_EDITOR_TOOL_METHODS, SceneEditorSession };
1700
+ //# sourceMappingURL=scene-editor-session.js.map