@openfairygui/backend 0.2.0-alpha.2 → 0.2.0-alpha.21

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.
package/src/runtime.ts CHANGED
@@ -1,17 +1,5 @@
1
- import {
2
- UAM_SUPPORTED_MATERIALIZATION_SCOPE,
3
- type UamProject,
4
- type UamTransactionOperation,
5
- } from '@openfairygui/core/uam';
6
1
  import type { ApplyUamTransactionAppError } from '@openfairygui/functions/uam';
7
- import {
8
- BACKEND_CAPABILITY_SCHEMA_VERSION,
9
- BACKEND_COMPATIBILITY_POLICY,
10
- BACKEND_CONTRACT_VERSION,
11
- type BackendResponseMeta,
12
- } from './contracts.js';
13
- import { createRuntimePathPolicy, type PathPolicyViolationError } from './path-policy.js';
14
- import { createArtifactCapabilities } from './services/artifact-service.js';
2
+ import type { PathPolicyViolationError } from './path-policy.js';
15
3
  import { AuthoringService } from './services/authoring-service.js';
16
4
  import { CacheService } from './services/cache-service.js';
17
5
  import type { BackendContext, BackendSessionState } from './services/context.js';
@@ -19,527 +7,46 @@ import { EventService } from './services/event-service.js';
19
7
  import { JobService } from './services/job-service.js';
20
8
  import { ReadService } from './services/read-service.js';
21
9
  import { RuntimeService } from './services/runtime-service.js';
22
-
23
- export interface BackendFileHandle {
24
- writeFile(content: string): Promise<void>;
25
- close(): Promise<void>;
26
- }
27
-
28
- export interface BackendFileStat {
29
- isFile(): boolean;
30
- isDirectory(): boolean;
31
- }
32
-
33
- export interface BackendFileSystem {
34
- stat(filePath: string): Promise<BackendFileStat>;
35
- readdir(dirPath: string): Promise<string[]>;
36
- readFile(filePath: string): Promise<string>;
37
- readFileRaw(filePath: string): Promise<Uint8Array>;
38
- writeFile(filePath: string, content: string): Promise<void>;
39
- writeFileRaw(filePath: string, data: Uint8Array): Promise<void>;
40
- mkdir(dirPath: string, options?: { recursive?: boolean }): Promise<void>;
41
- resolvePath(filePath: string): Promise<string>;
42
- openExclusive(filePath: string): Promise<BackendFileHandle>;
43
- unlink(filePath: string): Promise<void>;
44
- join(...paths: string[]): string;
45
- dirname(filePath: string): string;
46
- resolve(...paths: string[]): string;
47
- }
48
-
49
- export interface BackendHostAdapter {
50
- lockMetadata?(input: { canonicalPathKey: string; canonicalProjectPath: string; lockFilePath: string }): unknown;
51
- }
52
-
53
- export interface BackendArtifactBridgeCapability {
54
- available: false;
55
- requiredHost: 'node';
56
- executionBoundary: 'external-bridge';
57
- bridgeEntrypoint: '@openfairygui/backend/node';
58
- reason: string;
59
- }
60
-
61
- export interface BackendCapabilityManifest {
62
- browserSafe: true;
63
- rootEntrypoint: '@openfairygui/backend';
64
- nodeEntrypoint: '@openfairygui/backend/node';
65
- adapters: {
66
- fileSystem: {
67
- injected: true;
68
- requiredFor: readonly ['openSession', 'saveSession'];
69
- };
70
- host: {
71
- injected: true;
72
- requiredFor: readonly ['advisoryLockMetadata'];
73
- };
74
- };
75
- executionBoundaries: {
76
- projectSession: 'in-process-browser-safe';
77
- fileBackedSession: 'adapter-backed';
78
- artifactPublish: BackendArtifactBridgeCapability;
79
- artifactRestore: BackendArtifactBridgeCapability;
80
- };
81
- diagnostics: {
82
- stableCodes: true;
83
- errorDiagnosticMirror: true;
84
- };
85
- }
86
-
87
- export interface BackendCapabilities {
88
- contractVersion: typeof BACKEND_CONTRACT_VERSION;
89
- capabilitySchemaVersion: typeof BACKEND_CAPABILITY_SCHEMA_VERSION;
90
- transactionKernelOwner: '@openfairygui/core';
91
- appSeamOwner: '@openfairygui/functions';
92
- runtimeOwner: '@openfairygui/backend';
93
- methods: readonly [
94
- 'getCapabilities',
95
- 'openSession',
96
- 'openProjectSession',
97
- 'getSession',
98
- 'applyTransaction',
99
- 'saveSession',
100
- 'closeSession',
101
- 'getEvents',
102
- 'getJob',
103
- 'listJobs',
104
- 'cancelJob',
105
- 'getCacheSnapshot',
106
- 'refreshCache',
107
- ];
108
- read: {
109
- capabilitySnapshot: true;
110
- sessionSnapshot: true;
111
- };
112
- authoring: {
113
- applyTransaction: true;
114
- saveSession: true;
115
- resourceKinds: readonly string[];
116
- nodeKinds: readonly string[];
117
- gearKinds: readonly string[];
118
- unsupported: readonly ['artifact.publish', 'artifact.restore'];
119
- };
120
- artifact: {
121
- publish: false;
122
- restore: false;
123
- status: 'bridge-required';
124
- publishBridge: BackendArtifactBridgeCapability;
125
- restoreBridge: BackendArtifactBridgeCapability;
126
- };
127
- manifest: BackendCapabilityManifest;
128
- compatibilityPolicy: typeof BACKEND_COMPATIBILITY_POLICY;
129
- runtime: {
130
- sessionRuntime: true;
131
- advisoryLocking: true;
132
- coordinatedSave: true;
133
- atomicSave: false;
134
- staleRevisionProtection: true;
135
- pathPolicy: {
136
- canonicalization: 'realpath+normalized-casefold';
137
- sessionIdentity: 'project-root';
138
- saveTarget: 'opened-project-only';
139
- outputTargets: 'deferred';
140
- workspaceBoundary: 'project-root-only';
141
- };
142
- events: {
143
- polling: true;
144
- subscriptions: false;
145
- retentionLimit: 1000;
146
- sequenceScope: 'runtime';
147
- };
148
- jobs: {
149
- inMemory: true;
150
- cooperativeCancel: true;
151
- persistent: false;
152
- supportedKinds: readonly ['cache.refresh'];
153
- artifactJobs: false;
154
- completedRetentionLimit: 100;
155
- };
156
- cache: {
157
- derivedReadOnly: true;
158
- keyedBy: 'canonicalPathKey';
159
- sourceOfTruth: false;
160
- refreshMethod: 'refreshCache';
161
- };
162
- };
163
- }
164
-
165
- export interface BackendSessionSnapshot {
166
- sessionId: string;
167
- canonicalProjectPath: string;
168
- revision: number;
169
- lastSavedRevision: number;
170
- dirty: boolean;
171
- lockHeld: boolean;
172
- capabilities: BackendCapabilities;
173
- }
174
-
175
- export interface BackendSuccess<T> {
176
- ok: true;
177
- meta: BackendResponseMeta;
178
- data: T;
179
- }
180
-
181
- export interface BackendFailure<E extends BackendError = BackendError> {
182
- ok: false;
183
- meta: BackendResponseMeta;
184
- error: E;
185
- session?: BackendSessionSnapshot;
186
- }
187
-
188
- export type BackendResult<T, E extends BackendError = BackendError> = BackendSuccess<T> | BackendFailure<E>;
189
-
190
- export interface SessionNotFoundError {
191
- code: 'session_not_found';
192
- message: string;
193
- sessionId: string;
194
- }
195
-
196
- export interface SessionStaleWriteError {
197
- code: 'stale_write';
198
- message: string;
199
- sessionId: string;
200
- canonicalPathKey: string;
201
- expectedRevision: number;
202
- actualRevision: number;
203
- }
204
-
205
- export interface InProcessLockConflictError {
206
- code: 'lock_conflict';
207
- kind: 'in_process_session_exists';
208
- message: string;
209
- canonicalPathKey: string;
210
- holderSessionId: string;
211
- lockFilePath?: string;
212
- }
213
-
214
- export interface AdvisoryLockConflictError {
215
- code: 'lock_conflict';
216
- kind: 'advisory_lock_conflict';
217
- message: string;
218
- canonicalPathKey: string;
219
- holderSessionId?: string;
220
- lockFilePath: string;
221
- }
222
-
223
- export interface SavePartialFailureError {
224
- code: 'save_partial_failure';
225
- message: string;
226
- sessionId: string;
227
- canonicalPathKey: string;
228
- attemptedRevision: number;
229
- lastSavedRevision: number;
230
- committedPaths: string[];
231
- failedPaths: string[];
232
- diskMayBePartiallyUpdated: true;
233
- }
234
-
235
- export type BackendEventKind =
236
- | 'session.opened'
237
- | 'transaction.applied'
238
- | 'transaction.rejected'
239
- | 'save.started'
240
- | 'save.completed'
241
- | 'save.failed'
242
- | 'session.closeRequested'
243
- | 'session.closed'
244
- | 'cache.invalidated'
245
- | 'cache.updated'
246
- | 'job.created'
247
- | 'job.started'
248
- | 'job.progress'
249
- | 'job.cancelRequested'
250
- | 'job.cancelled'
251
- | 'job.completed'
252
- | 'job.failed';
253
-
254
- export interface BackendEvent {
255
- sequence: number;
256
- kind: BackendEventKind;
257
- timestamp: string;
258
- sessionId?: string;
259
- canonicalPathKey?: string;
260
- revision?: number;
261
- cacheRevision?: number;
262
- jobId?: string;
263
- diagnostics: import('./contracts.js').BackendDiagnostic[];
264
- payload?: unknown;
265
- }
266
-
267
- export interface GetEventsInput {
268
- sessionId: string;
269
- after?: string;
270
- limit?: number;
271
- }
272
-
273
- export interface GetEventsSnapshot {
274
- events: BackendEvent[];
275
- oldestSequence: number;
276
- currentSequence: number;
277
- cursorExpired: boolean;
278
- }
279
-
280
- export interface EventCursorInvalidError {
281
- code: 'event_cursor_invalid';
282
- message: string;
283
- sessionId: string;
284
- after: string;
285
- }
286
-
287
- export type BackendJobStatus = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
288
- export type BackendJobKind = 'cache.refresh';
289
- export type BackendJobListStatusFilter = BackendJobStatus | 'active' | 'terminal';
290
-
291
- export interface BackendJobProgress {
292
- completed: number;
293
- total?: number;
294
- message?: string;
295
- }
296
-
297
- export interface BackendJobSnapshot {
298
- jobId: string;
299
- kind: BackendJobKind;
300
- status: BackendJobStatus;
301
- createdAt: string;
302
- startedAt?: string;
303
- finishedAt?: string;
304
- sessionId?: string;
305
- canonicalPathKey?: string;
306
- revision?: number;
307
- cacheRevision?: number;
308
- diagnostics: import('./contracts.js').BackendDiagnostic[];
309
- progress?: BackendJobProgress;
310
- result?: unknown;
311
- error?: BackendError;
312
- }
313
-
314
- export interface BackendJobListSnapshot {
315
- jobs: BackendJobSnapshot[];
316
- }
317
-
318
- export interface GetJobInput {
319
- sessionId: string;
320
- jobId: string;
321
- }
322
-
323
- export interface ListJobsInput {
324
- sessionId: string;
325
- status?: BackendJobListStatusFilter;
326
- kind?: BackendJobKind;
327
- limit?: number;
328
- }
329
-
330
- export interface CancelJobInput {
331
- sessionId: string;
332
- jobId: string;
333
- }
334
-
335
- export interface BackendJobNotFoundError {
336
- code: 'job_not_found';
337
- message: string;
338
- sessionId: string;
339
- jobId: string;
340
- }
341
-
342
- export interface BackendJobNotCancellableError {
343
- code: 'job_not_cancellable';
344
- message: string;
345
- sessionId: string;
346
- jobId: string;
347
- status: 'completed' | 'failed' | 'cancelled';
348
- }
349
-
350
- export interface BackendJobCancelledError {
351
- code: 'job_cancelled';
352
- message: string;
353
- sessionId: string;
354
- jobId: string;
355
- }
356
-
357
- export interface CacheRefreshFailedError {
358
- code: 'cache_refresh_failed';
359
- message: string;
360
- sessionId: string;
361
- jobId: string;
362
- causeCode?: string;
363
- }
364
-
365
- export interface BackendCapabilityUnavailableError {
366
- code: 'capability_unavailable';
367
- message: string;
368
- capability: 'fileSystem' | 'artifact.publish' | 'artifact.restore';
369
- requiredAdapter?: 'BackendFileSystem';
370
- requiredHost?: 'node';
371
- bridgeBoundary?: 'external-bridge';
372
- }
373
-
374
- export type BackendJobErrors =
375
- | BackendJobNotFoundError
376
- | BackendJobNotCancellableError
377
- | BackendJobCancelledError
378
- | CacheRefreshFailedError;
379
-
380
- export interface BackendCacheSnapshot {
381
- cacheRevision: number;
382
- entries: BackendCacheEntry[];
383
- }
384
-
385
- export interface BackendCacheEntry {
386
- canonicalPathKey: string;
387
- sessionId?: string;
388
- revision: number;
389
- lastSavedRevision: number;
390
- dirty: boolean;
391
- valid: boolean;
392
- indexedAt: string;
393
- summary: {
394
- resourceCount: number;
395
- packageCount?: number;
396
- diagnostics: import('./contracts.js').BackendDiagnostic[];
397
- };
398
- }
399
-
400
- export interface GetCacheSnapshotInput {
401
- sessionId: string;
402
- }
403
-
404
- export interface RefreshCacheInput {
405
- sessionId: string;
406
- reason?: 'manual' | 'session_open' | 'after_save';
407
- }
408
-
409
- export type BackendError =
410
- | SessionNotFoundError
411
- | SessionStaleWriteError
412
- | InProcessLockConflictError
413
- | AdvisoryLockConflictError
414
- | SavePartialFailureError
415
- | PathPolicyViolationError
416
- | EventCursorInvalidError
417
- | BackendJobNotFoundError
418
- | BackendJobNotCancellableError
419
- | BackendJobCancelledError
420
- | CacheRefreshFailedError
421
- | BackendCapabilityUnavailableError
422
- | ApplyUamTransactionAppError;
423
-
424
- export interface ApplySessionTransactionInput {
425
- sessionId: string;
426
- expectedRevision: number;
427
- operations: UamTransactionOperation[];
428
- }
429
-
430
- export interface OpenProjectSessionInput {
431
- project: UamProject;
432
- sessionId?: string;
433
- canonicalProjectPath?: string;
434
- canonicalPathKey?: string;
435
- }
436
-
437
- export interface BackendRuntimeOptions {
438
- fileSystem?: BackendFileSystem;
439
- host?: BackendHostAdapter;
440
- }
441
-
442
- const BACKEND_METHODS = [
443
- 'getCapabilities',
444
- 'openSession',
445
- 'openProjectSession',
446
- 'getSession',
447
- 'applyTransaction',
448
- 'saveSession',
449
- 'closeSession',
450
- 'getEvents',
451
- 'getJob',
452
- 'listJobs',
453
- 'cancelJob',
454
- 'getCacheSnapshot',
455
- 'refreshCache',
456
- ] as const;
457
-
458
- const ARTIFACT_BRIDGE_CAPABILITY = {
459
- available: false,
460
- requiredHost: 'node',
461
- executionBoundary: 'external-bridge',
462
- bridgeEntrypoint: '@openfairygui/backend/node',
463
- reason: 'publish/restore require explicit Node-hosted filesystem and artifact execution.',
464
- } as const satisfies BackendArtifactBridgeCapability;
465
-
466
- function createCapabilities(): BackendCapabilities {
467
- return {
468
- contractVersion: BACKEND_CONTRACT_VERSION,
469
- capabilitySchemaVersion: BACKEND_CAPABILITY_SCHEMA_VERSION,
470
- transactionKernelOwner: '@openfairygui/core',
471
- appSeamOwner: '@openfairygui/functions',
472
- runtimeOwner: '@openfairygui/backend',
473
- methods: BACKEND_METHODS,
474
- read: {
475
- capabilitySnapshot: true,
476
- sessionSnapshot: true,
477
- },
478
- authoring: {
479
- applyTransaction: true,
480
- saveSession: true,
481
- resourceKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.resourceKinds],
482
- nodeKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.nodeKinds],
483
- gearKinds: [...UAM_SUPPORTED_MATERIALIZATION_SCOPE.gearKinds],
484
- unsupported: ['artifact.publish', 'artifact.restore'],
485
- },
486
- artifact: createArtifactCapabilities(),
487
- manifest: {
488
- browserSafe: true,
489
- rootEntrypoint: '@openfairygui/backend',
490
- nodeEntrypoint: '@openfairygui/backend/node',
491
- adapters: {
492
- fileSystem: {
493
- injected: true,
494
- requiredFor: ['openSession', 'saveSession'],
495
- },
496
- host: {
497
- injected: true,
498
- requiredFor: ['advisoryLockMetadata'],
499
- },
500
- },
501
- executionBoundaries: {
502
- projectSession: 'in-process-browser-safe',
503
- fileBackedSession: 'adapter-backed',
504
- artifactPublish: ARTIFACT_BRIDGE_CAPABILITY,
505
- artifactRestore: ARTIFACT_BRIDGE_CAPABILITY,
506
- },
507
- diagnostics: {
508
- stableCodes: true,
509
- errorDiagnosticMirror: true,
510
- },
511
- },
512
- compatibilityPolicy: BACKEND_COMPATIBILITY_POLICY,
513
- runtime: {
514
- sessionRuntime: true,
515
- advisoryLocking: true,
516
- coordinatedSave: true,
517
- atomicSave: false,
518
- staleRevisionProtection: true,
519
- pathPolicy: createRuntimePathPolicy(),
520
- events: {
521
- polling: true,
522
- subscriptions: false,
523
- retentionLimit: 1000,
524
- sequenceScope: 'runtime',
525
- },
526
- jobs: {
527
- inMemory: true,
528
- cooperativeCancel: true,
529
- persistent: false,
530
- supportedKinds: ['cache.refresh'],
531
- artifactJobs: false,
532
- completedRetentionLimit: 100,
533
- },
534
- cache: {
535
- derivedReadOnly: true,
536
- keyedBy: 'canonicalPathKey',
537
- sourceOfTruth: false,
538
- refreshMethod: 'refreshCache',
539
- },
540
- },
541
- };
542
- }
10
+ import { createCapabilities } from './runtime/capabilities.js';
11
+ import type {
12
+ AdvisoryLockConflictError,
13
+ ApplySessionTransactionInput,
14
+ BackendCacheEntry,
15
+ BackendCacheSnapshot,
16
+ BackendCapabilities,
17
+ BackendCapabilityUnavailableError,
18
+ BackendEvent,
19
+ BackendFileSystem,
20
+ BackendJobListSnapshot,
21
+ BackendJobNotCancellableError,
22
+ BackendJobNotFoundError,
23
+ BackendJobSnapshot,
24
+ BackendResult,
25
+ BackendRuntimeOptions,
26
+ BackendSessionSnapshot,
27
+ BackendSuccess,
28
+ CancelJobInput,
29
+ EventCursorInvalidError,
30
+ GetCacheSnapshotInput,
31
+ GetEventsInput,
32
+ GetEventsSnapshot,
33
+ GetJobInput,
34
+ InProcessLockConflictError,
35
+ ListJobsInput,
36
+ MaterializeSessionInput,
37
+ MaterializeSessionSnapshot,
38
+ MaterializeValidationFailedError,
39
+ MaterializeWriteFailedError,
40
+ OpenProjectSessionInput,
41
+ RefreshCacheInput,
42
+ SavePartialFailureError,
43
+ SaveSessionInput,
44
+ SessionNotFoundError,
45
+ SessionStaleWriteError,
46
+ UamFidelityUnsupportedError,
47
+ } from './runtime/contracts.js';
48
+
49
+ export * from './runtime/contracts.js';
543
50
 
544
51
  export class BackendRuntime {
545
52
  private readonly fileSystem?: BackendFileSystem;
@@ -617,23 +124,43 @@ export class BackendRuntime {
617
124
  return this.authoringService.applyTransaction(input);
618
125
  }
619
126
 
620
- public async saveSession(input: {
621
- sessionId: string;
622
- expectedRevision?: number;
623
- targetPath?: string;
624
- }): Promise<
127
+ public async saveSession(
128
+ input: SaveSessionInput,
129
+ ): Promise<
625
130
  BackendResult<
626
- BackendSessionSnapshot,
131
+ BackendSessionSnapshot | MaterializeSessionSnapshot,
627
132
  | SessionNotFoundError
628
133
  | SessionStaleWriteError
629
134
  | SavePartialFailureError
135
+ | UamFidelityUnsupportedError
136
+ | MaterializeValidationFailedError
137
+ | MaterializeWriteFailedError
630
138
  | PathPolicyViolationError
139
+ | InProcessLockConflictError
631
140
  | BackendCapabilityUnavailableError
632
141
  >
633
142
  > {
634
143
  return this.authoringService.saveSession(input);
635
144
  }
636
145
 
146
+ public async materializeSession(
147
+ input: MaterializeSessionInput,
148
+ ): Promise<
149
+ BackendResult<
150
+ MaterializeSessionSnapshot,
151
+ | SessionNotFoundError
152
+ | SessionStaleWriteError
153
+ | UamFidelityUnsupportedError
154
+ | MaterializeValidationFailedError
155
+ | MaterializeWriteFailedError
156
+ | PathPolicyViolationError
157
+ | InProcessLockConflictError
158
+ | BackendCapabilityUnavailableError
159
+ >
160
+ > {
161
+ return this.authoringService.materializeSession(input);
162
+ }
163
+
637
164
  public async closeSession(input: {
638
165
  sessionId: string;
639
166
  }): Promise<BackendResult<{ sessionId: string; closed: true }, SessionNotFoundError>> {