@openfairygui/backend 0.6.3 → 0.7.1

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,89 +0,0 @@
1
- import type { Document } from '@openfairygui/core';
2
- import { type FileSystem, type ProjectBranchDirectory, type ProjectSourceFile, ProjectWriter } from '@openfairygui/core/project-io';
3
- import type { BackendFileSystem } from '../runtime.js';
4
- import { ProjectWriteTransactionError } from '../runtime/contracts.js';
5
- import { assertProjectPathContained } from '../path-policy.js';
6
-
7
- function createWriterFileSystem(
8
- fileSystem: BackendFileSystem,
9
- projectRoot: string,
10
- writtenPaths: string[],
11
- failedPaths: string[],
12
- ): FileSystem {
13
- const contained = async <T>(targetPath: string, operation: () => Promise<T>): Promise<T> => {
14
- await assertProjectPathContained(fileSystem, projectRoot, targetPath);
15
- return operation();
16
- };
17
- async function trackWrite<T>(targetPath: string, write: () => Promise<T>): Promise<T> {
18
- try {
19
- const result = await contained(targetPath, write);
20
- writtenPaths.push(targetPath);
21
- return result;
22
- } catch (error) {
23
- failedPaths.push(targetPath);
24
- throw error;
25
- }
26
- }
27
-
28
- return {
29
- resolvePath: (path) => contained(path, () => fileSystem.resolvePath(path)),
30
- readFile: (path) => contained(path, () => fileSystem.readFile(path)),
31
- readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
32
- writeFile: (path, content) =>
33
- trackWrite(path, async () => {
34
- await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
35
- await fileSystem.writeFile(path, content);
36
- }),
37
- writeFileRaw: (path, data) =>
38
- trackWrite(path, async () => {
39
- await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
40
- await fileSystem.writeFileRaw(path, data);
41
- }),
42
- mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
43
- readdir: (path) => contained(path, () => fileSystem.readdir(path)),
44
- async exists(path): Promise<boolean> {
45
- await assertProjectPathContained(fileSystem, projectRoot, path);
46
- try {
47
- await fileSystem.stat(path);
48
- return true;
49
- } catch {
50
- return false;
51
- }
52
- },
53
- join: (...paths) => fileSystem.join(...paths),
54
- dirname: (path) => fileSystem.dirname(path),
55
- unlink: (path) => trackWrite(path, () => fileSystem.unlink(path)),
56
- rmdir: (path) => trackWrite(path, () => fileSystem.rmdir(path)),
57
- };
58
- }
59
-
60
- export async function writeSessionProject(input: {
61
- fileSystem: BackendFileSystem;
62
- document: Document;
63
- fairyPath: string;
64
- staleSourceFiles: ProjectSourceFile[];
65
- staleResourceFolders: import('@openfairygui/core/project-io').ProjectResourceFolder[];
66
- staleBranchDirectories: ProjectBranchDirectory[];
67
- writtenPaths: string[];
68
- failedPaths: string[];
69
- }): Promise<void> {
70
- const projectRoot = input.fileSystem.dirname(input.fairyPath);
71
- const write = async (fileSystem: BackendFileSystem): Promise<void> => {
72
- const writer = new ProjectWriter(
73
- createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths),
74
- );
75
- await writer.write(input.document, input.fairyPath, {
76
- staleSourceFiles: input.staleSourceFiles,
77
- staleResourceFolders: input.staleResourceFolders,
78
- staleBranchDirectories: input.staleBranchDirectories,
79
- });
80
- };
81
-
82
- if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
83
- try {
84
- await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
85
- } catch (error) {
86
- if (ProjectWriteTransactionError.is(error) && !error.diskMayBePartiallyUpdated) input.writtenPaths.length = 0;
87
- throw error;
88
- }
89
- }
@@ -1,70 +0,0 @@
1
- import type { InProcessLockConflictError } from '../runtime/contracts.js';
2
- import type { BackendSessionState } from './context.js';
3
-
4
- type SessionTarget = Pick<BackendSessionState, 'canonicalPathKey' | 'canonicalProjectPath'> &
5
- Partial<Pick<BackendSessionState, 'fileSystem' | 'fairyPath' | 'lockFilePath'>>;
6
-
7
- interface PathReservation {
8
- commit(session: BackendSessionState): void;
9
- release(): void;
10
- }
11
-
12
- /** Owns live sessions and path claims, including claims made before asynchronous I/O. */
13
- export class SessionRegistry {
14
- private readonly sessions = new Map<string, BackendSessionState>();
15
- private readonly paths = new Map<string, { sessionId: string }>();
16
- private readonly opening = new Set<string>();
17
-
18
- public get(sessionId: string): BackendSessionState | undefined {
19
- return this.sessions.get(sessionId);
20
- }
21
-
22
- public has(sessionId: string): boolean {
23
- return this.sessions.has(sessionId) || this.opening.has(sessionId);
24
- }
25
-
26
- public reserve(sessionId: string, target: SessionTarget): PathReservation | InProcessLockConflictError {
27
- const key = target.canonicalPathKey;
28
- const previous = this.paths.get(key);
29
- if (previous && previous.sessionId !== sessionId) {
30
- return {
31
- code: 'lock_conflict',
32
- kind: 'in_process_session_exists',
33
- message: `Project is already open in this backend runtime: ${target.canonicalProjectPath}`,
34
- canonicalPathKey: key,
35
- holderSessionId: previous.sessionId,
36
- lockFilePath: target.lockFilePath,
37
- };
38
- }
39
- const claim = previous ?? { sessionId };
40
- this.paths.set(key, claim);
41
- if (!this.sessions.has(sessionId)) this.opening.add(sessionId);
42
- let committed = false;
43
- return {
44
- commit: (session) => {
45
- if (session.sessionId !== sessionId || this.paths.get(key) !== claim)
46
- throw new Error('Session path reservation lost.');
47
- if (session.canonicalPathKey !== key) this.releasePath(session.canonicalPathKey, sessionId);
48
- Object.assign(session, target);
49
- this.sessions.set(sessionId, session);
50
- this.opening.delete(sessionId);
51
- committed = true;
52
- },
53
- release: () => {
54
- if (committed) return;
55
- if (!previous && this.paths.get(key) === claim) this.paths.delete(key);
56
- this.opening.delete(sessionId);
57
- },
58
- };
59
- }
60
-
61
- public remove(session: BackendSessionState): void {
62
- if (this.sessions.get(session.sessionId) !== session) return;
63
- this.sessions.delete(session.sessionId);
64
- this.releasePath(session.canonicalPathKey, session.sessionId);
65
- }
66
-
67
- private releasePath(key: string, sessionId: string): void {
68
- if (this.paths.get(key)?.sessionId === sessionId) this.paths.delete(key);
69
- }
70
- }
@@ -1,45 +0,0 @@
1
- import type {
2
- BackendCapabilities,
3
- BackendSessionSnapshot,
4
- SessionNotFoundError,
5
- SessionStaleWriteError,
6
- } from '../runtime.js';
7
- import { cloneReadData, type ReadonlyData, type BackendSessionState, type SessionReadView } from './context.js';
8
-
9
- export function toSessionSnapshot(
10
- session: Pick<SessionReadView, 'sessionId' | 'canonicalProjectPath' | 'revision' | 'lastSavedRevision' | 'dirty' | 'uamFidelity' | 'lockHeld'>,
11
- capabilities: ReadonlyData<BackendCapabilities>,
12
- ): BackendSessionSnapshot {
13
- return {
14
- sessionId: session.sessionId,
15
- canonicalProjectPath: session.canonicalProjectPath,
16
- revision: session.revision,
17
- lastSavedRevision: session.lastSavedRevision,
18
- dirty: session.dirty,
19
- uamFidelity: session.uamFidelity,
20
- lockHeld: session.lockHeld,
21
- capabilities: cloneReadData<BackendCapabilities>(capabilities),
22
- };
23
- }
24
-
25
- export function createSessionNotFoundError(sessionId: string): SessionNotFoundError {
26
- return {
27
- code: 'session_not_found',
28
- message: `Session was not found: ${sessionId}`,
29
- sessionId,
30
- };
31
- }
32
-
33
- export function createStaleWriteError(
34
- session: Pick<BackendSessionState, 'sessionId' | 'canonicalPathKey' | 'revision'>,
35
- expectedRevision: number,
36
- ): SessionStaleWriteError {
37
- return {
38
- code: 'stale_write',
39
- message: `Expected revision ${expectedRevision} does not match current revision ${session.revision}.`,
40
- sessionId: session.sessionId,
41
- canonicalPathKey: session.canonicalPathKey,
42
- expectedRevision,
43
- actualRevision: session.revision,
44
- };
45
- }
@@ -1,116 +0,0 @@
1
- import { materializeUamProject, type UamProject } from '@openfairygui/core/uam';
2
- import { BACKEND_TRANSACTION_PREVIEW_LIMITS, type BackendTransactionEntityChange, type BackendTransactionPreview } from '../runtime/contracts.js';
3
- import { captureProject } from './capture-project.js';
4
- import type { BackendSessionState } from './context.js';
5
-
6
- type Entity = { target: BackendTransactionEntityChange['target']; properties: Record<string, unknown> };
7
-
8
- /** Keep child identities/order on their parent, and compare each child's own properties separately. */
9
- function entities(project: UamProject): Map<string, Entity> {
10
- const result = new Map<string, Entity>();
11
- function add(target: Entity['target'], properties: object): void {
12
- const key = JSON.stringify(target);
13
- if (result.has(key)) throw new Error(`Ambiguous preview identity: ${key}`);
14
- result.set(key, { target, properties: properties as Entity['properties'] });
15
- }
16
- const { packages, ...properties } = project;
17
- add({ kind: 'project' }, { ...properties, packages: packages.map((pkg) => pkg.id) });
18
- for (const { resources, ...pkg } of packages) {
19
- const packageId = pkg.id;
20
- add({ kind: 'package', selector: { packageId } }, { ...pkg, resources: resources.map((resource) => resource.id) });
21
- for (const resource of resources) {
22
- const resourceTarget = { kind: 'resource' as const, selector: { packageId, resourceId: resource.id } };
23
- if (resource.kind !== 'component') { add(resourceTarget, resource); continue; }
24
- const { component, ...resourceProperties } = resource;
25
- add(resourceTarget, resourceProperties);
26
- const { displayList, controllers, transitions, ...componentProperties } = component;
27
- const selector = { packageId, componentResourceId: resource.id };
28
- add({ kind: 'component', selector }, {
29
- ...componentProperties, displayList: displayList.map((node) => node.id),
30
- controllers: controllers.map((controller) => controller.name), transitions: transitions.map((transition) => transition.name),
31
- });
32
- for (const node of displayList) add({ kind: 'displayNode', selector: { ...selector, displayNodeId: node.id } }, node);
33
- for (const controller of controllers) add({ kind: 'controller', selector: { ...selector, controllerName: controller.name } }, controller);
34
- for (const transition of transitions) add({ kind: 'transition', selector: { ...selector, transitionName: transition.name } }, transition);
35
- }
36
- }
37
- return result;
38
- }
39
-
40
- function equal(left: unknown, right: unknown, depth = 0): boolean {
41
- if (left === right) return true;
42
- if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false;
43
- if (left instanceof Uint8Array || right instanceof Uint8Array) {
44
- return left instanceof Uint8Array && right instanceof Uint8Array && left.length === right.length
45
- && left.every((value, index) => value === right[index]);
46
- }
47
- if (depth > 128) throw new Error('Preview property comparison exceeds the supported nesting depth.');
48
- if (Array.isArray(left) !== Array.isArray(right)) return false;
49
- if (Array.isArray(left) && Array.isArray(right) && left.length !== right.length) return false;
50
- const a = left as Record<string, unknown>, b = right as Record<string, unknown>;
51
- const keys = Object.keys(a);
52
- return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && equal(a[key], b[key], depth + 1));
53
- }
54
-
55
- export class PreviewBudgetError extends Error {}
56
-
57
- /** No host filesystem, cache, event or session mutation is involved in the projection. */
58
- export async function previewTransactionImpact(
59
- session: BackendSessionState,
60
- project: UamProject,
61
- fileSystemAvailable: boolean,
62
- ): Promise<BackendTransactionPreview> {
63
- const impact: BackendTransactionPreview['impact'] = { entities: [], files: [] };
64
- const before = entities(session.project), after = entities(project);
65
- let entries = 0, bytes = 0;
66
- const encoder = new TextEncoder();
67
- function count(value: unknown): void {
68
- bytes += encoder.encode(JSON.stringify(value)).byteLength;
69
- if (++entries > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxEntries || bytes > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) {
70
- throw new PreviewBudgetError('The complete transaction impact exceeds the preview response budget.');
71
- }
72
- }
73
- for (const key of new Set([...before.keys(), ...after.keys()])) {
74
- const previous = before.get(key), next = after.get(key);
75
- const fields = [...new Set([...Object.keys(previous?.properties ?? {}), ...Object.keys(next?.properties ?? {})])]
76
- .filter((field) => !previous || !next || !equal(previous.properties[field], next.properties[field])).sort();
77
- if (!fields.length && previous && next) continue;
78
- const change: BackendTransactionEntityChange = {
79
- target: (next ?? previous)!.target, change: !previous ? 'added' : !next ? 'removed' : 'updated', fields,
80
- };
81
- count(change); impact.entities.push(change);
82
- }
83
- const fairyFileName = session.fileSystem ? session.fairyPath.replace(/\\/g, '/').split('/').at(-1)! : 'Project.fairy';
84
- // ponytail: two full in-memory serializations reuse the writer; add writer-level incremental planning only if measured cost requires it.
85
- const [previousFiles, nextFiles] = await Promise.all([
86
- // The existing snapshot may contain the broken reference this transaction repairs.
87
- // It is serialized only into memory; the projected state and every save remain validated.
88
- captureProject(materializeUamProject(session.project, { validate: false }), fairyFileName),
89
- captureProject(materializeUamProject(project), fairyFileName),
90
- ]);
91
- for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
92
- const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
93
- if (equal(previous, next)) continue;
94
- const change = { path, kind: 'file' as const, change: previous === undefined ? 'added' as const : next === undefined ? 'removed' as const : 'updated' as const };
95
- count(change); impact.files.push(change);
96
- }
97
- for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
98
- if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
99
- const change = { path, kind: 'directory' as const, change: nextFiles.directories.has(path) ? 'added' as const : 'removed' as const };
100
- count(change); impact.files.push(change);
101
- }
102
- impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
103
- const preview: BackendTransactionPreview = {
104
- sessionId: session.sessionId, baseRevision: session.revision, projectedRevision: session.revision + 1,
105
- mode: 'execute-and-discard', impact,
106
- persistence: {
107
- requiredAfterApply: true, fileSystemAvailable, uamFidelity: session.uamFidelity, writeVerified: false,
108
- nextAction: session.uamFidelity === 'unsupported' || !fileSystemAvailable ? 'host-action'
109
- : session.fileSystem ? 'saveSession' : 'materializeSession',
110
- },
111
- };
112
- if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) {
113
- throw new PreviewBudgetError('The complete transaction preview exceeds the response byte budget.');
114
- }
115
- return preview;
116
- }
package/src/storage.ts DELETED
@@ -1,232 +0,0 @@
1
- import type { FileSystem as CoreProjectFileSystem } from '@openfairygui/core/project-io';
2
- import type { BackendFileStat, BackendFileSystem, BackendSessionLock } from './runtime.js';
3
-
4
- type StorageStatKind = 'file' | 'directory';
5
-
6
- export interface BackendStorageStatLike {
7
- kind?: StorageStatKind;
8
- type?: StorageStatKind;
9
- isFile?(): boolean;
10
- isDirectory?(): boolean;
11
- }
12
-
13
- export interface BackendAsyncStorageAdapter {
14
- readFile(filePath: string): Promise<string>;
15
- readFileRaw(filePath: string): Promise<Uint8Array>;
16
- writeFile(filePath: string, content: string): Promise<void>;
17
- writeFileRaw(filePath: string, data: Uint8Array): Promise<void>;
18
- mkdir(dirPath: string, options?: { recursive?: boolean }): Promise<void>;
19
- readdir(dirPath: string): Promise<string[]>;
20
- exists?(filePath: string): Promise<boolean>;
21
- stat?(filePath: string): Promise<BackendStorageStatLike>;
22
- /** Stable cross-context path identity; also scopes the default Web Lock name. */
23
- resolvePath?(filePath: string): Promise<string>;
24
- /**
25
- * Optional replacement for Web Locks. Acquisition must be atomic across browser contexts, remain held
26
- * until release(), and recover automatically when the owning document terminates.
27
- */
28
- acquireSessionLock?(lockPath: string): Promise<BackendSessionLock>;
29
- unlink(filePath: string): Promise<void>;
30
- rmdir(dirPath: string): Promise<void>;
31
- join?(...paths: string[]): string;
32
- dirname?(filePath: string): string;
33
- resolve?(...paths: string[]): string;
34
- }
35
-
36
- class StorageFileStat implements BackendFileStat {
37
- public constructor(private readonly kind: StorageStatKind) {}
38
-
39
- public isFile(): boolean {
40
- return this.kind === 'file';
41
- }
42
-
43
- public isDirectory(): boolean {
44
- return this.kind === 'directory';
45
- }
46
- }
47
-
48
- function createPathError(code: string, message: string): Error & { code: string } {
49
- const error = new Error(message) as Error & { code: string };
50
- error.code = code;
51
- return error;
52
- }
53
-
54
- function getWebLockManager(): LockManager | null {
55
- if (typeof navigator === 'undefined') return null;
56
- const lockManager = (navigator as Navigator & { locks?: LockManager }).locks;
57
- return lockManager && typeof lockManager.request === 'function' ? lockManager : null;
58
- }
59
-
60
- function acquireWebSessionLock(lockManager: LockManager, lockName: string): Promise<BackendSessionLock> {
61
- return new Promise((resolve, reject) => {
62
- let releasePlatformLock = (): void => undefined;
63
- const held = new Promise<void>((release) => {
64
- releasePlatformLock = release;
65
- });
66
- void lockManager
67
- .request(lockName, { mode: 'exclusive', ifAvailable: true }, async (lock) => {
68
- if (!lock) {
69
- reject(createPathError('EEXIST', `Browser session lock is already held: ${lockName}`));
70
- return;
71
- }
72
- let released = false;
73
- resolve({
74
- // Web Locks are the authority; a persisted marker would survive abrupt document termination.
75
- writeMetadata(): Promise<void> {
76
- return Promise.resolve();
77
- },
78
- release(): Promise<void> {
79
- if (!released) {
80
- released = true;
81
- releasePlatformLock();
82
- }
83
- return Promise.resolve();
84
- },
85
- });
86
- await held;
87
- })
88
- .catch(reject);
89
- });
90
- }
91
-
92
- function normalizeStoragePath(value: string): string {
93
- const normalized = value.replace(/\\/g, '/').replace(/\/+/g, '/');
94
- const absolute = normalized.startsWith('/');
95
- const rawSegments = normalized.split('/').filter((segment) => segment.length > 0);
96
- const segments: string[] = [];
97
-
98
- for (const segment of rawSegments) {
99
- if (segment === '.') continue;
100
- if (segment === '..') {
101
- if (segments.length > 0) segments.pop();
102
- continue;
103
- }
104
- segments.push(segment);
105
- }
106
-
107
- const joined = segments.join('/');
108
- if (absolute) return joined ? `/${joined}` : '/';
109
- return joined || '.';
110
- }
111
-
112
- function joinStoragePath(...paths: string[]): string {
113
- return normalizeStoragePath(paths.filter((part) => part.length > 0).join('/'));
114
- }
115
-
116
- function dirnameStoragePath(filePath: string): string {
117
- const normalized = normalizeStoragePath(filePath);
118
- if (normalized === '/' || normalized === '.') return '.';
119
- const absolute = normalized.startsWith('/');
120
- const parts = normalized.split('/').filter((part) => part.length > 0);
121
- parts.pop();
122
- if (parts.length === 0) return absolute ? '/' : '.';
123
- return `${absolute ? '/' : ''}${parts.join('/')}`;
124
- }
125
-
126
- function statFromLike(stat: BackendStorageStatLike): BackendFileStat {
127
- if (typeof stat.isFile === 'function' && typeof stat.isDirectory === 'function') {
128
- return stat as BackendFileStat;
129
- }
130
- const kind = stat.kind ?? stat.type;
131
- if (kind === 'file' || kind === 'directory') return new StorageFileStat(kind);
132
- throw createPathError('EINVAL', 'Storage stat must provide kind/type or isFile()/isDirectory().');
133
- }
134
-
135
- async function inferStat(storage: BackendAsyncStorageAdapter, filePath: string): Promise<BackendFileStat> {
136
- if (storage.stat) return statFromLike(await storage.stat(filePath));
137
-
138
- try {
139
- await storage.readdir(filePath);
140
- return new StorageFileStat('directory');
141
- } catch {
142
- // Try file probes below.
143
- }
144
-
145
- try {
146
- await storage.readFileRaw(filePath);
147
- return new StorageFileStat('file');
148
- } catch {
149
- try {
150
- await storage.readFile(filePath);
151
- return new StorageFileStat('file');
152
- } catch {
153
- throw createPathError('ENOENT', `Storage path not found: ${filePath}`);
154
- }
155
- }
156
- }
157
-
158
- export type BackendStorageFileSystem = BackendFileSystem & CoreProjectFileSystem;
159
-
160
- export function createBackendStorageFileSystem(storage: BackendAsyncStorageAdapter): BackendStorageFileSystem {
161
- if (typeof storage.unlink !== 'function') {
162
- throw createPathError('ENOTSUP', 'Storage adapter must provide unlink() for project resource lifecycle writes.');
163
- }
164
- if (typeof storage.rmdir !== 'function') {
165
- throw createPathError('ENOTSUP', 'Storage adapter must provide rmdir() for project resource folder lifecycle writes.');
166
- }
167
- const fileSystem: BackendStorageFileSystem = {
168
- stat(filePath: string): Promise<BackendFileStat> {
169
- return inferStat(storage, fileSystem.resolve(filePath));
170
- },
171
- readdir(dirPath: string): Promise<string[]> {
172
- return storage.readdir(fileSystem.resolve(dirPath));
173
- },
174
- readFile(filePath: string): Promise<string> {
175
- return storage.readFile(fileSystem.resolve(filePath));
176
- },
177
- readFileRaw(filePath: string): Promise<Uint8Array> {
178
- return storage.readFileRaw(fileSystem.resolve(filePath));
179
- },
180
- writeFile(filePath: string, content: string): Promise<void> {
181
- return storage.writeFile(fileSystem.resolve(filePath), content);
182
- },
183
- writeFileRaw(filePath: string, data: Uint8Array): Promise<void> {
184
- return storage.writeFileRaw(fileSystem.resolve(filePath), data);
185
- },
186
- mkdir(dirPath: string, options?: { recursive?: boolean }): Promise<void> {
187
- return storage.mkdir(fileSystem.resolve(dirPath), options);
188
- },
189
- async exists(filePath: string): Promise<boolean> {
190
- if (storage.exists) return storage.exists(fileSystem.resolve(filePath));
191
- try {
192
- await fileSystem.stat(filePath);
193
- return true;
194
- } catch {
195
- return false;
196
- }
197
- },
198
- resolvePath(filePath: string): Promise<string> {
199
- const resolved = fileSystem.resolve(filePath);
200
- return storage.resolvePath ? storage.resolvePath(resolved) : Promise.resolve(resolved);
201
- },
202
- async acquireSessionLock(lockPath: string): Promise<BackendSessionLock> {
203
- const resolved = fileSystem.resolve(lockPath);
204
- if (storage.acquireSessionLock) return storage.acquireSessionLock(resolved);
205
- const lockManager = getWebLockManager();
206
- if (!lockManager) {
207
- throw createPathError(
208
- 'ENOTSUP',
209
- 'Browser openSession requires Web Locks or BackendAsyncStorageAdapter.acquireSessionLock().',
210
- );
211
- }
212
- return acquireWebSessionLock(lockManager, `@openfairygui/backend:${resolved}`);
213
- },
214
- unlink(filePath: string): Promise<void> {
215
- return storage.unlink(fileSystem.resolve(filePath));
216
- },
217
- rmdir(dirPath: string): Promise<void> {
218
- return storage.rmdir(fileSystem.resolve(dirPath));
219
- },
220
- join(...paths: string[]): string {
221
- return storage.join ? storage.join(...paths) : joinStoragePath(...paths);
222
- },
223
- dirname(filePath: string): string {
224
- return storage.dirname ? storage.dirname(filePath) : dirnameStoragePath(filePath);
225
- },
226
- resolve(...paths: string[]): string {
227
- return storage.resolve ? storage.resolve(...paths) : joinStoragePath(...paths);
228
- },
229
- };
230
-
231
- return fileSystem;
232
- }