@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/node.cjs CHANGED
@@ -23,8 +23,11 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  //#endregion
24
24
  let node_fs_promises = require("node:fs/promises");
25
25
  node_fs_promises = __toESM(node_fs_promises);
26
+ let node_os = require("node:os");
27
+ node_os = __toESM(node_os);
26
28
  let node_path = require("node:path");
27
29
  node_path = __toESM(node_path);
30
+ let node_crypto = require("node:crypto");
28
31
  let _openfairygui_core_uam = require("@openfairygui/core/uam");
29
32
  let _openfairygui_functions_uam = require("@openfairygui/functions/uam");
30
33
  let _openfairygui_core_project_io = require("@openfairygui/core/project-io");
@@ -59,6 +62,16 @@ function createRuntimePathPolicy() {
59
62
  workspaceBoundary: "project-root-only"
60
63
  };
61
64
  }
65
+ async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
66
+ const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
67
+ const root = normalizeComparablePath(resolvedRoot);
68
+ const target = normalizeComparablePath(resolvedTarget);
69
+ if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
70
+ if (target === root || target.startsWith(`${root}/`)) return;
71
+ const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
72
+ error.code = "EACCES";
73
+ throw error;
74
+ }
62
75
  async function resolveFairyPath(fileSystem, input) {
63
76
  const resolvedInput = fileSystem.resolve(input);
64
77
  const stat = await fileSystem.stat(resolvedInput);
@@ -95,13 +108,622 @@ async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
95
108
  }
96
109
  //#endregion
97
110
  //#region src/contracts.ts
98
- const BACKEND_CONTRACT_VERSION = "1.1.0-p2";
111
+ const BACKEND_CONTRACT_VERSION = "2.0.0-p2";
99
112
  const BACKEND_COMPATIBILITY_POLICY = {
100
113
  incompatibleChange: "requires contractVersion bump",
101
114
  capabilitySchemaChange: "requires capabilitySchemaVersion bump",
102
115
  additiveChange: "allowed without breaking existing consumers"
103
116
  };
104
117
  //#endregion
118
+ //#region src/diagnostics.ts
119
+ const selector = {
120
+ kind: "revise-selector",
121
+ 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."
122
+ };
123
+ const source = {
124
+ kind: "host-action",
125
+ 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."
126
+ };
127
+ const path$1 = {
128
+ kind: "host-action",
129
+ 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."
130
+ };
131
+ const unsupported = {
132
+ kind: "revise-operation",
133
+ 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."
134
+ };
135
+ const payload = {
136
+ kind: "revise-operation",
137
+ 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."
138
+ };
139
+ const unchanged = {
140
+ kind: "refresh-and-replan",
141
+ 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."
142
+ };
143
+ const duplicate = {
144
+ kind: "revise-operation",
145
+ 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."
146
+ };
147
+ const references = {
148
+ kind: "revise-operation",
149
+ 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."
150
+ };
151
+ const project = {
152
+ kind: "host-action",
153
+ 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."
154
+ };
155
+ const capability = {
156
+ kind: "host-action",
157
+ 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."
158
+ };
159
+ const write = {
160
+ kind: "host-action",
161
+ 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."
162
+ };
163
+ const execution = {
164
+ kind: "host-action",
165
+ 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."
166
+ };
167
+ const job = {
168
+ kind: "host-action",
169
+ 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."
170
+ };
171
+ /** Exhaustiveness and exact ownership are checked against the canonical unions. */
172
+ const BACKEND_DIAGNOSTIC_GUIDES = [
173
+ {
174
+ code: "transaction_preview_failed",
175
+ owners: ["backend"],
176
+ remediation: {
177
+ kind: "host-action",
178
+ 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."
179
+ }
180
+ },
181
+ {
182
+ code: "stale_write",
183
+ owners: ["backend"],
184
+ remediation: {
185
+ kind: "refresh-and-replan",
186
+ 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."
187
+ }
188
+ },
189
+ {
190
+ code: "entity_query_failed",
191
+ owners: ["backend"],
192
+ remediation: {
193
+ kind: "host-action",
194
+ 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."
195
+ }
196
+ },
197
+ {
198
+ code: "session_not_found",
199
+ owners: ["backend"],
200
+ remediation: {
201
+ kind: "host-action",
202
+ 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."
203
+ }
204
+ },
205
+ {
206
+ code: "path_policy_violation",
207
+ owners: ["backend"],
208
+ remediation: path$1
209
+ },
210
+ {
211
+ code: "project_root_not_allowed",
212
+ owners: ["backend"],
213
+ remediation: path$1
214
+ },
215
+ {
216
+ code: "invalid_package_selector",
217
+ owners: ["core.transaction"],
218
+ remediation: selector
219
+ },
220
+ {
221
+ code: "invalid_component_selector",
222
+ owners: ["core.transaction"],
223
+ remediation: selector
224
+ },
225
+ {
226
+ code: "invalid_resource_selector",
227
+ owners: ["core.transaction"],
228
+ remediation: selector
229
+ },
230
+ {
231
+ code: "invalid_display_node_selector",
232
+ owners: ["core.transaction"],
233
+ remediation: selector
234
+ },
235
+ {
236
+ code: "invalid_resource_folder_selector",
237
+ owners: ["core.transaction"],
238
+ remediation: selector
239
+ },
240
+ {
241
+ code: "invalid_branch_selector",
242
+ owners: ["core.transaction"],
243
+ remediation: selector
244
+ },
245
+ {
246
+ code: "invalid_gear_selector",
247
+ owners: ["core.transaction"],
248
+ remediation: selector
249
+ },
250
+ {
251
+ code: "invalid_look_gear_selector",
252
+ owners: ["core.transaction"],
253
+ remediation: selector
254
+ },
255
+ {
256
+ code: "selector_ambiguity",
257
+ owners: ["core.transaction"],
258
+ remediation: selector
259
+ },
260
+ {
261
+ code: "unavailable_resource_source_bytes",
262
+ owners: ["core.transaction"],
263
+ remediation: source
264
+ },
265
+ {
266
+ code: "missing_source",
267
+ owners: ["core.validation"],
268
+ remediation: source
269
+ },
270
+ {
271
+ code: "unreadable_source",
272
+ owners: ["core.validation"],
273
+ remediation: source
274
+ },
275
+ {
276
+ code: "decode_capability_unavailable",
277
+ owners: ["core.validation"],
278
+ remediation: {
279
+ kind: "host-action",
280
+ 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."
281
+ }
282
+ },
283
+ {
284
+ code: "session_id_conflict",
285
+ owners: ["backend"],
286
+ remediation: {
287
+ kind: "host-action",
288
+ 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."
289
+ }
290
+ },
291
+ {
292
+ code: "lock_conflict",
293
+ owners: ["backend"],
294
+ remediation: {
295
+ kind: "host-action",
296
+ 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."
297
+ }
298
+ },
299
+ {
300
+ code: "event_cursor_invalid",
301
+ owners: ["backend"],
302
+ remediation: {
303
+ kind: "refresh-and-replan",
304
+ 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."
305
+ }
306
+ },
307
+ {
308
+ code: "corrupt_source",
309
+ owners: ["core.validation"],
310
+ remediation: source
311
+ },
312
+ {
313
+ code: "unsupported_operation",
314
+ owners: ["core.transaction"],
315
+ remediation: unsupported
316
+ },
317
+ {
318
+ code: "transaction_unsupported",
319
+ owners: ["core.transaction"],
320
+ remediation: unsupported
321
+ },
322
+ {
323
+ code: "unsupported_display_node_kind",
324
+ owners: ["core.transaction"],
325
+ remediation: unsupported
326
+ },
327
+ {
328
+ code: "unsupported_cross_package_image_ref",
329
+ owners: ["core.transaction"],
330
+ remediation: unsupported
331
+ },
332
+ {
333
+ code: "unsupported_gear_kind",
334
+ owners: ["core.transaction"],
335
+ remediation: unsupported
336
+ },
337
+ {
338
+ code: "unsupported_resource_mutation",
339
+ owners: ["core.transaction"],
340
+ remediation: unsupported
341
+ },
342
+ {
343
+ code: "unsupported_display_node_mutation",
344
+ owners: ["core.transaction"],
345
+ remediation: unsupported
346
+ },
347
+ {
348
+ code: "unsupported_text_field_target",
349
+ owners: ["core.transaction"],
350
+ remediation: unsupported
351
+ },
352
+ {
353
+ code: "unsupported_display_node_field",
354
+ owners: ["core.transaction"],
355
+ remediation: unsupported
356
+ },
357
+ {
358
+ code: "unsupported_operation_batch",
359
+ owners: ["core.transaction"],
360
+ remediation: unsupported
361
+ },
362
+ {
363
+ code: "unsupported_resource_kind",
364
+ owners: ["core.transaction", "core.validation"],
365
+ remediation: unsupported
366
+ },
367
+ {
368
+ code: "invalid_project_settings",
369
+ owners: ["core.transaction"],
370
+ remediation: payload
371
+ },
372
+ {
373
+ code: "invalid_package_settings",
374
+ owners: ["core.transaction"],
375
+ remediation: payload
376
+ },
377
+ {
378
+ code: "invalid_display_node_payload",
379
+ owners: ["core.transaction"],
380
+ remediation: payload
381
+ },
382
+ {
383
+ code: "invalid_resource_name",
384
+ owners: ["core.transaction"],
385
+ remediation: payload
386
+ },
387
+ {
388
+ code: "invalid_resource_path",
389
+ owners: ["core.transaction"],
390
+ remediation: payload
391
+ },
392
+ {
393
+ code: "invalid_resource_folder_path",
394
+ owners: ["core.transaction"],
395
+ remediation: payload
396
+ },
397
+ {
398
+ code: "invalid_resource_folder_atlas",
399
+ owners: ["core.transaction"],
400
+ remediation: payload
401
+ },
402
+ {
403
+ code: "invalid_attach_index",
404
+ owners: ["core.transaction"],
405
+ remediation: payload
406
+ },
407
+ {
408
+ code: "invalid_controller_payload",
409
+ owners: ["core.transaction"],
410
+ remediation: payload
411
+ },
412
+ {
413
+ code: "invalid_transition_payload",
414
+ owners: ["core.transaction"],
415
+ remediation: payload
416
+ },
417
+ {
418
+ code: "invalid_look_gear_payload",
419
+ owners: ["core.transaction"],
420
+ remediation: payload
421
+ },
422
+ {
423
+ code: "invalid_gear_payload",
424
+ owners: ["core.transaction"],
425
+ remediation: payload
426
+ },
427
+ {
428
+ code: "invalid_resource_payload",
429
+ owners: ["core.transaction"],
430
+ remediation: payload
431
+ },
432
+ {
433
+ code: "invalid_resource_bytes",
434
+ owners: ["core.transaction"],
435
+ remediation: payload
436
+ },
437
+ {
438
+ code: "invalid_movie_clip_jta",
439
+ owners: ["core.transaction"],
440
+ remediation: payload
441
+ },
442
+ {
443
+ code: "invalid_resource_index",
444
+ owners: ["core.transaction"],
445
+ remediation: payload
446
+ },
447
+ {
448
+ code: "invalid_branch_name",
449
+ owners: ["core.transaction"],
450
+ remediation: payload
451
+ },
452
+ {
453
+ code: "invalid_package_payload",
454
+ owners: ["core.transaction"],
455
+ remediation: payload
456
+ },
457
+ {
458
+ code: "invalid_package_index",
459
+ owners: ["core.transaction"],
460
+ remediation: payload
461
+ },
462
+ {
463
+ code: "invalid_component_payload",
464
+ owners: ["core.transaction"],
465
+ remediation: payload
466
+ },
467
+ {
468
+ code: "invalid_component_index",
469
+ owners: ["core.transaction"],
470
+ remediation: payload
471
+ },
472
+ {
473
+ code: "invalid_component_move",
474
+ owners: ["core.transaction"],
475
+ remediation: payload
476
+ },
477
+ {
478
+ code: "invalid_uam",
479
+ owners: ["core.transaction", "core.validation"],
480
+ remediation: payload
481
+ },
482
+ {
483
+ code: "project_settings_unchanged",
484
+ owners: ["core.transaction"],
485
+ remediation: unchanged
486
+ },
487
+ {
488
+ code: "package_settings_unchanged",
489
+ owners: ["core.transaction"],
490
+ remediation: unchanged
491
+ },
492
+ {
493
+ code: "display_node_props_unchanged",
494
+ owners: ["core.transaction"],
495
+ remediation: unchanged
496
+ },
497
+ {
498
+ code: "resource_folder_atlas_unchanged",
499
+ owners: ["core.transaction"],
500
+ remediation: unchanged
501
+ },
502
+ {
503
+ code: "duplicate_look_gear_controller",
504
+ owners: ["core.transaction"],
505
+ remediation: duplicate
506
+ },
507
+ {
508
+ code: "duplicate_transition_name",
509
+ owners: ["core.transaction"],
510
+ remediation: duplicate
511
+ },
512
+ {
513
+ code: "duplicate_look_gear_state_page",
514
+ owners: ["core.transaction"],
515
+ remediation: duplicate
516
+ },
517
+ {
518
+ code: "duplicate_gear_controller",
519
+ owners: ["core.transaction"],
520
+ remediation: duplicate
521
+ },
522
+ {
523
+ code: "duplicate_gear_state_page",
524
+ owners: ["core.transaction"],
525
+ remediation: duplicate
526
+ },
527
+ {
528
+ code: "duplicate_branch_name",
529
+ owners: ["core.transaction"],
530
+ remediation: duplicate
531
+ },
532
+ {
533
+ code: "duplicate_component_id",
534
+ owners: ["core.transaction"],
535
+ remediation: duplicate
536
+ },
537
+ {
538
+ code: "resource_folder_conflict",
539
+ owners: ["core.transaction"],
540
+ remediation: duplicate
541
+ },
542
+ {
543
+ code: "duplicate_resource_id",
544
+ owners: ["core.transaction", "core.validation"],
545
+ remediation: duplicate
546
+ },
547
+ {
548
+ code: "duplicate_package_id",
549
+ owners: ["core.transaction", "core.validation"],
550
+ remediation: duplicate
551
+ },
552
+ {
553
+ code: "duplicate_package_name",
554
+ owners: ["core.transaction", "core.validation"],
555
+ remediation: duplicate
556
+ },
557
+ {
558
+ code: "resource_folder_not_empty",
559
+ owners: ["core.transaction"],
560
+ remediation: references
561
+ },
562
+ {
563
+ code: "branch_not_empty",
564
+ owners: ["core.transaction"],
565
+ remediation: references
566
+ },
567
+ {
568
+ code: "branch_referenced",
569
+ owners: ["core.transaction"],
570
+ remediation: references
571
+ },
572
+ {
573
+ code: "invalid_resource_reference",
574
+ owners: ["core.transaction"],
575
+ remediation: references
576
+ },
577
+ {
578
+ code: "invalid_component_reference",
579
+ owners: ["core.transaction"],
580
+ remediation: references
581
+ },
582
+ {
583
+ code: "invalid_group_reference",
584
+ owners: ["core.transaction"],
585
+ remediation: references
586
+ },
587
+ {
588
+ code: "package_referenced",
589
+ owners: ["core.transaction"],
590
+ remediation: references
591
+ },
592
+ {
593
+ code: "component_referenced",
594
+ owners: ["core.transaction"],
595
+ remediation: references
596
+ },
597
+ {
598
+ code: "component_has_package_dependencies",
599
+ owners: ["core.transaction"],
600
+ remediation: references
601
+ },
602
+ {
603
+ code: "dangling_resource_reference",
604
+ owners: ["core.validation"],
605
+ remediation: references
606
+ },
607
+ {
608
+ code: "invalid_project_xml",
609
+ owners: ["core.validation"],
610
+ remediation: project
611
+ },
612
+ {
613
+ code: "invalid_package_xml",
614
+ owners: ["core.validation"],
615
+ remediation: project
616
+ },
617
+ {
618
+ code: "invalid_branch_package_xml",
619
+ owners: ["core.validation"],
620
+ remediation: project
621
+ },
622
+ {
623
+ code: "invalid_component_xml",
624
+ owners: ["core.validation"],
625
+ remediation: project
626
+ },
627
+ {
628
+ code: "invalid_project_value",
629
+ owners: ["core.validation"],
630
+ remediation: project
631
+ },
632
+ {
633
+ code: "desktop_incompatible_geometry",
634
+ owners: ["core.validation"],
635
+ remediation: project
636
+ },
637
+ {
638
+ code: "invalid_settings_json",
639
+ owners: ["core.validation"],
640
+ remediation: project
641
+ },
642
+ {
643
+ code: "path_collision",
644
+ owners: ["core.validation"],
645
+ remediation: path$1
646
+ },
647
+ {
648
+ code: "unsafe_path",
649
+ owners: ["core.validation"],
650
+ remediation: path$1
651
+ },
652
+ {
653
+ code: "capability_unavailable",
654
+ owners: ["backend"],
655
+ remediation: capability
656
+ },
657
+ {
658
+ code: "uam_fidelity_unsupported",
659
+ owners: ["backend"],
660
+ remediation: capability
661
+ },
662
+ {
663
+ code: "save_partial_failure",
664
+ owners: ["backend"],
665
+ remediation: write
666
+ },
667
+ {
668
+ code: "write_failed",
669
+ owners: ["backend"],
670
+ remediation: write
671
+ },
672
+ {
673
+ code: "project_open_failed",
674
+ owners: ["backend"],
675
+ remediation: project
676
+ },
677
+ {
678
+ code: "materialize_validation_failed",
679
+ owners: ["backend"],
680
+ remediation: project
681
+ },
682
+ {
683
+ code: "execution_failure",
684
+ owners: ["core.transaction"],
685
+ remediation: execution
686
+ },
687
+ {
688
+ code: "cache_refresh_failed",
689
+ owners: ["backend"],
690
+ remediation: execution
691
+ },
692
+ {
693
+ code: "job_not_found",
694
+ owners: ["backend"],
695
+ remediation: job
696
+ },
697
+ {
698
+ code: "job_not_cancellable",
699
+ owners: ["backend"],
700
+ remediation: job
701
+ },
702
+ {
703
+ code: "job_cancelled",
704
+ owners: ["backend"],
705
+ remediation: job
706
+ }
707
+ ];
708
+ const BACKEND_DIAGNOSTICS_URI = "openfairygui://docs/diagnostics";
709
+ `${BACKEND_DIAGNOSTICS_URI}`;
710
+ function enrichBackendDiagnostic(diagnostic, sessionId) {
711
+ const guide = BACKEND_DIAGNOSTIC_GUIDES.find((entry) => entry.code === diagnostic.code);
712
+ if (!guide) return { ...diagnostic };
713
+ return {
714
+ ...diagnostic,
715
+ owner: diagnostic.owner ?? guide.owners[0],
716
+ docsUri: `${BACKEND_DIAGNOSTICS_URI}/${guide.code}`,
717
+ remediation: {
718
+ ...guide.remediation,
719
+ ...sessionId && guide.remediation.kind !== "host-action" ? { read: {
720
+ method: "getProjectOutline",
721
+ input: { sessionId }
722
+ } } : {}
723
+ }
724
+ };
725
+ }
726
+ //#endregion
105
727
  //#region src/services/context.ts
106
728
  function diagnosticFromError(error) {
107
729
  return {
@@ -120,10 +742,10 @@ function createMeta(stage, startedAt, options) {
120
742
  revision: options?.revision,
121
743
  durationMs: Math.max(0, Date.now() - startedAt),
122
744
  warnings: options?.warnings ?? [],
123
- diagnostics: options?.diagnostics ?? [],
745
+ diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
124
746
  stage,
125
747
  contractVersion: BACKEND_CONTRACT_VERSION,
126
- capabilitySchemaVersion: 3
748
+ capabilitySchemaVersion: 10
127
749
  };
128
750
  }
129
751
  function success(stage, startedAt, data, options) {
@@ -147,10 +769,14 @@ function failure(stage, startedAt, error, session, options) {
147
769
  }
148
770
  //#endregion
149
771
  //#region src/services/session-project-writer.ts
150
- function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
772
+ function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
773
+ const contained = async (targetPath, operation) => {
774
+ await assertProjectPathContained(fileSystem, projectRoot, targetPath);
775
+ return operation();
776
+ };
151
777
  async function trackWrite(targetPath, write) {
152
778
  try {
153
- const result = await write();
779
+ const result = await contained(targetPath, write);
154
780
  writtenPaths.push(targetPath);
155
781
  return result;
156
782
  } catch (error) {
@@ -159,8 +785,8 @@ function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
159
785
  }
160
786
  }
161
787
  return {
162
- readFile: (path) => fileSystem.readFile(path),
163
- readFileRaw: (path) => fileSystem.readFileRaw(path),
788
+ readFile: (path) => contained(path, () => fileSystem.readFile(path)),
789
+ readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
164
790
  writeFile: (path, content) => trackWrite(path, async () => {
165
791
  await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
166
792
  await fileSystem.writeFile(path, content);
@@ -169,9 +795,10 @@ function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
169
795
  await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
170
796
  await fileSystem.writeFileRaw(path, data);
171
797
  }),
172
- mkdir: (path) => fileSystem.mkdir(path, { recursive: true }),
173
- readdir: (path) => fileSystem.readdir(path),
798
+ mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
799
+ readdir: (path) => contained(path, () => fileSystem.readdir(path)),
174
800
  async exists(path) {
801
+ await assertProjectPathContained(fileSystem, projectRoot, path);
175
802
  try {
176
803
  await fileSystem.stat(path);
177
804
  return true;
@@ -186,11 +813,21 @@ function createWriterFileSystem(fileSystem, writtenPaths, failedPaths) {
186
813
  };
187
814
  }
188
815
  async function writeSessionProject(input) {
189
- await new _openfairygui_core_project_io.ProjectWriter(createWriterFileSystem(input.fileSystem, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
190
- staleSourceFiles: input.staleSourceFiles,
191
- staleResourceFolders: input.staleResourceFolders,
192
- staleBranchDirectories: input.staleBranchDirectories
193
- });
816
+ const projectRoot = input.fileSystem.dirname(input.fairyPath);
817
+ const write = async (fileSystem) => {
818
+ await new _openfairygui_core_project_io.ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
819
+ staleSourceFiles: input.staleSourceFiles,
820
+ staleResourceFolders: input.staleResourceFolders,
821
+ staleBranchDirectories: input.staleBranchDirectories
822
+ });
823
+ };
824
+ if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
825
+ try {
826
+ await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
827
+ } catch (error) {
828
+ input.writtenPaths.length = 0;
829
+ throw error;
830
+ }
194
831
  }
195
832
  //#endregion
196
833
  //#region src/services/session-utils.ts
@@ -224,6 +861,260 @@ function createStaleWriteError(session, expectedRevision) {
224
861
  };
225
862
  }
226
863
  //#endregion
864
+ //#region src/runtime/contracts.ts
865
+ const BACKEND_ENTITY_QUERY_LIMITS = {
866
+ maxBytes: 262144,
867
+ maxDepth: 32,
868
+ maxNodes: 1e5
869
+ };
870
+ const BACKEND_TRANSACTION_PREVIEW_LIMITS = {
871
+ maxBytes: 262144,
872
+ maxEntries: 2e3
873
+ };
874
+ /** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
875
+ const BACKEND_RESOURCE_QUERY_FIELDS = [
876
+ "kind",
877
+ "id",
878
+ "name",
879
+ "path",
880
+ "exported",
881
+ "favorite",
882
+ "branch",
883
+ "branchItemIds",
884
+ "fileName",
885
+ "file",
886
+ "dimensions",
887
+ "image",
888
+ "movieClip"
889
+ ];
890
+ //#endregion
891
+ //#region src/services/capture-project.ts
892
+ function createCaptureFileSystem(files, directories) {
893
+ const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
894
+ return {
895
+ async readFile(filePath) {
896
+ const value = files.get(normalize(filePath));
897
+ if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
898
+ return value;
899
+ },
900
+ async readFileRaw(filePath) {
901
+ const value = files.get(normalize(filePath));
902
+ if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
903
+ return value.slice();
904
+ },
905
+ async writeFile(filePath, content) {
906
+ files.set(normalize(filePath), content);
907
+ },
908
+ async writeFileRaw(filePath, data) {
909
+ files.set(normalize(filePath), data.slice());
910
+ },
911
+ async mkdir(dirPath) {
912
+ directories.add(normalize(dirPath));
913
+ },
914
+ async readdir() {
915
+ return [];
916
+ },
917
+ async exists(filePath) {
918
+ return files.has(normalize(filePath));
919
+ },
920
+ join(...paths) {
921
+ return normalize(paths.filter(Boolean).join("/"));
922
+ },
923
+ dirname(filePath) {
924
+ const normalized = normalize(filePath);
925
+ const separator = normalized.lastIndexOf("/");
926
+ return separator < 0 ? "" : normalized.slice(0, separator);
927
+ },
928
+ async unlink(filePath) {
929
+ files.delete(normalize(filePath));
930
+ }
931
+ };
932
+ }
933
+ function capturedFilesEqual(left, right) {
934
+ if (left.size !== right.size) return false;
935
+ for (const [filePath, leftValue] of left) {
936
+ const rightValue = right.get(filePath);
937
+ if (typeof leftValue === "string") {
938
+ if (leftValue !== rightValue) return false;
939
+ continue;
940
+ }
941
+ if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
942
+ for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
943
+ }
944
+ return true;
945
+ }
946
+ function capturedDirectoriesEqual(left, right) {
947
+ return left.size === right.size && [...left].every((directory) => right.has(directory));
948
+ }
949
+ /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
950
+ async function captureProject(document, fairyFileName) {
951
+ const files = /* @__PURE__ */ new Map();
952
+ const directories = /* @__PURE__ */ new Set();
953
+ await new _openfairygui_core_project_io.ProjectWriter(createCaptureFileSystem(files, directories)).write(document, fairyFileName);
954
+ return {
955
+ files,
956
+ directories
957
+ };
958
+ }
959
+ //#endregion
960
+ //#region src/services/transaction-preview.ts
961
+ /** Keep child identities/order on their parent, and compare each child's own properties separately. */
962
+ function entities(project) {
963
+ const result = /* @__PURE__ */ new Map();
964
+ function add(target, properties) {
965
+ const key = JSON.stringify(target);
966
+ if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
967
+ result.set(key, {
968
+ target,
969
+ properties
970
+ });
971
+ }
972
+ const { packages, ...properties } = project;
973
+ add({ kind: "project" }, {
974
+ ...properties,
975
+ packages: packages.map((pkg) => pkg.id)
976
+ });
977
+ for (const { resources, ...pkg } of packages) {
978
+ const packageId = pkg.id;
979
+ add({
980
+ kind: "package",
981
+ selector: { packageId }
982
+ }, {
983
+ ...pkg,
984
+ resources: resources.map((resource) => resource.id)
985
+ });
986
+ for (const resource of resources) {
987
+ const resourceTarget = {
988
+ kind: "resource",
989
+ selector: {
990
+ packageId,
991
+ resourceId: resource.id
992
+ }
993
+ };
994
+ if (resource.kind !== "component") {
995
+ add(resourceTarget, resource);
996
+ continue;
997
+ }
998
+ const { component, ...resourceProperties } = resource;
999
+ add(resourceTarget, resourceProperties);
1000
+ const { displayList, controllers, transitions, ...componentProperties } = component;
1001
+ const selector = {
1002
+ packageId,
1003
+ componentResourceId: resource.id
1004
+ };
1005
+ add({
1006
+ kind: "component",
1007
+ selector
1008
+ }, {
1009
+ ...componentProperties,
1010
+ displayList: displayList.map((node) => node.id),
1011
+ controllers: controllers.map((controller) => controller.name),
1012
+ transitions: transitions.map((transition) => transition.name)
1013
+ });
1014
+ for (const node of displayList) add({
1015
+ kind: "displayNode",
1016
+ selector: {
1017
+ ...selector,
1018
+ displayNodeId: node.id
1019
+ }
1020
+ }, node);
1021
+ for (const controller of controllers) add({
1022
+ kind: "controller",
1023
+ selector: {
1024
+ ...selector,
1025
+ controllerName: controller.name
1026
+ }
1027
+ }, controller);
1028
+ for (const transition of transitions) add({
1029
+ kind: "transition",
1030
+ selector: {
1031
+ ...selector,
1032
+ transitionName: transition.name
1033
+ }
1034
+ }, transition);
1035
+ }
1036
+ }
1037
+ return result;
1038
+ }
1039
+ function equal(left, right, depth = 0) {
1040
+ if (left === right) return true;
1041
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
1042
+ 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]);
1043
+ if (depth > 128) throw new Error("Preview property comparison exceeds the supported nesting depth.");
1044
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
1045
+ if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
1046
+ const a = left, b = right;
1047
+ const keys = Object.keys(a);
1048
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
1049
+ }
1050
+ var PreviewBudgetError = class extends Error {};
1051
+ /** No host filesystem, cache, event or session mutation is involved in the projection. */
1052
+ async function previewTransactionImpact(session, project, fileSystemAvailable) {
1053
+ const impact = {
1054
+ entities: [],
1055
+ files: []
1056
+ };
1057
+ const before = entities(session.project), after = entities(project);
1058
+ let entries = 0, bytes = 0;
1059
+ const encoder = new TextEncoder();
1060
+ function count(value) {
1061
+ bytes += encoder.encode(JSON.stringify(value)).byteLength;
1062
+ 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.");
1063
+ }
1064
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
1065
+ const previous = before.get(key), next = after.get(key);
1066
+ const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])].filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
1067
+ if (!fields.length && previous && next) continue;
1068
+ const change = {
1069
+ target: (next ?? previous).target,
1070
+ change: !previous ? "added" : !next ? "removed" : "updated",
1071
+ fields
1072
+ };
1073
+ count(change);
1074
+ impact.entities.push(change);
1075
+ }
1076
+ const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, "/").split("/").at(-1) : "Project.fairy";
1077
+ const [previousFiles, nextFiles] = await Promise.all([captureProject((0, _openfairygui_core_uam.materializeUamProject)(session.project), fairyFileName), captureProject((0, _openfairygui_core_uam.materializeUamProject)(project), fairyFileName)]);
1078
+ for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
1079
+ const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
1080
+ if (equal(previous, next)) continue;
1081
+ const change = {
1082
+ path,
1083
+ kind: "file",
1084
+ change: previous === void 0 ? "added" : next === void 0 ? "removed" : "updated"
1085
+ };
1086
+ count(change);
1087
+ impact.files.push(change);
1088
+ }
1089
+ for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
1090
+ if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
1091
+ const change = {
1092
+ path,
1093
+ kind: "directory",
1094
+ change: nextFiles.directories.has(path) ? "added" : "removed"
1095
+ };
1096
+ count(change);
1097
+ impact.files.push(change);
1098
+ }
1099
+ impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
1100
+ const preview = {
1101
+ sessionId: session.sessionId,
1102
+ baseRevision: session.revision,
1103
+ projectedRevision: session.revision + 1,
1104
+ mode: "execute-and-discard",
1105
+ impact,
1106
+ persistence: {
1107
+ requiredAfterApply: true,
1108
+ fileSystemAvailable,
1109
+ uamFidelity: session.uamFidelity,
1110
+ writeVerified: false,
1111
+ nextAction: session.uamFidelity === "unsupported" || !fileSystemAvailable ? "host-action" : session.fileSystem ? "saveSession" : "materializeSession"
1112
+ }
1113
+ };
1114
+ if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction preview exceeds the response byte budget.");
1115
+ return preview;
1116
+ }
1117
+ //#endregion
227
1118
  //#region src/services/authoring-service.ts
228
1119
  function sourceFileKey(source) {
229
1120
  return [
@@ -253,8 +1144,12 @@ function recordStaleProjectFiles(session, previousProject, nextProject) {
253
1144
  for (const directory of (0, _openfairygui_core_uam.staleBranchDirectories)(nextProject, previousProject)) session.pendingStaleBranchDirectories.delete(branchDirectoryKey(directory));
254
1145
  }
255
1146
  function toBackendDiagnostics(error) {
256
- return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({ ...diagnostic })) : [{
1147
+ return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({
1148
+ ...diagnostic,
1149
+ owner: "core.transaction"
1150
+ })) : [{
257
1151
  code: error.code,
1152
+ owner: "core.transaction",
258
1153
  message: error.message,
259
1154
  severity: "error",
260
1155
  operationKind: error.operationKind,
@@ -342,6 +1237,46 @@ var AuthoringService = class {
342
1237
  if (this.sessionOperations.get(sessionId) === tail) this.sessionOperations.delete(sessionId);
343
1238
  }
344
1239
  }
1240
+ async preflightTransaction(input) {
1241
+ const queuedInput = structuredClone(input);
1242
+ detachSharedByteViews(queuedInput);
1243
+ return this.runSessionExclusive(queuedInput.sessionId, async () => {
1244
+ const startedAt = Date.now();
1245
+ const session = this.context.sessions.get(queuedInput.sessionId);
1246
+ if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1247
+ const meta = {
1248
+ sessionId: session.sessionId,
1249
+ revision: session.revision
1250
+ };
1251
+ if (queuedInput.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, queuedInput.expectedRevision), toSessionSnapshot(session, this.context.capabilities), meta);
1252
+ const project = structuredClone(session.project);
1253
+ detachSharedByteViews(project);
1254
+ const result = await (0, _openfairygui_functions_uam.applyUamTransactionAppAsync)({
1255
+ project,
1256
+ operations: queuedInput.operations
1257
+ });
1258
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1259
+ if (!result.ok) return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
1260
+ ...meta,
1261
+ diagnostics: toBackendDiagnostics(result.error)
1262
+ });
1263
+ try {
1264
+ const preview = await previewTransactionImpact({
1265
+ ...session,
1266
+ project
1267
+ }, result.project, Boolean(session.fileSystem));
1268
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1269
+ return success("authoring", startedAt, preview, meta);
1270
+ } catch (error) {
1271
+ return failure("authoring", startedAt, {
1272
+ code: "transaction_preview_failed",
1273
+ sessionId: session.sessionId,
1274
+ reason: error instanceof PreviewBudgetError ? "response_budget_exceeded" : "projection_failed",
1275
+ message: error instanceof Error ? error.message : String(error)
1276
+ }, toSessionSnapshot(session, this.context.capabilities), meta);
1277
+ }
1278
+ });
1279
+ }
345
1280
  async applyTransaction(input) {
346
1281
  const queuedInput = structuredClone(input);
347
1282
  detachSharedByteViews(queuedInput);
@@ -421,7 +1356,7 @@ var AuthoringService = class {
421
1356
  const startedAt = Date.now();
422
1357
  const session = this.context.sessions.get(input.sessionId);
423
1358
  if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
424
- const fileSystem = session.fileSystem ?? input.fileSystem ?? this.context.fileSystem;
1359
+ const fileSystem = session.fileSystem ?? input.fileSystem;
425
1360
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("saveSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
426
1361
  sessionId: session.sessionId,
427
1362
  revision: session.revision
@@ -504,7 +1439,7 @@ var AuthoringService = class {
504
1439
  lastSavedRevision: session.lastSavedRevision,
505
1440
  committedPaths,
506
1441
  failedPaths,
507
- diskMayBePartiallyUpdated: true
1442
+ diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
508
1443
  }, toSessionSnapshot(session, this.context.capabilities), {
509
1444
  sessionId: session.sessionId,
510
1445
  revision: session.revision
@@ -523,7 +1458,7 @@ var AuthoringService = class {
523
1458
  revision: session.revision
524
1459
  });
525
1460
  const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
526
- const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem ?? this.context.fileSystem;
1461
+ const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
527
1462
  if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("materializeSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
528
1463
  sessionId: session.sessionId,
529
1464
  revision: session.revision
@@ -679,7 +1614,7 @@ var AuthoringService = class {
679
1614
  failedPaths,
680
1615
  skippedPaths,
681
1616
  diagnostics: diagnosticsFromError,
682
- diskMayBePartiallyUpdated: true
1617
+ diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
683
1618
  }, toSessionSnapshot(session, this.context.capabilities), {
684
1619
  sessionId: session.sessionId,
685
1620
  revision: session.revision,
@@ -749,7 +1684,7 @@ var EventService = class {
749
1684
  ...event,
750
1685
  sequence: this.context.nextEventSequence(),
751
1686
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
752
- diagnostics: event.diagnostics ?? []
1687
+ diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
753
1688
  };
754
1689
  const sessionId = event.sessionId;
755
1690
  if (!sessionId) return emitted;
@@ -1077,6 +2012,37 @@ var JobService = class {
1077
2012
  };
1078
2013
  //#endregion
1079
2014
  //#region src/services/read-service.ts
2015
+ /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
2016
+ function queryResponseProblem(value) {
2017
+ const pending = [{
2018
+ value,
2019
+ depth: 0
2020
+ }];
2021
+ let nodes = 0;
2022
+ let stringUnits = 0;
2023
+ while (pending.length) {
2024
+ const { value, depth } = pending.pop();
2025
+ if (++nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes || depth > BACKEND_ENTITY_QUERY_LIMITS.maxDepth) return "response_budget_exceeded";
2026
+ if (typeof value === "string" && (stringUnits += value.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return "response_budget_exceeded";
2027
+ if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") continue;
2028
+ if (typeof value === "number") {
2029
+ if (!Number.isFinite(value)) return "non_json_value";
2030
+ continue;
2031
+ }
2032
+ if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return "non_json_value";
2033
+ if (Array.isArray(value) && value.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return "response_budget_exceeded";
2034
+ const entries = Object.entries(value);
2035
+ if (entries.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return "response_budget_exceeded";
2036
+ for (const [key, child] of entries) {
2037
+ if (!Array.isArray(value) && (stringUnits += key.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return "response_budget_exceeded";
2038
+ pending.push({
2039
+ value: child,
2040
+ depth: depth + 1
2041
+ });
2042
+ }
2043
+ }
2044
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return "response_budget_exceeded";
2045
+ }
1080
2046
  function toProjectOutline(session) {
1081
2047
  const project = session.project;
1082
2048
  return {
@@ -1144,6 +2110,121 @@ var ReadService = class {
1144
2110
  revision: session.revision
1145
2111
  });
1146
2112
  }
2113
+ queryEntity(input) {
2114
+ const startedAt = Date.now();
2115
+ const session = this.context.sessions.get(input.sessionId);
2116
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2117
+ const meta = {
2118
+ sessionId: session.sessionId,
2119
+ revision: session.revision
2120
+ };
2121
+ const reject = (reason) => failure("read", startedAt, {
2122
+ code: "entity_query_failed",
2123
+ sessionId: session.sessionId,
2124
+ reason,
2125
+ message: `Entity query failed: ${reason}.`
2126
+ }, void 0, meta);
2127
+ const target = input.target;
2128
+ if (!target || typeof target !== "object" || Array.isArray(target) || Object.keys(target).some((key) => key !== "kind" && key !== "selector")) return reject("invalid_query");
2129
+ const respond = (entity) => {
2130
+ const data = {
2131
+ ...meta,
2132
+ target,
2133
+ entity
2134
+ };
2135
+ const problem = queryResponseProblem(data);
2136
+ return problem ? reject(problem) : success("read", startedAt, structuredClone(data), meta);
2137
+ };
2138
+ if (target.kind === "project") {
2139
+ if (Object.hasOwn(target, "selector")) return reject("invalid_query");
2140
+ const { projectId, settings } = session.project;
2141
+ return respond({
2142
+ kind: "project",
2143
+ properties: {
2144
+ projectId,
2145
+ settings
2146
+ }
2147
+ });
2148
+ }
2149
+ const keys = target.kind === "package" ? ["packageId"] : target.kind === "resource" ? ["packageId", "resourceId"] : target.kind === "component" ? ["packageId", "componentResourceId"] : target.kind === "displayNode" ? [
2150
+ "packageId",
2151
+ "componentResourceId",
2152
+ "displayNodeId"
2153
+ ] : target.kind === "controller" ? [
2154
+ "packageId",
2155
+ "componentResourceId",
2156
+ "controllerName"
2157
+ ] : target.kind === "transition" ? [
2158
+ "packageId",
2159
+ "componentResourceId",
2160
+ "transitionName"
2161
+ ] : [];
2162
+ const selector = target.selector;
2163
+ 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");
2164
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2165
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2166
+ if (target.kind === "package") {
2167
+ const { id, name, compressPNG, jpegQuality, publish } = packages[0];
2168
+ return respond({
2169
+ kind: "package",
2170
+ properties: {
2171
+ id,
2172
+ name,
2173
+ settings: {
2174
+ compressPNG,
2175
+ jpegQuality,
2176
+ publish
2177
+ }
2178
+ }
2179
+ });
2180
+ }
2181
+ const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === "resource" ? selector.resourceId : selector.componentResourceId));
2182
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2183
+ const resource = resources[0];
2184
+ let entity;
2185
+ if (target.kind === "resource") {
2186
+ const record = resource;
2187
+ entity = {
2188
+ kind: "resource",
2189
+ properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS.filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]]))
2190
+ };
2191
+ } else {
2192
+ if (resource.kind !== "component") return reject("not_found");
2193
+ if (target.kind === "component") {
2194
+ const { size, properties, customData } = resource.component;
2195
+ entity = {
2196
+ kind: "component",
2197
+ properties: {
2198
+ size,
2199
+ properties,
2200
+ customData
2201
+ }
2202
+ };
2203
+ } else if (target.kind === "controller") {
2204
+ const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
2205
+ if (controllers.length !== 1) return reject(controllers.length ? "ambiguous" : "not_found");
2206
+ entity = {
2207
+ kind: "controller",
2208
+ properties: controllers[0]
2209
+ };
2210
+ } else if (target.kind === "transition") {
2211
+ const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
2212
+ if (transitions.length !== 1) return reject(transitions.length ? "ambiguous" : "not_found");
2213
+ entity = {
2214
+ kind: "transition",
2215
+ properties: transitions[0]
2216
+ };
2217
+ } else {
2218
+ const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
2219
+ if (nodes.length !== 1) return reject(nodes.length ? "ambiguous" : "not_found");
2220
+ entity = {
2221
+ kind: "displayNode",
2222
+ properties: nodes[0]
2223
+ };
2224
+ }
2225
+ }
2226
+ return respond(entity);
2227
+ }
1147
2228
  validateSession(input) {
1148
2229
  const startedAt = Date.now();
1149
2230
  const session = this.context.sessions.get(input.sessionId);
@@ -1160,7 +2241,8 @@ var ReadService = class {
1160
2241
  code,
1161
2242
  message,
1162
2243
  severity,
1163
- path
2244
+ path,
2245
+ owner: "core.validation"
1164
2246
  }))
1165
2247
  });
1166
2248
  }
@@ -1168,7 +2250,7 @@ var ReadService = class {
1168
2250
  //#endregion
1169
2251
  //#region src/services/runtime-service.ts
1170
2252
  function randomId() {
1171
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
2253
+ return crypto.randomUUID();
1172
2254
  }
1173
2255
  function createCapabilityUnavailableError(capability) {
1174
2256
  const artifactCapability = capability === "artifact.publish" || capability === "artifact.restore";
@@ -1181,29 +2263,33 @@ function createCapabilityUnavailableError(capability) {
1181
2263
  bridgeBoundary: artifactCapability ? "external-bridge" : void 0
1182
2264
  };
1183
2265
  }
1184
- function createProjectReaderFileSystem(fileSystem) {
2266
+ function createProjectReaderFileSystem(fileSystem, projectRoot) {
2267
+ const contained = async (filePath, operation) => {
2268
+ await assertProjectPathContained(fileSystem, projectRoot, filePath);
2269
+ return operation();
2270
+ };
1185
2271
  return {
1186
2272
  readFile(filePath) {
1187
- return fileSystem.readFile(filePath);
2273
+ return contained(filePath, () => fileSystem.readFile(filePath));
1188
2274
  },
1189
2275
  readFileRaw(filePath) {
1190
- return fileSystem.readFileRaw(filePath);
2276
+ return contained(filePath, () => fileSystem.readFileRaw(filePath));
1191
2277
  },
1192
2278
  writeFile(filePath, content) {
1193
- return fileSystem.writeFile(filePath, content);
2279
+ return contained(filePath, () => fileSystem.writeFile(filePath, content));
1194
2280
  },
1195
2281
  writeFileRaw(filePath, data) {
1196
- return fileSystem.writeFileRaw(filePath, data);
2282
+ return contained(filePath, () => fileSystem.writeFileRaw(filePath, data));
1197
2283
  },
1198
2284
  async mkdir(dirPath) {
1199
- await fileSystem.mkdir(dirPath, { recursive: true });
2285
+ await contained(dirPath, () => fileSystem.mkdir(dirPath, { recursive: true }));
1200
2286
  },
1201
2287
  readdir(dirPath) {
1202
- return fileSystem.readdir(dirPath);
2288
+ return contained(dirPath, () => fileSystem.readdir(dirPath));
1203
2289
  },
1204
2290
  async exists(filePath) {
1205
2291
  try {
1206
- await fileSystem.stat(filePath);
2292
+ await contained(filePath, () => fileSystem.stat(filePath));
1207
2293
  return true;
1208
2294
  } catch {
1209
2295
  return false;
@@ -1217,63 +2303,6 @@ function createProjectReaderFileSystem(fileSystem) {
1217
2303
  }
1218
2304
  };
1219
2305
  }
1220
- function createCaptureFileSystem(files, directories) {
1221
- const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
1222
- return {
1223
- async readFile(filePath) {
1224
- const value = files.get(normalize(filePath));
1225
- if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
1226
- return value;
1227
- },
1228
- async readFileRaw(filePath) {
1229
- const value = files.get(normalize(filePath));
1230
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
1231
- return value.slice();
1232
- },
1233
- async writeFile(filePath, content) {
1234
- files.set(normalize(filePath), content);
1235
- },
1236
- async writeFileRaw(filePath, data) {
1237
- files.set(normalize(filePath), data.slice());
1238
- },
1239
- async mkdir(dirPath) {
1240
- directories.add(normalize(dirPath));
1241
- },
1242
- async readdir() {
1243
- return [];
1244
- },
1245
- async exists(filePath) {
1246
- return files.has(normalize(filePath));
1247
- },
1248
- join(...paths) {
1249
- return normalize(paths.filter(Boolean).join("/"));
1250
- },
1251
- dirname(filePath) {
1252
- const normalized = normalize(filePath);
1253
- const separator = normalized.lastIndexOf("/");
1254
- return separator < 0 ? "" : normalized.slice(0, separator);
1255
- },
1256
- async unlink(filePath) {
1257
- files.delete(normalize(filePath));
1258
- }
1259
- };
1260
- }
1261
- function capturedFilesEqual(left, right) {
1262
- if (left.size !== right.size) return false;
1263
- for (const [filePath, leftValue] of left) {
1264
- const rightValue = right.get(filePath);
1265
- if (typeof leftValue === "string") {
1266
- if (leftValue !== rightValue) return false;
1267
- continue;
1268
- }
1269
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
1270
- for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
1271
- }
1272
- return true;
1273
- }
1274
- function capturedDirectoriesEqual(left, right) {
1275
- return left.size === right.size && [...left].every((directory) => right.has(directory));
1276
- }
1277
2306
  async function hasFullUamFidelity(document, project) {
1278
2307
  const sourceFiles = /* @__PURE__ */ new Map();
1279
2308
  const materializedFiles = /* @__PURE__ */ new Map();
@@ -1297,9 +2326,25 @@ var RuntimeService = class {
1297
2326
  const startedAt = Date.now();
1298
2327
  if (!this.context.fileSystem) return failure("runtime", startedAt, createCapabilityUnavailableError("fileSystem"));
1299
2328
  const fileSystem = this.context.fileSystem;
2329
+ if (this.context.allowedProjectRoots?.length) {
2330
+ let allowed = false;
2331
+ for (const root of this.context.allowedProjectRoots) try {
2332
+ await assertProjectPathContained(fileSystem, root, input.projectPath);
2333
+ allowed = true;
2334
+ break;
2335
+ } catch (error) {
2336
+ if (error.code !== "EACCES") throw error;
2337
+ }
2338
+ if (!allowed) return failure("runtime", startedAt, {
2339
+ code: "project_root_not_allowed",
2340
+ message: "Project path is outside the configured allowed roots.",
2341
+ projectPath: input.projectPath
2342
+ });
2343
+ }
1300
2344
  const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
2345
+ await fileSystem.validateProjectRoot?.(canonicalProjectPath);
1301
2346
  const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
1302
- const lockFilePath = fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
2347
+ const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath) ?? fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
1303
2348
  if (existingSessionId) return failure("runtime", startedAt, {
1304
2349
  code: "lock_conflict",
1305
2350
  kind: "in_process_session_exists",
@@ -1319,7 +2364,7 @@ var RuntimeService = class {
1319
2364
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1320
2365
  canonicalPathKey
1321
2366
  }));
1322
- const read = await new _openfairygui_core_project_io.ProjectReader(createProjectReaderFileSystem(fileSystem)).readDetailed(fairyPath, { hydrateResourceBytes: true });
2367
+ const read = await new _openfairygui_core_project_io.ProjectReader(createProjectReaderFileSystem(fileSystem, canonicalProjectPath)).readDetailed(fairyPath, { hydrateResourceBytes: true });
1323
2368
  if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
1324
2369
  const document = read.document;
1325
2370
  const project = (0, _openfairygui_core_uam.liftDocumentToUamProject)(document);
@@ -1377,6 +2422,11 @@ var RuntimeService = class {
1377
2422
  openProjectSession(input) {
1378
2423
  const startedAt = Date.now();
1379
2424
  const sessionId = input.sessionId ?? randomId();
2425
+ if (this.context.sessions.has(sessionId)) return failure("runtime", startedAt, {
2426
+ code: "session_id_conflict",
2427
+ message: `Session id is already in use: ${sessionId}`,
2428
+ sessionId
2429
+ });
1380
2430
  const storage = input.storage;
1381
2431
  const memoryProjectPath = `memory://${sessionId}`;
1382
2432
  const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
@@ -1484,7 +2534,9 @@ const BACKEND_METHODS = [
1484
2534
  "openProjectSession",
1485
2535
  "getSession",
1486
2536
  "getProjectOutline",
2537
+ "queryEntity",
1487
2538
  "validateSession",
2539
+ "preflightTransaction",
1488
2540
  "applyTransaction",
1489
2541
  "saveSession",
1490
2542
  "materializeSession",
@@ -1503,10 +2555,10 @@ const ARTIFACT_BRIDGE_CAPABILITY = {
1503
2555
  bridgeEntrypoint: "@openfairygui/backend/node",
1504
2556
  reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
1505
2557
  };
1506
- function createCapabilities() {
2558
+ function createCapabilities(atomicSave = false) {
1507
2559
  return {
1508
2560
  contractVersion: BACKEND_CONTRACT_VERSION,
1509
- capabilitySchemaVersion: 3,
2561
+ capabilitySchemaVersion: 10,
1510
2562
  transactionKernelOwner: "@openfairygui/core",
1511
2563
  appSeamOwner: "@openfairygui/functions",
1512
2564
  runtimeOwner: "@openfairygui/backend",
@@ -1515,9 +2567,29 @@ function createCapabilities() {
1515
2567
  capabilitySnapshot: true,
1516
2568
  sessionSnapshot: true,
1517
2569
  projectOutline: true,
2570
+ entityQuery: {
2571
+ kinds: [
2572
+ "project",
2573
+ "package",
2574
+ "resource",
2575
+ "component",
2576
+ "displayNode",
2577
+ "controller",
2578
+ "transition"
2579
+ ],
2580
+ projection: "properties",
2581
+ sourceBytes: false,
2582
+ limits: BACKEND_ENTITY_QUERY_LIMITS
2583
+ },
1518
2584
  projectValidation: true
1519
2585
  },
1520
2586
  authoring: {
2587
+ preflightTransaction: {
2588
+ mode: "execute-and-discard",
2589
+ reservesRevision: false,
2590
+ impact: "model-diff",
2591
+ limits: BACKEND_TRANSACTION_PREVIEW_LIMITS
2592
+ },
1521
2593
  applyTransaction: true,
1522
2594
  saveSession: true,
1523
2595
  resourceKinds: [..._openfairygui_core_uam.UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
@@ -1567,7 +2639,9 @@ function createCapabilities() {
1567
2639
  },
1568
2640
  diagnostics: {
1569
2641
  stableCodes: true,
1570
- errorDiagnosticMirror: true
2642
+ errorDiagnosticMirror: true,
2643
+ recoveryGuides: "all-formal-codes",
2644
+ automaticRepair: false
1571
2645
  }
1572
2646
  },
1573
2647
  compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
@@ -1575,7 +2649,7 @@ function createCapabilities() {
1575
2649
  sessionRuntime: true,
1576
2650
  advisoryLocking: true,
1577
2651
  coordinatedSave: true,
1578
- atomicSave: false,
2652
+ atomicSave,
1579
2653
  staleRevisionProtection: true,
1580
2654
  pathPolicy: createRuntimePathPolicy(),
1581
2655
  events: {
@@ -1621,10 +2695,11 @@ var BackendRuntime = class {
1621
2695
  jobService;
1622
2696
  constructor(options = {}) {
1623
2697
  this.fileSystem = options.fileSystem;
1624
- this.capabilities = createCapabilities();
2698
+ this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
1625
2699
  this.context = {
1626
2700
  fileSystem: this.fileSystem,
1627
2701
  host: options.host,
2702
+ allowedProjectRoots: options.allowedProjectRoots,
1628
2703
  capabilities: this.capabilities,
1629
2704
  sessions: this.sessions,
1630
2705
  sessionsByPath: this.sessionsByPath,
@@ -1647,7 +2722,16 @@ var BackendRuntime = class {
1647
2722
  return this.readService.getCapabilities();
1648
2723
  }
1649
2724
  async openSession(input) {
1650
- return this.runtimeService.openSession(input);
2725
+ const startedAt = Date.now();
2726
+ try {
2727
+ return await this.runtimeService.openSession(input);
2728
+ } catch {
2729
+ return failure("runtime", startedAt, {
2730
+ code: "project_open_failed",
2731
+ message: "Unable to open project.",
2732
+ projectPath: input.projectPath
2733
+ });
2734
+ }
1651
2735
  }
1652
2736
  openProjectSession(input) {
1653
2737
  return this.runtimeService.openProjectSession(input);
@@ -1658,9 +2742,15 @@ var BackendRuntime = class {
1658
2742
  getProjectOutline(input) {
1659
2743
  return this.readService.getProjectOutline(input);
1660
2744
  }
2745
+ queryEntity(input) {
2746
+ return this.readService.queryEntity(input);
2747
+ }
1661
2748
  validateSession(input) {
1662
2749
  return this.readService.validateSession(input);
1663
2750
  }
2751
+ async preflightTransaction(input) {
2752
+ return this.authoringService.preflightTransaction(input);
2753
+ }
1664
2754
  async applyTransaction(input) {
1665
2755
  return this.authoringService.applyTransaction(input);
1666
2756
  }
@@ -1671,7 +2761,7 @@ var BackendRuntime = class {
1671
2761
  return this.authoringService.materializeSession(input);
1672
2762
  }
1673
2763
  async closeSession(input) {
1674
- return this.runtimeService.closeSession(input);
2764
+ return this.authoringService.runSessionExclusive(input.sessionId, () => this.runtimeService.closeSession(input));
1675
2765
  }
1676
2766
  getEvents(input) {
1677
2767
  return this.eventService.getEvents(input);
@@ -1694,13 +2784,161 @@ var BackendRuntime = class {
1694
2784
  };
1695
2785
  //#endregion
1696
2786
  //#region src/node.ts
2787
+ const PROCESS_START_TIME = Math.trunc(Date.now() - process.uptime() * 1e3);
2788
+ function parseLockMetadata(content) {
2789
+ try {
2790
+ const value = JSON.parse(content);
2791
+ if (value.schemaVersion !== 1 || !Number.isSafeInteger(value.pid) || !Number.isFinite(value.processStartTime) || typeof value.hostname !== "string" || typeof value.token !== "string") return null;
2792
+ return value;
2793
+ } catch {
2794
+ return null;
2795
+ }
2796
+ }
2797
+ function isProcessAlive(metadata) {
2798
+ if (metadata.hostname !== node_os.default.hostname()) return true;
2799
+ if (metadata.pid === process.pid) return Math.abs(metadata.processStartTime - PROCESS_START_TIME) < 1e3;
2800
+ try {
2801
+ process.kill(metadata.pid, 0);
2802
+ return true;
2803
+ } catch (error) {
2804
+ return error.code !== "ESRCH";
2805
+ }
2806
+ }
2807
+ async function recoverStaleLock(filePath) {
2808
+ let before;
2809
+ try {
2810
+ before = await node_fs_promises.default.readFile(filePath, "utf-8");
2811
+ } catch {
2812
+ return false;
2813
+ }
2814
+ const metadata = parseLockMetadata(before);
2815
+ if (!metadata || isProcessAlive(metadata)) return false;
2816
+ const current = parseLockMetadata(await node_fs_promises.default.readFile(filePath, "utf-8").catch(() => ""));
2817
+ if (!current || current.token !== metadata.token) return false;
2818
+ await node_fs_promises.default.unlink(filePath);
2819
+ return true;
2820
+ }
2821
+ async function resolvePathThroughExistingAncestor(filePath) {
2822
+ const missing = [];
2823
+ let candidate = node_path.default.resolve(filePath);
2824
+ for (;;) try {
2825
+ const resolved = await node_fs_promises.default.realpath(candidate);
2826
+ return node_path.default.join(resolved, ...missing);
2827
+ } catch (error) {
2828
+ const code = error.code;
2829
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
2830
+ const parent = node_path.default.dirname(candidate);
2831
+ if (parent === candidate) return node_path.default.resolve(filePath);
2832
+ missing.unshift(node_path.default.basename(candidate));
2833
+ candidate = parent;
2834
+ }
2835
+ }
2836
+ async function pathExists(filePath) {
2837
+ return node_fs_promises.default.stat(filePath).then(() => true, (error) => {
2838
+ if (error.code === "ENOENT") return false;
2839
+ throw error;
2840
+ });
2841
+ }
2842
+ async function assertNoSymlinks(dirPath) {
2843
+ for (const entry of await node_fs_promises.default.readdir(dirPath, { withFileTypes: true })) {
2844
+ const entryPath = node_path.default.join(dirPath, entry.name);
2845
+ if (entry.isSymbolicLink()) throw new Error(`Symbolic links are not supported in project directories: ${entryPath}`);
2846
+ if (entry.isDirectory()) await assertNoSymlinks(entryPath);
2847
+ }
2848
+ }
2849
+ function createStagedNodeFileSystem(projectRoot, stagingRoot) {
2850
+ const { runProjectWriteTransaction: _, ...base } = createNodeBackendFileSystem();
2851
+ const translate = (filePath) => {
2852
+ const relative = node_path.default.relative(projectRoot, node_path.default.resolve(filePath));
2853
+ if (relative.startsWith("..") || node_path.default.isAbsolute(relative)) {
2854
+ const error = /* @__PURE__ */ new Error(`Project path escapes the staged root: ${filePath}`);
2855
+ error.code = "EACCES";
2856
+ throw error;
2857
+ }
2858
+ return node_path.default.join(stagingRoot, relative);
2859
+ };
2860
+ return {
2861
+ ...base,
2862
+ stat: (filePath) => node_fs_promises.default.stat(translate(filePath)),
2863
+ async readdir(dirPath) {
2864
+ const entries = await node_fs_promises.default.readdir(translate(dirPath), { withFileTypes: true });
2865
+ const symlink = entries.find((entry) => entry.isSymbolicLink());
2866
+ if (symlink) throw new Error(`Symbolic links are not supported in project directories: ${node_path.default.join(dirPath, symlink.name)}`);
2867
+ return entries.map((entry) => entry.name);
2868
+ },
2869
+ readFile: (filePath) => node_fs_promises.default.readFile(translate(filePath), "utf-8"),
2870
+ async readFileRaw(filePath) {
2871
+ const buffer = await node_fs_promises.default.readFile(translate(filePath));
2872
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2873
+ },
2874
+ writeFile: (filePath, content) => node_fs_promises.default.writeFile(translate(filePath), content, "utf-8"),
2875
+ writeFileRaw: (filePath, data) => node_fs_promises.default.writeFile(translate(filePath), data),
2876
+ async mkdir(dirPath, options) {
2877
+ await node_fs_promises.default.mkdir(translate(dirPath), { recursive: options?.recursive ?? false });
2878
+ },
2879
+ resolvePath: (filePath) => resolvePathThroughExistingAncestor(translate(filePath)),
2880
+ unlink: (filePath) => node_fs_promises.default.unlink(translate(filePath)),
2881
+ rmdir: (dirPath) => node_fs_promises.default.rmdir(translate(dirPath))
2882
+ };
2883
+ }
2884
+ async function runNodeProjectWriteTransaction(projectRoot, write) {
2885
+ const root = node_path.default.resolve(projectRoot);
2886
+ const parent = node_path.default.dirname(root);
2887
+ const name = node_path.default.basename(root);
2888
+ const staging = node_path.default.join(parent, `.${name}.save-${(0, node_crypto.randomUUID)()}`);
2889
+ const backup = node_path.default.join(parent, `.${name}.save-backup-${(0, node_crypto.randomUUID)()}`);
2890
+ const existed = await pathExists(root);
2891
+ if (existed) {
2892
+ await assertNoSymlinks(root);
2893
+ await node_fs_promises.default.cp(root, staging, {
2894
+ recursive: true,
2895
+ errorOnExist: true,
2896
+ force: false
2897
+ });
2898
+ } else await node_fs_promises.default.mkdir(staging, { recursive: true });
2899
+ try {
2900
+ await write(createStagedNodeFileSystem(root, staging));
2901
+ } catch (error) {
2902
+ await node_fs_promises.default.rm(staging, {
2903
+ recursive: true,
2904
+ force: true
2905
+ });
2906
+ throw error;
2907
+ }
2908
+ if (!existed) {
2909
+ await node_fs_promises.default.rename(staging, root);
2910
+ return;
2911
+ }
2912
+ await node_fs_promises.default.rename(root, backup);
2913
+ try {
2914
+ await node_fs_promises.default.rename(staging, root);
2915
+ } catch (error) {
2916
+ await node_fs_promises.default.rename(backup, root);
2917
+ await node_fs_promises.default.rm(staging, {
2918
+ recursive: true,
2919
+ force: true
2920
+ });
2921
+ throw error;
2922
+ }
2923
+ await node_fs_promises.default.rm(backup, {
2924
+ recursive: true,
2925
+ force: true
2926
+ }).catch(() => void 0);
2927
+ }
1697
2928
  function createNodeBackendFileSystem() {
1698
2929
  return {
1699
2930
  stat(filePath) {
1700
2931
  return node_fs_promises.default.stat(filePath);
1701
2932
  },
1702
- readdir(dirPath) {
1703
- return node_fs_promises.default.readdir(dirPath);
2933
+ async readdir(dirPath) {
2934
+ const entries = await node_fs_promises.default.readdir(dirPath, { withFileTypes: true });
2935
+ const symlink = entries.find((entry) => entry.isSymbolicLink());
2936
+ if (symlink) {
2937
+ const error = /* @__PURE__ */ new Error(`Symbolic links are not supported in project directories: ${node_path.default.join(dirPath, symlink.name)}`);
2938
+ error.code = "ELOOP";
2939
+ throw error;
2940
+ }
2941
+ return entries.map((entry) => entry.name);
1704
2942
  },
1705
2943
  readFile(filePath) {
1706
2944
  return node_fs_promises.default.readFile(filePath, "utf-8");
@@ -1719,16 +2957,32 @@ function createNodeBackendFileSystem() {
1719
2957
  await node_fs_promises.default.mkdir(dirPath, { recursive: options?.recursive ?? false });
1720
2958
  },
1721
2959
  async resolvePath(filePath) {
1722
- try {
1723
- return await node_fs_promises.default.realpath(filePath);
1724
- } catch {
1725
- return node_path.default.resolve(filePath);
1726
- }
2960
+ return resolvePathThroughExistingAncestor(filePath);
1727
2961
  },
2962
+ validateProjectRoot: assertNoSymlinks,
2963
+ getSessionLockPath(canonicalProjectPath) {
2964
+ return node_path.default.join(node_path.default.dirname(canonicalProjectPath), `.${node_path.default.basename(canonicalProjectPath)}.openfairygui.backend.lock`);
2965
+ },
2966
+ runProjectWriteTransaction: runNodeProjectWriteTransaction,
1728
2967
  async acquireSessionLock(filePath) {
1729
- const handle = await node_fs_promises.default.open(filePath, "wx");
2968
+ let handle;
2969
+ try {
2970
+ handle = await node_fs_promises.default.open(filePath, "wx");
2971
+ } catch (error) {
2972
+ if (error.code !== "EEXIST" || !await recoverStaleLock(filePath)) throw error;
2973
+ handle = await node_fs_promises.default.open(filePath, "wx");
2974
+ }
2975
+ const owner = {
2976
+ schemaVersion: 1,
2977
+ pid: process.pid,
2978
+ processStartTime: PROCESS_START_TIME,
2979
+ hostname: node_os.default.hostname(),
2980
+ token: (0, node_crypto.randomUUID)(),
2981
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2982
+ };
1730
2983
  let closed = false;
1731
2984
  let released = false;
2985
+ let metadataWritten = false;
1732
2986
  const closeHandle = async () => {
1733
2987
  if (closed) return;
1734
2988
  await handle.close();
@@ -1736,13 +2990,23 @@ function createNodeBackendFileSystem() {
1736
2990
  };
1737
2991
  return {
1738
2992
  async writeMetadata(content) {
1739
- await handle.writeFile(content, "utf-8");
2993
+ let supplied = {};
2994
+ try {
2995
+ const parsed = JSON.parse(content);
2996
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) supplied = parsed;
2997
+ } catch {}
2998
+ await handle.writeFile(JSON.stringify({
2999
+ ...supplied,
3000
+ ...owner
3001
+ }, null, 2), "utf-8");
3002
+ metadataWritten = true;
1740
3003
  await closeHandle();
1741
3004
  },
1742
3005
  async release() {
1743
3006
  if (released) return;
1744
3007
  await closeHandle();
1745
- await node_fs_promises.default.unlink(filePath).catch((error) => {
3008
+ const current = metadataWritten ? parseLockMetadata(await node_fs_promises.default.readFile(filePath, "utf-8").catch(() => "")) : null;
3009
+ if (!metadataWritten || current?.token === owner.token) await node_fs_promises.default.unlink(filePath).catch((error) => {
1746
3010
  if (error.code !== "ENOENT") throw error;
1747
3011
  });
1748
3012
  released = true;
@@ -1768,11 +3032,7 @@ function createNodeBackendFileSystem() {
1768
3032
  }
1769
3033
  function createNodeBackendHostAdapter() {
1770
3034
  return { lockMetadata(input) {
1771
- return {
1772
- pid: process.pid,
1773
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1774
- canonicalPathKey: input.canonicalPathKey
1775
- };
3035
+ return { canonicalPathKey: input.canonicalPathKey };
1776
3036
  } };
1777
3037
  }
1778
3038
  function createNodeBackendRuntime(options = {}) {