@openfairygui/backend 0.6.3 → 0.7.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.
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
@@ -0,0 +1,2189 @@
1
+ import { r as enrichBackendDiagnostic } from "./diagnostics-DTnLXQGs.mjs";
2
+ import { UAM_SUPPORTED_MATERIALIZATION_SCOPE, UAM_SUPPORTED_TRANSACTION_SCOPE, commitUamProjectSourcePaths, liftDocumentToUamProject, materializeUamProject, normalizeUamProject, staleBranchDirectories, staleResourceFolders, staleSourceFiles, validateUamProject } from "@openfairygui/core/uam";
3
+ import { applyUamTransactionAppAsync } from "@openfairygui/functions/uam";
4
+ import { ProjectReader, ProjectWriter } from "@openfairygui/core/project-io";
5
+ import { validateProject } from "@openfairygui/functions";
6
+ //#region src/contracts.ts
7
+ const BACKEND_CONTRACT_VERSION = "3.0.0";
8
+ const BACKEND_CAPABILITY_SCHEMA_VERSION = 15;
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/path-policy.ts
16
+ /** A classified project-open failure whose message is safe to return to the caller. */
17
+ var ProjectOpenError = class extends Error {
18
+ constructor(reason, message) {
19
+ super(message);
20
+ this.reason = reason;
21
+ }
22
+ };
23
+ const OPEN_FAILURE_MESSAGES = {
24
+ project_not_found: "Project path does not exist.",
25
+ not_a_project_file: "Project path is neither a .fairy file nor a directory.",
26
+ no_project_file: "Project directory contains no .fairy file.",
27
+ multiple_project_files: "Project directory contains more than one .fairy file; open the intended .fairy file directly.",
28
+ symbolic_link_unsupported: "Project directory contains a symbolic link, which this host does not support.",
29
+ access_denied: "Project path could not be accessed.",
30
+ project_read_failed: "Project files could not be read.",
31
+ unknown: "Unable to open project."
32
+ };
33
+ function classifyProjectOpenFailure(error) {
34
+ if (error instanceof ProjectOpenError) return {
35
+ reason: error.reason,
36
+ message: error.message
37
+ };
38
+ const code = typeof error === "object" && error !== null ? error.code : void 0;
39
+ const reason = code === "ENOENT" || code === "ENOTDIR" || code === "NotFoundError" ? "project_not_found" : code === "ELOOP" ? "symbolic_link_unsupported" : code === "EACCES" || code === "EPERM" || code === "NotAllowedError" ? "access_denied" : "unknown";
40
+ return {
41
+ reason,
42
+ message: OPEN_FAILURE_MESSAGES[reason]
43
+ };
44
+ }
45
+ function openError(reason, detail) {
46
+ return new ProjectOpenError(reason, detail ? `${OPEN_FAILURE_MESSAGES[reason]} ${detail}` : OPEN_FAILURE_MESSAGES[reason]);
47
+ }
48
+ function createProjectReadFailure(detail) {
49
+ return openError("project_read_failed", detail);
50
+ }
51
+ function normalizeComparablePath(value, caseSensitive = false) {
52
+ const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
53
+ const driveMatch = normalized.match(/^([a-z]:)(?:\/(.*))?$/i);
54
+ const drivePrefix = driveMatch?.[1].toLowerCase() ?? "";
55
+ const remainder = driveMatch ? driveMatch[2] ?? "" : normalized;
56
+ const hasRoot = driveMatch ? true : remainder.startsWith("/");
57
+ const rawSegments = remainder.split("/").filter((segment) => segment.length > 0);
58
+ const segments = [];
59
+ for (const segment of rawSegments) {
60
+ if (segment === ".") continue;
61
+ if (segment === "..") {
62
+ if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
63
+ else if (!hasRoot) segments.push("..");
64
+ continue;
65
+ }
66
+ segments.push(segment);
67
+ }
68
+ const joined = segments.join("/");
69
+ const comparable = drivePrefix ? `${drivePrefix}/${joined}`.replace(/\/$/, "") : hasRoot ? `/${joined}`.replace(/\/$/, "") : joined || ".";
70
+ return caseSensitive ? comparable : comparable.toLowerCase();
71
+ }
72
+ function createRuntimePathPolicy(caseSensitivePaths = false) {
73
+ return {
74
+ canonicalization: caseSensitivePaths ? "realpath+normalized" : "realpath+normalized-casefold",
75
+ sessionIdentity: "project-root",
76
+ saveTarget: "opened-project-only",
77
+ outputTargets: "deferred",
78
+ workspaceBoundary: "project-root-only"
79
+ };
80
+ }
81
+ async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
82
+ const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
83
+ const root = normalizeComparablePath(resolvedRoot, fileSystem.caseSensitivePaths);
84
+ const target = normalizeComparablePath(resolvedTarget, fileSystem.caseSensitivePaths);
85
+ if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
86
+ if (target === root || target.startsWith(`${root}/`)) return;
87
+ const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
88
+ error.code = "EACCES";
89
+ throw error;
90
+ }
91
+ async function resolveFairyPath(fileSystem, input) {
92
+ const resolvedInput = fileSystem.resolve(input);
93
+ const stat = await fileSystem.stat(resolvedInput);
94
+ if (stat.isFile() && resolvedInput.endsWith(".fairy")) return await fileSystem.resolvePath(resolvedInput);
95
+ if (stat.isDirectory()) {
96
+ const fairyFiles = (await fileSystem.readdir(resolvedInput)).filter((entry) => entry.endsWith(".fairy"));
97
+ if (fairyFiles.length === 1) return await fileSystem.resolvePath(fileSystem.join(resolvedInput, fairyFiles[0]));
98
+ if (fairyFiles.length > 1) throw openError("multiple_project_files", `Found: ${fairyFiles.join(", ")}`);
99
+ throw openError("no_project_file");
100
+ }
101
+ throw openError("not_a_project_file");
102
+ }
103
+ async function resolveCanonicalProjectRoot(fileSystem, input) {
104
+ const fairyPath = await resolveFairyPath(fileSystem, input);
105
+ const canonicalProjectPath = await fileSystem.resolvePath(fileSystem.dirname(fairyPath));
106
+ return {
107
+ fairyPath,
108
+ canonicalProjectPath,
109
+ canonicalPathKey: normalizeComparablePath(canonicalProjectPath, fileSystem.caseSensitivePaths)
110
+ };
111
+ }
112
+ async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
113
+ if (!targetPath) return null;
114
+ const attemptedPath = await fileSystem.resolvePath(fileSystem.resolve(targetPath));
115
+ const allowedPath = await fileSystem.resolvePath(openedFairyPath);
116
+ const caseSensitive = fileSystem.caseSensitivePaths;
117
+ if (normalizeComparablePath(attemptedPath, caseSensitive) === normalizeComparablePath(allowedPath, caseSensitive)) return null;
118
+ return {
119
+ code: "path_policy_violation",
120
+ message: `Save target is restricted to the originally opened project file: ${allowedPath}`,
121
+ policy: "save_target",
122
+ attemptedPath,
123
+ allowedPath
124
+ };
125
+ }
126
+ //#endregion
127
+ //#region src/services/context.ts
128
+ /** Borrow without copying the entire project before a read has checked its response budget. */
129
+ function readView(value) {
130
+ return value;
131
+ }
132
+ /** A detached copy is writable again; this is the only conversion from a borrowed read view. */
133
+ function cloneReadData(value) {
134
+ return structuredClone(value);
135
+ }
136
+ function diagnosticFromError(error) {
137
+ return {
138
+ code: error.code,
139
+ message: error.message,
140
+ severity: "error"
141
+ };
142
+ }
143
+ function randomId$1() {
144
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
145
+ }
146
+ function createMeta(stage, startedAt, options) {
147
+ return {
148
+ requestId: options?.requestId ?? randomId$1(),
149
+ sessionId: options?.sessionId,
150
+ revision: options?.revision,
151
+ durationMs: Math.max(0, Date.now() - startedAt),
152
+ warnings: options?.warnings ?? [],
153
+ diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
154
+ stage,
155
+ contractVersion: BACKEND_CONTRACT_VERSION,
156
+ capabilitySchemaVersion: 15
157
+ };
158
+ }
159
+ function success(stage, startedAt, data, options) {
160
+ return {
161
+ ok: true,
162
+ meta: createMeta(stage, startedAt, options),
163
+ data
164
+ };
165
+ }
166
+ function failure(stage, startedAt, error, session, options) {
167
+ const diagnostics = options?.diagnostics ?? [diagnosticFromError(error)];
168
+ return {
169
+ ok: false,
170
+ meta: createMeta(stage, startedAt, {
171
+ ...options,
172
+ diagnostics
173
+ }),
174
+ error,
175
+ session
176
+ };
177
+ }
178
+ //#endregion
179
+ //#region src/services/session-utils.ts
180
+ function toSessionSnapshot(session, capabilities) {
181
+ return {
182
+ sessionId: session.sessionId,
183
+ canonicalProjectPath: session.canonicalProjectPath,
184
+ revision: session.revision,
185
+ lastSavedRevision: session.lastSavedRevision,
186
+ dirty: session.dirty,
187
+ uamFidelity: session.uamFidelity,
188
+ lockHeld: session.lockHeld,
189
+ capabilities: cloneReadData(capabilities)
190
+ };
191
+ }
192
+ function createSessionNotFoundError(sessionId) {
193
+ return {
194
+ code: "session_not_found",
195
+ message: `Session was not found: ${sessionId}`,
196
+ sessionId
197
+ };
198
+ }
199
+ function createStaleWriteError(session, expectedRevision) {
200
+ return {
201
+ code: "stale_write",
202
+ message: `Expected revision ${expectedRevision} does not match current revision ${session.revision}.`,
203
+ sessionId: session.sessionId,
204
+ canonicalPathKey: session.canonicalPathKey,
205
+ expectedRevision,
206
+ actualRevision: session.revision
207
+ };
208
+ }
209
+ //#endregion
210
+ //#region src/runtime/contracts.ts
211
+ const BACKEND_ENTITY_QUERY_LIMITS = {
212
+ maxBytes: 262144,
213
+ maxDepth: 32,
214
+ maxNodes: 1e5
215
+ };
216
+ const BACKEND_SESSION_READ_LIMITS = {
217
+ model: {
218
+ maxBytes: 4194304,
219
+ maxDepth: 64,
220
+ maxNodes: 5e5
221
+ },
222
+ resourceBytes: 1048576
223
+ };
224
+ const BACKEND_TRANSACTION_PREVIEW_LIMITS = {
225
+ maxBytes: 262144,
226
+ maxEntries: 2e3
227
+ };
228
+ /** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
229
+ const BACKEND_RESOURCE_QUERY_FIELDS = [
230
+ "kind",
231
+ "id",
232
+ "name",
233
+ "path",
234
+ "exported",
235
+ "favorite",
236
+ "branch",
237
+ "branchItemIds",
238
+ "fileName",
239
+ "file",
240
+ "dimensions",
241
+ "image",
242
+ "movieClip"
243
+ ];
244
+ /** A failed staged write with an explicit outcome for the original project. */
245
+ var ProjectWriteTransactionError = class extends Error {
246
+ code = "project_write_transaction_failed";
247
+ /** Recognizes the same contract across separately bundled Node/root or ESM/CJS entries. */
248
+ static is(error) {
249
+ if (typeof error !== "object" || error === null) return false;
250
+ const value = error;
251
+ 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");
252
+ }
253
+ constructor(cause, diskMayBePartiallyUpdated, recoveryPaths = []) {
254
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
255
+ this.diskMayBePartiallyUpdated = diskMayBePartiallyUpdated;
256
+ this.recoveryPaths = recoveryPaths;
257
+ this.name = "ProjectWriteTransactionError";
258
+ }
259
+ };
260
+ //#endregion
261
+ //#region src/services/capture-project.ts
262
+ function createCaptureFileSystem(files, directories) {
263
+ const normalize = (filePath) => filePath.replace(/\\/g, "/").replace(/\/+/g, "/");
264
+ return {
265
+ async readFile(filePath) {
266
+ const value = files.get(normalize(filePath));
267
+ if (typeof value !== "string") throw new Error(`Captured text file was not found: ${filePath}`);
268
+ return value;
269
+ },
270
+ async readFileRaw(filePath) {
271
+ const value = files.get(normalize(filePath));
272
+ if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
273
+ return value.slice();
274
+ },
275
+ async writeFile(filePath, content) {
276
+ files.set(normalize(filePath), content);
277
+ },
278
+ async writeFileRaw(filePath, data) {
279
+ files.set(normalize(filePath), data.slice());
280
+ },
281
+ async mkdir(dirPath) {
282
+ directories.add(normalize(dirPath));
283
+ },
284
+ async readdir() {
285
+ return [];
286
+ },
287
+ async exists(filePath) {
288
+ return files.has(normalize(filePath));
289
+ },
290
+ join(...paths) {
291
+ return normalize(paths.filter(Boolean).join("/"));
292
+ },
293
+ dirname(filePath) {
294
+ const normalized = normalize(filePath);
295
+ const separator = normalized.lastIndexOf("/");
296
+ return separator < 0 ? "" : normalized.slice(0, separator);
297
+ },
298
+ async unlink(filePath) {
299
+ files.delete(normalize(filePath));
300
+ }
301
+ };
302
+ }
303
+ function capturedFilesEqual(left, right) {
304
+ if (left.size !== right.size) return false;
305
+ for (const [filePath, leftValue] of left) {
306
+ const rightValue = right.get(filePath);
307
+ if (typeof leftValue === "string") {
308
+ if (leftValue !== rightValue) return false;
309
+ continue;
310
+ }
311
+ if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
312
+ for (let index = 0; index < leftValue.length; index += 1) if (leftValue[index] !== rightValue[index]) return false;
313
+ }
314
+ return true;
315
+ }
316
+ function capturedDirectoriesEqual(left, right) {
317
+ return left.size === right.size && [...left].every((directory) => right.has(directory));
318
+ }
319
+ /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
320
+ async function captureProject(document, fairyFileName) {
321
+ const files = /* @__PURE__ */ new Map();
322
+ const directories = /* @__PURE__ */ new Set();
323
+ await new ProjectWriter(createCaptureFileSystem(files, directories)).write(document, fairyFileName);
324
+ return {
325
+ files,
326
+ directories
327
+ };
328
+ }
329
+ //#endregion
330
+ //#region src/services/transaction-preview.ts
331
+ /** Keep child identities/order on their parent, and compare each child's own properties separately. */
332
+ function entities(project) {
333
+ const result = /* @__PURE__ */ new Map();
334
+ function add(target, properties) {
335
+ const key = JSON.stringify(target);
336
+ if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
337
+ result.set(key, {
338
+ target,
339
+ properties
340
+ });
341
+ }
342
+ const { packages, ...properties } = project;
343
+ add({ kind: "project" }, {
344
+ ...properties,
345
+ packages: packages.map((pkg) => pkg.id)
346
+ });
347
+ for (const { resources, ...pkg } of packages) {
348
+ const packageId = pkg.id;
349
+ add({
350
+ kind: "package",
351
+ selector: { packageId }
352
+ }, {
353
+ ...pkg,
354
+ resources: resources.map((resource) => resource.id)
355
+ });
356
+ for (const resource of resources) {
357
+ const resourceTarget = {
358
+ kind: "resource",
359
+ selector: {
360
+ packageId,
361
+ resourceId: resource.id
362
+ }
363
+ };
364
+ if (resource.kind !== "component") {
365
+ add(resourceTarget, resource);
366
+ continue;
367
+ }
368
+ const { component, ...resourceProperties } = resource;
369
+ add(resourceTarget, resourceProperties);
370
+ const { displayList, controllers, transitions, ...componentProperties } = component;
371
+ const selector = {
372
+ packageId,
373
+ componentResourceId: resource.id
374
+ };
375
+ add({
376
+ kind: "component",
377
+ selector
378
+ }, {
379
+ ...componentProperties,
380
+ displayList: displayList.map((node) => node.id),
381
+ controllers: controllers.map((controller) => controller.name),
382
+ transitions: transitions.map((transition) => transition.name)
383
+ });
384
+ for (const node of displayList) add({
385
+ kind: "displayNode",
386
+ selector: {
387
+ ...selector,
388
+ displayNodeId: node.id
389
+ }
390
+ }, node);
391
+ for (const controller of controllers) add({
392
+ kind: "controller",
393
+ selector: {
394
+ ...selector,
395
+ controllerName: controller.name
396
+ }
397
+ }, controller);
398
+ for (const transition of transitions) add({
399
+ kind: "transition",
400
+ selector: {
401
+ ...selector,
402
+ transitionName: transition.name
403
+ }
404
+ }, transition);
405
+ }
406
+ }
407
+ return result;
408
+ }
409
+ function equal(left, right, depth = 0) {
410
+ if (left === right) return true;
411
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
412
+ 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]);
413
+ if (depth > 128) throw new Error("Preview property comparison exceeds the supported nesting depth.");
414
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
415
+ if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
416
+ const a = left, b = right;
417
+ const keys = Object.keys(a);
418
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
419
+ }
420
+ var PreviewBudgetError = class extends Error {};
421
+ /** No host filesystem, cache, event or session mutation is involved in the projection. */
422
+ async function previewTransactionImpact(session, project, fileSystemAvailable) {
423
+ const impact = {
424
+ entities: [],
425
+ files: []
426
+ };
427
+ const before = entities(session.project), after = entities(project);
428
+ let entries = 0, bytes = 0;
429
+ const encoder = new TextEncoder();
430
+ function count(value) {
431
+ bytes += encoder.encode(JSON.stringify(value)).byteLength;
432
+ 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.");
433
+ }
434
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
435
+ const previous = before.get(key), next = after.get(key);
436
+ const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])].filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
437
+ if (!fields.length && previous && next) continue;
438
+ const change = {
439
+ target: (next ?? previous).target,
440
+ change: !previous ? "added" : !next ? "removed" : "updated",
441
+ fields
442
+ };
443
+ count(change);
444
+ impact.entities.push(change);
445
+ }
446
+ const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, "/").split("/").at(-1) : "Project.fairy";
447
+ const [previousFiles, nextFiles] = await Promise.all([captureProject(materializeUamProject(session.project, { validate: false }), fairyFileName), captureProject(materializeUamProject(project), fairyFileName)]);
448
+ for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
449
+ const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
450
+ if (equal(previous, next)) continue;
451
+ const change = {
452
+ path,
453
+ kind: "file",
454
+ change: previous === void 0 ? "added" : next === void 0 ? "removed" : "updated"
455
+ };
456
+ count(change);
457
+ impact.files.push(change);
458
+ }
459
+ for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
460
+ if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
461
+ const change = {
462
+ path,
463
+ kind: "directory",
464
+ change: nextFiles.directories.has(path) ? "added" : "removed"
465
+ };
466
+ count(change);
467
+ impact.files.push(change);
468
+ }
469
+ impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
470
+ const preview = {
471
+ sessionId: session.sessionId,
472
+ baseRevision: session.revision,
473
+ projectedRevision: session.revision + 1,
474
+ mode: "execute-and-discard",
475
+ impact,
476
+ persistence: {
477
+ requiredAfterApply: true,
478
+ fileSystemAvailable,
479
+ uamFidelity: session.uamFidelity,
480
+ writeVerified: false,
481
+ nextAction: session.uamFidelity === "unsupported" || !fileSystemAvailable ? "host-action" : session.fileSystem ? "saveSession" : "materializeSession"
482
+ }
483
+ };
484
+ if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) throw new PreviewBudgetError("The complete transaction preview exceeds the response byte budget.");
485
+ return preview;
486
+ }
487
+ //#endregion
488
+ //#region src/services/authoring-service.ts
489
+ function sourceFileKey(source) {
490
+ return [
491
+ source.branch,
492
+ source.packageName,
493
+ source.path,
494
+ source.fileName
495
+ ].join("\0");
496
+ }
497
+ function resourceFolderKey(folder) {
498
+ return [
499
+ folder.branch,
500
+ folder.packageName,
501
+ folder.path
502
+ ].join("\0");
503
+ }
504
+ function branchDirectoryKey(directory) {
505
+ return [directory.branch, directory.packageName ?? ""].join("\0");
506
+ }
507
+ function recordStaleProjectFiles(session, previousProject, nextProject) {
508
+ if (!session.fileSystem) return;
509
+ for (const source of staleSourceFiles(previousProject, nextProject)) session.pendingStaleSourceFiles.set(sourceFileKey(source), source);
510
+ for (const source of staleSourceFiles(nextProject, previousProject)) session.pendingStaleSourceFiles.delete(sourceFileKey(source));
511
+ for (const folder of staleResourceFolders(previousProject, nextProject)) session.pendingStaleResourceFolders.set(resourceFolderKey(folder), folder);
512
+ for (const folder of staleResourceFolders(nextProject, previousProject)) session.pendingStaleResourceFolders.delete(resourceFolderKey(folder));
513
+ for (const directory of staleBranchDirectories(previousProject, nextProject)) session.pendingStaleBranchDirectories.set(branchDirectoryKey(directory), directory);
514
+ for (const directory of staleBranchDirectories(nextProject, previousProject)) session.pendingStaleBranchDirectories.delete(branchDirectoryKey(directory));
515
+ }
516
+ function toBackendDiagnostics(error) {
517
+ return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({
518
+ ...diagnostic,
519
+ owner: "core.transaction"
520
+ })) : [{
521
+ code: error.code,
522
+ owner: "core.transaction",
523
+ message: error.message,
524
+ severity: "error",
525
+ operationKind: error.operationKind,
526
+ opIndex: error.opIndex,
527
+ opId: error.opId
528
+ }];
529
+ }
530
+ function detachSharedByteViews(value, seen = /* @__PURE__ */ new WeakSet()) {
531
+ if (!value || typeof value !== "object" || seen.has(value)) return;
532
+ seen.add(value);
533
+ for (const [key, child] of Object.entries(value)) {
534
+ if (child instanceof Uint8Array) {
535
+ if (typeof SharedArrayBuffer !== "undefined" && child.buffer instanceof SharedArrayBuffer) value[key] = new Uint8Array(child);
536
+ continue;
537
+ }
538
+ detachSharedByteViews(child, seen);
539
+ }
540
+ }
541
+ var AuthoringService = class {
542
+ constructor(context, cacheService, eventService, sessionOperations) {
543
+ this.context = context;
544
+ this.cacheService = cacheService;
545
+ this.eventService = eventService;
546
+ this.sessionOperations = sessionOperations;
547
+ }
548
+ async preflightTransaction(input) {
549
+ const queuedInput = structuredClone(input);
550
+ detachSharedByteViews(queuedInput);
551
+ return this.sessionOperations.run(queuedInput.sessionId, async () => {
552
+ const startedAt = Date.now();
553
+ const session = this.context.sessions.get(queuedInput.sessionId);
554
+ if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
555
+ const meta = {
556
+ sessionId: session.sessionId,
557
+ revision: session.revision
558
+ };
559
+ if (queuedInput.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, queuedInput.expectedRevision), toSessionSnapshot(session, this.context.capabilities), meta);
560
+ const project = structuredClone(session.project);
561
+ detachSharedByteViews(project);
562
+ const result = await applyUamTransactionAppAsync({
563
+ project,
564
+ operations: queuedInput.operations
565
+ });
566
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
567
+ if (!result.ok) return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
568
+ ...meta,
569
+ diagnostics: toBackendDiagnostics(result.error)
570
+ });
571
+ try {
572
+ const preview = await previewTransactionImpact({
573
+ ...session,
574
+ project
575
+ }, result.project, Boolean(session.fileSystem));
576
+ if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
577
+ return success("authoring", startedAt, preview, meta);
578
+ } catch (error) {
579
+ return failure("authoring", startedAt, {
580
+ code: "transaction_preview_failed",
581
+ sessionId: session.sessionId,
582
+ reason: error instanceof PreviewBudgetError ? "response_budget_exceeded" : "projection_failed",
583
+ message: error instanceof Error ? error.message : String(error)
584
+ }, toSessionSnapshot(session, this.context.capabilities), meta);
585
+ }
586
+ });
587
+ }
588
+ async applyTransaction(input) {
589
+ const queuedInput = structuredClone(input);
590
+ detachSharedByteViews(queuedInput);
591
+ return this.sessionOperations.run(queuedInput.sessionId, () => this.applyTransactionExclusive(queuedInput));
592
+ }
593
+ async applyTransactionExclusive(input) {
594
+ const startedAt = Date.now();
595
+ const session = this.context.sessions.get(input.sessionId);
596
+ if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
597
+ if (input.expectedRevision !== session.revision) {
598
+ this.eventService.emit({
599
+ kind: "transaction.rejected",
600
+ sessionId: session.sessionId,
601
+ canonicalPathKey: session.canonicalPathKey,
602
+ revision: session.revision
603
+ });
604
+ return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
605
+ sessionId: session.sessionId,
606
+ revision: session.revision
607
+ });
608
+ }
609
+ const result = await applyUamTransactionAppAsync({
610
+ project: session.project,
611
+ operations: input.operations
612
+ });
613
+ if (this.context.sessions.get(input.sessionId) !== session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
614
+ if (result.ok === false) {
615
+ const diagnostics = toBackendDiagnostics(result.error);
616
+ this.eventService.emit({
617
+ kind: "transaction.rejected",
618
+ sessionId: session.sessionId,
619
+ canonicalPathKey: session.canonicalPathKey,
620
+ revision: session.revision,
621
+ diagnostics
622
+ });
623
+ return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
624
+ sessionId: session.sessionId,
625
+ revision: session.revision,
626
+ diagnostics
627
+ });
628
+ }
629
+ recordStaleProjectFiles(session, session.project, result.project);
630
+ session.project = result.project;
631
+ session.revision += 1;
632
+ session.dirty = true;
633
+ const cacheEntry = this.cacheService.invalidateSession(session);
634
+ this.eventService.emit({
635
+ kind: "transaction.applied",
636
+ sessionId: session.sessionId,
637
+ canonicalPathKey: session.canonicalPathKey,
638
+ revision: session.revision
639
+ });
640
+ this.eventService.emit({
641
+ kind: "cache.invalidated",
642
+ sessionId: session.sessionId,
643
+ canonicalPathKey: session.canonicalPathKey,
644
+ revision: session.revision,
645
+ cacheRevision: cacheEntry.revision
646
+ });
647
+ return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
648
+ sessionId: session.sessionId,
649
+ revision: session.revision
650
+ });
651
+ }
652
+ };
653
+ //#endregion
654
+ //#region src/services/session-project-writer.ts
655
+ function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
656
+ const contained = async (targetPath, operation) => {
657
+ await assertProjectPathContained(fileSystem, projectRoot, targetPath);
658
+ return operation();
659
+ };
660
+ async function trackWrite(targetPath, write) {
661
+ try {
662
+ const result = await contained(targetPath, write);
663
+ writtenPaths.push(targetPath);
664
+ return result;
665
+ } catch (error) {
666
+ failedPaths.push(targetPath);
667
+ throw error;
668
+ }
669
+ }
670
+ return {
671
+ resolvePath: (path) => contained(path, () => fileSystem.resolvePath(path)),
672
+ readFile: (path) => contained(path, () => fileSystem.readFile(path)),
673
+ readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
674
+ writeFile: (path, content) => trackWrite(path, async () => {
675
+ await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
676
+ await fileSystem.writeFile(path, content);
677
+ }),
678
+ writeFileRaw: (path, data) => trackWrite(path, async () => {
679
+ await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
680
+ await fileSystem.writeFileRaw(path, data);
681
+ }),
682
+ mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
683
+ readdir: (path) => contained(path, () => fileSystem.readdir(path)),
684
+ async exists(path) {
685
+ await assertProjectPathContained(fileSystem, projectRoot, path);
686
+ try {
687
+ await fileSystem.stat(path);
688
+ return true;
689
+ } catch {
690
+ return false;
691
+ }
692
+ },
693
+ join: (...paths) => fileSystem.join(...paths),
694
+ dirname: (path) => fileSystem.dirname(path),
695
+ unlink: (path) => trackWrite(path, () => fileSystem.unlink(path)),
696
+ rmdir: (path) => trackWrite(path, () => fileSystem.rmdir(path))
697
+ };
698
+ }
699
+ async function writeSessionProject(input) {
700
+ const projectRoot = input.fileSystem.dirname(input.fairyPath);
701
+ const write = async (fileSystem) => {
702
+ await new ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
703
+ staleSourceFiles: input.staleSourceFiles,
704
+ staleResourceFolders: input.staleResourceFolders,
705
+ staleBranchDirectories: input.staleBranchDirectories
706
+ });
707
+ };
708
+ if (!input.fileSystem.runProjectWriteTransaction) {
709
+ await write(input.fileSystem);
710
+ return [];
711
+ }
712
+ try {
713
+ return ((await input.fileSystem.runProjectWriteTransaction(projectRoot, write)).retainedBackupPaths ?? []).map((backupPath) => ({
714
+ code: "save_backup_retained",
715
+ message: `The project was saved, but the previous project copy could not be removed: ${backupPath}`
716
+ }));
717
+ } catch (error) {
718
+ if (ProjectWriteTransactionError.is(error) && !error.diskMayBePartiallyUpdated) input.writtenPaths.length = 0;
719
+ throw error;
720
+ }
721
+ }
722
+ //#endregion
723
+ //#region src/services/persistence-service.ts
724
+ function createCapabilityUnavailableError$1(message) {
725
+ return {
726
+ code: "capability_unavailable",
727
+ message,
728
+ capability: "fileSystem",
729
+ requiredAdapter: "BackendFileSystem"
730
+ };
731
+ }
732
+ function createUamFidelityUnsupportedError(session) {
733
+ return {
734
+ code: "uam_fidelity_unsupported",
735
+ message: "The source project contains formal properties that the current UAM cannot preserve.",
736
+ sessionId: session.sessionId,
737
+ canonicalPathKey: session.canonicalPathKey
738
+ };
739
+ }
740
+ function validationDiagnostics(sessionProject) {
741
+ return validateUamProject(sessionProject).map((issue) => ({
742
+ code: "materialize_validation_failed",
743
+ message: issue.message,
744
+ severity: "error",
745
+ path: issue.path,
746
+ operationKind: "materializeSession"
747
+ }));
748
+ }
749
+ function toMaterializeSnapshot(session, capabilities, input) {
750
+ return {
751
+ ...toSessionSnapshot(session, capabilities),
752
+ mode: "fullProject",
753
+ reason: input.reason,
754
+ materializeRevision: session.revision,
755
+ saveRevision: session.lastSavedRevision,
756
+ writtenPaths: [...input.writtenPaths],
757
+ skippedPaths: [...input.skippedPaths],
758
+ diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic }))
759
+ };
760
+ }
761
+ function storageCanonicalTarget(input) {
762
+ const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || ".");
763
+ return {
764
+ fileSystem: input.fileSystem,
765
+ fairyPath: input.fairyPath,
766
+ canonicalProjectPath,
767
+ canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath, input.fileSystem.caseSensitivePaths)
768
+ };
769
+ }
770
+ var PersistenceService = class {
771
+ constructor(context, cacheService, eventService, sessionOperations) {
772
+ this.context = context;
773
+ this.cacheService = cacheService;
774
+ this.eventService = eventService;
775
+ this.sessionOperations = sessionOperations;
776
+ }
777
+ async saveSession(input) {
778
+ if (input.force === true || input.mode === "materializeCleanSession") return this.materializeSession({
779
+ sessionId: input.sessionId,
780
+ expectedRevision: input.expectedRevision,
781
+ targetPath: input.targetPath,
782
+ fileSystem: input.fileSystem,
783
+ mode: "fullProject",
784
+ reason: "force_save"
785
+ });
786
+ const captured = { ...input };
787
+ return this.sessionOperations.run(captured.sessionId, () => this.saveSessionExclusive(captured));
788
+ }
789
+ finishSuccessfulSave(session) {
790
+ session.lastSavedRevision = session.revision;
791
+ session.dirty = false;
792
+ const cacheEntry = this.cacheService.refreshSession(session);
793
+ this.eventService.emit({
794
+ kind: "save.completed",
795
+ sessionId: session.sessionId,
796
+ canonicalPathKey: session.canonicalPathKey,
797
+ revision: session.revision
798
+ });
799
+ this.eventService.emit({
800
+ kind: "cache.updated",
801
+ sessionId: session.sessionId,
802
+ canonicalPathKey: session.canonicalPathKey,
803
+ revision: session.revision,
804
+ cacheRevision: cacheEntry.revision
805
+ });
806
+ }
807
+ async saveSessionExclusive(input) {
808
+ const startedAt = Date.now();
809
+ const session = this.context.sessions.get(input.sessionId);
810
+ if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
811
+ const fileSystem = session.fileSystem ?? input.fileSystem;
812
+ if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("saveSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
813
+ sessionId: session.sessionId,
814
+ revision: session.revision
815
+ });
816
+ if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
817
+ sessionId: session.sessionId,
818
+ revision: session.revision
819
+ });
820
+ const targetViolation = await validateSaveTarget(fileSystem, session.fairyPath, input.targetPath);
821
+ if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
822
+ sessionId: session.sessionId,
823
+ revision: session.revision
824
+ });
825
+ if (!session.dirty) return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
826
+ sessionId: session.sessionId,
827
+ revision: session.revision
828
+ });
829
+ if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
830
+ sessionId: session.sessionId,
831
+ revision: session.revision
832
+ });
833
+ const committedPaths = [];
834
+ const failedPaths = [];
835
+ this.eventService.emit({
836
+ kind: "save.started",
837
+ sessionId: session.sessionId,
838
+ canonicalPathKey: session.canonicalPathKey,
839
+ revision: session.revision
840
+ });
841
+ try {
842
+ const warnings = await writeSessionProject({
843
+ fileSystem,
844
+ document: materializeUamProject(session.project),
845
+ fairyPath: session.fairyPath,
846
+ staleSourceFiles: [...session.pendingStaleSourceFiles.values()],
847
+ staleResourceFolders: [...session.pendingStaleResourceFolders.values()],
848
+ staleBranchDirectories: [...session.pendingStaleBranchDirectories.values()],
849
+ writtenPaths: committedPaths,
850
+ failedPaths
851
+ });
852
+ session.fileSystem ??= fileSystem;
853
+ session.pendingStaleSourceFiles.clear();
854
+ session.pendingStaleResourceFolders.clear();
855
+ session.pendingStaleBranchDirectories.clear();
856
+ commitUamProjectSourcePaths(session.project);
857
+ this.finishSuccessfulSave(session);
858
+ return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
859
+ sessionId: session.sessionId,
860
+ revision: session.revision,
861
+ warnings
862
+ });
863
+ } catch (error) {
864
+ this.cacheService.invalidateSession(session);
865
+ this.eventService.emit({
866
+ kind: "save.failed",
867
+ sessionId: session.sessionId,
868
+ canonicalPathKey: session.canonicalPathKey,
869
+ revision: session.revision
870
+ });
871
+ return failure("authoring", startedAt, {
872
+ code: "save_partial_failure",
873
+ message: error instanceof Error ? error.message : String(error),
874
+ sessionId: session.sessionId,
875
+ canonicalPathKey: session.canonicalPathKey,
876
+ attemptedRevision: session.revision,
877
+ lastSavedRevision: session.lastSavedRevision,
878
+ committedPaths,
879
+ failedPaths,
880
+ diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
881
+ ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
882
+ }, toSessionSnapshot(session, this.context.capabilities), {
883
+ sessionId: session.sessionId,
884
+ revision: session.revision
885
+ });
886
+ }
887
+ }
888
+ async materializeSession(input) {
889
+ const captured = {
890
+ ...input,
891
+ storage: input.storage && { ...input.storage }
892
+ };
893
+ return this.sessionOperations.run(captured.sessionId, () => this.materializeSessionExclusive(captured));
894
+ }
895
+ async materializeSessionExclusive(input) {
896
+ const startedAt = Date.now();
897
+ const session = this.context.sessions.get(input.sessionId);
898
+ if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
899
+ if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
900
+ sessionId: session.sessionId,
901
+ revision: session.revision
902
+ });
903
+ const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
904
+ const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
905
+ if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("materializeSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
906
+ sessionId: session.sessionId,
907
+ revision: session.revision
908
+ });
909
+ const fairyPath = storageTarget?.fairyPath ?? session.fairyPath;
910
+ if (session.lockHeld && (fileSystem !== session.fileSystem || fairyPath !== session.fairyPath || storageTarget && (storageTarget.canonicalPathKey !== session.canonicalPathKey || storageTarget.canonicalProjectPath !== session.canonicalProjectPath))) return failure("authoring", startedAt, {
911
+ code: "path_policy_violation",
912
+ message: "A locked file-backed session must keep its opened storage binding.",
913
+ policy: "save_target",
914
+ attemptedPath: fairyPath,
915
+ allowedPath: session.fairyPath
916
+ }, toSessionSnapshot(session, this.context.capabilities), {
917
+ sessionId: session.sessionId,
918
+ revision: session.revision
919
+ });
920
+ const targetViolation = await validateSaveTarget(fileSystem, fairyPath, input.targetPath);
921
+ if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
922
+ sessionId: session.sessionId,
923
+ revision: session.revision
924
+ });
925
+ if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
926
+ sessionId: session.sessionId,
927
+ revision: session.revision
928
+ });
929
+ const diagnostics = validationDiagnostics(session.project);
930
+ if (diagnostics.length > 0) return failure("authoring", startedAt, {
931
+ code: "materialize_validation_failed",
932
+ message: `UAM materialize validation failed with ${diagnostics.length} issue(s).`,
933
+ sessionId: session.sessionId,
934
+ canonicalPathKey: session.canonicalPathKey,
935
+ issueCount: diagnostics.length,
936
+ diagnostics
937
+ }, toSessionSnapshot(session, this.context.capabilities), {
938
+ sessionId: session.sessionId,
939
+ revision: session.revision,
940
+ diagnostics
941
+ });
942
+ let document;
943
+ try {
944
+ document = materializeUamProject(session.project);
945
+ } catch (error) {
946
+ const diagnosticsFromError = [{
947
+ code: "materialize_validation_failed",
948
+ message: error instanceof Error ? error.message : String(error),
949
+ severity: "error",
950
+ operationKind: "materializeSession"
951
+ }];
952
+ return failure("authoring", startedAt, {
953
+ code: "materialize_validation_failed",
954
+ message: error instanceof Error ? error.message : String(error),
955
+ sessionId: session.sessionId,
956
+ canonicalPathKey: session.canonicalPathKey,
957
+ issueCount: diagnosticsFromError.length,
958
+ diagnostics: diagnosticsFromError
959
+ }, toSessionSnapshot(session, this.context.capabilities), {
960
+ sessionId: session.sessionId,
961
+ revision: session.revision,
962
+ diagnostics: diagnosticsFromError
963
+ });
964
+ }
965
+ const writtenPaths = [];
966
+ const failedPaths = [];
967
+ const skippedPaths = [];
968
+ const reservation = storageTarget ? this.context.sessions.reserve(session.sessionId, storageTarget) : null;
969
+ if (reservation && "code" in reservation) return failure("authoring", startedAt, reservation, toSessionSnapshot(session, this.context.capabilities), {
970
+ sessionId: session.sessionId,
971
+ revision: session.revision
972
+ });
973
+ this.eventService.emit({
974
+ kind: "save.started",
975
+ sessionId: session.sessionId,
976
+ canonicalPathKey: storageTarget?.canonicalPathKey ?? session.canonicalPathKey,
977
+ revision: session.revision
978
+ });
979
+ try {
980
+ const isSessionStorageTarget = fileSystem === session.fileSystem && fairyPath === session.fairyPath;
981
+ const warnings = await writeSessionProject({
982
+ fileSystem,
983
+ document,
984
+ fairyPath,
985
+ staleSourceFiles: isSessionStorageTarget ? [...session.pendingStaleSourceFiles.values()] : [],
986
+ staleResourceFolders: isSessionStorageTarget ? [...session.pendingStaleResourceFolders.values()] : [],
987
+ staleBranchDirectories: isSessionStorageTarget ? [...session.pendingStaleBranchDirectories.values()] : [],
988
+ writtenPaths,
989
+ failedPaths
990
+ });
991
+ if (isSessionStorageTarget) {
992
+ session.pendingStaleSourceFiles.clear();
993
+ session.pendingStaleResourceFolders.clear();
994
+ session.pendingStaleBranchDirectories.clear();
995
+ }
996
+ if (storageTarget && !isSessionStorageTarget) {
997
+ session.pendingStaleSourceFiles.clear();
998
+ session.pendingStaleResourceFolders.clear();
999
+ session.pendingStaleBranchDirectories.clear();
1000
+ }
1001
+ if (isSessionStorageTarget || storageTarget) commitUamProjectSourcePaths(session.project);
1002
+ reservation?.commit(session);
1003
+ this.finishSuccessfulSave(session);
1004
+ return success("authoring", startedAt, toMaterializeSnapshot(session, this.context.capabilities, {
1005
+ reason: input.reason,
1006
+ writtenPaths,
1007
+ skippedPaths,
1008
+ diagnostics: []
1009
+ }), {
1010
+ sessionId: session.sessionId,
1011
+ revision: session.revision,
1012
+ warnings
1013
+ });
1014
+ } catch (error) {
1015
+ const diagnosticsFromError = [{
1016
+ code: "write_failed",
1017
+ message: error instanceof Error ? error.message : String(error),
1018
+ severity: "error",
1019
+ path: failedPaths[0],
1020
+ operationKind: "materializeSession"
1021
+ }];
1022
+ this.cacheService.invalidateSession(session);
1023
+ this.eventService.emit({
1024
+ kind: "save.failed",
1025
+ sessionId: session.sessionId,
1026
+ canonicalPathKey: session.canonicalPathKey,
1027
+ revision: session.revision,
1028
+ diagnostics: diagnosticsFromError
1029
+ });
1030
+ return failure("authoring", startedAt, {
1031
+ code: "write_failed",
1032
+ message: error instanceof Error ? error.message : String(error),
1033
+ sessionId: session.sessionId,
1034
+ canonicalPathKey: session.canonicalPathKey,
1035
+ attemptedRevision: session.revision,
1036
+ lastSavedRevision: session.lastSavedRevision,
1037
+ writtenPaths,
1038
+ failedPaths,
1039
+ skippedPaths,
1040
+ diagnostics: diagnosticsFromError,
1041
+ diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
1042
+ ...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
1043
+ }, toSessionSnapshot(session, this.context.capabilities), {
1044
+ sessionId: session.sessionId,
1045
+ revision: session.revision,
1046
+ diagnostics: diagnosticsFromError
1047
+ });
1048
+ } finally {
1049
+ reservation?.release();
1050
+ }
1051
+ }
1052
+ };
1053
+ //#endregion
1054
+ //#region src/services/cache-service.ts
1055
+ function createCacheEntry(session, valid) {
1056
+ return {
1057
+ canonicalPathKey: session.canonicalPathKey,
1058
+ sessionId: session.sessionId,
1059
+ revision: session.revision,
1060
+ lastSavedRevision: session.lastSavedRevision,
1061
+ dirty: session.dirty,
1062
+ valid,
1063
+ indexedAt: (/* @__PURE__ */ new Date()).toISOString(),
1064
+ summary: {
1065
+ packageCount: session.project.packages.length,
1066
+ resourceCount: session.project.packages.reduce((total, pkg) => total + pkg.resources.length, 0),
1067
+ diagnostics: []
1068
+ }
1069
+ };
1070
+ }
1071
+ var CacheService = class {
1072
+ cacheBySession = /* @__PURE__ */ new Map();
1073
+ constructor(getSession, events) {
1074
+ this.getSession = getSession;
1075
+ this.events = events;
1076
+ }
1077
+ getCacheSnapshot(input) {
1078
+ const startedAt = Date.now();
1079
+ const session = this.getSession(input.sessionId);
1080
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1081
+ const entry = this.cacheBySession.get(input.sessionId);
1082
+ return success("read", startedAt, {
1083
+ cacheRevision: entry?.revision ?? session.revision,
1084
+ entries: entry ? [structuredClone(entry)] : []
1085
+ }, {
1086
+ sessionId: session.sessionId,
1087
+ revision: session.revision
1088
+ });
1089
+ }
1090
+ refreshCache(input) {
1091
+ const startedAt = Date.now();
1092
+ const session = this.getSession(input.sessionId);
1093
+ if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1094
+ const entry = this.refreshSession(session);
1095
+ this.events.emit({
1096
+ kind: "cache.updated",
1097
+ sessionId: session.sessionId,
1098
+ canonicalPathKey: session.canonicalPathKey,
1099
+ revision: session.revision,
1100
+ cacheRevision: entry.revision,
1101
+ payload: { reason: input.reason ?? "manual" }
1102
+ });
1103
+ return success("runtime", startedAt, {
1104
+ cacheRevision: entry.revision,
1105
+ entries: [structuredClone(entry)]
1106
+ }, {
1107
+ sessionId: session.sessionId,
1108
+ revision: session.revision
1109
+ });
1110
+ }
1111
+ refreshSession(session) {
1112
+ const entry = createCacheEntry(session, true);
1113
+ this.cacheBySession.set(session.sessionId, entry);
1114
+ return entry;
1115
+ }
1116
+ invalidateSession(session) {
1117
+ const entry = createCacheEntry(session, false);
1118
+ this.cacheBySession.set(session.sessionId, entry);
1119
+ return entry;
1120
+ }
1121
+ removeSession(sessionId) {
1122
+ this.cacheBySession.delete(sessionId);
1123
+ }
1124
+ };
1125
+ //#endregion
1126
+ //#region src/services/session-registry.ts
1127
+ /** Owns live sessions and path claims, including claims made before asynchronous I/O. */
1128
+ var SessionRegistry = class {
1129
+ sessions = /* @__PURE__ */ new Map();
1130
+ paths = /* @__PURE__ */ new Map();
1131
+ opening = /* @__PURE__ */ new Set();
1132
+ idleTimers = /* @__PURE__ */ new Map();
1133
+ activity = /* @__PURE__ */ new Map();
1134
+ activitySequence = 0;
1135
+ constructor(maxSessions, idleTimeoutMs = 0, onIdle) {
1136
+ this.maxSessions = maxSessions;
1137
+ this.idleTimeoutMs = idleTimeoutMs;
1138
+ this.onIdle = onIdle;
1139
+ }
1140
+ isIdle(sessionId, activity) {
1141
+ return this.activity.get(sessionId) === activity;
1142
+ }
1143
+ peek(sessionId) {
1144
+ return this.sessions.get(sessionId);
1145
+ }
1146
+ touch(sessionId) {
1147
+ if (!this.sessions.has(sessionId) || !this.idleTimeoutMs) return;
1148
+ clearTimeout(this.idleTimers.get(sessionId));
1149
+ const activity = ++this.activitySequence;
1150
+ this.activity.set(sessionId, activity);
1151
+ const timer = setTimeout(() => {
1152
+ this.idleTimers.delete(sessionId);
1153
+ this.onIdle?.(sessionId, activity).catch(() => this.touch(sessionId));
1154
+ }, this.idleTimeoutMs);
1155
+ if (typeof timer === "object" && "unref" in timer) timer.unref();
1156
+ this.idleTimers.set(sessionId, timer);
1157
+ }
1158
+ /** Check immediately before reserve, in the same synchronous step, so concurrent opens cannot overshoot. */
1159
+ checkCapacity() {
1160
+ if (this.sessions.size + this.opening.size < this.maxSessions) return null;
1161
+ return {
1162
+ code: "session_limit_exceeded",
1163
+ message: `This backend runtime already has ${this.maxSessions} open sessions. Close sessions that are no longer needed.`,
1164
+ maxSessions: this.maxSessions
1165
+ };
1166
+ }
1167
+ get(sessionId) {
1168
+ this.touch(sessionId);
1169
+ return this.sessions.get(sessionId);
1170
+ }
1171
+ has(sessionId) {
1172
+ return this.sessions.has(sessionId) || this.opening.has(sessionId);
1173
+ }
1174
+ reserve(sessionId, target) {
1175
+ const key = target.canonicalPathKey;
1176
+ const previous = this.paths.get(key);
1177
+ if (previous && previous.sessionId !== sessionId) return {
1178
+ code: "lock_conflict",
1179
+ kind: "in_process_session_exists",
1180
+ message: `Project is already open in this backend runtime: ${target.canonicalProjectPath}`,
1181
+ canonicalPathKey: key,
1182
+ holderSessionId: previous.sessionId,
1183
+ lockFilePath: target.lockFilePath
1184
+ };
1185
+ const claim = previous ?? { sessionId };
1186
+ this.paths.set(key, claim);
1187
+ if (!this.sessions.has(sessionId)) this.opening.add(sessionId);
1188
+ let committed = false;
1189
+ return {
1190
+ commit: (session) => {
1191
+ if (session.sessionId !== sessionId || this.paths.get(key) !== claim) throw new Error("Session path reservation lost.");
1192
+ if (session.canonicalPathKey !== key) this.releasePath(session.canonicalPathKey, sessionId);
1193
+ Object.assign(session, target);
1194
+ this.sessions.set(sessionId, session);
1195
+ this.touch(sessionId);
1196
+ this.opening.delete(sessionId);
1197
+ committed = true;
1198
+ },
1199
+ release: () => {
1200
+ if (committed) return;
1201
+ if (!previous && this.paths.get(key) === claim) this.paths.delete(key);
1202
+ this.opening.delete(sessionId);
1203
+ }
1204
+ };
1205
+ }
1206
+ remove(session) {
1207
+ if (this.sessions.get(session.sessionId) !== session) return;
1208
+ this.sessions.delete(session.sessionId);
1209
+ clearTimeout(this.idleTimers.get(session.sessionId));
1210
+ this.idleTimers.delete(session.sessionId);
1211
+ this.activity.delete(session.sessionId);
1212
+ this.releasePath(session.canonicalPathKey, session.sessionId);
1213
+ }
1214
+ releasePath(key, sessionId) {
1215
+ if (this.paths.get(key)?.sessionId === sessionId) this.paths.delete(key);
1216
+ }
1217
+ };
1218
+ //#endregion
1219
+ //#region src/services/session-operation-queue.ts
1220
+ /** Serializes lifecycle and authoring operations for one session, without blocking other sessions. */
1221
+ var SessionOperationQueue = class {
1222
+ operations = /* @__PURE__ */ new Map();
1223
+ isBusy(sessionId) {
1224
+ return this.operations.has(sessionId);
1225
+ }
1226
+ async run(sessionId, operation) {
1227
+ const previous = this.operations.get(sessionId) ?? Promise.resolve();
1228
+ let release = () => void 0;
1229
+ const current = new Promise((resolve) => {
1230
+ release = resolve;
1231
+ });
1232
+ const tail = previous.then(() => current);
1233
+ this.operations.set(sessionId, tail);
1234
+ await previous;
1235
+ try {
1236
+ return await operation();
1237
+ } finally {
1238
+ release();
1239
+ if (this.operations.get(sessionId) === tail) this.operations.delete(sessionId);
1240
+ }
1241
+ }
1242
+ };
1243
+ //#endregion
1244
+ //#region src/services/event-service.ts
1245
+ const DEFAULT_EVENT_RETENTION_LIMIT = 1e3;
1246
+ var EventService = class {
1247
+ eventsBySession = /* @__PURE__ */ new Map();
1248
+ sequence = 0;
1249
+ constructor(getSession) {
1250
+ this.getSession = getSession;
1251
+ }
1252
+ emit(event) {
1253
+ const emitted = {
1254
+ ...event,
1255
+ sequence: ++this.sequence,
1256
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1257
+ diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
1258
+ };
1259
+ const sessionId = event.sessionId;
1260
+ if (!sessionId) return emitted;
1261
+ const events = this.eventsBySession.get(sessionId) ?? [];
1262
+ events.push(emitted);
1263
+ while (events.length > DEFAULT_EVENT_RETENTION_LIMIT) events.shift();
1264
+ this.eventsBySession.set(sessionId, events);
1265
+ return emitted;
1266
+ }
1267
+ getEvents(input) {
1268
+ const startedAt = Date.now();
1269
+ const session = this.getSession(input.sessionId);
1270
+ if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1271
+ const events = this.eventsBySession.get(input.sessionId) ?? [];
1272
+ const oldestSequence = events[0]?.sequence ?? (events.length === 0 ? 1 : 0);
1273
+ const currentSequence = events.at(-1)?.sequence ?? 0;
1274
+ const after = input.after === void 0 ? 0 : Number(input.after);
1275
+ if (!Number.isInteger(after) || after < 0) return failure("runtime", startedAt, {
1276
+ code: "event_cursor_invalid",
1277
+ message: `Invalid event cursor: ${input.after}`,
1278
+ sessionId: input.sessionId,
1279
+ after: String(input.after)
1280
+ });
1281
+ if (events.length > 0 && after !== 0 && after < oldestSequence - 1) return failure("runtime", startedAt, {
1282
+ code: "event_cursor_invalid",
1283
+ message: `Event cursor has expired: ${after}`,
1284
+ sessionId: input.sessionId,
1285
+ after: String(input.after)
1286
+ });
1287
+ if (after > currentSequence) return failure("runtime", startedAt, {
1288
+ code: "event_cursor_invalid",
1289
+ message: `Unknown event cursor: ${after}`,
1290
+ sessionId: input.sessionId,
1291
+ after: String(input.after)
1292
+ });
1293
+ const filtered = events.filter((event) => event.sequence > after);
1294
+ const limit = input.limit === void 0 ? filtered.length : Math.max(0, input.limit);
1295
+ return success("runtime", startedAt, {
1296
+ events: filtered.slice(0, limit).map((event) => structuredClone(event)),
1297
+ oldestSequence,
1298
+ currentSequence,
1299
+ cursorExpired: false
1300
+ }, {
1301
+ sessionId: session.sessionId,
1302
+ revision: session.revision
1303
+ });
1304
+ }
1305
+ removeSession(sessionId) {
1306
+ this.eventsBySession.delete(sessionId);
1307
+ }
1308
+ };
1309
+ //#endregion
1310
+ //#region src/services/read-service.ts
1311
+ /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
1312
+ function queryResponseProblem(value, limits = BACKEND_ENTITY_QUERY_LIMITS) {
1313
+ const pending = [{
1314
+ value,
1315
+ depth: 0
1316
+ }];
1317
+ let nodes = 0;
1318
+ let stringUnits = 0;
1319
+ while (pending.length) {
1320
+ const { value, depth } = pending.pop();
1321
+ if (++nodes > limits.maxNodes || depth > limits.maxDepth) return "response_budget_exceeded";
1322
+ if (typeof value === "string" && (stringUnits += value.length) > limits.maxBytes) return "response_budget_exceeded";
1323
+ if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") continue;
1324
+ if (typeof value === "number") {
1325
+ if (!Number.isFinite(value)) return "non_json_value";
1326
+ continue;
1327
+ }
1328
+ if (typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return "non_json_value";
1329
+ if (Array.isArray(value) && value.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
1330
+ const entries = Object.entries(value);
1331
+ if (entries.length + pending.length + nodes > limits.maxNodes) return "response_budget_exceeded";
1332
+ for (const [key, child] of entries) {
1333
+ if (!Array.isArray(value) && (stringUnits += key.length) > limits.maxBytes) return "response_budget_exceeded";
1334
+ pending.push({
1335
+ value: child,
1336
+ depth: depth + 1
1337
+ });
1338
+ }
1339
+ }
1340
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limits.maxBytes) return "response_budget_exceeded";
1341
+ }
1342
+ function readFailure(startedAt, sessionId, reason, revision) {
1343
+ return failure("read", startedAt, {
1344
+ code: "session_read_failed",
1345
+ sessionId,
1346
+ reason,
1347
+ message: `Session read failed: ${reason}.`
1348
+ }, void 0, {
1349
+ sessionId,
1350
+ revision
1351
+ });
1352
+ }
1353
+ function toProjectOutline(session) {
1354
+ const project = session.project;
1355
+ return {
1356
+ sessionId: session.sessionId,
1357
+ revision: session.revision,
1358
+ projectId: project.projectId,
1359
+ projectType: project.projectType,
1360
+ version: project.version,
1361
+ branches: [...project.branches],
1362
+ packages: project.packages.map((pkg) => ({
1363
+ id: pkg.id,
1364
+ name: pkg.name,
1365
+ branchNames: [...pkg.branchNames],
1366
+ folders: pkg.folders.map((folder) => ({
1367
+ branch: folder.branch,
1368
+ path: folder.path
1369
+ })),
1370
+ resources: pkg.resources.map((resource) => ({
1371
+ id: resource.id,
1372
+ name: resource.name,
1373
+ path: resource.path,
1374
+ kind: resource.kind,
1375
+ branch: resource.branch,
1376
+ ...resource.kind === "component" ? { component: {
1377
+ displayList: resource.component.displayList.map((node) => ({
1378
+ id: node.id,
1379
+ name: node.name,
1380
+ kind: node.kind
1381
+ })),
1382
+ controllers: resource.component.controllers.map((controller) => ({
1383
+ name: controller.name,
1384
+ pages: controller.pages.map((page) => ({
1385
+ id: page.id,
1386
+ name: page.name
1387
+ }))
1388
+ })),
1389
+ transitions: resource.component.transitions.map((transition) => ({ name: transition.name }))
1390
+ } } : {}
1391
+ }))
1392
+ }))
1393
+ };
1394
+ }
1395
+ var ReadService = class {
1396
+ constructor(getSessionState, capabilities) {
1397
+ this.getSessionState = getSessionState;
1398
+ this.capabilities = capabilities;
1399
+ }
1400
+ getCapabilities() {
1401
+ return success("read", Date.now(), cloneReadData(this.capabilities));
1402
+ }
1403
+ getSession(input) {
1404
+ const startedAt = Date.now();
1405
+ const session = this.getSessionState(input.sessionId);
1406
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1407
+ return success("read", startedAt, toSessionSnapshot(session, this.capabilities), {
1408
+ sessionId: session.sessionId,
1409
+ revision: session.revision
1410
+ });
1411
+ }
1412
+ getProjectOutline(input) {
1413
+ const startedAt = Date.now();
1414
+ const session = this.getSessionState(input.sessionId);
1415
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1416
+ return success("read", startedAt, toProjectOutline(session), {
1417
+ sessionId: session.sessionId,
1418
+ revision: session.revision
1419
+ });
1420
+ }
1421
+ queryEntity(input) {
1422
+ const startedAt = Date.now();
1423
+ const session = this.getSessionState(input.sessionId);
1424
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1425
+ const meta = {
1426
+ sessionId: session.sessionId,
1427
+ revision: session.revision
1428
+ };
1429
+ const reject = (reason) => failure("read", startedAt, {
1430
+ code: "entity_query_failed",
1431
+ sessionId: session.sessionId,
1432
+ reason,
1433
+ message: `Entity query failed: ${reason}.`
1434
+ }, void 0, meta);
1435
+ const target = input.target;
1436
+ if (!target || typeof target !== "object" || Array.isArray(target) || Object.keys(target).some((key) => key !== "kind" && key !== "selector")) return reject("invalid_query");
1437
+ const respond = (entity) => {
1438
+ const data = {
1439
+ ...meta,
1440
+ target,
1441
+ entity
1442
+ };
1443
+ const problem = queryResponseProblem(data);
1444
+ return problem ? reject(problem) : success("read", startedAt, cloneReadData(data), meta);
1445
+ };
1446
+ if (target.kind === "project") {
1447
+ if (Object.hasOwn(target, "selector")) return reject("invalid_query");
1448
+ const { projectId, settings } = session.project;
1449
+ return respond({
1450
+ kind: "project",
1451
+ properties: {
1452
+ projectId,
1453
+ settings
1454
+ }
1455
+ });
1456
+ }
1457
+ const keys = target.kind === "package" ? ["packageId"] : target.kind === "resource" ? ["packageId", "resourceId"] : target.kind === "component" ? ["packageId", "componentResourceId"] : target.kind === "displayNode" ? [
1458
+ "packageId",
1459
+ "componentResourceId",
1460
+ "displayNodeId"
1461
+ ] : target.kind === "controller" ? [
1462
+ "packageId",
1463
+ "componentResourceId",
1464
+ "controllerName"
1465
+ ] : target.kind === "transition" ? [
1466
+ "packageId",
1467
+ "componentResourceId",
1468
+ "transitionName"
1469
+ ] : [];
1470
+ const selector = target.selector;
1471
+ 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");
1472
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
1473
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
1474
+ if (target.kind === "package") {
1475
+ const { id, name, compressPNG, jpegQuality, publish } = packages[0];
1476
+ return respond({
1477
+ kind: "package",
1478
+ properties: {
1479
+ id,
1480
+ name,
1481
+ settings: {
1482
+ compressPNG,
1483
+ jpegQuality,
1484
+ publish
1485
+ }
1486
+ }
1487
+ });
1488
+ }
1489
+ const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === "resource" ? selector.resourceId : selector.componentResourceId));
1490
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
1491
+ const resource = resources[0];
1492
+ let entity;
1493
+ if (target.kind === "resource") {
1494
+ const record = resource;
1495
+ entity = {
1496
+ kind: "resource",
1497
+ properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS.filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]]))
1498
+ };
1499
+ } else {
1500
+ if (resource.kind !== "component") return reject("not_found");
1501
+ if (target.kind === "component") {
1502
+ const { size, properties, customData } = resource.component;
1503
+ entity = {
1504
+ kind: "component",
1505
+ properties: {
1506
+ size,
1507
+ properties,
1508
+ customData
1509
+ }
1510
+ };
1511
+ } else if (target.kind === "controller") {
1512
+ const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
1513
+ if (controllers.length !== 1) return reject(controllers.length ? "ambiguous" : "not_found");
1514
+ entity = {
1515
+ kind: "controller",
1516
+ properties: controllers[0]
1517
+ };
1518
+ } else if (target.kind === "transition") {
1519
+ const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
1520
+ if (transitions.length !== 1) return reject(transitions.length ? "ambiguous" : "not_found");
1521
+ entity = {
1522
+ kind: "transition",
1523
+ properties: transitions[0]
1524
+ };
1525
+ } else {
1526
+ const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
1527
+ if (nodes.length !== 1) return reject(nodes.length ? "ambiguous" : "not_found");
1528
+ entity = {
1529
+ kind: "displayNode",
1530
+ properties: nodes[0]
1531
+ };
1532
+ }
1533
+ }
1534
+ return respond(entity);
1535
+ }
1536
+ resolveReadSession(input, startedAt) {
1537
+ 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");
1538
+ const session = this.getSessionState(input.sessionId);
1539
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1540
+ const meta = {
1541
+ sessionId: session.sessionId,
1542
+ revision: session.revision
1543
+ };
1544
+ if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("read", startedAt, {
1545
+ code: "stale_read",
1546
+ sessionId: session.sessionId,
1547
+ expectedRevision: input.expectedRevision,
1548
+ actualRevision: session.revision,
1549
+ message: "The session edit revision changed. Restart the model and resource read."
1550
+ }, void 0, meta);
1551
+ return success("read", startedAt, session, meta);
1552
+ }
1553
+ readSessionState(input) {
1554
+ const startedAt = Date.now();
1555
+ const resolved = this.resolveReadSession(input, startedAt);
1556
+ if (!resolved.ok) return resolved;
1557
+ const session = resolved.data;
1558
+ const meta = {
1559
+ sessionId: session.sessionId,
1560
+ revision: session.revision
1561
+ };
1562
+ const data = {
1563
+ ...meta,
1564
+ dirty: session.dirty,
1565
+ lastSavedRevision: session.lastSavedRevision,
1566
+ uamFidelity: session.uamFidelity,
1567
+ readComplete: session.readComplete,
1568
+ readDiagnostics: session.readDiagnostics,
1569
+ project: {
1570
+ ...session.project,
1571
+ packages: session.project.packages.map((pkg) => ({
1572
+ ...pkg,
1573
+ resources: pkg.resources.map((resource) => {
1574
+ if (resource.kind === "component") return resource;
1575
+ const { sourceBytes: _sourceBytes, ...model } = resource;
1576
+ return model;
1577
+ })
1578
+ }))
1579
+ }
1580
+ };
1581
+ const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
1582
+ return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, cloneReadData(data), meta);
1583
+ }
1584
+ readResourceBytes(input) {
1585
+ const startedAt = Date.now();
1586
+ const resolved = this.resolveReadSession(input, startedAt);
1587
+ if (!resolved.ok) return resolved;
1588
+ const session = resolved.data;
1589
+ const reject = (reason) => readFailure(startedAt, session.sessionId, reason, session.revision);
1590
+ const selector = input.selector;
1591
+ 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");
1592
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
1593
+ if (packages.length !== 1) return reject(packages.length ? "ambiguous" : "not_found");
1594
+ const resources = packages[0].resources.filter((resource) => resource.id === selector.resourceId);
1595
+ if (resources.length !== 1) return reject(resources.length ? "ambiguous" : "not_found");
1596
+ const resource = resources[0];
1597
+ if (resource.kind === "component") return reject("unsupported_resource");
1598
+ if (!(resource.sourceBytes instanceof Uint8Array)) return reject("bytes_unavailable");
1599
+ if (resource.sourceBytes.byteLength > BACKEND_SESSION_READ_LIMITS.resourceBytes) return reject("response_budget_exceeded");
1600
+ const meta = {
1601
+ sessionId: session.sessionId,
1602
+ revision: session.revision
1603
+ };
1604
+ return success("read", startedAt, {
1605
+ ...meta,
1606
+ selector: { ...selector },
1607
+ sourceBytes: new Uint8Array(resource.sourceBytes)
1608
+ }, meta);
1609
+ }
1610
+ validateSession(input) {
1611
+ const startedAt = Date.now();
1612
+ const session = this.getSessionState(input.sessionId);
1613
+ if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1614
+ const report = validateProject(cloneReadData(session.project), {
1615
+ readDiagnostics: cloneReadData(session.readDiagnostics),
1616
+ complete: session.readComplete,
1617
+ validateSources: true
1618
+ });
1619
+ return success("read", startedAt, report, {
1620
+ sessionId: session.sessionId,
1621
+ revision: session.revision,
1622
+ diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({
1623
+ code,
1624
+ message,
1625
+ severity,
1626
+ path,
1627
+ owner: "core.validation"
1628
+ }))
1629
+ });
1630
+ }
1631
+ };
1632
+ //#endregion
1633
+ //#region src/services/runtime-service.ts
1634
+ function randomId() {
1635
+ return crypto.randomUUID();
1636
+ }
1637
+ function createCapabilityUnavailableError(capability) {
1638
+ const artifactCapability = capability === "artifact.publish" || capability === "artifact.restore";
1639
+ return {
1640
+ code: "capability_unavailable",
1641
+ message: artifactCapability ? `${capability} requires the Node bridge boundary exposed by @openfairygui/backend/node.` : `${capability} requires an injected BackendFileSystem adapter.`,
1642
+ capability,
1643
+ requiredAdapter: capability === "fileSystem" ? "BackendFileSystem" : void 0,
1644
+ requiredHost: artifactCapability ? "node" : void 0,
1645
+ bridgeBoundary: artifactCapability ? "external-bridge" : void 0
1646
+ };
1647
+ }
1648
+ function createProjectReaderFileSystem(fileSystem, projectRoot) {
1649
+ const contained = async (filePath, operation) => {
1650
+ await assertProjectPathContained(fileSystem, projectRoot, filePath);
1651
+ return operation();
1652
+ };
1653
+ return {
1654
+ stat: (path) => contained(path, () => fileSystem.stat(path)),
1655
+ readFile(filePath) {
1656
+ return contained(filePath, () => fileSystem.readFile(filePath));
1657
+ },
1658
+ readFileRaw(filePath) {
1659
+ return contained(filePath, () => fileSystem.readFileRaw(filePath));
1660
+ },
1661
+ writeFile(filePath, content) {
1662
+ return contained(filePath, () => fileSystem.writeFile(filePath, content));
1663
+ },
1664
+ writeFileRaw(filePath, data) {
1665
+ return contained(filePath, () => fileSystem.writeFileRaw(filePath, data));
1666
+ },
1667
+ async mkdir(dirPath) {
1668
+ await contained(dirPath, () => fileSystem.mkdir(dirPath, { recursive: true }));
1669
+ },
1670
+ readdir(dirPath) {
1671
+ return contained(dirPath, () => fileSystem.readdir(dirPath));
1672
+ },
1673
+ async exists(filePath) {
1674
+ try {
1675
+ await contained(filePath, () => fileSystem.stat(filePath));
1676
+ return true;
1677
+ } catch {
1678
+ return false;
1679
+ }
1680
+ },
1681
+ join(...paths) {
1682
+ return fileSystem.join(...paths);
1683
+ },
1684
+ dirname(filePath) {
1685
+ return fileSystem.dirname(filePath);
1686
+ }
1687
+ };
1688
+ }
1689
+ async function hasFullUamFidelity(document, project) {
1690
+ const sourceFiles = /* @__PURE__ */ new Map();
1691
+ const materializedFiles = /* @__PURE__ */ new Map();
1692
+ const sourceDirectories = /* @__PURE__ */ new Set();
1693
+ const materializedDirectories = /* @__PURE__ */ new Set();
1694
+ try {
1695
+ await Promise.all([new ProjectWriter(createCaptureFileSystem(sourceFiles, sourceDirectories)).write(document, "Project.fairy"), new ProjectWriter(createCaptureFileSystem(materializedFiles, materializedDirectories)).write(materializeUamProject(project), "Project.fairy")]);
1696
+ } catch {
1697
+ return false;
1698
+ }
1699
+ return capturedFilesEqual(sourceFiles, materializedFiles) && capturedDirectoriesEqual(sourceDirectories, materializedDirectories);
1700
+ }
1701
+ var RuntimeService = class {
1702
+ constructor(context, cacheService, eventService, sessionOperations) {
1703
+ this.context = context;
1704
+ this.cacheService = cacheService;
1705
+ this.eventService = eventService;
1706
+ this.sessionOperations = sessionOperations;
1707
+ }
1708
+ async expireIdleSession(sessionId, activity) {
1709
+ const sessions = this.context.sessions;
1710
+ if (this.sessionOperations.isBusy(sessionId)) {
1711
+ sessions.touch(sessionId);
1712
+ return;
1713
+ }
1714
+ await this.sessionOperations.run(sessionId, async () => {
1715
+ const session = sessions.peek(sessionId);
1716
+ if (!session || !sessions.isIdle(sessionId, activity)) return;
1717
+ if (session.dirty) {
1718
+ sessions.touch(sessionId);
1719
+ return;
1720
+ }
1721
+ if (!(await this.closeSession({ sessionId })).ok) sessions.touch(sessionId);
1722
+ });
1723
+ }
1724
+ async openSession(input) {
1725
+ const startedAt = Date.now();
1726
+ if (!this.context.fileSystem) return failure("runtime", startedAt, createCapabilityUnavailableError("fileSystem"));
1727
+ const fileSystem = this.context.fileSystem;
1728
+ if (this.context.allowedProjectRoots) {
1729
+ let allowed = false;
1730
+ for (const root of this.context.allowedProjectRoots) try {
1731
+ await assertProjectPathContained(fileSystem, root, input.projectPath);
1732
+ allowed = true;
1733
+ break;
1734
+ } catch (error) {
1735
+ if (error.code !== "EACCES") throw error;
1736
+ }
1737
+ if (!allowed) return failure("runtime", startedAt, {
1738
+ code: "project_root_not_allowed",
1739
+ message: "Project path is outside the configured allowed roots.",
1740
+ projectPath: input.projectPath
1741
+ });
1742
+ }
1743
+ const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
1744
+ await fileSystem.validateProjectRoot?.(canonicalProjectPath);
1745
+ const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath) ?? fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
1746
+ const sessionId = randomId();
1747
+ const limit = this.context.sessions.checkCapacity();
1748
+ if (limit) return failure("runtime", startedAt, limit);
1749
+ const reservation = this.context.sessions.reserve(sessionId, {
1750
+ canonicalPathKey,
1751
+ canonicalProjectPath,
1752
+ lockFilePath
1753
+ });
1754
+ if ("code" in reservation) return failure("runtime", startedAt, reservation);
1755
+ let sessionLock = null;
1756
+ try {
1757
+ sessionLock = await fileSystem.acquireSessionLock(lockFilePath);
1758
+ await sessionLock.writeMetadata(JSON.stringify(this.context.host?.lockMetadata?.({
1759
+ canonicalPathKey,
1760
+ canonicalProjectPath,
1761
+ lockFilePath
1762
+ }) ?? {
1763
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1764
+ canonicalPathKey
1765
+ }));
1766
+ const read = await new ProjectReader(createProjectReaderFileSystem(fileSystem, canonicalProjectPath)).readDetailed(fairyPath, { hydrateResourceBytes: true });
1767
+ if (!read.document) throw createProjectReadFailure(read.diagnostics[0]?.message);
1768
+ const document = read.document;
1769
+ const project = liftDocumentToUamProject(document);
1770
+ const session = {
1771
+ sessionId,
1772
+ fairyPath,
1773
+ canonicalProjectPath,
1774
+ canonicalPathKey,
1775
+ lockFilePath,
1776
+ sessionLock,
1777
+ fileSystem,
1778
+ project,
1779
+ readDiagnostics: read.diagnostics,
1780
+ readComplete: read.complete,
1781
+ uamFidelity: read.complete && await hasFullUamFidelity(document, project) ? "full" : "unsupported",
1782
+ revision: 0,
1783
+ lastSavedRevision: 0,
1784
+ pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
1785
+ pendingStaleResourceFolders: /* @__PURE__ */ new Map(),
1786
+ pendingStaleBranchDirectories: /* @__PURE__ */ new Map(),
1787
+ dirty: false,
1788
+ lockHeld: true,
1789
+ closed: false
1790
+ };
1791
+ reservation.commit(session);
1792
+ this.cacheService.refreshSession(session);
1793
+ this.eventService.emit({
1794
+ kind: "session.opened",
1795
+ sessionId,
1796
+ canonicalPathKey,
1797
+ revision: session.revision
1798
+ });
1799
+ return success("runtime", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1800
+ sessionId: session.sessionId,
1801
+ revision: session.revision
1802
+ });
1803
+ } catch (error) {
1804
+ if (sessionLock) await sessionLock.release().catch(() => void 0);
1805
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST") return failure("runtime", startedAt, {
1806
+ code: "lock_conflict",
1807
+ kind: "advisory_lock_conflict",
1808
+ message: `Advisory lock already exists for project: ${canonicalProjectPath}`,
1809
+ canonicalPathKey,
1810
+ lockFilePath
1811
+ });
1812
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOTSUP") return failure("runtime", startedAt, {
1813
+ ...createCapabilityUnavailableError("fileSystem"),
1814
+ message: error instanceof Error ? error.message : String(error)
1815
+ });
1816
+ throw error;
1817
+ } finally {
1818
+ reservation.release();
1819
+ }
1820
+ }
1821
+ openProjectSession(input) {
1822
+ const startedAt = Date.now();
1823
+ const sessionId = input.sessionId ?? randomId();
1824
+ if (this.context.sessions.has(sessionId)) return failure("runtime", startedAt, {
1825
+ code: "session_id_conflict",
1826
+ message: `Session id is already in use: ${sessionId}`,
1827
+ sessionId
1828
+ });
1829
+ const storage = input.storage;
1830
+ const memoryProjectPath = `memory://${sessionId}`;
1831
+ const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
1832
+ const canonicalPathKey = storage?.canonicalPathKey ?? input.canonicalPathKey ?? (storage ? normalizeComparablePath(canonicalProjectPath, storage.fileSystem.caseSensitivePaths) : canonicalProjectPath.toLowerCase());
1833
+ const project = normalizeUamProject(input.project);
1834
+ const limit = this.context.sessions.checkCapacity();
1835
+ if (limit) return failure("runtime", startedAt, limit);
1836
+ const reservation = this.context.sessions.reserve(sessionId, {
1837
+ canonicalPathKey,
1838
+ canonicalProjectPath
1839
+ });
1840
+ if ("code" in reservation) return failure("runtime", startedAt, reservation);
1841
+ const session = {
1842
+ sessionId,
1843
+ fairyPath: storage?.fairyPath ?? canonicalProjectPath,
1844
+ canonicalProjectPath,
1845
+ canonicalPathKey,
1846
+ lockFilePath: "",
1847
+ sessionLock: null,
1848
+ fileSystem: storage?.fileSystem,
1849
+ project,
1850
+ readDiagnostics: [],
1851
+ readComplete: true,
1852
+ uamFidelity: "full",
1853
+ revision: 0,
1854
+ lastSavedRevision: 0,
1855
+ pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
1856
+ pendingStaleResourceFolders: /* @__PURE__ */ new Map(),
1857
+ pendingStaleBranchDirectories: /* @__PURE__ */ new Map(),
1858
+ dirty: false,
1859
+ lockHeld: false,
1860
+ closed: false
1861
+ };
1862
+ reservation.commit(session);
1863
+ this.cacheService.refreshSession(session);
1864
+ this.eventService.emit({
1865
+ kind: "session.opened",
1866
+ sessionId,
1867
+ canonicalPathKey,
1868
+ revision: session.revision
1869
+ });
1870
+ return success("runtime", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1871
+ sessionId: session.sessionId,
1872
+ revision: session.revision
1873
+ });
1874
+ }
1875
+ async closeSession(input) {
1876
+ const startedAt = Date.now();
1877
+ const session = this.context.sessions.get(input.sessionId);
1878
+ if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1879
+ this.eventService.emit({
1880
+ kind: "session.closeRequested",
1881
+ sessionId: session.sessionId,
1882
+ canonicalPathKey: session.canonicalPathKey,
1883
+ revision: session.revision
1884
+ });
1885
+ try {
1886
+ await session.sessionLock?.release();
1887
+ } catch (error) {
1888
+ return failure("runtime", startedAt, {
1889
+ code: "session_close_failed",
1890
+ message: error instanceof Error ? error.message : String(error),
1891
+ sessionId: session.sessionId,
1892
+ lockFilePath: session.lockFilePath
1893
+ }, toSessionSnapshot(session, this.context.capabilities), {
1894
+ sessionId: session.sessionId,
1895
+ revision: session.revision
1896
+ });
1897
+ }
1898
+ session.sessionLock = null;
1899
+ session.lockHeld = false;
1900
+ session.closed = true;
1901
+ this.context.sessions.remove(session);
1902
+ this.cacheService.removeSession(session.sessionId);
1903
+ this.eventService.emit({
1904
+ kind: "session.closed",
1905
+ sessionId: session.sessionId,
1906
+ canonicalPathKey: session.canonicalPathKey,
1907
+ revision: session.revision
1908
+ });
1909
+ this.eventService.removeSession(session.sessionId);
1910
+ return success("runtime", startedAt, {
1911
+ sessionId: session.sessionId,
1912
+ closed: true
1913
+ }, {
1914
+ sessionId: session.sessionId,
1915
+ revision: session.revision
1916
+ });
1917
+ }
1918
+ };
1919
+ //#endregion
1920
+ //#region src/services/artifact-service.ts
1921
+ function createArtifactCapabilities() {
1922
+ const bridge = {
1923
+ available: false,
1924
+ requiredHost: "node",
1925
+ executionBoundary: "external-bridge",
1926
+ bridgeEntrypoint: "@openfairygui/backend/node",
1927
+ reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
1928
+ };
1929
+ return {
1930
+ publish: false,
1931
+ restore: false,
1932
+ status: "bridge-required",
1933
+ publishBridge: bridge,
1934
+ restoreBridge: bridge
1935
+ };
1936
+ }
1937
+ //#endregion
1938
+ //#region src/runtime/capabilities.ts
1939
+ const BACKEND_METHODS = [
1940
+ "getCapabilities",
1941
+ "openSession",
1942
+ "openProjectSession",
1943
+ "getSession",
1944
+ "getProjectOutline",
1945
+ "queryEntity",
1946
+ "readSessionState",
1947
+ "readResourceBytes",
1948
+ "validateSession",
1949
+ "preflightTransaction",
1950
+ "applyTransaction",
1951
+ "saveSession",
1952
+ "materializeSession",
1953
+ "closeSession",
1954
+ "getEvents",
1955
+ "getCacheSnapshot",
1956
+ "refreshCache"
1957
+ ];
1958
+ const ARTIFACT_BRIDGE_CAPABILITY = {
1959
+ available: false,
1960
+ requiredHost: "node",
1961
+ executionBoundary: "external-bridge",
1962
+ bridgeEntrypoint: "@openfairygui/backend/node",
1963
+ reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
1964
+ };
1965
+ function createCapabilities(atomicSave = false, caseSensitivePaths = false, maxSessions = 32, idleSessionTimeoutMs = 30 * 6e4) {
1966
+ return {
1967
+ contractVersion: BACKEND_CONTRACT_VERSION,
1968
+ capabilitySchemaVersion: 15,
1969
+ transactionKernelOwner: "@openfairygui/core",
1970
+ appSeamOwner: "@openfairygui/functions",
1971
+ runtimeOwner: "@openfairygui/backend",
1972
+ methods: BACKEND_METHODS,
1973
+ read: {
1974
+ capabilitySnapshot: true,
1975
+ sessionSnapshot: true,
1976
+ projectOutline: true,
1977
+ entityQuery: {
1978
+ kinds: [
1979
+ "project",
1980
+ "package",
1981
+ "resource",
1982
+ "component",
1983
+ "displayNode",
1984
+ "controller",
1985
+ "transition"
1986
+ ],
1987
+ projection: "properties",
1988
+ sourceBytes: false,
1989
+ limits: BACKEND_ENTITY_QUERY_LIMITS
1990
+ },
1991
+ sessionState: {
1992
+ sourceBytes: false,
1993
+ limits: BACKEND_SESSION_READ_LIMITS.model
1994
+ },
1995
+ resourceBytes: {
1996
+ expectedRevisionRequired: true,
1997
+ hydration: false,
1998
+ maxBytes: BACKEND_SESSION_READ_LIMITS.resourceBytes
1999
+ },
2000
+ projectValidation: true
2001
+ },
2002
+ authoring: {
2003
+ preflightTransaction: {
2004
+ mode: "execute-and-discard",
2005
+ reservesRevision: false,
2006
+ impact: "model-diff",
2007
+ limits: BACKEND_TRANSACTION_PREVIEW_LIMITS
2008
+ },
2009
+ applyTransaction: true,
2010
+ saveSession: true,
2011
+ resourceKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
2012
+ nodeKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.nodeKinds],
2013
+ gearKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.gearKinds],
2014
+ transactionScope: {
2015
+ resourceKinds: [...UAM_SUPPORTED_TRANSACTION_SCOPE.resourceKinds],
2016
+ nodeKinds: [...UAM_SUPPORTED_TRANSACTION_SCOPE.nodeKinds],
2017
+ gearKinds: [...UAM_SUPPORTED_TRANSACTION_SCOPE.gearKinds]
2018
+ },
2019
+ unsupported: ["artifact.publish", "artifact.restore"]
2020
+ },
2021
+ artifact: createArtifactCapabilities(),
2022
+ manifest: {
2023
+ browserSafe: true,
2024
+ rootEntrypoint: "@openfairygui/backend",
2025
+ nodeEntrypoint: "@openfairygui/backend/node",
2026
+ adapters: {
2027
+ fileSystem: {
2028
+ injected: true,
2029
+ requiredFor: [
2030
+ "openSession",
2031
+ "saveSession",
2032
+ "materializeSession"
2033
+ ]
2034
+ },
2035
+ projectStorage: {
2036
+ injected: true,
2037
+ browserSafe: true,
2038
+ requiredFor: [
2039
+ "openProjectSession.writeback",
2040
+ "saveSession",
2041
+ "materializeSession"
2042
+ ],
2043
+ adapterFactory: "createBackendStorageFileSystem"
2044
+ },
2045
+ host: {
2046
+ injected: true,
2047
+ requiredFor: ["advisoryLockMetadata"]
2048
+ }
2049
+ },
2050
+ executionBoundaries: {
2051
+ projectSession: "in-process-browser-safe",
2052
+ fileBackedSession: "adapter-backed",
2053
+ artifactPublish: ARTIFACT_BRIDGE_CAPABILITY,
2054
+ artifactRestore: ARTIFACT_BRIDGE_CAPABILITY
2055
+ },
2056
+ diagnostics: {
2057
+ stableCodes: true,
2058
+ errorDiagnosticMirror: true,
2059
+ recoveryGuides: "all-formal-codes",
2060
+ automaticRepair: false
2061
+ }
2062
+ },
2063
+ compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
2064
+ runtime: {
2065
+ sessionRuntime: true,
2066
+ maxSessions,
2067
+ idleSessionTimeoutMs,
2068
+ advisoryLocking: true,
2069
+ coordinatedSave: true,
2070
+ atomicSave,
2071
+ staleRevisionProtection: true,
2072
+ pathPolicy: createRuntimePathPolicy(caseSensitivePaths),
2073
+ events: {
2074
+ polling: true,
2075
+ subscriptions: false,
2076
+ retentionLimit: 1e3,
2077
+ sequenceScope: "runtime"
2078
+ },
2079
+ cache: {
2080
+ derivedReadOnly: true,
2081
+ keyedBy: "sessionId",
2082
+ refreshMode: "synchronous",
2083
+ sourceOfTruth: false,
2084
+ refreshMethod: "refreshCache"
2085
+ }
2086
+ }
2087
+ };
2088
+ }
2089
+ //#endregion
2090
+ //#region src/runtime.ts
2091
+ var BackendRuntime = class {
2092
+ fileSystem;
2093
+ capabilities;
2094
+ sessions;
2095
+ sessionOperations = new SessionOperationQueue();
2096
+ context;
2097
+ readService;
2098
+ runtimeService;
2099
+ authoringService;
2100
+ persistenceService;
2101
+ cacheService;
2102
+ eventService;
2103
+ constructor(options = {}) {
2104
+ this.fileSystem = options.fileSystem;
2105
+ const maxSessions = options.maxSessions ?? 32;
2106
+ if (!Number.isSafeInteger(maxSessions) || maxSessions < 1) throw new RangeError(`maxSessions must be a positive integer: ${maxSessions}`);
2107
+ const idleTimeout = options.idleSessionTimeoutMs ?? 30 * 6e4;
2108
+ if (!Number.isSafeInteger(idleTimeout) || idleTimeout < 0 || idleTimeout > 2147483647) throw new RangeError("idleSessionTimeoutMs must be an integer between 0 and 2147483647.");
2109
+ this.sessions = new SessionRegistry(maxSessions, idleTimeout, (sessionId, activity) => this.runtimeService.expireIdleSession(sessionId, activity));
2110
+ this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction), options.fileSystem?.caseSensitivePaths ?? false, maxSessions, idleTimeout);
2111
+ this.context = {
2112
+ fileSystem: this.fileSystem,
2113
+ host: options.host,
2114
+ allowedProjectRoots: options.allowedProjectRoots,
2115
+ capabilities: this.capabilities,
2116
+ sessions: this.sessions
2117
+ };
2118
+ const getSession = (sessionId) => this.sessions.get(sessionId);
2119
+ this.readService = new ReadService((sessionId) => readView(getSession(sessionId)), this.capabilities);
2120
+ this.eventService = new EventService(getSession);
2121
+ this.cacheService = new CacheService(getSession, this.eventService);
2122
+ this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService, this.sessionOperations);
2123
+ this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService, this.sessionOperations);
2124
+ this.persistenceService = new PersistenceService(this.context, this.cacheService, this.eventService, this.sessionOperations);
2125
+ }
2126
+ getCapabilities() {
2127
+ return this.readService.getCapabilities();
2128
+ }
2129
+ async openSession(input) {
2130
+ const startedAt = Date.now();
2131
+ try {
2132
+ return await this.runtimeService.openSession(input);
2133
+ } catch (error) {
2134
+ return failure("runtime", startedAt, {
2135
+ code: "project_open_failed",
2136
+ ...classifyProjectOpenFailure(error),
2137
+ projectPath: input.projectPath
2138
+ });
2139
+ }
2140
+ }
2141
+ openProjectSession(input) {
2142
+ return this.runtimeService.openProjectSession(input);
2143
+ }
2144
+ getSession(input) {
2145
+ return this.readService.getSession(input);
2146
+ }
2147
+ getProjectOutline(input) {
2148
+ return this.readService.getProjectOutline(input);
2149
+ }
2150
+ queryEntity(input) {
2151
+ return this.readService.queryEntity(input);
2152
+ }
2153
+ readSessionState(input) {
2154
+ return this.readService.readSessionState(input);
2155
+ }
2156
+ readResourceBytes(input) {
2157
+ return this.readService.readResourceBytes(input);
2158
+ }
2159
+ validateSession(input) {
2160
+ return this.readService.validateSession(input);
2161
+ }
2162
+ async preflightTransaction(input) {
2163
+ return this.authoringService.preflightTransaction(input);
2164
+ }
2165
+ async applyTransaction(input) {
2166
+ return this.authoringService.applyTransaction(input);
2167
+ }
2168
+ async saveSession(input) {
2169
+ return this.persistenceService.saveSession(input);
2170
+ }
2171
+ async materializeSession(input) {
2172
+ return this.persistenceService.materializeSession(input);
2173
+ }
2174
+ async closeSession(input) {
2175
+ const captured = { ...input };
2176
+ return this.sessionOperations.run(captured.sessionId, () => this.runtimeService.closeSession(captured));
2177
+ }
2178
+ getEvents(input) {
2179
+ return this.eventService.getEvents(input);
2180
+ }
2181
+ getCacheSnapshot(input) {
2182
+ return this.cacheService.getCacheSnapshot(input);
2183
+ }
2184
+ refreshCache(input) {
2185
+ return this.cacheService.refreshCache(input);
2186
+ }
2187
+ };
2188
+ //#endregion
2189
+ export { ProjectWriteTransactionError as a, BACKEND_CAPABILITY_SCHEMA_VERSION as c, BACKEND_TRANSACTION_PREVIEW_LIMITS as i, BACKEND_COMPATIBILITY_POLICY as l, BACKEND_ENTITY_QUERY_LIMITS as n, normalizeComparablePath as o, BACKEND_SESSION_READ_LIMITS as r, resolveFairyPath as s, BackendRuntime as t, BACKEND_CONTRACT_VERSION as u };