@openfairygui/backend 0.2.0-alpha.9 → 0.2.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.
@@ -1,1417 +0,0 @@
1
- import { UAM_SUPPORTED_MATERIALIZATION_SCOPE, UAM_SUPPORTED_TRANSACTION_SCOPE, liftDocumentToUamProject, materializeUamProject, normalizeUamProject, validateUamProject } from "@openfairygui/core/uam";
2
- import { ProjectReader, ProjectWriter } from "@openfairygui/core/project-io";
3
- import { applyUamTransactionApp } from "@openfairygui/functions/uam";
4
- //#region src/contracts.ts
5
- const BACKEND_CONTRACT_VERSION = "1.1.0-p2";
6
- const BACKEND_CAPABILITY_SCHEMA_VERSION = 2;
7
- const BACKEND_COMPATIBILITY_POLICY = {
8
- incompatibleChange: "requires contractVersion bump",
9
- capabilitySchemaChange: "requires capabilitySchemaVersion bump",
10
- additiveChange: "allowed without breaking existing consumers"
11
- };
12
- //#endregion
13
- //#region src/path-policy.ts
14
- function normalizeComparablePath(value) {
15
- const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
16
- const driveMatch = normalized.match(/^([a-z]:)(?:\/(.*))?$/i);
17
- const drivePrefix = driveMatch?.[1].toLowerCase() ?? "";
18
- const remainder = driveMatch ? driveMatch[2] ?? "" : normalized;
19
- const hasRoot = driveMatch ? true : remainder.startsWith("/");
20
- const rawSegments = remainder.split("/").filter((segment) => segment.length > 0);
21
- const segments = [];
22
- for (const segment of rawSegments) {
23
- if (segment === ".") continue;
24
- if (segment === "..") {
25
- if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
26
- else if (!hasRoot) segments.push("..");
27
- continue;
28
- }
29
- segments.push(segment);
30
- }
31
- const joined = segments.join("/");
32
- return (drivePrefix ? `${drivePrefix}/${joined}`.replace(/\/$/, "") : hasRoot ? `/${joined}`.replace(/\/$/, "") : joined || ".").toLowerCase();
33
- }
34
- function createRuntimePathPolicy() {
35
- return {
36
- canonicalization: "realpath+normalized-casefold",
37
- sessionIdentity: "project-root",
38
- saveTarget: "opened-project-only",
39
- outputTargets: "deferred",
40
- workspaceBoundary: "project-root-only"
41
- };
42
- }
43
- async function resolveFairyPath(fileSystem, input) {
44
- const resolvedInput = fileSystem.resolve(input);
45
- const stat = await fileSystem.stat(resolvedInput);
46
- if (stat.isFile() && resolvedInput.endsWith(".fairy")) return await fileSystem.resolvePath(resolvedInput);
47
- if (stat.isDirectory()) {
48
- const fairyFiles = (await fileSystem.readdir(resolvedInput)).filter((entry) => entry.endsWith(".fairy"));
49
- if (fairyFiles.length === 1) return await fileSystem.resolvePath(fileSystem.join(resolvedInput, fairyFiles[0]));
50
- if (fairyFiles.length > 1) throw new Error(`Multiple .fairy files found in ${resolvedInput}: ${fairyFiles.join(", ")}`);
51
- throw new Error(`No .fairy file found in ${resolvedInput}`);
52
- }
53
- throw new Error(`Input is not a .fairy file or directory: ${resolvedInput}`);
54
- }
55
- async function resolveCanonicalProjectRoot(fileSystem, input) {
56
- const fairyPath = await resolveFairyPath(fileSystem, input);
57
- const canonicalProjectPath = await fileSystem.resolvePath(fileSystem.dirname(fairyPath));
58
- return {
59
- fairyPath,
60
- canonicalProjectPath,
61
- canonicalPathKey: normalizeComparablePath(canonicalProjectPath)
62
- };
63
- }
64
- async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
65
- if (!targetPath) return null;
66
- const attemptedPath = await fileSystem.resolvePath(fileSystem.resolve(targetPath));
67
- const allowedPath = await fileSystem.resolvePath(openedFairyPath);
68
- if (normalizeComparablePath(attemptedPath) === normalizeComparablePath(allowedPath)) return null;
69
- return {
70
- code: "path_policy_violation",
71
- message: `Save target is restricted to the originally opened project file: ${allowedPath}`,
72
- policy: "save_target",
73
- attemptedPath,
74
- allowedPath
75
- };
76
- }
77
- //#endregion
78
- //#region src/services/artifact-service.ts
79
- function createArtifactCapabilities() {
80
- const bridge = {
81
- available: false,
82
- requiredHost: "node",
83
- executionBoundary: "external-bridge",
84
- bridgeEntrypoint: "@openfairygui/backend/node",
85
- reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
86
- };
87
- return {
88
- publish: false,
89
- restore: false,
90
- status: "bridge-required",
91
- publishBridge: bridge,
92
- restoreBridge: bridge
93
- };
94
- }
95
- //#endregion
96
- //#region src/services/context.ts
97
- function diagnosticFromError(error) {
98
- return {
99
- code: error.code,
100
- message: error.message,
101
- severity: "error"
102
- };
103
- }
104
- function randomId$1() {
105
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
106
- }
107
- function createMeta(stage, startedAt, options) {
108
- return {
109
- requestId: options?.requestId ?? randomId$1(),
110
- sessionId: options?.sessionId,
111
- revision: options?.revision,
112
- durationMs: Math.max(0, Date.now() - startedAt),
113
- warnings: options?.warnings ?? [],
114
- diagnostics: options?.diagnostics ?? [],
115
- stage,
116
- contractVersion: BACKEND_CONTRACT_VERSION,
117
- capabilitySchemaVersion: 2
118
- };
119
- }
120
- function success(stage, startedAt, data, options) {
121
- return {
122
- ok: true,
123
- meta: createMeta(stage, startedAt, options),
124
- data
125
- };
126
- }
127
- function failure(stage, startedAt, error, session, options) {
128
- const diagnostics = options?.diagnostics ?? [diagnosticFromError(error)];
129
- return {
130
- ok: false,
131
- meta: createMeta(stage, startedAt, {
132
- ...options,
133
- diagnostics
134
- }),
135
- error,
136
- session
137
- };
138
- }
139
- //#endregion
140
- //#region src/services/snapshot-utils.ts
141
- function cloneJsonValue(value) {
142
- if (value === void 0 || value === null) return value;
143
- return JSON.parse(JSON.stringify(value));
144
- }
145
- function cloneEventSnapshot(event) {
146
- return {
147
- ...event,
148
- diagnostics: event.diagnostics.map((diagnostic) => ({ ...diagnostic })),
149
- payload: cloneJsonValue(event.payload)
150
- };
151
- }
152
- function cloneJobSnapshot(job) {
153
- return {
154
- ...job,
155
- diagnostics: job.diagnostics.map((diagnostic) => ({ ...diagnostic })),
156
- progress: job.progress ? { ...job.progress } : void 0,
157
- result: cloneJsonValue(job.result),
158
- error: cloneJsonValue(job.error)
159
- };
160
- }
161
- function cloneCacheEntrySnapshot(entry) {
162
- return {
163
- ...entry,
164
- summary: {
165
- ...entry.summary,
166
- diagnostics: entry.summary.diagnostics.map((diagnostic) => ({ ...diagnostic }))
167
- }
168
- };
169
- }
170
- function cloneCapabilitiesSnapshot(capabilities) {
171
- return cloneJsonValue(capabilities);
172
- }
173
- //#endregion
174
- //#region src/services/session-utils.ts
175
- function toSessionSnapshot(session, capabilities) {
176
- return {
177
- sessionId: session.sessionId,
178
- canonicalProjectPath: session.canonicalProjectPath,
179
- revision: session.revision,
180
- lastSavedRevision: session.lastSavedRevision,
181
- dirty: session.dirty,
182
- lockHeld: session.lockHeld,
183
- capabilities: cloneCapabilitiesSnapshot(capabilities)
184
- };
185
- }
186
- function createSessionNotFoundError(sessionId) {
187
- return {
188
- code: "session_not_found",
189
- message: `Session was not found: ${sessionId}`,
190
- sessionId
191
- };
192
- }
193
- function createStaleWriteError(session, expectedRevision) {
194
- return {
195
- code: "stale_write",
196
- message: `Expected revision ${expectedRevision} does not match current revision ${session.revision}.`,
197
- sessionId: session.sessionId,
198
- canonicalPathKey: session.canonicalPathKey,
199
- expectedRevision,
200
- actualRevision: session.revision
201
- };
202
- }
203
- //#endregion
204
- //#region src/services/authoring-service.ts
205
- function createWriterFileSystem(fileSystem, committedPaths, failedPaths) {
206
- async function trackWrite(targetPath, fn) {
207
- try {
208
- const result = await fn();
209
- committedPaths.push(targetPath);
210
- return result;
211
- } catch (error) {
212
- failedPaths.push(targetPath);
213
- throw error;
214
- }
215
- }
216
- return {
217
- async readFile(filePath) {
218
- return fileSystem.readFile(filePath);
219
- },
220
- async readFileRaw(filePath) {
221
- return fileSystem.readFileRaw(filePath);
222
- },
223
- async writeFile(filePath, content) {
224
- await trackWrite(filePath, async () => {
225
- await fileSystem.mkdir(fileSystem.dirname(filePath), { recursive: true });
226
- await fileSystem.writeFile(filePath, content);
227
- });
228
- },
229
- async writeFileRaw(filePath, data) {
230
- await trackWrite(filePath, async () => {
231
- await fileSystem.mkdir(fileSystem.dirname(filePath), { recursive: true });
232
- await fileSystem.writeFileRaw(filePath, data);
233
- });
234
- },
235
- async mkdir(dirPath) {
236
- await fileSystem.mkdir(dirPath, { recursive: true });
237
- },
238
- async readdir(dirPath) {
239
- return fileSystem.readdir(dirPath);
240
- },
241
- async exists(filePath) {
242
- try {
243
- await fileSystem.stat(filePath);
244
- return true;
245
- } catch {
246
- return false;
247
- }
248
- },
249
- join(...paths) {
250
- return fileSystem.join(...paths);
251
- },
252
- dirname(filePath) {
253
- return fileSystem.dirname(filePath);
254
- }
255
- };
256
- }
257
- function toBackendDiagnostics(error) {
258
- return error.diagnostics.length > 0 ? error.diagnostics.map((diagnostic) => ({ ...diagnostic })) : [{
259
- code: error.code,
260
- message: error.message,
261
- severity: "error",
262
- operationKind: error.operationKind,
263
- opIndex: error.opIndex,
264
- opId: error.opId
265
- }];
266
- }
267
- function createCapabilityUnavailableError$1(message) {
268
- return {
269
- code: "capability_unavailable",
270
- message,
271
- capability: "fileSystem",
272
- requiredAdapter: "BackendFileSystem"
273
- };
274
- }
275
- function validationDiagnostics(sessionProject) {
276
- return validateUamProject(sessionProject).map((issue) => ({
277
- code: "materialize_validation_failed",
278
- message: issue.message,
279
- severity: "error",
280
- path: issue.path,
281
- operationKind: "materializeSession"
282
- }));
283
- }
284
- function toMaterializeSnapshot(session, capabilities, input) {
285
- return {
286
- ...toSessionSnapshot(session, capabilities),
287
- mode: "fullProject",
288
- reason: input.reason,
289
- materializeRevision: session.revision,
290
- saveRevision: session.lastSavedRevision,
291
- writtenPaths: [...input.writtenPaths],
292
- skippedPaths: [...input.skippedPaths],
293
- diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic }))
294
- };
295
- }
296
- function storageCanonicalTarget(input) {
297
- const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || ".");
298
- return {
299
- fileSystem: input.fileSystem,
300
- fairyPath: input.fairyPath,
301
- canonicalProjectPath,
302
- canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath)
303
- };
304
- }
305
- var AuthoringService = class {
306
- constructor(context, cacheService, eventService) {
307
- this.context = context;
308
- this.cacheService = cacheService;
309
- this.eventService = eventService;
310
- }
311
- async applyTransaction(input) {
312
- const startedAt = Date.now();
313
- const session = this.context.sessions.get(input.sessionId);
314
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
315
- if (input.expectedRevision !== session.revision) {
316
- this.eventService.emit({
317
- kind: "transaction.rejected",
318
- sessionId: session.sessionId,
319
- canonicalPathKey: session.canonicalPathKey,
320
- revision: session.revision
321
- });
322
- return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
323
- sessionId: session.sessionId,
324
- revision: session.revision
325
- });
326
- }
327
- const result = applyUamTransactionApp({
328
- project: session.project,
329
- operations: input.operations
330
- });
331
- if (result.ok === false) {
332
- const diagnostics = toBackendDiagnostics(result.error);
333
- this.eventService.emit({
334
- kind: "transaction.rejected",
335
- sessionId: session.sessionId,
336
- canonicalPathKey: session.canonicalPathKey,
337
- revision: session.revision,
338
- diagnostics
339
- });
340
- return failure("authoring", startedAt, result.error, toSessionSnapshot(session, this.context.capabilities), {
341
- sessionId: session.sessionId,
342
- revision: session.revision,
343
- diagnostics
344
- });
345
- }
346
- session.project = result.project;
347
- session.revision += 1;
348
- session.dirty = true;
349
- const cacheEntry = this.cacheService.invalidateSession(session);
350
- this.eventService.emit({
351
- kind: "transaction.applied",
352
- sessionId: session.sessionId,
353
- canonicalPathKey: session.canonicalPathKey,
354
- revision: session.revision
355
- });
356
- this.eventService.emit({
357
- kind: "cache.invalidated",
358
- sessionId: session.sessionId,
359
- canonicalPathKey: session.canonicalPathKey,
360
- revision: session.revision,
361
- cacheRevision: cacheEntry.revision
362
- });
363
- return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
364
- sessionId: session.sessionId,
365
- revision: session.revision
366
- });
367
- }
368
- async saveSession(input) {
369
- if (input.force === true || input.mode === "materializeCleanSession") return this.materializeSession({
370
- sessionId: input.sessionId,
371
- expectedRevision: input.expectedRevision,
372
- targetPath: input.targetPath,
373
- fileSystem: input.fileSystem,
374
- mode: "fullProject",
375
- reason: "force_save"
376
- });
377
- const startedAt = Date.now();
378
- const session = this.context.sessions.get(input.sessionId);
379
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
380
- const fileSystem = input.fileSystem ?? session.fileSystem ?? this.context.fileSystem;
381
- if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("saveSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
382
- sessionId: session.sessionId,
383
- revision: session.revision
384
- });
385
- if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
386
- sessionId: session.sessionId,
387
- revision: session.revision
388
- });
389
- const targetViolation = await validateSaveTarget(fileSystem, session.fairyPath, input.targetPath);
390
- if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
391
- sessionId: session.sessionId,
392
- revision: session.revision
393
- });
394
- if (!session.dirty) return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
395
- sessionId: session.sessionId,
396
- revision: session.revision
397
- });
398
- const committedPaths = [];
399
- const failedPaths = [];
400
- this.eventService.emit({
401
- kind: "save.started",
402
- sessionId: session.sessionId,
403
- canonicalPathKey: session.canonicalPathKey,
404
- revision: session.revision
405
- });
406
- try {
407
- await new ProjectWriter(createWriterFileSystem(fileSystem, committedPaths, failedPaths)).write(materializeUamProject(session.project), session.fairyPath);
408
- session.lastSavedRevision = session.revision;
409
- session.dirty = false;
410
- const cacheEntry = this.cacheService.refreshSession(session);
411
- this.eventService.emit({
412
- kind: "save.completed",
413
- sessionId: session.sessionId,
414
- canonicalPathKey: session.canonicalPathKey,
415
- revision: session.revision
416
- });
417
- this.eventService.emit({
418
- kind: "cache.updated",
419
- sessionId: session.sessionId,
420
- canonicalPathKey: session.canonicalPathKey,
421
- revision: session.revision,
422
- cacheRevision: cacheEntry.revision
423
- });
424
- return success("authoring", startedAt, toSessionSnapshot(session, this.context.capabilities), {
425
- sessionId: session.sessionId,
426
- revision: session.revision
427
- });
428
- } catch (error) {
429
- this.cacheService.invalidateSession(session);
430
- this.eventService.emit({
431
- kind: "save.failed",
432
- sessionId: session.sessionId,
433
- canonicalPathKey: session.canonicalPathKey,
434
- revision: session.revision
435
- });
436
- return failure("authoring", startedAt, {
437
- code: "save_partial_failure",
438
- message: error instanceof Error ? error.message : String(error),
439
- sessionId: session.sessionId,
440
- canonicalPathKey: session.canonicalPathKey,
441
- attemptedRevision: session.revision,
442
- lastSavedRevision: session.lastSavedRevision,
443
- committedPaths,
444
- failedPaths,
445
- diskMayBePartiallyUpdated: true
446
- }, toSessionSnapshot(session, this.context.capabilities), {
447
- sessionId: session.sessionId,
448
- revision: session.revision
449
- });
450
- }
451
- }
452
- async materializeSession(input) {
453
- const startedAt = Date.now();
454
- const session = this.context.sessions.get(input.sessionId);
455
- if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(input.sessionId));
456
- if (input.expectedRevision !== void 0 && input.expectedRevision !== session.revision) return failure("authoring", startedAt, createStaleWriteError(session, input.expectedRevision), toSessionSnapshot(session, this.context.capabilities), {
457
- sessionId: session.sessionId,
458
- revision: session.revision
459
- });
460
- const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
461
- const fileSystem = storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem ?? this.context.fileSystem;
462
- if (!fileSystem) return failure("authoring", startedAt, createCapabilityUnavailableError$1("materializeSession requires an injected BackendFileSystem adapter."), toSessionSnapshot(session, this.context.capabilities), {
463
- sessionId: session.sessionId,
464
- revision: session.revision
465
- });
466
- const fairyPath = storageTarget?.fairyPath ?? session.fairyPath;
467
- const targetViolation = await validateSaveTarget(fileSystem, fairyPath, input.targetPath);
468
- if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
469
- sessionId: session.sessionId,
470
- revision: session.revision
471
- });
472
- if (storageTarget) {
473
- const holderSessionId = this.context.sessionsByPath.get(storageTarget.canonicalPathKey);
474
- if (holderSessionId && holderSessionId !== session.sessionId) return failure("authoring", startedAt, {
475
- code: "lock_conflict",
476
- kind: "in_process_session_exists",
477
- message: `Project is already open in this backend runtime: ${storageTarget.canonicalProjectPath}`,
478
- canonicalPathKey: storageTarget.canonicalPathKey,
479
- holderSessionId
480
- }, toSessionSnapshot(session, this.context.capabilities), {
481
- sessionId: session.sessionId,
482
- revision: session.revision
483
- });
484
- }
485
- const diagnostics = validationDiagnostics(session.project);
486
- if (diagnostics.length > 0) return failure("authoring", startedAt, {
487
- code: "materialize_validation_failed",
488
- message: `UAM materialize validation failed with ${diagnostics.length} issue(s).`,
489
- sessionId: session.sessionId,
490
- canonicalPathKey: session.canonicalPathKey,
491
- issueCount: diagnostics.length,
492
- diagnostics
493
- }, toSessionSnapshot(session, this.context.capabilities), {
494
- sessionId: session.sessionId,
495
- revision: session.revision,
496
- diagnostics
497
- });
498
- let document;
499
- try {
500
- document = materializeUamProject(session.project);
501
- } catch (error) {
502
- const diagnosticsFromError = [{
503
- code: "materialize_validation_failed",
504
- message: error instanceof Error ? error.message : String(error),
505
- severity: "error",
506
- operationKind: "materializeSession"
507
- }];
508
- return failure("authoring", startedAt, {
509
- code: "materialize_validation_failed",
510
- message: error instanceof Error ? error.message : String(error),
511
- sessionId: session.sessionId,
512
- canonicalPathKey: session.canonicalPathKey,
513
- issueCount: diagnosticsFromError.length,
514
- diagnostics: diagnosticsFromError
515
- }, toSessionSnapshot(session, this.context.capabilities), {
516
- sessionId: session.sessionId,
517
- revision: session.revision,
518
- diagnostics: diagnosticsFromError
519
- });
520
- }
521
- const writtenPaths = [];
522
- const failedPaths = [];
523
- const skippedPaths = [];
524
- this.eventService.emit({
525
- kind: "save.started",
526
- sessionId: session.sessionId,
527
- canonicalPathKey: storageTarget?.canonicalPathKey ?? session.canonicalPathKey,
528
- revision: session.revision
529
- });
530
- try {
531
- await new ProjectWriter(createWriterFileSystem(fileSystem, writtenPaths, failedPaths)).write(document, fairyPath);
532
- if (storageTarget) {
533
- this.context.sessionsByPath.delete(session.canonicalPathKey);
534
- session.fileSystem = storageTarget.fileSystem;
535
- session.fairyPath = storageTarget.fairyPath;
536
- session.canonicalProjectPath = storageTarget.canonicalProjectPath;
537
- session.canonicalPathKey = storageTarget.canonicalPathKey;
538
- this.context.sessionsByPath.set(session.canonicalPathKey, session.sessionId);
539
- }
540
- session.lastSavedRevision = session.revision;
541
- session.dirty = false;
542
- const cacheEntry = this.cacheService.refreshSession(session);
543
- this.eventService.emit({
544
- kind: "save.completed",
545
- sessionId: session.sessionId,
546
- canonicalPathKey: session.canonicalPathKey,
547
- revision: session.revision
548
- });
549
- this.eventService.emit({
550
- kind: "cache.updated",
551
- sessionId: session.sessionId,
552
- canonicalPathKey: session.canonicalPathKey,
553
- revision: session.revision,
554
- cacheRevision: cacheEntry.revision
555
- });
556
- return success("authoring", startedAt, toMaterializeSnapshot(session, this.context.capabilities, {
557
- reason: input.reason,
558
- writtenPaths,
559
- skippedPaths,
560
- diagnostics: []
561
- }), {
562
- sessionId: session.sessionId,
563
- revision: session.revision
564
- });
565
- } catch (error) {
566
- const diagnosticsFromError = [{
567
- code: "write_failed",
568
- message: error instanceof Error ? error.message : String(error),
569
- severity: "error",
570
- path: failedPaths[0],
571
- operationKind: "materializeSession"
572
- }];
573
- this.cacheService.invalidateSession(session);
574
- this.eventService.emit({
575
- kind: "save.failed",
576
- sessionId: session.sessionId,
577
- canonicalPathKey: session.canonicalPathKey,
578
- revision: session.revision,
579
- diagnostics: diagnosticsFromError
580
- });
581
- return failure("authoring", startedAt, {
582
- code: "write_failed",
583
- message: error instanceof Error ? error.message : String(error),
584
- sessionId: session.sessionId,
585
- canonicalPathKey: session.canonicalPathKey,
586
- attemptedRevision: session.revision,
587
- lastSavedRevision: session.lastSavedRevision,
588
- writtenPaths,
589
- failedPaths,
590
- skippedPaths,
591
- diagnostics: diagnosticsFromError,
592
- diskMayBePartiallyUpdated: true
593
- }, toSessionSnapshot(session, this.context.capabilities), {
594
- sessionId: session.sessionId,
595
- revision: session.revision,
596
- diagnostics: diagnosticsFromError
597
- });
598
- }
599
- }
600
- };
601
- //#endregion
602
- //#region src/services/cache-service.ts
603
- function createCacheEntry(session, valid) {
604
- return {
605
- canonicalPathKey: session.canonicalPathKey,
606
- sessionId: session.sessionId,
607
- revision: session.revision,
608
- lastSavedRevision: session.lastSavedRevision,
609
- dirty: session.dirty,
610
- valid,
611
- indexedAt: (/* @__PURE__ */ new Date()).toISOString(),
612
- summary: {
613
- packageCount: session.project.packages.length,
614
- resourceCount: session.project.packages.reduce((total, pkg) => total + pkg.resources.length, 0),
615
- diagnostics: []
616
- }
617
- };
618
- }
619
- var CacheService = class {
620
- constructor(context) {
621
- this.context = context;
622
- }
623
- getCacheSnapshot(input) {
624
- const startedAt = Date.now();
625
- const session = this.context.sessions.get(input.sessionId);
626
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
627
- const entry = this.context.cacheBySession.get(input.sessionId);
628
- return success("read", startedAt, {
629
- cacheRevision: entry?.revision ?? session.revision,
630
- entries: entry ? [cloneCacheEntrySnapshot(entry)] : []
631
- }, {
632
- sessionId: session.sessionId,
633
- revision: session.revision
634
- });
635
- }
636
- refreshSession(session) {
637
- const entry = createCacheEntry(session, true);
638
- this.context.cacheBySession.set(session.sessionId, entry);
639
- return entry;
640
- }
641
- invalidateSession(session) {
642
- const entry = createCacheEntry(session, false);
643
- this.context.cacheBySession.set(session.sessionId, entry);
644
- return entry;
645
- }
646
- removeSession(sessionId) {
647
- this.context.cacheBySession.delete(sessionId);
648
- }
649
- };
650
- //#endregion
651
- //#region src/services/event-service.ts
652
- const DEFAULT_EVENT_RETENTION_LIMIT = 1e3;
653
- var EventService = class {
654
- constructor(context) {
655
- this.context = context;
656
- }
657
- emit(event) {
658
- const emitted = {
659
- ...event,
660
- sequence: this.context.nextEventSequence(),
661
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
662
- diagnostics: event.diagnostics ?? []
663
- };
664
- const sessionId = event.sessionId;
665
- if (!sessionId) return emitted;
666
- const events = this.context.eventsBySession.get(sessionId) ?? [];
667
- events.push(emitted);
668
- while (events.length > DEFAULT_EVENT_RETENTION_LIMIT) events.shift();
669
- this.context.eventsBySession.set(sessionId, events);
670
- return emitted;
671
- }
672
- getEvents(input) {
673
- const startedAt = Date.now();
674
- const session = this.context.sessions.get(input.sessionId);
675
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
676
- const events = this.context.eventsBySession.get(input.sessionId) ?? [];
677
- const oldestSequence = events[0]?.sequence ?? (events.length === 0 ? 1 : 0);
678
- const currentSequence = events.at(-1)?.sequence ?? 0;
679
- const after = input.after === void 0 ? 0 : Number(input.after);
680
- if (!Number.isInteger(after) || after < 0) return failure("runtime", startedAt, {
681
- code: "event_cursor_invalid",
682
- message: `Invalid event cursor: ${input.after}`,
683
- sessionId: input.sessionId,
684
- after: String(input.after)
685
- });
686
- if (events.length > 0 && after !== 0 && after < oldestSequence - 1) return failure("runtime", startedAt, {
687
- code: "event_cursor_invalid",
688
- message: `Event cursor has expired: ${after}`,
689
- sessionId: input.sessionId,
690
- after: String(input.after)
691
- });
692
- if (after > currentSequence) return failure("runtime", startedAt, {
693
- code: "event_cursor_invalid",
694
- message: `Unknown event cursor: ${after}`,
695
- sessionId: input.sessionId,
696
- after: String(input.after)
697
- });
698
- const filtered = events.filter((event) => event.sequence > after);
699
- const limit = input.limit === void 0 ? filtered.length : Math.max(0, input.limit);
700
- return success("runtime", startedAt, {
701
- events: filtered.slice(0, limit).map(cloneEventSnapshot),
702
- oldestSequence,
703
- currentSequence,
704
- cursorExpired: false
705
- }, {
706
- sessionId: session.sessionId,
707
- revision: session.revision
708
- });
709
- }
710
- removeSession(sessionId) {
711
- this.context.eventsBySession.delete(sessionId);
712
- }
713
- };
714
- //#endregion
715
- //#region src/services/job-service.ts
716
- const COMPLETED_JOB_RETENTION_LIMIT = 100;
717
- const REFRESH_START_DELAY_MS = 0;
718
- const REFRESH_COMPLETE_DELAY_MS = 50;
719
- function isTerminal(status) {
720
- return status === "completed" || status === "failed" || status === "cancelled";
721
- }
722
- var JobService = class {
723
- constructor(context, cacheService, eventService) {
724
- this.context = context;
725
- this.cacheService = cacheService;
726
- this.eventService = eventService;
727
- }
728
- cancellationRequests = /* @__PURE__ */ new Set();
729
- getJobs(sessionId) {
730
- return this.context.jobsBySession.get(sessionId) ?? [];
731
- }
732
- setJobs(sessionId, jobs) {
733
- const retained = [];
734
- let terminalCount = 0;
735
- for (let index = jobs.length - 1; index >= 0; index -= 1) {
736
- const job = jobs[index];
737
- if (isTerminal(job.status)) {
738
- if (terminalCount >= COMPLETED_JOB_RETENTION_LIMIT) continue;
739
- terminalCount += 1;
740
- }
741
- retained.push(job);
742
- }
743
- this.context.jobsBySession.set(sessionId, retained.reverse());
744
- }
745
- refreshCache(input) {
746
- const startedAt = Date.now();
747
- const session = this.context.sessions.get(input.sessionId);
748
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
749
- const jobId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
750
- const job = {
751
- jobId,
752
- kind: "cache.refresh",
753
- status: "queued",
754
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
755
- sessionId: session.sessionId,
756
- canonicalPathKey: session.canonicalPathKey,
757
- revision: session.revision,
758
- diagnostics: [],
759
- progress: {
760
- completed: 0,
761
- total: 1,
762
- message: input.reason ?? "manual"
763
- }
764
- };
765
- const jobs = this.getJobs(session.sessionId);
766
- jobs.push(job);
767
- this.setJobs(session.sessionId, jobs);
768
- this.eventService.emit({
769
- kind: "job.created",
770
- sessionId: session.sessionId,
771
- canonicalPathKey: session.canonicalPathKey,
772
- revision: session.revision,
773
- jobId
774
- });
775
- this.scheduleRefreshJob(session.sessionId, jobId);
776
- return success("runtime", startedAt, cloneJobSnapshot(job), {
777
- sessionId: session.sessionId,
778
- revision: session.revision
779
- });
780
- }
781
- getJob(input) {
782
- const startedAt = Date.now();
783
- const session = this.context.sessions.get(input.sessionId);
784
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
785
- const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
786
- if (!job) return failure("runtime", startedAt, {
787
- code: "job_not_found",
788
- message: `Job was not found: ${input.jobId}`,
789
- sessionId: input.sessionId,
790
- jobId: input.jobId
791
- }, void 0, {
792
- sessionId: session.sessionId,
793
- revision: session.revision
794
- });
795
- return success("runtime", startedAt, cloneJobSnapshot(job), {
796
- sessionId: session.sessionId,
797
- revision: session.revision
798
- });
799
- }
800
- listJobs(input) {
801
- const startedAt = Date.now();
802
- const session = this.context.sessions.get(input.sessionId);
803
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
804
- let jobs = [...this.getJobs(input.sessionId)];
805
- if (input.kind) jobs = jobs.filter((job) => job.kind === input.kind);
806
- if (input.status) if (input.status === "active") jobs = jobs.filter((job) => !isTerminal(job.status));
807
- else if (input.status === "terminal") jobs = jobs.filter((job) => isTerminal(job.status));
808
- else jobs = jobs.filter((job) => job.status === input.status);
809
- if (input.limit !== void 0) jobs = jobs.slice(0, Math.max(0, input.limit));
810
- return success("runtime", startedAt, { jobs: jobs.map(cloneJobSnapshot) }, {
811
- sessionId: session.sessionId,
812
- revision: session.revision
813
- });
814
- }
815
- cancelJob(input) {
816
- const startedAt = Date.now();
817
- const session = this.context.sessions.get(input.sessionId);
818
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
819
- const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
820
- if (!job) return failure("runtime", startedAt, {
821
- code: "job_not_found",
822
- message: `Job was not found: ${input.jobId}`,
823
- sessionId: input.sessionId,
824
- jobId: input.jobId
825
- }, void 0, {
826
- sessionId: session.sessionId,
827
- revision: session.revision
828
- });
829
- if (isTerminal(job.status)) return failure("runtime", startedAt, {
830
- code: "job_not_cancellable",
831
- message: `Job is already terminal: ${input.jobId}`,
832
- sessionId: input.sessionId,
833
- jobId: input.jobId,
834
- status: job.status
835
- }, void 0, {
836
- sessionId: session.sessionId,
837
- revision: session.revision
838
- });
839
- this.cancellationRequests.add(job.jobId);
840
- this.eventService.emit({
841
- kind: "job.cancelRequested",
842
- sessionId: input.sessionId,
843
- canonicalPathKey: session.canonicalPathKey,
844
- revision: session.revision,
845
- jobId: job.jobId
846
- });
847
- return success("runtime", startedAt, cloneJobSnapshot(this.cancelRefreshJob(session.sessionId, job)), {
848
- sessionId: session.sessionId,
849
- revision: session.revision
850
- });
851
- }
852
- removeSession(sessionId) {
853
- for (const job of this.getJobs(sessionId)) this.cancellationRequests.delete(job.jobId);
854
- this.context.jobsBySession.delete(sessionId);
855
- }
856
- replaceJob(sessionId, nextJob) {
857
- const jobs = this.getJobs(sessionId).map((job) => job.jobId === nextJob.jobId ? nextJob : job);
858
- this.setJobs(sessionId, jobs);
859
- }
860
- scheduleRefreshJob(sessionId, jobId) {
861
- setTimeout(() => this.startRefreshJob(sessionId, jobId), REFRESH_START_DELAY_MS);
862
- }
863
- startRefreshJob(sessionId, jobId) {
864
- const session = this.context.sessions.get(sessionId);
865
- if (!session || session.closed) return;
866
- const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
867
- if (!job || isTerminal(job.status)) return;
868
- if (this.cancellationRequests.has(jobId)) {
869
- this.cancelRefreshJob(sessionId, job);
870
- return;
871
- }
872
- const running = {
873
- ...job,
874
- status: "running",
875
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
876
- progress: {
877
- completed: 0,
878
- total: 1,
879
- message: "refreshing cache"
880
- }
881
- };
882
- this.replaceJob(sessionId, running);
883
- this.eventService.emit({
884
- kind: "job.started",
885
- sessionId,
886
- canonicalPathKey: session.canonicalPathKey,
887
- revision: session.revision,
888
- jobId
889
- });
890
- this.eventService.emit({
891
- kind: "job.progress",
892
- sessionId,
893
- canonicalPathKey: session.canonicalPathKey,
894
- revision: session.revision,
895
- jobId,
896
- payload: running.progress
897
- });
898
- setTimeout(() => this.completeRefreshJob(sessionId, jobId), REFRESH_COMPLETE_DELAY_MS);
899
- }
900
- completeRefreshJob(sessionId, jobId) {
901
- const session = this.context.sessions.get(sessionId);
902
- if (!session || session.closed) return;
903
- const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
904
- if (!job || isTerminal(job.status)) return;
905
- if (this.cancellationRequests.has(jobId)) {
906
- this.cancelRefreshJob(sessionId, job);
907
- return;
908
- }
909
- try {
910
- const entry = this.cacheService.refreshSession(session);
911
- const completed = {
912
- ...job,
913
- status: "completed",
914
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
915
- cacheRevision: entry.revision,
916
- progress: {
917
- completed: 1,
918
- total: 1,
919
- message: "cache refreshed"
920
- },
921
- result: { cacheRevision: entry.revision }
922
- };
923
- this.replaceJob(sessionId, completed);
924
- this.eventService.emit({
925
- kind: "job.completed",
926
- sessionId,
927
- canonicalPathKey: session.canonicalPathKey,
928
- revision: session.revision,
929
- cacheRevision: entry.revision,
930
- jobId
931
- });
932
- this.eventService.emit({
933
- kind: "cache.updated",
934
- sessionId,
935
- canonicalPathKey: session.canonicalPathKey,
936
- revision: session.revision,
937
- cacheRevision: entry.revision
938
- });
939
- } catch (error) {
940
- const failed = {
941
- ...job,
942
- status: "failed",
943
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
944
- error: {
945
- code: "cache_refresh_failed",
946
- message: error instanceof Error ? error.message : "Cache refresh failed",
947
- sessionId,
948
- jobId
949
- }
950
- };
951
- this.replaceJob(sessionId, failed);
952
- this.eventService.emit({
953
- kind: "job.failed",
954
- sessionId,
955
- canonicalPathKey: session.canonicalPathKey,
956
- revision: session.revision,
957
- jobId,
958
- diagnostics: failed.diagnostics
959
- });
960
- }
961
- }
962
- cancelRefreshJob(sessionId, job) {
963
- const session = this.context.sessions.get(sessionId);
964
- const cancelled = {
965
- ...job,
966
- status: "cancelled",
967
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
968
- error: {
969
- code: "job_cancelled",
970
- message: `Job was cancelled: ${job.jobId}`,
971
- sessionId,
972
- jobId: job.jobId
973
- }
974
- };
975
- this.replaceJob(sessionId, cancelled);
976
- this.cancellationRequests.delete(job.jobId);
977
- this.eventService.emit({
978
- kind: "job.cancelled",
979
- sessionId,
980
- canonicalPathKey: session?.canonicalPathKey ?? job.canonicalPathKey,
981
- revision: session?.revision ?? job.revision,
982
- jobId: job.jobId
983
- });
984
- return cancelled;
985
- }
986
- };
987
- //#endregion
988
- //#region src/services/read-service.ts
989
- var ReadService = class {
990
- constructor(context) {
991
- this.context = context;
992
- }
993
- getCapabilities() {
994
- return success("read", Date.now(), cloneCapabilitiesSnapshot(this.context.capabilities));
995
- }
996
- getSession(input) {
997
- const startedAt = Date.now();
998
- const session = this.context.sessions.get(input.sessionId);
999
- if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
1000
- return success("read", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1001
- sessionId: session.sessionId,
1002
- revision: session.revision
1003
- });
1004
- }
1005
- };
1006
- //#endregion
1007
- //#region src/services/runtime-service.ts
1008
- function randomId() {
1009
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1010
- }
1011
- function createCapabilityUnavailableError(capability) {
1012
- const artifactCapability = capability === "artifact.publish" || capability === "artifact.restore";
1013
- return {
1014
- code: "capability_unavailable",
1015
- message: artifactCapability ? `${capability} requires the Node bridge boundary exposed by @openfairygui/backend/node.` : `${capability} requires an injected BackendFileSystem adapter.`,
1016
- capability,
1017
- requiredAdapter: capability === "fileSystem" ? "BackendFileSystem" : void 0,
1018
- requiredHost: artifactCapability ? "node" : void 0,
1019
- bridgeBoundary: artifactCapability ? "external-bridge" : void 0
1020
- };
1021
- }
1022
- function createProjectReaderFileSystem(fileSystem) {
1023
- return {
1024
- readFile(filePath) {
1025
- return fileSystem.readFile(filePath);
1026
- },
1027
- readFileRaw(filePath) {
1028
- return fileSystem.readFileRaw(filePath);
1029
- },
1030
- writeFile(filePath, content) {
1031
- return fileSystem.writeFile(filePath, content);
1032
- },
1033
- writeFileRaw(filePath, data) {
1034
- return fileSystem.writeFileRaw(filePath, data);
1035
- },
1036
- async mkdir(dirPath) {
1037
- await fileSystem.mkdir(dirPath, { recursive: true });
1038
- },
1039
- readdir(dirPath) {
1040
- return fileSystem.readdir(dirPath);
1041
- },
1042
- async exists(filePath) {
1043
- try {
1044
- await fileSystem.stat(filePath);
1045
- return true;
1046
- } catch {
1047
- return false;
1048
- }
1049
- },
1050
- join(...paths) {
1051
- return fileSystem.join(...paths);
1052
- },
1053
- dirname(filePath) {
1054
- return fileSystem.dirname(filePath);
1055
- }
1056
- };
1057
- }
1058
- var RuntimeService = class {
1059
- constructor(context, cacheService, eventService, jobService) {
1060
- this.context = context;
1061
- this.cacheService = cacheService;
1062
- this.eventService = eventService;
1063
- this.jobService = jobService;
1064
- }
1065
- async openSession(input) {
1066
- const startedAt = Date.now();
1067
- if (!this.context.fileSystem) return failure("runtime", startedAt, createCapabilityUnavailableError("fileSystem"));
1068
- const fileSystem = this.context.fileSystem;
1069
- const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
1070
- const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
1071
- const lockFilePath = fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
1072
- if (existingSessionId) return failure("runtime", startedAt, {
1073
- code: "lock_conflict",
1074
- kind: "in_process_session_exists",
1075
- message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
1076
- canonicalPathKey,
1077
- holderSessionId: existingSessionId,
1078
- lockFilePath
1079
- });
1080
- let advisoryLock = null;
1081
- try {
1082
- advisoryLock = await fileSystem.openExclusive(lockFilePath);
1083
- await advisoryLock.writeFile(JSON.stringify(this.context.host?.lockMetadata?.({
1084
- canonicalPathKey,
1085
- canonicalProjectPath,
1086
- lockFilePath
1087
- }) ?? {
1088
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1089
- canonicalPathKey
1090
- }));
1091
- await advisoryLock.close();
1092
- const project = liftDocumentToUamProject(await new ProjectReader(createProjectReaderFileSystem(fileSystem)).read(fairyPath));
1093
- const sessionId = randomId();
1094
- const session = {
1095
- sessionId,
1096
- fairyPath,
1097
- canonicalProjectPath,
1098
- canonicalPathKey,
1099
- lockFilePath,
1100
- fileSystem,
1101
- project,
1102
- revision: 0,
1103
- lastSavedRevision: 0,
1104
- dirty: false,
1105
- lockHeld: true,
1106
- closed: false
1107
- };
1108
- this.context.sessions.set(sessionId, session);
1109
- this.context.sessionsByPath.set(canonicalPathKey, sessionId);
1110
- this.cacheService.refreshSession(session);
1111
- this.eventService.emit({
1112
- kind: "session.opened",
1113
- sessionId,
1114
- canonicalPathKey,
1115
- revision: session.revision
1116
- });
1117
- return success("runtime", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1118
- sessionId: session.sessionId,
1119
- revision: session.revision
1120
- });
1121
- } catch (error) {
1122
- if (typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST") return failure("runtime", startedAt, {
1123
- code: "lock_conflict",
1124
- kind: "advisory_lock_conflict",
1125
- message: `Advisory lock already exists for project: ${canonicalProjectPath}`,
1126
- canonicalPathKey,
1127
- lockFilePath
1128
- });
1129
- if (advisoryLock) {
1130
- await advisoryLock.close().catch(() => void 0);
1131
- await fileSystem.unlink(lockFilePath).catch(() => void 0);
1132
- }
1133
- throw error;
1134
- }
1135
- }
1136
- openProjectSession(input) {
1137
- const startedAt = Date.now();
1138
- const sessionId = input.sessionId ?? randomId();
1139
- const storage = input.storage;
1140
- const memoryProjectPath = `memory://${sessionId}`;
1141
- const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
1142
- const canonicalPathKey = storage?.canonicalPathKey ?? input.canonicalPathKey ?? (storage ? normalizeComparablePath(canonicalProjectPath) : canonicalProjectPath.toLowerCase());
1143
- const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
1144
- if (existingSessionId) return failure("runtime", startedAt, {
1145
- code: "lock_conflict",
1146
- kind: "in_process_session_exists",
1147
- message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
1148
- canonicalPathKey,
1149
- holderSessionId: existingSessionId
1150
- });
1151
- const session = {
1152
- sessionId,
1153
- fairyPath: storage?.fairyPath ?? canonicalProjectPath,
1154
- canonicalProjectPath,
1155
- canonicalPathKey,
1156
- lockFilePath: "",
1157
- fileSystem: storage?.fileSystem,
1158
- project: normalizeUamProject(input.project),
1159
- revision: 0,
1160
- lastSavedRevision: 0,
1161
- dirty: false,
1162
- lockHeld: false,
1163
- closed: false
1164
- };
1165
- this.context.sessions.set(sessionId, session);
1166
- this.context.sessionsByPath.set(canonicalPathKey, sessionId);
1167
- this.cacheService.refreshSession(session);
1168
- this.eventService.emit({
1169
- kind: "session.opened",
1170
- sessionId,
1171
- canonicalPathKey,
1172
- revision: session.revision
1173
- });
1174
- return success("runtime", startedAt, toSessionSnapshot(session, this.context.capabilities), {
1175
- sessionId: session.sessionId,
1176
- revision: session.revision
1177
- });
1178
- }
1179
- async closeSession(input) {
1180
- const startedAt = Date.now();
1181
- const session = this.context.sessions.get(input.sessionId);
1182
- if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
1183
- this.eventService.emit({
1184
- kind: "session.closeRequested",
1185
- sessionId: session.sessionId,
1186
- canonicalPathKey: session.canonicalPathKey,
1187
- revision: session.revision
1188
- });
1189
- if (this.context.fileSystem && session.lockFilePath) await this.context.fileSystem.unlink(session.lockFilePath).catch(() => void 0);
1190
- session.lockHeld = false;
1191
- session.closed = true;
1192
- this.context.sessions.delete(session.sessionId);
1193
- this.context.sessionsByPath.delete(session.canonicalPathKey);
1194
- this.cacheService.removeSession(session.sessionId);
1195
- this.jobService.removeSession(session.sessionId);
1196
- this.eventService.emit({
1197
- kind: "session.closed",
1198
- sessionId: session.sessionId,
1199
- canonicalPathKey: session.canonicalPathKey,
1200
- revision: session.revision
1201
- });
1202
- this.eventService.removeSession(session.sessionId);
1203
- return success("runtime", startedAt, {
1204
- sessionId: session.sessionId,
1205
- closed: true
1206
- }, {
1207
- sessionId: session.sessionId,
1208
- revision: session.revision
1209
- });
1210
- }
1211
- };
1212
- //#endregion
1213
- //#region src/runtime.ts
1214
- const BACKEND_METHODS = [
1215
- "getCapabilities",
1216
- "openSession",
1217
- "openProjectSession",
1218
- "getSession",
1219
- "applyTransaction",
1220
- "saveSession",
1221
- "materializeSession",
1222
- "closeSession",
1223
- "getEvents",
1224
- "getJob",
1225
- "listJobs",
1226
- "cancelJob",
1227
- "getCacheSnapshot",
1228
- "refreshCache"
1229
- ];
1230
- const ARTIFACT_BRIDGE_CAPABILITY = {
1231
- available: false,
1232
- requiredHost: "node",
1233
- executionBoundary: "external-bridge",
1234
- bridgeEntrypoint: "@openfairygui/backend/node",
1235
- reason: "publish/restore require explicit Node-hosted filesystem and artifact execution."
1236
- };
1237
- function createCapabilities() {
1238
- return {
1239
- contractVersion: BACKEND_CONTRACT_VERSION,
1240
- capabilitySchemaVersion: 2,
1241
- transactionKernelOwner: "@openfairygui/core",
1242
- appSeamOwner: "@openfairygui/functions",
1243
- runtimeOwner: "@openfairygui/backend",
1244
- methods: BACKEND_METHODS,
1245
- read: {
1246
- capabilitySnapshot: true,
1247
- sessionSnapshot: true
1248
- },
1249
- authoring: {
1250
- applyTransaction: true,
1251
- saveSession: true,
1252
- resourceKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
1253
- nodeKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.nodeKinds],
1254
- gearKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.gearKinds],
1255
- transactionScope: {
1256
- resourceKinds: [...UAM_SUPPORTED_TRANSACTION_SCOPE.resourceKinds],
1257
- nodeKinds: [...UAM_SUPPORTED_TRANSACTION_SCOPE.nodeKinds],
1258
- gearKinds: [...UAM_SUPPORTED_TRANSACTION_SCOPE.gearKinds]
1259
- },
1260
- unsupported: ["artifact.publish", "artifact.restore"]
1261
- },
1262
- artifact: createArtifactCapabilities(),
1263
- manifest: {
1264
- browserSafe: true,
1265
- rootEntrypoint: "@openfairygui/backend",
1266
- nodeEntrypoint: "@openfairygui/backend/node",
1267
- adapters: {
1268
- fileSystem: {
1269
- injected: true,
1270
- requiredFor: [
1271
- "openSession",
1272
- "saveSession",
1273
- "materializeSession"
1274
- ]
1275
- },
1276
- projectStorage: {
1277
- injected: true,
1278
- browserSafe: true,
1279
- requiredFor: [
1280
- "openProjectSession.writeback",
1281
- "saveSession",
1282
- "materializeSession"
1283
- ],
1284
- adapterFactory: "createBackendStorageFileSystem"
1285
- },
1286
- host: {
1287
- injected: true,
1288
- requiredFor: ["advisoryLockMetadata"]
1289
- }
1290
- },
1291
- executionBoundaries: {
1292
- projectSession: "in-process-browser-safe",
1293
- fileBackedSession: "adapter-backed",
1294
- artifactPublish: ARTIFACT_BRIDGE_CAPABILITY,
1295
- artifactRestore: ARTIFACT_BRIDGE_CAPABILITY
1296
- },
1297
- diagnostics: {
1298
- stableCodes: true,
1299
- errorDiagnosticMirror: true
1300
- }
1301
- },
1302
- compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
1303
- runtime: {
1304
- sessionRuntime: true,
1305
- advisoryLocking: true,
1306
- coordinatedSave: true,
1307
- atomicSave: false,
1308
- staleRevisionProtection: true,
1309
- pathPolicy: createRuntimePathPolicy(),
1310
- events: {
1311
- polling: true,
1312
- subscriptions: false,
1313
- retentionLimit: 1e3,
1314
- sequenceScope: "runtime"
1315
- },
1316
- jobs: {
1317
- inMemory: true,
1318
- cooperativeCancel: true,
1319
- persistent: false,
1320
- supportedKinds: ["cache.refresh"],
1321
- artifactJobs: false,
1322
- completedRetentionLimit: 100
1323
- },
1324
- cache: {
1325
- derivedReadOnly: true,
1326
- keyedBy: "canonicalPathKey",
1327
- sourceOfTruth: false,
1328
- refreshMethod: "refreshCache"
1329
- }
1330
- }
1331
- };
1332
- }
1333
- var BackendRuntime = class {
1334
- fileSystem;
1335
- capabilities;
1336
- sessions = /* @__PURE__ */ new Map();
1337
- sessionsByPath = /* @__PURE__ */ new Map();
1338
- eventsBySession = /* @__PURE__ */ new Map();
1339
- jobsBySession = /* @__PURE__ */ new Map();
1340
- cacheBySession = /* @__PURE__ */ new Map();
1341
- eventSequence = 0;
1342
- context;
1343
- readService;
1344
- runtimeService;
1345
- authoringService;
1346
- cacheService;
1347
- eventService;
1348
- jobService;
1349
- constructor(options = {}) {
1350
- this.fileSystem = options.fileSystem;
1351
- this.capabilities = createCapabilities();
1352
- this.context = {
1353
- fileSystem: this.fileSystem,
1354
- host: options.host,
1355
- capabilities: this.capabilities,
1356
- sessions: this.sessions,
1357
- sessionsByPath: this.sessionsByPath,
1358
- eventsBySession: this.eventsBySession,
1359
- jobsBySession: this.jobsBySession,
1360
- cacheBySession: this.cacheBySession,
1361
- nextEventSequence: () => {
1362
- this.eventSequence += 1;
1363
- return this.eventSequence;
1364
- }
1365
- };
1366
- this.readService = new ReadService(this.context);
1367
- this.eventService = new EventService(this.context);
1368
- this.cacheService = new CacheService(this.context);
1369
- this.jobService = new JobService(this.context, this.cacheService, this.eventService);
1370
- this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService, this.jobService);
1371
- this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService);
1372
- }
1373
- getCapabilities() {
1374
- return this.readService.getCapabilities();
1375
- }
1376
- async openSession(input) {
1377
- return this.runtimeService.openSession(input);
1378
- }
1379
- openProjectSession(input) {
1380
- return this.runtimeService.openProjectSession(input);
1381
- }
1382
- getSession(input) {
1383
- return this.readService.getSession(input);
1384
- }
1385
- async applyTransaction(input) {
1386
- return this.authoringService.applyTransaction(input);
1387
- }
1388
- async saveSession(input) {
1389
- return this.authoringService.saveSession(input);
1390
- }
1391
- async materializeSession(input) {
1392
- return this.authoringService.materializeSession(input);
1393
- }
1394
- async closeSession(input) {
1395
- return this.runtimeService.closeSession(input);
1396
- }
1397
- getEvents(input) {
1398
- return this.eventService.getEvents(input);
1399
- }
1400
- getJob(input) {
1401
- return this.jobService.getJob(input);
1402
- }
1403
- listJobs(input) {
1404
- return this.jobService.listJobs(input);
1405
- }
1406
- cancelJob(input) {
1407
- return this.jobService.cancelJob(input);
1408
- }
1409
- getCacheSnapshot(input) {
1410
- return this.cacheService.getCacheSnapshot(input);
1411
- }
1412
- refreshCache(input) {
1413
- return this.jobService.refreshCache(input);
1414
- }
1415
- };
1416
- //#endregion
1417
- export { BACKEND_CONTRACT_VERSION as i, BACKEND_CAPABILITY_SCHEMA_VERSION as n, BACKEND_COMPATIBILITY_POLICY as r, BackendRuntime as t };