@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.
@@ -5,11 +5,40 @@ import type {
5
5
  BackendResult,
6
6
  BackendSessionSnapshot,
7
7
  GetProjectOutlineInput,
8
+ QueryEntityInput,
9
+ BackendEntitySnapshot,
10
+ BackendResourceSnapshot,
11
+ EntityQueryError,
8
12
  SessionNotFoundError,
9
13
  } from '../runtime.js';
10
14
  import { createSessionNotFoundError, toSessionSnapshot } from './session-utils.js';
11
15
  import { validateProject } from '@openfairygui/functions';
12
16
  import type { ProjectValidationReport } from '@openfairygui/core';
17
+ import { BACKEND_ENTITY_QUERY_LIMITS, BACKEND_RESOURCE_QUERY_FIELDS } from '../runtime/contracts.js';
18
+
19
+ /** Bound traversal before serialization or cloning, including non-JSON values on a malformed native input. */
20
+ function queryResponseProblem(value: unknown): EntityQueryError['reason'] | undefined {
21
+ const pending = [{ value, depth: 0 }];
22
+ let nodes = 0;
23
+ let stringUnits = 0;
24
+ while (pending.length) {
25
+ const { value, depth } = pending.pop()!;
26
+ if (++nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes || depth > BACKEND_ENTITY_QUERY_LIMITS.maxDepth) return 'response_budget_exceeded';
27
+ if (typeof value === 'string' && (stringUnits += value.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return 'response_budget_exceeded';
28
+ if (value === undefined || value === null || typeof value === 'string' || typeof value === 'boolean') continue;
29
+ if (typeof value === 'number') { if (!Number.isFinite(value)) return 'non_json_value'; continue; }
30
+ if (typeof value !== 'object' || (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) return 'non_json_value';
31
+ if (Array.isArray(value) && value.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return 'response_budget_exceeded';
32
+ const entries = Object.entries(value);
33
+ if (entries.length + pending.length + nodes > BACKEND_ENTITY_QUERY_LIMITS.maxNodes) return 'response_budget_exceeded';
34
+ for (const [key, child] of entries) {
35
+ if (!Array.isArray(value) && (stringUnits += key.length) > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return 'response_budget_exceeded';
36
+ pending.push({ value: child, depth: depth + 1 });
37
+ }
38
+ }
39
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > BACKEND_ENTITY_QUERY_LIMITS.maxBytes) return 'response_budget_exceeded';
40
+ return undefined;
41
+ }
13
42
 
14
43
  function toProjectOutline(session: BackendSessionState): BackendProjectOutline {
15
44
  const project = session.project;
@@ -84,6 +113,73 @@ export class ReadService {
84
113
  });
85
114
  }
86
115
 
116
+ public queryEntity(input: QueryEntityInput): BackendResult<BackendEntitySnapshot, SessionNotFoundError | EntityQueryError> {
117
+ const startedAt = Date.now();
118
+ const session = this.context.sessions.get(input.sessionId);
119
+ if (!session || session.closed) return failure('read', startedAt, createSessionNotFoundError(input.sessionId));
120
+ const meta = { sessionId: session.sessionId, revision: session.revision };
121
+ const reject = (reason: EntityQueryError['reason']) => failure('read', startedAt, {
122
+ code: 'entity_query_failed' as const, sessionId: session.sessionId, reason,
123
+ message: `Entity query failed: ${reason}.`,
124
+ }, undefined, meta);
125
+ const target = input.target;
126
+ if (!target || typeof target !== 'object' || Array.isArray(target) || Object.keys(target).some((key) => key !== 'kind' && key !== 'selector')) return reject('invalid_query');
127
+ const respond = (entity: BackendEntitySnapshot['entity']) => {
128
+ const data = { ...meta, target, entity };
129
+ const problem = queryResponseProblem(data);
130
+ return problem ? reject(problem) : success('read', startedAt, structuredClone(data), meta);
131
+ };
132
+ if (target.kind === 'project') {
133
+ if (Object.hasOwn(target, 'selector')) return reject('invalid_query');
134
+ const { projectId, settings } = session.project;
135
+ return respond({ kind: 'project', properties: { projectId, settings } });
136
+ }
137
+ const keys = target.kind === 'package' ? ['packageId']
138
+ : target.kind === 'resource' ? ['packageId', 'resourceId']
139
+ : target.kind === 'component' ? ['packageId', 'componentResourceId']
140
+ : target.kind === 'displayNode' ? ['packageId', 'componentResourceId', 'displayNodeId']
141
+ : target.kind === 'controller' ? ['packageId', 'componentResourceId', 'controllerName']
142
+ : target.kind === 'transition' ? ['packageId', 'componentResourceId', 'transitionName'] : [];
143
+ const selector = target.selector as unknown as Record<string, unknown>;
144
+ if (!keys.length || !selector || typeof selector !== 'object' || Array.isArray(selector)
145
+ || Object.keys(selector).length !== keys.length
146
+ || keys.some((key) => !Object.hasOwn(selector, key) || typeof selector[key] !== 'string' || !(selector[key] as string).length || (selector[key] as string).length > 256)) return reject('invalid_query');
147
+ const packages = session.project.packages.filter((pkg) => pkg.id === selector.packageId);
148
+ if (packages.length !== 1) return reject(packages.length ? 'ambiguous' : 'not_found');
149
+ if (target.kind === 'package') {
150
+ const { id, name, compressPNG, jpegQuality, publish } = packages[0];
151
+ return respond({ kind: 'package', properties: { id, name, settings: { compressPNG, jpegQuality, publish } } });
152
+ }
153
+ const resources = packages[0].resources.filter((resource) => resource.id === (target.kind === 'resource' ? selector.resourceId : selector.componentResourceId));
154
+ if (resources.length !== 1) return reject(resources.length ? 'ambiguous' : 'not_found');
155
+ const resource = resources[0];
156
+ let entity: BackendEntitySnapshot['entity'];
157
+ if (target.kind === 'resource') {
158
+ const record = resource as unknown as Record<string, unknown>;
159
+ entity = { kind: 'resource', properties: Object.fromEntries(BACKEND_RESOURCE_QUERY_FIELDS
160
+ .filter((key) => Object.hasOwn(record, key)).map((key) => [key, record[key]])) as BackendResourceSnapshot };
161
+ } else {
162
+ if (resource.kind !== 'component') return reject('not_found');
163
+ if (target.kind === 'component') {
164
+ const { size, properties, customData } = resource.component;
165
+ entity = { kind: 'component', properties: { size, properties, customData } };
166
+ } else if (target.kind === 'controller') {
167
+ const controllers = resource.component.controllers.filter((controller) => controller.name === selector.controllerName);
168
+ if (controllers.length !== 1) return reject(controllers.length ? 'ambiguous' : 'not_found');
169
+ entity = { kind: 'controller', properties: controllers[0] };
170
+ } else if (target.kind === 'transition') {
171
+ const transitions = resource.component.transitions.filter((transition) => transition.name === selector.transitionName);
172
+ if (transitions.length !== 1) return reject(transitions.length ? 'ambiguous' : 'not_found');
173
+ entity = { kind: 'transition', properties: transitions[0] };
174
+ } else {
175
+ const nodes = resource.component.displayList.filter((node) => node.id === selector.displayNodeId);
176
+ if (nodes.length !== 1) return reject(nodes.length ? 'ambiguous' : 'not_found');
177
+ entity = { kind: 'displayNode', properties: nodes[0] };
178
+ }
179
+ }
180
+ return respond(entity);
181
+ }
182
+
87
183
  public validateSession(
88
184
  input: { sessionId: string },
89
185
  ): BackendResult<ProjectValidationReport, SessionNotFoundError> {
@@ -100,7 +196,7 @@ export class ReadService {
100
196
  return success('read', startedAt, report, {
101
197
  sessionId: session.sessionId,
102
198
  revision: session.revision,
103
- diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({ code, message, severity, path })),
199
+ diagnostics: report.diagnostics.map(({ code, message, severity, path }) => ({ code, message, severity, path, owner: 'core.validation' })),
104
200
  });
105
201
  }
106
202
  }
@@ -1,3 +1,4 @@
1
+ import { capturedDirectoriesEqual, capturedFilesEqual, createCaptureFileSystem } from './capture-project.js';
1
2
  import { type FileSystem, ProjectReader, ProjectWriter } from '@openfairygui/core/project-io';
2
3
  import {
3
4
  liftDocumentToUamProject,
@@ -5,7 +6,7 @@ import {
5
6
  normalizeUamProject,
6
7
  type UamProject,
7
8
  } from '@openfairygui/core/uam';
8
- import { normalizeComparablePath, resolveCanonicalProjectRoot } from '../path-policy.js';
9
+ import { assertProjectPathContained, normalizeComparablePath, resolveCanonicalProjectRoot } from '../path-policy.js';
9
10
  import type {
10
11
  AdvisoryLockConflictError,
11
12
  BackendCapabilityUnavailableError,
@@ -14,6 +15,8 @@ import type {
14
15
  BackendSessionSnapshot,
15
16
  InProcessLockConflictError,
16
17
  OpenProjectSessionInput,
18
+ ProjectRootNotAllowedError,
19
+ SessionIdConflictError,
17
20
  SessionNotFoundError,
18
21
  } from '../runtime.js';
19
22
  import type { CacheService } from './cache-service.js';
@@ -23,7 +26,7 @@ import type { JobService } from './job-service.js';
23
26
  import { createSessionNotFoundError, toSessionSnapshot } from './session-utils.js';
24
27
 
25
28
  function randomId(): string {
26
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
29
+ return crypto.randomUUID();
27
30
  }
28
31
 
29
32
  function createCapabilityUnavailableError(
@@ -42,29 +45,36 @@ function createCapabilityUnavailableError(
42
45
  };
43
46
  }
44
47
 
45
- function createProjectReaderFileSystem(fileSystem: NonNullable<BackendContext['fileSystem']>): FileSystem {
48
+ function createProjectReaderFileSystem(
49
+ fileSystem: NonNullable<BackendContext['fileSystem']>,
50
+ projectRoot: string,
51
+ ): FileSystem {
52
+ const contained = async <T>(filePath: string, operation: () => Promise<T>): Promise<T> => {
53
+ await assertProjectPathContained(fileSystem, projectRoot, filePath);
54
+ return operation();
55
+ };
46
56
  return {
47
57
  readFile(filePath: string): Promise<string> {
48
- return fileSystem.readFile(filePath);
58
+ return contained(filePath, () => fileSystem.readFile(filePath));
49
59
  },
50
60
  readFileRaw(filePath: string): Promise<Uint8Array> {
51
- return fileSystem.readFileRaw(filePath);
61
+ return contained(filePath, () => fileSystem.readFileRaw(filePath));
52
62
  },
53
63
  writeFile(filePath: string, content: string): Promise<void> {
54
- return fileSystem.writeFile(filePath, content);
64
+ return contained(filePath, () => fileSystem.writeFile(filePath, content));
55
65
  },
56
66
  writeFileRaw(filePath: string, data: Uint8Array): Promise<void> {
57
- return fileSystem.writeFileRaw(filePath, data);
67
+ return contained(filePath, () => fileSystem.writeFileRaw(filePath, data));
58
68
  },
59
69
  async mkdir(dirPath: string): Promise<void> {
60
- await fileSystem.mkdir(dirPath, { recursive: true });
70
+ await contained(dirPath, () => fileSystem.mkdir(dirPath, { recursive: true }));
61
71
  },
62
72
  readdir(dirPath: string): Promise<string[]> {
63
- return fileSystem.readdir(dirPath);
73
+ return contained(dirPath, () => fileSystem.readdir(dirPath));
64
74
  },
65
75
  async exists(filePath: string): Promise<boolean> {
66
76
  try {
67
- await fileSystem.stat(filePath);
77
+ await contained(filePath, () => fileSystem.stat(filePath));
68
78
  return true;
69
79
  } catch {
70
80
  return false;
@@ -79,71 +89,6 @@ function createProjectReaderFileSystem(fileSystem: NonNullable<BackendContext['f
79
89
  };
80
90
  }
81
91
 
82
- function createCaptureFileSystem(
83
- files: Map<string, string | Uint8Array>,
84
- directories: Set<string>,
85
- ): FileSystem {
86
- const normalize = (filePath: string): string => filePath.replace(/\\/g, '/').replace(/\/+/g, '/');
87
- return {
88
- async readFile(filePath: string): Promise<string> {
89
- const value = files.get(normalize(filePath));
90
- if (typeof value !== 'string') throw new Error(`Captured text file was not found: ${filePath}`);
91
- return value;
92
- },
93
- async readFileRaw(filePath: string): Promise<Uint8Array> {
94
- const value = files.get(normalize(filePath));
95
- if (!(value instanceof Uint8Array)) throw new Error(`Captured binary file was not found: ${filePath}`);
96
- return value.slice();
97
- },
98
- async writeFile(filePath: string, content: string): Promise<void> {
99
- files.set(normalize(filePath), content);
100
- },
101
- async writeFileRaw(filePath: string, data: Uint8Array): Promise<void> {
102
- files.set(normalize(filePath), data.slice());
103
- },
104
- async mkdir(dirPath: string): Promise<void> {
105
- directories.add(normalize(dirPath));
106
- },
107
- async readdir(): Promise<string[]> {
108
- return [];
109
- },
110
- async exists(filePath: string): Promise<boolean> {
111
- return files.has(normalize(filePath));
112
- },
113
- join(...paths: string[]): string {
114
- return normalize(paths.filter(Boolean).join('/'));
115
- },
116
- dirname(filePath: string): string {
117
- const normalized = normalize(filePath);
118
- const separator = normalized.lastIndexOf('/');
119
- return separator < 0 ? '' : normalized.slice(0, separator);
120
- },
121
- async unlink(filePath: string): Promise<void> {
122
- files.delete(normalize(filePath));
123
- },
124
- };
125
- }
126
-
127
- function capturedFilesEqual(left: Map<string, string | Uint8Array>, right: Map<string, string | Uint8Array>): boolean {
128
- if (left.size !== right.size) return false;
129
- for (const [filePath, leftValue] of left) {
130
- const rightValue = right.get(filePath);
131
- if (typeof leftValue === 'string') {
132
- if (leftValue !== rightValue) return false;
133
- continue;
134
- }
135
- if (!(rightValue instanceof Uint8Array) || leftValue.length !== rightValue.length) return false;
136
- for (let index = 0; index < leftValue.length; index += 1) {
137
- if (leftValue[index] !== rightValue[index]) return false;
138
- }
139
- }
140
- return true;
141
- }
142
-
143
- function capturedDirectoriesEqual(left: Set<string>, right: Set<string>): boolean {
144
- return left.size === right.size && [...left].every((directory) => right.has(directory));
145
- }
146
-
147
92
  async function hasFullUamFidelity(
148
93
  document: Awaited<ReturnType<ProjectReader['read']>>,
149
94
  project: UamProject,
@@ -180,7 +125,7 @@ export class RuntimeService {
180
125
  }): Promise<
181
126
  BackendResult<
182
127
  BackendSessionSnapshot,
183
- InProcessLockConflictError | AdvisoryLockConflictError | BackendCapabilityUnavailableError
128
+ InProcessLockConflictError | AdvisoryLockConflictError | BackendCapabilityUnavailableError | ProjectRootNotAllowedError
184
129
  >
185
130
  > {
186
131
  const startedAt = Date.now();
@@ -188,10 +133,31 @@ export class RuntimeService {
188
133
  return failure('runtime', startedAt, createCapabilityUnavailableError('fileSystem'));
189
134
  }
190
135
  const fileSystem = this.context.fileSystem;
136
+ if (this.context.allowedProjectRoots?.length) {
137
+ let allowed = false;
138
+ for (const root of this.context.allowedProjectRoots) {
139
+ try {
140
+ await assertProjectPathContained(fileSystem, root, input.projectPath);
141
+ allowed = true;
142
+ break;
143
+ } catch (error) {
144
+ if ((error as { code?: unknown }).code !== 'EACCES') throw error;
145
+ }
146
+ }
147
+ if (!allowed) {
148
+ return failure('runtime', startedAt, {
149
+ code: 'project_root_not_allowed',
150
+ message: 'Project path is outside the configured allowed roots.',
151
+ projectPath: input.projectPath,
152
+ });
153
+ }
154
+ }
191
155
  const resolved = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
192
156
  const { fairyPath, canonicalProjectPath, canonicalPathKey } = resolved;
157
+ await fileSystem.validateProjectRoot?.(canonicalProjectPath);
193
158
  const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
194
- const lockFilePath = fileSystem.join(canonicalProjectPath, '.openfairygui.backend.lock');
159
+ const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath)
160
+ ?? fileSystem.join(canonicalProjectPath, '.openfairygui.backend.lock');
195
161
 
196
162
  if (existingSessionId) {
197
163
  return failure('runtime', startedAt, {
@@ -219,7 +185,7 @@ export class RuntimeService {
219
185
  },
220
186
  ),
221
187
  );
222
- const reader = new ProjectReader(createProjectReaderFileSystem(fileSystem));
188
+ const reader = new ProjectReader(createProjectReaderFileSystem(fileSystem, canonicalProjectPath));
223
189
  const read = await reader.readDetailed(fairyPath, { hydrateResourceBytes: true });
224
190
  if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
225
191
  const document = read.document;
@@ -276,9 +242,18 @@ export class RuntimeService {
276
242
  }
277
243
  }
278
244
 
279
- public openProjectSession(input: OpenProjectSessionInput): BackendResult<BackendSessionSnapshot> {
245
+ public openProjectSession(
246
+ input: OpenProjectSessionInput,
247
+ ): BackendResult<BackendSessionSnapshot, InProcessLockConflictError | SessionIdConflictError> {
280
248
  const startedAt = Date.now();
281
249
  const sessionId = input.sessionId ?? randomId();
250
+ if (this.context.sessions.has(sessionId)) {
251
+ return failure('runtime', startedAt, {
252
+ code: 'session_id_conflict',
253
+ message: `Session id is already in use: ${sessionId}`,
254
+ sessionId,
255
+ });
256
+ }
282
257
  const storage = input.storage;
283
258
  const memoryProjectPath = `memory://${sessionId}`;
284
259
  const canonicalProjectPath =
@@ -1,15 +1,21 @@
1
1
  import type { Document } from '@openfairygui/core';
2
2
  import { type FileSystem, type ProjectBranchDirectory, type ProjectSourceFile, ProjectWriter } from '@openfairygui/core/project-io';
3
3
  import type { BackendFileSystem } from '../runtime.js';
4
+ import { assertProjectPathContained } from '../path-policy.js';
4
5
 
5
6
  function createWriterFileSystem(
6
7
  fileSystem: BackendFileSystem,
8
+ projectRoot: string,
7
9
  writtenPaths: string[],
8
10
  failedPaths: string[],
9
11
  ): FileSystem {
12
+ const contained = async <T>(targetPath: string, operation: () => Promise<T>): Promise<T> => {
13
+ await assertProjectPathContained(fileSystem, projectRoot, targetPath);
14
+ return operation();
15
+ };
10
16
  async function trackWrite<T>(targetPath: string, write: () => Promise<T>): Promise<T> {
11
17
  try {
12
- const result = await write();
18
+ const result = await contained(targetPath, write);
13
19
  writtenPaths.push(targetPath);
14
20
  return result;
15
21
  } catch (error) {
@@ -19,8 +25,8 @@ function createWriterFileSystem(
19
25
  }
20
26
 
21
27
  return {
22
- readFile: (path) => fileSystem.readFile(path),
23
- readFileRaw: (path) => fileSystem.readFileRaw(path),
28
+ readFile: (path) => contained(path, () => fileSystem.readFile(path)),
29
+ readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
24
30
  writeFile: (path, content) =>
25
31
  trackWrite(path, async () => {
26
32
  await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
@@ -31,9 +37,10 @@ function createWriterFileSystem(
31
37
  await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
32
38
  await fileSystem.writeFileRaw(path, data);
33
39
  }),
34
- mkdir: (path) => fileSystem.mkdir(path, { recursive: true }),
35
- readdir: (path) => fileSystem.readdir(path),
40
+ mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
41
+ readdir: (path) => contained(path, () => fileSystem.readdir(path)),
36
42
  async exists(path): Promise<boolean> {
43
+ await assertProjectPathContained(fileSystem, projectRoot, path);
37
44
  try {
38
45
  await fileSystem.stat(path);
39
46
  return true;
@@ -58,12 +65,23 @@ export async function writeSessionProject(input: {
58
65
  writtenPaths: string[];
59
66
  failedPaths: string[];
60
67
  }): Promise<void> {
61
- const writer = new ProjectWriter(
62
- createWriterFileSystem(input.fileSystem, input.writtenPaths, input.failedPaths),
63
- );
64
- await writer.write(input.document, input.fairyPath, {
65
- staleSourceFiles: input.staleSourceFiles,
66
- staleResourceFolders: input.staleResourceFolders,
67
- staleBranchDirectories: input.staleBranchDirectories,
68
- });
68
+ const projectRoot = input.fileSystem.dirname(input.fairyPath);
69
+ const write = async (fileSystem: BackendFileSystem): Promise<void> => {
70
+ const writer = new ProjectWriter(
71
+ createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths),
72
+ );
73
+ await writer.write(input.document, input.fairyPath, {
74
+ staleSourceFiles: input.staleSourceFiles,
75
+ staleResourceFolders: input.staleResourceFolders,
76
+ staleBranchDirectories: input.staleBranchDirectories,
77
+ });
78
+ };
79
+
80
+ if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
81
+ try {
82
+ await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
83
+ } catch (error) {
84
+ input.writtenPaths.length = 0;
85
+ throw error;
86
+ }
69
87
  }
@@ -0,0 +1,114 @@
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
+ captureProject(materializeUamProject(session.project), fairyFileName),
87
+ captureProject(materializeUamProject(project), fairyFileName),
88
+ ]);
89
+ for (const path of new Set([...previousFiles.files.keys(), ...nextFiles.files.keys()])) {
90
+ const previous = previousFiles.files.get(path), next = nextFiles.files.get(path);
91
+ if (equal(previous, next)) continue;
92
+ const change = { path, kind: 'file' as const, change: previous === undefined ? 'added' as const : next === undefined ? 'removed' as const : 'updated' as const };
93
+ count(change); impact.files.push(change);
94
+ }
95
+ for (const path of new Set([...previousFiles.directories, ...nextFiles.directories])) {
96
+ if (previousFiles.directories.has(path) === nextFiles.directories.has(path)) continue;
97
+ const change = { path, kind: 'directory' as const, change: nextFiles.directories.has(path) ? 'added' as const : 'removed' as const };
98
+ count(change); impact.files.push(change);
99
+ }
100
+ impact.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.kind.localeCompare(b.kind));
101
+ const preview: BackendTransactionPreview = {
102
+ sessionId: session.sessionId, baseRevision: session.revision, projectedRevision: session.revision + 1,
103
+ mode: 'execute-and-discard', impact,
104
+ persistence: {
105
+ requiredAfterApply: true, fileSystemAvailable, uamFidelity: session.uamFidelity, writeVerified: false,
106
+ nextAction: session.uamFidelity === 'unsupported' || !fileSystemAvailable ? 'host-action'
107
+ : session.fileSystem ? 'saveSession' : 'materializeSession',
108
+ },
109
+ };
110
+ if (encoder.encode(JSON.stringify(preview)).byteLength > BACKEND_TRANSACTION_PREVIEW_LIMITS.maxBytes) {
111
+ throw new PreviewBudgetError('The complete transaction preview exceeds the response byte budget.');
112
+ }
113
+ return preview;
114
+ }