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