@openfairygui/backend 0.6.2 → 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 +11506 -5902
  8. package/dist/docs.d.cts +5 -185
  9. package/dist/docs.d.mts +5 -185
  10. package/dist/docs.mjs +11504 -5901
  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 -24165
  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
package/src/runtime.ts DELETED
@@ -1,231 +0,0 @@
1
- import type { ApplyUamTransactionAppError } from '@openfairygui/functions/uam';
2
- import type { ProjectValidationReport } from '@openfairygui/core';
3
- import type { PathPolicyViolationError } from './path-policy.js';
4
- import { AuthoringService } from './services/authoring-service.js';
5
- import { PersistenceService } from './services/persistence-service.js';
6
- import { CacheService } from './services/cache-service.js';
7
- import { type BackendContext, failure, readView } from './services/context.js';
8
- import { SessionRegistry } from './services/session-registry.js';
9
- import { SessionOperationQueue } from './services/session-operation-queue.js';
10
- import { EventService } from './services/event-service.js';
11
- import { ReadService } from './services/read-service.js';
12
- import { RuntimeService } from './services/runtime-service.js';
13
- import { createCapabilities } from './runtime/capabilities.js';
14
- import type {
15
- AdvisoryLockConflictError,
16
- ApplySessionTransactionInput,
17
- BackendCacheSnapshot,
18
- BackendCapabilities,
19
- BackendCapabilityUnavailableError,
20
- BackendFileSystem,
21
- BackendProjectOutline,
22
- BackendResult,
23
- BackendRuntimeOptions,
24
- BackendSessionSnapshot,
25
- BackendSuccess,
26
- BackendTransactionPreview,
27
- EventCursorInvalidError,
28
- GetCacheSnapshotInput,
29
- GetEventsInput,
30
- GetEventsSnapshot,
31
- GetProjectOutlineInput,
32
- QueryEntityInput,
33
- BackendEntitySnapshot,
34
- EntityQueryError,
35
- ReadSessionStateInput,
36
- ReadResourceBytesInput,
37
- BackendSessionStateSnapshot,
38
- BackendResourceBytesSnapshot,
39
- SessionReadError,
40
- SessionStaleReadError,
41
- ValidateSessionInput,
42
- InProcessLockConflictError,
43
- MaterializeSessionInput,
44
- MaterializeSessionSnapshot,
45
- MaterializeValidationFailedError,
46
- MaterializeWriteFailedError,
47
- OpenProjectSessionInput,
48
- ProjectOpenFailedError,
49
- ProjectRootNotAllowedError,
50
- RefreshCacheInput,
51
- SavePartialFailureError,
52
- SaveSessionInput,
53
- SessionIdConflictError,
54
- SessionNotFoundError,
55
- SessionCloseFailedError,
56
- SessionStaleWriteError,
57
- TransactionPreviewError,
58
- UamFidelityUnsupportedError,
59
- } from './runtime/contracts.js';
60
-
61
- export * from './runtime/contracts.js';
62
-
63
- export class BackendRuntime {
64
- private readonly fileSystem?: BackendFileSystem;
65
- private readonly capabilities: BackendCapabilities;
66
- private readonly sessions = new SessionRegistry();
67
- private readonly sessionOperations = new SessionOperationQueue();
68
- private readonly context: BackendContext;
69
- private readonly readService: ReadService;
70
- private readonly runtimeService: RuntimeService;
71
- private readonly authoringService: AuthoringService;
72
- private readonly persistenceService: PersistenceService;
73
- private readonly cacheService: CacheService;
74
- private readonly eventService: EventService;
75
-
76
- public constructor(options: BackendRuntimeOptions = {}) {
77
- this.fileSystem = options.fileSystem;
78
- this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
79
- this.context = {
80
- fileSystem: this.fileSystem,
81
- host: options.host,
82
- allowedProjectRoots: options.allowedProjectRoots,
83
- capabilities: this.capabilities,
84
- sessions: this.sessions,
85
- };
86
- const getSession = (sessionId: string) => this.sessions.get(sessionId);
87
- this.readService = new ReadService((sessionId) => readView(getSession(sessionId)), this.capabilities);
88
- this.eventService = new EventService(getSession);
89
- this.cacheService = new CacheService(getSession, this.eventService);
90
- this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService);
91
- this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService, this.sessionOperations);
92
- this.persistenceService = new PersistenceService(this.context, this.cacheService, this.eventService, this.sessionOperations);
93
- }
94
-
95
- public getCapabilities(): BackendSuccess<BackendCapabilities> {
96
- return this.readService.getCapabilities() as BackendSuccess<BackendCapabilities>;
97
- }
98
-
99
- public async openSession(input: {
100
- projectPath: string;
101
- }): Promise<
102
- BackendResult<
103
- BackendSessionSnapshot,
104
- InProcessLockConflictError
105
- | AdvisoryLockConflictError
106
- | BackendCapabilityUnavailableError
107
- | ProjectRootNotAllowedError
108
- | ProjectOpenFailedError
109
- >
110
- > {
111
- const startedAt = Date.now();
112
- try {
113
- return await this.runtimeService.openSession(input);
114
- } catch {
115
- return failure('runtime', startedAt, {
116
- code: 'project_open_failed',
117
- message: 'Unable to open project.',
118
- projectPath: input.projectPath,
119
- });
120
- }
121
- }
122
-
123
- public openProjectSession(
124
- input: OpenProjectSessionInput,
125
- ): BackendResult<BackendSessionSnapshot, InProcessLockConflictError | SessionIdConflictError> {
126
- return this.runtimeService.openProjectSession(input);
127
- }
128
-
129
- public getSession(input: { sessionId: string }): BackendResult<BackendSessionSnapshot, SessionNotFoundError> {
130
- return this.readService.getSession(input);
131
- }
132
-
133
- public getProjectOutline(
134
- input: GetProjectOutlineInput,
135
- ): BackendResult<BackendProjectOutline, SessionNotFoundError> {
136
- return this.readService.getProjectOutline(input);
137
- }
138
-
139
- public queryEntity(input: QueryEntityInput): BackendResult<BackendEntitySnapshot, SessionNotFoundError | EntityQueryError> {
140
- return this.readService.queryEntity(input);
141
- }
142
-
143
- public readSessionState(input: ReadSessionStateInput): BackendResult<BackendSessionStateSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
144
- return this.readService.readSessionState(input);
145
- }
146
-
147
- public readResourceBytes(input: ReadResourceBytesInput): BackendResult<BackendResourceBytesSnapshot, SessionNotFoundError | SessionReadError | SessionStaleReadError> {
148
- return this.readService.readResourceBytes(input);
149
- }
150
-
151
- public validateSession(
152
- input: ValidateSessionInput,
153
- ): BackendResult<ProjectValidationReport, SessionNotFoundError> {
154
- return this.readService.validateSession(input);
155
- }
156
-
157
- public async preflightTransaction(
158
- input: ApplySessionTransactionInput,
159
- ): Promise<BackendResult<BackendTransactionPreview, SessionNotFoundError | SessionStaleWriteError | ApplyUamTransactionAppError | TransactionPreviewError>> {
160
- return this.authoringService.preflightTransaction(input);
161
- }
162
-
163
- public async applyTransaction(
164
- input: ApplySessionTransactionInput,
165
- ): Promise<
166
- BackendResult<
167
- BackendSessionSnapshot,
168
- SessionNotFoundError | SessionStaleWriteError | ApplyUamTransactionAppError
169
- >
170
- > {
171
- return this.authoringService.applyTransaction(input);
172
- }
173
-
174
- public async saveSession(
175
- input: SaveSessionInput,
176
- ): Promise<
177
- BackendResult<
178
- BackendSessionSnapshot | MaterializeSessionSnapshot,
179
- | SessionNotFoundError
180
- | SessionStaleWriteError
181
- | SavePartialFailureError
182
- | UamFidelityUnsupportedError
183
- | MaterializeValidationFailedError
184
- | MaterializeWriteFailedError
185
- | PathPolicyViolationError
186
- | InProcessLockConflictError
187
- | BackendCapabilityUnavailableError
188
- >
189
- > {
190
- return this.persistenceService.saveSession(input);
191
- }
192
-
193
- public async materializeSession(
194
- input: MaterializeSessionInput,
195
- ): Promise<
196
- BackendResult<
197
- MaterializeSessionSnapshot,
198
- | SessionNotFoundError
199
- | SessionStaleWriteError
200
- | UamFidelityUnsupportedError
201
- | MaterializeValidationFailedError
202
- | MaterializeWriteFailedError
203
- | PathPolicyViolationError
204
- | InProcessLockConflictError
205
- | BackendCapabilityUnavailableError
206
- >
207
- > {
208
- return this.persistenceService.materializeSession(input);
209
- }
210
-
211
- public async closeSession(input: {
212
- sessionId: string;
213
- }): Promise<BackendResult<{ sessionId: string; closed: true }, SessionNotFoundError | SessionCloseFailedError>> {
214
- const captured = { ...input };
215
- return this.sessionOperations.run(captured.sessionId, () => this.runtimeService.closeSession(captured));
216
- }
217
-
218
- public getEvents(
219
- input: GetEventsInput,
220
- ): BackendResult<GetEventsSnapshot, SessionNotFoundError | EventCursorInvalidError> {
221
- return this.eventService.getEvents(input);
222
- }
223
-
224
- public getCacheSnapshot(input: GetCacheSnapshotInput): BackendResult<BackendCacheSnapshot, SessionNotFoundError> {
225
- return this.cacheService.getCacheSnapshot(input);
226
- }
227
-
228
- public refreshCache(input: RefreshCacheInput): BackendResult<BackendCacheSnapshot, SessionNotFoundError> {
229
- return this.cacheService.refreshCache(input);
230
- }
231
- }
@@ -1,19 +0,0 @@
1
- import type { BackendCapabilities } from '../runtime.js';
2
-
3
- export function createArtifactCapabilities(): BackendCapabilities['artifact'] {
4
- const bridge = {
5
- available: false,
6
- requiredHost: 'node',
7
- executionBoundary: 'external-bridge',
8
- bridgeEntrypoint: '@openfairygui/backend/node',
9
- reason: 'publish/restore require explicit Node-hosted filesystem and artifact execution.',
10
- } as const;
11
-
12
- return {
13
- publish: false,
14
- restore: false,
15
- status: 'bridge-required',
16
- publishBridge: bridge,
17
- restoreBridge: bridge,
18
- };
19
- }
@@ -1,229 +0,0 @@
1
- import type { ProjectBranchDirectory, ProjectResourceFolder, ProjectSourceFile } from '@openfairygui/core/project-io';
2
- import { staleBranchDirectories, staleResourceFolders, staleSourceFiles, type UamProject } from '@openfairygui/core/uam';
3
- import { type ApplyUamTransactionAppError, applyUamTransactionAppAsync } from '@openfairygui/functions/uam';
4
- import type { BackendDiagnostic } from '../contracts.js';
5
- import type { ApplySessionTransactionInput, BackendResult, BackendSessionSnapshot, BackendTransactionPreview, SessionNotFoundError, SessionStaleWriteError, TransactionPreviewError } from '../runtime/contracts.js';
6
- import type { CacheService } from './cache-service.js';
7
- import { type BackendContext, type BackendSessionState, failure, success } from './context.js';
8
- import type { EventService } from './event-service.js';
9
- import type { SessionOperationQueue } from './session-operation-queue.js';
10
- import { createSessionNotFoundError, createStaleWriteError, toSessionSnapshot } from './session-utils.js';
11
- import { PreviewBudgetError, previewTransactionImpact } from './transaction-preview.js';
12
-
13
- function sourceFileKey(source: ProjectSourceFile): string {
14
- return [source.branch, source.packageName, source.path, source.fileName].join('\0');
15
- }
16
-
17
- function resourceFolderKey(folder: ProjectResourceFolder): string {
18
- return [folder.branch, folder.packageName, folder.path].join('\0');
19
- }
20
-
21
- function branchDirectoryKey(directory: ProjectBranchDirectory): string {
22
- return [directory.branch, directory.packageName ?? ''].join('\0');
23
- }
24
-
25
- function recordStaleProjectFiles(
26
- session: BackendSessionState,
27
- previousProject: UamProject,
28
- nextProject: UamProject,
29
- ): void {
30
- if (!session.fileSystem) return;
31
- for (const source of staleSourceFiles(previousProject, nextProject)) {
32
- session.pendingStaleSourceFiles.set(sourceFileKey(source), source);
33
- }
34
- for (const source of staleSourceFiles(nextProject, previousProject)) {
35
- session.pendingStaleSourceFiles.delete(sourceFileKey(source));
36
- }
37
- for (const folder of staleResourceFolders(previousProject, nextProject)) {
38
- session.pendingStaleResourceFolders.set(resourceFolderKey(folder), folder);
39
- }
40
- for (const folder of staleResourceFolders(nextProject, previousProject)) {
41
- session.pendingStaleResourceFolders.delete(resourceFolderKey(folder));
42
- }
43
- for (const directory of staleBranchDirectories(previousProject, nextProject)) {
44
- session.pendingStaleBranchDirectories.set(branchDirectoryKey(directory), directory);
45
- }
46
- for (const directory of staleBranchDirectories(nextProject, previousProject)) {
47
- session.pendingStaleBranchDirectories.delete(branchDirectoryKey(directory));
48
- }
49
- }
50
-
51
- function toBackendDiagnostics(error: ApplyUamTransactionAppError): BackendDiagnostic[] {
52
- return error.diagnostics.length > 0
53
- ? error.diagnostics.map((diagnostic) => ({ ...diagnostic, owner: 'core.transaction' }))
54
- : [
55
- {
56
- code: error.code,
57
- owner: 'core.transaction',
58
- message: error.message,
59
- severity: 'error',
60
- operationKind: error.operationKind,
61
- opIndex: error.opIndex,
62
- opId: error.opId,
63
- },
64
- ];
65
- }
66
-
67
- function detachSharedByteViews(value: unknown, seen = new WeakSet<object>()): void {
68
- if (!value || typeof value !== 'object' || seen.has(value)) return;
69
- seen.add(value);
70
- for (const [key, child] of Object.entries(value)) {
71
- if (child instanceof Uint8Array) {
72
- if (typeof SharedArrayBuffer !== 'undefined' && child.buffer instanceof SharedArrayBuffer) {
73
- (value as Record<string, unknown>)[key] = new Uint8Array(child);
74
- }
75
- continue;
76
- }
77
- detachSharedByteViews(child, seen);
78
- }
79
- }
80
-
81
- export class AuthoringService {
82
- public constructor(
83
- private readonly context: Pick<BackendContext, 'capabilities'> & { sessions: Pick<BackendContext['sessions'], 'get'> },
84
- private readonly cacheService: CacheService,
85
- private readonly eventService: EventService,
86
- private readonly sessionOperations: SessionOperationQueue,
87
- ) {}
88
-
89
- public async preflightTransaction(
90
- input: ApplySessionTransactionInput,
91
- ): Promise<BackendResult<BackendTransactionPreview, SessionNotFoundError | SessionStaleWriteError | ApplyUamTransactionAppError | TransactionPreviewError>> {
92
- const queuedInput = structuredClone(input);
93
- detachSharedByteViews(queuedInput);
94
- return this.sessionOperations.run(queuedInput.sessionId, async () => {
95
- const startedAt = Date.now();
96
- const session = this.context.sessions.get(queuedInput.sessionId);
97
- if (!session || session.closed) return failure('authoring', startedAt, createSessionNotFoundError(queuedInput.sessionId));
98
- const meta = { sessionId: session.sessionId, revision: session.revision };
99
- if (queuedInput.expectedRevision !== session.revision) {
100
- return failure('authoring', startedAt, createStaleWriteError(session, queuedInput.expectedRevision),
101
- toSessionSnapshot(session, this.context.capabilities), meta);
102
- }
103
- // The authoritative session, including source bytes, never enters the preview executor.
104
- const project = structuredClone(session.project);
105
- detachSharedByteViews(project);
106
- const result = await applyUamTransactionAppAsync({ project, operations: queuedInput.operations });
107
- if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) {
108
- return failure('authoring', startedAt, createSessionNotFoundError(queuedInput.sessionId));
109
- }
110
- if (!result.ok) {
111
- return failure('authoring', startedAt, result.error, toSessionSnapshot(session, this.context.capabilities),
112
- { ...meta, diagnostics: toBackendDiagnostics(result.error) });
113
- }
114
- try {
115
- const preview = await previewTransactionImpact({ ...session, project }, result.project, Boolean(session.fileSystem));
116
- if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) {
117
- return failure('authoring', startedAt, createSessionNotFoundError(queuedInput.sessionId));
118
- }
119
- return success('authoring', startedAt, preview, meta);
120
- } catch (error) {
121
- return failure('authoring', startedAt, {
122
- code: 'transaction_preview_failed' as const, sessionId: session.sessionId,
123
- reason: error instanceof PreviewBudgetError ? 'response_budget_exceeded' as const : 'projection_failed' as const,
124
- message: error instanceof Error ? error.message : String(error),
125
- }, toSessionSnapshot(session, this.context.capabilities), meta);
126
- }
127
- });
128
- }
129
-
130
- public async applyTransaction(
131
- input: ApplySessionTransactionInput,
132
- ): Promise<
133
- BackendResult<
134
- BackendSessionSnapshot,
135
- SessionNotFoundError | SessionStaleWriteError | ApplyUamTransactionAppError
136
- >
137
- > {
138
- const queuedInput = structuredClone(input);
139
- detachSharedByteViews(queuedInput);
140
- return this.sessionOperations.run(queuedInput.sessionId, () => this.applyTransactionExclusive(queuedInput));
141
- }
142
-
143
- private async applyTransactionExclusive(
144
- input: ApplySessionTransactionInput,
145
- ): Promise<
146
- BackendResult<
147
- BackendSessionSnapshot,
148
- SessionNotFoundError | SessionStaleWriteError | ApplyUamTransactionAppError
149
- >
150
- > {
151
- const startedAt = Date.now();
152
- const session = this.context.sessions.get(input.sessionId);
153
- if (!session || session.closed) {
154
- return failure('authoring', startedAt, createSessionNotFoundError(input.sessionId));
155
- }
156
- if (input.expectedRevision !== session.revision) {
157
- this.eventService.emit({
158
- kind: 'transaction.rejected',
159
- sessionId: session.sessionId,
160
- canonicalPathKey: session.canonicalPathKey,
161
- revision: session.revision,
162
- });
163
- return failure(
164
- 'authoring',
165
- startedAt,
166
- createStaleWriteError(session, input.expectedRevision),
167
- toSessionSnapshot(session, this.context.capabilities),
168
- {
169
- sessionId: session.sessionId,
170
- revision: session.revision,
171
- },
172
- );
173
- }
174
-
175
- const result = await applyUamTransactionAppAsync({
176
- project: session.project,
177
- operations: input.operations,
178
- });
179
- if (this.context.sessions.get(input.sessionId) !== session || session.closed) {
180
- return failure('authoring', startedAt, createSessionNotFoundError(input.sessionId));
181
- }
182
- if (result.ok === false) {
183
- const diagnostics = toBackendDiagnostics(result.error);
184
- this.eventService.emit({
185
- kind: 'transaction.rejected',
186
- sessionId: session.sessionId,
187
- canonicalPathKey: session.canonicalPathKey,
188
- revision: session.revision,
189
- diagnostics,
190
- });
191
- return failure(
192
- 'authoring',
193
- startedAt,
194
- result.error,
195
- toSessionSnapshot(session, this.context.capabilities),
196
- {
197
- sessionId: session.sessionId,
198
- revision: session.revision,
199
- diagnostics,
200
- },
201
- );
202
- }
203
-
204
- recordStaleProjectFiles(session, session.project, result.project);
205
- session.project = result.project;
206
- session.revision += 1;
207
- session.dirty = true;
208
- const cacheEntry = this.cacheService.invalidateSession(session);
209
- this.eventService.emit({
210
- kind: 'transaction.applied',
211
- sessionId: session.sessionId,
212
- canonicalPathKey: session.canonicalPathKey,
213
- revision: session.revision,
214
- });
215
- this.eventService.emit({
216
- kind: 'cache.invalidated',
217
- sessionId: session.sessionId,
218
- canonicalPathKey: session.canonicalPathKey,
219
- revision: session.revision,
220
- cacheRevision: cacheEntry.revision,
221
- });
222
-
223
- return success('authoring', startedAt, toSessionSnapshot(session, this.context.capabilities), {
224
- sessionId: session.sessionId,
225
- revision: session.revision,
226
- });
227
- }
228
-
229
- }
@@ -1,81 +0,0 @@
1
- import { failure, success, type BackendSessionState } from './context.js';
2
- import type { EventService } from './event-service.js';
3
- import { createSessionNotFoundError } from './session-utils.js';
4
- import type {
5
- BackendCacheEntry,
6
- BackendCacheSnapshot,
7
- BackendResult,
8
- GetCacheSnapshotInput,
9
- RefreshCacheInput,
10
- SessionNotFoundError,
11
- } from '../runtime.js';
12
-
13
- type CacheSession = Readonly<Pick<BackendSessionState,
14
- 'sessionId' | 'canonicalPathKey' | 'revision' | 'lastSavedRevision' | 'dirty' | 'closed'>> & {
15
- readonly project: { readonly packages: readonly { readonly resources: readonly unknown[] }[] };
16
- };
17
-
18
- function createCacheEntry(session: CacheSession, valid: boolean): BackendCacheEntry {
19
- return {
20
- canonicalPathKey: session.canonicalPathKey,
21
- sessionId: session.sessionId,
22
- revision: session.revision,
23
- lastSavedRevision: session.lastSavedRevision,
24
- dirty: session.dirty,
25
- valid,
26
- indexedAt: new Date().toISOString(),
27
- summary: {
28
- packageCount: session.project.packages.length,
29
- resourceCount: session.project.packages.reduce((total, pkg) => total + pkg.resources.length, 0),
30
- diagnostics: [],
31
- },
32
- };
33
- }
34
-
35
- export class CacheService {
36
- private readonly cacheBySession = new Map<string, BackendCacheEntry>();
37
- public constructor(private readonly getSession: (sessionId: string) => CacheSession | undefined, private readonly events: EventService) {}
38
-
39
- public getCacheSnapshot(input: GetCacheSnapshotInput): BackendResult<BackendCacheSnapshot, SessionNotFoundError> {
40
- const startedAt = Date.now();
41
- const session = this.getSession(input.sessionId);
42
- if (!session || session.closed) {
43
- return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
44
- }
45
- const entry = this.cacheBySession.get(input.sessionId);
46
- return success('read', startedAt, {
47
- cacheRevision: entry?.revision ?? session.revision,
48
- entries: entry ? [structuredClone(entry)] : [],
49
- }, { sessionId: session.sessionId, revision: session.revision });
50
- }
51
-
52
- public refreshCache(input: RefreshCacheInput): BackendResult<BackendCacheSnapshot, SessionNotFoundError> {
53
- const startedAt = Date.now();
54
- const session = this.getSession(input.sessionId);
55
- if (!session || session.closed) return failure('runtime', startedAt, createSessionNotFoundError(input.sessionId));
56
- const entry = this.refreshSession(session);
57
- this.events.emit({
58
- kind: 'cache.updated', sessionId: session.sessionId, canonicalPathKey: session.canonicalPathKey,
59
- revision: session.revision, cacheRevision: entry.revision, payload: { reason: input.reason ?? 'manual' },
60
- });
61
- return success('runtime', startedAt, {
62
- cacheRevision: entry.revision, entries: [structuredClone(entry)],
63
- }, { sessionId: session.sessionId, revision: session.revision });
64
- }
65
-
66
- public refreshSession(session: CacheSession): BackendCacheEntry {
67
- const entry = createCacheEntry(session, true);
68
- this.cacheBySession.set(session.sessionId, entry);
69
- return entry;
70
- }
71
-
72
- public invalidateSession(session: CacheSession): BackendCacheEntry {
73
- const entry = createCacheEntry(session, false);
74
- this.cacheBySession.set(session.sessionId, entry);
75
- return entry;
76
- }
77
-
78
- public removeSession(sessionId: string): void {
79
- this.cacheBySession.delete(sessionId);
80
- }
81
- }
@@ -1,75 +0,0 @@
1
- import { type FileSystem, ProjectWriter } from '@openfairygui/core/project-io';
2
- import type { Document } from '@openfairygui/core';
3
-
4
- export function createCaptureFileSystem(
5
- files: Map<string, string | Uint8Array>,
6
- directories: Set<string>,
7
- ): FileSystem {
8
- const normalize = (filePath: string): string => filePath.replace(/\\/g, '/').replace(/\/+/g, '/');
9
- return {
10
- async readFile(filePath: string): Promise<string> {
11
- const value = files.get(normalize(filePath));
12
- if (typeof value !== 'string') throw new Error(`Captured text file was not found: ${filePath}`);
13
- return value;
14
- },
15
- async readFileRaw(filePath: string): Promise<Uint8Array> {
16
- const value = files.get(normalize(filePath));
17
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
18
- return value.slice();
19
- },
20
- async writeFile(filePath: string, content: string): Promise<void> {
21
- files.set(normalize(filePath), content);
22
- },
23
- async writeFileRaw(filePath: string, data: Uint8Array): Promise<void> {
24
- files.set(normalize(filePath), data.slice());
25
- },
26
- async mkdir(dirPath: string): Promise<void> {
27
- directories.add(normalize(dirPath));
28
- },
29
- async readdir(): Promise<string[]> {
30
- return [];
31
- },
32
- async exists(filePath: string): Promise<boolean> {
33
- return files.has(normalize(filePath));
34
- },
35
- join(...paths: string[]): string {
36
- return normalize(paths.filter(Boolean).join('/'));
37
- },
38
- dirname(filePath: string): string {
39
- const normalized = normalize(filePath);
40
- const separator = normalized.lastIndexOf('/');
41
- return separator < 0 ? '' : normalized.slice(0, separator);
42
- },
43
- async unlink(filePath: string): Promise<void> {
44
- files.delete(normalize(filePath));
45
- },
46
- };
47
- }
48
-
49
- export function capturedFilesEqual(left: Map<string, string | Uint8Array>, right: Map<string, string | Uint8Array>): boolean {
50
- if (left.size !== right.size) return false;
51
- for (const [filePath, leftValue] of left) {
52
- const rightValue = right.get(filePath);
53
- if (typeof leftValue === 'string') {
54
- if (leftValue !== rightValue) return false;
55
- continue;
56
- }
57
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
58
- for (let index = 0; index < leftValue.length; index += 1) {
59
- if (leftValue[index] !== rightValue[index]) return false;
60
- }
61
- }
62
- return true;
63
- }
64
-
65
- export function capturedDirectoriesEqual(left: Set<string>, right: Set<string>): boolean {
66
- return left.size === right.size && [...left].every((directory) => right.has(directory));
67
- }
68
-
69
- /** Serialize only into memory. This is a model projection, not a disk inventory or write plan. */
70
- export async function captureProject(document: Document, fairyFileName: string) {
71
- const files = new Map<string, string | Uint8Array>();
72
- const directories = new Set<string>();
73
- await new ProjectWriter(createCaptureFileSystem(files, directories)).write(document, fairyFileName);
74
- return { files, directories };
75
- }