@openfairygui/backend 0.3.0 → 0.4.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.
- package/README.md +4 -2
- package/dist/docs.cjs +12756 -0
- package/dist/docs.d.cts +284 -0
- package/dist/docs.d.mts +284 -0
- package/dist/docs.mjs +12746 -0
- package/dist/index.cjs +1201 -97
- package/dist/index.d.cts +1867 -48
- package/dist/index.d.mts +1867 -48
- package/dist/index.mjs +1196 -98
- package/dist/node.cjs +1371 -111
- package/dist/node.d.cts +186 -12
- package/dist/node.d.mts +186 -12
- package/dist/node.mjs +1370 -111
- package/docs/skills/openfairygui/SKILL.md +16 -0
- package/docs/workflow.md +50 -0
- package/package.json +19 -5
- package/src/contracts.ts +21 -3
- package/src/diagnostics.ts +181 -0
- package/src/docs.ts +109 -0
- package/src/generated/contracts.ts +17927 -0
- package/src/generated/docs.ts +12 -0
- package/src/index.ts +27 -0
- package/src/node.ts +213 -14
- package/src/path-policy.ts +18 -0
- package/src/runtime/capabilities.ts +12 -5
- package/src/runtime/contracts.ts +147 -21
- package/src/runtime.ts +42 -8
- package/src/services/authoring-service.ts +51 -6
- package/src/services/capture-project.ts +75 -0
- package/src/services/context.ts +3 -1
- package/src/services/event-service.ts +2 -1
- package/src/services/read-service.ts +97 -1
- package/src/services/runtime-service.ts +54 -79
- package/src/services/session-project-writer.ts +31 -13
- package/src/services/transaction-preview.ts +114 -0
package/src/runtime/contracts.ts
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
UamDisplayNodeKind,
|
|
3
|
+
UamDisplayNode,
|
|
4
|
+
UamDisplayNodeSelector,
|
|
5
|
+
UamComponentModel,
|
|
6
|
+
UamComponentSelector,
|
|
7
|
+
UamControllerModel,
|
|
8
|
+
UamControllerSelector,
|
|
9
|
+
UamTransitionModel,
|
|
10
|
+
UamTransitionSelector,
|
|
11
|
+
UamResourceSelector,
|
|
12
|
+
UamImageResource,
|
|
13
|
+
UamMovieClipResource,
|
|
14
|
+
UamGenericAssetResource,
|
|
15
|
+
UamComponentResource,
|
|
3
16
|
UamProject,
|
|
17
|
+
UamPackageSettings,
|
|
18
|
+
UamPackageSelector,
|
|
4
19
|
UamResource,
|
|
5
20
|
UamTransactionOperation,
|
|
6
21
|
} from '@openfairygui/core/uam';
|
|
@@ -13,6 +28,58 @@ import type {
|
|
|
13
28
|
BackendResponseMeta,
|
|
14
29
|
} from '../contracts.js';
|
|
15
30
|
import type { PathPolicyViolationError } from '../path-policy.js';
|
|
31
|
+
import type { BACKEND_METHODS } from './capabilities.js';
|
|
32
|
+
import type { BackendRuntime } from '../runtime.js';
|
|
33
|
+
|
|
34
|
+
export type BackendMethodName = keyof BackendRuntime;
|
|
35
|
+
|
|
36
|
+
export const BACKEND_ENTITY_QUERY_LIMITS = { maxBytes: 262144, maxDepth: 32, maxNodes: 100000 } as const;
|
|
37
|
+
export const BACKEND_TRANSACTION_PREVIEW_LIMITS = { maxBytes: 262144, maxEntries: 2000 } as const;
|
|
38
|
+
/** Fixed resource projection. Binary content, source bookkeeping and arbitrary metadata are excluded. */
|
|
39
|
+
export const BACKEND_RESOURCE_QUERY_FIELDS = [
|
|
40
|
+
'kind', 'id', 'name', 'path', 'exported', 'favorite', 'branch', 'branchItemIds',
|
|
41
|
+
'fileName', 'file', 'dimensions', 'image', 'movieClip',
|
|
42
|
+
] as const;
|
|
43
|
+
type ResourceQueryFields<T> = Pick<T, Extract<keyof T, typeof BACKEND_RESOURCE_QUERY_FIELDS[number]>>;
|
|
44
|
+
export type BackendResourceSnapshot = ResourceQueryFields<UamImageResource> | ResourceQueryFields<UamMovieClipResource>
|
|
45
|
+
| ResourceQueryFields<UamGenericAssetResource> | ResourceQueryFields<UamComponentResource>;
|
|
46
|
+
export type BackendComponentSnapshot = Pick<UamComponentModel, 'size' | 'properties' | 'customData'>;
|
|
47
|
+
export type BackendProjectSnapshot = Pick<UamProject, 'projectId' | 'settings'>;
|
|
48
|
+
export interface BackendPackageSnapshot {
|
|
49
|
+
id: string;
|
|
50
|
+
name: string;
|
|
51
|
+
settings: UamPackageSettings;
|
|
52
|
+
}
|
|
53
|
+
export type BackendEntityTarget =
|
|
54
|
+
| { kind: 'project' }
|
|
55
|
+
| { kind: 'package'; selector: UamPackageSelector }
|
|
56
|
+
| { kind: 'resource'; selector: UamResourceSelector }
|
|
57
|
+
| { kind: 'component'; selector: UamComponentSelector }
|
|
58
|
+
| { kind: 'displayNode'; selector: UamDisplayNodeSelector }
|
|
59
|
+
| { kind: 'controller'; selector: UamControllerSelector }
|
|
60
|
+
| { kind: 'transition'; selector: UamTransitionSelector };
|
|
61
|
+
export interface QueryEntityInput {
|
|
62
|
+
sessionId: string;
|
|
63
|
+
target: BackendEntityTarget;
|
|
64
|
+
}
|
|
65
|
+
export interface BackendEntitySnapshot {
|
|
66
|
+
sessionId: string;
|
|
67
|
+
revision: number;
|
|
68
|
+
target: BackendEntityTarget;
|
|
69
|
+
entity: { kind: 'project'; properties: BackendProjectSnapshot }
|
|
70
|
+
| { kind: 'package'; properties: BackendPackageSnapshot }
|
|
71
|
+
| { kind: 'resource'; properties: BackendResourceSnapshot }
|
|
72
|
+
| { kind: 'component'; properties: BackendComponentSnapshot }
|
|
73
|
+
| { kind: 'displayNode'; properties: UamDisplayNode }
|
|
74
|
+
| { kind: 'controller'; properties: UamControllerModel }
|
|
75
|
+
| { kind: 'transition'; properties: UamTransitionModel };
|
|
76
|
+
}
|
|
77
|
+
export interface EntityQueryError {
|
|
78
|
+
code: 'entity_query_failed';
|
|
79
|
+
message: string;
|
|
80
|
+
sessionId: string;
|
|
81
|
+
reason: 'invalid_query' | 'not_found' | 'ambiguous' | 'response_budget_exceeded' | 'non_json_value';
|
|
82
|
+
}
|
|
16
83
|
|
|
17
84
|
/** An exclusive lock owned for the lifetime of one backend session. */
|
|
18
85
|
export interface BackendSessionLock {
|
|
@@ -36,6 +103,15 @@ export interface BackendFileSystem {
|
|
|
36
103
|
writeFileRaw(filePath: string, data: Uint8Array): Promise<void>;
|
|
37
104
|
mkdir(dirPath: string, options?: { recursive?: boolean }): Promise<void>;
|
|
38
105
|
resolvePath(filePath: string): Promise<string>;
|
|
106
|
+
/** Optional host validation before a project is read. Node rejects links anywhere in the project tree. */
|
|
107
|
+
validateProjectRoot?(projectRoot: string): Promise<void>;
|
|
108
|
+
/** Optional host-specific lock location. Node keeps it beside the project so directory swaps do not move it. */
|
|
109
|
+
getSessionLockPath?(canonicalProjectPath: string): string;
|
|
110
|
+
/** Runs project writes against a staged copy and commits them as one directory swap. */
|
|
111
|
+
runProjectWriteTransaction?(
|
|
112
|
+
projectRoot: string,
|
|
113
|
+
write: (stagedFileSystem: BackendFileSystem) => Promise<void>,
|
|
114
|
+
): Promise<void>;
|
|
39
115
|
acquireSessionLock(lockPath: string): Promise<BackendSessionLock>;
|
|
40
116
|
unlink(filePath: string): Promise<void>;
|
|
41
117
|
rmdir(dirPath: string): Promise<void>;
|
|
@@ -85,6 +161,8 @@ export interface BackendCapabilityManifest {
|
|
|
85
161
|
diagnostics: {
|
|
86
162
|
stableCodes: true;
|
|
87
163
|
errorDiagnosticMirror: true;
|
|
164
|
+
recoveryGuides: 'all-formal-codes';
|
|
165
|
+
automaticRepair: false;
|
|
88
166
|
};
|
|
89
167
|
}
|
|
90
168
|
|
|
@@ -94,31 +172,16 @@ export interface BackendCapabilities {
|
|
|
94
172
|
transactionKernelOwner: '@openfairygui/core';
|
|
95
173
|
appSeamOwner: '@openfairygui/functions';
|
|
96
174
|
runtimeOwner: '@openfairygui/backend';
|
|
97
|
-
methods:
|
|
98
|
-
'getCapabilities',
|
|
99
|
-
'openSession',
|
|
100
|
-
'openProjectSession',
|
|
101
|
-
'getSession',
|
|
102
|
-
'getProjectOutline',
|
|
103
|
-
'validateSession',
|
|
104
|
-
'applyTransaction',
|
|
105
|
-
'saveSession',
|
|
106
|
-
'materializeSession',
|
|
107
|
-
'closeSession',
|
|
108
|
-
'getEvents',
|
|
109
|
-
'getJob',
|
|
110
|
-
'listJobs',
|
|
111
|
-
'cancelJob',
|
|
112
|
-
'getCacheSnapshot',
|
|
113
|
-
'refreshCache',
|
|
114
|
-
];
|
|
175
|
+
methods: typeof BACKEND_METHODS;
|
|
115
176
|
read: {
|
|
116
177
|
capabilitySnapshot: true;
|
|
117
178
|
sessionSnapshot: true;
|
|
118
179
|
projectOutline: true;
|
|
180
|
+
entityQuery: { kinds: readonly BackendEntityTarget['kind'][]; projection: 'properties'; sourceBytes: false; limits: typeof BACKEND_ENTITY_QUERY_LIMITS };
|
|
119
181
|
projectValidation: true;
|
|
120
182
|
};
|
|
121
183
|
authoring: {
|
|
184
|
+
preflightTransaction: { mode: 'execute-and-discard'; reservesRevision: false; impact: 'model-diff'; limits: typeof BACKEND_TRANSACTION_PREVIEW_LIMITS };
|
|
122
185
|
applyTransaction: true;
|
|
123
186
|
saveSession: true;
|
|
124
187
|
resourceKinds: readonly string[];
|
|
@@ -144,7 +207,7 @@ export interface BackendCapabilities {
|
|
|
144
207
|
sessionRuntime: true;
|
|
145
208
|
advisoryLocking: true;
|
|
146
209
|
coordinatedSave: true;
|
|
147
|
-
atomicSave:
|
|
210
|
+
atomicSave: boolean;
|
|
148
211
|
staleRevisionProtection: true;
|
|
149
212
|
pathPolicy: {
|
|
150
213
|
canonicalization: 'realpath+normalized-casefold';
|
|
@@ -276,6 +339,12 @@ export interface AdvisoryLockConflictError {
|
|
|
276
339
|
lockFilePath: string;
|
|
277
340
|
}
|
|
278
341
|
|
|
342
|
+
export interface SessionIdConflictError {
|
|
343
|
+
code: 'session_id_conflict';
|
|
344
|
+
message: string;
|
|
345
|
+
sessionId: string;
|
|
346
|
+
}
|
|
347
|
+
|
|
279
348
|
export interface SavePartialFailureError {
|
|
280
349
|
code: 'save_partial_failure';
|
|
281
350
|
message: string;
|
|
@@ -285,7 +354,7 @@ export interface SavePartialFailureError {
|
|
|
285
354
|
lastSavedRevision: number;
|
|
286
355
|
committedPaths: string[];
|
|
287
356
|
failedPaths: string[];
|
|
288
|
-
diskMayBePartiallyUpdated:
|
|
357
|
+
diskMayBePartiallyUpdated: boolean;
|
|
289
358
|
}
|
|
290
359
|
|
|
291
360
|
export interface UamFidelityUnsupportedError {
|
|
@@ -315,7 +384,7 @@ export interface MaterializeWriteFailedError {
|
|
|
315
384
|
failedPaths: string[];
|
|
316
385
|
skippedPaths: string[];
|
|
317
386
|
diagnostics: BackendDiagnostic[];
|
|
318
|
-
diskMayBePartiallyUpdated:
|
|
387
|
+
diskMayBePartiallyUpdated: boolean;
|
|
319
388
|
}
|
|
320
389
|
|
|
321
390
|
export type BackendEventKind =
|
|
@@ -494,6 +563,9 @@ export interface RefreshCacheInput {
|
|
|
494
563
|
|
|
495
564
|
export type BackendError =
|
|
496
565
|
| SessionNotFoundError
|
|
566
|
+
| TransactionPreviewError
|
|
567
|
+
| EntityQueryError
|
|
568
|
+
| SessionIdConflictError
|
|
497
569
|
| SessionStaleWriteError
|
|
498
570
|
| InProcessLockConflictError
|
|
499
571
|
| AdvisoryLockConflictError
|
|
@@ -508,14 +580,64 @@ export type BackendError =
|
|
|
508
580
|
| BackendJobCancelledError
|
|
509
581
|
| CacheRefreshFailedError
|
|
510
582
|
| BackendCapabilityUnavailableError
|
|
583
|
+
| ProjectRootNotAllowedError
|
|
584
|
+
| ProjectOpenFailedError
|
|
511
585
|
| ApplyUamTransactionAppError;
|
|
512
586
|
|
|
587
|
+
export interface ProjectRootNotAllowedError {
|
|
588
|
+
code: 'project_root_not_allowed';
|
|
589
|
+
message: string;
|
|
590
|
+
projectPath: string;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
export interface ProjectOpenFailedError {
|
|
594
|
+
code: 'project_open_failed';
|
|
595
|
+
message: string;
|
|
596
|
+
projectPath: string;
|
|
597
|
+
}
|
|
598
|
+
|
|
513
599
|
export interface ApplySessionTransactionInput {
|
|
514
600
|
sessionId: string;
|
|
515
601
|
expectedRevision: number;
|
|
516
602
|
operations: UamTransactionOperation[];
|
|
517
603
|
}
|
|
518
604
|
|
|
605
|
+
export interface BackendTransactionPreview {
|
|
606
|
+
sessionId: string;
|
|
607
|
+
baseRevision: number;
|
|
608
|
+
/** Revision after applying this batch at baseRevision, including an empty batch. Not reserved. */
|
|
609
|
+
projectedRevision: number;
|
|
610
|
+
mode: 'execute-and-discard';
|
|
611
|
+
/** Complete, bounded comparison of current and projected UAM, not unsaved changes since last save. */
|
|
612
|
+
impact: {
|
|
613
|
+
entities: BackendTransactionEntityChange[];
|
|
614
|
+
/** Project-relative paths from the actual ProjectWriter, including empty directories. Not a disk write plan. */
|
|
615
|
+
files: Array<{ path: string; kind: 'file' | 'directory'; change: 'added' | 'removed' | 'updated' }>;
|
|
616
|
+
};
|
|
617
|
+
persistence: {
|
|
618
|
+
requiredAfterApply: true;
|
|
619
|
+
nextAction: 'saveSession' | 'materializeSession' | 'host-action';
|
|
620
|
+
fileSystemAvailable: boolean;
|
|
621
|
+
uamFidelity: BackendSessionSnapshot['uamFidelity'];
|
|
622
|
+
/** Preflight never verifies filesystem permissions, materialize destinations or actual disk state. */
|
|
623
|
+
writeVerified: false;
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
export interface BackendTransactionEntityChange {
|
|
628
|
+
target: BackendEntityTarget;
|
|
629
|
+
change: 'added' | 'removed' | 'updated';
|
|
630
|
+
/** Changed top-level property names; child collections contain identities and preserve their order. */
|
|
631
|
+
fields: string[];
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
export interface TransactionPreviewError {
|
|
635
|
+
code: 'transaction_preview_failed';
|
|
636
|
+
message: string;
|
|
637
|
+
sessionId: string;
|
|
638
|
+
reason: 'response_budget_exceeded' | 'projection_failed';
|
|
639
|
+
}
|
|
640
|
+
|
|
519
641
|
export interface GetProjectOutlineInput {
|
|
520
642
|
sessionId: string;
|
|
521
643
|
}
|
|
@@ -528,7 +650,9 @@ export interface OpenProjectSessionInput {
|
|
|
528
650
|
/** Authoritative UAM project. Use BackendRuntime.openSession() when importing an existing project from storage. */
|
|
529
651
|
project: UamProject;
|
|
530
652
|
sessionId?: string;
|
|
653
|
+
/** Session identity only; without explicit storage or a per-call filesystem this grants no filesystem access. */
|
|
531
654
|
canonicalProjectPath?: string;
|
|
655
|
+
/** Host-defined session identity; not a filesystem authorization or an allowed-root override. */
|
|
532
656
|
canonicalPathKey?: string;
|
|
533
657
|
/** Optional writeback target for the authoritative UAM project; this is not an import source. */
|
|
534
658
|
storage?: BackendProjectSessionStorage;
|
|
@@ -563,4 +687,6 @@ export interface MaterializeSessionInput {
|
|
|
563
687
|
export interface BackendRuntimeOptions {
|
|
564
688
|
fileSystem?: BackendFileSystem;
|
|
565
689
|
host?: BackendHostAdapter;
|
|
690
|
+
/** Canonical filesystem roots available to file-backed sessions. Omit for unrestricted library use. */
|
|
691
|
+
allowedProjectRoots?: readonly string[];
|
|
566
692
|
}
|
package/src/runtime.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { ProjectValidationReport } from '@openfairygui/core';
|
|
|
3
3
|
import type { PathPolicyViolationError } from './path-policy.js';
|
|
4
4
|
import { AuthoringService } from './services/authoring-service.js';
|
|
5
5
|
import { CacheService } from './services/cache-service.js';
|
|
6
|
-
import type
|
|
6
|
+
import { type BackendContext, type BackendSessionState, failure } from './services/context.js';
|
|
7
7
|
import { EventService } from './services/event-service.js';
|
|
8
8
|
import { JobService } from './services/job-service.js';
|
|
9
9
|
import { ReadService } from './services/read-service.js';
|
|
@@ -27,6 +27,7 @@ import type {
|
|
|
27
27
|
BackendRuntimeOptions,
|
|
28
28
|
BackendSessionSnapshot,
|
|
29
29
|
BackendSuccess,
|
|
30
|
+
BackendTransactionPreview,
|
|
30
31
|
CancelJobInput,
|
|
31
32
|
EventCursorInvalidError,
|
|
32
33
|
GetCacheSnapshotInput,
|
|
@@ -34,6 +35,9 @@ import type {
|
|
|
34
35
|
GetEventsSnapshot,
|
|
35
36
|
GetJobInput,
|
|
36
37
|
GetProjectOutlineInput,
|
|
38
|
+
QueryEntityInput,
|
|
39
|
+
BackendEntitySnapshot,
|
|
40
|
+
EntityQueryError,
|
|
37
41
|
ValidateSessionInput,
|
|
38
42
|
InProcessLockConflictError,
|
|
39
43
|
ListJobsInput,
|
|
@@ -42,11 +46,15 @@ import type {
|
|
|
42
46
|
MaterializeValidationFailedError,
|
|
43
47
|
MaterializeWriteFailedError,
|
|
44
48
|
OpenProjectSessionInput,
|
|
49
|
+
ProjectOpenFailedError,
|
|
50
|
+
ProjectRootNotAllowedError,
|
|
45
51
|
RefreshCacheInput,
|
|
46
52
|
SavePartialFailureError,
|
|
47
53
|
SaveSessionInput,
|
|
54
|
+
SessionIdConflictError,
|
|
48
55
|
SessionNotFoundError,
|
|
49
56
|
SessionStaleWriteError,
|
|
57
|
+
TransactionPreviewError,
|
|
50
58
|
UamFidelityUnsupportedError,
|
|
51
59
|
} from './runtime/contracts.js';
|
|
52
60
|
|
|
@@ -71,10 +79,11 @@ export class BackendRuntime {
|
|
|
71
79
|
|
|
72
80
|
public constructor(options: BackendRuntimeOptions = {}) {
|
|
73
81
|
this.fileSystem = options.fileSystem;
|
|
74
|
-
this.capabilities = createCapabilities();
|
|
82
|
+
this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
|
|
75
83
|
this.context = {
|
|
76
84
|
fileSystem: this.fileSystem,
|
|
77
85
|
host: options.host,
|
|
86
|
+
allowedProjectRoots: options.allowedProjectRoots,
|
|
78
87
|
capabilities: this.capabilities,
|
|
79
88
|
sessions: this.sessions,
|
|
80
89
|
sessionsByPath: this.sessionsByPath,
|
|
@@ -103,13 +112,28 @@ export class BackendRuntime {
|
|
|
103
112
|
}): Promise<
|
|
104
113
|
BackendResult<
|
|
105
114
|
BackendSessionSnapshot,
|
|
106
|
-
InProcessLockConflictError
|
|
115
|
+
InProcessLockConflictError
|
|
116
|
+
| AdvisoryLockConflictError
|
|
117
|
+
| BackendCapabilityUnavailableError
|
|
118
|
+
| ProjectRootNotAllowedError
|
|
119
|
+
| ProjectOpenFailedError
|
|
107
120
|
>
|
|
108
121
|
> {
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
122
|
+
const startedAt = Date.now();
|
|
123
|
+
try {
|
|
124
|
+
return await this.runtimeService.openSession(input);
|
|
125
|
+
} catch {
|
|
126
|
+
return failure('runtime', startedAt, {
|
|
127
|
+
code: 'project_open_failed',
|
|
128
|
+
message: 'Unable to open project.',
|
|
129
|
+
projectPath: input.projectPath,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
public openProjectSession(
|
|
135
|
+
input: OpenProjectSessionInput,
|
|
136
|
+
): BackendResult<BackendSessionSnapshot, InProcessLockConflictError | SessionIdConflictError> {
|
|
113
137
|
return this.runtimeService.openProjectSession(input);
|
|
114
138
|
}
|
|
115
139
|
|
|
@@ -123,12 +147,22 @@ export class BackendRuntime {
|
|
|
123
147
|
return this.readService.getProjectOutline(input);
|
|
124
148
|
}
|
|
125
149
|
|
|
150
|
+
public queryEntity(input: QueryEntityInput): BackendResult<BackendEntitySnapshot, SessionNotFoundError | EntityQueryError> {
|
|
151
|
+
return this.readService.queryEntity(input);
|
|
152
|
+
}
|
|
153
|
+
|
|
126
154
|
public validateSession(
|
|
127
155
|
input: ValidateSessionInput,
|
|
128
156
|
): BackendResult<ProjectValidationReport, SessionNotFoundError> {
|
|
129
157
|
return this.readService.validateSession(input);
|
|
130
158
|
}
|
|
131
159
|
|
|
160
|
+
public async preflightTransaction(
|
|
161
|
+
input: ApplySessionTransactionInput,
|
|
162
|
+
): Promise<BackendResult<BackendTransactionPreview, SessionNotFoundError | SessionStaleWriteError | ApplyUamTransactionAppError | TransactionPreviewError>> {
|
|
163
|
+
return this.authoringService.preflightTransaction(input);
|
|
164
|
+
}
|
|
165
|
+
|
|
132
166
|
public async applyTransaction(
|
|
133
167
|
input: ApplySessionTransactionInput,
|
|
134
168
|
): Promise<
|
|
@@ -180,7 +214,7 @@ export class BackendRuntime {
|
|
|
180
214
|
public async closeSession(input: {
|
|
181
215
|
sessionId: string;
|
|
182
216
|
}): Promise<BackendResult<{ sessionId: string; closed: true }, SessionNotFoundError>> {
|
|
183
|
-
return this.runtimeService.closeSession(input);
|
|
217
|
+
return this.authoringService.runSessionExclusive(input.sessionId, () => this.runtimeService.closeSession(input));
|
|
184
218
|
}
|
|
185
219
|
|
|
186
220
|
public getEvents(
|
|
@@ -17,6 +17,7 @@ import type {
|
|
|
17
17
|
BackendFileSystem,
|
|
18
18
|
BackendResult,
|
|
19
19
|
BackendSessionSnapshot,
|
|
20
|
+
BackendTransactionPreview,
|
|
20
21
|
InProcessLockConflictError,
|
|
21
22
|
MaterializeSessionInput,
|
|
22
23
|
MaterializeSessionSnapshot,
|
|
@@ -26,6 +27,7 @@ import type {
|
|
|
26
27
|
SaveSessionInput,
|
|
27
28
|
SessionNotFoundError,
|
|
28
29
|
SessionStaleWriteError,
|
|
30
|
+
TransactionPreviewError,
|
|
29
31
|
UamFidelityUnsupportedError,
|
|
30
32
|
} from '../runtime.js';
|
|
31
33
|
import type { CacheService } from './cache-service.js';
|
|
@@ -33,6 +35,7 @@ import { type BackendContext, failure, success } from './context.js';
|
|
|
33
35
|
import type { EventService } from './event-service.js';
|
|
34
36
|
import { writeSessionProject } from './session-project-writer.js';
|
|
35
37
|
import { createSessionNotFoundError, createStaleWriteError, toSessionSnapshot } from './session-utils.js';
|
|
38
|
+
import { PreviewBudgetError, previewTransactionImpact } from './transaction-preview.js';
|
|
36
39
|
|
|
37
40
|
function sourceFileKey(source: ProjectSourceFile): string {
|
|
38
41
|
return [source.branch, source.packageName, source.path, source.fileName].join('\0');
|
|
@@ -74,10 +77,11 @@ function recordStaleProjectFiles(
|
|
|
74
77
|
|
|
75
78
|
function toBackendDiagnostics(error: ApplyUamTransactionAppError): BackendDiagnostic[] {
|
|
76
79
|
return error.diagnostics.length > 0
|
|
77
|
-
? error.diagnostics.map((diagnostic) => ({ ...diagnostic }))
|
|
80
|
+
? error.diagnostics.map((diagnostic) => ({ ...diagnostic, owner: 'core.transaction' }))
|
|
78
81
|
: [
|
|
79
82
|
{
|
|
80
83
|
code: error.code,
|
|
84
|
+
owner: 'core.transaction',
|
|
81
85
|
message: error.message,
|
|
82
86
|
severity: 'error',
|
|
83
87
|
operationKind: error.operationKind,
|
|
@@ -178,7 +182,7 @@ export class AuthoringService {
|
|
|
178
182
|
private readonly eventService: EventService,
|
|
179
183
|
) {}
|
|
180
184
|
|
|
181
|
-
|
|
185
|
+
public async runSessionExclusive<T>(sessionId: string, operation: () => Promise<T>): Promise<T> {
|
|
182
186
|
const previous = this.sessionOperations.get(sessionId) ?? Promise.resolve();
|
|
183
187
|
let release = (): void => undefined;
|
|
184
188
|
const current = new Promise<void>((resolve) => {
|
|
@@ -195,6 +199,47 @@ export class AuthoringService {
|
|
|
195
199
|
}
|
|
196
200
|
}
|
|
197
201
|
|
|
202
|
+
public async preflightTransaction(
|
|
203
|
+
input: ApplySessionTransactionInput,
|
|
204
|
+
): Promise<BackendResult<BackendTransactionPreview, SessionNotFoundError | SessionStaleWriteError | ApplyUamTransactionAppError | TransactionPreviewError>> {
|
|
205
|
+
const queuedInput = structuredClone(input);
|
|
206
|
+
detachSharedByteViews(queuedInput);
|
|
207
|
+
return this.runSessionExclusive(queuedInput.sessionId, async () => {
|
|
208
|
+
const startedAt = Date.now();
|
|
209
|
+
const session = this.context.sessions.get(queuedInput.sessionId);
|
|
210
|
+
if (!session || session.closed) return failure('authoring', startedAt, createSessionNotFoundError(queuedInput.sessionId));
|
|
211
|
+
const meta = { sessionId: session.sessionId, revision: session.revision };
|
|
212
|
+
if (queuedInput.expectedRevision !== session.revision) {
|
|
213
|
+
return failure('authoring', startedAt, createStaleWriteError(session, queuedInput.expectedRevision),
|
|
214
|
+
toSessionSnapshot(session, this.context.capabilities), meta);
|
|
215
|
+
}
|
|
216
|
+
// The authoritative session, including source bytes, never enters the preview executor.
|
|
217
|
+
const project = structuredClone(session.project);
|
|
218
|
+
detachSharedByteViews(project);
|
|
219
|
+
const result = await applyUamTransactionAppAsync({ project, operations: queuedInput.operations });
|
|
220
|
+
if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) {
|
|
221
|
+
return failure('authoring', startedAt, createSessionNotFoundError(queuedInput.sessionId));
|
|
222
|
+
}
|
|
223
|
+
if (!result.ok) {
|
|
224
|
+
return failure('authoring', startedAt, result.error, toSessionSnapshot(session, this.context.capabilities),
|
|
225
|
+
{ ...meta, diagnostics: toBackendDiagnostics(result.error) });
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
const preview = await previewTransactionImpact({ ...session, project }, result.project, Boolean(session.fileSystem));
|
|
229
|
+
if (this.context.sessions.get(queuedInput.sessionId) !== session || session.closed) {
|
|
230
|
+
return failure('authoring', startedAt, createSessionNotFoundError(queuedInput.sessionId));
|
|
231
|
+
}
|
|
232
|
+
return success('authoring', startedAt, preview, meta);
|
|
233
|
+
} catch (error) {
|
|
234
|
+
return failure('authoring', startedAt, {
|
|
235
|
+
code: 'transaction_preview_failed' as const, sessionId: session.sessionId,
|
|
236
|
+
reason: error instanceof PreviewBudgetError ? 'response_budget_exceeded' as const : 'projection_failed' as const,
|
|
237
|
+
message: error instanceof Error ? error.message : String(error),
|
|
238
|
+
}, toSessionSnapshot(session, this.context.capabilities), meta);
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
198
243
|
public async applyTransaction(
|
|
199
244
|
input: ApplySessionTransactionInput,
|
|
200
245
|
): Promise<
|
|
@@ -344,7 +389,7 @@ export class AuthoringService {
|
|
|
344
389
|
if (!session || session.closed) {
|
|
345
390
|
return failure('authoring', startedAt, createSessionNotFoundError(input.sessionId));
|
|
346
391
|
}
|
|
347
|
-
const fileSystem = session.fileSystem ?? input.fileSystem
|
|
392
|
+
const fileSystem = session.fileSystem ?? input.fileSystem;
|
|
348
393
|
if (!fileSystem) {
|
|
349
394
|
return failure(
|
|
350
395
|
'authoring',
|
|
@@ -465,7 +510,7 @@ export class AuthoringService {
|
|
|
465
510
|
lastSavedRevision: session.lastSavedRevision,
|
|
466
511
|
committedPaths,
|
|
467
512
|
failedPaths,
|
|
468
|
-
diskMayBePartiallyUpdated:
|
|
513
|
+
diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction,
|
|
469
514
|
},
|
|
470
515
|
toSessionSnapshot(session, this.context.capabilities),
|
|
471
516
|
{
|
|
@@ -529,7 +574,7 @@ export class AuthoringService {
|
|
|
529
574
|
|
|
530
575
|
const storageTarget = input.storage ? storageCanonicalTarget(input.storage) : null;
|
|
531
576
|
const fileSystem =
|
|
532
|
-
storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem
|
|
577
|
+
storageTarget?.fileSystem ?? input.fileSystem ?? session.fileSystem;
|
|
533
578
|
if (!fileSystem) {
|
|
534
579
|
return failure(
|
|
535
580
|
'authoring',
|
|
@@ -744,7 +789,7 @@ export class AuthoringService {
|
|
|
744
789
|
failedPaths,
|
|
745
790
|
skippedPaths,
|
|
746
791
|
diagnostics: diagnosticsFromError,
|
|
747
|
-
diskMayBePartiallyUpdated:
|
|
792
|
+
diskMayBePartiallyUpdated: !fileSystem.runProjectWriteTransaction,
|
|
748
793
|
},
|
|
749
794
|
toSessionSnapshot(session, this.context.capabilities),
|
|
750
795
|
{
|
|
@@ -0,0 +1,75 @@
|
|
|
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
|
+
}
|
package/src/services/context.ts
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
type BackendResponseMeta,
|
|
7
7
|
type BackendStage,
|
|
8
8
|
} from '../contracts.js';
|
|
9
|
+
import { enrichBackendDiagnostic } from '../diagnostics.js';
|
|
9
10
|
import type {
|
|
10
11
|
BackendCacheEntry,
|
|
11
12
|
BackendCapabilities,
|
|
@@ -48,6 +49,7 @@ export interface BackendSessionState {
|
|
|
48
49
|
export interface BackendContext {
|
|
49
50
|
fileSystem?: BackendFileSystem;
|
|
50
51
|
host?: BackendHostAdapter;
|
|
52
|
+
allowedProjectRoots?: readonly string[];
|
|
51
53
|
capabilities: BackendCapabilities;
|
|
52
54
|
sessions: Map<string, BackendSessionState>;
|
|
53
55
|
sessionsByPath: Map<string, string>;
|
|
@@ -86,7 +88,7 @@ export function createMeta(
|
|
|
86
88
|
revision: options?.revision,
|
|
87
89
|
durationMs: Math.max(0, Date.now() - startedAt),
|
|
88
90
|
warnings: options?.warnings ?? [],
|
|
89
|
-
diagnostics: options?.diagnostics ?? [],
|
|
91
|
+
diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
|
|
90
92
|
stage,
|
|
91
93
|
contractVersion: BACKEND_CONTRACT_VERSION,
|
|
92
94
|
capabilitySchemaVersion: BACKEND_CAPABILITY_SCHEMA_VERSION,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { failure, success, type BackendContext } from './context.js';
|
|
2
|
+
import { enrichBackendDiagnostic } from '../diagnostics.js';
|
|
2
3
|
import { createSessionNotFoundError } from './session-utils.js';
|
|
3
4
|
import type {
|
|
4
5
|
BackendEvent,
|
|
@@ -21,7 +22,7 @@ export class EventService {
|
|
|
21
22
|
...event,
|
|
22
23
|
sequence: this.context.nextEventSequence(),
|
|
23
24
|
timestamp: new Date().toISOString(),
|
|
24
|
-
diagnostics: event.diagnostics ?? [],
|
|
25
|
+
diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId)),
|
|
25
26
|
};
|
|
26
27
|
const sessionId = event.sessionId;
|
|
27
28
|
if (!sessionId) return emitted;
|