@openfairygui/backend 0.3.1 → 0.5.0-alpha.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.
package/dist/node.mjs CHANGED
@@ -82,13 +82,638 @@ async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
82
82
  }
83
83
  //#endregion
84
84
  //#region src/contracts.ts
85
- const BACKEND_CONTRACT_VERSION = "1.1.0-p2";
85
+ const BACKEND_CONTRACT_VERSION = "2.0.0-p2";
86
86
  const BACKEND_COMPATIBILITY_POLICY = {
87
87
  incompatibleChange: "requires contractVersion bump",
88
88
  capabilitySchemaChange: "requires capabilitySchemaVersion bump",
89
89
  additiveChange: "allowed without breaking existing consumers"
90
90
  };
91
91
  //#endregion
92
+ //#region src/diagnostics.ts
93
+ const selector = {
94
+ kind: "revise-selector",
95
+ message: "Read the current outline and query the relevant entity. Use its exact identifiers, inspect the reported selector path, then rebuild and preflight the transaction. Do not guess identifiers or retry the unchanged transaction."
96
+ };
97
+ const source = {
98
+ kind: "host-action",
99
+ message: "Ask the host to inspect the reported source and hydrate its bytes through project I/O or import. Preserve unsaved work; reopening disk state can discard it. No session hydration/repair API is exposed. Revalidate and replan after the host has supplied a complete project."
100
+ };
101
+ const path$1 = {
102
+ kind: "host-action",
103
+ message: "Ask the host to review the attempted path and authorized project root. saveSession only writes the original project; it is not Save As. Do not widen allowed roots or bypass path checks. A separately authorized export may use materializeSession."
104
+ };
105
+ const unsupported = {
106
+ kind: "revise-operation",
107
+ message: "Read the operation schema, capabilities and reported target kind/field. Stop unsupported work or replan using supported operations with equivalent intended semantics. Never silently drop fields or objects to make a transaction pass."
108
+ };
109
+ const payload = {
110
+ kind: "revise-operation",
111
+ message: "Inspect the diagnostic path and current operation schema or UAM issues. Correct values, required fields and indices against exact queried entities, then preflight. Do not invent defaults or coerce away invalid data."
112
+ };
113
+ const unchanged = {
114
+ kind: "refresh-and-replan",
115
+ message: "Query current settings/entity and compare with the request. If already satisfied, report no change; otherwise replan from the current revision. Do not manufacture a mutation or resubmit the same no-op."
116
+ };
117
+ const duplicate = {
118
+ kind: "revise-operation",
119
+ message: "Query current entities and resolve the conflicting ID, name or page explicitly. Choose an unused value only when authorized by the intended edit, then preflight. Never overwrite or delete an existing entity to clear the conflict."
120
+ };
121
+ const references = {
122
+ kind: "revise-operation",
123
+ message: "Query affected entities and references before editing, moving or removing anything. Replan intended dependent changes together and preflight. Do not delete dependent objects or strip references without authorization."
124
+ };
125
+ const project = {
126
+ kind: "host-action",
127
+ message: "Inspect the project path and validation diagnostics with the host. Correct source XML/settings or unsupported geometry using authoritative project data; preserve originals and unsaved work before reopening or validating. Do not guess missing structure or discard rejected content."
128
+ };
129
+ const capability = {
130
+ kind: "host-action",
131
+ message: "Read capability/error details. Ask the host to provide the required filesystem, decoder or complete UAM adapter. Preserve the session and unsaved work; do not substitute a lossy path or bypass checks."
132
+ };
133
+ const write = {
134
+ kind: "host-action",
135
+ message: "Preserve the dirty session and inspect the error, actual target files and permissions with the host. Partial writes may have changed files: verify or recover them before a newly authorized save. Do not clear dirty state, discard memory or blindly retry."
136
+ };
137
+ const execution = {
138
+ kind: "host-action",
139
+ message: "Inspect the execution/cache failure and current session/revision. Preserve sources and unsaved work and report the cause to the host. Replan after resolution; failed execution or cache work is not a completed edit."
140
+ };
141
+ const job = {
142
+ kind: "host-action",
143
+ message: "Inspect the job ID and status with getJob/listJobs. Do not fabricate, restart or force-cancel a missing, terminal or non-cancellable job. Ask the host before scheduling new work; cancellation is not success."
144
+ };
145
+ /** Exhaustiveness and exact ownership are checked against the canonical unions. */
146
+ const BACKEND_DIAGNOSTIC_GUIDES = [
147
+ {
148
+ code: "stale_read",
149
+ owners: ["backend"],
150
+ remediation: {
151
+ kind: "refresh-and-replan",
152
+ message: "Discard the incomplete model/bytes read and restart with readSessionState. Use its revision for every readResourceBytes call. No historical state is retained or reserved; do not combine resources from different edit revisions."
153
+ }
154
+ },
155
+ {
156
+ code: "session_read_failed",
157
+ owners: ["backend"],
158
+ remediation: {
159
+ kind: "host-action",
160
+ message: "Inspect error.reason: invalid_query requires valid inputs; not_found/ambiguous requires exact current resource identifiers; unsupported_resource/bytes_unavailable means primary bytes cannot be read from this session. Budget or non-JSON failures require host inspection. Preserve unsaved work; do not save, reopen, repair or mutate the model merely to obtain a read."
161
+ }
162
+ },
163
+ {
164
+ code: "transaction_preview_failed",
165
+ owners: ["backend"],
166
+ remediation: {
167
+ kind: "host-action",
168
+ message: "No complete preview is available. Inspect error.reason with the host: response_budget_exceeded requires a smaller independently meaningful authorized batch; projection_failed requires inspecting the project serialization failure. Preserve the session and never treat a missing or truncated impact as approval to apply or save."
169
+ }
170
+ },
171
+ {
172
+ code: "stale_write",
173
+ owners: ["backend"],
174
+ remediation: {
175
+ kind: "refresh-and-replan",
176
+ message: "Refresh the outline and affected entities, then replan from their current revision and preflight again. A preview reserves no revision. Never replace expectedRevision and blindly retry the original transaction or save."
177
+ }
178
+ },
179
+ {
180
+ code: "entity_query_failed",
181
+ owners: ["backend"],
182
+ remediation: {
183
+ kind: "host-action",
184
+ message: "Inspect error.reason: invalid_query requires correcting the target; not_found/ambiguous requires current exact identifiers; response_budget_exceeded/non_json_value requires host inspection of the entity. Do not broaden queries or mutate data to evade the response limits."
185
+ }
186
+ },
187
+ {
188
+ code: "session_not_found",
189
+ owners: ["backend"],
190
+ remediation: {
191
+ kind: "host-action",
192
+ message: "Ask the host to confirm the runtime and project, recover any unsaved state, then explicitly open a new session if appropriate. Session IDs are runtime-local. Read its new revision and replan; never reuse an expired session or assume disk contains unsaved changes."
193
+ }
194
+ },
195
+ {
196
+ code: "path_policy_violation",
197
+ owners: ["backend"],
198
+ remediation: path$1
199
+ },
200
+ {
201
+ code: "project_root_not_allowed",
202
+ owners: ["backend"],
203
+ remediation: path$1
204
+ },
205
+ {
206
+ code: "invalid_package_selector",
207
+ owners: ["core.transaction"],
208
+ remediation: selector
209
+ },
210
+ {
211
+ code: "invalid_component_selector",
212
+ owners: ["core.transaction"],
213
+ remediation: selector
214
+ },
215
+ {
216
+ code: "invalid_resource_selector",
217
+ owners: ["core.transaction"],
218
+ remediation: selector
219
+ },
220
+ {
221
+ code: "invalid_display_node_selector",
222
+ owners: ["core.transaction"],
223
+ remediation: selector
224
+ },
225
+ {
226
+ code: "invalid_resource_folder_selector",
227
+ owners: ["core.transaction"],
228
+ remediation: selector
229
+ },
230
+ {
231
+ code: "invalid_branch_selector",
232
+ owners: ["core.transaction"],
233
+ remediation: selector
234
+ },
235
+ {
236
+ code: "invalid_gear_selector",
237
+ owners: ["core.transaction"],
238
+ remediation: selector
239
+ },
240
+ {
241
+ code: "invalid_look_gear_selector",
242
+ owners: ["core.transaction"],
243
+ remediation: selector
244
+ },
245
+ {
246
+ code: "selector_ambiguity",
247
+ owners: ["core.transaction"],
248
+ remediation: selector
249
+ },
250
+ {
251
+ code: "unavailable_resource_source_bytes",
252
+ owners: ["core.transaction"],
253
+ remediation: source
254
+ },
255
+ {
256
+ code: "missing_source",
257
+ owners: ["core.validation"],
258
+ remediation: source
259
+ },
260
+ {
261
+ code: "unreadable_source",
262
+ owners: ["core.validation"],
263
+ remediation: source
264
+ },
265
+ {
266
+ code: "decode_capability_unavailable",
267
+ owners: ["core.validation"],
268
+ remediation: {
269
+ kind: "host-action",
270
+ message: "Validation is incomplete, not passed. Inspect whether source bytes are unloaded or a decoder is unavailable. Ask the host to hydrate sources or provide the required decoder (Node image validation uses optional Sharp), then validate again. Do not install dependencies or change the project automatically."
271
+ }
272
+ },
273
+ {
274
+ code: "session_id_conflict",
275
+ owners: ["backend"],
276
+ remediation: {
277
+ kind: "host-action",
278
+ message: "Use getSession to inspect the existing session. Reuse it only for the intended project, or choose a new session ID; do not close another owner\\u0027s session to make room."
279
+ }
280
+ },
281
+ {
282
+ code: "lock_conflict",
283
+ owners: ["backend"],
284
+ remediation: {
285
+ kind: "host-action",
286
+ message: "Another owner holds the project lock. Preserve unsaved work and ask that owner to close its session, then explicitly reopen. Never remove a live lock, force-close a peer, or bypass locking."
287
+ }
288
+ },
289
+ {
290
+ code: "event_cursor_invalid",
291
+ owners: ["backend"],
292
+ remediation: {
293
+ kind: "refresh-and-replan",
294
+ message: "Read the error and getEvents cursor bounds. Request a fresh bounded event page without the invalid cursor and refresh the current outline before replanning; missing retained history is not evidence that nothing changed."
295
+ }
296
+ },
297
+ {
298
+ code: "corrupt_source",
299
+ owners: ["core.validation"],
300
+ remediation: source
301
+ },
302
+ {
303
+ code: "unsupported_operation",
304
+ owners: ["core.transaction"],
305
+ remediation: unsupported
306
+ },
307
+ {
308
+ code: "transaction_unsupported",
309
+ owners: ["core.transaction"],
310
+ remediation: unsupported
311
+ },
312
+ {
313
+ code: "unsupported_display_node_kind",
314
+ owners: ["core.transaction"],
315
+ remediation: unsupported
316
+ },
317
+ {
318
+ code: "unsupported_cross_package_image_ref",
319
+ owners: ["core.transaction"],
320
+ remediation: unsupported
321
+ },
322
+ {
323
+ code: "unsupported_gear_kind",
324
+ owners: ["core.transaction"],
325
+ remediation: unsupported
326
+ },
327
+ {
328
+ code: "unsupported_resource_mutation",
329
+ owners: ["core.transaction"],
330
+ remediation: unsupported
331
+ },
332
+ {
333
+ code: "unsupported_display_node_mutation",
334
+ owners: ["core.transaction"],
335
+ remediation: unsupported
336
+ },
337
+ {
338
+ code: "unsupported_text_field_target",
339
+ owners: ["core.transaction"],
340
+ remediation: unsupported
341
+ },
342
+ {
343
+ code: "unsupported_display_node_field",
344
+ owners: ["core.transaction"],
345
+ remediation: unsupported
346
+ },
347
+ {
348
+ code: "unsupported_operation_batch",
349
+ owners: ["core.transaction"],
350
+ remediation: unsupported
351
+ },
352
+ {
353
+ code: "unsupported_resource_kind",
354
+ owners: ["core.transaction", "core.validation"],
355
+ remediation: unsupported
356
+ },
357
+ {
358
+ code: "invalid_project_settings",
359
+ owners: ["core.transaction"],
360
+ remediation: payload
361
+ },
362
+ {
363
+ code: "invalid_package_settings",
364
+ owners: ["core.transaction"],
365
+ remediation: payload
366
+ },
367
+ {
368
+ code: "invalid_display_node_payload",
369
+ owners: ["core.transaction"],
370
+ remediation: payload
371
+ },
372
+ {
373
+ code: "invalid_resource_name",
374
+ owners: ["core.transaction"],
375
+ remediation: payload
376
+ },
377
+ {
378
+ code: "invalid_resource_path",
379
+ owners: ["core.transaction"],
380
+ remediation: payload
381
+ },
382
+ {
383
+ code: "invalid_resource_folder_path",
384
+ owners: ["core.transaction"],
385
+ remediation: payload
386
+ },
387
+ {
388
+ code: "invalid_resource_folder_atlas",
389
+ owners: ["core.transaction"],
390
+ remediation: payload
391
+ },
392
+ {
393
+ code: "invalid_attach_index",
394
+ owners: ["core.transaction"],
395
+ remediation: payload
396
+ },
397
+ {
398
+ code: "invalid_controller_payload",
399
+ owners: ["core.transaction"],
400
+ remediation: payload
401
+ },
402
+ {
403
+ code: "invalid_transition_payload",
404
+ owners: ["core.transaction"],
405
+ remediation: payload
406
+ },
407
+ {
408
+ code: "invalid_look_gear_payload",
409
+ owners: ["core.transaction"],
410
+ remediation: payload
411
+ },
412
+ {
413
+ code: "invalid_gear_payload",
414
+ owners: ["core.transaction"],
415
+ remediation: payload
416
+ },
417
+ {
418
+ code: "invalid_resource_payload",
419
+ owners: ["core.transaction"],
420
+ remediation: payload
421
+ },
422
+ {
423
+ code: "invalid_resource_bytes",
424
+ owners: ["core.transaction"],
425
+ remediation: payload
426
+ },
427
+ {
428
+ code: "invalid_movie_clip_jta",
429
+ owners: ["core.transaction"],
430
+ remediation: payload
431
+ },
432
+ {
433
+ code: "invalid_resource_index",
434
+ owners: ["core.transaction"],
435
+ remediation: payload
436
+ },
437
+ {
438
+ code: "invalid_branch_name",
439
+ owners: ["core.transaction"],
440
+ remediation: payload
441
+ },
442
+ {
443
+ code: "invalid_package_payload",
444
+ owners: ["core.transaction"],
445
+ remediation: payload
446
+ },
447
+ {
448
+ code: "invalid_package_index",
449
+ owners: ["core.transaction"],
450
+ remediation: payload
451
+ },
452
+ {
453
+ code: "invalid_component_payload",
454
+ owners: ["core.transaction"],
455
+ remediation: payload
456
+ },
457
+ {
458
+ code: "invalid_component_index",
459
+ owners: ["core.transaction"],
460
+ remediation: payload
461
+ },
462
+ {
463
+ code: "invalid_component_move",
464
+ owners: ["core.transaction"],
465
+ remediation: payload
466
+ },
467
+ {
468
+ code: "invalid_uam",
469
+ owners: ["core.transaction", "core.validation"],
470
+ remediation: payload
471
+ },
472
+ {
473
+ code: "project_settings_unchanged",
474
+ owners: ["core.transaction"],
475
+ remediation: unchanged
476
+ },
477
+ {
478
+ code: "package_settings_unchanged",
479
+ owners: ["core.transaction"],
480
+ remediation: unchanged
481
+ },
482
+ {
483
+ code: "display_node_props_unchanged",
484
+ owners: ["core.transaction"],
485
+ remediation: unchanged
486
+ },
487
+ {
488
+ code: "resource_folder_atlas_unchanged",
489
+ owners: ["core.transaction"],
490
+ remediation: unchanged
491
+ },
492
+ {
493
+ code: "duplicate_look_gear_controller",
494
+ owners: ["core.transaction"],
495
+ remediation: duplicate
496
+ },
497
+ {
498
+ code: "duplicate_transition_name",
499
+ owners: ["core.transaction"],
500
+ remediation: duplicate
501
+ },
502
+ {
503
+ code: "duplicate_look_gear_state_page",
504
+ owners: ["core.transaction"],
505
+ remediation: duplicate
506
+ },
507
+ {
508
+ code: "duplicate_gear_controller",
509
+ owners: ["core.transaction"],
510
+ remediation: duplicate
511
+ },
512
+ {
513
+ code: "duplicate_gear_state_page",
514
+ owners: ["core.transaction"],
515
+ remediation: duplicate
516
+ },
517
+ {
518
+ code: "duplicate_branch_name",
519
+ owners: ["core.transaction"],
520
+ remediation: duplicate
521
+ },
522
+ {
523
+ code: "duplicate_component_id",
524
+ owners: ["core.transaction"],
525
+ remediation: duplicate
526
+ },
527
+ {
528
+ code: "resource_folder_conflict",
529
+ owners: ["core.transaction"],
530
+ remediation: duplicate
531
+ },
532
+ {
533
+ code: "duplicate_resource_id",
534
+ owners: ["core.transaction", "core.validation"],
535
+ remediation: duplicate
536
+ },
537
+ {
538
+ code: "duplicate_package_id",
539
+ owners: ["core.transaction", "core.validation"],
540
+ remediation: duplicate
541
+ },
542
+ {
543
+ code: "duplicate_package_name",
544
+ owners: ["core.transaction", "core.validation"],
545
+ remediation: duplicate
546
+ },
547
+ {
548
+ code: "resource_folder_not_empty",
549
+ owners: ["core.transaction"],
550
+ remediation: references
551
+ },
552
+ {
553
+ code: "branch_not_empty",
554
+ owners: ["core.transaction"],
555
+ remediation: references
556
+ },
557
+ {
558
+ code: "branch_referenced",
559
+ owners: ["core.transaction"],
560
+ remediation: references
561
+ },
562
+ {
563
+ code: "invalid_resource_reference",
564
+ owners: ["core.transaction"],
565
+ remediation: references
566
+ },
567
+ {
568
+ code: "invalid_component_reference",
569
+ owners: ["core.transaction"],
570
+ remediation: references
571
+ },
572
+ {
573
+ code: "invalid_group_reference",
574
+ owners: ["core.transaction"],
575
+ remediation: references
576
+ },
577
+ {
578
+ code: "package_referenced",
579
+ owners: ["core.transaction"],
580
+ remediation: references
581
+ },
582
+ {
583
+ code: "component_referenced",
584
+ owners: ["core.transaction"],
585
+ remediation: references
586
+ },
587
+ {
588
+ code: "component_has_package_dependencies",
589
+ owners: ["core.transaction"],
590
+ remediation: references
591
+ },
592
+ {
593
+ code: "dangling_resource_reference",
594
+ owners: ["core.validation"],
595
+ remediation: references
596
+ },
597
+ {
598
+ code: "invalid_project_xml",
599
+ owners: ["core.validation"],
600
+ remediation: project
601
+ },
602
+ {
603
+ code: "invalid_package_xml",
604
+ owners: ["core.validation"],
605
+ remediation: project
606
+ },
607
+ {
608
+ code: "invalid_branch_package_xml",
609
+ owners: ["core.validation"],
610
+ remediation: project
611
+ },
612
+ {
613
+ code: "invalid_component_xml",
614
+ owners: ["core.validation"],
615
+ remediation: project
616
+ },
617
+ {
618
+ code: "invalid_project_value",
619
+ owners: ["core.validation"],
620
+ remediation: project
621
+ },
622
+ {
623
+ code: "desktop_incompatible_geometry",
624
+ owners: ["core.validation"],
625
+ remediation: project
626
+ },
627
+ {
628
+ code: "invalid_settings_json",
629
+ owners: ["core.validation"],
630
+ remediation: project
631
+ },
632
+ {
633
+ code: "path_collision",
634
+ owners: ["core.validation"],
635
+ remediation: path$1
636
+ },
637
+ {
638
+ code: "unsafe_path",
639
+ owners: ["core.validation"],
640
+ remediation: path$1
641
+ },
642
+ {
643
+ code: "capability_unavailable",
644
+ owners: ["backend"],
645
+ remediation: capability
646
+ },
647
+ {
648
+ code: "uam_fidelity_unsupported",
649
+ owners: ["backend"],
650
+ remediation: capability
651
+ },
652
+ {
653
+ code: "save_partial_failure",
654
+ owners: ["backend"],
655
+ remediation: write
656
+ },
657
+ {
658
+ code: "write_failed",
659
+ owners: ["backend"],
660
+ remediation: write
661
+ },
662
+ {
663
+ code: "project_open_failed",
664
+ owners: ["backend"],
665
+ remediation: project
666
+ },
667
+ {
668
+ code: "materialize_validation_failed",
669
+ owners: ["backend"],
670
+ remediation: project
671
+ },
672
+ {
673
+ code: "execution_failure",
674
+ owners: ["core.transaction"],
675
+ remediation: execution
676
+ },
677
+ {
678
+ code: "cache_refresh_failed",
679
+ owners: ["backend"],
680
+ remediation: execution
681
+ },
682
+ {
683
+ code: "job_not_found",
684
+ owners: ["backend"],
685
+ remediation: job
686
+ },
687
+ {
688
+ code: "job_not_cancellable",
689
+ owners: ["backend"],
690
+ remediation: job
691
+ },
692
+ {
693
+ code: "job_cancelled",
694
+ owners: ["backend"],
695
+ remediation: job
696
+ }
697
+ ];
698
+ const BACKEND_DIAGNOSTICS_URI = "openfairygui://docs/diagnostics";
699
+ `${BACKEND_DIAGNOSTICS_URI}`;
700
+ function enrichBackendDiagnostic(diagnostic, sessionId) {
701
+ const guide = BACKEND_DIAGNOSTIC_GUIDES.find((entry) => entry.code === diagnostic.code);
702
+ if (!guide) return { ...diagnostic };
703
+ return {
704
+ ...diagnostic,
705
+ owner: diagnostic.owner ?? guide.owners[0],
706
+ docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}`,
707
+ remediation: {
708
+ ...guide.remediation,
709
+ ...sessionId && guide.remediation.kind !== "host-action" ? { read: {
710
+ method: "getProjectOutline",
711
+ input: { sessionId }
712
+ } } : {}
713
+ }
714
+ };
715
+ }
716
+ //#endregion
92
717
  //#region src/services/context.ts
93
718
  function diagnosticFromError(error) {
94
719
  return {
@@ -107,10 +732,10 @@ function createMeta(stage, startedAt, options) {
107
732
  revision: options?.revision,
108
733
  durationMs: Math.max(0, Date.now() - startedAt),
109
734
  warnings: options?.warnings ?? [],
110
- diagnostics: options?.diagnostics ?? [],
735
+ diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
111
736
  stage,
112
737
  contractVersion: BACKEND_CONTRACT_VERSION,
113
- capabilitySchemaVersion: 3
738
+ capabilitySchemaVersion: 11
114
739
  };
115
740
  }
116
741
  function success(stage, startedAt, data, options) {
@@ -226,6 +851,268 @@ function createStaleWriteError(session, expectedRevision) {
226
851
  };
227
852
  }
228
853
  //#endregion
854
+ //#region src/runtime/contracts.ts
855
+ const BACKEND_ENTITY_QUERY_LIMITS = {
856
+ maxBytes: 262144,
857
+ maxDepth: 32,
858
+ maxNodes: 1e5
859
+ };
860
+ const BACKEND_SESSION_READ_LIMITS = {
861
+ model: {
862
+ maxBytes: 4194304,
863
+ maxDepth: 64,
864
+ maxNodes: 5e5
865
+ },
866
+ resourceBytes: 1048576
867
+ };
868
+ const BACKEND_TRANSACTION_PREVIEW_LIMITS = {
869
+ maxBytes: 262144,
870
+ maxEntries: 2e3
871
+ };
872
+ /** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
873
+ const BACKEND_RESOURCE_QUERY_FIELDS = [
874
+ "kind",
875
+ "id",
876
+ "name",
877
+ "path",
878
+ "exported",
879
+ "favorite",
880
+ "branch",
881
+ "branchItemIds",
882
+ "fileName",
883
+ "file",
884
+ "dimensions",
885
+ "image",
886
+ "movieClip"
887
+ ];
888
+ //#endregion
889
+ //#region src/services/capture-project.ts
890
+ function createCaptureFileSystem(files, directories) {
891
+ const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
892
+ return {
893
+ async readFile(filePath) {
894
+ const value = files.get(normalize(filePath));
895
+ if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
896
+ return value;
897
+ },
898
+ async readFileRaw(filePath) {
899
+ const value = files.get(normalize(filePath));
900
+ if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
901
+ return value.slice();
902
+ },
903
+ async writeFile(filePath, content) {
904
+ files.set(normalize(filePath), content);
905
+ },
906
+ async writeFileRaw(filePath, data) {
907
+ files.set(normalize(filePath), data.slice());
908
+ },
909
+ async mkdir(dirPath) {
910
+ directories.add(normalize(dirPath));
911
+ },
912
+ async readdir() {
913
+ return [];
914
+ },
915
+ async exists(filePath) {
916
+ return files.has(normalize(filePath));
917
+ },
918
+ join(...paths) {
919
+ return normalize(paths.filter(Boolean).join("/"));
920
+ },
921
+ dirname(filePath) {
922
+ const normalized = normalize(filePath);
923
+ const separator = normalized.lastIndexOf("/");
924
+ return separator < 0 ? "" : normalized.slice(0, separator);
925
+ },
926
+ async unlink(filePath) {
927
+ files.delete(normalize(filePath));
928
+ }
929
+ };
930
+ }
931
+ function capturedFilesEqual(left, right) {
932
+ if (left.size !== right.size) return false;
933
+ for (const [filePath, leftValue] of left) {
934
+ const rightValue = right.get(filePath);
935
+ if (typeof leftValue === "string") {
936
+ if (leftValue !== rightValue) return false;
937
+ continue;
938
+ }
939
+ if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
940
+ for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
941
+ }
942
+ return true;
943
+ }
944
+ function capturedDirectoriesEqual(left, right) {
945
+ return left.size === right.size && [...left].every((directory) => right.has(directory));
946
+ }
947
+ /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
948
+ async function captureProject(document, fairyFileName) {
949
+ const files = /* @__PURE__ */ new Map();
950
+ const directories = /* @__PURE__ */ new Set();
951
+ await new ProjectWriter(createCaptureFileSystem(files, directories)).write(document, fairyFileName);
952
+ return {
953
+ files,
954
+ directories
955
+ };
956
+ }
957
+ //#endregion
958
+ //#region src/services/transaction-preview.ts
959
+ /** Keep child identities/order on their parent, and compare each child's own properties separately. */
960
+ function entities(project) {
961
+ const result = /* @__PURE__ */ new Map();
962
+ function add(target, properties) {
963
+ const key = JSON.stringify(target);
964
+ if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
965
+ result.set(key, {
966
+ target,
967
+ properties
968
+ });
969
+ }
970
+ const { packages, ...properties } = project;
971
+ add({ kind: "project" }, {
972
+ ...properties,
973
+ packages: packages.map((pkg) => pkg.id)
974
+ });
975
+ for (const { resources, ...pkg } of packages) {
976
+ const packageId = pkg.id;
977
+ add({
978
+ kind: "package",
979
+ selector: { packageId }
980
+ }, {
981
+ ...pkg,
982
+ resources: resources.map((resource) => resource.id)
983
+ });
984
+ for (const resource of resources) {
985
+ const resourceTarget = {
986
+ kind: "resource",
987
+ selector: {
988
+ packageId,
989
+ resourceId: resource.id
990
+ }
991
+ };
992
+ if (resource.kind !== "component") {
993
+ add(resourceTarget, resource);
994
+ continue;
995
+ }
996
+ const { component, ...resourceProperties } = resource;
997
+ add(resourceTarget, resourceProperties);
998
+ const { displayList, controllers, transitions, ...componentProperties } = component;
999
+ const selector = {
1000
+ packageId,
1001
+ componentResourceId: resource.id
1002
+ };
1003
+ add({
1004
+ kind: "component",
1005
+ selector
1006
+ }, {
1007
+ ...componentProperties,
1008
+ displayList: displayList.map((node) => node.id),
1009
+ controllers: controllers.map((controller) => controller.name),
1010
+ transitions: transitions.map((transition) => transition.name)
1011
+ });
1012
+ for (const node of displayList) add({
1013
+ kind: "displayNode",
1014
+ selector: {
1015
+ ...selector,
1016
+ displayNodeId: node.id
1017
+ }
1018
+ }, node);
1019
+ for (const controller of controllers) add({
1020
+ kind: "controller",
1021
+ selector: {
1022
+ ...selector,
1023
+ controllerName: controller.name
1024
+ }
1025
+ }, controller);
1026
+ for (const transition of transitions) add({
1027
+ kind: "transition",
1028
+ selector: {
1029
+ ...selector,
1030
+ transitionName: transition.name
1031
+ }
1032
+ }, transition);
1033
+ }
1034
+ }
1035
+ return result;
1036
+ }
1037
+ function equal(left, right, depth = 0) {
1038
+ if (left === right) return true;
1039
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
1040
+ if (left instanceof Uint8Array || right instanceof Uint8Array) return left instanceof Uint8Array && right instanceof Uint8Array && left.length === right.length && left.every((value, index) => value === right[index]);
1041
+ if (depth > 128) throw new Error("Preview property comparison exceeds the supported nesting depth.");
1042
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
1043
+ if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
1044
+ const a = left, b = right;
1045
+ const keys = Object.keys(a);
1046
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
1047
+ }
1048
+ var PreviewBudgetError = class extends Error {};
1049
+ /** No host filesystem, cache, event or session mutation is involved in the projection. */
1050
+ async function previewTransactionImpact(session, project, fileSystemAvailable) {
1051
+ const impact = {
1052
+ entities: [],
1053
+ files: []
1054
+ };
1055
+ const before = entities(session.project), after = entities(project);
1056
+ let entries = 0, bytes = 0;
1057
+ const encoder = new TextEncoder();
1058
+ function count(value) {
1059
+ bytes += encoder.encode(JSON.stringify(value)).byteLength;
1060
+ if (++entries > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxEntries || bytes > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction impact exceeds the preview response budget.");
1061
+ }
1062
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
1063
+ const previous = before.get(key), next = after.get(key);
1064
+ const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])].filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
1065
+ if (!fields.length && previous && next) continue;
1066
+ const change = {
1067
+ target: (next ?? previous).target,
1068
+ change: !previous ? "added" : !next ? "removed" : "updated",
1069
+ fields
1070
+ };
1071
+ count(change);
1072
+ impact.entities.push(change);
1073
+ }
1074
+ const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, "/").split("/").at(-1) : "Project.fairy";
1075
+ const [previousFiles, nextFiles] = await Promise.all([captureProject(materializeUamProject(session.project), fairyFileName), captureProject(materializeUamProject(project), fairyFileName)]);
1076
+ for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
1077
+ const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
1078
+ if (equal(previous, next)) continue;
1079
+ const change = {
1080
+ path,
1081
+ kind: "file",
1082
+ change: previous === void 0 ? "added" : next === void 0 ? "removed" : "updated"
1083
+ };
1084
+ count(change);
1085
+ impact.files.push(change);
1086
+ }
1087
+ for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
1088
+ if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
1089
+ const change = {
1090
+ path,
1091
+ kind: "directory",
1092
+ change: nextFiles.directories.has(path) ? "added" : "removed"
1093
+ };
1094
+ count(change);
1095
+ impact.files.push(change);
1096
+ }
1097
+ impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
1098
+ const preview = {
1099
+ sessionId: session.sessionId,
1100
+ baseRevision: session.revision,
1101
+ projectedRevision: session.revision + 1,
1102
+ mode: "execute-and-discard",
1103
+ impact,
1104
+ persistence: {
1105
+ requiredAfterApply: true,
1106
+ fileSystemAvailable,
1107
+ uamFidelity: session.uamFidelity,
1108
+ writeVerified: false,
1109
+ nextAction: session.uamFidelity === "unsupported" || !fileSystemAvailable ? "host-action" : session.fileSystem ? "saveSession" : "materializeSession"
1110
+ }
1111
+ };
1112
+ if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction preview exceeds the response byte budget.");
1113
+ return preview;
1114
+ }
1115
+ //#endregion
229
1116
  //#region src/services/authoring-service.ts
230
1117
  function sourceFileKey(source) {
231
1118
  return [
@@ -255,8 +1142,12 @@ function recordStaleProjectFiles(session, previousProject, nextProject) {
255
1142
  for (const directory of staleBranchDirectories(nextProject, previousProject)) session.pendingStaleBranchDirectories.delete(branchDirectoryKey(directory));
256
1143
  }
257
1144
  function toBackendDiagnostics(error) {
258
- return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({ ...diagnostic })) : [{
1145
+ return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({
1146
+ ...diagnostic,
1147
+ owner: "core.transaction"
1148
+ })) : [{
259
1149
  code: error.code,
1150
+ owner: "core.transaction",
260
1151
  message: error.message,
261
1152
  severity: "error",
262
1153
  operationKind: error.operationKind,
@@ -344,6 +1235,46 @@ var AuthoringService = class {
344
1235
  if (this.sessionOperations.get(sessionId) === tail) this.sessionOperations.delete(sessionId);
345
1236
  }
346
1237
  }
1238
+ async preflightTransaction(input) {
1239
+ const queuedInput = structuredClone(input);
1240
+ detachSharedByteViews(queuedInput);
1241
+ return this.runSessionExclusive(queuedInput.sessionId, async () => {
1242
+ const startedAt = Date.now();
1243
+ const session = this.context.sessions.get(queuedInput.sessionId);
1244
+ if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1245
+ const meta = {
1246
+ sessionId: session.sessionId,
1247
+ revision: session.revision
1248
+ };
1249
+ if (queuedInput.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, queuedInput.expectedRevision), toSessionSnapshot(session, this.context.capabilities), meta);
1250
+ const project = structuredClone(session.project);
1251
+ detachSharedByteViews(project);
1252
+ const result = await applyUamTransactionAppAsync({
1253
+ project,
1254
+ operations: queuedInput.operations
1255
+ });
1256
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1257
+ if (!result.ok) return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
1258
+ ...meta,
1259
+ diagnostics: toBackendDiagnostics(result.error)
1260
+ });
1261
+ try {
1262
+ const preview = await previewTransactionImpact({
1263
+ ...session,
1264
+ project
1265
+ }, result.project, Boolean(session.fileSystem));
1266
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1267
+ return success("authoring", startedAt, preview, meta);
1268
+ } catch (error) {
1269
+ return failure("authoring", startedAt, {
1270
+ code: "transaction_preview_failed",
1271
+ sessionId: session.sessionId,
1272
+ reason: error instanceof PreviewBudgetError ? "response_budget_exceeded" : "projection_failed",
1273
+ message: error instanceof Error ? error.message : String(error)
1274
+ }, toSessionSnapshot(session, this.context.capabilities), meta);
1275
+ }
1276
+ });
1277
+ }
347
1278
  async applyTransaction(input) {
348
1279
  const queuedInput = structuredClone(input);
349
1280
  detachSharedByteViews(queuedInput);
@@ -423,7 +1354,7 @@ var AuthoringService = class {
423
1354
  const startedAt = Date.now();
424
1355
  const session = this.context.sessions.get(input.sessionId);
425
1356
  if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
426
- const fileSystem = session.fileSystem ?? input.fileSystem ?? this.context.fileSystem;
1357
+ const fileSystem = session.fileSystem ?? input.fileSystem;
427
1358
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("saveSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
428
1359
  sessionId: session.sessionId,
429
1360
  revision: session.revision
@@ -525,7 +1456,7 @@ var AuthoringService = class {
525
1456
  revision: session.revision
526
1457
  });
527
1458
  const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
528
- const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem ?? this.context.fileSystem;
1459
+ const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
529
1460
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("materializeSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
530
1461
  sessionId: session.sessionId,
531
1462
  revision: session.revision
@@ -751,7 +1682,7 @@ var EventService = class {
751
1682
  ...event,
752
1683
  sequence: this.context.nextEventSequence(),
753
1684
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
754
- diagnostics: event.diagnostics ?? []
1685
+ diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
755
1686
  };
756
1687
  const sessionId = event.sessionId;
757
1688
  if (!sessionId) return emitted;
@@ -1079,6 +2010,48 @@ var JobService = class {
1079
2010
  };
1080
2011
  //#endregion
1081
2012
  //#region src/services/read-service.ts
2013
+ /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
2014
+ function queryResponseProblem(value, limits = BACKEND_ENTITY_QUERY_LIMITS) {
2015
+ const pending = [{
2016
+ value,
2017
+ depth: 0
2018
+ }];
2019
+ let nodes = 0;
2020
+ let stringUnits = 0;
2021
+ while (pending.length) {
2022
+ const { value, depth } = pending.pop();
2023
+ if (++nodes > limits.maxNodes || depth > limits.maxDepth) return "response_budget_exceeded";
2024
+ if (typeof value === "string" && (stringUnits += value.length) > limits.maxBytes) return "response_budget_exceeded";
2025
+ if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") continue;
2026
+ if (typeof value === "number") {
2027
+ if (!Number.isFinite(value)) return "non_json_value";
2028
+ continue;
2029
+ }
2030
+ if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return "non_json_value";
2031
+ if (Array.isArray(value) && value.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
2032
+ const entries = Object.entries(value);
2033
+ if (entries.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
2034
+ for (const [key, child] of entries) {
2035
+ if (!Array.isArray(value) && (stringUnits += key.length) > limits.maxBytes) return "response_budget_exceeded";
2036
+ pending.push({
2037
+ value: child,
2038
+ depth: depth + 1
2039
+ });
2040
+ }
2041
+ }
2042
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limits.maxBytes) return "response_budget_exceeded";
2043
+ }
2044
+ function readFailure(startedAt, sessionId, reason, revision) {
2045
+ return failure("read", startedAt, {
2046
+ code: "session_read_failed",
2047
+ sessionId,
2048
+ reason,
2049
+ message: `Session read failed: ${reason}.`
2050
+ }, void 0, {
2051
+ sessionId,
2052
+ revision
2053
+ });
2054
+ }
1082
2055
  function toProjectOutline(session) {
1083
2056
  const project = session.project;
1084
2057
  return {
@@ -1146,6 +2119,195 @@ var ReadService = class {
1146
2119
  revision: session.revision
1147
2120
  });
1148
2121
  }
2122
+ queryEntity(input) {
2123
+ const startedAt = Date.now();
2124
+ const session = this.context.sessions.get(input.sessionId);
2125
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2126
+ const meta = {
2127
+ sessionId: session.sessionId,
2128
+ revision: session.revision
2129
+ };
2130
+ const reject = (reason) => failure("read", startedAt, {
2131
+ code: "entity_query_failed",
2132
+ sessionId: session.sessionId,
2133
+ reason,
2134
+ message: `Entity query failed: ${reason}.`
2135
+ }, void 0, meta);
2136
+ const target = input.target;
2137
+ if (!target || typeof target !== "object" || Array.isArray(target) || Object.keys(target).some((key) => key !== "kind" && key !== "selector")) return reject("invalid_query");
2138
+ const respond = (entity) => {
2139
+ const data = {
2140
+ ...meta,
2141
+ target,
2142
+ entity
2143
+ };
2144
+ const problem = queryResponseProblem(data);
2145
+ return problem ? reject(problem) : success("read", startedAt, structuredClone(data), meta);
2146
+ };
2147
+ if (target.kind === "project") {
2148
+ if (Object.hasOwn(target, "selector")) return reject("invalid_query");
2149
+ const { projectId, settings } = session.project;
2150
+ return respond({
2151
+ kind: "project",
2152
+ properties: {
2153
+ projectId,
2154
+ settings
2155
+ }
2156
+ });
2157
+ }
2158
+ const keys = target.kind === "package" ? ["packageId"] : target.kind === "resource" ? ["packageId", "resourceId"] : target.kind === "component" ? ["packageId", "componentResourceId"] : target.kind === "displayNode" ? [
2159
+ "packageId",
2160
+ "componentResourceId",
2161
+ "displayNodeId"
2162
+ ] : target.kind === "controller" ? [
2163
+ "packageId",
2164
+ "componentResourceId",
2165
+ "controllerName"
2166
+ ] : target.kind === "transition" ? [
2167
+ "packageId",
2168
+ "componentResourceId",
2169
+ "transitionName"
2170
+ ] : [];
2171
+ const selector = target.selector;
2172
+ if (!keys.length || !selector || typeof selector !== "object" || Array.isArray(selector) || Object.keys(selector).length !== keys.length || keys.some((key) => !Object.hasOwn(selector, key) || typeof selector[key] !== "string" || !selector[key].length || selector[key].length > 256)) return reject("invalid_query");
2173
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2174
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2175
+ if (target.kind === "package") {
2176
+ const { id, name, compressPNG, jpegQuality, publish } = packages[0];
2177
+ return respond({
2178
+ kind: "package",
2179
+ properties: {
2180
+ id,
2181
+ name,
2182
+ settings: {
2183
+ compressPNG,
2184
+ jpegQuality,
2185
+ publish
2186
+ }
2187
+ }
2188
+ });
2189
+ }
2190
+ const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === "resource" ? selector.resourceId : selector.componentResourceId));
2191
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2192
+ const resource = resources[0];
2193
+ let entity;
2194
+ if (target.kind === "resource") {
2195
+ const record = resource;
2196
+ entity = {
2197
+ kind: "resource",
2198
+ properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS.filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]]))
2199
+ };
2200
+ } else {
2201
+ if (resource.kind !== "component") return reject("not_found");
2202
+ if (target.kind === "component") {
2203
+ const { size, properties, customData } = resource.component;
2204
+ entity = {
2205
+ kind: "component",
2206
+ properties: {
2207
+ size,
2208
+ properties,
2209
+ customData
2210
+ }
2211
+ };
2212
+ } else if (target.kind === "controller") {
2213
+ const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
2214
+ if (controllers.length !== 1) return reject(controllers.length ? "ambiguous" : "not_found");
2215
+ entity = {
2216
+ kind: "controller",
2217
+ properties: controllers[0]
2218
+ };
2219
+ } else if (target.kind === "transition") {
2220
+ const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
2221
+ if (transitions.length !== 1) return reject(transitions.length ? "ambiguous" : "not_found");
2222
+ entity = {
2223
+ kind: "transition",
2224
+ properties: transitions[0]
2225
+ };
2226
+ } else {
2227
+ const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
2228
+ if (nodes.length !== 1) return reject(nodes.length ? "ambiguous" : "not_found");
2229
+ entity = {
2230
+ kind: "displayNode",
2231
+ properties: nodes[0]
2232
+ };
2233
+ }
2234
+ }
2235
+ return respond(entity);
2236
+ }
2237
+ resolveReadSession(input, startedAt) {
2238
+ if (!input || typeof input.sessionId !== "string" || !input.sessionId.length || input.sessionId.length > 256 || input.expectedRevision !== void 0 && (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0)) return readFailure(startedAt, typeof input?.sessionId === "string" ? input.sessionId : "", "invalid_query");
2239
+ const session = this.context.sessions.get(input.sessionId);
2240
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2241
+ const meta = {
2242
+ sessionId: session.sessionId,
2243
+ revision: session.revision
2244
+ };
2245
+ if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("read", startedAt, {
2246
+ code: "stale_read",
2247
+ sessionId: session.sessionId,
2248
+ expectedRevision: input.expectedRevision,
2249
+ actualRevision: session.revision,
2250
+ message: "The session edit revision changed. Restart the model and resource read."
2251
+ }, void 0, meta);
2252
+ return success("read", startedAt, session, meta);
2253
+ }
2254
+ readSessionState(input) {
2255
+ const startedAt = Date.now();
2256
+ const resolved = this.resolveReadSession(input, startedAt);
2257
+ if (!resolved.ok) return resolved;
2258
+ const session = resolved.data;
2259
+ const meta = {
2260
+ sessionId: session.sessionId,
2261
+ revision: session.revision
2262
+ };
2263
+ const data = {
2264
+ ...meta,
2265
+ dirty: session.dirty,
2266
+ lastSavedRevision: session.lastSavedRevision,
2267
+ uamFidelity: session.uamFidelity,
2268
+ readComplete: session.readComplete,
2269
+ readDiagnostics: session.readDiagnostics,
2270
+ project: {
2271
+ ...session.project,
2272
+ packages: session.project.packages.map((pkg) => ({
2273
+ ...pkg,
2274
+ resources: pkg.resources.map((resource) => {
2275
+ if (resource.kind === "component") return resource;
2276
+ const { sourceBytes: _sourceBytes, ...model } = resource;
2277
+ return model;
2278
+ })
2279
+ }))
2280
+ }
2281
+ };
2282
+ const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
2283
+ return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, structuredClone(data), meta);
2284
+ }
2285
+ readResourceBytes(input) {
2286
+ const startedAt = Date.now();
2287
+ const resolved = this.resolveReadSession(input, startedAt);
2288
+ if (!resolved.ok) return resolved;
2289
+ const session = resolved.data;
2290
+ const reject = (reason) => readFailure(startedAt, session.sessionId, reason, session.revision);
2291
+ const selector = input.selector;
2292
+ if (input.expectedRevision === void 0 || !selector || typeof selector !== "object" || Array.isArray(selector) || Object.keys(selector).length !== 2 || ["packageId", "resourceId"].some((key) => !Object.hasOwn(selector, key)) || [selector.packageId, selector.resourceId].some((value) => typeof value !== "string" || !value.length || value.length > 256)) return reject("invalid_query");
2293
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2294
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2295
+ const resources = packages[0].resources.filter((resource) => resource.id === selector.resourceId);
2296
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2297
+ const resource = resources[0];
2298
+ if (resource.kind === "component") return reject("unsupported_resource");
2299
+ if (!(resource.sourceBytes instanceof Uint8Array)) return reject("bytes_unavailable");
2300
+ if (resource.sourceBytes.byteLength > BACKEND_SESSION_READ_LIMITS.resourceBytes) return reject("response_budget_exceeded");
2301
+ const meta = {
2302
+ sessionId: session.sessionId,
2303
+ revision: session.revision
2304
+ };
2305
+ return success("read", startedAt, {
2306
+ ...meta,
2307
+ selector: { ...selector },
2308
+ sourceBytes: new Uint8Array(resource.sourceBytes)
2309
+ }, meta);
2310
+ }
1149
2311
  validateSession(input) {
1150
2312
  const startedAt = Date.now();
1151
2313
  const session = this.context.sessions.get(input.sessionId);
@@ -1162,7 +2324,8 @@ var ReadService = class {
1162
2324
  code,
1163
2325
  message,
1164
2326
  severity,
1165
- path
2327
+ path,
2328
+ owner: "core.validation"
1166
2329
  }))
1167
2330
  });
1168
2331
  }
@@ -1223,63 +2386,6 @@ function createProjectReaderFileSystem(fileSystem, projectRoot) {
1223
2386
  }
1224
2387
  };
1225
2388
  }
1226
- function createCaptureFileSystem(files, directories) {
1227
- const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
1228
- return {
1229
- async readFile(filePath) {
1230
- const value = files.get(normalize(filePath));
1231
- if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
1232
- return value;
1233
- },
1234
- async readFileRaw(filePath) {
1235
- const value = files.get(normalize(filePath));
1236
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
1237
- return value.slice();
1238
- },
1239
- async writeFile(filePath, content) {
1240
- files.set(normalize(filePath), content);
1241
- },
1242
- async writeFileRaw(filePath, data) {
1243
- files.set(normalize(filePath), data.slice());
1244
- },
1245
- async mkdir(dirPath) {
1246
- directories.add(normalize(dirPath));
1247
- },
1248
- async readdir() {
1249
- return [];
1250
- },
1251
- async exists(filePath) {
1252
- return files.has(normalize(filePath));
1253
- },
1254
- join(...paths) {
1255
- return normalize(paths.filter(Boolean).join("/"));
1256
- },
1257
- dirname(filePath) {
1258
- const normalized = normalize(filePath);
1259
- const separator = normalized.lastIndexOf("/");
1260
- return separator < 0 ? "" : normalized.slice(0, separator);
1261
- },
1262
- async unlink(filePath) {
1263
- files.delete(normalize(filePath));
1264
- }
1265
- };
1266
- }
1267
- function capturedFilesEqual(left, right) {
1268
- if (left.size !== right.size) return false;
1269
- for (const [filePath, leftValue] of left) {
1270
- const rightValue = right.get(filePath);
1271
- if (typeof leftValue === "string") {
1272
- if (leftValue !== rightValue) return false;
1273
- continue;
1274
- }
1275
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
1276
- for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
1277
- }
1278
- return true;
1279
- }
1280
- function capturedDirectoriesEqual(left, right) {
1281
- return left.size === right.size && [...left].every((directory) => right.has(directory));
1282
- }
1283
2389
  async function hasFullUamFidelity(document, project) {
1284
2390
  const sourceFiles = /* @__PURE__ */ new Map();
1285
2391
  const materializedFiles = /* @__PURE__ */ new Map();
@@ -1511,7 +2617,11 @@ const BACKEND_METHODS = [
1511
2617
  "openProjectSession",
1512
2618
  "getSession",
1513
2619
  "getProjectOutline",
2620
+ "queryEntity",
2621
+ "readSessionState",
2622
+ "readResourceBytes",
1514
2623
  "validateSession",
2624
+ "preflightTransaction",
1515
2625
  "applyTransaction",
1516
2626
  "saveSession",
1517
2627
  "materializeSession",
@@ -1533,7 +2643,7 @@ const ARTIFACT_BRIDGE_CAPABILITY = {
1533
2643
  function createCapabilities(atomicSave = false) {
1534
2644
  return {
1535
2645
  contractVersion: BACKEND_CONTRACT_VERSION,
1536
- capabilitySchemaVersion: 3,
2646
+ capabilitySchemaVersion: 11,
1537
2647
  transactionKernelOwner: "@openfairygui/core",
1538
2648
  appSeamOwner: "@openfairygui/functions",
1539
2649
  runtimeOwner: "@openfairygui/backend",
@@ -1542,9 +2652,38 @@ function createCapabilities(atomicSave = false) {
1542
2652
  capabilitySnapshot: true,
1543
2653
  sessionSnapshot: true,
1544
2654
  projectOutline: true,
2655
+ entityQuery: {
2656
+ kinds: [
2657
+ "project",
2658
+ "package",
2659
+ "resource",
2660
+ "component",
2661
+ "displayNode",
2662
+ "controller",
2663
+ "transition"
2664
+ ],
2665
+ projection: "properties",
2666
+ sourceBytes: false,
2667
+ limits: BACKEND_ENTITY_QUERY_LIMITS
2668
+ },
2669
+ sessionState: {
2670
+ sourceBytes: false,
2671
+ limits: BACKEND_SESSION_READ_LIMITS.model
2672
+ },
2673
+ resourceBytes: {
2674
+ expectedRevisionRequired: true,
2675
+ hydration: false,
2676
+ maxBytes: BACKEND_SESSION_READ_LIMITS.resourceBytes
2677
+ },
1545
2678
  projectValidation: true
1546
2679
  },
1547
2680
  authoring: {
2681
+ preflightTransaction: {
2682
+ mode: "execute-and-discard",
2683
+ reservesRevision: false,
2684
+ impact: "model-diff",
2685
+ limits: BACKEND_TRANSACTION_PREVIEW_LIMITS
2686
+ },
1548
2687
  applyTransaction: true,
1549
2688
  saveSession: true,
1550
2689
  resourceKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
@@ -1594,7 +2733,9 @@ function createCapabilities(atomicSave = false) {
1594
2733
  },
1595
2734
  diagnostics: {
1596
2735
  stableCodes: true,
1597
- errorDiagnosticMirror: true
2736
+ errorDiagnosticMirror: true,
2737
+ recoveryGuides: "all-formal-codes",
2738
+ automaticRepair: false
1598
2739
  }
1599
2740
  },
1600
2741
  compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
@@ -1695,9 +2836,21 @@ var BackendRuntime = class {
1695
2836
  getProjectOutline(input) {
1696
2837
  return this.readService.getProjectOutline(input);
1697
2838
  }
2839
+ queryEntity(input) {
2840
+ return this.readService.queryEntity(input);
2841
+ }
2842
+ readSessionState(input) {
2843
+ return this.readService.readSessionState(input);
2844
+ }
2845
+ readResourceBytes(input) {
2846
+ return this.readService.readResourceBytes(input);
2847
+ }
1698
2848
  validateSession(input) {
1699
2849
  return this.readService.validateSession(input);
1700
2850
  }
2851
+ async preflightTransaction(input) {
2852
+ return this.authoringService.preflightTransaction(input);
2853
+ }
1701
2854
  async applyTransaction(input) {
1702
2855
  return this.authoringService.applyTransaction(input);
1703
2856
  }