@openfairygui/backend 0.3.0 → 0.4.0

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,634 @@ 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 = 10;
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: "transaction_preview_failed",
72
+ owners: ["backend"],
73
+ remediation: {
74
+ kind: "host-action",
75
+ 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."
76
+ }
77
+ },
78
+ {
79
+ code: "stale_write",
80
+ owners: ["backend"],
81
+ remediation: {
82
+ kind: "refresh-and-replan",
83
+ 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."
84
+ }
85
+ },
86
+ {
87
+ code: "entity_query_failed",
88
+ owners: ["backend"],
89
+ remediation: {
90
+ kind: "host-action",
91
+ 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."
92
+ }
93
+ },
94
+ {
95
+ code: "session_not_found",
96
+ owners: ["backend"],
97
+ remediation: {
98
+ kind: "host-action",
99
+ 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."
100
+ }
101
+ },
102
+ {
103
+ code: "path_policy_violation",
104
+ owners: ["backend"],
105
+ remediation: path
106
+ },
107
+ {
108
+ code: "project_root_not_allowed",
109
+ owners: ["backend"],
110
+ remediation: path
111
+ },
112
+ {
113
+ code: "invalid_package_selector",
114
+ owners: ["core.transaction"],
115
+ remediation: selector
116
+ },
117
+ {
118
+ code: "invalid_component_selector",
119
+ owners: ["core.transaction"],
120
+ remediation: selector
121
+ },
122
+ {
123
+ code: "invalid_resource_selector",
124
+ owners: ["core.transaction"],
125
+ remediation: selector
126
+ },
127
+ {
128
+ code: "invalid_display_node_selector",
129
+ owners: ["core.transaction"],
130
+ remediation: selector
131
+ },
132
+ {
133
+ code: "invalid_resource_folder_selector",
134
+ owners: ["core.transaction"],
135
+ remediation: selector
136
+ },
137
+ {
138
+ code: "invalid_branch_selector",
139
+ owners: ["core.transaction"],
140
+ remediation: selector
141
+ },
142
+ {
143
+ code: "invalid_gear_selector",
144
+ owners: ["core.transaction"],
145
+ remediation: selector
146
+ },
147
+ {
148
+ code: "invalid_look_gear_selector",
149
+ owners: ["core.transaction"],
150
+ remediation: selector
151
+ },
152
+ {
153
+ code: "selector_ambiguity",
154
+ owners: ["core.transaction"],
155
+ remediation: selector
156
+ },
157
+ {
158
+ code: "unavailable_resource_source_bytes",
159
+ owners: ["core.transaction"],
160
+ remediation: source
161
+ },
162
+ {
163
+ code: "missing_source",
164
+ owners: ["core.validation"],
165
+ remediation: source
166
+ },
167
+ {
168
+ code: "unreadable_source",
169
+ owners: ["core.validation"],
170
+ remediation: source
171
+ },
172
+ {
173
+ code: "decode_capability_unavailable",
174
+ owners: ["core.validation"],
175
+ remediation: {
176
+ kind: "host-action",
177
+ 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."
178
+ }
179
+ },
180
+ {
181
+ code: "session_id_conflict",
182
+ owners: ["backend"],
183
+ remediation: {
184
+ kind: "host-action",
185
+ 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."
186
+ }
187
+ },
188
+ {
189
+ code: "lock_conflict",
190
+ owners: ["backend"],
191
+ remediation: {
192
+ kind: "host-action",
193
+ 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."
194
+ }
195
+ },
196
+ {
197
+ code: "event_cursor_invalid",
198
+ owners: ["backend"],
199
+ remediation: {
200
+ kind: "refresh-and-replan",
201
+ 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."
202
+ }
203
+ },
204
+ {
205
+ code: "corrupt_source",
206
+ owners: ["core.validation"],
207
+ remediation: source
208
+ },
209
+ {
210
+ code: "unsupported_operation",
211
+ owners: ["core.transaction"],
212
+ remediation: unsupported
213
+ },
214
+ {
215
+ code: "transaction_unsupported",
216
+ owners: ["core.transaction"],
217
+ remediation: unsupported
218
+ },
219
+ {
220
+ code: "unsupported_display_node_kind",
221
+ owners: ["core.transaction"],
222
+ remediation: unsupported
223
+ },
224
+ {
225
+ code: "unsupported_cross_package_image_ref",
226
+ owners: ["core.transaction"],
227
+ remediation: unsupported
228
+ },
229
+ {
230
+ code: "unsupported_gear_kind",
231
+ owners: ["core.transaction"],
232
+ remediation: unsupported
233
+ },
234
+ {
235
+ code: "unsupported_resource_mutation",
236
+ owners: ["core.transaction"],
237
+ remediation: unsupported
238
+ },
239
+ {
240
+ code: "unsupported_display_node_mutation",
241
+ owners: ["core.transaction"],
242
+ remediation: unsupported
243
+ },
244
+ {
245
+ code: "unsupported_text_field_target",
246
+ owners: ["core.transaction"],
247
+ remediation: unsupported
248
+ },
249
+ {
250
+ code: "unsupported_display_node_field",
251
+ owners: ["core.transaction"],
252
+ remediation: unsupported
253
+ },
254
+ {
255
+ code: "unsupported_operation_batch",
256
+ owners: ["core.transaction"],
257
+ remediation: unsupported
258
+ },
259
+ {
260
+ code: "unsupported_resource_kind",
261
+ owners: ["core.transaction", "core.validation"],
262
+ remediation: unsupported
263
+ },
264
+ {
265
+ code: "invalid_project_settings",
266
+ owners: ["core.transaction"],
267
+ remediation: payload
268
+ },
269
+ {
270
+ code: "invalid_package_settings",
271
+ owners: ["core.transaction"],
272
+ remediation: payload
273
+ },
274
+ {
275
+ code: "invalid_display_node_payload",
276
+ owners: ["core.transaction"],
277
+ remediation: payload
278
+ },
279
+ {
280
+ code: "invalid_resource_name",
281
+ owners: ["core.transaction"],
282
+ remediation: payload
283
+ },
284
+ {
285
+ code: "invalid_resource_path",
286
+ owners: ["core.transaction"],
287
+ remediation: payload
288
+ },
289
+ {
290
+ code: "invalid_resource_folder_path",
291
+ owners: ["core.transaction"],
292
+ remediation: payload
293
+ },
294
+ {
295
+ code: "invalid_resource_folder_atlas",
296
+ owners: ["core.transaction"],
297
+ remediation: payload
298
+ },
299
+ {
300
+ code: "invalid_attach_index",
301
+ owners: ["core.transaction"],
302
+ remediation: payload
303
+ },
304
+ {
305
+ code: "invalid_controller_payload",
306
+ owners: ["core.transaction"],
307
+ remediation: payload
308
+ },
309
+ {
310
+ code: "invalid_transition_payload",
311
+ owners: ["core.transaction"],
312
+ remediation: payload
313
+ },
314
+ {
315
+ code: "invalid_look_gear_payload",
316
+ owners: ["core.transaction"],
317
+ remediation: payload
318
+ },
319
+ {
320
+ code: "invalid_gear_payload",
321
+ owners: ["core.transaction"],
322
+ remediation: payload
323
+ },
324
+ {
325
+ code: "invalid_resource_payload",
326
+ owners: ["core.transaction"],
327
+ remediation: payload
328
+ },
329
+ {
330
+ code: "invalid_resource_bytes",
331
+ owners: ["core.transaction"],
332
+ remediation: payload
333
+ },
334
+ {
335
+ code: "invalid_movie_clip_jta",
336
+ owners: ["core.transaction"],
337
+ remediation: payload
338
+ },
339
+ {
340
+ code: "invalid_resource_index",
341
+ owners: ["core.transaction"],
342
+ remediation: payload
343
+ },
344
+ {
345
+ code: "invalid_branch_name",
346
+ owners: ["core.transaction"],
347
+ remediation: payload
348
+ },
349
+ {
350
+ code: "invalid_package_payload",
351
+ owners: ["core.transaction"],
352
+ remediation: payload
353
+ },
354
+ {
355
+ code: "invalid_package_index",
356
+ owners: ["core.transaction"],
357
+ remediation: payload
358
+ },
359
+ {
360
+ code: "invalid_component_payload",
361
+ owners: ["core.transaction"],
362
+ remediation: payload
363
+ },
364
+ {
365
+ code: "invalid_component_index",
366
+ owners: ["core.transaction"],
367
+ remediation: payload
368
+ },
369
+ {
370
+ code: "invalid_component_move",
371
+ owners: ["core.transaction"],
372
+ remediation: payload
373
+ },
374
+ {
375
+ code: "invalid_uam",
376
+ owners: ["core.transaction", "core.validation"],
377
+ remediation: payload
378
+ },
379
+ {
380
+ code: "project_settings_unchanged",
381
+ owners: ["core.transaction"],
382
+ remediation: unchanged
383
+ },
384
+ {
385
+ code: "package_settings_unchanged",
386
+ owners: ["core.transaction"],
387
+ remediation: unchanged
388
+ },
389
+ {
390
+ code: "display_node_props_unchanged",
391
+ owners: ["core.transaction"],
392
+ remediation: unchanged
393
+ },
394
+ {
395
+ code: "resource_folder_atlas_unchanged",
396
+ owners: ["core.transaction"],
397
+ remediation: unchanged
398
+ },
399
+ {
400
+ code: "duplicate_look_gear_controller",
401
+ owners: ["core.transaction"],
402
+ remediation: duplicate
403
+ },
404
+ {
405
+ code: "duplicate_transition_name",
406
+ owners: ["core.transaction"],
407
+ remediation: duplicate
408
+ },
409
+ {
410
+ code: "duplicate_look_gear_state_page",
411
+ owners: ["core.transaction"],
412
+ remediation: duplicate
413
+ },
414
+ {
415
+ code: "duplicate_gear_controller",
416
+ owners: ["core.transaction"],
417
+ remediation: duplicate
418
+ },
419
+ {
420
+ code: "duplicate_gear_state_page",
421
+ owners: ["core.transaction"],
422
+ remediation: duplicate
423
+ },
424
+ {
425
+ code: "duplicate_branch_name",
426
+ owners: ["core.transaction"],
427
+ remediation: duplicate
428
+ },
429
+ {
430
+ code: "duplicate_component_id",
431
+ owners: ["core.transaction"],
432
+ remediation: duplicate
433
+ },
434
+ {
435
+ code: "resource_folder_conflict",
436
+ owners: ["core.transaction"],
437
+ remediation: duplicate
438
+ },
439
+ {
440
+ code: "duplicate_resource_id",
441
+ owners: ["core.transaction", "core.validation"],
442
+ remediation: duplicate
443
+ },
444
+ {
445
+ code: "duplicate_package_id",
446
+ owners: ["core.transaction", "core.validation"],
447
+ remediation: duplicate
448
+ },
449
+ {
450
+ code: "duplicate_package_name",
451
+ owners: ["core.transaction", "core.validation"],
452
+ remediation: duplicate
453
+ },
454
+ {
455
+ code: "resource_folder_not_empty",
456
+ owners: ["core.transaction"],
457
+ remediation: references
458
+ },
459
+ {
460
+ code: "branch_not_empty",
461
+ owners: ["core.transaction"],
462
+ remediation: references
463
+ },
464
+ {
465
+ code: "branch_referenced",
466
+ owners: ["core.transaction"],
467
+ remediation: references
468
+ },
469
+ {
470
+ code: "invalid_resource_reference",
471
+ owners: ["core.transaction"],
472
+ remediation: references
473
+ },
474
+ {
475
+ code: "invalid_component_reference",
476
+ owners: ["core.transaction"],
477
+ remediation: references
478
+ },
479
+ {
480
+ code: "invalid_group_reference",
481
+ owners: ["core.transaction"],
482
+ remediation: references
483
+ },
484
+ {
485
+ code: "package_referenced",
486
+ owners: ["core.transaction"],
487
+ remediation: references
488
+ },
489
+ {
490
+ code: "component_referenced",
491
+ owners: ["core.transaction"],
492
+ remediation: references
493
+ },
494
+ {
495
+ code: "component_has_package_dependencies",
496
+ owners: ["core.transaction"],
497
+ remediation: references
498
+ },
499
+ {
500
+ code: "dangling_resource_reference",
501
+ owners: ["core.validation"],
502
+ remediation: references
503
+ },
504
+ {
505
+ code: "invalid_project_xml",
506
+ owners: ["core.validation"],
507
+ remediation: project
508
+ },
509
+ {
510
+ code: "invalid_package_xml",
511
+ owners: ["core.validation"],
512
+ remediation: project
513
+ },
514
+ {
515
+ code: "invalid_branch_package_xml",
516
+ owners: ["core.validation"],
517
+ remediation: project
518
+ },
519
+ {
520
+ code: "invalid_component_xml",
521
+ owners: ["core.validation"],
522
+ remediation: project
523
+ },
524
+ {
525
+ code: "invalid_project_value",
526
+ owners: ["core.validation"],
527
+ remediation: project
528
+ },
529
+ {
530
+ code: "desktop_incompatible_geometry",
531
+ owners: ["core.validation"],
532
+ remediation: project
533
+ },
534
+ {
535
+ code: "invalid_settings_json",
536
+ owners: ["core.validation"],
537
+ remediation: project
538
+ },
539
+ {
540
+ code: "path_collision",
541
+ owners: ["core.validation"],
542
+ remediation: path
543
+ },
544
+ {
545
+ code: "unsafe_path",
546
+ owners: ["core.validation"],
547
+ remediation: path
548
+ },
549
+ {
550
+ code: "capability_unavailable",
551
+ owners: ["backend"],
552
+ remediation: capability
553
+ },
554
+ {
555
+ code: "uam_fidelity_unsupported",
556
+ owners: ["backend"],
557
+ remediation: capability
558
+ },
559
+ {
560
+ code: "save_partial_failure",
561
+ owners: ["backend"],
562
+ remediation: write
563
+ },
564
+ {
565
+ code: "write_failed",
566
+ owners: ["backend"],
567
+ remediation: write
568
+ },
569
+ {
570
+ code: "project_open_failed",
571
+ owners: ["backend"],
572
+ remediation: project
573
+ },
574
+ {
575
+ code: "materialize_validation_failed",
576
+ owners: ["backend"],
577
+ remediation: project
578
+ },
579
+ {
580
+ code: "execution_failure",
581
+ owners: ["core.transaction"],
582
+ remediation: execution
583
+ },
584
+ {
585
+ code: "cache_refresh_failed",
586
+ owners: ["backend"],
587
+ remediation: execution
588
+ },
589
+ {
590
+ code: "job_not_found",
591
+ owners: ["backend"],
592
+ remediation: job
593
+ },
594
+ {
595
+ code: "job_not_cancellable",
596
+ owners: ["backend"],
597
+ remediation: job
598
+ },
599
+ {
600
+ code: "job_cancelled",
601
+ owners: ["backend"],
602
+ remediation: job
603
+ }
604
+ ];
605
+ const BACKEND_DIAGNOSTICS_URI = "openfairygui://docs/diagnostics";
606
+ const BACKEND_DIAGNOSTIC_TEMPLATE = `${BACKEND_DIAGNOSTICS_URI}/{code}`;
607
+ function getBackendDiagnosticCatalog() {
608
+ return BACKEND_DIAGNOSTIC_GUIDES.map((guide) => ({
609
+ ...structuredClone(guide),
610
+ docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}`
611
+ }));
612
+ }
613
+ function getBackendDiagnosticGuide(code) {
614
+ const guide = getBackendDiagnosticCatalog().find((entry) => entry.code === code);
615
+ if (!guide) throw new RangeError(`No recovery guide for diagnostic: ${code}`);
616
+ return guide;
617
+ }
618
+ function enrichBackendDiagnostic(diagnostic, sessionId) {
619
+ const guide = BACKEND_DIAGNOSTIC_GUIDES.find((entry) => entry.code === diagnostic.code);
620
+ if (!guide) return { ...diagnostic };
621
+ return {
622
+ ...diagnostic,
623
+ owner: diagnostic.owner ?? guide.owners[0],
624
+ docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}`,
625
+ remediation: {
626
+ ...guide.remediation,
627
+ ...sessionId && guide.remediation.kind !== "host-action" ? { read: {
628
+ method: "getProjectOutline",
629
+ input: { sessionId }
630
+ } } : {}
631
+ }
632
+ };
633
+ }
634
+ //#endregion
15
635
  //#region src/path-policy.ts
16
636
  function normalizeComparablePath(value) {
17
637
  const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
@@ -42,6 +662,16 @@ function createRuntimePathPolicy() {
42
662
  workspaceBoundary: "project-root-only"
43
663
  };
44
664
  }
665
+ async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
666
+ const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
667
+ const root = normalizeComparablePath(resolvedRoot);
668
+ const target = normalizeComparablePath(resolvedTarget);
669
+ if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
670
+ if (target === root || target.startsWith(`${root}/`)) return;
671
+ const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
672
+ error.code = "EACCES";
673
+ throw error;
674
+ }
45
675
  async function resolveFairyPath(fileSystem, input) {
46
676
  const resolvedInput = fileSystem.resolve(input);
47
677
  const stat = await fileSystem.stat(resolvedInput);
@@ -95,10 +725,10 @@ function createMeta(stage, startedAt, options) {
95
725
  revision: options?.revision,
96
726
  durationMs: Math.max(0, Date.now() - startedAt),
97
727
  warnings: options?.warnings ?? [],
98
- diagnostics: options?.diagnostics ?? [],
728
+ diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
99
729
  stage,
100
730
  contractVersion: BACKEND_CONTRACT_VERSION,
101
- capabilitySchemaVersion: 3
731
+ capabilitySchemaVersion: 10
102
732
  };
103
733
  }
104
734
  function success(stage, startedAt, data, options) {
@@ -122,10 +752,14 @@ function failure(stage, startedAt, error, session, options) {
122
752
  }
123
753
  //#endregion
124
754
  //#region src/services/session-project-writer.ts
125
- function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
755
+ function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
756
+ const contained = async (targetPath, operation) => {
757
+ await assertProjectPathContained(fileSystem, projectRoot, targetPath);
758
+ return operation();
759
+ };
126
760
  async function trackWrite(targetPath, write) {
127
761
  try {
128
- const result = await write();
762
+ const result = await contained(targetPath, write);
129
763
  writtenPaths.push(targetPath);
130
764
  return result;
131
765
  } catch (error) {
@@ -134,8 +768,8 @@ function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
134
768
  }
135
769
  }
136
770
  return {
137
- readFile: (path) => fileSystem.readFile(path),
138
- readFileRaw: (path) => fileSystem.readFileRaw(path),
771
+ readFile: (path) => contained(path, () => fileSystem.readFile(path)),
772
+ readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
139
773
  writeFile: (path, content) => trackWrite(path, async () => {
140
774
  await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
141
775
  await fileSystem.writeFile(path, content);
@@ -144,9 +778,10 @@ function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
144
778
  await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
145
779
  await fileSystem.writeFileRaw(path, data);
146
780
  }),
147
- mkdir: (path) => fileSystem.mkdir(path, { recursive: true }),
148
- readdir: (path) => fileSystem.readdir(path),
781
+ mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
782
+ readdir: (path) => contained(path, () => fileSystem.readdir(path)),
149
783
  async exists(path) {
784
+ await assertProjectPathContained(fileSystem, projectRoot, path);
150
785
  try {
151
786
  await fileSystem.stat(path);
152
787
  return true;
@@ -161,11 +796,21 @@ function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
161
796
  };
162
797
  }
163
798
  async function writeSessionProject(input) {
164
- await new _openfairygui_core_project_io.ProjectWriter(createWriterFileSystem(input.fileSystem, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
165
- staleSourceFiles: input.staleSourceFiles,
166
- staleResourceFolders: input.staleResourceFolders,
167
- staleBranchDirectories: input.staleBranchDirectories
168
- });
799
+ const projectRoot = input.fileSystem.dirname(input.fairyPath);
800
+ const write = async (fileSystem) => {
801
+ await new _openfairygui_core_project_io.ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
802
+ staleSourceFiles: input.staleSourceFiles,
803
+ staleResourceFolders: input.staleResourceFolders,
804
+ staleBranchDirectories: input.staleBranchDirectories
805
+ });
806
+ };
807
+ if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
808
+ try {
809
+ await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
810
+ } catch (error) {
811
+ input.writtenPaths.length = 0;
812
+ throw error;
813
+ }
169
814
  }
170
815
  //#endregion
171
816
  //#region src/services/session-utils.ts
@@ -199,6 +844,260 @@ function createStaleWriteError(session, expectedRevision) {
199
844
  };
200
845
  }
201
846
  //#endregion
847
+ //#region src/runtime/contracts.ts
848
+ const BACKEND_ENTITY_QUERY_LIMITS = {
849
+ maxBytes: 262144,
850
+ maxDepth: 32,
851
+ maxNodes: 1e5
852
+ };
853
+ const BACKEND_TRANSACTION_PREVIEW_LIMITS = {
854
+ maxBytes: 262144,
855
+ maxEntries: 2e3
856
+ };
857
+ /** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
858
+ const BACKEND_RESOURCE_QUERY_FIELDS = [
859
+ "kind",
860
+ "id",
861
+ "name",
862
+ "path",
863
+ "exported",
864
+ "favorite",
865
+ "branch",
866
+ "branchItemIds",
867
+ "fileName",
868
+ "file",
869
+ "dimensions",
870
+ "image",
871
+ "movieClip"
872
+ ];
873
+ //#endregion
874
+ //#region src/services/capture-project.ts
875
+ function createCaptureFileSystem(files, directories) {
876
+ const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
877
+ return {
878
+ async readFile(filePath) {
879
+ const value = files.get(normalize(filePath));
880
+ if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
881
+ return value;
882
+ },
883
+ async readFileRaw(filePath) {
884
+ const value = files.get(normalize(filePath));
885
+ if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
886
+ return value.slice();
887
+ },
888
+ async writeFile(filePath, content) {
889
+ files.set(normalize(filePath), content);
890
+ },
891
+ async writeFileRaw(filePath, data) {
892
+ files.set(normalize(filePath), data.slice());
893
+ },
894
+ async mkdir(dirPath) {
895
+ directories.add(normalize(dirPath));
896
+ },
897
+ async readdir() {
898
+ return [];
899
+ },
900
+ async exists(filePath) {
901
+ return files.has(normalize(filePath));
902
+ },
903
+ join(...paths) {
904
+ return normalize(paths.filter(Boolean).join("/"));
905
+ },
906
+ dirname(filePath) {
907
+ const normalized = normalize(filePath);
908
+ const separator = normalized.lastIndexOf("/");
909
+ return separator < 0 ? "" : normalized.slice(0, separator);
910
+ },
911
+ async unlink(filePath) {
912
+ files.delete(normalize(filePath));
913
+ }
914
+ };
915
+ }
916
+ function capturedFilesEqual(left, right) {
917
+ if (left.size !== right.size) return false;
918
+ for (const [filePath, leftValue] of left) {
919
+ const rightValue = right.get(filePath);
920
+ if (typeof leftValue === "string") {
921
+ if (leftValue !== rightValue) return false;
922
+ continue;
923
+ }
924
+ if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
925
+ for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
926
+ }
927
+ return true;
928
+ }
929
+ function capturedDirectoriesEqual(left, right) {
930
+ return left.size === right.size && [...left].every((directory) => right.has(directory));
931
+ }
932
+ /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
933
+ async function captureProject(document, fairyFileName) {
934
+ const files = /* @__PURE__ */ new Map();
935
+ const directories = /* @__PURE__ */ new Set();
936
+ await new _openfairygui_core_project_io.ProjectWriter(createCaptureFileSystem(files, directories)).write(document, fairyFileName);
937
+ return {
938
+ files,
939
+ directories
940
+ };
941
+ }
942
+ //#endregion
943
+ //#region src/services/transaction-preview.ts
944
+ /** Keep child identities/order on their parent, and compare each child's own properties separately. */
945
+ function entities(project) {
946
+ const result = /* @__PURE__ */ new Map();
947
+ function add(target, properties) {
948
+ const key = JSON.stringify(target);
949
+ if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
950
+ result.set(key, {
951
+ target,
952
+ properties
953
+ });
954
+ }
955
+ const { packages, ...properties } = project;
956
+ add({ kind: "project" }, {
957
+ ...properties,
958
+ packages: packages.map((pkg) => pkg.id)
959
+ });
960
+ for (const { resources, ...pkg } of packages) {
961
+ const packageId = pkg.id;
962
+ add({
963
+ kind: "package",
964
+ selector: { packageId }
965
+ }, {
966
+ ...pkg,
967
+ resources: resources.map((resource) => resource.id)
968
+ });
969
+ for (const resource of resources) {
970
+ const resourceTarget = {
971
+ kind: "resource",
972
+ selector: {
973
+ packageId,
974
+ resourceId: resource.id
975
+ }
976
+ };
977
+ if (resource.kind !== "component") {
978
+ add(resourceTarget, resource);
979
+ continue;
980
+ }
981
+ const { component, ...resourceProperties } = resource;
982
+ add(resourceTarget, resourceProperties);
983
+ const { displayList, controllers, transitions, ...componentProperties } = component;
984
+ const selector = {
985
+ packageId,
986
+ componentResourceId: resource.id
987
+ };
988
+ add({
989
+ kind: "component",
990
+ selector
991
+ }, {
992
+ ...componentProperties,
993
+ displayList: displayList.map((node) => node.id),
994
+ controllers: controllers.map((controller) => controller.name),
995
+ transitions: transitions.map((transition) => transition.name)
996
+ });
997
+ for (const node of displayList) add({
998
+ kind: "displayNode",
999
+ selector: {
1000
+ ...selector,
1001
+ displayNodeId: node.id
1002
+ }
1003
+ }, node);
1004
+ for (const controller of controllers) add({
1005
+ kind: "controller",
1006
+ selector: {
1007
+ ...selector,
1008
+ controllerName: controller.name
1009
+ }
1010
+ }, controller);
1011
+ for (const transition of transitions) add({
1012
+ kind: "transition",
1013
+ selector: {
1014
+ ...selector,
1015
+ transitionName: transition.name
1016
+ }
1017
+ }, transition);
1018
+ }
1019
+ }
1020
+ return result;
1021
+ }
1022
+ function equal(left, right, depth = 0) {
1023
+ if (left === right) return true;
1024
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
1025
+ 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]);
1026
+ if (depth > 128) throw new Error("Preview property comparison exceeds the supported nesting depth.");
1027
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
1028
+ if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
1029
+ const a = left, b = right;
1030
+ const keys = Object.keys(a);
1031
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
1032
+ }
1033
+ var PreviewBudgetError = class extends Error {};
1034
+ /** No host filesystem, cache, event or session mutation is involved in the projection. */
1035
+ async function previewTransactionImpact(session, project, fileSystemAvailable) {
1036
+ const impact = {
1037
+ entities: [],
1038
+ files: []
1039
+ };
1040
+ const before = entities(session.project), after = entities(project);
1041
+ let entries = 0, bytes = 0;
1042
+ const encoder = new TextEncoder();
1043
+ function count(value) {
1044
+ bytes += encoder.encode(JSON.stringify(value)).byteLength;
1045
+ 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.");
1046
+ }
1047
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
1048
+ const previous = before.get(key), next = after.get(key);
1049
+ const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])].filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
1050
+ if (!fields.length && previous && next) continue;
1051
+ const change = {
1052
+ target: (next ?? previous).target,
1053
+ change: !previous ? "added" : !next ? "removed" : "updated",
1054
+ fields
1055
+ };
1056
+ count(change);
1057
+ impact.entities.push(change);
1058
+ }
1059
+ const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, "/").split("/").at(-1) : "Project.fairy";
1060
+ const [previousFiles, nextFiles] = await Promise.all([captureProject((0, _openfairygui_core_uam.materializeUamProject)(session.project), fairyFileName), captureProject((0, _openfairygui_core_uam.materializeUamProject)(project), fairyFileName)]);
1061
+ for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
1062
+ const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
1063
+ if (equal(previous, next)) continue;
1064
+ const change = {
1065
+ path,
1066
+ kind: "file",
1067
+ change: previous === void 0 ? "added" : next === void 0 ? "removed" : "updated"
1068
+ };
1069
+ count(change);
1070
+ impact.files.push(change);
1071
+ }
1072
+ for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
1073
+ if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
1074
+ const change = {
1075
+ path,
1076
+ kind: "directory",
1077
+ change: nextFiles.directories.has(path) ? "added" : "removed"
1078
+ };
1079
+ count(change);
1080
+ impact.files.push(change);
1081
+ }
1082
+ impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
1083
+ const preview = {
1084
+ sessionId: session.sessionId,
1085
+ baseRevision: session.revision,
1086
+ projectedRevision: session.revision + 1,
1087
+ mode: "execute-and-discard",
1088
+ impact,
1089
+ persistence: {
1090
+ requiredAfterApply: true,
1091
+ fileSystemAvailable,
1092
+ uamFidelity: session.uamFidelity,
1093
+ writeVerified: false,
1094
+ nextAction: session.uamFidelity === "unsupported" || !fileSystemAvailable ? "host-action" : session.fileSystem ? "saveSession" : "materializeSession"
1095
+ }
1096
+ };
1097
+ if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction preview exceeds the response byte budget.");
1098
+ return preview;
1099
+ }
1100
+ //#endregion
202
1101
  //#region src/services/authoring-service.ts
203
1102
  function sourceFileKey(source) {
204
1103
  return [
@@ -228,8 +1127,12 @@ function recordStaleProjectFiles(session, previousProject, nextProject) {
228
1127
  for (const directory of (0, _openfairygui_core_uam.staleBranchDirectories)(nextProject, previousProject)) session.pendingStaleBranchDirectories.delete(branchDirectoryKey(directory));
229
1128
  }
230
1129
  function toBackendDiagnostics(error) {
231
- return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({ ...diagnostic })) : [{
1130
+ return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({
1131
+ ...diagnostic,
1132
+ owner: "core.transaction"
1133
+ })) : [{
232
1134
  code: error.code,
1135
+ owner: "core.transaction",
233
1136
  message: error.message,
234
1137
  severity: "error",
235
1138
  operationKind: error.operationKind,
@@ -317,6 +1220,46 @@ var AuthoringService = class {
317
1220
  if (this.sessionOperations.get(sessionId) === tail) this.sessionOperations.delete(sessionId);
318
1221
  }
319
1222
  }
1223
+ async preflightTransaction(input) {
1224
+ const queuedInput = structuredClone(input);
1225
+ detachSharedByteViews(queuedInput);
1226
+ return this.runSessionExclusive(queuedInput.sessionId, async () => {
1227
+ const startedAt = Date.now();
1228
+ const session = this.context.sessions.get(queuedInput.sessionId);
1229
+ if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1230
+ const meta = {
1231
+ sessionId: session.sessionId,
1232
+ revision: session.revision
1233
+ };
1234
+ if (queuedInput.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, queuedInput.expectedRevision), toSessionSnapshot(session, this.context.capabilities), meta);
1235
+ const project = structuredClone(session.project);
1236
+ detachSharedByteViews(project);
1237
+ const result = await (0, _openfairygui_functions_uam.applyUamTransactionAppAsync)({
1238
+ project,
1239
+ operations: queuedInput.operations
1240
+ });
1241
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1242
+ if (!result.ok) return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
1243
+ ...meta,
1244
+ diagnostics: toBackendDiagnostics(result.error)
1245
+ });
1246
+ try {
1247
+ const preview = await previewTransactionImpact({
1248
+ ...session,
1249
+ project
1250
+ }, result.project, Boolean(session.fileSystem));
1251
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1252
+ return success("authoring", startedAt, preview, meta);
1253
+ } catch (error) {
1254
+ return failure("authoring", startedAt, {
1255
+ code: "transaction_preview_failed",
1256
+ sessionId: session.sessionId,
1257
+ reason: error instanceof PreviewBudgetError ? "response_budget_exceeded" : "projection_failed",
1258
+ message: error instanceof Error ? error.message : String(error)
1259
+ }, toSessionSnapshot(session, this.context.capabilities), meta);
1260
+ }
1261
+ });
1262
+ }
320
1263
  async applyTransaction(input) {
321
1264
  const queuedInput = structuredClone(input);
322
1265
  detachSharedByteViews(queuedInput);
@@ -396,7 +1339,7 @@ var AuthoringService = class {
396
1339
  const startedAt = Date.now();
397
1340
  const session = this.context.sessions.get(input.sessionId);
398
1341
  if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
399
- const fileSystem = session.fileSystem ?? input.fileSystem ?? this.context.fileSystem;
1342
+ const fileSystem = session.fileSystem ?? input.fileSystem;
400
1343
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("saveSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
401
1344
  sessionId: session.sessionId,
402
1345
  revision: session.revision
@@ -479,7 +1422,7 @@ var AuthoringService = class {
479
1422
  lastSavedRevision: session.lastSavedRevision,
480
1423
  committedPaths,
481
1424
  failedPaths,
482
- diskMayBePartiallyUpdated: true
1425
+ diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
483
1426
  }, toSessionSnapshot(session, this.context.capabilities), {
484
1427
  sessionId: session.sessionId,
485
1428
  revision: session.revision
@@ -498,7 +1441,7 @@ var AuthoringService = class {
498
1441
  revision: session.revision
499
1442
  });
500
1443
  const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
501
- const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem ?? this.context.fileSystem;
1444
+ const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
502
1445
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("materializeSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
503
1446
  sessionId: session.sessionId,
504
1447
  revision: session.revision
@@ -654,7 +1597,7 @@ var AuthoringService = class {
654
1597
  failedPaths,
655
1598
  skippedPaths,
656
1599
  diagnostics: diagnosticsFromError,
657
- diskMayBePartiallyUpdated: true
1600
+ diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
658
1601
  }, toSessionSnapshot(session, this.context.capabilities), {
659
1602
  sessionId: session.sessionId,
660
1603
  revision: session.revision,
@@ -724,7 +1667,7 @@ var EventService = class {
724
1667
  ...event,
725
1668
  sequence: this.context.nextEventSequence(),
726
1669
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
727
- diagnostics: event.diagnostics ?? []
1670
+ diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
728
1671
  };
729
1672
  const sessionId = event.sessionId;
730
1673
  if (!sessionId) return emitted;
@@ -1052,6 +1995,37 @@ var JobService = class {
1052
1995
  };
1053
1996
  //#endregion
1054
1997
  //#region src/services/read-service.ts
1998
+ /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
1999
+ function queryResponseProblem(value) {
2000
+ const pending = [{
2001
+ value,
2002
+ depth: 0
2003
+ }];
2004
+ let nodes = 0;
2005
+ let stringUnits = 0;
2006
+ while (pending.length) {
2007
+ const { value, depth } = pending.pop();
2008
+ if (++nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes || depth > BACKEND_ENTITY_QUERY_LIMITS.maxDepth) return "response_budget_exceeded";
2009
+ if (typeof value === "string" && (stringUnits += value.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return "response_budget_exceeded";
2010
+ if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") continue;
2011
+ if (typeof value === "number") {
2012
+ if (!Number.isFinite(value)) return "non_json_value";
2013
+ continue;
2014
+ }
2015
+ if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return "non_json_value";
2016
+ if (Array.isArray(value) && value.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return "response_budget_exceeded";
2017
+ const entries = Object.entries(value);
2018
+ if (entries.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return "response_budget_exceeded";
2019
+ for (const [key, child] of entries) {
2020
+ if (!Array.isArray(value) && (stringUnits += key.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return "response_budget_exceeded";
2021
+ pending.push({
2022
+ value: child,
2023
+ depth: depth + 1
2024
+ });
2025
+ }
2026
+ }
2027
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return "response_budget_exceeded";
2028
+ }
1055
2029
  function toProjectOutline(session) {
1056
2030
  const project = session.project;
1057
2031
  return {
@@ -1119,6 +2093,121 @@ var ReadService = class {
1119
2093
  revision: session.revision
1120
2094
  });
1121
2095
  }
2096
+ queryEntity(input) {
2097
+ const startedAt = Date.now();
2098
+ const session = this.context.sessions.get(input.sessionId);
2099
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2100
+ const meta = {
2101
+ sessionId: session.sessionId,
2102
+ revision: session.revision
2103
+ };
2104
+ const reject = (reason) => failure("read", startedAt, {
2105
+ code: "entity_query_failed",
2106
+ sessionId: session.sessionId,
2107
+ reason,
2108
+ message: `Entity query failed: ${reason}.`
2109
+ }, void 0, meta);
2110
+ const target = input.target;
2111
+ if (!target || typeof target !== "object" || Array.isArray(target) || Object.keys(target).some((key) => key !== "kind" && key !== "selector")) return reject("invalid_query");
2112
+ const respond = (entity) => {
2113
+ const data = {
2114
+ ...meta,
2115
+ target,
2116
+ entity
2117
+ };
2118
+ const problem = queryResponseProblem(data);
2119
+ return problem ? reject(problem) : success("read", startedAt, structuredClone(data), meta);
2120
+ };
2121
+ if (target.kind === "project") {
2122
+ if (Object.hasOwn(target, "selector")) return reject("invalid_query");
2123
+ const { projectId, settings } = session.project;
2124
+ return respond({
2125
+ kind: "project",
2126
+ properties: {
2127
+ projectId,
2128
+ settings
2129
+ }
2130
+ });
2131
+ }
2132
+ const keys = target.kind === "package" ? ["packageId"] : target.kind === "resource" ? ["packageId", "resourceId"] : target.kind === "component" ? ["packageId", "componentResourceId"] : target.kind === "displayNode" ? [
2133
+ "packageId",
2134
+ "componentResourceId",
2135
+ "displayNodeId"
2136
+ ] : target.kind === "controller" ? [
2137
+ "packageId",
2138
+ "componentResourceId",
2139
+ "controllerName"
2140
+ ] : target.kind === "transition" ? [
2141
+ "packageId",
2142
+ "componentResourceId",
2143
+ "transitionName"
2144
+ ] : [];
2145
+ const selector = target.selector;
2146
+ 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");
2147
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2148
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2149
+ if (target.kind === "package") {
2150
+ const { id, name, compressPNG, jpegQuality, publish } = packages[0];
2151
+ return respond({
2152
+ kind: "package",
2153
+ properties: {
2154
+ id,
2155
+ name,
2156
+ settings: {
2157
+ compressPNG,
2158
+ jpegQuality,
2159
+ publish
2160
+ }
2161
+ }
2162
+ });
2163
+ }
2164
+ const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === "resource" ? selector.resourceId : selector.componentResourceId));
2165
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2166
+ const resource = resources[0];
2167
+ let entity;
2168
+ if (target.kind === "resource") {
2169
+ const record = resource;
2170
+ entity = {
2171
+ kind: "resource",
2172
+ properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS.filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]]))
2173
+ };
2174
+ } else {
2175
+ if (resource.kind !== "component") return reject("not_found");
2176
+ if (target.kind === "component") {
2177
+ const { size, properties, customData } = resource.component;
2178
+ entity = {
2179
+ kind: "component",
2180
+ properties: {
2181
+ size,
2182
+ properties,
2183
+ customData
2184
+ }
2185
+ };
2186
+ } else if (target.kind === "controller") {
2187
+ const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
2188
+ if (controllers.length !== 1) return reject(controllers.length ? "ambiguous" : "not_found");
2189
+ entity = {
2190
+ kind: "controller",
2191
+ properties: controllers[0]
2192
+ };
2193
+ } else if (target.kind === "transition") {
2194
+ const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
2195
+ if (transitions.length !== 1) return reject(transitions.length ? "ambiguous" : "not_found");
2196
+ entity = {
2197
+ kind: "transition",
2198
+ properties: transitions[0]
2199
+ };
2200
+ } else {
2201
+ const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
2202
+ if (nodes.length !== 1) return reject(nodes.length ? "ambiguous" : "not_found");
2203
+ entity = {
2204
+ kind: "displayNode",
2205
+ properties: nodes[0]
2206
+ };
2207
+ }
2208
+ }
2209
+ return respond(entity);
2210
+ }
1122
2211
  validateSession(input) {
1123
2212
  const startedAt = Date.now();
1124
2213
  const session = this.context.sessions.get(input.sessionId);
@@ -1135,7 +2224,8 @@ var ReadService = class {
1135
2224
  code,
1136
2225
  message,
1137
2226
  severity,
1138
- path
2227
+ path,
2228
+ owner: "core.validation"
1139
2229
  }))
1140
2230
  });
1141
2231
  }
@@ -1143,7 +2233,7 @@ var ReadService = class {
1143
2233
  //#endregion
1144
2234
  //#region src/services/runtime-service.ts
1145
2235
  function randomId() {
1146
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
2236
+ return crypto.randomUUID();
1147
2237
  }
1148
2238
  function createCapabilityUnavailableError(capability) {
1149
2239
  const artifactCapability = capability === "artifact.publish" || capability === "artifact.restore";
@@ -1156,29 +2246,33 @@ function createCapabilityUnavailableError(capability) {
1156
2246
  bridgeBoundary: artifactCapability ? "external-bridge" : void 0
1157
2247
  };
1158
2248
  }
1159
- function createProjectReaderFileSystem(fileSystem) {
2249
+ function createProjectReaderFileSystem(fileSystem, projectRoot) {
2250
+ const contained = async (filePath, operation) => {
2251
+ await assertProjectPathContained(fileSystem, projectRoot, filePath);
2252
+ return operation();
2253
+ };
1160
2254
  return {
1161
2255
  readFile(filePath) {
1162
- return fileSystem.readFile(filePath);
2256
+ return contained(filePath, () => fileSystem.readFile(filePath));
1163
2257
  },
1164
2258
  readFileRaw(filePath) {
1165
- return fileSystem.readFileRaw(filePath);
2259
+ return contained(filePath, () => fileSystem.readFileRaw(filePath));
1166
2260
  },
1167
2261
  writeFile(filePath, content) {
1168
- return fileSystem.writeFile(filePath, content);
2262
+ return contained(filePath, () => fileSystem.writeFile(filePath, content));
1169
2263
  },
1170
2264
  writeFileRaw(filePath, data) {
1171
- return fileSystem.writeFileRaw(filePath, data);
2265
+ return contained(filePath, () => fileSystem.writeFileRaw(filePath, data));
1172
2266
  },
1173
2267
  async mkdir(dirPath) {
1174
- await fileSystem.mkdir(dirPath, { recursive: true });
2268
+ await contained(dirPath, () => fileSystem.mkdir(dirPath, { recursive: true }));
1175
2269
  },
1176
2270
  readdir(dirPath) {
1177
- return fileSystem.readdir(dirPath);
2271
+ return contained(dirPath, () => fileSystem.readdir(dirPath));
1178
2272
  },
1179
2273
  async exists(filePath) {
1180
2274
  try {
1181
- await fileSystem.stat(filePath);
2275
+ await contained(filePath, () => fileSystem.stat(filePath));
1182
2276
  return true;
1183
2277
  } catch {
1184
2278
  return false;
@@ -1192,63 +2286,6 @@ function createProjectReaderFileSystem(fileSystem) {
1192
2286
  }
1193
2287
  };
1194
2288
  }
1195
- function createCaptureFileSystem(files, directories) {
1196
- const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
1197
- return {
1198
- async readFile(filePath) {
1199
- const value = files.get(normalize(filePath));
1200
- if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
1201
- return value;
1202
- },
1203
- async readFileRaw(filePath) {
1204
- const value = files.get(normalize(filePath));
1205
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
1206
- return value.slice();
1207
- },
1208
- async writeFile(filePath, content) {
1209
- files.set(normalize(filePath), content);
1210
- },
1211
- async writeFileRaw(filePath, data) {
1212
- files.set(normalize(filePath), data.slice());
1213
- },
1214
- async mkdir(dirPath) {
1215
- directories.add(normalize(dirPath));
1216
- },
1217
- async readdir() {
1218
- return [];
1219
- },
1220
- async exists(filePath) {
1221
- return files.has(normalize(filePath));
1222
- },
1223
- join(...paths) {
1224
- return normalize(paths.filter(Boolean).join("/"));
1225
- },
1226
- dirname(filePath) {
1227
- const normalized = normalize(filePath);
1228
- const separator = normalized.lastIndexOf("/");
1229
- return separator < 0 ? "" : normalized.slice(0, separator);
1230
- },
1231
- async unlink(filePath) {
1232
- files.delete(normalize(filePath));
1233
- }
1234
- };
1235
- }
1236
- function capturedFilesEqual(left, right) {
1237
- if (left.size !== right.size) return false;
1238
- for (const [filePath, leftValue] of left) {
1239
- const rightValue = right.get(filePath);
1240
- if (typeof leftValue === "string") {
1241
- if (leftValue !== rightValue) return false;
1242
- continue;
1243
- }
1244
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
1245
- for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
1246
- }
1247
- return true;
1248
- }
1249
- function capturedDirectoriesEqual(left, right) {
1250
- return left.size === right.size && [...left].every((directory) => right.has(directory));
1251
- }
1252
2289
  async function hasFullUamFidelity(document, project) {
1253
2290
  const sourceFiles = /* @__PURE__ */ new Map();
1254
2291
  const materializedFiles = /* @__PURE__ */ new Map();
@@ -1272,9 +2309,25 @@ var RuntimeService = class {
1272
2309
  const startedAt = Date.now();
1273
2310
  if (!this.context.fileSystem) return failure("runtime", startedAt, createCapabilityUnavailableError("fileSystem"));
1274
2311
  const fileSystem = this.context.fileSystem;
2312
+ if (this.context.allowedProjectRoots?.length) {
2313
+ let allowed = false;
2314
+ for (const root of this.context.allowedProjectRoots) try {
2315
+ await assertProjectPathContained(fileSystem, root, input.projectPath);
2316
+ allowed = true;
2317
+ break;
2318
+ } catch (error) {
2319
+ if (error.code !== "EACCES") throw error;
2320
+ }
2321
+ if (!allowed) return failure("runtime", startedAt, {
2322
+ code: "project_root_not_allowed",
2323
+ message: "Project path is outside the configured allowed roots.",
2324
+ projectPath: input.projectPath
2325
+ });
2326
+ }
1275
2327
  const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
2328
+ await fileSystem.validateProjectRoot?.(canonicalProjectPath);
1276
2329
  const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
1277
- const lockFilePath = fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
2330
+ const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath) ?? fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
1278
2331
  if (existingSessionId) return failure("runtime", startedAt, {
1279
2332
  code: "lock_conflict",
1280
2333
  kind: "in_process_session_exists",
@@ -1294,7 +2347,7 @@ var RuntimeService = class {
1294
2347
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1295
2348
  canonicalPathKey
1296
2349
  }));
1297
- const read = await new _openfairygui_core_project_io.ProjectReader(createProjectReaderFileSystem(fileSystem)).readDetailed(fairyPath, { hydrateResourceBytes: true });
2350
+ const read = await new _openfairygui_core_project_io.ProjectReader(createProjectReaderFileSystem(fileSystem, canonicalProjectPath)).readDetailed(fairyPath, { hydrateResourceBytes: true });
1298
2351
  if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
1299
2352
  const document = read.document;
1300
2353
  const project = (0, _openfairygui_core_uam.liftDocumentToUamProject)(document);
@@ -1352,6 +2405,11 @@ var RuntimeService = class {
1352
2405
  openProjectSession(input) {
1353
2406
  const startedAt = Date.now();
1354
2407
  const sessionId = input.sessionId ?? randomId();
2408
+ if (this.context.sessions.has(sessionId)) return failure("runtime", startedAt, {
2409
+ code: "session_id_conflict",
2410
+ message: `Session id is already in use: ${sessionId}`,
2411
+ sessionId
2412
+ });
1355
2413
  const storage = input.storage;
1356
2414
  const memoryProjectPath = `memory://${sessionId}`;
1357
2415
  const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
@@ -1459,7 +2517,9 @@ const BACKEND_METHODS = [
1459
2517
  "openProjectSession",
1460
2518
  "getSession",
1461
2519
  "getProjectOutline",
2520
+ "queryEntity",
1462
2521
  "validateSession",
2522
+ "preflightTransaction",
1463
2523
  "applyTransaction",
1464
2524
  "saveSession",
1465
2525
  "materializeSession",
@@ -1478,10 +2538,10 @@ const ARTIFACT_BRIDGE_CAPABILITY = {
1478
2538
  bridgeEntrypoint: "@openfairygui/backend/node",
1479
2539
  reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
1480
2540
  };
1481
- function createCapabilities() {
2541
+ function createCapabilities(atomicSave = false) {
1482
2542
  return {
1483
2543
  contractVersion: BACKEND_CONTRACT_VERSION,
1484
- capabilitySchemaVersion: 3,
2544
+ capabilitySchemaVersion: 10,
1485
2545
  transactionKernelOwner: "@openfairygui/core",
1486
2546
  appSeamOwner: "@openfairygui/functions",
1487
2547
  runtimeOwner: "@openfairygui/backend",
@@ -1490,9 +2550,29 @@ function createCapabilities() {
1490
2550
  capabilitySnapshot: true,
1491
2551
  sessionSnapshot: true,
1492
2552
  projectOutline: true,
2553
+ entityQuery: {
2554
+ kinds: [
2555
+ "project",
2556
+ "package",
2557
+ "resource",
2558
+ "component",
2559
+ "displayNode",
2560
+ "controller",
2561
+ "transition"
2562
+ ],
2563
+ projection: "properties",
2564
+ sourceBytes: false,
2565
+ limits: BACKEND_ENTITY_QUERY_LIMITS
2566
+ },
1493
2567
  projectValidation: true
1494
2568
  },
1495
2569
  authoring: {
2570
+ preflightTransaction: {
2571
+ mode: "execute-and-discard",
2572
+ reservesRevision: false,
2573
+ impact: "model-diff",
2574
+ limits: BACKEND_TRANSACTION_PREVIEW_LIMITS
2575
+ },
1496
2576
  applyTransaction: true,
1497
2577
  saveSession: true,
1498
2578
  resourceKinds: [..._openfairygui_core_uam.UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
@@ -1542,7 +2622,9 @@ function createCapabilities() {
1542
2622
  },
1543
2623
  diagnostics: {
1544
2624
  stableCodes: true,
1545
- errorDiagnosticMirror: true
2625
+ errorDiagnosticMirror: true,
2626
+ recoveryGuides: "all-formal-codes",
2627
+ automaticRepair: false
1546
2628
  }
1547
2629
  },
1548
2630
  compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
@@ -1550,7 +2632,7 @@ function createCapabilities() {
1550
2632
  sessionRuntime: true,
1551
2633
  advisoryLocking: true,
1552
2634
  coordinatedSave: true,
1553
- atomicSave: false,
2635
+ atomicSave,
1554
2636
  staleRevisionProtection: true,
1555
2637
  pathPolicy: createRuntimePathPolicy(),
1556
2638
  events: {
@@ -1596,10 +2678,11 @@ var BackendRuntime = class {
1596
2678
  jobService;
1597
2679
  constructor(options = {}) {
1598
2680
  this.fileSystem = options.fileSystem;
1599
- this.capabilities = createCapabilities();
2681
+ this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
1600
2682
  this.context = {
1601
2683
  fileSystem: this.fileSystem,
1602
2684
  host: options.host,
2685
+ allowedProjectRoots: options.allowedProjectRoots,
1603
2686
  capabilities: this.capabilities,
1604
2687
  sessions: this.sessions,
1605
2688
  sessionsByPath: this.sessionsByPath,
@@ -1622,7 +2705,16 @@ var BackendRuntime = class {
1622
2705
  return this.readService.getCapabilities();
1623
2706
  }
1624
2707
  async openSession(input) {
1625
- return this.runtimeService.openSession(input);
2708
+ const startedAt = Date.now();
2709
+ try {
2710
+ return await this.runtimeService.openSession(input);
2711
+ } catch {
2712
+ return failure("runtime", startedAt, {
2713
+ code: "project_open_failed",
2714
+ message: "Unable to open project.",
2715
+ projectPath: input.projectPath
2716
+ });
2717
+ }
1626
2718
  }
1627
2719
  openProjectSession(input) {
1628
2720
  return this.runtimeService.openProjectSession(input);
@@ -1633,9 +2725,15 @@ var BackendRuntime = class {
1633
2725
  getProjectOutline(input) {
1634
2726
  return this.readService.getProjectOutline(input);
1635
2727
  }
2728
+ queryEntity(input) {
2729
+ return this.readService.queryEntity(input);
2730
+ }
1636
2731
  validateSession(input) {
1637
2732
  return this.readService.validateSession(input);
1638
2733
  }
2734
+ async preflightTransaction(input) {
2735
+ return this.authoringService.preflightTransaction(input);
2736
+ }
1639
2737
  async applyTransaction(input) {
1640
2738
  return this.authoringService.applyTransaction(input);
1641
2739
  }
@@ -1646,7 +2744,7 @@ var BackendRuntime = class {
1646
2744
  return this.authoringService.materializeSession(input);
1647
2745
  }
1648
2746
  async closeSession(input) {
1649
- return this.runtimeService.closeSession(input);
2747
+ return this.authoringService.runSessionExclusive(input.sessionId, () => this.runtimeService.closeSession(input));
1650
2748
  }
1651
2749
  getEvents(input) {
1652
2750
  return this.eventService.getEvents(input);
@@ -1841,5 +2939,11 @@ function createBackendStorageFileSystem(storage) {
1841
2939
  exports.BACKEND_CAPABILITY_SCHEMA_VERSION = BACKEND_CAPABILITY_SCHEMA_VERSION;
1842
2940
  exports.BACKEND_COMPATIBILITY_POLICY = BACKEND_COMPATIBILITY_POLICY;
1843
2941
  exports.BACKEND_CONTRACT_VERSION = BACKEND_CONTRACT_VERSION;
2942
+ exports.BACKEND_DIAGNOSTICS_URI = BACKEND_DIAGNOSTICS_URI;
2943
+ exports.BACKEND_DIAGNOSTIC_TEMPLATE = BACKEND_DIAGNOSTIC_TEMPLATE;
2944
+ exports.BACKEND_ENTITY_QUERY_LIMITS = BACKEND_ENTITY_QUERY_LIMITS;
2945
+ exports.BACKEND_TRANSACTION_PREVIEW_LIMITS = BACKEND_TRANSACTION_PREVIEW_LIMITS;
1844
2946
  exports.BackendRuntime = BackendRuntime;
1845
2947
  exports.createBackendStorageFileSystem = createBackendStorageFileSystem;
2948
+ exports.getBackendDiagnosticCatalog = getBackendDiagnosticCatalog;
2949
+ exports.getBackendDiagnosticGuide = getBackendDiagnosticGuide;