@openfairygui/backend 0.6.3 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/contracts-Bx8HUr7I.d.cts +756 -0
  2. package/dist/contracts-CMQiPEyz.d.mts +756 -0
  3. package/dist/diagnostics-CIe7S-RW.cjs +670 -0
  4. package/dist/diagnostics-CZ12H1Mx.d.cts +1679 -0
  5. package/dist/diagnostics-CpJ8cAP6.d.mts +1679 -0
  6. package/dist/diagnostics-DTnLXQGs.mjs +641 -0
  7. package/dist/docs.cjs +11530 -5940
  8. package/dist/docs.d.cts +5 -185
  9. package/dist/docs.d.mts +5 -185
  10. package/dist/docs.mjs +11528 -5939
  11. package/dist/index.cjs +16 -2703
  12. package/dist/index.d.cts +5 -2362
  13. package/dist/index.d.mts +5 -2362
  14. package/dist/index.mjs +4 -2691
  15. package/dist/node.cjs +367 -2779
  16. package/dist/node.d.cts +4 -724
  17. package/dist/node.d.mts +4 -724
  18. package/dist/node.mjs +359 -2751
  19. package/dist/rolldown-runtime-BJqNVkSG.cjs +28 -0
  20. package/dist/runtime-DYqG77ak.cjs +2249 -0
  21. package/dist/runtime-gStewf1p.mjs +2189 -0
  22. package/package.json +4 -5
  23. package/src/contracts.ts +0 -58
  24. package/src/diagnostics.ts +0 -188
  25. package/src/docs.ts +0 -109
  26. package/src/generated/contracts.ts +0 -24207
  27. package/src/generated/docs.ts +0 -12
  28. package/src/index.ts +0 -99
  29. package/src/node.ts +0 -317
  30. package/src/path-policy.ts +0 -123
  31. package/src/runtime/capabilities.ts +0 -131
  32. package/src/runtime/contracts.ts +0 -672
  33. package/src/runtime.ts +0 -231
  34. package/src/services/artifact-service.ts +0 -19
  35. package/src/services/authoring-service.ts +0 -229
  36. package/src/services/cache-service.ts +0 -81
  37. package/src/services/capture-project.ts +0 -75
  38. package/src/services/context.ts +0 -150
  39. package/src/services/event-service.ts +0 -86
  40. package/src/services/persistence-service.ts +0 -550
  41. package/src/services/read-service.ts +0 -274
  42. package/src/services/runtime-service.ts +0 -342
  43. package/src/services/session-operation-queue.ts +0 -21
  44. package/src/services/session-project-writer.ts +0 -89
  45. package/src/services/session-registry.ts +0 -70
  46. package/src/services/session-utils.ts +0 -45
  47. package/src/services/transaction-preview.ts +0 -116
  48. package/src/storage.ts +0 -232
package/dist/index.cjs CHANGED
@@ -1,2694 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let _openfairygui_core_uam = require("@openfairygui/core/uam");
3
- let _openfairygui_functions_uam = require("@openfairygui/functions/uam");
4
- let _openfairygui_core_project_io = require("@openfairygui/core/project-io");
5
- let _openfairygui_functions = require("@openfairygui/functions");
6
- //#region src/contracts.ts
7
- const BACKEND_CONTRACT_VERSION = "3.0.0";
8
- const BACKEND_CAPABILITY_SCHEMA_VERSION = 12;
9
- const BACKEND_COMPATIBILITY_POLICY = {
10
- incompatibleChange: "requires contractVersion bump",
11
- capabilitySchemaChange: "requires capabilitySchemaVersion bump",
12
- additiveChange: "allowed without breaking existing consumers"
13
- };
14
- //#endregion
15
- //#region src/diagnostics.ts
16
- const selector = {
17
- kind: "revise-selector",
18
- message: "Read the current outline and query the relevant entity. Use its exact identifiers, inspect the reported selector path, then rebuild and preflight the transaction. Do not guess identifiers or retry the unchanged transaction."
19
- };
20
- const source = {
21
- kind: "host-action",
22
- message: "Ask the host to inspect the reported source and hydrate its bytes through project I/O or import. Preserve unsaved work; reopening disk state can discard it. No session hydration/repair API is exposed. Revalidate and replan after the host has supplied a complete project."
23
- };
24
- const path = {
25
- kind: "host-action",
26
- message: "Ask the host to review the attempted path and authorized project root. saveSession only writes the original project; it is not Save As. Do not widen allowed roots or bypass path checks. A separately authorized export may use materializeSession."
27
- };
28
- const unsupported = {
29
- kind: "revise-operation",
30
- message: "Read the operation schema, capabilities and reported target kind/field. Stop unsupported work or replan using supported operations with equivalent intended semantics. Never silently drop fields or objects to make a transaction pass."
31
- };
32
- const payload = {
33
- kind: "revise-operation",
34
- message: "Inspect the diagnostic path and current operation schema or UAM issues. Correct values, required fields and indices against exact queried entities, then preflight. Do not invent defaults or coerce away invalid data."
35
- };
36
- const unchanged = {
37
- kind: "refresh-and-replan",
38
- message: "Query current settings/entity and compare with the request. If already satisfied, report no change; otherwise replan from the current revision. Do not manufacture a mutation or resubmit the same no-op."
39
- };
40
- const duplicate = {
41
- kind: "revise-operation",
42
- message: "Query current entities and resolve the conflicting ID, name or page explicitly. Choose an unused value only when authorized by the intended edit, then preflight. Never overwrite or delete an existing entity to clear the conflict."
43
- };
44
- const references = {
45
- kind: "revise-operation",
46
- message: "Query affected entities and references before editing, moving or removing anything. Replan intended dependent changes together and preflight. Do not delete dependent objects or strip references without authorization."
47
- };
48
- const project = {
49
- kind: "host-action",
50
- message: "Inspect the project path and validation diagnostics with the host. Correct source XML/settings or unsupported geometry using authoritative project data; preserve originals and unsaved work before reopening or validating. Do not guess missing structure or discard rejected content."
51
- };
52
- const capability = {
53
- kind: "host-action",
54
- message: "Read capability/error details. Ask the host to provide the required filesystem, decoder or complete UAM adapter. Preserve the session and unsaved work; do not substitute a lossy path or bypass checks."
55
- };
56
- const write = {
57
- kind: "host-action",
58
- message: "Preserve the dirty session and inspect the error, actual target files and permissions with the host. Partial writes may have changed files: verify or recover them before a newly authorized save. Do not clear dirty state, discard memory or blindly retry."
59
- };
60
- /** Exhaustiveness and exact ownership are checked against the canonical unions. */
61
- const BACKEND_DIAGNOSTIC_GUIDES = [
62
- {
63
- code: "stale_read",
64
- owners: ["backend"],
65
- remediation: {
66
- kind: "refresh-and-replan",
67
- message: "Discard the incomplete model/bytes read and restart with readSessionState. Use its revision for every readResourceBytes call. No historical state is retained or reserved; do not combine resources from different edit revisions."
68
- }
69
- },
70
- {
71
- code: "session_read_failed",
72
- owners: ["backend"],
73
- remediation: {
74
- kind: "host-action",
75
- message: "Inspect error.reason: invalid_query requires valid inputs; not_found/ambiguous requires exact current resource identifiers; unsupported_resource/bytes_unavailable means primary bytes cannot be read from this session. Budget or non-JSON failures require host inspection. Preserve unsaved work; do not save, reopen, repair or mutate the model merely to obtain a read."
76
- }
77
- },
78
- {
79
- code: "transaction_preview_failed",
80
- owners: ["backend"],
81
- remediation: {
82
- kind: "host-action",
83
- 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."
84
- }
85
- },
86
- {
87
- code: "stale_write",
88
- owners: ["backend"],
89
- remediation: {
90
- kind: "refresh-and-replan",
91
- 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."
92
- }
93
- },
94
- {
95
- code: "entity_query_failed",
96
- owners: ["backend"],
97
- remediation: {
98
- kind: "host-action",
99
- 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."
100
- }
101
- },
102
- {
103
- code: "session_not_found",
104
- owners: ["backend"],
105
- remediation: {
106
- kind: "host-action",
107
- 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."
108
- }
109
- },
110
- {
111
- code: "session_close_failed",
112
- owners: ["backend"],
113
- remediation: {
114
- kind: "host-action",
115
- message: "The session and lock ownership remain registered. Inspect the reported lock release failure, correct the storage problem, then retry closeSession with the same session ID. Do not remove the lock file or open a replacement session to bypass the owner."
116
- }
117
- },
118
- {
119
- code: "path_policy_violation",
120
- owners: ["backend"],
121
- remediation: path
122
- },
123
- {
124
- code: "project_root_not_allowed",
125
- owners: ["backend"],
126
- remediation: path
127
- },
128
- {
129
- code: "invalid_package_selector",
130
- owners: ["core.transaction"],
131
- remediation: selector
132
- },
133
- {
134
- code: "invalid_component_selector",
135
- owners: ["core.transaction"],
136
- remediation: selector
137
- },
138
- {
139
- code: "invalid_resource_selector",
140
- owners: ["core.transaction"],
141
- remediation: selector
142
- },
143
- {
144
- code: "invalid_display_node_selector",
145
- owners: ["core.transaction"],
146
- remediation: selector
147
- },
148
- {
149
- code: "invalid_resource_folder_selector",
150
- owners: ["core.transaction"],
151
- remediation: selector
152
- },
153
- {
154
- code: "invalid_branch_selector",
155
- owners: ["core.transaction"],
156
- remediation: selector
157
- },
158
- {
159
- code: "invalid_gear_selector",
160
- owners: ["core.transaction"],
161
- remediation: selector
162
- },
163
- {
164
- code: "invalid_look_gear_selector",
165
- owners: ["core.transaction"],
166
- remediation: selector
167
- },
168
- {
169
- code: "selector_ambiguity",
170
- owners: ["core.transaction"],
171
- remediation: selector
172
- },
173
- {
174
- code: "unavailable_resource_source_bytes",
175
- owners: ["core.transaction"],
176
- remediation: source
177
- },
178
- {
179
- code: "missing_source",
180
- owners: ["core.validation"],
181
- remediation: source
182
- },
183
- {
184
- code: "unreadable_source",
185
- owners: ["core.validation"],
186
- remediation: source
187
- },
188
- {
189
- code: "decode_capability_unavailable",
190
- owners: ["core.validation"],
191
- remediation: {
192
- kind: "host-action",
193
- message: "Validation is incomplete, not passed. Inspect whether source bytes are unloaded or a decoder is unavailable. Ask the host to hydrate sources or provide the required decoder (Node image validation uses optional Sharp), then validate again. Do not install dependencies or change the project automatically."
194
- }
195
- },
196
- {
197
- code: "session_id_conflict",
198
- owners: ["backend"],
199
- remediation: {
200
- kind: "host-action",
201
- message: "Use getSession to inspect the existing session. Reuse it only for the intended project, or choose a new session ID; do not close another owner\\u0027s session to make room."
202
- }
203
- },
204
- {
205
- code: "lock_conflict",
206
- owners: ["backend"],
207
- remediation: {
208
- kind: "host-action",
209
- message: "Another owner holds the project lock. Preserve unsaved work and ask that owner to close its session, then explicitly reopen. Never remove a live lock, force-close a peer, or bypass locking."
210
- }
211
- },
212
- {
213
- code: "event_cursor_invalid",
214
- owners: ["backend"],
215
- remediation: {
216
- kind: "refresh-and-replan",
217
- message: "Read the error and getEvents cursor bounds. Request a fresh bounded event page without the invalid cursor and refresh the current outline before replanning; missing retained history is not evidence that nothing changed."
218
- }
219
- },
220
- {
221
- code: "corrupt_source",
222
- owners: ["core.validation"],
223
- remediation: source
224
- },
225
- {
226
- code: "unsupported_operation",
227
- owners: ["core.transaction"],
228
- remediation: unsupported
229
- },
230
- {
231
- code: "transaction_unsupported",
232
- owners: ["core.transaction"],
233
- remediation: unsupported
234
- },
235
- {
236
- code: "unsupported_display_node_kind",
237
- owners: ["core.transaction"],
238
- remediation: unsupported
239
- },
240
- {
241
- code: "unsupported_cross_package_image_ref",
242
- owners: ["core.transaction"],
243
- remediation: unsupported
244
- },
245
- {
246
- code: "unsupported_gear_kind",
247
- owners: ["core.transaction"],
248
- remediation: unsupported
249
- },
250
- {
251
- code: "unsupported_resource_mutation",
252
- owners: ["core.transaction"],
253
- remediation: unsupported
254
- },
255
- {
256
- code: "unsupported_display_node_mutation",
257
- owners: ["core.transaction"],
258
- remediation: unsupported
259
- },
260
- {
261
- code: "unsupported_text_field_target",
262
- owners: ["core.transaction"],
263
- remediation: unsupported
264
- },
265
- {
266
- code: "unsupported_display_node_field",
267
- owners: ["core.transaction"],
268
- remediation: unsupported
269
- },
270
- {
271
- code: "unsupported_operation_batch",
272
- owners: ["core.transaction"],
273
- remediation: unsupported
274
- },
275
- {
276
- code: "unsupported_resource_kind",
277
- owners: ["core.transaction", "core.validation"],
278
- remediation: unsupported
279
- },
280
- {
281
- code: "invalid_project_settings",
282
- owners: ["core.transaction"],
283
- remediation: payload
284
- },
285
- {
286
- code: "invalid_package_settings",
287
- owners: ["core.transaction"],
288
- remediation: payload
289
- },
290
- {
291
- code: "invalid_display_node_payload",
292
- owners: ["core.transaction"],
293
- remediation: payload
294
- },
295
- {
296
- code: "invalid_resource_name",
297
- owners: ["core.transaction"],
298
- remediation: payload
299
- },
300
- {
301
- code: "invalid_resource_path",
302
- owners: ["core.transaction"],
303
- remediation: payload
304
- },
305
- {
306
- code: "invalid_resource_folder_path",
307
- owners: ["core.transaction"],
308
- remediation: payload
309
- },
310
- {
311
- code: "invalid_resource_folder_atlas",
312
- owners: ["core.transaction"],
313
- remediation: payload
314
- },
315
- {
316
- code: "invalid_attach_index",
317
- owners: ["core.transaction"],
318
- remediation: payload
319
- },
320
- {
321
- code: "invalid_controller_payload",
322
- owners: ["core.transaction"],
323
- remediation: payload
324
- },
325
- {
326
- code: "invalid_transition_payload",
327
- owners: ["core.transaction"],
328
- remediation: payload
329
- },
330
- {
331
- code: "invalid_look_gear_payload",
332
- owners: ["core.transaction"],
333
- remediation: payload
334
- },
335
- {
336
- code: "invalid_gear_payload",
337
- owners: ["core.transaction"],
338
- remediation: payload
339
- },
340
- {
341
- code: "invalid_resource_payload",
342
- owners: ["core.transaction"],
343
- remediation: payload
344
- },
345
- {
346
- code: "invalid_resource_bytes",
347
- owners: ["core.transaction"],
348
- remediation: payload
349
- },
350
- {
351
- code: "invalid_movie_clip_jta",
352
- owners: ["core.transaction"],
353
- remediation: payload
354
- },
355
- {
356
- code: "invalid_resource_index",
357
- owners: ["core.transaction"],
358
- remediation: payload
359
- },
360
- {
361
- code: "invalid_branch_name",
362
- owners: ["core.transaction"],
363
- remediation: payload
364
- },
365
- {
366
- code: "invalid_package_payload",
367
- owners: ["core.transaction"],
368
- remediation: payload
369
- },
370
- {
371
- code: "invalid_package_index",
372
- owners: ["core.transaction"],
373
- remediation: payload
374
- },
375
- {
376
- code: "invalid_component_payload",
377
- owners: ["core.transaction"],
378
- remediation: payload
379
- },
380
- {
381
- code: "invalid_component_index",
382
- owners: ["core.transaction"],
383
- remediation: payload
384
- },
385
- {
386
- code: "invalid_component_move",
387
- owners: ["core.transaction"],
388
- remediation: payload
389
- },
390
- {
391
- code: "invalid_uam",
392
- owners: ["core.transaction", "core.validation"],
393
- remediation: payload
394
- },
395
- {
396
- code: "project_settings_unchanged",
397
- owners: ["core.transaction"],
398
- remediation: unchanged
399
- },
400
- {
401
- code: "package_settings_unchanged",
402
- owners: ["core.transaction"],
403
- remediation: unchanged
404
- },
405
- {
406
- code: "display_node_props_unchanged",
407
- owners: ["core.transaction"],
408
- remediation: unchanged
409
- },
410
- {
411
- code: "resource_folder_atlas_unchanged",
412
- owners: ["core.transaction"],
413
- remediation: unchanged
414
- },
415
- {
416
- code: "duplicate_look_gear_controller",
417
- owners: ["core.transaction"],
418
- remediation: duplicate
419
- },
420
- {
421
- code: "duplicate_transition_name",
422
- owners: ["core.transaction"],
423
- remediation: duplicate
424
- },
425
- {
426
- code: "duplicate_look_gear_state_page",
427
- owners: ["core.transaction"],
428
- remediation: duplicate
429
- },
430
- {
431
- code: "duplicate_gear_controller",
432
- owners: ["core.transaction"],
433
- remediation: duplicate
434
- },
435
- {
436
- code: "duplicate_gear_state_page",
437
- owners: ["core.transaction"],
438
- remediation: duplicate
439
- },
440
- {
441
- code: "duplicate_branch_name",
442
- owners: ["core.transaction"],
443
- remediation: duplicate
444
- },
445
- {
446
- code: "duplicate_component_id",
447
- owners: ["core.transaction"],
448
- remediation: duplicate
449
- },
450
- {
451
- code: "resource_folder_conflict",
452
- owners: ["core.transaction"],
453
- remediation: duplicate
454
- },
455
- {
456
- code: "duplicate_resource_id",
457
- owners: ["core.transaction", "core.validation"],
458
- remediation: duplicate
459
- },
460
- {
461
- code: "duplicate_package_id",
462
- owners: ["core.transaction", "core.validation"],
463
- remediation: duplicate
464
- },
465
- {
466
- code: "duplicate_package_name",
467
- owners: ["core.transaction", "core.validation"],
468
- remediation: duplicate
469
- },
470
- {
471
- code: "resource_folder_not_empty",
472
- owners: ["core.transaction"],
473
- remediation: references
474
- },
475
- {
476
- code: "branch_not_empty",
477
- owners: ["core.transaction"],
478
- remediation: references
479
- },
480
- {
481
- code: "branch_referenced",
482
- owners: ["core.transaction"],
483
- remediation: references
484
- },
485
- {
486
- code: "invalid_resource_reference",
487
- owners: ["core.transaction"],
488
- remediation: references
489
- },
490
- {
491
- code: "invalid_component_reference",
492
- owners: ["core.transaction"],
493
- remediation: references
494
- },
495
- {
496
- code: "invalid_group_reference",
497
- owners: ["core.transaction"],
498
- remediation: references
499
- },
500
- {
501
- code: "package_referenced",
502
- owners: ["core.transaction"],
503
- remediation: references
504
- },
505
- {
506
- code: "component_referenced",
507
- owners: ["core.transaction"],
508
- remediation: references
509
- },
510
- {
511
- code: "component_has_package_dependencies",
512
- owners: ["core.transaction"],
513
- remediation: references
514
- },
515
- {
516
- code: "dangling_resource_reference",
517
- owners: ["core.validation"],
518
- remediation: references
519
- },
520
- {
521
- code: "invalid_project_xml",
522
- owners: ["core.validation"],
523
- remediation: project
524
- },
525
- {
526
- code: "invalid_package_xml",
527
- owners: ["core.validation"],
528
- remediation: project
529
- },
530
- {
531
- code: "invalid_branch_package_xml",
532
- owners: ["core.validation"],
533
- remediation: project
534
- },
535
- {
536
- code: "invalid_component_xml",
537
- owners: ["core.validation"],
538
- remediation: project
539
- },
540
- {
541
- code: "invalid_project_value",
542
- owners: ["core.validation"],
543
- remediation: project
544
- },
545
- {
546
- code: "desktop_incompatible_geometry",
547
- owners: ["core.validation"],
548
- remediation: project
549
- },
550
- {
551
- code: "invalid_settings_json",
552
- owners: ["core.validation"],
553
- remediation: project
554
- },
555
- {
556
- code: "path_collision",
557
- owners: ["core.validation"],
558
- remediation: path
559
- },
560
- {
561
- code: "unsafe_path",
562
- owners: ["core.validation"],
563
- remediation: path
564
- },
565
- {
566
- code: "capability_unavailable",
567
- owners: ["backend"],
568
- remediation: capability
569
- },
570
- {
571
- code: "uam_fidelity_unsupported",
572
- owners: ["backend"],
573
- remediation: capability
574
- },
575
- {
576
- code: "save_partial_failure",
577
- owners: ["backend"],
578
- remediation: write
579
- },
580
- {
581
- code: "write_failed",
582
- owners: ["backend"],
583
- remediation: write
584
- },
585
- {
586
- code: "project_open_failed",
587
- owners: ["backend"],
588
- remediation: project
589
- },
590
- {
591
- code: "materialize_validation_failed",
592
- owners: ["backend"],
593
- remediation: project
594
- },
595
- {
596
- code: "execution_failure",
597
- owners: ["core.transaction"],
598
- remediation: {
599
- kind: "host-action",
600
- 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."
601
- }
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
634
- //#region src/services/context.ts
635
- /** Borrow without copying the entire project before a read has checked its response budget. */
636
- function readView(value) {
637
- return value;
638
- }
639
- /** A detached copy is writable again; this is the only conversion from a borrowed read view. */
640
- function cloneReadData(value) {
641
- return structuredClone(value);
642
- }
643
- function diagnosticFromError(error) {
644
- return {
645
- code: error.code,
646
- message: error.message,
647
- severity: "error"
648
- };
649
- }
650
- function randomId$1() {
651
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
652
- }
653
- function createMeta(stage, startedAt, options) {
654
- return {
655
- requestId: options?.requestId ?? randomId$1(),
656
- sessionId: options?.sessionId,
657
- revision: options?.revision,
658
- durationMs: Math.max(0, Date.now() - startedAt),
659
- warnings: options?.warnings ?? [],
660
- diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
661
- stage,
662
- contractVersion: BACKEND_CONTRACT_VERSION,
663
- capabilitySchemaVersion: 12
664
- };
665
- }
666
- function success(stage, startedAt, data, options) {
667
- return {
668
- ok: true,
669
- meta: createMeta(stage, startedAt, options),
670
- data
671
- };
672
- }
673
- function failure(stage, startedAt, error, session, options) {
674
- const diagnostics = options?.diagnostics ?? [diagnosticFromError(error)];
675
- return {
676
- ok: false,
677
- meta: createMeta(stage, startedAt, {
678
- ...options,
679
- diagnostics
680
- }),
681
- error,
682
- session
683
- };
684
- }
685
- //#endregion
686
- //#region src/services/session-utils.ts
687
- function toSessionSnapshot(session, capabilities) {
688
- return {
689
- sessionId: session.sessionId,
690
- canonicalProjectPath: session.canonicalProjectPath,
691
- revision: session.revision,
692
- lastSavedRevision: session.lastSavedRevision,
693
- dirty: session.dirty,
694
- uamFidelity: session.uamFidelity,
695
- lockHeld: session.lockHeld,
696
- capabilities: cloneReadData(capabilities)
697
- };
698
- }
699
- function createSessionNotFoundError(sessionId) {
700
- return {
701
- code: "session_not_found",
702
- message: `Session was not found: ${sessionId}`,
703
- sessionId
704
- };
705
- }
706
- function createStaleWriteError(session, expectedRevision) {
707
- return {
708
- code: "stale_write",
709
- message: `Expected revision ${expectedRevision} does not match current revision ${session.revision}.`,
710
- sessionId: session.sessionId,
711
- canonicalPathKey: session.canonicalPathKey,
712
- expectedRevision,
713
- actualRevision: session.revision
714
- };
715
- }
716
- //#endregion
717
- //#region src/runtime/contracts.ts
718
- const BACKEND_ENTITY_QUERY_LIMITS = {
719
- maxBytes: 262144,
720
- maxDepth: 32,
721
- maxNodes: 1e5
722
- };
723
- const BACKEND_SESSION_READ_LIMITS = {
724
- model: {
725
- maxBytes: 4194304,
726
- maxDepth: 64,
727
- maxNodes: 5e5
728
- },
729
- resourceBytes: 1048576
730
- };
731
- const BACKEND_TRANSACTION_PREVIEW_LIMITS = {
732
- maxBytes: 262144,
733
- maxEntries: 2e3
734
- };
735
- /** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
736
- const BACKEND_RESOURCE_QUERY_FIELDS = [
737
- "kind",
738
- "id",
739
- "name",
740
- "path",
741
- "exported",
742
- "favorite",
743
- "branch",
744
- "branchItemIds",
745
- "fileName",
746
- "file",
747
- "dimensions",
748
- "image",
749
- "movieClip"
750
- ];
751
- /** A failed staged write with an explicit outcome for the original project. */
752
- var ProjectWriteTransactionError = class extends Error {
753
- code = "project_write_transaction_failed";
754
- /** Recognizes the same contract across separately bundled Node/root or ESM/CJS entries. */
755
- static is(error) {
756
- if (typeof error !== "object" || error === null) return false;
757
- const value = error;
758
- return value.code === "project_write_transaction_failed" && typeof value.message === "string" && typeof value.diskMayBePartiallyUpdated === "boolean" && Array.isArray(value.recoveryPaths) && value.recoveryPaths.every((path) => typeof path === "string");
759
- }
760
- constructor(cause, diskMayBePartiallyUpdated, recoveryPaths = []) {
761
- super(cause instanceof Error ? cause.message : String(cause), { cause });
762
- this.diskMayBePartiallyUpdated = diskMayBePartiallyUpdated;
763
- this.recoveryPaths = recoveryPaths;
764
- this.name = "ProjectWriteTransactionError";
765
- }
766
- };
767
- //#endregion
768
- //#region src/services/capture-project.ts
769
- function createCaptureFileSystem(files, directories) {
770
- const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
771
- return {
772
- async readFile(filePath) {
773
- const value = files.get(normalize(filePath));
774
- if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
775
- return value;
776
- },
777
- async readFileRaw(filePath) {
778
- const value = files.get(normalize(filePath));
779
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
780
- return value.slice();
781
- },
782
- async writeFile(filePath, content) {
783
- files.set(normalize(filePath), content);
784
- },
785
- async writeFileRaw(filePath, data) {
786
- files.set(normalize(filePath), data.slice());
787
- },
788
- async mkdir(dirPath) {
789
- directories.add(normalize(dirPath));
790
- },
791
- async readdir() {
792
- return [];
793
- },
794
- async exists(filePath) {
795
- return files.has(normalize(filePath));
796
- },
797
- join(...paths) {
798
- return normalize(paths.filter(Boolean).join("/"));
799
- },
800
- dirname(filePath) {
801
- const normalized = normalize(filePath);
802
- const separator = normalized.lastIndexOf("/");
803
- return separator < 0 ? "" : normalized.slice(0, separator);
804
- },
805
- async unlink(filePath) {
806
- files.delete(normalize(filePath));
807
- }
808
- };
809
- }
810
- function capturedFilesEqual(left, right) {
811
- if (left.size !== right.size) return false;
812
- for (const [filePath, leftValue] of left) {
813
- const rightValue = right.get(filePath);
814
- if (typeof leftValue === "string") {
815
- if (leftValue !== rightValue) return false;
816
- continue;
817
- }
818
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
819
- for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
820
- }
821
- return true;
822
- }
823
- function capturedDirectoriesEqual(left, right) {
824
- return left.size === right.size && [...left].every((directory) => right.has(directory));
825
- }
826
- /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
827
- async function captureProject(document, fairyFileName) {
828
- const files = /* @__PURE__ */ new Map();
829
- const directories = /* @__PURE__ */ new Set();
830
- await new _openfairygui_core_project_io.ProjectWriter(createCaptureFileSystem(files, directories)).write(document, fairyFileName);
831
- return {
832
- files,
833
- directories
834
- };
835
- }
836
- //#endregion
837
- //#region src/services/transaction-preview.ts
838
- /** Keep child identities/order on their parent, and compare each child's own properties separately. */
839
- function entities(project) {
840
- const result = /* @__PURE__ */ new Map();
841
- function add(target, properties) {
842
- const key = JSON.stringify(target);
843
- if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
844
- result.set(key, {
845
- target,
846
- properties
847
- });
848
- }
849
- const { packages, ...properties } = project;
850
- add({ kind: "project" }, {
851
- ...properties,
852
- packages: packages.map((pkg) => pkg.id)
853
- });
854
- for (const { resources, ...pkg } of packages) {
855
- const packageId = pkg.id;
856
- add({
857
- kind: "package",
858
- selector: { packageId }
859
- }, {
860
- ...pkg,
861
- resources: resources.map((resource) => resource.id)
862
- });
863
- for (const resource of resources) {
864
- const resourceTarget = {
865
- kind: "resource",
866
- selector: {
867
- packageId,
868
- resourceId: resource.id
869
- }
870
- };
871
- if (resource.kind !== "component") {
872
- add(resourceTarget, resource);
873
- continue;
874
- }
875
- const { component, ...resourceProperties } = resource;
876
- add(resourceTarget, resourceProperties);
877
- const { displayList, controllers, transitions, ...componentProperties } = component;
878
- const selector = {
879
- packageId,
880
- componentResourceId: resource.id
881
- };
882
- add({
883
- kind: "component",
884
- selector
885
- }, {
886
- ...componentProperties,
887
- displayList: displayList.map((node) => node.id),
888
- controllers: controllers.map((controller) => controller.name),
889
- transitions: transitions.map((transition) => transition.name)
890
- });
891
- for (const node of displayList) add({
892
- kind: "displayNode",
893
- selector: {
894
- ...selector,
895
- displayNodeId: node.id
896
- }
897
- }, node);
898
- for (const controller of controllers) add({
899
- kind: "controller",
900
- selector: {
901
- ...selector,
902
- controllerName: controller.name
903
- }
904
- }, controller);
905
- for (const transition of transitions) add({
906
- kind: "transition",
907
- selector: {
908
- ...selector,
909
- transitionName: transition.name
910
- }
911
- }, transition);
912
- }
913
- }
914
- return result;
915
- }
916
- function equal(left, right, depth = 0) {
917
- if (left === right) return true;
918
- if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
919
- 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]);
920
- if (depth > 128) throw new Error("Preview property comparison exceeds the supported nesting depth.");
921
- if (Array.isArray(left) !== Array.isArray(right)) return false;
922
- if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
923
- const a = left, b = right;
924
- const keys = Object.keys(a);
925
- return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
926
- }
927
- var PreviewBudgetError = class extends Error {};
928
- /** No host filesystem, cache, event or session mutation is involved in the projection. */
929
- async function previewTransactionImpact(session, project, fileSystemAvailable) {
930
- const impact = {
931
- entities: [],
932
- files: []
933
- };
934
- const before = entities(session.project), after = entities(project);
935
- let entries = 0, bytes = 0;
936
- const encoder = new TextEncoder();
937
- function count(value) {
938
- bytes += encoder.encode(JSON.stringify(value)).byteLength;
939
- 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.");
940
- }
941
- for (const key of new Set([...before.keys(), ...after.keys()])) {
942
- const previous = before.get(key), next = after.get(key);
943
- const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])].filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
944
- if (!fields.length && previous && next) continue;
945
- const change = {
946
- target: (next ?? previous).target,
947
- change: !previous ? "added" : !next ? "removed" : "updated",
948
- fields
949
- };
950
- count(change);
951
- impact.entities.push(change);
952
- }
953
- const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, "/").split("/").at(-1) : "Project.fairy";
954
- const [previousFiles, nextFiles] = await Promise.all([captureProject((0, _openfairygui_core_uam.materializeUamProject)(session.project, { validate: false }), fairyFileName), captureProject((0, _openfairygui_core_uam.materializeUamProject)(project), fairyFileName)]);
955
- for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
956
- const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
957
- if (equal(previous, next)) continue;
958
- const change = {
959
- path,
960
- kind: "file",
961
- change: previous === void 0 ? "added" : next === void 0 ? "removed" : "updated"
962
- };
963
- count(change);
964
- impact.files.push(change);
965
- }
966
- for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
967
- if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
968
- const change = {
969
- path,
970
- kind: "directory",
971
- change: nextFiles.directories.has(path) ? "added" : "removed"
972
- };
973
- count(change);
974
- impact.files.push(change);
975
- }
976
- impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
977
- const preview = {
978
- sessionId: session.sessionId,
979
- baseRevision: session.revision,
980
- projectedRevision: session.revision + 1,
981
- mode: "execute-and-discard",
982
- impact,
983
- persistence: {
984
- requiredAfterApply: true,
985
- fileSystemAvailable,
986
- uamFidelity: session.uamFidelity,
987
- writeVerified: false,
988
- nextAction: session.uamFidelity === "unsupported" || !fileSystemAvailable ? "host-action" : session.fileSystem ? "saveSession" : "materializeSession"
989
- }
990
- };
991
- if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction preview exceeds the response byte budget.");
992
- return preview;
993
- }
994
- //#endregion
995
- //#region src/services/authoring-service.ts
996
- function sourceFileKey(source) {
997
- return [
998
- source.branch,
999
- source.packageName,
1000
- source.path,
1001
- source.fileName
1002
- ].join("\0");
1003
- }
1004
- function resourceFolderKey(folder) {
1005
- return [
1006
- folder.branch,
1007
- folder.packageName,
1008
- folder.path
1009
- ].join("\0");
1010
- }
1011
- function branchDirectoryKey(directory) {
1012
- return [directory.branch, directory.packageName ?? ""].join("\0");
1013
- }
1014
- function recordStaleProjectFiles(session, previousProject, nextProject) {
1015
- if (!session.fileSystem) return;
1016
- for (const source of (0, _openfairygui_core_uam.staleSourceFiles)(previousProject, nextProject)) session.pendingStaleSourceFiles.set(sourceFileKey(source), source);
1017
- for (const source of (0, _openfairygui_core_uam.staleSourceFiles)(nextProject, previousProject)) session.pendingStaleSourceFiles.delete(sourceFileKey(source));
1018
- for (const folder of (0, _openfairygui_core_uam.staleResourceFolders)(previousProject, nextProject)) session.pendingStaleResourceFolders.set(resourceFolderKey(folder), folder);
1019
- for (const folder of (0, _openfairygui_core_uam.staleResourceFolders)(nextProject, previousProject)) session.pendingStaleResourceFolders.delete(resourceFolderKey(folder));
1020
- for (const directory of (0, _openfairygui_core_uam.staleBranchDirectories)(previousProject, nextProject)) session.pendingStaleBranchDirectories.set(branchDirectoryKey(directory), directory);
1021
- for (const directory of (0, _openfairygui_core_uam.staleBranchDirectories)(nextProject, previousProject)) session.pendingStaleBranchDirectories.delete(branchDirectoryKey(directory));
1022
- }
1023
- function toBackendDiagnostics(error) {
1024
- return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({
1025
- ...diagnostic,
1026
- owner: "core.transaction"
1027
- })) : [{
1028
- code: error.code,
1029
- owner: "core.transaction",
1030
- message: error.message,
1031
- severity: "error",
1032
- operationKind: error.operationKind,
1033
- opIndex: error.opIndex,
1034
- opId: error.opId
1035
- }];
1036
- }
1037
- function detachSharedByteViews(value, seen = /* @__PURE__ */ new WeakSet()) {
1038
- if (!value || typeof value !== "object" || seen.has(value)) return;
1039
- seen.add(value);
1040
- for (const [key, child] of Object.entries(value)) {
1041
- if (child instanceof Uint8Array) {
1042
- if (typeof SharedArrayBuffer !== "undefined" && child.buffer instanceof SharedArrayBuffer) value[key] = new Uint8Array(child);
1043
- continue;
1044
- }
1045
- detachSharedByteViews(child, seen);
1046
- }
1047
- }
1048
- var AuthoringService = class {
1049
- constructor(context, cacheService, eventService, sessionOperations) {
1050
- this.context = context;
1051
- this.cacheService = cacheService;
1052
- this.eventService = eventService;
1053
- this.sessionOperations = sessionOperations;
1054
- }
1055
- async preflightTransaction(input) {
1056
- const queuedInput = structuredClone(input);
1057
- detachSharedByteViews(queuedInput);
1058
- return this.sessionOperations.run(queuedInput.sessionId, async () => {
1059
- const startedAt = Date.now();
1060
- const session = this.context.sessions.get(queuedInput.sessionId);
1061
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1062
- const meta = {
1063
- sessionId: session.sessionId,
1064
- revision: session.revision
1065
- };
1066
- if (queuedInput.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, queuedInput.expectedRevision), toSessionSnapshot(session, this.context.capabilities), meta);
1067
- const project = structuredClone(session.project);
1068
- detachSharedByteViews(project);
1069
- const result = await (0, _openfairygui_functions_uam.applyUamTransactionAppAsync)({
1070
- project,
1071
- operations: queuedInput.operations
1072
- });
1073
- if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1074
- if (!result.ok) return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
1075
- ...meta,
1076
- diagnostics: toBackendDiagnostics(result.error)
1077
- });
1078
- try {
1079
- const preview = await previewTransactionImpact({
1080
- ...session,
1081
- project
1082
- }, result.project, Boolean(session.fileSystem));
1083
- if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
1084
- return success("authoring", startedAt, preview, meta);
1085
- } catch (error) {
1086
- return failure("authoring", startedAt, {
1087
- code: "transaction_preview_failed",
1088
- sessionId: session.sessionId,
1089
- reason: error instanceof PreviewBudgetError ? "response_budget_exceeded" : "projection_failed",
1090
- message: error instanceof Error ? error.message : String(error)
1091
- }, toSessionSnapshot(session, this.context.capabilities), meta);
1092
- }
1093
- });
1094
- }
1095
- async applyTransaction(input) {
1096
- const queuedInput = structuredClone(input);
1097
- detachSharedByteViews(queuedInput);
1098
- return this.sessionOperations.run(queuedInput.sessionId, () => this.applyTransactionExclusive(queuedInput));
1099
- }
1100
- async applyTransactionExclusive(input) {
1101
- const startedAt = Date.now();
1102
- const session = this.context.sessions.get(input.sessionId);
1103
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
1104
- if (input.expectedRevision !== session.revision) {
1105
- this.eventService.emit({
1106
- kind: "transaction.rejected",
1107
- sessionId: session.sessionId,
1108
- canonicalPathKey: session.canonicalPathKey,
1109
- revision: session.revision
1110
- });
1111
- return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
1112
- sessionId: session.sessionId,
1113
- revision: session.revision
1114
- });
1115
- }
1116
- const result = await (0, _openfairygui_functions_uam.applyUamTransactionAppAsync)({
1117
- project: session.project,
1118
- operations: input.operations
1119
- });
1120
- if (this.context.sessions.get(input.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
1121
- if (result.ok === false) {
1122
- const diagnostics = toBackendDiagnostics(result.error);
1123
- this.eventService.emit({
1124
- kind: "transaction.rejected",
1125
- sessionId: session.sessionId,
1126
- canonicalPathKey: session.canonicalPathKey,
1127
- revision: session.revision,
1128
- diagnostics
1129
- });
1130
- return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
1131
- sessionId: session.sessionId,
1132
- revision: session.revision,
1133
- diagnostics
1134
- });
1135
- }
1136
- recordStaleProjectFiles(session, session.project, result.project);
1137
- session.project = result.project;
1138
- session.revision += 1;
1139
- session.dirty = true;
1140
- const cacheEntry = this.cacheService.invalidateSession(session);
1141
- this.eventService.emit({
1142
- kind: "transaction.applied",
1143
- sessionId: session.sessionId,
1144
- canonicalPathKey: session.canonicalPathKey,
1145
- revision: session.revision
1146
- });
1147
- this.eventService.emit({
1148
- kind: "cache.invalidated",
1149
- sessionId: session.sessionId,
1150
- canonicalPathKey: session.canonicalPathKey,
1151
- revision: session.revision,
1152
- cacheRevision: cacheEntry.revision
1153
- });
1154
- return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1155
- sessionId: session.sessionId,
1156
- revision: session.revision
1157
- });
1158
- }
1159
- };
1160
- //#endregion
1161
- //#region src/path-policy.ts
1162
- function normalizeComparablePath(value) {
1163
- const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
1164
- const driveMatch = normalized.match(/^([a-z]:)(?:\/(.*))?$/i);
1165
- const drivePrefix = driveMatch?.[1].toLowerCase() ?? "";
1166
- const remainder = driveMatch ? driveMatch[2] ?? "" : normalized;
1167
- const hasRoot = driveMatch ? true : remainder.startsWith("/");
1168
- const rawSegments = remainder.split("/").filter((segment) => segment.length > 0);
1169
- const segments = [];
1170
- for (const segment of rawSegments) {
1171
- if (segment === ".") continue;
1172
- if (segment === "..") {
1173
- if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
1174
- else if (!hasRoot) segments.push("..");
1175
- continue;
1176
- }
1177
- segments.push(segment);
1178
- }
1179
- const joined = segments.join("/");
1180
- return (drivePrefix ? `${drivePrefix}/${joined}`.replace(/\/$/, "") : hasRoot ? `/${joined}`.replace(/\/$/, "") : joined || ".").toLowerCase();
1181
- }
1182
- function createRuntimePathPolicy() {
1183
- return {
1184
- canonicalization: "realpath+normalized-casefold",
1185
- sessionIdentity: "project-root",
1186
- saveTarget: "opened-project-only",
1187
- outputTargets: "deferred",
1188
- workspaceBoundary: "project-root-only"
1189
- };
1190
- }
1191
- async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
1192
- const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
1193
- const root = normalizeComparablePath(resolvedRoot);
1194
- const target = normalizeComparablePath(resolvedTarget);
1195
- if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
1196
- if (target === root || target.startsWith(`${root}/`)) return;
1197
- const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
1198
- error.code = "EACCES";
1199
- throw error;
1200
- }
1201
- async function resolveFairyPath(fileSystem, input) {
1202
- const resolvedInput = fileSystem.resolve(input);
1203
- const stat = await fileSystem.stat(resolvedInput);
1204
- if (stat.isFile() && resolvedInput.endsWith(".fairy")) return await fileSystem.resolvePath(resolvedInput);
1205
- if (stat.isDirectory()) {
1206
- const fairyFiles = (await fileSystem.readdir(resolvedInput)).filter((entry) => entry.endsWith(".fairy"));
1207
- if (fairyFiles.length === 1) return await fileSystem.resolvePath(fileSystem.join(resolvedInput, fairyFiles[0]));
1208
- if (fairyFiles.length > 1) throw new Error(`Multiple .fairy files found in ${resolvedInput}: ${fairyFiles.join(", ")}`);
1209
- throw new Error(`No .fairy file found in ${resolvedInput}`);
1210
- }
1211
- throw new Error(`Input is not a .fairy file or directory: ${resolvedInput}`);
1212
- }
1213
- async function resolveCanonicalProjectRoot(fileSystem, input) {
1214
- const fairyPath = await resolveFairyPath(fileSystem, input);
1215
- const canonicalProjectPath = await fileSystem.resolvePath(fileSystem.dirname(fairyPath));
1216
- return {
1217
- fairyPath,
1218
- canonicalProjectPath,
1219
- canonicalPathKey: normalizeComparablePath(canonicalProjectPath)
1220
- };
1221
- }
1222
- async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
1223
- if (!targetPath) return null;
1224
- const attemptedPath = await fileSystem.resolvePath(fileSystem.resolve(targetPath));
1225
- const allowedPath = await fileSystem.resolvePath(openedFairyPath);
1226
- if (normalizeComparablePath(attemptedPath) === normalizeComparablePath(allowedPath)) return null;
1227
- return {
1228
- code: "path_policy_violation",
1229
- message: `Save target is restricted to the originally opened project file: ${allowedPath}`,
1230
- policy: "save_target",
1231
- attemptedPath,
1232
- allowedPath
1233
- };
1234
- }
1235
- //#endregion
1236
- //#region src/services/session-project-writer.ts
1237
- function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
1238
- const contained = async (targetPath, operation) => {
1239
- await assertProjectPathContained(fileSystem, projectRoot, targetPath);
1240
- return operation();
1241
- };
1242
- async function trackWrite(targetPath, write) {
1243
- try {
1244
- const result = await contained(targetPath, write);
1245
- writtenPaths.push(targetPath);
1246
- return result;
1247
- } catch (error) {
1248
- failedPaths.push(targetPath);
1249
- throw error;
1250
- }
1251
- }
1252
- return {
1253
- resolvePath: (path) => contained(path, () => fileSystem.resolvePath(path)),
1254
- readFile: (path) => contained(path, () => fileSystem.readFile(path)),
1255
- readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
1256
- writeFile: (path, content) => trackWrite(path, async () => {
1257
- await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
1258
- await fileSystem.writeFile(path, content);
1259
- }),
1260
- writeFileRaw: (path, data) => trackWrite(path, async () => {
1261
- await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
1262
- await fileSystem.writeFileRaw(path, data);
1263
- }),
1264
- mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
1265
- readdir: (path) => contained(path, () => fileSystem.readdir(path)),
1266
- async exists(path) {
1267
- await assertProjectPathContained(fileSystem, projectRoot, path);
1268
- try {
1269
- await fileSystem.stat(path);
1270
- return true;
1271
- } catch {
1272
- return false;
1273
- }
1274
- },
1275
- join: (...paths) => fileSystem.join(...paths),
1276
- dirname: (path) => fileSystem.dirname(path),
1277
- unlink: (path) => trackWrite(path, () => fileSystem.unlink(path)),
1278
- rmdir: (path) => trackWrite(path, () => fileSystem.rmdir(path))
1279
- };
1280
- }
1281
- async function writeSessionProject(input) {
1282
- const projectRoot = input.fileSystem.dirname(input.fairyPath);
1283
- const write = async (fileSystem) => {
1284
- await new _openfairygui_core_project_io.ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
1285
- staleSourceFiles: input.staleSourceFiles,
1286
- staleResourceFolders: input.staleResourceFolders,
1287
- staleBranchDirectories: input.staleBranchDirectories
1288
- });
1289
- };
1290
- if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
1291
- try {
1292
- await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
1293
- } catch (error) {
1294
- if (ProjectWriteTransactionError.is(error) && !error.diskMayBePartiallyUpdated) input.writtenPaths.length = 0;
1295
- throw error;
1296
- }
1297
- }
1298
- //#endregion
1299
- //#region src/services/persistence-service.ts
1300
- function createCapabilityUnavailableError$1(message) {
1301
- return {
1302
- code: "capability_unavailable",
1303
- message,
1304
- capability: "fileSystem",
1305
- requiredAdapter: "BackendFileSystem"
1306
- };
1307
- }
1308
- function createUamFidelityUnsupportedError(session) {
1309
- return {
1310
- code: "uam_fidelity_unsupported",
1311
- message: "The source project contains formal properties that the current UAM cannot preserve.",
1312
- sessionId: session.sessionId,
1313
- canonicalPathKey: session.canonicalPathKey
1314
- };
1315
- }
1316
- function validationDiagnostics(sessionProject) {
1317
- return (0, _openfairygui_core_uam.validateUamProject)(sessionProject).map((issue) => ({
1318
- code: "materialize_validation_failed",
1319
- message: issue.message,
1320
- severity: "error",
1321
- path: issue.path,
1322
- operationKind: "materializeSession"
1323
- }));
1324
- }
1325
- function toMaterializeSnapshot(session, capabilities, input) {
1326
- return {
1327
- ...toSessionSnapshot(session, capabilities),
1328
- mode: "fullProject",
1329
- reason: input.reason,
1330
- materializeRevision: session.revision,
1331
- saveRevision: session.lastSavedRevision,
1332
- writtenPaths: [...input.writtenPaths],
1333
- skippedPaths: [...input.skippedPaths],
1334
- diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic }))
1335
- };
1336
- }
1337
- function storageCanonicalTarget(input) {
1338
- const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || ".");
1339
- return {
1340
- fileSystem: input.fileSystem,
1341
- fairyPath: input.fairyPath,
1342
- canonicalProjectPath,
1343
- canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath)
1344
- };
1345
- }
1346
- var PersistenceService = class {
1347
- constructor(context, cacheService, eventService, sessionOperations) {
1348
- this.context = context;
1349
- this.cacheService = cacheService;
1350
- this.eventService = eventService;
1351
- this.sessionOperations = sessionOperations;
1352
- }
1353
- async saveSession(input) {
1354
- if (input.force === true || input.mode === "materializeCleanSession") return this.materializeSession({
1355
- sessionId: input.sessionId,
1356
- expectedRevision: input.expectedRevision,
1357
- targetPath: input.targetPath,
1358
- fileSystem: input.fileSystem,
1359
- mode: "fullProject",
1360
- reason: "force_save"
1361
- });
1362
- const captured = { ...input };
1363
- return this.sessionOperations.run(captured.sessionId, () => this.saveSessionExclusive(captured));
1364
- }
1365
- finishSuccessfulSave(session) {
1366
- session.lastSavedRevision = session.revision;
1367
- session.dirty = false;
1368
- const cacheEntry = this.cacheService.refreshSession(session);
1369
- this.eventService.emit({
1370
- kind: "save.completed",
1371
- sessionId: session.sessionId,
1372
- canonicalPathKey: session.canonicalPathKey,
1373
- revision: session.revision
1374
- });
1375
- this.eventService.emit({
1376
- kind: "cache.updated",
1377
- sessionId: session.sessionId,
1378
- canonicalPathKey: session.canonicalPathKey,
1379
- revision: session.revision,
1380
- cacheRevision: cacheEntry.revision
1381
- });
1382
- }
1383
- async saveSessionExclusive(input) {
1384
- const startedAt = Date.now();
1385
- const session = this.context.sessions.get(input.sessionId);
1386
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
1387
- const fileSystem = session.fileSystem ?? input.fileSystem;
1388
- if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("saveSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
1389
- sessionId: session.sessionId,
1390
- revision: session.revision
1391
- });
1392
- if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
1393
- sessionId: session.sessionId,
1394
- revision: session.revision
1395
- });
1396
- const targetViolation = await validateSaveTarget(fileSystem, session.fairyPath, input.targetPath);
1397
- if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
1398
- sessionId: session.sessionId,
1399
- revision: session.revision
1400
- });
1401
- if (!session.dirty) return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1402
- sessionId: session.sessionId,
1403
- revision: session.revision
1404
- });
1405
- if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
1406
- sessionId: session.sessionId,
1407
- revision: session.revision
1408
- });
1409
- const committedPaths = [];
1410
- const failedPaths = [];
1411
- this.eventService.emit({
1412
- kind: "save.started",
1413
- sessionId: session.sessionId,
1414
- canonicalPathKey: session.canonicalPathKey,
1415
- revision: session.revision
1416
- });
1417
- try {
1418
- await writeSessionProject({
1419
- fileSystem,
1420
- document: (0, _openfairygui_core_uam.materializeUamProject)(session.project),
1421
- fairyPath: session.fairyPath,
1422
- staleSourceFiles: [...session.pendingStaleSourceFiles.values()],
1423
- staleResourceFolders: [...session.pendingStaleResourceFolders.values()],
1424
- staleBranchDirectories: [...session.pendingStaleBranchDirectories.values()],
1425
- writtenPaths: committedPaths,
1426
- failedPaths
1427
- });
1428
- session.fileSystem ??= fileSystem;
1429
- session.pendingStaleSourceFiles.clear();
1430
- session.pendingStaleResourceFolders.clear();
1431
- session.pendingStaleBranchDirectories.clear();
1432
- (0, _openfairygui_core_uam.commitUamProjectSourcePaths)(session.project);
1433
- this.finishSuccessfulSave(session);
1434
- return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1435
- sessionId: session.sessionId,
1436
- revision: session.revision
1437
- });
1438
- } catch (error) {
1439
- this.cacheService.invalidateSession(session);
1440
- this.eventService.emit({
1441
- kind: "save.failed",
1442
- sessionId: session.sessionId,
1443
- canonicalPathKey: session.canonicalPathKey,
1444
- revision: session.revision
1445
- });
1446
- return failure("authoring", startedAt, {
1447
- code: "save_partial_failure",
1448
- message: error instanceof Error ? error.message : String(error),
1449
- sessionId: session.sessionId,
1450
- canonicalPathKey: session.canonicalPathKey,
1451
- attemptedRevision: session.revision,
1452
- lastSavedRevision: session.lastSavedRevision,
1453
- committedPaths,
1454
- failedPaths,
1455
- diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
1456
- ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
1457
- }, toSessionSnapshot(session, this.context.capabilities), {
1458
- sessionId: session.sessionId,
1459
- revision: session.revision
1460
- });
1461
- }
1462
- }
1463
- async materializeSession(input) {
1464
- const captured = {
1465
- ...input,
1466
- storage: input.storage && { ...input.storage }
1467
- };
1468
- return this.sessionOperations.run(captured.sessionId, () => this.materializeSessionExclusive(captured));
1469
- }
1470
- async materializeSessionExclusive(input) {
1471
- const startedAt = Date.now();
1472
- const session = this.context.sessions.get(input.sessionId);
1473
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
1474
- if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
1475
- sessionId: session.sessionId,
1476
- revision: session.revision
1477
- });
1478
- const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
1479
- const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
1480
- if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("materializeSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
1481
- sessionId: session.sessionId,
1482
- revision: session.revision
1483
- });
1484
- const fairyPath = storageTarget?.fairyPath ?? session.fairyPath;
1485
- if (session.lockHeld && (fileSystem !== session.fileSystem || fairyPath !== session.fairyPath || storageTarget && (storageTarget.canonicalPathKey !== session.canonicalPathKey || storageTarget.canonicalProjectPath !== session.canonicalProjectPath))) return failure("authoring", startedAt, {
1486
- code: "path_policy_violation",
1487
- message: "A locked file-backed session must keep its opened storage binding.",
1488
- policy: "save_target",
1489
- attemptedPath: fairyPath,
1490
- allowedPath: session.fairyPath
1491
- }, toSessionSnapshot(session, this.context.capabilities), {
1492
- sessionId: session.sessionId,
1493
- revision: session.revision
1494
- });
1495
- const targetViolation = await validateSaveTarget(fileSystem, fairyPath, input.targetPath);
1496
- if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
1497
- sessionId: session.sessionId,
1498
- revision: session.revision
1499
- });
1500
- if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
1501
- sessionId: session.sessionId,
1502
- revision: session.revision
1503
- });
1504
- const diagnostics = validationDiagnostics(session.project);
1505
- if (diagnostics.length > 0) return failure("authoring", startedAt, {
1506
- code: "materialize_validation_failed",
1507
- message: `UAM materialize validation failed with ${diagnostics.length} issue(s).`,
1508
- sessionId: session.sessionId,
1509
- canonicalPathKey: session.canonicalPathKey,
1510
- issueCount: diagnostics.length,
1511
- diagnostics
1512
- }, toSessionSnapshot(session, this.context.capabilities), {
1513
- sessionId: session.sessionId,
1514
- revision: session.revision,
1515
- diagnostics
1516
- });
1517
- let document;
1518
- try {
1519
- document = (0, _openfairygui_core_uam.materializeUamProject)(session.project);
1520
- } catch (error) {
1521
- const diagnosticsFromError = [{
1522
- code: "materialize_validation_failed",
1523
- message: error instanceof Error ? error.message : String(error),
1524
- severity: "error",
1525
- operationKind: "materializeSession"
1526
- }];
1527
- return failure("authoring", startedAt, {
1528
- code: "materialize_validation_failed",
1529
- message: error instanceof Error ? error.message : String(error),
1530
- sessionId: session.sessionId,
1531
- canonicalPathKey: session.canonicalPathKey,
1532
- issueCount: diagnosticsFromError.length,
1533
- diagnostics: diagnosticsFromError
1534
- }, toSessionSnapshot(session, this.context.capabilities), {
1535
- sessionId: session.sessionId,
1536
- revision: session.revision,
1537
- diagnostics: diagnosticsFromError
1538
- });
1539
- }
1540
- const writtenPaths = [];
1541
- const failedPaths = [];
1542
- const skippedPaths = [];
1543
- const reservation = storageTarget ? this.context.sessions.reserve(session.sessionId, storageTarget) : null;
1544
- if (reservation && "code" in reservation) return failure("authoring", startedAt, reservation, toSessionSnapshot(session, this.context.capabilities), {
1545
- sessionId: session.sessionId,
1546
- revision: session.revision
1547
- });
1548
- this.eventService.emit({
1549
- kind: "save.started",
1550
- sessionId: session.sessionId,
1551
- canonicalPathKey: storageTarget?.canonicalPathKey ?? session.canonicalPathKey,
1552
- revision: session.revision
1553
- });
1554
- try {
1555
- const isSessionStorageTarget = fileSystem === session.fileSystem && fairyPath === session.fairyPath;
1556
- await writeSessionProject({
1557
- fileSystem,
1558
- document,
1559
- fairyPath,
1560
- staleSourceFiles: isSessionStorageTarget ? [...session.pendingStaleSourceFiles.values()] : [],
1561
- staleResourceFolders: isSessionStorageTarget ? [...session.pendingStaleResourceFolders.values()] : [],
1562
- staleBranchDirectories: isSessionStorageTarget ? [...session.pendingStaleBranchDirectories.values()] : [],
1563
- writtenPaths,
1564
- failedPaths
1565
- });
1566
- if (isSessionStorageTarget) {
1567
- session.pendingStaleSourceFiles.clear();
1568
- session.pendingStaleResourceFolders.clear();
1569
- session.pendingStaleBranchDirectories.clear();
1570
- }
1571
- if (storageTarget && !isSessionStorageTarget) {
1572
- session.pendingStaleSourceFiles.clear();
1573
- session.pendingStaleResourceFolders.clear();
1574
- session.pendingStaleBranchDirectories.clear();
1575
- }
1576
- if (isSessionStorageTarget || storageTarget) (0, _openfairygui_core_uam.commitUamProjectSourcePaths)(session.project);
1577
- reservation?.commit(session);
1578
- this.finishSuccessfulSave(session);
1579
- return success("authoring", startedAt, toMaterializeSnapshot(session, this.context.capabilities, {
1580
- reason: input.reason,
1581
- writtenPaths,
1582
- skippedPaths,
1583
- diagnostics: []
1584
- }), {
1585
- sessionId: session.sessionId,
1586
- revision: session.revision
1587
- });
1588
- } catch (error) {
1589
- const diagnosticsFromError = [{
1590
- code: "write_failed",
1591
- message: error instanceof Error ? error.message : String(error),
1592
- severity: "error",
1593
- path: failedPaths[0],
1594
- operationKind: "materializeSession"
1595
- }];
1596
- this.cacheService.invalidateSession(session);
1597
- this.eventService.emit({
1598
- kind: "save.failed",
1599
- sessionId: session.sessionId,
1600
- canonicalPathKey: session.canonicalPathKey,
1601
- revision: session.revision,
1602
- diagnostics: diagnosticsFromError
1603
- });
1604
- return failure("authoring", startedAt, {
1605
- code: "write_failed",
1606
- message: error instanceof Error ? error.message : String(error),
1607
- sessionId: session.sessionId,
1608
- canonicalPathKey: session.canonicalPathKey,
1609
- attemptedRevision: session.revision,
1610
- lastSavedRevision: session.lastSavedRevision,
1611
- writtenPaths,
1612
- failedPaths,
1613
- skippedPaths,
1614
- diagnostics: diagnosticsFromError,
1615
- diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
1616
- ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
1617
- }, toSessionSnapshot(session, this.context.capabilities), {
1618
- sessionId: session.sessionId,
1619
- revision: session.revision,
1620
- diagnostics: diagnosticsFromError
1621
- });
1622
- } finally {
1623
- reservation?.release();
1624
- }
1625
- }
1626
- };
1627
- //#endregion
1628
- //#region src/services/cache-service.ts
1629
- function createCacheEntry(session, valid) {
1630
- return {
1631
- canonicalPathKey: session.canonicalPathKey,
1632
- sessionId: session.sessionId,
1633
- revision: session.revision,
1634
- lastSavedRevision: session.lastSavedRevision,
1635
- dirty: session.dirty,
1636
- valid,
1637
- indexedAt: (/* @__PURE__ */ new Date()).toISOString(),
1638
- summary: {
1639
- packageCount: session.project.packages.length,
1640
- resourceCount: session.project.packages.reduce((total, pkg) => total + pkg.resources.length, 0),
1641
- diagnostics: []
1642
- }
1643
- };
1644
- }
1645
- var CacheService = class {
1646
- cacheBySession = /* @__PURE__ */ new Map();
1647
- constructor(getSession, events) {
1648
- this.getSession = getSession;
1649
- this.events = events;
1650
- }
1651
- getCacheSnapshot(input) {
1652
- const startedAt = Date.now();
1653
- const session = this.getSession(input.sessionId);
1654
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1655
- const entry = this.cacheBySession.get(input.sessionId);
1656
- return success("read", startedAt, {
1657
- cacheRevision: entry?.revision ?? session.revision,
1658
- entries: entry ? [structuredClone(entry)] : []
1659
- }, {
1660
- sessionId: session.sessionId,
1661
- revision: session.revision
1662
- });
1663
- }
1664
- refreshCache(input) {
1665
- const startedAt = Date.now();
1666
- const session = this.getSession(input.sessionId);
1667
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1668
- const entry = this.refreshSession(session);
1669
- this.events.emit({
1670
- kind: "cache.updated",
1671
- sessionId: session.sessionId,
1672
- canonicalPathKey: session.canonicalPathKey,
1673
- revision: session.revision,
1674
- cacheRevision: entry.revision,
1675
- payload: { reason: input.reason ?? "manual" }
1676
- });
1677
- return success("runtime", startedAt, {
1678
- cacheRevision: entry.revision,
1679
- entries: [structuredClone(entry)]
1680
- }, {
1681
- sessionId: session.sessionId,
1682
- revision: session.revision
1683
- });
1684
- }
1685
- refreshSession(session) {
1686
- const entry = createCacheEntry(session, true);
1687
- this.cacheBySession.set(session.sessionId, entry);
1688
- return entry;
1689
- }
1690
- invalidateSession(session) {
1691
- const entry = createCacheEntry(session, false);
1692
- this.cacheBySession.set(session.sessionId, entry);
1693
- return entry;
1694
- }
1695
- removeSession(sessionId) {
1696
- this.cacheBySession.delete(sessionId);
1697
- }
1698
- };
1699
- //#endregion
1700
- //#region src/services/session-registry.ts
1701
- /** Owns live sessions and path claims, including claims made before asynchronous I/O. */
1702
- var SessionRegistry = class {
1703
- sessions = /* @__PURE__ */ new Map();
1704
- paths = /* @__PURE__ */ new Map();
1705
- opening = /* @__PURE__ */ new Set();
1706
- get(sessionId) {
1707
- return this.sessions.get(sessionId);
1708
- }
1709
- has(sessionId) {
1710
- return this.sessions.has(sessionId) || this.opening.has(sessionId);
1711
- }
1712
- reserve(sessionId, target) {
1713
- const key = target.canonicalPathKey;
1714
- const previous = this.paths.get(key);
1715
- if (previous && previous.sessionId !== sessionId) return {
1716
- code: "lock_conflict",
1717
- kind: "in_process_session_exists",
1718
- message: `Project is already open in this backend runtime: ${target.canonicalProjectPath}`,
1719
- canonicalPathKey: key,
1720
- holderSessionId: previous.sessionId,
1721
- lockFilePath: target.lockFilePath
1722
- };
1723
- const claim = previous ?? { sessionId };
1724
- this.paths.set(key, claim);
1725
- if (!this.sessions.has(sessionId)) this.opening.add(sessionId);
1726
- let committed = false;
1727
- return {
1728
- commit: (session) => {
1729
- if (session.sessionId !== sessionId || this.paths.get(key) !== claim) throw new Error("Session path reservation lost.");
1730
- if (session.canonicalPathKey !== key) this.releasePath(session.canonicalPathKey, sessionId);
1731
- Object.assign(session, target);
1732
- this.sessions.set(sessionId, session);
1733
- this.opening.delete(sessionId);
1734
- committed = true;
1735
- },
1736
- release: () => {
1737
- if (committed) return;
1738
- if (!previous && this.paths.get(key) === claim) this.paths.delete(key);
1739
- this.opening.delete(sessionId);
1740
- }
1741
- };
1742
- }
1743
- remove(session) {
1744
- if (this.sessions.get(session.sessionId) !== session) return;
1745
- this.sessions.delete(session.sessionId);
1746
- this.releasePath(session.canonicalPathKey, session.sessionId);
1747
- }
1748
- releasePath(key, sessionId) {
1749
- if (this.paths.get(key)?.sessionId === sessionId) this.paths.delete(key);
1750
- }
1751
- };
1752
- //#endregion
1753
- //#region src/services/session-operation-queue.ts
1754
- /** Serializes lifecycle and authoring operations for one session, without blocking other sessions. */
1755
- var SessionOperationQueue = class {
1756
- operations = /* @__PURE__ */ new Map();
1757
- async run(sessionId, operation) {
1758
- const previous = this.operations.get(sessionId) ?? Promise.resolve();
1759
- let release = () => void 0;
1760
- const current = new Promise((resolve) => {
1761
- release = resolve;
1762
- });
1763
- const tail = previous.then(() => current);
1764
- this.operations.set(sessionId, tail);
1765
- await previous;
1766
- try {
1767
- return await operation();
1768
- } finally {
1769
- release();
1770
- if (this.operations.get(sessionId) === tail) this.operations.delete(sessionId);
1771
- }
1772
- }
1773
- };
1774
- //#endregion
1775
- //#region src/services/event-service.ts
1776
- const DEFAULT_EVENT_RETENTION_LIMIT = 1e3;
1777
- var EventService = class {
1778
- eventsBySession = /* @__PURE__ */ new Map();
1779
- sequence = 0;
1780
- constructor(getSession) {
1781
- this.getSession = getSession;
1782
- }
1783
- emit(event) {
1784
- const emitted = {
1785
- ...event,
1786
- sequence: ++this.sequence,
1787
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1788
- diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
1789
- };
1790
- const sessionId = event.sessionId;
1791
- if (!sessionId) return emitted;
1792
- const events = this.eventsBySession.get(sessionId) ?? [];
1793
- events.push(emitted);
1794
- while (events.length > DEFAULT_EVENT_RETENTION_LIMIT) events.shift();
1795
- this.eventsBySession.set(sessionId, events);
1796
- return emitted;
1797
- }
1798
- getEvents(input) {
1799
- const startedAt = Date.now();
1800
- const session = this.getSession(input.sessionId);
1801
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1802
- const events = this.eventsBySession.get(input.sessionId) ?? [];
1803
- const oldestSequence = events[0]?.sequence ?? (events.length === 0 ? 1 : 0);
1804
- const currentSequence = events.at(-1)?.sequence ?? 0;
1805
- const after = input.after === void 0 ? 0 : Number(input.after);
1806
- if (!Number.isInteger(after) || after < 0) return failure("runtime", startedAt, {
1807
- code: "event_cursor_invalid",
1808
- message: `Invalid event cursor: ${input.after}`,
1809
- sessionId: input.sessionId,
1810
- after: String(input.after)
1811
- });
1812
- if (events.length > 0 && after !== 0 && after < oldestSequence - 1) return failure("runtime", startedAt, {
1813
- code: "event_cursor_invalid",
1814
- message: `Event cursor has expired: ${after}`,
1815
- sessionId: input.sessionId,
1816
- after: String(input.after)
1817
- });
1818
- if (after > currentSequence) return failure("runtime", startedAt, {
1819
- code: "event_cursor_invalid",
1820
- message: `Unknown event cursor: ${after}`,
1821
- sessionId: input.sessionId,
1822
- after: String(input.after)
1823
- });
1824
- const filtered = events.filter((event) => event.sequence > after);
1825
- const limit = input.limit === void 0 ? filtered.length : Math.max(0, input.limit);
1826
- return success("runtime", startedAt, {
1827
- events: filtered.slice(0, limit).map((event) => structuredClone(event)),
1828
- oldestSequence,
1829
- currentSequence,
1830
- cursorExpired: false
1831
- }, {
1832
- sessionId: session.sessionId,
1833
- revision: session.revision
1834
- });
1835
- }
1836
- removeSession(sessionId) {
1837
- this.eventsBySession.delete(sessionId);
1838
- }
1839
- };
1840
- //#endregion
1841
- //#region src/services/read-service.ts
1842
- /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
1843
- function queryResponseProblem(value, limits = BACKEND_ENTITY_QUERY_LIMITS) {
1844
- const pending = [{
1845
- value,
1846
- depth: 0
1847
- }];
1848
- let nodes = 0;
1849
- let stringUnits = 0;
1850
- while (pending.length) {
1851
- const { value, depth } = pending.pop();
1852
- if (++nodes > limits.maxNodes || depth > limits.maxDepth) return "response_budget_exceeded";
1853
- if (typeof value === "string" && (stringUnits += value.length) > limits.maxBytes) return "response_budget_exceeded";
1854
- if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") continue;
1855
- if (typeof value === "number") {
1856
- if (!Number.isFinite(value)) return "non_json_value";
1857
- continue;
1858
- }
1859
- if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return "non_json_value";
1860
- if (Array.isArray(value) && value.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
1861
- const entries = Object.entries(value);
1862
- if (entries.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
1863
- for (const [key, child] of entries) {
1864
- if (!Array.isArray(value) && (stringUnits += key.length) > limits.maxBytes) return "response_budget_exceeded";
1865
- pending.push({
1866
- value: child,
1867
- depth: depth + 1
1868
- });
1869
- }
1870
- }
1871
- if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limits.maxBytes) return "response_budget_exceeded";
1872
- }
1873
- function readFailure(startedAt, sessionId, reason, revision) {
1874
- return failure("read", startedAt, {
1875
- code: "session_read_failed",
1876
- sessionId,
1877
- reason,
1878
- message: `Session read failed: ${reason}.`
1879
- }, void 0, {
1880
- sessionId,
1881
- revision
1882
- });
1883
- }
1884
- function toProjectOutline(session) {
1885
- const project = session.project;
1886
- return {
1887
- sessionId: session.sessionId,
1888
- revision: session.revision,
1889
- projectId: project.projectId,
1890
- projectType: project.projectType,
1891
- version: project.version,
1892
- branches: [...project.branches],
1893
- packages: project.packages.map((pkg) => ({
1894
- id: pkg.id,
1895
- name: pkg.name,
1896
- branchNames: [...pkg.branchNames],
1897
- folders: pkg.folders.map((folder) => ({
1898
- branch: folder.branch,
1899
- path: folder.path
1900
- })),
1901
- resources: pkg.resources.map((resource) => ({
1902
- id: resource.id,
1903
- name: resource.name,
1904
- path: resource.path,
1905
- kind: resource.kind,
1906
- branch: resource.branch,
1907
- ...resource.kind === "component" ? { component: {
1908
- displayList: resource.component.displayList.map((node) => ({
1909
- id: node.id,
1910
- name: node.name,
1911
- kind: node.kind
1912
- })),
1913
- controllers: resource.component.controllers.map((controller) => ({
1914
- name: controller.name,
1915
- pages: controller.pages.map((page) => ({
1916
- id: page.id,
1917
- name: page.name
1918
- }))
1919
- })),
1920
- transitions: resource.component.transitions.map((transition) => ({ name: transition.name }))
1921
- } } : {}
1922
- }))
1923
- }))
1924
- };
1925
- }
1926
- var ReadService = class {
1927
- constructor(getSessionState, capabilities) {
1928
- this.getSessionState = getSessionState;
1929
- this.capabilities = capabilities;
1930
- }
1931
- getCapabilities() {
1932
- return success("read", Date.now(), cloneReadData(this.capabilities));
1933
- }
1934
- getSession(input) {
1935
- const startedAt = Date.now();
1936
- const session = this.getSessionState(input.sessionId);
1937
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1938
- return success("read", startedAt, toSessionSnapshot(session, this.capabilities), {
1939
- sessionId: session.sessionId,
1940
- revision: session.revision
1941
- });
1942
- }
1943
- getProjectOutline(input) {
1944
- const startedAt = Date.now();
1945
- const session = this.getSessionState(input.sessionId);
1946
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1947
- return success("read", startedAt, toProjectOutline(session), {
1948
- sessionId: session.sessionId,
1949
- revision: session.revision
1950
- });
1951
- }
1952
- queryEntity(input) {
1953
- const startedAt = Date.now();
1954
- const session = this.getSessionState(input.sessionId);
1955
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1956
- const meta = {
1957
- sessionId: session.sessionId,
1958
- revision: session.revision
1959
- };
1960
- const reject = (reason) => failure("read", startedAt, {
1961
- code: "entity_query_failed",
1962
- sessionId: session.sessionId,
1963
- reason,
1964
- message: `Entity query failed: ${reason}.`
1965
- }, void 0, meta);
1966
- const target = input.target;
1967
- if (!target || typeof target !== "object" || Array.isArray(target) || Object.keys(target).some((key) => key !== "kind" && key !== "selector")) return reject("invalid_query");
1968
- const respond = (entity) => {
1969
- const data = {
1970
- ...meta,
1971
- target,
1972
- entity
1973
- };
1974
- const problem = queryResponseProblem(data);
1975
- return problem ? reject(problem) : success("read", startedAt, cloneReadData(data), meta);
1976
- };
1977
- if (target.kind === "project") {
1978
- if (Object.hasOwn(target, "selector")) return reject("invalid_query");
1979
- const { projectId, settings } = session.project;
1980
- return respond({
1981
- kind: "project",
1982
- properties: {
1983
- projectId,
1984
- settings
1985
- }
1986
- });
1987
- }
1988
- const keys = target.kind === "package" ? ["packageId"] : target.kind === "resource" ? ["packageId", "resourceId"] : target.kind === "component" ? ["packageId", "componentResourceId"] : target.kind === "displayNode" ? [
1989
- "packageId",
1990
- "componentResourceId",
1991
- "displayNodeId"
1992
- ] : target.kind === "controller" ? [
1993
- "packageId",
1994
- "componentResourceId",
1995
- "controllerName"
1996
- ] : target.kind === "transition" ? [
1997
- "packageId",
1998
- "componentResourceId",
1999
- "transitionName"
2000
- ] : [];
2001
- const selector = target.selector;
2002
- 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");
2003
- const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2004
- if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2005
- if (target.kind === "package") {
2006
- const { id, name, compressPNG, jpegQuality, publish } = packages[0];
2007
- return respond({
2008
- kind: "package",
2009
- properties: {
2010
- id,
2011
- name,
2012
- settings: {
2013
- compressPNG,
2014
- jpegQuality,
2015
- publish
2016
- }
2017
- }
2018
- });
2019
- }
2020
- const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === "resource" ? selector.resourceId : selector.componentResourceId));
2021
- if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2022
- const resource = resources[0];
2023
- let entity;
2024
- if (target.kind === "resource") {
2025
- const record = resource;
2026
- entity = {
2027
- kind: "resource",
2028
- properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS.filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]]))
2029
- };
2030
- } else {
2031
- if (resource.kind !== "component") return reject("not_found");
2032
- if (target.kind === "component") {
2033
- const { size, properties, customData } = resource.component;
2034
- entity = {
2035
- kind: "component",
2036
- properties: {
2037
- size,
2038
- properties,
2039
- customData
2040
- }
2041
- };
2042
- } else if (target.kind === "controller") {
2043
- const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
2044
- if (controllers.length !== 1) return reject(controllers.length ? "ambiguous" : "not_found");
2045
- entity = {
2046
- kind: "controller",
2047
- properties: controllers[0]
2048
- };
2049
- } else if (target.kind === "transition") {
2050
- const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
2051
- if (transitions.length !== 1) return reject(transitions.length ? "ambiguous" : "not_found");
2052
- entity = {
2053
- kind: "transition",
2054
- properties: transitions[0]
2055
- };
2056
- } else {
2057
- const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
2058
- if (nodes.length !== 1) return reject(nodes.length ? "ambiguous" : "not_found");
2059
- entity = {
2060
- kind: "displayNode",
2061
- properties: nodes[0]
2062
- };
2063
- }
2064
- }
2065
- return respond(entity);
2066
- }
2067
- resolveReadSession(input, startedAt) {
2068
- if (!input || typeof input.sessionId !== "string" || !input.sessionId.length || input.sessionId.length > 256 || input.expectedRevision !== void 0 && (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0)) return readFailure(startedAt, typeof input?.sessionId === "string" ? input.sessionId : "", "invalid_query");
2069
- const session = this.getSessionState(input.sessionId);
2070
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2071
- const meta = {
2072
- sessionId: session.sessionId,
2073
- revision: session.revision
2074
- };
2075
- if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("read", startedAt, {
2076
- code: "stale_read",
2077
- sessionId: session.sessionId,
2078
- expectedRevision: input.expectedRevision,
2079
- actualRevision: session.revision,
2080
- message: "The session edit revision changed. Restart the model and resource read."
2081
- }, void 0, meta);
2082
- return success("read", startedAt, session, meta);
2083
- }
2084
- readSessionState(input) {
2085
- const startedAt = Date.now();
2086
- const resolved = this.resolveReadSession(input, startedAt);
2087
- if (!resolved.ok) return resolved;
2088
- const session = resolved.data;
2089
- const meta = {
2090
- sessionId: session.sessionId,
2091
- revision: session.revision
2092
- };
2093
- const data = {
2094
- ...meta,
2095
- dirty: session.dirty,
2096
- lastSavedRevision: session.lastSavedRevision,
2097
- uamFidelity: session.uamFidelity,
2098
- readComplete: session.readComplete,
2099
- readDiagnostics: session.readDiagnostics,
2100
- project: {
2101
- ...session.project,
2102
- packages: session.project.packages.map((pkg) => ({
2103
- ...pkg,
2104
- resources: pkg.resources.map((resource) => {
2105
- if (resource.kind === "component") return resource;
2106
- const { sourceBytes: _sourceBytes, ...model } = resource;
2107
- return model;
2108
- })
2109
- }))
2110
- }
2111
- };
2112
- const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
2113
- return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, cloneReadData(data), meta);
2114
- }
2115
- readResourceBytes(input) {
2116
- const startedAt = Date.now();
2117
- const resolved = this.resolveReadSession(input, startedAt);
2118
- if (!resolved.ok) return resolved;
2119
- const session = resolved.data;
2120
- const reject = (reason) => readFailure(startedAt, session.sessionId, reason, session.revision);
2121
- const selector = input.selector;
2122
- if (input.expectedRevision === void 0 || !selector || typeof selector !== "object" || Array.isArray(selector) || Object.keys(selector).length !== 2 || ["packageId", "resourceId"].some((key) => !Object.hasOwn(selector, key)) || [selector.packageId, selector.resourceId].some((value) => typeof value !== "string" || !value.length || value.length > 256)) return reject("invalid_query");
2123
- const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
2124
- if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
2125
- const resources = packages[0].resources.filter((resource) => resource.id === selector.resourceId);
2126
- if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
2127
- const resource = resources[0];
2128
- if (resource.kind === "component") return reject("unsupported_resource");
2129
- if (!(resource.sourceBytes instanceof Uint8Array)) return reject("bytes_unavailable");
2130
- if (resource.sourceBytes.byteLength > BACKEND_SESSION_READ_LIMITS.resourceBytes) return reject("response_budget_exceeded");
2131
- const meta = {
2132
- sessionId: session.sessionId,
2133
- revision: session.revision
2134
- };
2135
- return success("read", startedAt, {
2136
- ...meta,
2137
- selector: { ...selector },
2138
- sourceBytes: new Uint8Array(resource.sourceBytes)
2139
- }, meta);
2140
- }
2141
- validateSession(input) {
2142
- const startedAt = Date.now();
2143
- const session = this.getSessionState(input.sessionId);
2144
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2145
- const report = (0, _openfairygui_functions.validateProject)(cloneReadData(session.project), {
2146
- readDiagnostics: cloneReadData(session.readDiagnostics),
2147
- complete: session.readComplete,
2148
- validateSources: true
2149
- });
2150
- return success("read", startedAt, report, {
2151
- sessionId: session.sessionId,
2152
- revision: session.revision,
2153
- diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({
2154
- code,
2155
- message,
2156
- severity,
2157
- path,
2158
- owner: "core.validation"
2159
- }))
2160
- });
2161
- }
2162
- };
2163
- //#endregion
2164
- //#region src/services/runtime-service.ts
2165
- function randomId() {
2166
- return crypto.randomUUID();
2167
- }
2168
- function createCapabilityUnavailableError(capability) {
2169
- const artifactCapability = capability === "artifact.publish" || capability === "artifact.restore";
2170
- return {
2171
- code: "capability_unavailable",
2172
- message: artifactCapability ? `${capability} requires the Node bridge boundary exposed by @openfairygui/backend/node.` : `${capability} requires an injected BackendFileSystem adapter.`,
2173
- capability,
2174
- requiredAdapter: capability === "fileSystem" ? "BackendFileSystem" : void 0,
2175
- requiredHost: artifactCapability ? "node" : void 0,
2176
- bridgeBoundary: artifactCapability ? "external-bridge" : void 0
2177
- };
2178
- }
2179
- function createProjectReaderFileSystem(fileSystem, projectRoot) {
2180
- const contained = async (filePath, operation) => {
2181
- await assertProjectPathContained(fileSystem, projectRoot, filePath);
2182
- return operation();
2183
- };
2184
- return {
2185
- stat: (path) => contained(path, () => fileSystem.stat(path)),
2186
- readFile(filePath) {
2187
- return contained(filePath, () => fileSystem.readFile(filePath));
2188
- },
2189
- readFileRaw(filePath) {
2190
- return contained(filePath, () => fileSystem.readFileRaw(filePath));
2191
- },
2192
- writeFile(filePath, content) {
2193
- return contained(filePath, () => fileSystem.writeFile(filePath, content));
2194
- },
2195
- writeFileRaw(filePath, data) {
2196
- return contained(filePath, () => fileSystem.writeFileRaw(filePath, data));
2197
- },
2198
- async mkdir(dirPath) {
2199
- await contained(dirPath, () => fileSystem.mkdir(dirPath, { recursive: true }));
2200
- },
2201
- readdir(dirPath) {
2202
- return contained(dirPath, () => fileSystem.readdir(dirPath));
2203
- },
2204
- async exists(filePath) {
2205
- try {
2206
- await contained(filePath, () => fileSystem.stat(filePath));
2207
- return true;
2208
- } catch {
2209
- return false;
2210
- }
2211
- },
2212
- join(...paths) {
2213
- return fileSystem.join(...paths);
2214
- },
2215
- dirname(filePath) {
2216
- return fileSystem.dirname(filePath);
2217
- }
2218
- };
2219
- }
2220
- async function hasFullUamFidelity(document, project) {
2221
- const sourceFiles = /* @__PURE__ */ new Map();
2222
- const materializedFiles = /* @__PURE__ */ new Map();
2223
- const sourceDirectories = /* @__PURE__ */ new Set();
2224
- const materializedDirectories = /* @__PURE__ */ new Set();
2225
- try {
2226
- await Promise.all([new _openfairygui_core_project_io.ProjectWriter(createCaptureFileSystem(sourceFiles, sourceDirectories)).write(document, "Project.fairy"), new _openfairygui_core_project_io.ProjectWriter(createCaptureFileSystem(materializedFiles, materializedDirectories)).write((0, _openfairygui_core_uam.materializeUamProject)(project), "Project.fairy")]);
2227
- } catch {
2228
- return false;
2229
- }
2230
- return capturedFilesEqual(sourceFiles, materializedFiles) && capturedDirectoriesEqual(sourceDirectories, materializedDirectories);
2231
- }
2232
- var RuntimeService = class {
2233
- constructor(context, cacheService, eventService) {
2234
- this.context = context;
2235
- this.cacheService = cacheService;
2236
- this.eventService = eventService;
2237
- }
2238
- async openSession(input) {
2239
- const startedAt = Date.now();
2240
- if (!this.context.fileSystem) return failure("runtime", startedAt, createCapabilityUnavailableError("fileSystem"));
2241
- const fileSystem = this.context.fileSystem;
2242
- if (this.context.allowedProjectRoots?.length) {
2243
- let allowed = false;
2244
- for (const root of this.context.allowedProjectRoots) try {
2245
- await assertProjectPathContained(fileSystem, root, input.projectPath);
2246
- allowed = true;
2247
- break;
2248
- } catch (error) {
2249
- if (error.code !== "EACCES") throw error;
2250
- }
2251
- if (!allowed) return failure("runtime", startedAt, {
2252
- code: "project_root_not_allowed",
2253
- message: "Project path is outside the configured allowed roots.",
2254
- projectPath: input.projectPath
2255
- });
2256
- }
2257
- const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
2258
- await fileSystem.validateProjectRoot?.(canonicalProjectPath);
2259
- const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath) ?? fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
2260
- const sessionId = randomId();
2261
- const reservation = this.context.sessions.reserve(sessionId, {
2262
- canonicalPathKey,
2263
- canonicalProjectPath,
2264
- lockFilePath
2265
- });
2266
- if ("code" in reservation) return failure("runtime", startedAt, reservation);
2267
- let sessionLock = null;
2268
- try {
2269
- sessionLock = await fileSystem.acquireSessionLock(lockFilePath);
2270
- await sessionLock.writeMetadata(JSON.stringify(this.context.host?.lockMetadata?.({
2271
- canonicalPathKey,
2272
- canonicalProjectPath,
2273
- lockFilePath
2274
- }) ?? {
2275
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2276
- canonicalPathKey
2277
- }));
2278
- const read = await new _openfairygui_core_project_io.ProjectReader(createProjectReaderFileSystem(fileSystem, canonicalProjectPath)).readDetailed(fairyPath, { hydrateResourceBytes: true });
2279
- if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
2280
- const document = read.document;
2281
- const project = (0, _openfairygui_core_uam.liftDocumentToUamProject)(document);
2282
- const session = {
2283
- sessionId,
2284
- fairyPath,
2285
- canonicalProjectPath,
2286
- canonicalPathKey,
2287
- lockFilePath,
2288
- sessionLock,
2289
- fileSystem,
2290
- project,
2291
- readDiagnostics: read.diagnostics,
2292
- readComplete: read.complete,
2293
- uamFidelity: read.complete && await hasFullUamFidelity(document, project) ? "full" : "unsupported",
2294
- revision: 0,
2295
- lastSavedRevision: 0,
2296
- pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
2297
- pendingStaleResourceFolders: /* @__PURE__ */ new Map(),
2298
- pendingStaleBranchDirectories: /* @__PURE__ */ new Map(),
2299
- dirty: false,
2300
- lockHeld: true,
2301
- closed: false
2302
- };
2303
- reservation.commit(session);
2304
- this.cacheService.refreshSession(session);
2305
- this.eventService.emit({
2306
- kind: "session.opened",
2307
- sessionId,
2308
- canonicalPathKey,
2309
- revision: session.revision
2310
- });
2311
- return success("runtime", startedAt, toSessionSnapshot(session, this.context.capabilities), {
2312
- sessionId: session.sessionId,
2313
- revision: session.revision
2314
- });
2315
- } catch (error) {
2316
- if (sessionLock) await sessionLock.release().catch(() => void 0);
2317
- if (typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST") return failure("runtime", startedAt, {
2318
- code: "lock_conflict",
2319
- kind: "advisory_lock_conflict",
2320
- message: `Advisory lock already exists for project: ${canonicalProjectPath}`,
2321
- canonicalPathKey,
2322
- lockFilePath
2323
- });
2324
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOTSUP") return failure("runtime", startedAt, {
2325
- ...createCapabilityUnavailableError("fileSystem"),
2326
- message: error instanceof Error ? error.message : String(error)
2327
- });
2328
- throw error;
2329
- } finally {
2330
- reservation.release();
2331
- }
2332
- }
2333
- openProjectSession(input) {
2334
- const startedAt = Date.now();
2335
- const sessionId = input.sessionId ?? randomId();
2336
- if (this.context.sessions.has(sessionId)) return failure("runtime", startedAt, {
2337
- code: "session_id_conflict",
2338
- message: `Session id is already in use: ${sessionId}`,
2339
- sessionId
2340
- });
2341
- const storage = input.storage;
2342
- const memoryProjectPath = `memory://${sessionId}`;
2343
- const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
2344
- const canonicalPathKey = storage?.canonicalPathKey ?? input.canonicalPathKey ?? (storage ? normalizeComparablePath(canonicalProjectPath) : canonicalProjectPath.toLowerCase());
2345
- const project = (0, _openfairygui_core_uam.normalizeUamProject)(input.project);
2346
- const reservation = this.context.sessions.reserve(sessionId, {
2347
- canonicalPathKey,
2348
- canonicalProjectPath
2349
- });
2350
- if ("code" in reservation) return failure("runtime", startedAt, reservation);
2351
- const session = {
2352
- sessionId,
2353
- fairyPath: storage?.fairyPath ?? canonicalProjectPath,
2354
- canonicalProjectPath,
2355
- canonicalPathKey,
2356
- lockFilePath: "",
2357
- sessionLock: null,
2358
- fileSystem: storage?.fileSystem,
2359
- project,
2360
- readDiagnostics: [],
2361
- readComplete: true,
2362
- uamFidelity: "full",
2363
- revision: 0,
2364
- lastSavedRevision: 0,
2365
- pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
2366
- pendingStaleResourceFolders: /* @__PURE__ */ new Map(),
2367
- pendingStaleBranchDirectories: /* @__PURE__ */ new Map(),
2368
- dirty: false,
2369
- lockHeld: false,
2370
- closed: false
2371
- };
2372
- reservation.commit(session);
2373
- this.cacheService.refreshSession(session);
2374
- this.eventService.emit({
2375
- kind: "session.opened",
2376
- sessionId,
2377
- canonicalPathKey,
2378
- revision: session.revision
2379
- });
2380
- return success("runtime", startedAt, toSessionSnapshot(session, this.context.capabilities), {
2381
- sessionId: session.sessionId,
2382
- revision: session.revision
2383
- });
2384
- }
2385
- async closeSession(input) {
2386
- const startedAt = Date.now();
2387
- const session = this.context.sessions.get(input.sessionId);
2388
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
2389
- this.eventService.emit({
2390
- kind: "session.closeRequested",
2391
- sessionId: session.sessionId,
2392
- canonicalPathKey: session.canonicalPathKey,
2393
- revision: session.revision
2394
- });
2395
- try {
2396
- await session.sessionLock?.release();
2397
- } catch (error) {
2398
- return failure("runtime", startedAt, {
2399
- code: "session_close_failed",
2400
- message: error instanceof Error ? error.message : String(error),
2401
- sessionId: session.sessionId,
2402
- lockFilePath: session.lockFilePath
2403
- }, toSessionSnapshot(session, this.context.capabilities), {
2404
- sessionId: session.sessionId,
2405
- revision: session.revision
2406
- });
2407
- }
2408
- session.sessionLock = null;
2409
- session.lockHeld = false;
2410
- session.closed = true;
2411
- this.context.sessions.remove(session);
2412
- this.cacheService.removeSession(session.sessionId);
2413
- this.eventService.emit({
2414
- kind: "session.closed",
2415
- sessionId: session.sessionId,
2416
- canonicalPathKey: session.canonicalPathKey,
2417
- revision: session.revision
2418
- });
2419
- this.eventService.removeSession(session.sessionId);
2420
- return success("runtime", startedAt, {
2421
- sessionId: session.sessionId,
2422
- closed: true
2423
- }, {
2424
- sessionId: session.sessionId,
2425
- revision: session.revision
2426
- });
2427
- }
2428
- };
2429
- //#endregion
2430
- //#region src/services/artifact-service.ts
2431
- function createArtifactCapabilities() {
2432
- const bridge = {
2433
- available: false,
2434
- requiredHost: "node",
2435
- executionBoundary: "external-bridge",
2436
- bridgeEntrypoint: "@openfairygui/backend/node",
2437
- reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
2438
- };
2439
- return {
2440
- publish: false,
2441
- restore: false,
2442
- status: "bridge-required",
2443
- publishBridge: bridge,
2444
- restoreBridge: bridge
2445
- };
2446
- }
2447
- //#endregion
2448
- //#region src/runtime/capabilities.ts
2449
- const BACKEND_METHODS = [
2450
- "getCapabilities",
2451
- "openSession",
2452
- "openProjectSession",
2453
- "getSession",
2454
- "getProjectOutline",
2455
- "queryEntity",
2456
- "readSessionState",
2457
- "readResourceBytes",
2458
- "validateSession",
2459
- "preflightTransaction",
2460
- "applyTransaction",
2461
- "saveSession",
2462
- "materializeSession",
2463
- "closeSession",
2464
- "getEvents",
2465
- "getCacheSnapshot",
2466
- "refreshCache"
2467
- ];
2468
- const ARTIFACT_BRIDGE_CAPABILITY = {
2469
- available: false,
2470
- requiredHost: "node",
2471
- executionBoundary: "external-bridge",
2472
- bridgeEntrypoint: "@openfairygui/backend/node",
2473
- reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
2474
- };
2475
- function createCapabilities(atomicSave = false) {
2476
- return {
2477
- contractVersion: BACKEND_CONTRACT_VERSION,
2478
- capabilitySchemaVersion: 12,
2479
- transactionKernelOwner: "@openfairygui/core",
2480
- appSeamOwner: "@openfairygui/functions",
2481
- runtimeOwner: "@openfairygui/backend",
2482
- methods: BACKEND_METHODS,
2483
- read: {
2484
- capabilitySnapshot: true,
2485
- sessionSnapshot: true,
2486
- projectOutline: true,
2487
- entityQuery: {
2488
- kinds: [
2489
- "project",
2490
- "package",
2491
- "resource",
2492
- "component",
2493
- "displayNode",
2494
- "controller",
2495
- "transition"
2496
- ],
2497
- projection: "properties",
2498
- sourceBytes: false,
2499
- limits: BACKEND_ENTITY_QUERY_LIMITS
2500
- },
2501
- sessionState: {
2502
- sourceBytes: false,
2503
- limits: BACKEND_SESSION_READ_LIMITS.model
2504
- },
2505
- resourceBytes: {
2506
- expectedRevisionRequired: true,
2507
- hydration: false,
2508
- maxBytes: BACKEND_SESSION_READ_LIMITS.resourceBytes
2509
- },
2510
- projectValidation: true
2511
- },
2512
- authoring: {
2513
- preflightTransaction: {
2514
- mode: "execute-and-discard",
2515
- reservesRevision: false,
2516
- impact: "model-diff",
2517
- limits: BACKEND_TRANSACTION_PREVIEW_LIMITS
2518
- },
2519
- applyTransaction: true,
2520
- saveSession: true,
2521
- resourceKinds: [..._openfairygui_core_uam.UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
2522
- nodeKinds: [..._openfairygui_core_uam.UAM_SUPPORTED_MATERIALIZATION_SCOPE.nodeKinds],
2523
- gearKinds: [..._openfairygui_core_uam.UAM_SUPPORTED_MATERIALIZATION_SCOPE.gearKinds],
2524
- transactionScope: {
2525
- resourceKinds: [..._openfairygui_core_uam.UAM_SUPPORTED_TRANSACTION_SCOPE.resourceKinds],
2526
- nodeKinds: [..._openfairygui_core_uam.UAM_SUPPORTED_TRANSACTION_SCOPE.nodeKinds],
2527
- gearKinds: [..._openfairygui_core_uam.UAM_SUPPORTED_TRANSACTION_SCOPE.gearKinds]
2528
- },
2529
- unsupported: ["artifact.publish", "artifact.restore"]
2530
- },
2531
- artifact: createArtifactCapabilities(),
2532
- manifest: {
2533
- browserSafe: true,
2534
- rootEntrypoint: "@openfairygui/backend",
2535
- nodeEntrypoint: "@openfairygui/backend/node",
2536
- adapters: {
2537
- fileSystem: {
2538
- injected: true,
2539
- requiredFor: [
2540
- "openSession",
2541
- "saveSession",
2542
- "materializeSession"
2543
- ]
2544
- },
2545
- projectStorage: {
2546
- injected: true,
2547
- browserSafe: true,
2548
- requiredFor: [
2549
- "openProjectSession.writeback",
2550
- "saveSession",
2551
- "materializeSession"
2552
- ],
2553
- adapterFactory: "createBackendStorageFileSystem"
2554
- },
2555
- host: {
2556
- injected: true,
2557
- requiredFor: ["advisoryLockMetadata"]
2558
- }
2559
- },
2560
- executionBoundaries: {
2561
- projectSession: "in-process-browser-safe",
2562
- fileBackedSession: "adapter-backed",
2563
- artifactPublish: ARTIFACT_BRIDGE_CAPABILITY,
2564
- artifactRestore: ARTIFACT_BRIDGE_CAPABILITY
2565
- },
2566
- diagnostics: {
2567
- stableCodes: true,
2568
- errorDiagnosticMirror: true,
2569
- recoveryGuides: "all-formal-codes",
2570
- automaticRepair: false
2571
- }
2572
- },
2573
- compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
2574
- runtime: {
2575
- sessionRuntime: true,
2576
- advisoryLocking: true,
2577
- coordinatedSave: true,
2578
- atomicSave,
2579
- staleRevisionProtection: true,
2580
- pathPolicy: createRuntimePathPolicy(),
2581
- events: {
2582
- polling: true,
2583
- subscriptions: false,
2584
- retentionLimit: 1e3,
2585
- sequenceScope: "runtime"
2586
- },
2587
- cache: {
2588
- derivedReadOnly: true,
2589
- keyedBy: "sessionId",
2590
- refreshMode: "synchronous",
2591
- sourceOfTruth: false,
2592
- refreshMethod: "refreshCache"
2593
- }
2594
- }
2595
- };
2596
- }
2597
- //#endregion
2598
- //#region src/runtime.ts
2599
- var BackendRuntime = class {
2600
- fileSystem;
2601
- capabilities;
2602
- sessions = new SessionRegistry();
2603
- sessionOperations = new SessionOperationQueue();
2604
- context;
2605
- readService;
2606
- runtimeService;
2607
- authoringService;
2608
- persistenceService;
2609
- cacheService;
2610
- eventService;
2611
- constructor(options = {}) {
2612
- this.fileSystem = options.fileSystem;
2613
- this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
2614
- this.context = {
2615
- fileSystem: this.fileSystem,
2616
- host: options.host,
2617
- allowedProjectRoots: options.allowedProjectRoots,
2618
- capabilities: this.capabilities,
2619
- sessions: this.sessions
2620
- };
2621
- const getSession = (sessionId) => this.sessions.get(sessionId);
2622
- this.readService = new ReadService((sessionId) => readView(getSession(sessionId)), this.capabilities);
2623
- this.eventService = new EventService(getSession);
2624
- this.cacheService = new CacheService(getSession, this.eventService);
2625
- this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService);
2626
- this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService, this.sessionOperations);
2627
- this.persistenceService = new PersistenceService(this.context, this.cacheService, this.eventService, this.sessionOperations);
2628
- }
2629
- getCapabilities() {
2630
- return this.readService.getCapabilities();
2631
- }
2632
- async openSession(input) {
2633
- const startedAt = Date.now();
2634
- try {
2635
- return await this.runtimeService.openSession(input);
2636
- } catch {
2637
- return failure("runtime", startedAt, {
2638
- code: "project_open_failed",
2639
- message: "Unable to open project.",
2640
- projectPath: input.projectPath
2641
- });
2642
- }
2643
- }
2644
- openProjectSession(input) {
2645
- return this.runtimeService.openProjectSession(input);
2646
- }
2647
- getSession(input) {
2648
- return this.readService.getSession(input);
2649
- }
2650
- getProjectOutline(input) {
2651
- return this.readService.getProjectOutline(input);
2652
- }
2653
- queryEntity(input) {
2654
- return this.readService.queryEntity(input);
2655
- }
2656
- readSessionState(input) {
2657
- return this.readService.readSessionState(input);
2658
- }
2659
- readResourceBytes(input) {
2660
- return this.readService.readResourceBytes(input);
2661
- }
2662
- validateSession(input) {
2663
- return this.readService.validateSession(input);
2664
- }
2665
- async preflightTransaction(input) {
2666
- return this.authoringService.preflightTransaction(input);
2667
- }
2668
- async applyTransaction(input) {
2669
- return this.authoringService.applyTransaction(input);
2670
- }
2671
- async saveSession(input) {
2672
- return this.persistenceService.saveSession(input);
2673
- }
2674
- async materializeSession(input) {
2675
- return this.persistenceService.materializeSession(input);
2676
- }
2677
- async closeSession(input) {
2678
- const captured = { ...input };
2679
- return this.sessionOperations.run(captured.sessionId, () => this.runtimeService.closeSession(captured));
2680
- }
2681
- getEvents(input) {
2682
- return this.eventService.getEvents(input);
2683
- }
2684
- getCacheSnapshot(input) {
2685
- return this.cacheService.getCacheSnapshot(input);
2686
- }
2687
- refreshCache(input) {
2688
- return this.cacheService.refreshCache(input);
2689
- }
2690
- };
2691
- //#endregion
2
+ const require_runtime = require("./runtime-DYqG77ak.cjs");
3
+ const require_diagnostics = require("./diagnostics-CIe7S-RW.cjs");
2692
4
  //#region src/storage.ts
2693
5
  var StorageFileStat = class {
2694
6
  constructor(kind) {
@@ -2799,6 +111,7 @@ function createBackendStorageFileSystem(storage) {
2799
111
  if (typeof storage.unlink !== "function") throw createPathError("ENOTSUP", "Storage adapter must provide unlink() for project resource lifecycle writes.");
2800
112
  if (typeof storage.rmdir !== "function") throw createPathError("ENOTSUP", "Storage adapter must provide rmdir() for project resource folder lifecycle writes.");
2801
113
  const fileSystem = {
114
+ caseSensitivePaths: storage.caseSensitivePaths ?? true,
2802
115
  stat(filePath) {
2803
116
  return inferStat(storage, fileSystem.resolve(filePath));
2804
117
  },
@@ -2834,7 +147,7 @@ function createBackendStorageFileSystem(storage) {
2834
147
  return storage.resolvePath ? storage.resolvePath(resolved) : Promise.resolve(resolved);
2835
148
  },
2836
149
  async acquireSessionLock(lockPath) {
2837
- const resolved = fileSystem.resolve(lockPath);
150
+ const resolved = require_runtime.normalizeComparablePath(await fileSystem.resolvePath(lockPath), fileSystem.caseSensitivePaths);
2838
151
  if (storage.acquireSessionLock) return storage.acquireSessionLock(resolved);
2839
152
  const lockManager = getWebLockManager();
2840
153
  if (!lockManager) throw createPathError("ENOTSUP", "Browser openSession requires Web Locks or BackendAsyncStorageAdapter.acquireSessionLock().");
@@ -2859,16 +172,16 @@ function createBackendStorageFileSystem(storage) {
2859
172
  return fileSystem;
2860
173
  }
2861
174
  //#endregion
2862
- exports.BACKEND_CAPABILITY_SCHEMA_VERSION = BACKEND_CAPABILITY_SCHEMA_VERSION;
2863
- exports.BACKEND_COMPATIBILITY_POLICY = BACKEND_COMPATIBILITY_POLICY;
2864
- exports.BACKEND_CONTRACT_VERSION = BACKEND_CONTRACT_VERSION;
2865
- exports.BACKEND_DIAGNOSTICS_URI = BACKEND_DIAGNOSTICS_URI;
2866
- exports.BACKEND_DIAGNOSTIC_TEMPLATE = BACKEND_DIAGNOSTIC_TEMPLATE;
2867
- exports.BACKEND_ENTITY_QUERY_LIMITS = BACKEND_ENTITY_QUERY_LIMITS;
2868
- exports.BACKEND_SESSION_READ_LIMITS = BACKEND_SESSION_READ_LIMITS;
2869
- exports.BACKEND_TRANSACTION_PREVIEW_LIMITS = BACKEND_TRANSACTION_PREVIEW_LIMITS;
2870
- exports.BackendRuntime = BackendRuntime;
2871
- exports.ProjectWriteTransactionError = ProjectWriteTransactionError;
175
+ exports.BACKEND_CAPABILITY_SCHEMA_VERSION = require_runtime.BACKEND_CAPABILITY_SCHEMA_VERSION;
176
+ exports.BACKEND_COMPATIBILITY_POLICY = require_runtime.BACKEND_COMPATIBILITY_POLICY;
177
+ exports.BACKEND_CONTRACT_VERSION = require_runtime.BACKEND_CONTRACT_VERSION;
178
+ exports.BACKEND_DIAGNOSTICS_URI = require_diagnostics.BACKEND_DIAGNOSTICS_URI;
179
+ exports.BACKEND_DIAGNOSTIC_TEMPLATE = require_diagnostics.BACKEND_DIAGNOSTIC_TEMPLATE;
180
+ exports.BACKEND_ENTITY_QUERY_LIMITS = require_runtime.BACKEND_ENTITY_QUERY_LIMITS;
181
+ exports.BACKEND_SESSION_READ_LIMITS = require_runtime.BACKEND_SESSION_READ_LIMITS;
182
+ exports.BACKEND_TRANSACTION_PREVIEW_LIMITS = require_runtime.BACKEND_TRANSACTION_PREVIEW_LIMITS;
183
+ exports.BackendRuntime = require_runtime.BackendRuntime;
184
+ exports.ProjectWriteTransactionError = require_runtime.ProjectWriteTransactionError;
2872
185
  exports.createBackendStorageFileSystem = createBackendStorageFileSystem;
2873
- exports.getBackendDiagnosticCatalog = getBackendDiagnosticCatalog;
2874
- exports.getBackendDiagnosticGuide = getBackendDiagnosticGuide;
186
+ exports.getBackendDiagnosticCatalog = require_diagnostics.getBackendDiagnosticCatalog;
187
+ exports.getBackendDiagnosticGuide = require_diagnostics.getBackendDiagnosticGuide;