@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/index.cjs CHANGED
@@ -4,14 +4,650 @@ let _openfairygui_functions_uam = require("@openfairygui/functions/uam");
4
4
  let _openfairygui_core_project_io = require("@openfairygui/core/project-io");
5
5
  let _openfairygui_functions = require("@openfairygui/functions");
6
6
  //#region src/contracts.ts
7
- const BACKEND_CONTRACT_VERSION = "1.1.0-p2";
8
- const BACKEND_CAPABILITY_SCHEMA_VERSION = 3;
7
+ const BACKEND_CONTRACT_VERSION = "2.0.0-p2";
8
+ const BACKEND_CAPABILITY_SCHEMA_VERSION = 11;
9
9
  const BACKEND_COMPATIBILITY_POLICY = {
10
10
  incompatibleChange: "requires contractVersion bump",
11
11
  capabilitySchemaChange: "requires capabilitySchemaVersion bump",
12
12
  additiveChange: "allowed without breaking existing consumers"
13
13
  };
14
14
  //#endregion
15
+ //#region src/diagnostics.ts
16
+ const selector = {
17
+ kind: "revise-selector",
18
+ 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."
19
+ };
20
+ const source = {
21
+ kind: "host-action",
22
+ 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."
23
+ };
24
+ const path = {
25
+ kind: "host-action",
26
+ 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."
27
+ };
28
+ const unsupported = {
29
+ kind: "revise-operation",
30
+ 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."
31
+ };
32
+ const payload = {
33
+ kind: "revise-operation",
34
+ 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."
35
+ };
36
+ const unchanged = {
37
+ kind: "refresh-and-replan",
38
+ 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."
39
+ };
40
+ const duplicate = {
41
+ kind: "revise-operation",
42
+ 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."
43
+ };
44
+ const references = {
45
+ kind: "revise-operation",
46
+ 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."
47
+ };
48
+ const project = {
49
+ kind: "host-action",
50
+ 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."
51
+ };
52
+ const capability = {
53
+ kind: "host-action",
54
+ 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."
55
+ };
56
+ const write = {
57
+ kind: "host-action",
58
+ 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."
59
+ };
60
+ const execution = {
61
+ kind: "host-action",
62
+ 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."
63
+ };
64
+ const job = {
65
+ kind: "host-action",
66
+ 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."
67
+ };
68
+ /** Exhaustiveness and exact ownership are checked against the canonical unions. */
69
+ const BACKEND_DIAGNOSTIC_GUIDES = [
70
+ {
71
+ code: "stale_read",
72
+ owners: ["backend"],
73
+ remediation: {
74
+ kind: "refresh-and-replan",
75
+ 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."
76
+ }
77
+ },
78
+ {
79
+ code: "session_read_failed",
80
+ owners: ["backend"],
81
+ remediation: {
82
+ kind: "host-action",
83
+ 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."
84
+ }
85
+ },
86
+ {
87
+ code: "transaction_preview_failed",
88
+ owners: ["backend"],
89
+ remediation: {
90
+ kind: "host-action",
91
+ 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."
92
+ }
93
+ },
94
+ {
95
+ code: "stale_write",
96
+ owners: ["backend"],
97
+ remediation: {
98
+ kind: "refresh-and-replan",
99
+ 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."
100
+ }
101
+ },
102
+ {
103
+ code: "entity_query_failed",
104
+ owners: ["backend"],
105
+ remediation: {
106
+ kind: "host-action",
107
+ 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."
108
+ }
109
+ },
110
+ {
111
+ code: "session_not_found",
112
+ owners: ["backend"],
113
+ remediation: {
114
+ kind: "host-action",
115
+ 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."
116
+ }
117
+ },
118
+ {
119
+ code: "path_policy_violation",
120
+ owners: ["backend"],
121
+ remediation: path
122
+ },
123
+ {
124
+ code: "project_root_not_allowed",
125
+ owners: ["backend"],
126
+ remediation: path
127
+ },
128
+ {
129
+ code: "invalid_package_selector",
130
+ owners: ["core.transaction"],
131
+ remediation: selector
132
+ },
133
+ {
134
+ code: "invalid_component_selector",
135
+ owners: ["core.transaction"],
136
+ remediation: selector
137
+ },
138
+ {
139
+ code: "invalid_resource_selector",
140
+ owners: ["core.transaction"],
141
+ remediation: selector
142
+ },
143
+ {
144
+ code: "invalid_display_node_selector",
145
+ owners: ["core.transaction"],
146
+ remediation: selector
147
+ },
148
+ {
149
+ code: "invalid_resource_folder_selector",
150
+ owners: ["core.transaction"],
151
+ remediation: selector
152
+ },
153
+ {
154
+ code: "invalid_branch_selector",
155
+ owners: ["core.transaction"],
156
+ remediation: selector
157
+ },
158
+ {
159
+ code: "invalid_gear_selector",
160
+ owners: ["core.transaction"],
161
+ remediation: selector
162
+ },
163
+ {
164
+ code: "invalid_look_gear_selector",
165
+ owners: ["core.transaction"],
166
+ remediation: selector
167
+ },
168
+ {
169
+ code: "selector_ambiguity",
170
+ owners: ["core.transaction"],
171
+ remediation: selector
172
+ },
173
+ {
174
+ code: "unavailable_resource_source_bytes",
175
+ owners: ["core.transaction"],
176
+ remediation: source
177
+ },
178
+ {
179
+ code: "missing_source",
180
+ owners: ["core.validation"],
181
+ remediation: source
182
+ },
183
+ {
184
+ code: "unreadable_source",
185
+ owners: ["core.validation"],
186
+ remediation: source
187
+ },
188
+ {
189
+ code: "decode_capability_unavailable",
190
+ owners: ["core.validation"],
191
+ remediation: {
192
+ kind: "host-action",
193
+ 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."
194
+ }
195
+ },
196
+ {
197
+ code: "session_id_conflict",
198
+ owners: ["backend"],
199
+ remediation: {
200
+ kind: "host-action",
201
+ 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."
202
+ }
203
+ },
204
+ {
205
+ code: "lock_conflict",
206
+ owners: ["backend"],
207
+ remediation: {
208
+ kind: "host-action",
209
+ 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."
210
+ }
211
+ },
212
+ {
213
+ code: "event_cursor_invalid",
214
+ owners: ["backend"],
215
+ remediation: {
216
+ kind: "refresh-and-replan",
217
+ 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."
218
+ }
219
+ },
220
+ {
221
+ code: "corrupt_source",
222
+ owners: ["core.validation"],
223
+ remediation: source
224
+ },
225
+ {
226
+ code: "unsupported_operation",
227
+ owners: ["core.transaction"],
228
+ remediation: unsupported
229
+ },
230
+ {
231
+ code: "transaction_unsupported",
232
+ owners: ["core.transaction"],
233
+ remediation: unsupported
234
+ },
235
+ {
236
+ code: "unsupported_display_node_kind",
237
+ owners: ["core.transaction"],
238
+ remediation: unsupported
239
+ },
240
+ {
241
+ code: "unsupported_cross_package_image_ref",
242
+ owners: ["core.transaction"],
243
+ remediation: unsupported
244
+ },
245
+ {
246
+ code: "unsupported_gear_kind",
247
+ owners: ["core.transaction"],
248
+ remediation: unsupported
249
+ },
250
+ {
251
+ code: "unsupported_resource_mutation",
252
+ owners: ["core.transaction"],
253
+ remediation: unsupported
254
+ },
255
+ {
256
+ code: "unsupported_display_node_mutation",
257
+ owners: ["core.transaction"],
258
+ remediation: unsupported
259
+ },
260
+ {
261
+ code: "unsupported_text_field_target",
262
+ owners: ["core.transaction"],
263
+ remediation: unsupported
264
+ },
265
+ {
266
+ code: "unsupported_display_node_field",
267
+ owners: ["core.transaction"],
268
+ remediation: unsupported
269
+ },
270
+ {
271
+ code: "unsupported_operation_batch",
272
+ owners: ["core.transaction"],
273
+ remediation: unsupported
274
+ },
275
+ {
276
+ code: "unsupported_resource_kind",
277
+ owners: ["core.transaction", "core.validation"],
278
+ remediation: unsupported
279
+ },
280
+ {
281
+ code: "invalid_project_settings",
282
+ owners: ["core.transaction"],
283
+ remediation: payload
284
+ },
285
+ {
286
+ code: "invalid_package_settings",
287
+ owners: ["core.transaction"],
288
+ remediation: payload
289
+ },
290
+ {
291
+ code: "invalid_display_node_payload",
292
+ owners: ["core.transaction"],
293
+ remediation: payload
294
+ },
295
+ {
296
+ code: "invalid_resource_name",
297
+ owners: ["core.transaction"],
298
+ remediation: payload
299
+ },
300
+ {
301
+ code: "invalid_resource_path",
302
+ owners: ["core.transaction"],
303
+ remediation: payload
304
+ },
305
+ {
306
+ code: "invalid_resource_folder_path",
307
+ owners: ["core.transaction"],
308
+ remediation: payload
309
+ },
310
+ {
311
+ code: "invalid_resource_folder_atlas",
312
+ owners: ["core.transaction"],
313
+ remediation: payload
314
+ },
315
+ {
316
+ code: "invalid_attach_index",
317
+ owners: ["core.transaction"],
318
+ remediation: payload
319
+ },
320
+ {
321
+ code: "invalid_controller_payload",
322
+ owners: ["core.transaction"],
323
+ remediation: payload
324
+ },
325
+ {
326
+ code: "invalid_transition_payload",
327
+ owners: ["core.transaction"],
328
+ remediation: payload
329
+ },
330
+ {
331
+ code: "invalid_look_gear_payload",
332
+ owners: ["core.transaction"],
333
+ remediation: payload
334
+ },
335
+ {
336
+ code: "invalid_gear_payload",
337
+ owners: ["core.transaction"],
338
+ remediation: payload
339
+ },
340
+ {
341
+ code: "invalid_resource_payload",
342
+ owners: ["core.transaction"],
343
+ remediation: payload
344
+ },
345
+ {
346
+ code: "invalid_resource_bytes",
347
+ owners: ["core.transaction"],
348
+ remediation: payload
349
+ },
350
+ {
351
+ code: "invalid_movie_clip_jta",
352
+ owners: ["core.transaction"],
353
+ remediation: payload
354
+ },
355
+ {
356
+ code: "invalid_resource_index",
357
+ owners: ["core.transaction"],
358
+ remediation: payload
359
+ },
360
+ {
361
+ code: "invalid_branch_name",
362
+ owners: ["core.transaction"],
363
+ remediation: payload
364
+ },
365
+ {
366
+ code: "invalid_package_payload",
367
+ owners: ["core.transaction"],
368
+ remediation: payload
369
+ },
370
+ {
371
+ code: "invalid_package_index",
372
+ owners: ["core.transaction"],
373
+ remediation: payload
374
+ },
375
+ {
376
+ code: "invalid_component_payload",
377
+ owners: ["core.transaction"],
378
+ remediation: payload
379
+ },
380
+ {
381
+ code: "invalid_component_index",
382
+ owners: ["core.transaction"],
383
+ remediation: payload
384
+ },
385
+ {
386
+ code: "invalid_component_move",
387
+ owners: ["core.transaction"],
388
+ remediation: payload
389
+ },
390
+ {
391
+ code: "invalid_uam",
392
+ owners: ["core.transaction", "core.validation"],
393
+ remediation: payload
394
+ },
395
+ {
396
+ code: "project_settings_unchanged",
397
+ owners: ["core.transaction"],
398
+ remediation: unchanged
399
+ },
400
+ {
401
+ code: "package_settings_unchanged",
402
+ owners: ["core.transaction"],
403
+ remediation: unchanged
404
+ },
405
+ {
406
+ code: "display_node_props_unchanged",
407
+ owners: ["core.transaction"],
408
+ remediation: unchanged
409
+ },
410
+ {
411
+ code: "resource_folder_atlas_unchanged",
412
+ owners: ["core.transaction"],
413
+ remediation: unchanged
414
+ },
415
+ {
416
+ code: "duplicate_look_gear_controller",
417
+ owners: ["core.transaction"],
418
+ remediation: duplicate
419
+ },
420
+ {
421
+ code: "duplicate_transition_name",
422
+ owners: ["core.transaction"],
423
+ remediation: duplicate
424
+ },
425
+ {
426
+ code: "duplicate_look_gear_state_page",
427
+ owners: ["core.transaction"],
428
+ remediation: duplicate
429
+ },
430
+ {
431
+ code: "duplicate_gear_controller",
432
+ owners: ["core.transaction"],
433
+ remediation: duplicate
434
+ },
435
+ {
436
+ code: "duplicate_gear_state_page",
437
+ owners: ["core.transaction"],
438
+ remediation: duplicate
439
+ },
440
+ {
441
+ code: "duplicate_branch_name",
442
+ owners: ["core.transaction"],
443
+ remediation: duplicate
444
+ },
445
+ {
446
+ code: "duplicate_component_id",
447
+ owners: ["core.transaction"],
448
+ remediation: duplicate
449
+ },
450
+ {
451
+ code: "resource_folder_conflict",
452
+ owners: ["core.transaction"],
453
+ remediation: duplicate
454
+ },
455
+ {
456
+ code: "duplicate_resource_id",
457
+ owners: ["core.transaction", "core.validation"],
458
+ remediation: duplicate
459
+ },
460
+ {
461
+ code: "duplicate_package_id",
462
+ owners: ["core.transaction", "core.validation"],
463
+ remediation: duplicate
464
+ },
465
+ {
466
+ code: "duplicate_package_name",
467
+ owners: ["core.transaction", "core.validation"],
468
+ remediation: duplicate
469
+ },
470
+ {
471
+ code: "resource_folder_not_empty",
472
+ owners: ["core.transaction"],
473
+ remediation: references
474
+ },
475
+ {
476
+ code: "branch_not_empty",
477
+ owners: ["core.transaction"],
478
+ remediation: references
479
+ },
480
+ {
481
+ code: "branch_referenced",
482
+ owners: ["core.transaction"],
483
+ remediation: references
484
+ },
485
+ {
486
+ code: "invalid_resource_reference",
487
+ owners: ["core.transaction"],
488
+ remediation: references
489
+ },
490
+ {
491
+ code: "invalid_component_reference",
492
+ owners: ["core.transaction"],
493
+ remediation: references
494
+ },
495
+ {
496
+ code: "invalid_group_reference",
497
+ owners: ["core.transaction"],
498
+ remediation: references
499
+ },
500
+ {
501
+ code: "package_referenced",
502
+ owners: ["core.transaction"],
503
+ remediation: references
504
+ },
505
+ {
506
+ code: "component_referenced",
507
+ owners: ["core.transaction"],
508
+ remediation: references
509
+ },
510
+ {
511
+ code: "component_has_package_dependencies",
512
+ owners: ["core.transaction"],
513
+ remediation: references
514
+ },
515
+ {
516
+ code: "dangling_resource_reference",
517
+ owners: ["core.validation"],
518
+ remediation: references
519
+ },
520
+ {
521
+ code: "invalid_project_xml",
522
+ owners: ["core.validation"],
523
+ remediation: project
524
+ },
525
+ {
526
+ code: "invalid_package_xml",
527
+ owners: ["core.validation"],
528
+ remediation: project
529
+ },
530
+ {
531
+ code: "invalid_branch_package_xml",
532
+ owners: ["core.validation"],
533
+ remediation: project
534
+ },
535
+ {
536
+ code: "invalid_component_xml",
537
+ owners: ["core.validation"],
538
+ remediation: project
539
+ },
540
+ {
541
+ code: "invalid_project_value",
542
+ owners: ["core.validation"],
543
+ remediation: project
544
+ },
545
+ {
546
+ code: "desktop_incompatible_geometry",
547
+ owners: ["core.validation"],
548
+ remediation: project
549
+ },
550
+ {
551
+ code: "invalid_settings_json",
552
+ owners: ["core.validation"],
553
+ remediation: project
554
+ },
555
+ {
556
+ code: "path_collision",
557
+ owners: ["core.validation"],
558
+ remediation: path
559
+ },
560
+ {
561
+ code: "unsafe_path",
562
+ owners: ["core.validation"],
563
+ remediation: path
564
+ },
565
+ {
566
+ code: "capability_unavailable",
567
+ owners: ["backend"],
568
+ remediation: capability
569
+ },
570
+ {
571
+ code: "uam_fidelity_unsupported",
572
+ owners: ["backend"],
573
+ remediation: capability
574
+ },
575
+ {
576
+ code: "save_partial_failure",
577
+ owners: ["backend"],
578
+ remediation: write
579
+ },
580
+ {
581
+ code: "write_failed",
582
+ owners: ["backend"],
583
+ remediation: write
584
+ },
585
+ {
586
+ code: "project_open_failed",
587
+ owners: ["backend"],
588
+ remediation: project
589
+ },
590
+ {
591
+ code: "materialize_validation_failed",
592
+ owners: ["backend"],
593
+ remediation: project
594
+ },
595
+ {
596
+ code: "execution_failure",
597
+ owners: ["core.transaction"],
598
+ remediation: execution
599
+ },
600
+ {
601
+ code: "cache_refresh_failed",
602
+ owners: ["backend"],
603
+ remediation: execution
604
+ },
605
+ {
606
+ code: "job_not_found",
607
+ owners: ["backend"],
608
+ remediation: job
609
+ },
610
+ {
611
+ code: "job_not_cancellable",
612
+ owners: ["backend"],
613
+ remediation: job
614
+ },
615
+ {
616
+ code: "job_cancelled",
617
+ owners: ["backend"],
618
+ remediation: job
619
+ }
620
+ ];
621
+ const BACKEND_DIAGNOSTICS_URI = "openfairygui://docs/diagnostics";
622
+ const BACKEND_DIAGNOSTIC_TEMPLATE = `${BACKEND_DIAGNOSTICS_URI}/{code}`;
623
+ function getBackendDiagnosticCatalog() {
624
+ return BACKEND_DIAGNOSTIC_GUIDES.map((guide) => ({
625
+ ...structuredClone(guide),
626
+ docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}`
627
+ }));
628
+ }
629
+ function getBackendDiagnosticGuide(code) {
630
+ const guide = getBackendDiagnosticCatalog().find((entry) => entry.code === code);
631
+ if (!guide) throw new RangeError(`No recovery guide for diagnostic: ${code}`);
632
+ return guide;
633
+ }
634
+ function enrichBackendDiagnostic(diagnostic, sessionId) {
635
+ const guide = BACKEND_DIAGNOSTIC_GUIDES.find((entry) => entry.code === diagnostic.code);
636
+ if (!guide) return { ...diagnostic };
637
+ return {
638
+ ...diagnostic,
639
+ owner: diagnostic.owner ?? guide.owners[0],
640
+ docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}`,
641
+ remediation: {
642
+ ...guide.remediation,
643
+ ...sessionId && guide.remediation.kind !== "host-action" ? { read: {
644
+ method: "getProjectOutline",
645
+ input: { sessionId }
646
+ } } : {}
647
+ }
648
+ };
649
+ }
650
+ //#endregion
15
651
  //#region src/path-policy.ts
16
652
  function normalizeComparablePath(value) {
17
653
  const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
@@ -105,10 +741,10 @@ function createMeta(stage, startedAt, options) {
105
741
  revision: options?.revision,
106
742
  durationMs: Math.max(0, Date.now() - startedAt),
107
743
  warnings: options?.warnings ?? [],
108
- diagnostics: options?.diagnostics ?? [],
744
+ diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
109
745
  stage,
110
746
  contractVersion: BACKEND_CONTRACT_VERSION,
111
- capabilitySchemaVersion: 3
747
+ capabilitySchemaVersion: 11
112
748
  };
113
749
  }
114
750
  function success(stage, startedAt, data, options) {
@@ -224,6 +860,268 @@ function createStaleWriteError(session, expectedRevision) {
224
860
  };
225
861
  }
226
862
  //#endregion
863
+ //#region src/runtime/contracts.ts
864
+ const BACKEND_ENTITY_QUERY_LIMITS = {
865
+ maxBytes: 262144,
866
+ maxDepth: 32,
867
+ maxNodes: 1e5
868
+ };
869
+ const BACKEND_SESSION_READ_LIMITS = {
870
+ model: {
871
+ maxBytes: 4194304,
872
+ maxDepth: 64,
873
+ maxNodes: 5e5
874
+ },
875
+ resourceBytes: 1048576
876
+ };
877
+ const BACKEND_TRANSACTION_PREVIEW_LIMITS = {
878
+ maxBytes: 262144,
879
+ maxEntries: 2e3
880
+ };
881
+ /** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
882
+ const BACKEND_RESOURCE_QUERY_FIELDS = [
883
+ "kind",
884
+ "id",
885
+ "name",
886
+ "path",
887
+ "exported",
888
+ "favorite",
889
+ "branch",
890
+ "branchItemIds",
891
+ "fileName",
892
+ "file",
893
+ "dimensions",
894
+ "image",
895
+ "movieClip"
896
+ ];
897
+ //#endregion
898
+ //#region src/services/capture-project.ts
899
+ function createCaptureFileSystem(files, directories) {
900
+ const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
901
+ return {
902
+ async readFile(filePath) {
903
+ const value = files.get(normalize(filePath));
904
+ if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
905
+ return value;
906
+ },
907
+ async readFileRaw(filePath) {
908
+ const value = files.get(normalize(filePath));
909
+ if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
910
+ return value.slice();
911
+ },
912
+ async writeFile(filePath, content) {
913
+ files.set(normalize(filePath), content);
914
+ },
915
+ async writeFileRaw(filePath, data) {
916
+ files.set(normalize(filePath), data.slice());
917
+ },
918
+ async mkdir(dirPath) {
919
+ directories.add(normalize(dirPath));
920
+ },
921
+ async readdir() {
922
+ return [];
923
+ },
924
+ async exists(filePath) {
925
+ return files.has(normalize(filePath));
926
+ },
927
+ join(...paths) {
928
+ return normalize(paths.filter(Boolean).join("/"));
929
+ },
930
+ dirname(filePath) {
931
+ const normalized = normalize(filePath);
932
+ const separator = normalized.lastIndexOf("/");
933
+ return separator < 0 ? "" : normalized.slice(0, separator);
934
+ },
935
+ async unlink(filePath) {
936
+ files.delete(normalize(filePath));
937
+ }
938
+ };
939
+ }
940
+ function capturedFilesEqual(left, right) {
941
+ if (left.size !== right.size) return false;
942
+ for (const [filePath, leftValue] of left) {
943
+ const rightValue = right.get(filePath);
944
+ if (typeof leftValue === "string") {
945
+ if (leftValue !== rightValue) return false;
946
+ continue;
947
+ }
948
+ if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
949
+ for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
950
+ }
951
+ return true;
952
+ }
953
+ function capturedDirectoriesEqual(left, right) {
954
+ return left.size === right.size && [...left].every((directory) => right.has(directory));
955
+ }
956
+ /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
957
+ async function captureProject(document, fairyFileName) {
958
+ const files = /* @__PURE__ */ new Map();
959
+ const directories = /* @__PURE__ */ new Set();
960
+ await new _openfairygui_core_project_io.ProjectWriter(createCaptureFileSystem(files, directories)).write(document, fairyFileName);
961
+ return {
962
+ files,
963
+ directories
964
+ };
965
+ }
966
+ //#endregion
967
+ //#region src/services/transaction-preview.ts
968
+ /** Keep child identities/order on their parent, and compare each child's own properties separately. */
969
+ function entities(project) {
970
+ const result = /* @__PURE__ */ new Map();
971
+ function add(target, properties) {
972
+ const key = JSON.stringify(target);
973
+ if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
974
+ result.set(key, {
975
+ target,
976
+ properties
977
+ });
978
+ }
979
+ const { packages, ...properties } = project;
980
+ add({ kind: "project" }, {
981
+ ...properties,
982
+ packages: packages.map((pkg) => pkg.id)
983
+ });
984
+ for (const { resources, ...pkg } of packages) {
985
+ const packageId = pkg.id;
986
+ add({
987
+ kind: "package",
988
+ selector: { packageId }
989
+ }, {
990
+ ...pkg,
991
+ resources: resources.map((resource) => resource.id)
992
+ });
993
+ for (const resource of resources) {
994
+ const resourceTarget = {
995
+ kind: "resource",
996
+ selector: {
997
+ packageId,
998
+ resourceId: resource.id
999
+ }
1000
+ };
1001
+ if (resource.kind !== "component") {
1002
+ add(resourceTarget, resource);
1003
+ continue;
1004
+ }
1005
+ const { component, ...resourceProperties } = resource;
1006
+ add(resourceTarget, resourceProperties);
1007
+ const { displayList, controllers, transitions, ...componentProperties } = component;
1008
+ const selector = {
1009
+ packageId,
1010
+ componentResourceId: resource.id
1011
+ };
1012
+ add({
1013
+ kind: "component",
1014
+ selector
1015
+ }, {
1016
+ ...componentProperties,
1017
+ displayList: displayList.map((node) => node.id),
1018
+ controllers: controllers.map((controller) => controller.name),
1019
+ transitions: transitions.map((transition) => transition.name)
1020
+ });
1021
+ for (const node of displayList) add({
1022
+ kind: "displayNode",
1023
+ selector: {
1024
+ ...selector,
1025
+ displayNodeId: node.id
1026
+ }
1027
+ }, node);
1028
+ for (const controller of controllers) add({
1029
+ kind: "controller",
1030
+ selector: {
1031
+ ...selector,
1032
+ controllerName: controller.name
1033
+ }
1034
+ }, controller);
1035
+ for (const transition of transitions) add({
1036
+ kind: "transition",
1037
+ selector: {
1038
+ ...selector,
1039
+ transitionName: transition.name
1040
+ }
1041
+ }, transition);
1042
+ }
1043
+ }
1044
+ return result;
1045
+ }
1046
+ function equal(left, right, depth = 0) {
1047
+ if (left === right) return true;
1048
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
1049
+ 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]);
1050
+ if (depth > 128) throw new Error("Preview property comparison exceeds the supported nesting depth.");
1051
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
1052
+ if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
1053
+ const a = left, b = right;
1054
+ const keys = Object.keys(a);
1055
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
1056
+ }
1057
+ var PreviewBudgetError = class extends Error {};
1058
+ /** No host filesystem, cache, event or session mutation is involved in the projection. */
1059
+ async function previewTransactionImpact(session, project, fileSystemAvailable) {
1060
+ const impact = {
1061
+ entities: [],
1062
+ files: []
1063
+ };
1064
+ const before = entities(session.project), after = entities(project);
1065
+ let entries = 0, bytes = 0;
1066
+ const encoder = new TextEncoder();
1067
+ function count(value) {
1068
+ bytes += encoder.encode(JSON.stringify(value)).byteLength;
1069
+ 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.");
1070
+ }
1071
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
1072
+ const previous = before.get(key), next = after.get(key);
1073
+ const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])].filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
1074
+ if (!fields.length && previous && next) continue;
1075
+ const change = {
1076
+ target: (next ?? previous).target,
1077
+ change: !previous ? "added" : !next ? "removed" : "updated",
1078
+ fields
1079
+ };
1080
+ count(change);
1081
+ impact.entities.push(change);
1082
+ }
1083
+ const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, "/").split("/").at(-1) : "Project.fairy";
1084
+ const [previousFiles, nextFiles] = await Promise.all([captureProject((0, _openfairygui_core_uam.materializeUamProject)(session.project), fairyFileName), captureProject((0, _openfairygui_core_uam.materializeUamProject)(project), fairyFileName)]);
1085
+ for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
1086
+ const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
1087
+ if (equal(previous, next)) continue;
1088
+ const change = {
1089
+ path,
1090
+ kind: "file",
1091
+ change: previous === void 0 ? "added" : next === void 0 ? "removed" : "updated"
1092
+ };
1093
+ count(change);
1094
+ impact.files.push(change);
1095
+ }
1096
+ for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
1097
+ if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
1098
+ const change = {
1099
+ path,
1100
+ kind: "directory",
1101
+ change: nextFiles.directories.has(path) ? "added" : "removed"
1102
+ };
1103
+ count(change);
1104
+ impact.files.push(change);
1105
+ }
1106
+ impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
1107
+ const preview = {
1108
+ sessionId: session.sessionId,
1109
+ baseRevision: session.revision,
1110
+ projectedRevision: session.revision + 1,
1111
+ mode: "execute-and-discard",
1112
+ impact,
1113
+ persistence: {
1114
+ requiredAfterApply: true,
1115
+ fileSystemAvailable,
1116
+ uamFidelity: session.uamFidelity,
1117
+ writeVerified: false,
1118
+ nextAction: session.uamFidelity === "unsupported" || !fileSystemAvailable ? "host-action" : session.fileSystem ? "saveSession" : "materializeSession"
1119
+ }
1120
+ };
1121
+ if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction preview exceeds the response byte budget.");
1122
+ return preview;
1123
+ }
1124
+ //#endregion
227
1125
  //#region src/services/authoring-service.ts
228
1126
  function sourceFileKey(source) {
229
1127
  return [
@@ -253,8 +1151,12 @@ function recordStaleProjectFiles(session, previousProject, nextProject) {
253
1151
  for (const directory of (0, _openfairygui_core_uam.staleBranchDirectories)(nextProject, previousProject)) session.pendingStaleBranchDirectories.delete(branchDirectoryKey(directory));
254
1152
  }
255
1153
  function toBackendDiagnostics(error) {
256
- return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({ ...diagnostic })) : [{
1154
+ return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({
1155
+ ...diagnostic,
1156
+ owner: "core.transaction"
1157
+ })) : [{
257
1158
  code: error.code,
1159
+ owner: "core.transaction",
258
1160
  message: error.message,
259
1161
  severity: "error",
260
1162
  operationKind: error.operationKind,
@@ -342,6 +1244,46 @@ var AuthoringService = class {
342
1244
  if (this.sessionOperations.get(sessionId) === tail) this.sessionOperations.delete(sessionId);
343
1245
  }
344
1246
  }
1247
+ async preflightTransaction(input) {
1248
+ const queuedInput = structuredClone(input);
1249
+ detachSharedByteViews(queuedInput);
1250
+ return this.runSessionExclusive(queuedInput.sessionId, async () => {
1251
+ const startedAt = Date.now();
1252
+ const session = this.context.sessions.get(queuedInput.sessionId);
1253
+ if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1254
+ const meta = {
1255
+ sessionId: session.sessionId,
1256
+ revision: session.revision
1257
+ };
1258
+ if (queuedInput.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, queuedInput.expectedRevision), toSessionSnapshot(session, this.context.capabilities), meta);
1259
+ const project = structuredClone(session.project);
1260
+ detachSharedByteViews(project);
1261
+ const result = await (0, _openfairygui_functions_uam.applyUamTransactionAppAsync)({
1262
+ project,
1263
+ operations: queuedInput.operations
1264
+ });
1265
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1266
+ if (!result.ok) return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
1267
+ ...meta,
1268
+ diagnostics: toBackendDiagnostics(result.error)
1269
+ });
1270
+ try {
1271
+ const preview = await previewTransactionImpact({
1272
+ ...session,
1273
+ project
1274
+ }, result.project, Boolean(session.fileSystem));
1275
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1276
+ return success("authoring", startedAt, preview, meta);
1277
+ } catch (error) {
1278
+ return failure("authoring", startedAt, {
1279
+ code: "transaction_preview_failed",
1280
+ sessionId: session.sessionId,
1281
+ reason: error instanceof PreviewBudgetError ? "response_budget_exceeded" : "projection_failed",
1282
+ message: error instanceof Error ? error.message : String(error)
1283
+ }, toSessionSnapshot(session, this.context.capabilities), meta);
1284
+ }
1285
+ });
1286
+ }
345
1287
  async applyTransaction(input) {
346
1288
  const queuedInput = structuredClone(input);
347
1289
  detachSharedByteViews(queuedInput);
@@ -421,7 +1363,7 @@ var AuthoringService = class {
421
1363
  const startedAt = Date.now();
422
1364
  const session = this.context.sessions.get(input.sessionId);
423
1365
  if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
424
- const fileSystem = session.fileSystem ?? input.fileSystem ?? this.context.fileSystem;
1366
+ const fileSystem = session.fileSystem ?? input.fileSystem;
425
1367
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("saveSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
426
1368
  sessionId: session.sessionId,
427
1369
  revision: session.revision
@@ -523,7 +1465,7 @@ var AuthoringService = class {
523
1465
  revision: session.revision
524
1466
  });
525
1467
  const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
526
- const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem ?? this.context.fileSystem;
1468
+ const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
527
1469
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("materializeSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
528
1470
  sessionId: session.sessionId,
529
1471
  revision: session.revision
@@ -749,7 +1691,7 @@ var EventService = class {
749
1691
  ...event,
750
1692
  sequence: this.context.nextEventSequence(),
751
1693
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
752
- diagnostics: event.diagnostics ?? []
1694
+ diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
753
1695
  };
754
1696
  const sessionId = event.sessionId;
755
1697
  if (!sessionId) return emitted;
@@ -1077,6 +2019,48 @@ var JobService = class {
1077
2019
  };
1078
2020
  //#endregion
1079
2021
  //#region src/services/read-service.ts
2022
+ /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
2023
+ function queryResponseProblem(value, limits = BACKEND_ENTITY_QUERY_LIMITS) {
2024
+ const pending = [{
2025
+ value,
2026
+ depth: 0
2027
+ }];
2028
+ let nodes = 0;
2029
+ let stringUnits = 0;
2030
+ while (pending.length) {
2031
+ const { value, depth } = pending.pop();
2032
+ if (++nodes > limits.maxNodes || depth > limits.maxDepth) return "response_budget_exceeded";
2033
+ if (typeof value === "string" && (stringUnits += value.length) > limits.maxBytes) return "response_budget_exceeded";
2034
+ if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") continue;
2035
+ if (typeof value === "number") {
2036
+ if (!Number.isFinite(value)) return "non_json_value";
2037
+ continue;
2038
+ }
2039
+ if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return "non_json_value";
2040
+ if (Array.isArray(value) && value.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
2041
+ const entries = Object.entries(value);
2042
+ if (entries.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
2043
+ for (const [key, child] of entries) {
2044
+ if (!Array.isArray(value) && (stringUnits += key.length) > limits.maxBytes) return "response_budget_exceeded";
2045
+ pending.push({
2046
+ value: child,
2047
+ depth: depth + 1
2048
+ });
2049
+ }
2050
+ }
2051
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limits.maxBytes) return "response_budget_exceeded";
2052
+ }
2053
+ function readFailure(startedAt, sessionId, reason, revision) {
2054
+ return failure("read", startedAt, {
2055
+ code: "session_read_failed",
2056
+ sessionId,
2057
+ reason,
2058
+ message: `Session read failed: ${reason}.`
2059
+ }, void 0, {
2060
+ sessionId,
2061
+ revision
2062
+ });
2063
+ }
1080
2064
  function toProjectOutline(session) {
1081
2065
  const project = session.project;
1082
2066
  return {
@@ -1144,6 +2128,195 @@ var ReadService = class {
1144
2128
  revision: session.revision
1145
2129
  });
1146
2130
  }
2131
+ queryEntity(input) {
2132
+ const startedAt = Date.now();
2133
+ const session = this.context.sessions.get(input.sessionId);
2134
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2135
+ const meta = {
2136
+ sessionId: session.sessionId,
2137
+ revision: session.revision
2138
+ };
2139
+ const reject = (reason) => failure("read", startedAt, {
2140
+ code: "entity_query_failed",
2141
+ sessionId: session.sessionId,
2142
+ reason,
2143
+ message: `Entity query failed: ${reason}.`
2144
+ }, void 0, meta);
2145
+ const target = input.target;
2146
+ if (!target || typeof target !== "object" || Array.isArray(target) || Object.keys(target).some((key) => key !== "kind" && key !== "selector")) return reject("invalid_query");
2147
+ const respond = (entity) => {
2148
+ const data = {
2149
+ ...meta,
2150
+ target,
2151
+ entity
2152
+ };
2153
+ const problem = queryResponseProblem(data);
2154
+ return problem ? reject(problem) : success("read", startedAt, structuredClone(data), meta);
2155
+ };
2156
+ if (target.kind === "project") {
2157
+ if (Object.hasOwn(target, "selector")) return reject("invalid_query");
2158
+ const { projectId, settings } = session.project;
2159
+ return respond({
2160
+ kind: "project",
2161
+ properties: {
2162
+ projectId,
2163
+ settings
2164
+ }
2165
+ });
2166
+ }
2167
+ const keys = target.kind === "package" ? ["packageId"] : target.kind === "resource" ? ["packageId", "resourceId"] : target.kind === "component" ? ["packageId", "componentResourceId"] : target.kind === "displayNode" ? [
2168
+ "packageId",
2169
+ "componentResourceId",
2170
+ "displayNodeId"
2171
+ ] : target.kind === "controller" ? [
2172
+ "packageId",
2173
+ "componentResourceId",
2174
+ "controllerName"
2175
+ ] : target.kind === "transition" ? [
2176
+ "packageId",
2177
+ "componentResourceId",
2178
+ "transitionName"
2179
+ ] : [];
2180
+ const selector = target.selector;
2181
+ 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");
2182
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2183
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2184
+ if (target.kind === "package") {
2185
+ const { id, name, compressPNG, jpegQuality, publish } = packages[0];
2186
+ return respond({
2187
+ kind: "package",
2188
+ properties: {
2189
+ id,
2190
+ name,
2191
+ settings: {
2192
+ compressPNG,
2193
+ jpegQuality,
2194
+ publish
2195
+ }
2196
+ }
2197
+ });
2198
+ }
2199
+ const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === "resource" ? selector.resourceId : selector.componentResourceId));
2200
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2201
+ const resource = resources[0];
2202
+ let entity;
2203
+ if (target.kind === "resource") {
2204
+ const record = resource;
2205
+ entity = {
2206
+ kind: "resource",
2207
+ properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS.filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]]))
2208
+ };
2209
+ } else {
2210
+ if (resource.kind !== "component") return reject("not_found");
2211
+ if (target.kind === "component") {
2212
+ const { size, properties, customData } = resource.component;
2213
+ entity = {
2214
+ kind: "component",
2215
+ properties: {
2216
+ size,
2217
+ properties,
2218
+ customData
2219
+ }
2220
+ };
2221
+ } else if (target.kind === "controller") {
2222
+ const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
2223
+ if (controllers.length !== 1) return reject(controllers.length ? "ambiguous" : "not_found");
2224
+ entity = {
2225
+ kind: "controller",
2226
+ properties: controllers[0]
2227
+ };
2228
+ } else if (target.kind === "transition") {
2229
+ const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
2230
+ if (transitions.length !== 1) return reject(transitions.length ? "ambiguous" : "not_found");
2231
+ entity = {
2232
+ kind: "transition",
2233
+ properties: transitions[0]
2234
+ };
2235
+ } else {
2236
+ const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
2237
+ if (nodes.length !== 1) return reject(nodes.length ? "ambiguous" : "not_found");
2238
+ entity = {
2239
+ kind: "displayNode",
2240
+ properties: nodes[0]
2241
+ };
2242
+ }
2243
+ }
2244
+ return respond(entity);
2245
+ }
2246
+ resolveReadSession(input, startedAt) {
2247
+ 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");
2248
+ const session = this.context.sessions.get(input.sessionId);
2249
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2250
+ const meta = {
2251
+ sessionId: session.sessionId,
2252
+ revision: session.revision
2253
+ };
2254
+ if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("read", startedAt, {
2255
+ code: "stale_read",
2256
+ sessionId: session.sessionId,
2257
+ expectedRevision: input.expectedRevision,
2258
+ actualRevision: session.revision,
2259
+ message: "The session edit revision changed. Restart the model and resource read."
2260
+ }, void 0, meta);
2261
+ return success("read", startedAt, session, meta);
2262
+ }
2263
+ readSessionState(input) {
2264
+ const startedAt = Date.now();
2265
+ const resolved = this.resolveReadSession(input, startedAt);
2266
+ if (!resolved.ok) return resolved;
2267
+ const session = resolved.data;
2268
+ const meta = {
2269
+ sessionId: session.sessionId,
2270
+ revision: session.revision
2271
+ };
2272
+ const data = {
2273
+ ...meta,
2274
+ dirty: session.dirty,
2275
+ lastSavedRevision: session.lastSavedRevision,
2276
+ uamFidelity: session.uamFidelity,
2277
+ readComplete: session.readComplete,
2278
+ readDiagnostics: session.readDiagnostics,
2279
+ project: {
2280
+ ...session.project,
2281
+ packages: session.project.packages.map((pkg) => ({
2282
+ ...pkg,
2283
+ resources: pkg.resources.map((resource) => {
2284
+ if (resource.kind === "component") return resource;
2285
+ const { sourceBytes: _sourceBytes, ...model } = resource;
2286
+ return model;
2287
+ })
2288
+ }))
2289
+ }
2290
+ };
2291
+ const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
2292
+ return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, structuredClone(data), meta);
2293
+ }
2294
+ readResourceBytes(input) {
2295
+ const startedAt = Date.now();
2296
+ const resolved = this.resolveReadSession(input, startedAt);
2297
+ if (!resolved.ok) return resolved;
2298
+ const session = resolved.data;
2299
+ const reject = (reason) => readFailure(startedAt, session.sessionId, reason, session.revision);
2300
+ const selector = input.selector;
2301
+ 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");
2302
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2303
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2304
+ const resources = packages[0].resources.filter((resource) => resource.id === selector.resourceId);
2305
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2306
+ const resource = resources[0];
2307
+ if (resource.kind === "component") return reject("unsupported_resource");
2308
+ if (!(resource.sourceBytes instanceof Uint8Array)) return reject("bytes_unavailable");
2309
+ if (resource.sourceBytes.byteLength > BACKEND_SESSION_READ_LIMITS.resourceBytes) return reject("response_budget_exceeded");
2310
+ const meta = {
2311
+ sessionId: session.sessionId,
2312
+ revision: session.revision
2313
+ };
2314
+ return success("read", startedAt, {
2315
+ ...meta,
2316
+ selector: { ...selector },
2317
+ sourceBytes: new Uint8Array(resource.sourceBytes)
2318
+ }, meta);
2319
+ }
1147
2320
  validateSession(input) {
1148
2321
  const startedAt = Date.now();
1149
2322
  const session = this.context.sessions.get(input.sessionId);
@@ -1160,7 +2333,8 @@ var ReadService = class {
1160
2333
  code,
1161
2334
  message,
1162
2335
  severity,
1163
- path
2336
+ path,
2337
+ owner: "core.validation"
1164
2338
  }))
1165
2339
  });
1166
2340
  }
@@ -1221,63 +2395,6 @@ function createProjectReaderFileSystem(fileSystem, projectRoot) {
1221
2395
  }
1222
2396
  };
1223
2397
  }
1224
- function createCaptureFileSystem(files, directories) {
1225
- const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
1226
- return {
1227
- async readFile(filePath) {
1228
- const value = files.get(normalize(filePath));
1229
- if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
1230
- return value;
1231
- },
1232
- async readFileRaw(filePath) {
1233
- const value = files.get(normalize(filePath));
1234
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
1235
- return value.slice();
1236
- },
1237
- async writeFile(filePath, content) {
1238
- files.set(normalize(filePath), content);
1239
- },
1240
- async writeFileRaw(filePath, data) {
1241
- files.set(normalize(filePath), data.slice());
1242
- },
1243
- async mkdir(dirPath) {
1244
- directories.add(normalize(dirPath));
1245
- },
1246
- async readdir() {
1247
- return [];
1248
- },
1249
- async exists(filePath) {
1250
- return files.has(normalize(filePath));
1251
- },
1252
- join(...paths) {
1253
- return normalize(paths.filter(Boolean).join("/"));
1254
- },
1255
- dirname(filePath) {
1256
- const normalized = normalize(filePath);
1257
- const separator = normalized.lastIndexOf("/");
1258
- return separator < 0 ? "" : normalized.slice(0, separator);
1259
- },
1260
- async unlink(filePath) {
1261
- files.delete(normalize(filePath));
1262
- }
1263
- };
1264
- }
1265
- function capturedFilesEqual(left, right) {
1266
- if (left.size !== right.size) return false;
1267
- for (const [filePath, leftValue] of left) {
1268
- const rightValue = right.get(filePath);
1269
- if (typeof leftValue === "string") {
1270
- if (leftValue !== rightValue) return false;
1271
- continue;
1272
- }
1273
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
1274
- for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
1275
- }
1276
- return true;
1277
- }
1278
- function capturedDirectoriesEqual(left, right) {
1279
- return left.size === right.size && [...left].every((directory) => right.has(directory));
1280
- }
1281
2398
  async function hasFullUamFidelity(document, project) {
1282
2399
  const sourceFiles = /* @__PURE__ */ new Map();
1283
2400
  const materializedFiles = /* @__PURE__ */ new Map();
@@ -1509,7 +2626,11 @@ const BACKEND_METHODS = [
1509
2626
  "openProjectSession",
1510
2627
  "getSession",
1511
2628
  "getProjectOutline",
2629
+ "queryEntity",
2630
+ "readSessionState",
2631
+ "readResourceBytes",
1512
2632
  "validateSession",
2633
+ "preflightTransaction",
1513
2634
  "applyTransaction",
1514
2635
  "saveSession",
1515
2636
  "materializeSession",
@@ -1531,7 +2652,7 @@ const ARTIFACT_BRIDGE_CAPABILITY = {
1531
2652
  function createCapabilities(atomicSave = false) {
1532
2653
  return {
1533
2654
  contractVersion: BACKEND_CONTRACT_VERSION,
1534
- capabilitySchemaVersion: 3,
2655
+ capabilitySchemaVersion: 11,
1535
2656
  transactionKernelOwner: "@openfairygui/core",
1536
2657
  appSeamOwner: "@openfairygui/functions",
1537
2658
  runtimeOwner: "@openfairygui/backend",
@@ -1540,9 +2661,38 @@ function createCapabilities(atomicSave = false) {
1540
2661
  capabilitySnapshot: true,
1541
2662
  sessionSnapshot: true,
1542
2663
  projectOutline: true,
2664
+ entityQuery: {
2665
+ kinds: [
2666
+ "project",
2667
+ "package",
2668
+ "resource",
2669
+ "component",
2670
+ "displayNode",
2671
+ "controller",
2672
+ "transition"
2673
+ ],
2674
+ projection: "properties",
2675
+ sourceBytes: false,
2676
+ limits: BACKEND_ENTITY_QUERY_LIMITS
2677
+ },
2678
+ sessionState: {
2679
+ sourceBytes: false,
2680
+ limits: BACKEND_SESSION_READ_LIMITS.model
2681
+ },
2682
+ resourceBytes: {
2683
+ expectedRevisionRequired: true,
2684
+ hydration: false,
2685
+ maxBytes: BACKEND_SESSION_READ_LIMITS.resourceBytes
2686
+ },
1543
2687
  projectValidation: true
1544
2688
  },
1545
2689
  authoring: {
2690
+ preflightTransaction: {
2691
+ mode: "execute-and-discard",
2692
+ reservesRevision: false,
2693
+ impact: "model-diff",
2694
+ limits: BACKEND_TRANSACTION_PREVIEW_LIMITS
2695
+ },
1546
2696
  applyTransaction: true,
1547
2697
  saveSession: true,
1548
2698
  resourceKinds: [..._openfairygui_core_uam.UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
@@ -1592,7 +2742,9 @@ function createCapabilities(atomicSave = false) {
1592
2742
  },
1593
2743
  diagnostics: {
1594
2744
  stableCodes: true,
1595
- errorDiagnosticMirror: true
2745
+ errorDiagnosticMirror: true,
2746
+ recoveryGuides: "all-formal-codes",
2747
+ automaticRepair: false
1596
2748
  }
1597
2749
  },
1598
2750
  compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
@@ -1693,9 +2845,21 @@ var BackendRuntime = class {
1693
2845
  getProjectOutline(input) {
1694
2846
  return this.readService.getProjectOutline(input);
1695
2847
  }
2848
+ queryEntity(input) {
2849
+ return this.readService.queryEntity(input);
2850
+ }
2851
+ readSessionState(input) {
2852
+ return this.readService.readSessionState(input);
2853
+ }
2854
+ readResourceBytes(input) {
2855
+ return this.readService.readResourceBytes(input);
2856
+ }
1696
2857
  validateSession(input) {
1697
2858
  return this.readService.validateSession(input);
1698
2859
  }
2860
+ async preflightTransaction(input) {
2861
+ return this.authoringService.preflightTransaction(input);
2862
+ }
1699
2863
  async applyTransaction(input) {
1700
2864
  return this.authoringService.applyTransaction(input);
1701
2865
  }
@@ -1901,5 +3065,12 @@ function createBackendStorageFileSystem(storage) {
1901
3065
  exports.BACKEND_CAPABILITY_SCHEMA_VERSION = BACKEND_CAPABILITY_SCHEMA_VERSION;
1902
3066
  exports.BACKEND_COMPATIBILITY_POLICY = BACKEND_COMPATIBILITY_POLICY;
1903
3067
  exports.BACKEND_CONTRACT_VERSION = BACKEND_CONTRACT_VERSION;
3068
+ exports.BACKEND_DIAGNOSTICS_URI = BACKEND_DIAGNOSTICS_URI;
3069
+ exports.BACKEND_DIAGNOSTIC_TEMPLATE = BACKEND_DIAGNOSTIC_TEMPLATE;
3070
+ exports.BACKEND_ENTITY_QUERY_LIMITS = BACKEND_ENTITY_QUERY_LIMITS;
3071
+ exports.BACKEND_SESSION_READ_LIMITS = BACKEND_SESSION_READ_LIMITS;
3072
+ exports.BACKEND_TRANSACTION_PREVIEW_LIMITS = BACKEND_TRANSACTION_PREVIEW_LIMITS;
1904
3073
  exports.BackendRuntime = BackendRuntime;
1905
3074
  exports.createBackendStorageFileSystem = createBackendStorageFileSystem;
3075
+ exports.getBackendDiagnosticCatalog = getBackendDiagnosticCatalog;
3076
+ exports.getBackendDiagnosticGuide = getBackendDiagnosticGuide;