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