@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
@@ -1,274 +0,0 @@
1
- import { failure, success, cloneReadData, type ReadonlyData, type SessionLookup, type SessionReadView } from './context.js';
2
- import type {
3
- BackendCapabilities,
4
- BackendProjectOutline,
5
- BackendResult,
6
- BackendSessionSnapshot,
7
- GetProjectOutlineInput,
8
- QueryEntityInput,
9
- BackendEntitySnapshot,
10
- BackendResourceSnapshot,
11
- EntityQueryError,
12
- SessionNotFoundError,
13
- ReadSessionStateInput,
14
- ReadResourceBytesInput,
15
- BackendSessionStateSnapshot,
16
- BackendResourceBytesSnapshot,
17
- SessionReadError,
18
- SessionStaleReadError,
19
- } from '../runtime.js';
20
- import { createSessionNotFoundError, toSessionSnapshot } from './session-utils.js';
21
- import { validateProject } from '@openfairygui/functions';
22
- import type { ProjectValidationReport } from '@openfairygui/core';
23
- import { BACKEND_ENTITY_QUERY_LIMITS, BACKEND_RESOURCE_QUERY_FIELDS, BACKEND_SESSION_READ_LIMITS } from '../runtime/contracts.js';
24
-
25
- /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
26
- function queryResponseProblem(value: unknown, limits: { maxBytes: number; maxNodes: number; maxDepth: number } = BACKEND_ENTITY_QUERY_LIMITS): 'response_budget_exceeded' | 'non_json_value' | undefined {
27
- const pending = [{ value, depth: 0 }];
28
- let nodes = 0;
29
- let stringUnits = 0;
30
- while (pending.length) {
31
- const { value, depth } = pending.pop()!;
32
- if (++nodes > limits.maxNodes || depth > limits.maxDepth) return 'response_budget_exceeded';
33
- if (typeof value === 'string' && (stringUnits += value.length) > limits.maxBytes) return 'response_budget_exceeded';
34
- if (value === undefined || value === null || typeof value === 'string' || typeof value === 'boolean') continue;
35
- if (typeof value === 'number') { if (!Number.isFinite(value)) return 'non_json_value'; continue; }
36
- if (typeof value !== 'object' || (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) return 'non_json_value';
37
- if (Array.isArray(value) && value.length + pending.length + nodes > limits.maxNodes) return 'response_budget_exceeded';
38
- const entries = Object.entries(value);
39
- if (entries.length + pending.length + nodes > limits.maxNodes) return 'response_budget_exceeded';
40
- for (const [key, child] of entries) {
41
- if (!Array.isArray(value) && (stringUnits += key.length) > limits.maxBytes) return 'response_budget_exceeded';
42
- pending.push({ value: child, depth: depth + 1 });
43
- }
44
- }
45
- if (new TextEncoder().encode(JSON.stringify(value)).byteLength > limits.maxBytes) return 'response_budget_exceeded';
46
- return undefined;
47
- }
48
-
49
- function readFailure(startedAt: number, sessionId: string, reason: SessionReadError['reason'], revision?: number) {
50
- return failure('read', startedAt, {
51
- code: 'session_read_failed' as const, sessionId, reason, message: `Session read failed: ${reason}.`,
52
- }, undefined, { sessionId, revision });
53
- }
54
-
55
- function toProjectOutline(session: SessionReadView): BackendProjectOutline {
56
- const project = session.project;
57
- // ponytail: full outline is O(project size); add filters or pagination only if payload size becomes a measured problem.
58
- return {
59
- sessionId: session.sessionId,
60
- revision: session.revision,
61
- projectId: project.projectId,
62
- projectType: project.projectType,
63
- version: project.version,
64
- branches: [...project.branches],
65
- packages: project.packages.map((pkg) => ({
66
- id: pkg.id,
67
- name: pkg.name,
68
- branchNames: [...pkg.branchNames],
69
- folders: pkg.folders.map((folder) => ({ branch: folder.branch, path: folder.path })),
70
- resources: pkg.resources.map((resource) => ({
71
- id: resource.id,
72
- name: resource.name,
73
- path: resource.path,
74
- kind: resource.kind,
75
- branch: resource.branch,
76
- ...(resource.kind === 'component' ? {
77
- component: {
78
- displayList: resource.component.displayList.map((node) => ({
79
- id: node.id,
80
- name: node.name,
81
- kind: node.kind,
82
- })),
83
- controllers: resource.component.controllers.map((controller) => ({
84
- name: controller.name,
85
- pages: controller.pages.map((page) => ({ id: page.id, name: page.name })),
86
- })),
87
- transitions: resource.component.transitions.map((transition) => ({ name: transition.name })),
88
- },
89
- } : {}),
90
- })),
91
- })),
92
- };
93
- }
94
-
95
- export class ReadService {
96
- public constructor(private readonly getSessionState: SessionLookup, private readonly capabilities: ReadonlyData<BackendCapabilities>) {}
97
-
98
- public getCapabilities(): BackendResult<BackendCapabilities> {
99
- return success('read', Date.now(), cloneReadData<BackendCapabilities>(this.capabilities));
100
- }
101
-
102
- public getSession(input: { sessionId: string }): BackendResult<BackendSessionSnapshot, SessionNotFoundError> {
103
- const startedAt = Date.now();
104
- const session = this.getSessionState(input.sessionId);
105
- if (!session || session.closed) {
106
- return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
107
- }
108
- return success('read', startedAt, toSessionSnapshot(session, this.capabilities), {
109
- sessionId: session.sessionId,
110
- revision: session.revision,
111
- });
112
- }
113
-
114
- public getProjectOutline(
115
- input: GetProjectOutlineInput,
116
- ): BackendResult<BackendProjectOutline, SessionNotFoundError> {
117
- const startedAt = Date.now();
118
- const session = this.getSessionState(input.sessionId);
119
- if (!session || session.closed) {
120
- return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
121
- }
122
- return success('read', startedAt, toProjectOutline(session), {
123
- sessionId: session.sessionId,
124
- revision: session.revision,
125
- });
126
- }
127
-
128
- public queryEntity(input: QueryEntityInput): BackendResult<BackendEntitySnapshot, SessionNotFoundError | EntityQueryError> {
129
- const startedAt = Date.now();
130
- const session = this.getSessionState(input.sessionId);
131
- if (!session || session.closed) return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
132
- const meta = { sessionId: session.sessionId, revision: session.revision };
133
- const reject = (reason: EntityQueryError['reason']) => failure('read', startedAt, {
134
- code: 'entity_query_failed' as const, sessionId: session.sessionId, reason,
135
- message: `Entity query failed: ${reason}.`,
136
- }, undefined, meta);
137
- const target = input.target;
138
- if (!target || typeof target !== 'object' || Array.isArray(target) || Object.keys(target).some((key) => key !== 'kind' && key !== 'selector')) return reject('invalid_query');
139
- const respond = (entity: ReadonlyData<BackendEntitySnapshot['entity']>) => {
140
- const data = { ...meta, target, entity };
141
- const problem = queryResponseProblem(data);
142
- return problem ? reject(problem) : success('read', startedAt, cloneReadData<BackendEntitySnapshot>(data), meta);
143
- };
144
- if (target.kind === 'project') {
145
- if (Object.hasOwn(target, 'selector')) return reject('invalid_query');
146
- const { projectId, settings } = session.project;
147
- return respond({ kind: 'project', properties: { projectId, settings } });
148
- }
149
- const keys = target.kind === 'package' ? ['packageId']
150
- : target.kind === 'resource' ? ['packageId', 'resourceId']
151
- : target.kind === 'component' ? ['packageId', 'componentResourceId']
152
- : target.kind === 'displayNode' ? ['packageId', 'componentResourceId', 'displayNodeId']
153
- : target.kind === 'controller' ? ['packageId', 'componentResourceId', 'controllerName']
154
- : target.kind === 'transition' ? ['packageId', 'componentResourceId', 'transitionName'] : [];
155
- const selector = target.selector as unknown as Record<string, unknown>;
156
- if (!keys.length || !selector || typeof selector !== 'object' || Array.isArray(selector)
157
- || Object.keys(selector).length !== keys.length
158
- || keys.some((key) => !Object.hasOwn(selector, key) || typeof selector[key] !== 'string' || !(selector[key] as string).length || (selector[key] as string).length > 256)) return reject('invalid_query');
159
- const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
160
- if (packages.length !== 1) return reject(packages.length ? 'ambiguous' : 'not_found');
161
- if (target.kind === 'package') {
162
- const { id, name, compressPNG, jpegQuality, publish } = packages[0];
163
- return respond({ kind: 'package', properties: { id, name, settings: { compressPNG, jpegQuality, publish } } });
164
- }
165
- const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === 'resource' ? selector.resourceId : selector.componentResourceId));
166
- if (resources.length !== 1) return reject(resources.length ? 'ambiguous' : 'not_found');
167
- const resource = resources[0];
168
- let entity: ReadonlyData<BackendEntitySnapshot['entity']>;
169
- if (target.kind === 'resource') {
170
- const record = resource as unknown as Record<string, unknown>;
171
- entity = { kind: 'resource', properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS
172
- .filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]])) as BackendResourceSnapshot };
173
- } else {
174
- if (resource.kind !== 'component') return reject('not_found');
175
- if (target.kind === 'component') {
176
- const { size, properties, customData } = resource.component;
177
- entity = { kind: 'component', properties: { size, properties, customData } };
178
- } else if (target.kind === 'controller') {
179
- const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
180
- if (controllers.length !== 1) return reject(controllers.length ? 'ambiguous' : 'not_found');
181
- entity = { kind: 'controller', properties: controllers[0] };
182
- } else if (target.kind === 'transition') {
183
- const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
184
- if (transitions.length !== 1) return reject(transitions.length ? 'ambiguous' : 'not_found');
185
- entity = { kind: 'transition', properties: transitions[0] };
186
- } else {
187
- const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
188
- if (nodes.length !== 1) return reject(nodes.length ? 'ambiguous' : 'not_found');
189
- entity = { kind: 'displayNode', properties: nodes[0] };
190
- }
191
- }
192
- return respond(entity);
193
- }
194
-
195
- private resolveReadSession(input: ReadSessionStateInput, startedAt: number): BackendResult<SessionReadView, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
196
- if (!input || typeof input.sessionId !== 'string' || !input.sessionId.length || input.sessionId.length > 256
197
- || (input.expectedRevision !== undefined && (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0))) {
198
- return readFailure(startedAt, typeof input?.sessionId === 'string' ? input.sessionId : '', 'invalid_query');
199
- }
200
- const session = this.getSessionState(input.sessionId);
201
- if (!session || session.closed) return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
202
- const meta = { sessionId: session.sessionId, revision: session.revision };
203
- if (input.expectedRevision !== undefined && input.expectedRevision !== session.revision) return failure('read', startedAt, {
204
- code: 'stale_read', sessionId: session.sessionId, expectedRevision: input.expectedRevision, actualRevision: session.revision,
205
- message: 'The session edit revision changed. Restart the model and resource read.',
206
- }, undefined, meta);
207
- return success('read', startedAt, session, meta);
208
- }
209
-
210
- public readSessionState(input: ReadSessionStateInput): BackendResult<BackendSessionStateSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
211
- const startedAt = Date.now();
212
- const resolved = this.resolveReadSession(input, startedAt);
213
- if (!resolved.ok) return resolved;
214
- const session = resolved.data;
215
- const meta = { sessionId: session.sessionId, revision: session.revision };
216
- // Capture synchronously: pending transactions have not committed; save bookkeeping may change without an edit revision.
217
- const data: ReadonlyData<BackendSessionStateSnapshot> = {
218
- ...meta, dirty: session.dirty, lastSavedRevision: session.lastSavedRevision,
219
- uamFidelity: session.uamFidelity, readComplete: session.readComplete, readDiagnostics: session.readDiagnostics,
220
- project: { ...session.project, packages: session.project.packages.map((pkg) => ({
221
- ...pkg, resources: pkg.resources.map((resource) => {
222
- if (resource.kind === 'component') return resource;
223
- const { sourceBytes: _sourceBytes, ...model } = resource;
224
- return model;
225
- }),
226
- })) },
227
- };
228
- const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
229
- return problem ? readFailure(startedAt, session.sessionId, problem, session.revision)
230
- : success('read', startedAt, cloneReadData<BackendSessionStateSnapshot>(data), meta);
231
- }
232
-
233
- public readResourceBytes(input: ReadResourceBytesInput): BackendResult<BackendResourceBytesSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
234
- const startedAt = Date.now();
235
- const resolved = this.resolveReadSession(input, startedAt);
236
- if (!resolved.ok) return resolved;
237
- const session = resolved.data;
238
- const reject = (reason: SessionReadError['reason']) => readFailure(startedAt, session.sessionId, reason, session.revision);
239
- const selector = input.selector;
240
- if (input.expectedRevision === undefined || !selector || typeof selector !== 'object' || Array.isArray(selector)
241
- || Object.keys(selector).length !== 2 || ['packageId', 'resourceId'].some((key) => !Object.hasOwn(selector, key))
242
- || [selector.packageId, selector.resourceId].some((value) => typeof value !== 'string' || !value.length || value.length > 256)) return reject('invalid_query');
243
- const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
244
- if (packages.length !== 1) return reject(packages.length ? 'ambiguous' : 'not_found');
245
- const resources = packages[0].resources.filter((resource) => resource.id === selector.resourceId);
246
- if (resources.length !== 1) return reject(resources.length ? 'ambiguous' : 'not_found');
247
- const resource = resources[0];
248
- if (resource.kind === 'component') return reject('unsupported_resource');
249
- if (!(resource.sourceBytes instanceof Uint8Array)) return reject('bytes_unavailable');
250
- if (resource.sourceBytes.byteLength > BACKEND_SESSION_READ_LIMITS.resourceBytes) return reject('response_budget_exceeded');
251
- const meta = { sessionId: session.sessionId, revision: session.revision };
252
- return success('read', startedAt, { ...meta, selector: { ...selector }, sourceBytes: new Uint8Array(resource.sourceBytes) }, meta);
253
- }
254
-
255
- public validateSession(
256
- input: { sessionId: string },
257
- ): BackendResult<ProjectValidationReport, SessionNotFoundError> {
258
- const startedAt = Date.now();
259
- const session = this.getSessionState(input.sessionId);
260
- if (!session || session.closed) {
261
- return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
262
- }
263
- const report = validateProject(cloneReadData<import('@openfairygui/core/uam').UamProject>(session.project), {
264
- readDiagnostics: cloneReadData<import('@openfairygui/core').ProjectDiagnostic[]>(session.readDiagnostics),
265
- complete: session.readComplete,
266
- validateSources: true,
267
- });
268
- return success('read', startedAt, report, {
269
- sessionId: session.sessionId,
270
- revision: session.revision,
271
- diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({ code, message, severity, path, owner: 'core.validation' })),
272
- });
273
- }
274
- }
@@ -1,342 +0,0 @@
1
- import { capturedDirectoriesEqual, capturedFilesEqual, createCaptureFileSystem } from './capture-project.js';
2
- import { type FileSystem, ProjectReader, ProjectWriter } from '@openfairygui/core/project-io';
3
- import {
4
- liftDocumentToUamProject,
5
- materializeUamProject,
6
- normalizeUamProject,
7
- type UamProject,
8
- } from '@openfairygui/core/uam';
9
- import { assertProjectPathContained, normalizeComparablePath, resolveCanonicalProjectRoot } from '../path-policy.js';
10
- import type {
11
- AdvisoryLockConflictError,
12
- BackendCapabilityUnavailableError,
13
- BackendResult,
14
- BackendSessionLock,
15
- BackendSessionSnapshot,
16
- InProcessLockConflictError,
17
- OpenProjectSessionInput,
18
- ProjectRootNotAllowedError,
19
- SessionIdConflictError,
20
- SessionNotFoundError,
21
- SessionCloseFailedError,
22
- } from '../runtime.js';
23
- import type { CacheService } from './cache-service.js';
24
- import { type BackendContext, type BackendSessionState, failure, success } from './context.js';
25
- import type { EventService } from './event-service.js';
26
- import { createSessionNotFoundError, toSessionSnapshot } from './session-utils.js';
27
-
28
- function randomId(): string {
29
- return crypto.randomUUID();
30
- }
31
-
32
- function createCapabilityUnavailableError(
33
- capability: BackendCapabilityUnavailableError['capability'],
34
- ): BackendCapabilityUnavailableError {
35
- const artifactCapability = capability === 'artifact.publish' || capability === 'artifact.restore';
36
- return {
37
- code: 'capability_unavailable',
38
- message: artifactCapability
39
- ? `${capability} requires the Node bridge boundary exposed by @openfairygui/backend/node.`
40
- : `${capability} requires an injected BackendFileSystem adapter.`,
41
- capability,
42
- requiredAdapter: capability === 'fileSystem' ? 'BackendFileSystem' : undefined,
43
- requiredHost: artifactCapability ? 'node' : undefined,
44
- bridgeBoundary: artifactCapability ? 'external-bridge' : undefined,
45
- };
46
- }
47
-
48
- function createProjectReaderFileSystem(
49
- fileSystem: NonNullable<BackendContext['fileSystem']>,
50
- projectRoot: string,
51
- ): FileSystem {
52
- const contained = async <T>(filePath: string, operation: () => Promise<T>): Promise<T> => {
53
- await assertProjectPathContained(fileSystem, projectRoot, filePath);
54
- return operation();
55
- };
56
- return {
57
- stat: (path) => contained(path, () => fileSystem.stat(path)),
58
- readFile(filePath: string): Promise<string> {
59
- return contained(filePath, () => fileSystem.readFile(filePath));
60
- },
61
- readFileRaw(filePath: string): Promise<Uint8Array> {
62
- return contained(filePath, () => fileSystem.readFileRaw(filePath));
63
- },
64
- writeFile(filePath: string, content: string): Promise<void> {
65
- return contained(filePath, () => fileSystem.writeFile(filePath, content));
66
- },
67
- writeFileRaw(filePath: string, data: Uint8Array): Promise<void> {
68
- return contained(filePath, () => fileSystem.writeFileRaw(filePath, data));
69
- },
70
- async mkdir(dirPath: string): Promise<void> {
71
- await contained(dirPath, () => fileSystem.mkdir(dirPath, { recursive: true }));
72
- },
73
- readdir(dirPath: string): Promise<string[]> {
74
- return contained(dirPath, () => fileSystem.readdir(dirPath));
75
- },
76
- async exists(filePath: string): Promise<boolean> {
77
- try {
78
- await contained(filePath, () => fileSystem.stat(filePath));
79
- return true;
80
- } catch {
81
- return false;
82
- }
83
- },
84
- join(...paths: string[]): string {
85
- return fileSystem.join(...paths);
86
- },
87
- dirname(filePath: string): string {
88
- return fileSystem.dirname(filePath);
89
- },
90
- };
91
- }
92
-
93
- async function hasFullUamFidelity(
94
- document: Awaited<ReturnType<ProjectReader['read']>>,
95
- project: UamProject,
96
- ): Promise<boolean> {
97
- const sourceFiles = new Map<string, string | Uint8Array>();
98
- const materializedFiles = new Map<string, string | Uint8Array>();
99
- const sourceDirectories = new Set<string>();
100
- const materializedDirectories = new Set<string>();
101
- try {
102
- await Promise.all([
103
- new ProjectWriter(createCaptureFileSystem(sourceFiles, sourceDirectories)).write(document, 'Project.fairy'),
104
- new ProjectWriter(createCaptureFileSystem(materializedFiles, materializedDirectories)).write(
105
- materializeUamProject(project),
106
- 'Project.fairy',
107
- ),
108
- ]);
109
- } catch {
110
- return false;
111
- }
112
- return capturedFilesEqual(sourceFiles, materializedFiles)
113
- && capturedDirectoriesEqual(sourceDirectories, materializedDirectories);
114
- }
115
-
116
- export class RuntimeService {
117
- public constructor(
118
- private readonly context: BackendContext,
119
- private readonly cacheService: CacheService,
120
- private readonly eventService: EventService,
121
- ) {}
122
-
123
- public async openSession(input: {
124
- projectPath: string;
125
- }): Promise<
126
- BackendResult<
127
- BackendSessionSnapshot,
128
- InProcessLockConflictError | AdvisoryLockConflictError | BackendCapabilityUnavailableError | ProjectRootNotAllowedError
129
- >
130
- > {
131
- const startedAt = Date.now();
132
- if (!this.context.fileSystem) {
133
- return failure('runtime', startedAt, createCapabilityUnavailableError('fileSystem'));
134
- }
135
- const fileSystem = this.context.fileSystem;
136
- if (this.context.allowedProjectRoots?.length) {
137
- let allowed = false;
138
- for (const root of this.context.allowedProjectRoots) {
139
- try {
140
- await assertProjectPathContained(fileSystem, root, input.projectPath);
141
- allowed = true;
142
- break;
143
- } catch (error) {
144
- if ((error as { code?: unknown }).code !== 'EACCES') throw error;
145
- }
146
- }
147
- if (!allowed) {
148
- return failure('runtime', startedAt, {
149
- code: 'project_root_not_allowed',
150
- message: 'Project path is outside the configured allowed roots.',
151
- projectPath: input.projectPath,
152
- });
153
- }
154
- }
155
- const resolved = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
156
- const { fairyPath, canonicalProjectPath, canonicalPathKey } = resolved;
157
- await fileSystem.validateProjectRoot?.(canonicalProjectPath);
158
- const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath)
159
- ?? fileSystem.join(canonicalProjectPath, '.openfairygui.backend.lock');
160
- const sessionId = randomId();
161
- const reservation = this.context.sessions.reserve(sessionId, { canonicalPathKey, canonicalProjectPath, lockFilePath });
162
- if ('code' in reservation) return failure('runtime', startedAt, reservation);
163
-
164
- let sessionLock: BackendSessionLock | null = null;
165
- try {
166
- sessionLock = await fileSystem.acquireSessionLock(lockFilePath);
167
- await sessionLock.writeMetadata(
168
- JSON.stringify(
169
- this.context.host?.lockMetadata?.({
170
- canonicalPathKey,
171
- canonicalProjectPath,
172
- lockFilePath,
173
- }) ?? {
174
- createdAt: new Date().toISOString(),
175
- canonicalPathKey,
176
- },
177
- ),
178
- );
179
- const reader = new ProjectReader(createProjectReaderFileSystem(fileSystem, canonicalProjectPath));
180
- const read = await reader.readDetailed(fairyPath, { hydrateResourceBytes: true });
181
- if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
182
- const document = read.document;
183
- const project = liftDocumentToUamProject(document);
184
- const session: BackendSessionState = {
185
- sessionId,
186
- fairyPath,
187
- canonicalProjectPath,
188
- canonicalPathKey,
189
- lockFilePath,
190
- sessionLock,
191
- fileSystem,
192
- project,
193
- readDiagnostics: read.diagnostics,
194
- readComplete: read.complete,
195
- uamFidelity: read.complete && (await hasFullUamFidelity(document, project)) ? 'full' : 'unsupported',
196
- revision: 0,
197
- lastSavedRevision: 0,
198
- pendingStaleSourceFiles: new Map(),
199
- pendingStaleResourceFolders: new Map(),
200
- pendingStaleBranchDirectories: new Map(),
201
- dirty: false,
202
- lockHeld: true,
203
- closed: false,
204
- };
205
- reservation.commit(session);
206
- this.cacheService.refreshSession(session);
207
- this.eventService.emit({ kind: 'session.opened', sessionId, canonicalPathKey, revision: session.revision });
208
-
209
- return success('runtime', startedAt, toSessionSnapshot(session, this.context.capabilities), {
210
- sessionId: session.sessionId,
211
- revision: session.revision,
212
- });
213
- } catch (error) {
214
- if (sessionLock) await sessionLock.release().catch(() => undefined);
215
- if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EEXIST') {
216
- return failure('runtime', startedAt, {
217
- code: 'lock_conflict',
218
- kind: 'advisory_lock_conflict',
219
- message: `Advisory lock already exists for project: ${canonicalProjectPath}`,
220
- canonicalPathKey,
221
- lockFilePath,
222
- });
223
- }
224
- if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOTSUP') {
225
- return failure('runtime', startedAt, {
226
- ...createCapabilityUnavailableError('fileSystem'),
227
- message: error instanceof Error ? error.message : String(error),
228
- });
229
- }
230
- throw error;
231
- } finally {
232
- reservation.release();
233
- }
234
- }
235
-
236
- public openProjectSession(
237
- input: OpenProjectSessionInput,
238
- ): BackendResult<BackendSessionSnapshot, InProcessLockConflictError | SessionIdConflictError> {
239
- const startedAt = Date.now();
240
- const sessionId = input.sessionId ?? randomId();
241
- if (this.context.sessions.has(sessionId)) {
242
- return failure('runtime', startedAt, {
243
- code: 'session_id_conflict',
244
- message: `Session id is already in use: ${sessionId}`,
245
- sessionId,
246
- });
247
- }
248
- const storage = input.storage;
249
- const memoryProjectPath = `memory://${sessionId}`;
250
- const canonicalProjectPath =
251
- storage?.canonicalProjectPath ??
252
- input.canonicalProjectPath ??
253
- (storage ? storage.fileSystem.dirname(storage.fairyPath) || '.' : memoryProjectPath);
254
- const canonicalPathKey =
255
- storage?.canonicalPathKey ??
256
- input.canonicalPathKey ??
257
- (storage ? normalizeComparablePath(canonicalProjectPath) : canonicalProjectPath.toLowerCase());
258
- // Normalize before claiming a path: malformed native input must not leave a reservation behind.
259
- const project = normalizeUamProject(input.project);
260
- const reservation = this.context.sessions.reserve(sessionId, { canonicalPathKey, canonicalProjectPath });
261
- if ('code' in reservation) return failure('runtime', startedAt, reservation);
262
-
263
- const session: BackendSessionState = {
264
- sessionId,
265
- fairyPath: storage?.fairyPath ?? canonicalProjectPath,
266
- canonicalProjectPath,
267
- canonicalPathKey,
268
- lockFilePath: '',
269
- sessionLock: null,
270
- fileSystem: storage?.fileSystem,
271
- project,
272
- readDiagnostics: [],
273
- readComplete: true,
274
- uamFidelity: 'full',
275
- revision: 0,
276
- lastSavedRevision: 0,
277
- pendingStaleSourceFiles: new Map(),
278
- pendingStaleResourceFolders: new Map(),
279
- pendingStaleBranchDirectories: new Map(),
280
- dirty: false,
281
- lockHeld: false,
282
- closed: false,
283
- };
284
- reservation.commit(session);
285
- this.cacheService.refreshSession(session);
286
- this.eventService.emit({ kind: 'session.opened', sessionId, canonicalPathKey, revision: session.revision });
287
-
288
- return success('runtime', startedAt, toSessionSnapshot(session, this.context.capabilities), {
289
- sessionId: session.sessionId,
290
- revision: session.revision,
291
- });
292
- }
293
-
294
- public async closeSession(input: {
295
- sessionId: string;
296
- }): Promise<BackendResult<{ sessionId: string; closed: true }, SessionNotFoundError | SessionCloseFailedError>> {
297
- const startedAt = Date.now();
298
- const session = this.context.sessions.get(input.sessionId);
299
- if (!session || session.closed) {
300
- return failure('runtime', startedAt, createSessionNotFoundError(input.sessionId));
301
- }
302
-
303
- this.eventService.emit({
304
- kind: 'session.closeRequested',
305
- sessionId: session.sessionId,
306
- canonicalPathKey: session.canonicalPathKey,
307
- revision: session.revision,
308
- });
309
- try {
310
- await session.sessionLock?.release();
311
- } catch (error) {
312
- return failure('runtime', startedAt, {
313
- code: 'session_close_failed',
314
- message: error instanceof Error ? error.message : String(error),
315
- sessionId: session.sessionId,
316
- lockFilePath: session.lockFilePath,
317
- }, toSessionSnapshot(session, this.context.capabilities), { sessionId: session.sessionId, revision: session.revision });
318
- }
319
- session.sessionLock = null;
320
- session.lockHeld = false;
321
- session.closed = true;
322
- this.context.sessions.remove(session);
323
- this.cacheService.removeSession(session.sessionId);
324
- this.eventService.emit({
325
- kind: 'session.closed',
326
- sessionId: session.sessionId,
327
- canonicalPathKey: session.canonicalPathKey,
328
- revision: session.revision,
329
- });
330
- this.eventService.removeSession(session.sessionId);
331
-
332
- return success(
333
- 'runtime',
334
- startedAt,
335
- {
336
- sessionId: session.sessionId,
337
- closed: true,
338
- },
339
- { sessionId: session.sessionId, revision: session.revision },
340
- );
341
- }
342
- }
@@ -1,21 +0,0 @@
1
- /** Serializes lifecycle and authoring operations for one session, without blocking other sessions. */
2
- export class SessionOperationQueue {
3
- private readonly operations = new Map<string, Promise<void>>();
4
-
5
- public async run<T>(sessionId: string, operation: () => Promise<T>): Promise<T> {
6
- const previous = this.operations.get(sessionId) ?? Promise.resolve();
7
- let release = (): void => undefined;
8
- const current = new Promise<void>((resolve) => {
9
- release = resolve;
10
- });
11
- const tail = previous.then(() => current);
12
- this.operations.set(sessionId, tail);
13
- await previous;
14
- try {
15
- return await operation();
16
- } finally {
17
- release();
18
- if (this.operations.get(sessionId) === tail) this.operations.delete(sessionId);
19
- }
20
- }
21
- }