@openfairygui/backend 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.cjs CHANGED
@@ -32,83 +32,8 @@ let _openfairygui_core_uam = require("@openfairygui/core/uam");
32
32
  let _openfairygui_functions_uam = require("@openfairygui/functions/uam");
33
33
  let _openfairygui_core_project_io = require("@openfairygui/core/project-io");
34
34
  let _openfairygui_functions = require("@openfairygui/functions");
35
- //#region src/path-policy.ts
36
- function normalizeComparablePath(value) {
37
- const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
38
- const driveMatch = normalized.match(/^([a-z]:)(?:\/(.*))?$/i);
39
- const drivePrefix = driveMatch?.[1].toLowerCase() ?? "";
40
- const remainder = driveMatch ? driveMatch[2] ?? "" : normalized;
41
- const hasRoot = driveMatch ? true : remainder.startsWith("/");
42
- const rawSegments = remainder.split("/").filter((segment) => segment.length > 0);
43
- const segments = [];
44
- for (const segment of rawSegments) {
45
- if (segment === ".") continue;
46
- if (segment === "..") {
47
- if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
48
- else if (!hasRoot) segments.push("..");
49
- continue;
50
- }
51
- segments.push(segment);
52
- }
53
- const joined = segments.join("/");
54
- return (drivePrefix ? `${drivePrefix}/${joined}`.replace(/\/$/, "") : hasRoot ? `/${joined}`.replace(/\/$/, "") : joined || ".").toLowerCase();
55
- }
56
- function createRuntimePathPolicy() {
57
- return {
58
- canonicalization: "realpath+normalized-casefold",
59
- sessionIdentity: "project-root",
60
- saveTarget: "opened-project-only",
61
- outputTargets: "deferred",
62
- workspaceBoundary: "project-root-only"
63
- };
64
- }
65
- async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
66
- const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
67
- const root = normalizeComparablePath(resolvedRoot);
68
- const target = normalizeComparablePath(resolvedTarget);
69
- if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
70
- if (target === root || target.startsWith(`${root}/`)) return;
71
- const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
72
- error.code = "EACCES";
73
- throw error;
74
- }
75
- async function resolveFairyPath(fileSystem, input) {
76
- const resolvedInput = fileSystem.resolve(input);
77
- const stat = await fileSystem.stat(resolvedInput);
78
- if (stat.isFile() && resolvedInput.endsWith(".fairy")) return await fileSystem.resolvePath(resolvedInput);
79
- if (stat.isDirectory()) {
80
- const fairyFiles = (await fileSystem.readdir(resolvedInput)).filter((entry) => entry.endsWith(".fairy"));
81
- if (fairyFiles.length === 1) return await fileSystem.resolvePath(fileSystem.join(resolvedInput, fairyFiles[0]));
82
- if (fairyFiles.length > 1) throw new Error(`Multiple .fairy files found in ${resolvedInput}: ${fairyFiles.join(", ")}`);
83
- throw new Error(`No .fairy file found in ${resolvedInput}`);
84
- }
85
- throw new Error(`Input is not a .fairy file or directory: ${resolvedInput}`);
86
- }
87
- async function resolveCanonicalProjectRoot(fileSystem, input) {
88
- const fairyPath = await resolveFairyPath(fileSystem, input);
89
- const canonicalProjectPath = await fileSystem.resolvePath(fileSystem.dirname(fairyPath));
90
- return {
91
- fairyPath,
92
- canonicalProjectPath,
93
- canonicalPathKey: normalizeComparablePath(canonicalProjectPath)
94
- };
95
- }
96
- async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
97
- if (!targetPath) return null;
98
- const attemptedPath = await fileSystem.resolvePath(fileSystem.resolve(targetPath));
99
- const allowedPath = await fileSystem.resolvePath(openedFairyPath);
100
- if (normalizeComparablePath(attemptedPath) === normalizeComparablePath(allowedPath)) return null;
101
- return {
102
- code: "path_policy_violation",
103
- message: `Save target is restricted to the originally opened project file: ${allowedPath}`,
104
- policy: "save_target",
105
- attemptedPath,
106
- allowedPath
107
- };
108
- }
109
- //#endregion
110
35
  //#region src/contracts.ts
111
- const BACKEND_CONTRACT_VERSION = "2.0.0-p3";
36
+ const BACKEND_CONTRACT_VERSION = "3.0.0";
112
37
  const BACKEND_COMPATIBILITY_POLICY = {
113
38
  incompatibleChange: "requires contractVersion bump",
114
39
  capabilitySchemaChange: "requires capabilitySchemaVersion bump",
@@ -160,14 +85,6 @@ const write = {
160
85
  kind: "host-action",
161
86
  message: "Preserve the dirty session and inspect the error, actual target files and permissions with the host. Partial writes may have changed files: verify or recover them before a newly authorized save. Do not clear dirty state, discard memory or blindly retry."
162
87
  };
163
- const execution = {
164
- kind: "host-action",
165
- message: "Inspect the execution/cache failure and current session/revision. Preserve sources and unsaved work and report the cause to the host. Replan after resolution; failed execution or cache work is not a completed edit."
166
- };
167
- const job = {
168
- kind: "host-action",
169
- message: "Inspect the job ID and status with getJob/listJobs. Do not fabricate, restart or force-cancel a missing, terminal or non-cancellable job. Ask the host before scheduling new work; cancellation is not success."
170
- };
171
88
  /** Exhaustiveness and exact ownership are checked against the canonical unions. */
172
89
  const BACKEND_DIAGNOSTIC_GUIDES = [
173
90
  {
@@ -218,6 +135,14 @@ const BACKEND_DIAGNOSTIC_GUIDES = [
218
135
  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."
219
136
  }
220
137
  },
138
+ {
139
+ code: "session_close_failed",
140
+ owners: ["backend"],
141
+ remediation: {
142
+ kind: "host-action",
143
+ 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."
144
+ }
145
+ },
221
146
  {
222
147
  code: "path_policy_violation",
223
148
  owners: ["backend"],
@@ -698,27 +623,10 @@ const BACKEND_DIAGNOSTIC_GUIDES = [
698
623
  {
699
624
  code: "execution_failure",
700
625
  owners: ["core.transaction"],
701
- remediation: execution
702
- },
703
- {
704
- code: "cache_refresh_failed",
705
- owners: ["backend"],
706
- remediation: execution
707
- },
708
- {
709
- code: "job_not_found",
710
- owners: ["backend"],
711
- remediation: job
712
- },
713
- {
714
- code: "job_not_cancellable",
715
- owners: ["backend"],
716
- remediation: job
717
- },
718
- {
719
- code: "job_cancelled",
720
- owners: ["backend"],
721
- remediation: job
626
+ remediation: {
627
+ kind: "host-action",
628
+ 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."
629
+ }
722
630
  }
723
631
  ];
724
632
  const BACKEND_DIAGNOSTICS_URI = "openfairygui://docs/diagnostics";
@@ -741,6 +649,14 @@ function enrichBackendDiagnostic(diagnostic, sessionId) {
741
649
  }
742
650
  //#endregion
743
651
  //#region src/services/context.ts
652
+ /** Borrow without copying the entire project before a read has checked its response budget. */
653
+ function readView(value) {
654
+ return value;
655
+ }
656
+ /** A detached copy is writable again; this is the only conversion from a borrowed read view. */
657
+ function cloneReadData(value) {
658
+ return structuredClone(value);
659
+ }
744
660
  function diagnosticFromError(error) {
745
661
  return {
746
662
  code: error.code,
@@ -761,7 +677,7 @@ function createMeta(stage, startedAt, options) {
761
677
  diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
762
678
  stage,
763
679
  contractVersion: BACKEND_CONTRACT_VERSION,
764
- capabilitySchemaVersion: 11
680
+ capabilitySchemaVersion: 12
765
681
  };
766
682
  }
767
683
  function success(stage, startedAt, data, options) {
@@ -784,68 +700,6 @@ function failure(stage, startedAt, error, session, options) {
784
700
  };
785
701
  }
786
702
  //#endregion
787
- //#region src/services/session-project-writer.ts
788
- function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
789
- const contained = async (targetPath, operation) => {
790
- await assertProjectPathContained(fileSystem, projectRoot, targetPath);
791
- return operation();
792
- };
793
- async function trackWrite(targetPath, write) {
794
- try {
795
- const result = await contained(targetPath, write);
796
- writtenPaths.push(targetPath);
797
- return result;
798
- } catch (error) {
799
- failedPaths.push(targetPath);
800
- throw error;
801
- }
802
- }
803
- return {
804
- readFile: (path) => contained(path, () => fileSystem.readFile(path)),
805
- readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
806
- writeFile: (path, content) => trackWrite(path, async () => {
807
- await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
808
- await fileSystem.writeFile(path, content);
809
- }),
810
- writeFileRaw: (path, data) => trackWrite(path, async () => {
811
- await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
812
- await fileSystem.writeFileRaw(path, data);
813
- }),
814
- mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
815
- readdir: (path) => contained(path, () => fileSystem.readdir(path)),
816
- async exists(path) {
817
- await assertProjectPathContained(fileSystem, projectRoot, path);
818
- try {
819
- await fileSystem.stat(path);
820
- return true;
821
- } catch {
822
- return false;
823
- }
824
- },
825
- join: (...paths) => fileSystem.join(...paths),
826
- dirname: (path) => fileSystem.dirname(path),
827
- unlink: (path) => trackWrite(path, () => fileSystem.unlink(path)),
828
- rmdir: (path) => trackWrite(path, () => fileSystem.rmdir(path))
829
- };
830
- }
831
- async function writeSessionProject(input) {
832
- const projectRoot = input.fileSystem.dirname(input.fairyPath);
833
- const write = async (fileSystem) => {
834
- await new _openfairygui_core_project_io.ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
835
- staleSourceFiles: input.staleSourceFiles,
836
- staleResourceFolders: input.staleResourceFolders,
837
- staleBranchDirectories: input.staleBranchDirectories
838
- });
839
- };
840
- if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
841
- try {
842
- await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
843
- } catch (error) {
844
- input.writtenPaths.length = 0;
845
- throw error;
846
- }
847
- }
848
- //#endregion
849
703
  //#region src/services/session-utils.ts
850
704
  function toSessionSnapshot(session, capabilities) {
851
705
  return {
@@ -856,7 +710,7 @@ function toSessionSnapshot(session, capabilities) {
856
710
  dirty: session.dirty,
857
711
  uamFidelity: session.uamFidelity,
858
712
  lockHeld: session.lockHeld,
859
- capabilities: structuredClone(capabilities)
713
+ capabilities: cloneReadData(capabilities)
860
714
  };
861
715
  }
862
716
  function createSessionNotFoundError(sessionId) {
@@ -911,6 +765,22 @@ const BACKEND_RESOURCE_QUERY_FIELDS = [
911
765
  "image",
912
766
  "movieClip"
913
767
  ];
768
+ /** A failed staged write with an explicit outcome for the original project. */
769
+ var ProjectWriteTransactionError = class extends Error {
770
+ code = "project_write_transaction_failed";
771
+ /** Recognizes the same contract across separately bundled Node/root or ESM/CJS entries. */
772
+ static is(error) {
773
+ if (typeof error !== "object" || error === null) return false;
774
+ const value = error;
775
+ 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");
776
+ }
777
+ constructor(cause, diskMayBePartiallyUpdated, recoveryPaths = []) {
778
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
779
+ this.diskMayBePartiallyUpdated = diskMayBePartiallyUpdated;
780
+ this.recoveryPaths = recoveryPaths;
781
+ this.name = "ProjectWriteTransactionError";
782
+ }
783
+ };
914
784
  //#endregion
915
785
  //#region src/services/capture-project.ts
916
786
  function createCaptureFileSystem(files, directories) {
@@ -1181,52 +1051,6 @@ function toBackendDiagnostics(error) {
1181
1051
  opId: error.opId
1182
1052
  }];
1183
1053
  }
1184
- function createCapabilityUnavailableError$1(message) {
1185
- return {
1186
- code: "capability_unavailable",
1187
- message,
1188
- capability: "fileSystem",
1189
- requiredAdapter: "BackendFileSystem"
1190
- };
1191
- }
1192
- function createUamFidelityUnsupportedError(session) {
1193
- return {
1194
- code: "uam_fidelity_unsupported",
1195
- message: "The source project contains formal properties that the current UAM cannot preserve.",
1196
- sessionId: session.sessionId,
1197
- canonicalPathKey: session.canonicalPathKey
1198
- };
1199
- }
1200
- function validationDiagnostics(sessionProject) {
1201
- return (0, _openfairygui_core_uam.validateUamProject)(sessionProject).map((issue) => ({
1202
- code: "materialize_validation_failed",
1203
- message: issue.message,
1204
- severity: "error",
1205
- path: issue.path,
1206
- operationKind: "materializeSession"
1207
- }));
1208
- }
1209
- function toMaterializeSnapshot(session, capabilities, input) {
1210
- return {
1211
- ...toSessionSnapshot(session, capabilities),
1212
- mode: "fullProject",
1213
- reason: input.reason,
1214
- materializeRevision: session.revision,
1215
- saveRevision: session.lastSavedRevision,
1216
- writtenPaths: [...input.writtenPaths],
1217
- skippedPaths: [...input.skippedPaths],
1218
- diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic }))
1219
- };
1220
- }
1221
- function storageCanonicalTarget(input) {
1222
- const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || ".");
1223
- return {
1224
- fileSystem: input.fileSystem,
1225
- fairyPath: input.fairyPath,
1226
- canonicalProjectPath,
1227
- canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath)
1228
- };
1229
- }
1230
1054
  function detachSharedByteViews(value, seen = /* @__PURE__ */ new WeakSet()) {
1231
1055
  if (!value || typeof value !== "object" || seen.has(value)) return;
1232
1056
  seen.add(value);
@@ -1239,32 +1063,16 @@ function detachSharedByteViews(value, seen = /* @__PURE__ */ new WeakSet()) {
1239
1063
  }
1240
1064
  }
1241
1065
  var AuthoringService = class {
1242
- sessionOperations = /* @__PURE__ */ new Map();
1243
- constructor(context, cacheService, eventService) {
1066
+ constructor(context, cacheService, eventService, sessionOperations) {
1244
1067
  this.context = context;
1245
1068
  this.cacheService = cacheService;
1246
1069
  this.eventService = eventService;
1247
- }
1248
- async runSessionExclusive(sessionId, operation) {
1249
- const previous = this.sessionOperations.get(sessionId) ?? Promise.resolve();
1250
- let release = () => void 0;
1251
- const current = new Promise((resolve) => {
1252
- release = resolve;
1253
- });
1254
- const tail = previous.then(() => current);
1255
- this.sessionOperations.set(sessionId, tail);
1256
- await previous;
1257
- try {
1258
- return await operation();
1259
- } finally {
1260
- release();
1261
- if (this.sessionOperations.get(sessionId) === tail) this.sessionOperations.delete(sessionId);
1262
- }
1070
+ this.sessionOperations = sessionOperations;
1263
1071
  }
1264
1072
  async preflightTransaction(input) {
1265
1073
  const queuedInput = structuredClone(input);
1266
1074
  detachSharedByteViews(queuedInput);
1267
- return this.runSessionExclusive(queuedInput.sessionId, async () => {
1075
+ return this.sessionOperations.run(queuedInput.sessionId, async () => {
1268
1076
  const startedAt = Date.now();
1269
1077
  const session = this.context.sessions.get(queuedInput.sessionId);
1270
1078
  if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
@@ -1304,7 +1112,7 @@ var AuthoringService = class {
1304
1112
  async applyTransaction(input) {
1305
1113
  const queuedInput = structuredClone(input);
1306
1114
  detachSharedByteViews(queuedInput);
1307
- return this.runSessionExclusive(queuedInput.sessionId, () => this.applyTransactionExclusive(queuedInput));
1115
+ return this.sessionOperations.run(queuedInput.sessionId, () => this.applyTransactionExclusive(queuedInput));
1308
1116
  }
1309
1117
  async applyTransactionExclusive(input) {
1310
1118
  const startedAt = Date.now();
@@ -1365,6 +1173,200 @@ var AuthoringService = class {
1365
1173
  revision: session.revision
1366
1174
  });
1367
1175
  }
1176
+ };
1177
+ //#endregion
1178
+ //#region src/path-policy.ts
1179
+ function normalizeComparablePath(value) {
1180
+ const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
1181
+ const driveMatch = normalized.match(/^([a-z]:)(?:\/(.*))?$/i);
1182
+ const drivePrefix = driveMatch?.[1].toLowerCase() ?? "";
1183
+ const remainder = driveMatch ? driveMatch[2] ?? "" : normalized;
1184
+ const hasRoot = driveMatch ? true : remainder.startsWith("/");
1185
+ const rawSegments = remainder.split("/").filter((segment) => segment.length > 0);
1186
+ const segments = [];
1187
+ for (const segment of rawSegments) {
1188
+ if (segment === ".") continue;
1189
+ if (segment === "..") {
1190
+ if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
1191
+ else if (!hasRoot) segments.push("..");
1192
+ continue;
1193
+ }
1194
+ segments.push(segment);
1195
+ }
1196
+ const joined = segments.join("/");
1197
+ return (drivePrefix ? `${drivePrefix}/${joined}`.replace(/\/$/, "") : hasRoot ? `/${joined}`.replace(/\/$/, "") : joined || ".").toLowerCase();
1198
+ }
1199
+ function createRuntimePathPolicy() {
1200
+ return {
1201
+ canonicalization: "realpath+normalized-casefold",
1202
+ sessionIdentity: "project-root",
1203
+ saveTarget: "opened-project-only",
1204
+ outputTargets: "deferred",
1205
+ workspaceBoundary: "project-root-only"
1206
+ };
1207
+ }
1208
+ async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
1209
+ const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
1210
+ const root = normalizeComparablePath(resolvedRoot);
1211
+ const target = normalizeComparablePath(resolvedTarget);
1212
+ if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
1213
+ if (target === root || target.startsWith(`${root}/`)) return;
1214
+ const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
1215
+ error.code = "EACCES";
1216
+ throw error;
1217
+ }
1218
+ async function resolveFairyPath(fileSystem, input) {
1219
+ const resolvedInput = fileSystem.resolve(input);
1220
+ const stat = await fileSystem.stat(resolvedInput);
1221
+ if (stat.isFile() && resolvedInput.endsWith(".fairy")) return await fileSystem.resolvePath(resolvedInput);
1222
+ if (stat.isDirectory()) {
1223
+ const fairyFiles = (await fileSystem.readdir(resolvedInput)).filter((entry) => entry.endsWith(".fairy"));
1224
+ if (fairyFiles.length === 1) return await fileSystem.resolvePath(fileSystem.join(resolvedInput, fairyFiles[0]));
1225
+ if (fairyFiles.length > 1) throw new Error(`Multiple .fairy files found in ${resolvedInput}: ${fairyFiles.join(", ")}`);
1226
+ throw new Error(`No .fairy file found in ${resolvedInput}`);
1227
+ }
1228
+ throw new Error(`Input is not a .fairy file or directory: ${resolvedInput}`);
1229
+ }
1230
+ async function resolveCanonicalProjectRoot(fileSystem, input) {
1231
+ const fairyPath = await resolveFairyPath(fileSystem, input);
1232
+ const canonicalProjectPath = await fileSystem.resolvePath(fileSystem.dirname(fairyPath));
1233
+ return {
1234
+ fairyPath,
1235
+ canonicalProjectPath,
1236
+ canonicalPathKey: normalizeComparablePath(canonicalProjectPath)
1237
+ };
1238
+ }
1239
+ async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
1240
+ if (!targetPath) return null;
1241
+ const attemptedPath = await fileSystem.resolvePath(fileSystem.resolve(targetPath));
1242
+ const allowedPath = await fileSystem.resolvePath(openedFairyPath);
1243
+ if (normalizeComparablePath(attemptedPath) === normalizeComparablePath(allowedPath)) return null;
1244
+ return {
1245
+ code: "path_policy_violation",
1246
+ message: `Save target is restricted to the originally opened project file: ${allowedPath}`,
1247
+ policy: "save_target",
1248
+ attemptedPath,
1249
+ allowedPath
1250
+ };
1251
+ }
1252
+ //#endregion
1253
+ //#region src/services/session-project-writer.ts
1254
+ function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
1255
+ const contained = async (targetPath, operation) => {
1256
+ await assertProjectPathContained(fileSystem, projectRoot, targetPath);
1257
+ return operation();
1258
+ };
1259
+ async function trackWrite(targetPath, write) {
1260
+ try {
1261
+ const result = await contained(targetPath, write);
1262
+ writtenPaths.push(targetPath);
1263
+ return result;
1264
+ } catch (error) {
1265
+ failedPaths.push(targetPath);
1266
+ throw error;
1267
+ }
1268
+ }
1269
+ return {
1270
+ resolvePath: (path) => contained(path, () => fileSystem.resolvePath(path)),
1271
+ readFile: (path) => contained(path, () => fileSystem.readFile(path)),
1272
+ readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
1273
+ writeFile: (path, content) => trackWrite(path, async () => {
1274
+ await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
1275
+ await fileSystem.writeFile(path, content);
1276
+ }),
1277
+ writeFileRaw: (path, data) => trackWrite(path, async () => {
1278
+ await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
1279
+ await fileSystem.writeFileRaw(path, data);
1280
+ }),
1281
+ mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
1282
+ readdir: (path) => contained(path, () => fileSystem.readdir(path)),
1283
+ async exists(path) {
1284
+ await assertProjectPathContained(fileSystem, projectRoot, path);
1285
+ try {
1286
+ await fileSystem.stat(path);
1287
+ return true;
1288
+ } catch {
1289
+ return false;
1290
+ }
1291
+ },
1292
+ join: (...paths) => fileSystem.join(...paths),
1293
+ dirname: (path) => fileSystem.dirname(path),
1294
+ unlink: (path) => trackWrite(path, () => fileSystem.unlink(path)),
1295
+ rmdir: (path) => trackWrite(path, () => fileSystem.rmdir(path))
1296
+ };
1297
+ }
1298
+ async function writeSessionProject(input) {
1299
+ const projectRoot = input.fileSystem.dirname(input.fairyPath);
1300
+ const write = async (fileSystem) => {
1301
+ await new _openfairygui_core_project_io.ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
1302
+ staleSourceFiles: input.staleSourceFiles,
1303
+ staleResourceFolders: input.staleResourceFolders,
1304
+ staleBranchDirectories: input.staleBranchDirectories
1305
+ });
1306
+ };
1307
+ if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
1308
+ try {
1309
+ await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
1310
+ } catch (error) {
1311
+ if (ProjectWriteTransactionError.is(error) && !error.diskMayBePartiallyUpdated) input.writtenPaths.length = 0;
1312
+ throw error;
1313
+ }
1314
+ }
1315
+ //#endregion
1316
+ //#region src/services/persistence-service.ts
1317
+ function createCapabilityUnavailableError$1(message) {
1318
+ return {
1319
+ code: "capability_unavailable",
1320
+ message,
1321
+ capability: "fileSystem",
1322
+ requiredAdapter: "BackendFileSystem"
1323
+ };
1324
+ }
1325
+ function createUamFidelityUnsupportedError(session) {
1326
+ return {
1327
+ code: "uam_fidelity_unsupported",
1328
+ message: "The source project contains formal properties that the current UAM cannot preserve.",
1329
+ sessionId: session.sessionId,
1330
+ canonicalPathKey: session.canonicalPathKey
1331
+ };
1332
+ }
1333
+ function validationDiagnostics(sessionProject) {
1334
+ return (0, _openfairygui_core_uam.validateUamProject)(sessionProject).map((issue) => ({
1335
+ code: "materialize_validation_failed",
1336
+ message: issue.message,
1337
+ severity: "error",
1338
+ path: issue.path,
1339
+ operationKind: "materializeSession"
1340
+ }));
1341
+ }
1342
+ function toMaterializeSnapshot(session, capabilities, input) {
1343
+ return {
1344
+ ...toSessionSnapshot(session, capabilities),
1345
+ mode: "fullProject",
1346
+ reason: input.reason,
1347
+ materializeRevision: session.revision,
1348
+ saveRevision: session.lastSavedRevision,
1349
+ writtenPaths: [...input.writtenPaths],
1350
+ skippedPaths: [...input.skippedPaths],
1351
+ diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic }))
1352
+ };
1353
+ }
1354
+ function storageCanonicalTarget(input) {
1355
+ const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || ".");
1356
+ return {
1357
+ fileSystem: input.fileSystem,
1358
+ fairyPath: input.fairyPath,
1359
+ canonicalProjectPath,
1360
+ canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath)
1361
+ };
1362
+ }
1363
+ var PersistenceService = class {
1364
+ constructor(context, cacheService, eventService, sessionOperations) {
1365
+ this.context = context;
1366
+ this.cacheService = cacheService;
1367
+ this.eventService = eventService;
1368
+ this.sessionOperations = sessionOperations;
1369
+ }
1368
1370
  async saveSession(input) {
1369
1371
  if (input.force === true || input.mode === "materializeCleanSession") return this.materializeSession({
1370
1372
  sessionId: input.sessionId,
@@ -1374,7 +1376,8 @@ var AuthoringService = class {
1374
1376
  mode: "fullProject",
1375
1377
  reason: "force_save"
1376
1378
  });
1377
- return this.runSessionExclusive(input.sessionId, () => this.saveSessionExclusive(input));
1379
+ const captured = { ...input };
1380
+ return this.sessionOperations.run(captured.sessionId, () => this.saveSessionExclusive(captured));
1378
1381
  }
1379
1382
  finishSuccessfulSave(session) {
1380
1383
  session.lastSavedRevision = session.revision;
@@ -1466,7 +1469,8 @@ var AuthoringService = class {
1466
1469
  lastSavedRevision: session.lastSavedRevision,
1467
1470
  committedPaths,
1468
1471
  failedPaths,
1469
- diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
1472
+ diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
1473
+ ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
1470
1474
  }, toSessionSnapshot(session, this.context.capabilities), {
1471
1475
  sessionId: session.sessionId,
1472
1476
  revision: session.revision
@@ -1474,7 +1478,11 @@ var AuthoringService = class {
1474
1478
  }
1475
1479
  }
1476
1480
  async materializeSession(input) {
1477
- return this.runSessionExclusive(input.sessionId, () => this.materializeSessionExclusive(input));
1481
+ const captured = {
1482
+ ...input,
1483
+ storage: input.storage && { ...input.storage }
1484
+ };
1485
+ return this.sessionOperations.run(captured.sessionId, () => this.materializeSessionExclusive(captured));
1478
1486
  }
1479
1487
  async materializeSessionExclusive(input) {
1480
1488
  const startedAt = Date.now();
@@ -1491,24 +1499,21 @@ var AuthoringService = class {
1491
1499
  revision: session.revision
1492
1500
  });
1493
1501
  const fairyPath = storageTarget?.fairyPath ?? session.fairyPath;
1502
+ if (session.lockHeld && (fileSystem !== session.fileSystem || fairyPath !== session.fairyPath || storageTarget && (storageTarget.canonicalPathKey !== session.canonicalPathKey || storageTarget.canonicalProjectPath !== session.canonicalProjectPath))) return failure("authoring", startedAt, {
1503
+ code: "path_policy_violation",
1504
+ message: "A locked file-backed session must keep its opened storage binding.",
1505
+ policy: "save_target",
1506
+ attemptedPath: fairyPath,
1507
+ allowedPath: session.fairyPath
1508
+ }, toSessionSnapshot(session, this.context.capabilities), {
1509
+ sessionId: session.sessionId,
1510
+ revision: session.revision
1511
+ });
1494
1512
  const targetViolation = await validateSaveTarget(fileSystem, fairyPath, input.targetPath);
1495
1513
  if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
1496
1514
  sessionId: session.sessionId,
1497
1515
  revision: session.revision
1498
1516
  });
1499
- if (storageTarget) {
1500
- const holderSessionId = this.context.sessionsByPath.get(storageTarget.canonicalPathKey);
1501
- if (holderSessionId && holderSessionId !== session.sessionId) return failure("authoring", startedAt, {
1502
- code: "lock_conflict",
1503
- kind: "in_process_session_exists",
1504
- message: `Project is already open in this backend runtime: ${storageTarget.canonicalProjectPath}`,
1505
- canonicalPathKey: storageTarget.canonicalPathKey,
1506
- holderSessionId
1507
- }, toSessionSnapshot(session, this.context.capabilities), {
1508
- sessionId: session.sessionId,
1509
- revision: session.revision
1510
- });
1511
- }
1512
1517
  if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
1513
1518
  sessionId: session.sessionId,
1514
1519
  revision: session.revision
@@ -1552,6 +1557,11 @@ var AuthoringService = class {
1552
1557
  const writtenPaths = [];
1553
1558
  const failedPaths = [];
1554
1559
  const skippedPaths = [];
1560
+ const reservation = storageTarget ? this.context.sessions.reserve(session.sessionId, storageTarget) : null;
1561
+ if (reservation && "code" in reservation) return failure("authoring", startedAt, reservation, toSessionSnapshot(session, this.context.capabilities), {
1562
+ sessionId: session.sessionId,
1563
+ revision: session.revision
1564
+ });
1555
1565
  this.eventService.emit({
1556
1566
  kind: "save.started",
1557
1567
  sessionId: session.sessionId,
@@ -1581,14 +1591,7 @@ var AuthoringService = class {
1581
1591
  session.pendingStaleBranchDirectories.clear();
1582
1592
  }
1583
1593
  if (isSessionStorageTarget || storageTarget) (0, _openfairygui_core_uam.commitUamProjectSourcePaths)(session.project);
1584
- if (storageTarget) {
1585
- this.context.sessionsByPath.delete(session.canonicalPathKey);
1586
- session.fileSystem = storageTarget.fileSystem;
1587
- session.fairyPath = storageTarget.fairyPath;
1588
- session.canonicalProjectPath = storageTarget.canonicalProjectPath;
1589
- session.canonicalPathKey = storageTarget.canonicalPathKey;
1590
- this.context.sessionsByPath.set(session.canonicalPathKey, session.sessionId);
1591
- }
1594
+ reservation?.commit(session);
1592
1595
  this.finishSuccessfulSave(session);
1593
1596
  return success("authoring", startedAt, toMaterializeSnapshot(session, this.context.capabilities, {
1594
1597
  reason: input.reason,
@@ -1626,12 +1629,15 @@ var AuthoringService = class {
1626
1629
  failedPaths,
1627
1630
  skippedPaths,
1628
1631
  diagnostics: diagnosticsFromError,
1629
- diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction
1632
+ diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
1633
+ ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
1630
1634
  }, toSessionSnapshot(session, this.context.capabilities), {
1631
1635
  sessionId: session.sessionId,
1632
1636
  revision: session.revision,
1633
1637
  diagnostics: diagnosticsFromError
1634
1638
  });
1639
+ } finally {
1640
+ reservation?.release();
1635
1641
  }
1636
1642
  }
1637
1643
  };
@@ -1654,14 +1660,16 @@ function createCacheEntry(session, valid) {
1654
1660
  };
1655
1661
  }
1656
1662
  var CacheService = class {
1657
- constructor(context) {
1658
- this.context = context;
1663
+ cacheBySession = /* @__PURE__ */ new Map();
1664
+ constructor(getSession, events) {
1665
+ this.getSession = getSession;
1666
+ this.events = events;
1659
1667
  }
1660
1668
  getCacheSnapshot(input) {
1661
1669
  const startedAt = Date.now();
1662
- const session = this.context.sessions.get(input.sessionId);
1670
+ const session = this.getSession(input.sessionId);
1663
1671
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1664
- const entry = this.context.cacheBySession.get(input.sessionId);
1672
+ const entry = this.cacheBySession.get(input.sessionId);
1665
1673
  return success("read", startedAt, {
1666
1674
  cacheRevision: entry?.revision ?? session.revision,
1667
1675
  entries: entry ? [structuredClone(entry)] : []
@@ -1670,47 +1678,145 @@ var CacheService = class {
1670
1678
  revision: session.revision
1671
1679
  });
1672
1680
  }
1681
+ refreshCache(input) {
1682
+ const startedAt = Date.now();
1683
+ const session = this.getSession(input.sessionId);
1684
+ if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1685
+ const entry = this.refreshSession(session);
1686
+ this.events.emit({
1687
+ kind: "cache.updated",
1688
+ sessionId: session.sessionId,
1689
+ canonicalPathKey: session.canonicalPathKey,
1690
+ revision: session.revision,
1691
+ cacheRevision: entry.revision,
1692
+ payload: { reason: input.reason ?? "manual" }
1693
+ });
1694
+ return success("runtime", startedAt, {
1695
+ cacheRevision: entry.revision,
1696
+ entries: [structuredClone(entry)]
1697
+ }, {
1698
+ sessionId: session.sessionId,
1699
+ revision: session.revision
1700
+ });
1701
+ }
1673
1702
  refreshSession(session) {
1674
1703
  const entry = createCacheEntry(session, true);
1675
- this.context.cacheBySession.set(session.sessionId, entry);
1704
+ this.cacheBySession.set(session.sessionId, entry);
1676
1705
  return entry;
1677
1706
  }
1678
1707
  invalidateSession(session) {
1679
1708
  const entry = createCacheEntry(session, false);
1680
- this.context.cacheBySession.set(session.sessionId, entry);
1709
+ this.cacheBySession.set(session.sessionId, entry);
1681
1710
  return entry;
1682
1711
  }
1683
1712
  removeSession(sessionId) {
1684
- this.context.cacheBySession.delete(sessionId);
1713
+ this.cacheBySession.delete(sessionId);
1714
+ }
1715
+ };
1716
+ //#endregion
1717
+ //#region src/services/session-registry.ts
1718
+ /** Owns live sessions and path claims, including claims made before asynchronous I/O. */
1719
+ var SessionRegistry = class {
1720
+ sessions = /* @__PURE__ */ new Map();
1721
+ paths = /* @__PURE__ */ new Map();
1722
+ opening = /* @__PURE__ */ new Set();
1723
+ get(sessionId) {
1724
+ return this.sessions.get(sessionId);
1725
+ }
1726
+ has(sessionId) {
1727
+ return this.sessions.has(sessionId) || this.opening.has(sessionId);
1728
+ }
1729
+ reserve(sessionId, target) {
1730
+ const key = target.canonicalPathKey;
1731
+ const previous = this.paths.get(key);
1732
+ if (previous && previous.sessionId !== sessionId) return {
1733
+ code: "lock_conflict",
1734
+ kind: "in_process_session_exists",
1735
+ message: `Project is already open in this backend runtime: ${target.canonicalProjectPath}`,
1736
+ canonicalPathKey: key,
1737
+ holderSessionId: previous.sessionId,
1738
+ lockFilePath: target.lockFilePath
1739
+ };
1740
+ const claim = previous ?? { sessionId };
1741
+ this.paths.set(key, claim);
1742
+ if (!this.sessions.has(sessionId)) this.opening.add(sessionId);
1743
+ let committed = false;
1744
+ return {
1745
+ commit: (session) => {
1746
+ if (session.sessionId !== sessionId || this.paths.get(key) !== claim) throw new Error("Session path reservation lost.");
1747
+ if (session.canonicalPathKey !== key) this.releasePath(session.canonicalPathKey, sessionId);
1748
+ Object.assign(session, target);
1749
+ this.sessions.set(sessionId, session);
1750
+ this.opening.delete(sessionId);
1751
+ committed = true;
1752
+ },
1753
+ release: () => {
1754
+ if (committed) return;
1755
+ if (!previous && this.paths.get(key) === claim) this.paths.delete(key);
1756
+ this.opening.delete(sessionId);
1757
+ }
1758
+ };
1759
+ }
1760
+ remove(session) {
1761
+ if (this.sessions.get(session.sessionId) !== session) return;
1762
+ this.sessions.delete(session.sessionId);
1763
+ this.releasePath(session.canonicalPathKey, session.sessionId);
1764
+ }
1765
+ releasePath(key, sessionId) {
1766
+ if (this.paths.get(key)?.sessionId === sessionId) this.paths.delete(key);
1767
+ }
1768
+ };
1769
+ //#endregion
1770
+ //#region src/services/session-operation-queue.ts
1771
+ /** Serializes lifecycle and authoring operations for one session, without blocking other sessions. */
1772
+ var SessionOperationQueue = class {
1773
+ operations = /* @__PURE__ */ new Map();
1774
+ async run(sessionId, operation) {
1775
+ const previous = this.operations.get(sessionId) ?? Promise.resolve();
1776
+ let release = () => void 0;
1777
+ const current = new Promise((resolve) => {
1778
+ release = resolve;
1779
+ });
1780
+ const tail = previous.then(() => current);
1781
+ this.operations.set(sessionId, tail);
1782
+ await previous;
1783
+ try {
1784
+ return await operation();
1785
+ } finally {
1786
+ release();
1787
+ if (this.operations.get(sessionId) === tail) this.operations.delete(sessionId);
1788
+ }
1685
1789
  }
1686
1790
  };
1687
1791
  //#endregion
1688
1792
  //#region src/services/event-service.ts
1689
1793
  const DEFAULT_EVENT_RETENTION_LIMIT = 1e3;
1690
1794
  var EventService = class {
1691
- constructor(context) {
1692
- this.context = context;
1795
+ eventsBySession = /* @__PURE__ */ new Map();
1796
+ sequence = 0;
1797
+ constructor(getSession) {
1798
+ this.getSession = getSession;
1693
1799
  }
1694
1800
  emit(event) {
1695
1801
  const emitted = {
1696
1802
  ...event,
1697
- sequence: this.context.nextEventSequence(),
1803
+ sequence: ++this.sequence,
1698
1804
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1699
1805
  diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
1700
1806
  };
1701
1807
  const sessionId = event.sessionId;
1702
1808
  if (!sessionId) return emitted;
1703
- const events = this.context.eventsBySession.get(sessionId) ?? [];
1809
+ const events = this.eventsBySession.get(sessionId) ?? [];
1704
1810
  events.push(emitted);
1705
1811
  while (events.length > DEFAULT_EVENT_RETENTION_LIMIT) events.shift();
1706
- this.context.eventsBySession.set(sessionId, events);
1812
+ this.eventsBySession.set(sessionId, events);
1707
1813
  return emitted;
1708
1814
  }
1709
1815
  getEvents(input) {
1710
1816
  const startedAt = Date.now();
1711
- const session = this.context.sessions.get(input.sessionId);
1817
+ const session = this.getSession(input.sessionId);
1712
1818
  if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1713
- const events = this.context.eventsBySession.get(input.sessionId) ?? [];
1819
+ const events = this.eventsBySession.get(input.sessionId) ?? [];
1714
1820
  const oldestSequence = events[0]?.sequence ?? (events.length === 0 ? 1 : 0);
1715
1821
  const currentSequence = events.at(-1)?.sequence ?? 0;
1716
1822
  const after = input.after === void 0 ? 0 : Number(input.after);
@@ -1745,281 +1851,7 @@ var EventService = class {
1745
1851
  });
1746
1852
  }
1747
1853
  removeSession(sessionId) {
1748
- this.context.eventsBySession.delete(sessionId);
1749
- }
1750
- };
1751
- //#endregion
1752
- //#region src/services/job-service.ts
1753
- const COMPLETED_JOB_RETENTION_LIMIT = 100;
1754
- const REFRESH_START_DELAY_MS = 0;
1755
- const REFRESH_COMPLETE_DELAY_MS = 50;
1756
- function isTerminal(status) {
1757
- return status === "completed" || status === "failed" || status === "cancelled";
1758
- }
1759
- var JobService = class {
1760
- constructor(context, cacheService, eventService) {
1761
- this.context = context;
1762
- this.cacheService = cacheService;
1763
- this.eventService = eventService;
1764
- }
1765
- cancellationRequests = /* @__PURE__ */ new Set();
1766
- getJobs(sessionId) {
1767
- return this.context.jobsBySession.get(sessionId) ?? [];
1768
- }
1769
- setJobs(sessionId, jobs) {
1770
- const retained = [];
1771
- let terminalCount = 0;
1772
- for (let index = jobs.length - 1; index >= 0; index -= 1) {
1773
- const job = jobs[index];
1774
- if (isTerminal(job.status)) {
1775
- if (terminalCount >= COMPLETED_JOB_RETENTION_LIMIT) continue;
1776
- terminalCount += 1;
1777
- }
1778
- retained.push(job);
1779
- }
1780
- this.context.jobsBySession.set(sessionId, retained.reverse());
1781
- }
1782
- refreshCache(input) {
1783
- const startedAt = Date.now();
1784
- const session = this.context.sessions.get(input.sessionId);
1785
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1786
- const jobId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1787
- const job = {
1788
- jobId,
1789
- kind: "cache.refresh",
1790
- status: "queued",
1791
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1792
- sessionId: session.sessionId,
1793
- canonicalPathKey: session.canonicalPathKey,
1794
- revision: session.revision,
1795
- diagnostics: [],
1796
- progress: {
1797
- completed: 0,
1798
- total: 1,
1799
- message: input.reason ?? "manual"
1800
- }
1801
- };
1802
- const jobs = this.getJobs(session.sessionId);
1803
- jobs.push(job);
1804
- this.setJobs(session.sessionId, jobs);
1805
- this.eventService.emit({
1806
- kind: "job.created",
1807
- sessionId: session.sessionId,
1808
- canonicalPathKey: session.canonicalPathKey,
1809
- revision: session.revision,
1810
- jobId
1811
- });
1812
- this.scheduleRefreshJob(session.sessionId, jobId);
1813
- return success("runtime", startedAt, structuredClone(job), {
1814
- sessionId: session.sessionId,
1815
- revision: session.revision
1816
- });
1817
- }
1818
- getJob(input) {
1819
- const startedAt = Date.now();
1820
- const session = this.context.sessions.get(input.sessionId);
1821
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1822
- const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
1823
- if (!job) return failure("runtime", startedAt, {
1824
- code: "job_not_found",
1825
- message: `Job was not found: ${input.jobId}`,
1826
- sessionId: input.sessionId,
1827
- jobId: input.jobId
1828
- }, void 0, {
1829
- sessionId: session.sessionId,
1830
- revision: session.revision
1831
- });
1832
- return success("runtime", startedAt, structuredClone(job), {
1833
- sessionId: session.sessionId,
1834
- revision: session.revision
1835
- });
1836
- }
1837
- listJobs(input) {
1838
- const startedAt = Date.now();
1839
- const session = this.context.sessions.get(input.sessionId);
1840
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1841
- let jobs = [...this.getJobs(input.sessionId)];
1842
- if (input.kind) jobs = jobs.filter((job) => job.kind === input.kind);
1843
- if (input.status) if (input.status === "active") jobs = jobs.filter((job) => !isTerminal(job.status));
1844
- else if (input.status === "terminal") jobs = jobs.filter((job) => isTerminal(job.status));
1845
- else jobs = jobs.filter((job) => job.status === input.status);
1846
- if (input.limit !== void 0) jobs = jobs.slice(0, Math.max(0, input.limit));
1847
- return success("runtime", startedAt, { jobs: jobs.map((job) => structuredClone(job)) }, {
1848
- sessionId: session.sessionId,
1849
- revision: session.revision
1850
- });
1851
- }
1852
- cancelJob(input) {
1853
- const startedAt = Date.now();
1854
- const session = this.context.sessions.get(input.sessionId);
1855
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1856
- const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
1857
- if (!job) return failure("runtime", startedAt, {
1858
- code: "job_not_found",
1859
- message: `Job was not found: ${input.jobId}`,
1860
- sessionId: input.sessionId,
1861
- jobId: input.jobId
1862
- }, void 0, {
1863
- sessionId: session.sessionId,
1864
- revision: session.revision
1865
- });
1866
- if (isTerminal(job.status)) return failure("runtime", startedAt, {
1867
- code: "job_not_cancellable",
1868
- message: `Job is already terminal: ${input.jobId}`,
1869
- sessionId: input.sessionId,
1870
- jobId: input.jobId,
1871
- status: job.status
1872
- }, void 0, {
1873
- sessionId: session.sessionId,
1874
- revision: session.revision
1875
- });
1876
- this.cancellationRequests.add(job.jobId);
1877
- this.eventService.emit({
1878
- kind: "job.cancelRequested",
1879
- sessionId: input.sessionId,
1880
- canonicalPathKey: session.canonicalPathKey,
1881
- revision: session.revision,
1882
- jobId: job.jobId
1883
- });
1884
- const cancelled = this.cancelRefreshJob(session.sessionId, job);
1885
- return success("runtime", startedAt, structuredClone(cancelled), {
1886
- sessionId: session.sessionId,
1887
- revision: session.revision
1888
- });
1889
- }
1890
- removeSession(sessionId) {
1891
- for (const job of this.getJobs(sessionId)) this.cancellationRequests.delete(job.jobId);
1892
- this.context.jobsBySession.delete(sessionId);
1893
- }
1894
- replaceJob(sessionId, nextJob) {
1895
- const jobs = this.getJobs(sessionId).map((job) => job.jobId === nextJob.jobId ? nextJob : job);
1896
- this.setJobs(sessionId, jobs);
1897
- }
1898
- scheduleRefreshJob(sessionId, jobId) {
1899
- setTimeout(() => this.startRefreshJob(sessionId, jobId), REFRESH_START_DELAY_MS);
1900
- }
1901
- startRefreshJob(sessionId, jobId) {
1902
- const session = this.context.sessions.get(sessionId);
1903
- if (!session || session.closed) return;
1904
- const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
1905
- if (!job || isTerminal(job.status)) return;
1906
- if (this.cancellationRequests.has(jobId)) {
1907
- this.cancelRefreshJob(sessionId, job);
1908
- return;
1909
- }
1910
- const running = {
1911
- ...job,
1912
- status: "running",
1913
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1914
- progress: {
1915
- completed: 0,
1916
- total: 1,
1917
- message: "refreshing cache"
1918
- }
1919
- };
1920
- this.replaceJob(sessionId, running);
1921
- this.eventService.emit({
1922
- kind: "job.started",
1923
- sessionId,
1924
- canonicalPathKey: session.canonicalPathKey,
1925
- revision: session.revision,
1926
- jobId
1927
- });
1928
- this.eventService.emit({
1929
- kind: "job.progress",
1930
- sessionId,
1931
- canonicalPathKey: session.canonicalPathKey,
1932
- revision: session.revision,
1933
- jobId,
1934
- payload: running.progress
1935
- });
1936
- setTimeout(() => this.completeRefreshJob(sessionId, jobId), REFRESH_COMPLETE_DELAY_MS);
1937
- }
1938
- completeRefreshJob(sessionId, jobId) {
1939
- const session = this.context.sessions.get(sessionId);
1940
- if (!session || session.closed) return;
1941
- const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
1942
- if (!job || isTerminal(job.status)) return;
1943
- if (this.cancellationRequests.has(jobId)) {
1944
- this.cancelRefreshJob(sessionId, job);
1945
- return;
1946
- }
1947
- try {
1948
- const entry = this.cacheService.refreshSession(session);
1949
- const completed = {
1950
- ...job,
1951
- status: "completed",
1952
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1953
- cacheRevision: entry.revision,
1954
- progress: {
1955
- completed: 1,
1956
- total: 1,
1957
- message: "cache refreshed"
1958
- },
1959
- result: { cacheRevision: entry.revision }
1960
- };
1961
- this.replaceJob(sessionId, completed);
1962
- this.eventService.emit({
1963
- kind: "job.completed",
1964
- sessionId,
1965
- canonicalPathKey: session.canonicalPathKey,
1966
- revision: session.revision,
1967
- cacheRevision: entry.revision,
1968
- jobId
1969
- });
1970
- this.eventService.emit({
1971
- kind: "cache.updated",
1972
- sessionId,
1973
- canonicalPathKey: session.canonicalPathKey,
1974
- revision: session.revision,
1975
- cacheRevision: entry.revision
1976
- });
1977
- } catch (error) {
1978
- const failed = {
1979
- ...job,
1980
- status: "failed",
1981
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1982
- error: {
1983
- code: "cache_refresh_failed",
1984
- message: error instanceof Error ? error.message : "Cache refresh failed",
1985
- sessionId,
1986
- jobId
1987
- }
1988
- };
1989
- this.replaceJob(sessionId, failed);
1990
- this.eventService.emit({
1991
- kind: "job.failed",
1992
- sessionId,
1993
- canonicalPathKey: session.canonicalPathKey,
1994
- revision: session.revision,
1995
- jobId,
1996
- diagnostics: failed.diagnostics
1997
- });
1998
- }
1999
- }
2000
- cancelRefreshJob(sessionId, job) {
2001
- const session = this.context.sessions.get(sessionId);
2002
- const cancelled = {
2003
- ...job,
2004
- status: "cancelled",
2005
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
2006
- error: {
2007
- code: "job_cancelled",
2008
- message: `Job was cancelled: ${job.jobId}`,
2009
- sessionId,
2010
- jobId: job.jobId
2011
- }
2012
- };
2013
- this.replaceJob(sessionId, cancelled);
2014
- this.cancellationRequests.delete(job.jobId);
2015
- this.eventService.emit({
2016
- kind: "job.cancelled",
2017
- sessionId,
2018
- canonicalPathKey: session?.canonicalPathKey ?? job.canonicalPathKey,
2019
- revision: session?.revision ?? job.revision,
2020
- jobId: job.jobId
2021
- });
2022
- return cancelled;
1854
+ this.eventsBySession.delete(sessionId);
2023
1855
  }
2024
1856
  };
2025
1857
  //#endregion
@@ -2109,24 +1941,25 @@ function toProjectOutline(session) {
2109
1941
  };
2110
1942
  }
2111
1943
  var ReadService = class {
2112
- constructor(context) {
2113
- this.context = context;
1944
+ constructor(getSessionState, capabilities) {
1945
+ this.getSessionState = getSessionState;
1946
+ this.capabilities = capabilities;
2114
1947
  }
2115
1948
  getCapabilities() {
2116
- return success("read", Date.now(), structuredClone(this.context.capabilities));
1949
+ return success("read", Date.now(), cloneReadData(this.capabilities));
2117
1950
  }
2118
1951
  getSession(input) {
2119
1952
  const startedAt = Date.now();
2120
- const session = this.context.sessions.get(input.sessionId);
1953
+ const session = this.getSessionState(input.sessionId);
2121
1954
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2122
- return success("read", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1955
+ return success("read", startedAt, toSessionSnapshot(session, this.capabilities), {
2123
1956
  sessionId: session.sessionId,
2124
1957
  revision: session.revision
2125
1958
  });
2126
1959
  }
2127
1960
  getProjectOutline(input) {
2128
1961
  const startedAt = Date.now();
2129
- const session = this.context.sessions.get(input.sessionId);
1962
+ const session = this.getSessionState(input.sessionId);
2130
1963
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2131
1964
  return success("read", startedAt, toProjectOutline(session), {
2132
1965
  sessionId: session.sessionId,
@@ -2135,7 +1968,7 @@ var ReadService = class {
2135
1968
  }
2136
1969
  queryEntity(input) {
2137
1970
  const startedAt = Date.now();
2138
- const session = this.context.sessions.get(input.sessionId);
1971
+ const session = this.getSessionState(input.sessionId);
2139
1972
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2140
1973
  const meta = {
2141
1974
  sessionId: session.sessionId,
@@ -2156,7 +1989,7 @@ var ReadService = class {
2156
1989
  entity
2157
1990
  };
2158
1991
  const problem = queryResponseProblem(data);
2159
- return problem ? reject(problem) : success("read", startedAt, structuredClone(data), meta);
1992
+ return problem ? reject(problem) : success("read", startedAt, cloneReadData(data), meta);
2160
1993
  };
2161
1994
  if (target.kind === "project") {
2162
1995
  if (Object.hasOwn(target, "selector")) return reject("invalid_query");
@@ -2250,7 +2083,7 @@ var ReadService = class {
2250
2083
  }
2251
2084
  resolveReadSession(input, startedAt) {
2252
2085
  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");
2253
- const session = this.context.sessions.get(input.sessionId);
2086
+ const session = this.getSessionState(input.sessionId);
2254
2087
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2255
2088
  const meta = {
2256
2089
  sessionId: session.sessionId,
@@ -2294,7 +2127,7 @@ var ReadService = class {
2294
2127
  }
2295
2128
  };
2296
2129
  const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
2297
- return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, structuredClone(data), meta);
2130
+ return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, cloneReadData(data), meta);
2298
2131
  }
2299
2132
  readResourceBytes(input) {
2300
2133
  const startedAt = Date.now();
@@ -2324,10 +2157,10 @@ var ReadService = class {
2324
2157
  }
2325
2158
  validateSession(input) {
2326
2159
  const startedAt = Date.now();
2327
- const session = this.context.sessions.get(input.sessionId);
2160
+ const session = this.getSessionState(input.sessionId);
2328
2161
  if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
2329
- const report = (0, _openfairygui_functions.validateProject)(session.project, {
2330
- readDiagnostics: session.readDiagnostics,
2162
+ const report = (0, _openfairygui_functions.validateProject)(cloneReadData(session.project), {
2163
+ readDiagnostics: cloneReadData(session.readDiagnostics),
2331
2164
  complete: session.readComplete,
2332
2165
  validateSources: true
2333
2166
  });
@@ -2366,6 +2199,7 @@ function createProjectReaderFileSystem(fileSystem, projectRoot) {
2366
2199
  return operation();
2367
2200
  };
2368
2201
  return {
2202
+ stat: (path) => contained(path, () => fileSystem.stat(path)),
2369
2203
  readFile(filePath) {
2370
2204
  return contained(filePath, () => fileSystem.readFile(filePath));
2371
2205
  },
@@ -2413,11 +2247,10 @@ async function hasFullUamFidelity(document, project) {
2413
2247
  return capturedFilesEqual(sourceFiles, materializedFiles) && capturedDirectoriesEqual(sourceDirectories, materializedDirectories);
2414
2248
  }
2415
2249
  var RuntimeService = class {
2416
- constructor(context, cacheService, eventService, jobService) {
2250
+ constructor(context, cacheService, eventService) {
2417
2251
  this.context = context;
2418
2252
  this.cacheService = cacheService;
2419
2253
  this.eventService = eventService;
2420
- this.jobService = jobService;
2421
2254
  }
2422
2255
  async openSession(input) {
2423
2256
  const startedAt = Date.now();
@@ -2440,16 +2273,14 @@ var RuntimeService = class {
2440
2273
  }
2441
2274
  const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
2442
2275
  await fileSystem.validateProjectRoot?.(canonicalProjectPath);
2443
- const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
2444
2276
  const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath) ?? fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
2445
- if (existingSessionId) return failure("runtime", startedAt, {
2446
- code: "lock_conflict",
2447
- kind: "in_process_session_exists",
2448
- message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
2277
+ const sessionId = randomId();
2278
+ const reservation = this.context.sessions.reserve(sessionId, {
2449
2279
  canonicalPathKey,
2450
- holderSessionId: existingSessionId,
2280
+ canonicalProjectPath,
2451
2281
  lockFilePath
2452
2282
  });
2283
+ if ("code" in reservation) return failure("runtime", startedAt, reservation);
2453
2284
  let sessionLock = null;
2454
2285
  try {
2455
2286
  sessionLock = await fileSystem.acquireSessionLock(lockFilePath);
@@ -2465,7 +2296,6 @@ var RuntimeService = class {
2465
2296
  if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
2466
2297
  const document = read.document;
2467
2298
  const project = (0, _openfairygui_core_uam.liftDocumentToUamProject)(document);
2468
- const sessionId = randomId();
2469
2299
  const session = {
2470
2300
  sessionId,
2471
2301
  fairyPath,
@@ -2477,7 +2307,7 @@ var RuntimeService = class {
2477
2307
  project,
2478
2308
  readDiagnostics: read.diagnostics,
2479
2309
  readComplete: read.complete,
2480
- uamFidelity: await hasFullUamFidelity(document, project) ? "full" : "unsupported",
2310
+ uamFidelity: read.complete && await hasFullUamFidelity(document, project) ? "full" : "unsupported",
2481
2311
  revision: 0,
2482
2312
  lastSavedRevision: 0,
2483
2313
  pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
@@ -2487,8 +2317,7 @@ var RuntimeService = class {
2487
2317
  lockHeld: true,
2488
2318
  closed: false
2489
2319
  };
2490
- this.context.sessions.set(sessionId, session);
2491
- this.context.sessionsByPath.set(canonicalPathKey, sessionId);
2320
+ reservation.commit(session);
2492
2321
  this.cacheService.refreshSession(session);
2493
2322
  this.eventService.emit({
2494
2323
  kind: "session.opened",
@@ -2514,6 +2343,8 @@ var RuntimeService = class {
2514
2343
  message: error instanceof Error ? error.message : String(error)
2515
2344
  });
2516
2345
  throw error;
2346
+ } finally {
2347
+ reservation.release();
2517
2348
  }
2518
2349
  }
2519
2350
  openProjectSession(input) {
@@ -2528,14 +2359,12 @@ var RuntimeService = class {
2528
2359
  const memoryProjectPath = `memory://${sessionId}`;
2529
2360
  const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
2530
2361
  const canonicalPathKey = storage?.canonicalPathKey ?? input.canonicalPathKey ?? (storage ? normalizeComparablePath(canonicalProjectPath) : canonicalProjectPath.toLowerCase());
2531
- const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
2532
- if (existingSessionId) return failure("runtime", startedAt, {
2533
- code: "lock_conflict",
2534
- kind: "in_process_session_exists",
2535
- message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
2362
+ const project = (0, _openfairygui_core_uam.normalizeUamProject)(input.project);
2363
+ const reservation = this.context.sessions.reserve(sessionId, {
2536
2364
  canonicalPathKey,
2537
- holderSessionId: existingSessionId
2365
+ canonicalProjectPath
2538
2366
  });
2367
+ if ("code" in reservation) return failure("runtime", startedAt, reservation);
2539
2368
  const session = {
2540
2369
  sessionId,
2541
2370
  fairyPath: storage?.fairyPath ?? canonicalProjectPath,
@@ -2544,7 +2373,7 @@ var RuntimeService = class {
2544
2373
  lockFilePath: "",
2545
2374
  sessionLock: null,
2546
2375
  fileSystem: storage?.fileSystem,
2547
- project: (0, _openfairygui_core_uam.normalizeUamProject)(input.project),
2376
+ project,
2548
2377
  readDiagnostics: [],
2549
2378
  readComplete: true,
2550
2379
  uamFidelity: "full",
@@ -2557,8 +2386,7 @@ var RuntimeService = class {
2557
2386
  lockHeld: false,
2558
2387
  closed: false
2559
2388
  };
2560
- this.context.sessions.set(sessionId, session);
2561
- this.context.sessionsByPath.set(canonicalPathKey, sessionId);
2389
+ reservation.commit(session);
2562
2390
  this.cacheService.refreshSession(session);
2563
2391
  this.eventService.emit({
2564
2392
  kind: "session.opened",
@@ -2581,14 +2409,24 @@ var RuntimeService = class {
2581
2409
  canonicalPathKey: session.canonicalPathKey,
2582
2410
  revision: session.revision
2583
2411
  });
2584
- await session.sessionLock?.release().catch(() => void 0);
2412
+ try {
2413
+ await session.sessionLock?.release();
2414
+ } catch (error) {
2415
+ return failure("runtime", startedAt, {
2416
+ code: "session_close_failed",
2417
+ message: error instanceof Error ? error.message : String(error),
2418
+ sessionId: session.sessionId,
2419
+ lockFilePath: session.lockFilePath
2420
+ }, toSessionSnapshot(session, this.context.capabilities), {
2421
+ sessionId: session.sessionId,
2422
+ revision: session.revision
2423
+ });
2424
+ }
2585
2425
  session.sessionLock = null;
2586
2426
  session.lockHeld = false;
2587
2427
  session.closed = true;
2588
- this.context.sessions.delete(session.sessionId);
2589
- this.context.sessionsByPath.delete(session.canonicalPathKey);
2428
+ this.context.sessions.remove(session);
2590
2429
  this.cacheService.removeSession(session.sessionId);
2591
- this.jobService.removeSession(session.sessionId);
2592
2430
  this.eventService.emit({
2593
2431
  kind: "session.closed",
2594
2432
  sessionId: session.sessionId,
@@ -2641,9 +2479,6 @@ const BACKEND_METHODS = [
2641
2479
  "materializeSession",
2642
2480
  "closeSession",
2643
2481
  "getEvents",
2644
- "getJob",
2645
- "listJobs",
2646
- "cancelJob",
2647
2482
  "getCacheSnapshot",
2648
2483
  "refreshCache"
2649
2484
  ];
@@ -2657,7 +2492,7 @@ const ARTIFACT_BRIDGE_CAPABILITY = {
2657
2492
  function createCapabilities(atomicSave = false) {
2658
2493
  return {
2659
2494
  contractVersion: BACKEND_CONTRACT_VERSION,
2660
- capabilitySchemaVersion: 11,
2495
+ capabilitySchemaVersion: 12,
2661
2496
  transactionKernelOwner: "@openfairygui/core",
2662
2497
  appSeamOwner: "@openfairygui/functions",
2663
2498
  runtimeOwner: "@openfairygui/backend",
@@ -2766,17 +2601,10 @@ function createCapabilities(atomicSave = false) {
2766
2601
  retentionLimit: 1e3,
2767
2602
  sequenceScope: "runtime"
2768
2603
  },
2769
- jobs: {
2770
- inMemory: true,
2771
- cooperativeCancel: true,
2772
- persistent: false,
2773
- supportedKinds: ["cache.refresh"],
2774
- artifactJobs: false,
2775
- completedRetentionLimit: 100
2776
- },
2777
2604
  cache: {
2778
2605
  derivedReadOnly: true,
2779
- keyedBy: "canonicalPathKey",
2606
+ keyedBy: "sessionId",
2607
+ refreshMode: "synchronous",
2780
2608
  sourceOfTruth: false,
2781
2609
  refreshMethod: "refreshCache"
2782
2610
  }
@@ -2788,19 +2616,15 @@ function createCapabilities(atomicSave = false) {
2788
2616
  var BackendRuntime = class {
2789
2617
  fileSystem;
2790
2618
  capabilities;
2791
- sessions = /* @__PURE__ */ new Map();
2792
- sessionsByPath = /* @__PURE__ */ new Map();
2793
- eventsBySession = /* @__PURE__ */ new Map();
2794
- jobsBySession = /* @__PURE__ */ new Map();
2795
- cacheBySession = /* @__PURE__ */ new Map();
2796
- eventSequence = 0;
2619
+ sessions = new SessionRegistry();
2620
+ sessionOperations = new SessionOperationQueue();
2797
2621
  context;
2798
2622
  readService;
2799
2623
  runtimeService;
2800
2624
  authoringService;
2625
+ persistenceService;
2801
2626
  cacheService;
2802
2627
  eventService;
2803
- jobService;
2804
2628
  constructor(options = {}) {
2805
2629
  this.fileSystem = options.fileSystem;
2806
2630
  this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
@@ -2809,22 +2633,15 @@ var BackendRuntime = class {
2809
2633
  host: options.host,
2810
2634
  allowedProjectRoots: options.allowedProjectRoots,
2811
2635
  capabilities: this.capabilities,
2812
- sessions: this.sessions,
2813
- sessionsByPath: this.sessionsByPath,
2814
- eventsBySession: this.eventsBySession,
2815
- jobsBySession: this.jobsBySession,
2816
- cacheBySession: this.cacheBySession,
2817
- nextEventSequence: () => {
2818
- this.eventSequence += 1;
2819
- return this.eventSequence;
2820
- }
2636
+ sessions: this.sessions
2821
2637
  };
2822
- this.readService = new ReadService(this.context);
2823
- this.eventService = new EventService(this.context);
2824
- this.cacheService = new CacheService(this.context);
2825
- this.jobService = new JobService(this.context, this.cacheService, this.eventService);
2826
- this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService, this.jobService);
2827
- this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService);
2638
+ const getSession = (sessionId) => this.sessions.get(sessionId);
2639
+ this.readService = new ReadService((sessionId) => readView(getSession(sessionId)), this.capabilities);
2640
+ this.eventService = new EventService(getSession);
2641
+ this.cacheService = new CacheService(getSession, this.eventService);
2642
+ this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService);
2643
+ this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService, this.sessionOperations);
2644
+ this.persistenceService = new PersistenceService(this.context, this.cacheService, this.eventService, this.sessionOperations);
2828
2645
  }
2829
2646
  getCapabilities() {
2830
2647
  return this.readService.getCapabilities();
@@ -2869,31 +2686,23 @@ var BackendRuntime = class {
2869
2686
  return this.authoringService.applyTransaction(input);
2870
2687
  }
2871
2688
  async saveSession(input) {
2872
- return this.authoringService.saveSession(input);
2689
+ return this.persistenceService.saveSession(input);
2873
2690
  }
2874
2691
  async materializeSession(input) {
2875
- return this.authoringService.materializeSession(input);
2692
+ return this.persistenceService.materializeSession(input);
2876
2693
  }
2877
2694
  async closeSession(input) {
2878
- return this.authoringService.runSessionExclusive(input.sessionId, () => this.runtimeService.closeSession(input));
2695
+ const captured = { ...input };
2696
+ return this.sessionOperations.run(captured.sessionId, () => this.runtimeService.closeSession(captured));
2879
2697
  }
2880
2698
  getEvents(input) {
2881
2699
  return this.eventService.getEvents(input);
2882
2700
  }
2883
- getJob(input) {
2884
- return this.jobService.getJob(input);
2885
- }
2886
- listJobs(input) {
2887
- return this.jobService.listJobs(input);
2888
- }
2889
- cancelJob(input) {
2890
- return this.jobService.cancelJob(input);
2891
- }
2892
2701
  getCacheSnapshot(input) {
2893
2702
  return this.cacheService.getCacheSnapshot(input);
2894
2703
  }
2895
2704
  refreshCache(input) {
2896
- return this.jobService.refreshCache(input);
2705
+ return this.cacheService.refreshCache(input);
2897
2706
  }
2898
2707
  };
2899
2708
  //#endregion
@@ -3002,39 +2811,36 @@ async function runNodeProjectWriteTransaction(projectRoot, write) {
3002
2811
  const staging = node_path.default.join(parent, `.${name}.save-${(0, node_crypto.randomUUID)()}`);
3003
2812
  const backup = node_path.default.join(parent, `.${name}.save-backup-${(0, node_crypto.randomUUID)()}`);
3004
2813
  const existed = await pathExists(root);
3005
- if (existed) {
3006
- await assertNoSymlinks(root);
3007
- await node_fs_promises.default.cp(root, staging, {
3008
- recursive: true,
3009
- errorOnExist: true,
3010
- force: false
3011
- });
3012
- } else await node_fs_promises.default.mkdir(staging, { recursive: true });
3013
2814
  try {
2815
+ if (existed) {
2816
+ await assertNoSymlinks(root);
2817
+ await node_fs_promises.default.cp(root, staging, {
2818
+ recursive: true,
2819
+ errorOnExist: true,
2820
+ force: false
2821
+ });
2822
+ } else await node_fs_promises.default.mkdir(staging, { recursive: true });
3014
2823
  await write(createStagedNodeFileSystem(root, staging));
2824
+ if (existed) await node_fs_promises.default.rename(root, backup);
2825
+ try {
2826
+ await node_fs_promises.default.rename(staging, root);
2827
+ } catch (commitError) {
2828
+ if (existed) try {
2829
+ await node_fs_promises.default.rename(backup, root);
2830
+ } catch (rollbackError) {
2831
+ throw new ProjectWriteTransactionError(new AggregateError([commitError, rollbackError], "Project commit and rollback both failed."), true, [backup, staging]);
2832
+ }
2833
+ throw commitError;
2834
+ }
3015
2835
  } catch (error) {
2836
+ if (ProjectWriteTransactionError.is(error)) throw error;
3016
2837
  await node_fs_promises.default.rm(staging, {
3017
2838
  recursive: true,
3018
2839
  force: true
3019
- });
3020
- throw error;
3021
- }
3022
- if (!existed) {
3023
- await node_fs_promises.default.rename(staging, root);
3024
- return;
3025
- }
3026
- await node_fs_promises.default.rename(root, backup);
3027
- try {
3028
- await node_fs_promises.default.rename(staging, root);
3029
- } catch (error) {
3030
- await node_fs_promises.default.rename(backup, root);
3031
- await node_fs_promises.default.rm(staging, {
3032
- recursive: true,
3033
- force: true
3034
- });
3035
- throw error;
2840
+ }).catch(() => void 0);
2841
+ throw new ProjectWriteTransactionError(error, false);
3036
2842
  }
3037
- await node_fs_promises.default.rm(backup, {
2843
+ if (existed) await node_fs_promises.default.rm(backup, {
3038
2844
  recursive: true,
3039
2845
  force: true
3040
2846
  }).catch(() => void 0);
@@ -3119,10 +2925,16 @@ function createNodeBackendFileSystem() {
3119
2925
  async release() {
3120
2926
  if (released) return;
3121
2927
  await closeHandle();
3122
- const current = metadataWritten ? parseLockMetadata(await node_fs_promises.default.readFile(filePath, "utf-8").catch(() => "")) : null;
3123
- if (!metadataWritten || current?.token === owner.token) await node_fs_promises.default.unlink(filePath).catch((error) => {
2928
+ try {
2929
+ if (metadataWritten) {
2930
+ const current = parseLockMetadata(await node_fs_promises.default.readFile(filePath, "utf-8"));
2931
+ if (!current) throw new Error("Cannot release session lock: invalid ownership metadata");
2932
+ if (current.token !== owner.token) throw new Error("Cannot release session lock: ownership token changed");
2933
+ }
2934
+ await node_fs_promises.default.unlink(filePath);
2935
+ } catch (error) {
3124
2936
  if (error.code !== "ENOENT") throw error;
3125
- });
2937
+ }
3126
2938
  released = true;
3127
2939
  }
3128
2940
  };