@enhance-eng/enhance 0.1.22 → 0.1.33

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.
@@ -0,0 +1,4688 @@
1
+ #!/usr/bin/env node
2
+ import { $ as canvasRenderPendingSchema, An as canvasReferencePageOf, At as PartialBatchError, B as canvasCaptureCapabilityInputSchema, Bn as applyCanvasOperationsOutputSchema, Bt as PROTOTYPE_ARTIFACT_MANIFEST_PATH, C as canvasSnapshotToken, Cn as canvasTextPropsWithContent, Dn as canvasPrototypePropsSchema, E as resolveCanvasSnapshot, En as canvasConversionMetadataSchema, G as canvasRenderCapabilityInputSchema, Gn as getCanvasDocumentOutputSchema, Gt as getPrototypePublishStatusOutputSchema, Hn as canvasLayoutWithoutCssProperties, Ht as createPrototypeArtifactOutputSchema, I as canvasDuplicateCapabilityInputSchema, In as createCanvasPreparationOutputSchema, J as prototypePublishCapabilityInputSchema, Jn as canvasNodeStylePatchSchema, Jt as submitPrototypeArtifactOutputSchema, K as canvasWriteHtmlCapabilityInputSchema, Kt as prototypeArtifactManifestSchema, Ln as getCanvasPreparationOutputSchema, Mn as beginCanvasActivityOutputSchema, Mt as transcriptOutputSchema, N as canvasAssetImportOutputSchema, On as canvasRecordingPropsSchema, Ot as hasCanvasReferenceScope, P as canvasArrangeCapabilityInputSchema, Pn as AGENT_CLIENT_HEADER, Qn as canvasRenderStateSchema, Qt as createAgentTokenOutputSchema, Rn as PAGE_KIND, Rt as getRecordingOutputSchema, S as canvasExchangeDigest, Sn as canvasTextChangeBetween, St as canvasEditCapabilityInputSchema, T as encodeCanvasExchangeToken, Tn as canvasCaptureSchema, Tt as canvasReferenceNodeIds, U as canvasApplyCapabilityInputSchema, Un as textOf, Ut as foldPrototypeArtifactPath, Vn as getCanvasMutationOutputSchema, Vt as attachPrototypeArtifactOutputSchema, W as canvasReadCapabilityInputSchema, Wn as mapCanvasFontSources, Wt as getPrototypeArtifactCapabilitiesOutputSchema, X as transcriptReadCapabilityInputSchema, Xn as getCanvasConversionOutputSchema, Y as recordingSnapshotCapabilityInputSchema, Yn as createCanvasConversionOutputSchema, Yt as getMeOutputSchema, Z as canvasRenderBatchRequestSchema, Zt as cliAuthConfigurationSchema, _r as canvasImageAssetIdentityFromPath, ar as canvasReadableSceneDocumentSchema, bn as applyCanvasTypographyPatch, bt as canvasMakeEditableCapabilityInputSchema, cr as canvasAuthoredStyleDeclarations, dt as canvasTranscriptCursorSchema, en as listOrganisationsOutputSchema, fr as canvasCssValue, ft as canvasResourcesCursorSchema, gr as canvasFontAssetIdentityFromPath, gt as canvasFindInputSchema, hr as reserveCanvasAssetOutputSchema, ht as canvasFindCursorSchema, ir as getCanvasRenderOutputSchema, it as canvasRemoveCapabilityInputSchema, j as canvasAssetImportCapabilityInputSchema, jn as resolveCanvasReference, jt as CliError, k as operationStatusInputSchema, kn as DEFAULT_CANVAS_REFERENCE_PAGE_ID, kt as parseCanvasReference, lr as canvasAxisStyleProperties, lt as canvasUpdateHtmlCapabilityInputSchema, mr as reserveCanvasAssetInputSchema, nr as createRecordingSnapshotOutputSchema, nt as canvasRenderRequestSchema, or as canvasSceneDocumentSchema, ot as canvasOutlineCursorSchema, pr as canvasAssetUploadOutputSchema, q as commentAttentionCapabilityInputSchema, qt as prototypeArtifactPathSchema, rr as downloadCanvasRenderOutputSchema, rt as canvasRenderFileSchema, s as toRemoteError, st as canvasReadInputSchema, tr as createCanvasRenderOutputSchema, ut as canvasUpdateHtmlInputSchema, v as canvasPrototypeCapabilityInputSchema, vr as canvasAdditionalStyleSchema, vt as canvasInsertHtmlCapabilityInputSchema, w as decodeCanvasExchangeToken, wt as assertCanvasReferenceNodes, xn as canvasCssTypographyOwners, xr as listCanvasesOutputSchema, zn as applyCanvasOperationsInputSchema } from "./cli-output-identity.lib-CWNAXho4.mjs";
3
+ import process from "node:process";
4
+ import { z } from "zod";
5
+ import { homedir, tmpdir } from "node:os";
6
+ import { generateKeyBetween, generateNKeysBetween } from "fractional-indexing";
7
+ import { chmodSync, constants, createReadStream, createWriteStream, mkdirSync, writeFileSync } from "node:fs";
8
+ import path from "node:path";
9
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
10
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
11
+ import { access, mkdtemp, open, readFile, realpath, rm, stat } from "node:fs/promises";
12
+ import { isDeepStrictEqual } from "node:util";
13
+ import { generate, parse } from "css-tree";
14
+ import { parseFragment, serialize, serializeOuter } from "parse5";
15
+ import { performance as performance$1 } from "node:perf_hooks";
16
+ import { Readable, Transform } from "node:stream";
17
+ import { pipeline } from "node:stream/promises";
18
+ import { ZipFile } from "yazl";
19
+ import { createTRPCUntypedClient, httpLink } from "@trpc/client";
20
+ import { spawn } from "node:child_process";
21
+ import { createServer } from "node:http";
22
+
23
+ //#region ../../packages/contract/src/canvas/canvas-additional-style-patch.lib.ts
24
+ const reorderedDeclarations = (declarations, order) => {
25
+ const ordered = new Set(order);
26
+ const prefix = [];
27
+ const groups = /* @__PURE__ */ new Map();
28
+ let group = prefix;
29
+ for (const declaration of declarations) {
30
+ if (ordered.has(declaration.id)) {
31
+ group = [];
32
+ groups.set(declaration.id, group);
33
+ }
34
+ group.push(declaration);
35
+ }
36
+ return [...prefix, ...order.flatMap((id) => groups.get(id) ?? [])];
37
+ };
38
+ /** Peer rows keep their preceding anchor when an explicitly ordered subset moves. */
39
+ const applyCanvasAdditionalStylePatch = (before, patch) => {
40
+ const removed = new Set(patch.clear);
41
+ const values = new Map((before?.declarations ?? []).filter((item) => !removed.has(item.id)).map((item) => [item.id, item]));
42
+ const updates = patch.set ?? [];
43
+ for (const declaration of updates) values.set(declaration.id, declaration);
44
+ const declarations = Array.from(values, ([, value]) => value);
45
+ if (declarations.length === 0 && (patch.empty === "remove" || before === void 0 && patch.empty !== "keep")) return null;
46
+ return { declarations: patch.order === void 0 ? declarations : reorderedDeclarations(declarations, patch.order) };
47
+ };
48
+ const canvasAdditionalStylePatchBetween = (before, after) => {
49
+ const previous = new Map(before?.declarations.map((item) => [item.id, item]));
50
+ const next = after?.declarations ?? [];
51
+ const nextIds = new Set(next.map((item) => item.id));
52
+ const clear = Array.from(previous, ([id]) => id).filter((id) => !nextIds.has(id));
53
+ const set = next.filter((item) => {
54
+ const held = previous.get(item.id);
55
+ return held?.property !== item.property || held.value !== item.value || held.enabled !== item.enabled;
56
+ });
57
+ const patch = {
58
+ ...clear.length > 0 && { clear },
59
+ ...set.length > 0 && { set }
60
+ };
61
+ const projected = applyCanvasAdditionalStylePatch(before, patch);
62
+ const order = next.map((item) => item.id);
63
+ const hasOrderChange = JSON.stringify(projected?.declarations.map((item) => item.id) ?? []) !== JSON.stringify(order);
64
+ const empty = after === void 0 && before !== void 0 ? "remove" : before === void 0 && after !== void 0 && next.length === 0 ? "keep" : void 0;
65
+ return empty === void 0 && !hasOrderChange && set.length === 0 && clear.length === 0 ? null : {
66
+ ...patch,
67
+ ...hasOrderChange && { order },
68
+ ...empty !== void 0 && { empty }
69
+ };
70
+ };
71
+
72
+ //#endregion
73
+ //#region ../../packages/contract/src/canvas/canvas-html-source.lib.ts
74
+ const OMITTED_ELEMENTS = /* @__PURE__ */ new Set([
75
+ "base",
76
+ "embed",
77
+ "iframe",
78
+ "link",
79
+ "meta",
80
+ "object",
81
+ "script"
82
+ ]);
83
+ const EXECUTABLE_URL = /^(?:(?:javascript|vbscript):|data:text\/html(?:[;,]|$))/iu;
84
+ const UNSAFE_STYLE = /javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu;
85
+ const canRetainCanvasHtmlElement = (tag) => !OMITTED_ELEMENTS.has(tag.toLowerCase());
86
+ const canRetainCanvasHtmlStyle = (style) => !UNSAFE_STYLE.test(style);
87
+ const canRetainCanvasHtmlAttribute = (name, value) => {
88
+ const property = name.toLowerCase();
89
+ if (property === "srcdoc" || /^on/iu.test(property)) return false;
90
+ if (property === "style") return canRetainCanvasHtmlStyle(value);
91
+ return ![
92
+ "href",
93
+ "src",
94
+ "action",
95
+ "formaction",
96
+ "xlink:href"
97
+ ].includes(property) || !EXECUTABLE_URL.test(value.replaceAll(/[\p{Control}\s]/gu, ""));
98
+ };
99
+
100
+ //#endregion
101
+ //#region ../../packages/contract/src/canvas/canvas-image-resources.lib.ts
102
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
103
+ const mapPaint = (paint, map) => {
104
+ if (!isRecord(paint) || paint["kind"] !== "image" || typeof paint["assetId"] !== "string") return paint;
105
+ const assetId = map(paint["assetId"]);
106
+ return assetId === paint["assetId"] ? paint : {
107
+ ...paint,
108
+ assetId
109
+ };
110
+ };
111
+ const mapRichText = (value, map) => {
112
+ if (!Array.isArray(value)) return value;
113
+ return value.map((run) => {
114
+ if (!isRecord(run) || run["kind"] !== "span") return run;
115
+ const fills = Array.isArray(run["fills"]) ? run["fills"] : void 0;
116
+ return {
117
+ ...run,
118
+ ...fills !== void 0 && { fills: fills.map((paint) => mapPaint(paint, map)) },
119
+ ...Array.isArray(run["children"]) && { children: mapRichText(run["children"], map) }
120
+ };
121
+ });
122
+ };
123
+ /** Only resource slots change; links and imported source metadata can contain the same path. */
124
+ const mapCanvasNodeImageSources = (node, map) => {
125
+ const appearance = node.appearance;
126
+ const src = node.props?.["src"];
127
+ return {
128
+ ...node,
129
+ ...appearance !== void 0 && { appearance: {
130
+ ...appearance,
131
+ ...appearance.fills !== void 0 && { fills: appearance.fills.map((paint) => mapPaint(paint, map)) },
132
+ ...appearance.border !== void 0 && { border: {
133
+ ...appearance.border,
134
+ paint: mapPaint(appearance.border.paint, map)
135
+ } },
136
+ ...appearance.outline !== void 0 && { outline: {
137
+ ...appearance.outline,
138
+ paint: mapPaint(appearance.outline.paint, map)
139
+ } }
140
+ } },
141
+ ...node.typography?.stroke !== void 0 && { typography: {
142
+ ...node.typography,
143
+ stroke: {
144
+ ...node.typography.stroke,
145
+ paint: mapPaint(node.typography.stroke.paint, map)
146
+ }
147
+ } },
148
+ ...node.props !== void 0 && { props: {
149
+ ...node.props,
150
+ ...node.component === "image" && typeof src === "string" && { src: map(src) },
151
+ ...node.component === "text" && node.props["richText"] !== void 0 && { richText: mapRichText(node.props["richText"], map) }
152
+ } }
153
+ };
154
+ };
155
+
156
+ //#endregion
157
+ //#region src/application/auth.use-case.ts
158
+ const TOKEN = /^enh_[\w-]{43}$/;
159
+ const authenticated = (value) => {
160
+ const parsed = getMeOutputSchema.parse(value);
161
+ if (parsed.authentication.kind !== "agent" || parsed.person === null) throw new CliError("UNAUTHORIZED", "The credential is missing, expired, revoked, or invalid.", "Run 'enhance auth login' and complete authentication in the browser.");
162
+ return {
163
+ authenticated: true,
164
+ personId: parsed.person.id,
165
+ displayName: parsed.person.displayName,
166
+ tokenId: parsed.authentication.tokenId,
167
+ tokenLabel: parsed.authentication.tokenLabel,
168
+ expiresAt: parsed.authentication.expiresAt
169
+ };
170
+ };
171
+ const createAuthUseCase = (credentials, remote, browser) => ({
172
+ loginWithToken: async (token) => {
173
+ if (!TOKEN.test(token)) throw new CliError("BAD_REQUEST", "Agent tokens begin with enh_ and contain 32 base64url bytes.", "Pass a manual token from Settings to 'enhance auth login' through stdin.");
174
+ const status = authenticated(await remote.queryWithToken("person.me", {}, token));
175
+ await credentials.write(token);
176
+ return status;
177
+ },
178
+ loginWithBrowser: async (input) => {
179
+ const configuration = cliAuthConfigurationSchema.parse(await remote.authenticationConfig());
180
+ if (configuration.method === "token") throw new CliError("BAD_REQUEST", "Browser authentication is not configured for this Enhance environment.", "Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.");
181
+ const accessToken = await browser.authorize({
182
+ issuer: configuration.issuer,
183
+ clientId: configuration.clientId,
184
+ scope: configuration.scope,
185
+ openBrowser: input.openBrowser,
186
+ onReady: input.onReady,
187
+ ...input.signal !== void 0 && { signal: input.signal }
188
+ });
189
+ input.signal?.throwIfAborted();
190
+ const created = createAgentTokenOutputSchema.parse(await remote.mutateWithToken("person.createAgentToken", {
191
+ label: input.label,
192
+ expiresAt: null
193
+ }, accessToken));
194
+ const status = authenticated(await remote.queryWithToken("person.me", {}, created.token));
195
+ input.signal?.throwIfAborted();
196
+ await credentials.write(created.token);
197
+ return status;
198
+ },
199
+ status: async (requestRemote = remote) => {
200
+ if (await credentials.read() === null) throw new CliError("UNAUTHORIZED", `No credential exists at ${credentials.path}.`, "A human must run 'enhance auth login'.");
201
+ return authenticated(await requestRemote.query("person.me", {}));
202
+ },
203
+ logout: async () => ({ loggedOut: await credentials.remove() })
204
+ });
205
+
206
+ //#endregion
207
+ //#region src/application/render-png.use-case.ts
208
+ const PNG_SIGNATURE = Uint8Array.from(globalThis.atob("iVBORw0KGgo="), (character) => character.codePointAt(0) ?? 0);
209
+ const PNG_HEADER_BYTE_LENGTH = 24;
210
+ const PNG_WIDTH_OFFSET = 16;
211
+ const PNG_HEIGHT_OFFSET = 20;
212
+ const pngDimensions = (body) => {
213
+ if (body.byteLength < PNG_HEADER_BYTE_LENGTH || PNG_SIGNATURE.some((byte, index) => body[index] !== byte)) return null;
214
+ const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
215
+ return {
216
+ width: view.getUint32(PNG_WIDTH_OFFSET),
217
+ height: view.getUint32(PNG_HEIGHT_OFFSET)
218
+ };
219
+ };
220
+ const downloadVerifiedRenderPng = async (remote, job) => {
221
+ if (job.result.canvasId !== job.canvasId || job.result.requestedVersion !== job.requestedVersion || job.result.loadedVersion !== job.requestedVersion || JSON.stringify(job.result.target) !== JSON.stringify(job.target)) throw new CliError("INTERNAL", "The completed render evidence does not match its requested canvas, revision or target.", `Do not use the image. Report render job ${job.id}.`);
222
+ if (job.maxOutputPixels !== void 0 && job.result.width * job.result.height > job.maxOutputPixels) throw new CliError("INTERNAL", "The completed render exceeds its authorised output pixel limit.", `Do not use the image. Report render job ${job.id}.`, { reason: "RENDER_BUDGET_UNSUPPORTED" });
223
+ const signed = downloadCanvasRenderOutputSchema.safeParse(await remote.query("canvas.render.download", { jobId: job.id }));
224
+ if (!signed.success || signed.data.jobId !== job.id || signed.data.download.bytes !== job.result.bytes) throw new CliError("INTERNAL", "The API returned an invalid render download response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
225
+ const body = await remote.download(signed.data.download.url);
226
+ const dimensions = pngDimensions(body);
227
+ if (dimensions === null || body.byteLength !== job.result.bytes || dimensions.width !== job.result.width || dimensions.height !== job.result.height) throw new CliError("INTERNAL", "The downloaded render did not match its completed job metadata.", `Do not use the image. Report render job ${job.id}.`);
228
+ return body;
229
+ };
230
+
231
+ //#endregion
232
+ //#region src/application/render-artifact.use-case.ts
233
+ const nextCommands = (job) => {
234
+ const inspect = `enhance canvas inspect --canvas ${job.canvasId}`;
235
+ if (job.result.sourceState !== void 0) return [
236
+ "Inspect the PNG at path before persisting this moment.",
237
+ `enhance recording snapshot --canvas ${job.canvasId} --recording-id ${job.result.sourceState.recordingId} --at-ms ${String(job.result.sourceState.settledAtMs)}`,
238
+ inspect
239
+ ];
240
+ if (job.target.kind !== "node") return [inspect];
241
+ return [inspect, `enhance canvas node --canvas ${job.canvasId} --node-id ${job.target.nodeId}`];
242
+ };
243
+ const resultFrom = (job, written) => ({
244
+ jobId: job.id,
245
+ operation: {
246
+ kind: "canvas-render",
247
+ canvasId: job.canvasId,
248
+ jobId: job.id
249
+ },
250
+ canvasId: job.canvasId,
251
+ requestedVersion: job.requestedVersion,
252
+ loadedVersion: job.result.loadedVersion,
253
+ target: job.target,
254
+ sourceState: job.result.sourceState ?? null,
255
+ bounds: job.result.bounds,
256
+ width: job.result.width,
257
+ height: job.result.height,
258
+ scale: job.result.scale,
259
+ contentType: job.result.contentType,
260
+ bytes: job.result.bytes,
261
+ warnings: job.result.warnings,
262
+ path: written.path,
263
+ sensitive: true,
264
+ cleanup: written.temporary ? "unlink-after-use" : "caller-owned",
265
+ ...written.deleteAfter !== null && { deleteAfter: written.deleteAfter.toISOString() },
266
+ next: nextCommands(job)
267
+ });
268
+ const writeRenderArtifact = async (remote, files, job, input) => resultFrom(job, files.write({
269
+ body: await downloadVerifiedRenderPng(remote, job),
270
+ ...input
271
+ }));
272
+
273
+ //#endregion
274
+ //#region src/application/render-canvas.composite.ts
275
+ const POLL_MS$3 = 250;
276
+ const PROGRESS_HEARTBEAT_MS$1 = 5e3;
277
+ const RENDER_CANVAS_PROCEDURES = ["canvas.render.create", "canvas.render.get"];
278
+ const invalidResponse$3 = (operation) => new CliError("INTERNAL", `The API returned an invalid ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
279
+ const terminalFailure$1 = (job) => {
280
+ const failure = job.failure;
281
+ if (failure === null) return invalidResponse$3("render job");
282
+ const code = failure.reason === "VERSION_CHANGED" ? "CONFLICT" : failure.reason === "TARGET_NOT_FOUND" ? "NOT_FOUND" : failure.reason === "TARGET_INVALID" || failure.reason === "OUTPUT_TOO_LARGE" ? "BAD_REQUEST" : "INTERNAL";
283
+ const remediation = failure.reason === "VERSION_CHANGED" ? `Run 'enhance canvas inspect --canvas ${job.canvasId}', then render its returned version.` : failure.reason === "TARGET_NOT_FOUND" ? `Run 'enhance canvas tree --canvas ${job.canvasId}' and choose a current node id.` : failure.retryable ? "Retry the render. If it repeats, run `enhance doctor` and report the job id." : "Change the target or scale using the failure details, then retry.";
284
+ return new CliError(code, failure.message, remediation, {
285
+ jobId: job.id,
286
+ reason: failure.reason,
287
+ phase: failure.phase,
288
+ renderState: job.state
289
+ });
290
+ };
291
+ const wait$2 = async (milliseconds) => new Promise((resolve) => {
292
+ globalThis.setTimeout(resolve, milliseconds);
293
+ });
294
+ const readJob = async (remote, jobId) => {
295
+ const parsed = getCanvasRenderOutputSchema.safeParse(await remote.query(RENDER_CANVAS_PROCEDURES[1], { jobId }));
296
+ if (!parsed.success || parsed.data.job.id !== jobId) throw invalidResponse$3("render status");
297
+ return parsed.data.job;
298
+ };
299
+ const awaitJob = async (remote, input) => {
300
+ const startedAt = Date.now();
301
+ let lastReportedAt = 0;
302
+ let lastReportedState = "";
303
+ let job = input.initial;
304
+ while (job.state === "queued" || job.state === "running") {
305
+ const currentTime = Date.now();
306
+ const stateKey = `${job.state}:${job.phase}`;
307
+ if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS$1) {
308
+ input.progress({
309
+ event: "render.progress",
310
+ jobId: job.id,
311
+ state: job.state,
312
+ phase: job.phase,
313
+ elapsedMs: currentTime - startedAt,
314
+ timeoutMs: input.timeoutMs,
315
+ retryClientToken: input.retryClientToken
316
+ });
317
+ lastReportedAt = currentTime;
318
+ lastReportedState = stateKey;
319
+ }
320
+ if (currentTime >= input.deadline) {
321
+ if (input.timeoutOutcome === "pending") return job;
322
+ throw new CliError("INTERNAL", `Render ${job.id} did not finish before the local timeout.`, `Retry the exact command with --client-token ${input.retryClientToken} and a larger --timeout-ms. If the render remains unavailable, run \`enhance doctor\` and report the job id.`, {
323
+ jobId: job.id,
324
+ phase: job.phase
325
+ });
326
+ }
327
+ await wait$2(POLL_MS$3);
328
+ job = job.purpose === "inspection" && job.state === "queued" && job.attempt > 0 ? await input.resume() : await readJob(remote, job.id);
329
+ }
330
+ if (job.state !== "succeeded") throw terminalFailure$1(job);
331
+ return job;
332
+ };
333
+ const requestRenderJob = async (remote, input) => {
334
+ const made = createCanvasRenderOutputSchema.safeParse(await remote.mutate(RENDER_CANVAS_PROCEDURES[0], {
335
+ canvasId: input.canvasId,
336
+ ...input.expectedVersion !== null && { expectedVersion: input.expectedVersion },
337
+ target: input.target,
338
+ ...input.scope !== void 0 && { scope: input.scope },
339
+ ...input.sourceState !== null && { sourceState: input.sourceState },
340
+ scale: input.scale,
341
+ ...input.maxOutputPixels !== void 0 && { maxOutputPixels: input.maxOutputPixels },
342
+ format: "png"
343
+ }));
344
+ if (!made.success) throw invalidResponse$3("render creation");
345
+ if (made.data.job.canvasId !== input.canvasId || input.expectedVersion !== null && made.data.job.requestedVersion !== input.expectedVersion || JSON.stringify(made.data.job.target) !== JSON.stringify(input.target) || made.data.job.scale !== input.scale) throw invalidResponse$3("render identity");
346
+ return made.data.job;
347
+ };
348
+ const requireRenderBudget = (job, input) => {
349
+ if (input.maxOutputPixels !== void 0 && job.maxOutputPixels !== input.maxOutputPixels) throw new CliError("INTERNAL", "This API does not preserve the requested render pixel budget.", "Update the API and renderer together before rendering a batch.", { reason: "RENDER_BUDGET_UNSUPPORTED" });
350
+ };
351
+ const executeRender = async (dependencies, input) => {
352
+ const initial = await requestRenderJob(dependencies.remote, input);
353
+ try {
354
+ requireRenderBudget(initial, input);
355
+ const job = await awaitJob(dependencies.remote, {
356
+ initial,
357
+ resume: async () => requestRenderJob(dependencies.remote, input),
358
+ deadline: Date.now() + input.timeoutMs,
359
+ timeoutMs: input.timeoutMs,
360
+ retryClientToken: input.retryClientToken,
361
+ progress: dependencies.progress,
362
+ timeoutOutcome: input.timeoutOutcome
363
+ });
364
+ requireRenderBudget(job, input);
365
+ if (job.state !== "succeeded") return {
366
+ state: job.state,
367
+ phase: job.phase,
368
+ canvasId: job.canvasId,
369
+ requestedVersion: job.requestedVersion,
370
+ target: job.target,
371
+ operation: {
372
+ kind: "canvas-render",
373
+ canvasId: job.canvasId,
374
+ jobId: job.id
375
+ },
376
+ pixelsDelivered: false,
377
+ next: ["Read operation_status with includeImage true. Do not create another render.", "If it stays queued with attempt above 0, an attempt failed: repeat this exact request with the same clientToken to retry it."]
378
+ };
379
+ return await writeRenderArtifact(dependencies.remote, dependencies.files, job, {
380
+ outputPath: input.outputPath,
381
+ overwrite: input.overwrite,
382
+ at: dependencies.now()
383
+ });
384
+ } catch (error) {
385
+ const operation = JSON.stringify({
386
+ kind: "canvas-render",
387
+ canvasId: input.canvasId,
388
+ jobId: initial.id
389
+ });
390
+ if (error instanceof CliError) throw new CliError(error.code, error.message, error.remediation, {
391
+ ...error.fields,
392
+ jobId: initial.id,
393
+ operation
394
+ });
395
+ throw new CliError("INTERNAL", "The native render outcome could not be confirmed.", "Read operation_status or retry with the identical request and clientToken.", {
396
+ jobId: initial.id,
397
+ operation
398
+ });
399
+ }
400
+ };
401
+ const createRenderCanvasComposite = (remote, files, now, progress = () => null) => ({ execute: async (input) => executeRender({
402
+ remote,
403
+ files,
404
+ now,
405
+ progress
406
+ }, input) });
407
+
408
+ //#endregion
409
+ //#region src/application/canvas-activity.composite.ts
410
+ const PROCEDURES$1 = {
411
+ begin: "canvas.realtime.activity.begin",
412
+ renew: "canvas.realtime.activity.renew",
413
+ end: "canvas.realtime.activity.end"
414
+ };
415
+ const ignoreFailure = async (operation) => {
416
+ try {
417
+ await operation();
418
+ return true;
419
+ } catch {
420
+ return false;
421
+ }
422
+ };
423
+ const liveHandle = (remote, initial, activityId, renewAfterMs) => {
424
+ let target = initial;
425
+ let isFinished = false;
426
+ let isRenewing = false;
427
+ const renew = async () => {
428
+ if (isFinished || isRenewing) return;
429
+ isRenewing = true;
430
+ await ignoreFailure(async () => remote.mutate(PROCEDURES$1.renew, {
431
+ ...target,
432
+ nodeIds: [...target.nodeIds],
433
+ activityId
434
+ }));
435
+ isRenewing = false;
436
+ };
437
+ const timer = setInterval(() => void renew(), renewAfterMs);
438
+ return {
439
+ activityId,
440
+ update: async (next) => {
441
+ if (isFinished) return;
442
+ target = {
443
+ ...target,
444
+ ...next
445
+ };
446
+ await renew();
447
+ },
448
+ finish: async () => {
449
+ if (isFinished) return;
450
+ isFinished = true;
451
+ clearInterval(timer);
452
+ await ignoreFailure(async () => remote.mutate(PROCEDURES$1.end, {
453
+ canvasId: target.canvasId,
454
+ activityId
455
+ }));
456
+ }
457
+ };
458
+ };
459
+ const createCanvasActivityComposite = (remote) => ({
460
+ begin: async (target) => {
461
+ try {
462
+ const parsed = beginCanvasActivityOutputSchema.safeParse(await remote.mutate(PROCEDURES$1.begin, {
463
+ ...target,
464
+ nodeIds: [...target.nodeIds]
465
+ }));
466
+ return parsed.success ? liveHandle(remote, target, parsed.data.activityId, parsed.data.renewAfterMs) : null;
467
+ } catch {
468
+ return null;
469
+ }
470
+ },
471
+ finish: async (canvasId, activityId) => ignoreFailure(async () => remote.mutate(PROCEDURES$1.end, {
472
+ canvasId,
473
+ activityId
474
+ }))
475
+ });
476
+
477
+ //#endregion
478
+ //#region src/application/apply-canvas.composite.ts
479
+ const APPLY_PROCEDURE = "canvas.applyOperations";
480
+ const MAX_ACTIVITY_NODE_IDS$1 = 100;
481
+ const BOX_OPERATION_TYPES = /* @__PURE__ */ new Set([
482
+ "insertPrototype",
483
+ "insertText",
484
+ "setBox"
485
+ ]);
486
+ const hasOperationBox = (operation) => BOX_OPERATION_TYPES.has(operation.op);
487
+ const activityPhase = (input) => {
488
+ if (input.operations.some((operation) => operation.op === "insertNode" || operation.op === "insertText")) return "creating";
489
+ if (input.operations.some((operation) => operation.op === "remove")) return "deleting";
490
+ return "writing";
491
+ };
492
+ const operationNodeIds = (operation) => {
493
+ if (operation.op === "insertConvertedSubtree") return Object.keys(operation.nodes);
494
+ if (operation.op === "insertNode") return [operation.node.id];
495
+ return [operation.nodeId];
496
+ };
497
+ const activityNodeIds = (input) => [...new Set(input.operations.flatMap((operation) => operationNodeIds(operation)))].slice(0, MAX_ACTIVITY_NODE_IDS$1);
498
+ const operationBox = (operation) => {
499
+ if (operation.op === "insertConvertedSubtree") return operation.nodes[operation.rootNodeId]?.box ?? null;
500
+ if (operation.op === "insertNode") return operation.node.box ?? null;
501
+ if (hasOperationBox(operation)) return operation.box === "default" ? null : operation.box;
502
+ return null;
503
+ };
504
+ const union = (boxes) => {
505
+ const first = boxes[0];
506
+ if (first === void 0) return null;
507
+ let x1 = first.x;
508
+ let y1 = first.y;
509
+ let x2 = first.x + first.width;
510
+ let y2 = first.y + first.height;
511
+ for (const box of boxes.slice(1)) {
512
+ x1 = Math.min(x1, box.x);
513
+ y1 = Math.min(y1, box.y);
514
+ x2 = Math.max(x2, box.x + box.width);
515
+ y2 = Math.max(y2, box.y + box.height);
516
+ }
517
+ return {
518
+ x: x1,
519
+ y: y1,
520
+ width: x2 - x1,
521
+ height: y2 - y1
522
+ };
523
+ };
524
+ const apply = async (remote, input) => {
525
+ const response = await remote.mutate(APPLY_PROCEDURE, {
526
+ ...input,
527
+ documentFormatVersion: 7
528
+ });
529
+ const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
530
+ if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid canvas apply response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
531
+ return parsed.data;
532
+ };
533
+ const createApplyCanvasComposite = (remote) => ({ execute: async (input, options) => {
534
+ if (options?.activity === false) return apply(remote, input);
535
+ const activity = await createCanvasActivityComposite(remote).begin({
536
+ canvasId: input.canvasId,
537
+ phase: activityPhase(input),
538
+ nodeIds: activityNodeIds(input),
539
+ bounds: union(input.operations.flatMap((operation) => {
540
+ const box = operationBox(operation);
541
+ return box === null ? [] : [box];
542
+ }))
543
+ });
544
+ try {
545
+ return await apply(remote, input);
546
+ } finally {
547
+ await activity?.finish();
548
+ }
549
+ } });
550
+
551
+ //#endregion
552
+ //#region src/application/canvas-scene-at-version.use-case.ts
553
+ const sceneAtVersion = async (input, canvasId, expectedVersion) => {
554
+ const held = getCanvasDocumentOutputSchema.safeParse(await input.remote.query("canvas.document.get", { canvasId }));
555
+ if (!held.success) throw new CliError("INTERNAL", "The API returned an invalid canvas document.", "Run `enhance doctor` and report incompatible API and CLI versions.");
556
+ if (held.data.version !== expectedVersion) throw new CliError("CONFLICT", `Canvas version ${String(held.data.version)} no longer matches --base-version ${String(expectedVersion)}.`, `An earlier identical request may already have committed. Do not repeat it with a new client token. Inspect the intended scope with 'enhance canvas tree --canvas <the original canvas or selection link>' and reconcile against version ${String(held.data.version)} before submitting a new edit.`);
557
+ const scene = canvasReadableSceneDocumentSchema.safeParse(held.data.document);
558
+ if (scene.success) return scene.data;
559
+ throw new CliError("INTERNAL", "The stored canvas is not an editable scene.", "Open the canvas in the editor and repair or recreate the invalid document.");
560
+ };
561
+
562
+ //#endregion
563
+ //#region src/application/canvas-structure-document.use-case.ts
564
+ const ROOT_CANVAS_NODE_ID = "root";
565
+ const canvasChildIds = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : left.sortKey.localeCompare(right.sortKey)).map(([nodeId]) => nodeId);
566
+ const canvasChildrenByParent = (document) => {
567
+ const children = /* @__PURE__ */ new Map();
568
+ for (const [id, relationship] of Object.entries(document.relationships)) {
569
+ const siblings = children.get(relationship.parentId) ?? [];
570
+ siblings.push(id);
571
+ children.set(relationship.parentId, siblings);
572
+ }
573
+ for (const siblings of children.values()) siblings.sort((left, right) => {
574
+ const leftKey = document.relationships[left]?.sortKey ?? "";
575
+ const rightKey = document.relationships[right]?.sortKey ?? "";
576
+ return leftKey === rightKey ? left.localeCompare(right) : leftKey.localeCompare(rightKey);
577
+ });
578
+ return children;
579
+ };
580
+ const canCanvasNodeContainChildren = (node) => node !== void 0 && [
581
+ "root",
582
+ "frame",
583
+ "group"
584
+ ].includes(node.component);
585
+ const requireCanvasNode = (document, nodeId) => {
586
+ const node = document.nodes[nodeId];
587
+ if (node !== void 0) return node;
588
+ throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use a current stable node id.");
589
+ };
590
+ const canvasDescendantIds = (document, nodeId) => {
591
+ const found = /* @__PURE__ */ new Set();
592
+ const visit = (parentId) => {
593
+ for (const childId of canvasChildIds(document, parentId)) {
594
+ found.add(childId);
595
+ visit(childId);
596
+ }
597
+ };
598
+ visit(nodeId);
599
+ return found;
600
+ };
601
+ const isCanvasNodeLocked = (document, nodeId) => {
602
+ const visited = /* @__PURE__ */ new Set();
603
+ let current = nodeId;
604
+ while (current !== void 0) {
605
+ if (visited.has(current)) throw new CliError("BAD_REQUEST", "The canvas contains a parent cycle.", "Repair the canvas topology before editing.");
606
+ visited.add(current);
607
+ if (requireCanvasNode(document, current).locked === true) return true;
608
+ current = document.relationships[current]?.parentId;
609
+ }
610
+ return false;
611
+ };
612
+
613
+ //#endregion
614
+ //#region src/application/canvas-duplicate-operations.use-case.ts
615
+ const SLUG_LENGTH = 60;
616
+ const ID_LENGTH = 200;
617
+ const ID_SEQUENCE_LENGTH = 4;
618
+ const SORT_KEY_LENGTH = 500;
619
+ const FALLBACK_SORT_SEQUENCE_LENGTH = 6;
620
+ const slug = (source) => {
621
+ const held = source.normalize("NFKD").toLowerCase().replaceAll(/[^a-z0-9_-]+/gu, "-").replaceAll(/^-+|-+$/gu, "").slice(0, SLUG_LENGTH);
622
+ return held === "" ? "copy" : held;
623
+ };
624
+ const createDuplicateId = (prefix) => {
625
+ let sequence = 0;
626
+ return (label) => {
627
+ sequence += 1;
628
+ return `${slug(prefix)}_${slug(label)}_${String(sequence).padStart(ID_SEQUENCE_LENGTH, "0")}`.slice(0, ID_LENGTH);
629
+ };
630
+ };
631
+ const subtreeIds = (document, rootId) => {
632
+ const ordered = [];
633
+ const visit = (nodeId) => {
634
+ ordered.push(nodeId);
635
+ for (const childId of canvasChildIds(document, nodeId)) visit(childId);
636
+ };
637
+ visit(rootId);
638
+ return ordered;
639
+ };
640
+ const duplicateMap = (document, rootId, nextId) => Object.fromEntries(subtreeIds(document, rootId).map((nodeId) => [nodeId, nextId(requireCanvasNode(document, nodeId).label)]));
641
+ const duplicateInsertOperation = (context, oldId) => {
642
+ const { document, rootId, parentId, inputIndex, sourceSortKey, map } = context;
643
+ const node = requireCanvasNode(document, oldId);
644
+ const newId = map[oldId];
645
+ if (newId === void 0) throw new Error(`Missing duplicate id for ${oldId}`);
646
+ const oldParentage = document.relationships[oldId];
647
+ const isRoot = oldId === rootId;
648
+ const clonedParentId = isRoot ? parentId : map[oldParentage?.parentId ?? ""];
649
+ if (clonedParentId === void 0) throw new Error(`Missing duplicate parent for ${oldId}`);
650
+ const fallbackSort = `agent:${String(inputIndex + 1).padStart(FALLBACK_SORT_SEQUENCE_LENGTH, "0")}`;
651
+ return {
652
+ op: "insertNode",
653
+ node: {
654
+ ...structuredClone(node),
655
+ id: newId
656
+ },
657
+ parentage: {
658
+ parentId: clonedParentId,
659
+ sortKey: isRoot ? `${sourceSortKey}~agent-copy-${String(inputIndex + 1).padStart(ID_SEQUENCE_LENGTH, "0")}`.slice(0, SORT_KEY_LENGTH) : oldParentage?.sortKey ?? fallbackSort
660
+ }
661
+ };
662
+ };
663
+ const duplicateOne = (context) => {
664
+ const { document, input, inputIndex, nextId } = context;
665
+ const source = requireCanvasNode(document, input.id);
666
+ if (input.id === "root") throw new CliError("BAD_REQUEST", "The canvas root cannot be duplicated.", "Duplicate one or more root children instead.");
667
+ const sourceParentage = document.relationships[input.id];
668
+ if (sourceParentage === void 0) throw new CliError("BAD_REQUEST", `Canvas node ${input.id} is detached.`, "Choose a reachable node from canvas tree.");
669
+ const parentId = input.parentId ?? sourceParentage.parentId;
670
+ if (!canCanvasNodeContainChildren(document.nodes[parentId])) throw new CliError("BAD_REQUEST", `Canvas node ${parentId} cannot contain duplicates.`, "Choose a frame, group, or root as the destination.");
671
+ const map = duplicateMap(document, input.id, nextId);
672
+ const treeContext = {
673
+ document,
674
+ rootId: input.id,
675
+ parentId,
676
+ inputIndex,
677
+ sourceSortKey: sourceParentage.sortKey,
678
+ map
679
+ };
680
+ const operations = subtreeIds(document, input.id).map((oldId) => duplicateInsertOperation(treeContext, oldId));
681
+ const newId = map[input.id];
682
+ if (newId === void 0) throw new Error(`Missing duplicate root id for ${input.id}`);
683
+ return {
684
+ operations,
685
+ summary: {
686
+ sourceId: input.id,
687
+ newId,
688
+ name: source.label,
689
+ component: source.component,
690
+ descendantIdMap: Object.fromEntries(Object.entries(map).filter(([oldId]) => oldId !== input.id))
691
+ }
692
+ };
693
+ };
694
+ const duplicateCanvasNodeOperations = (document, inputs, idPrefix) => {
695
+ if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No nodes were provided to duplicate.", "Pass at least one stable node id.");
696
+ const nextId = createDuplicateId(idPrefix);
697
+ const duplicates = inputs.map((input, inputIndex) => duplicateOne({
698
+ document,
699
+ input,
700
+ inputIndex,
701
+ nextId
702
+ }));
703
+ return {
704
+ operations: duplicates.flatMap((duplicate) => duplicate.operations),
705
+ duplicatedNodes: duplicates.map((duplicate) => duplicate.summary)
706
+ };
707
+ };
708
+
709
+ //#endregion
710
+ //#region src/application/canvas-move-operations.use-case.ts
711
+ const moveState = (document) => ({
712
+ document,
713
+ children: new Map(Object.keys(document.nodes).map((nodeId) => [nodeId, canvasChildIds(document, nodeId)])),
714
+ parentOf: new Map(Object.entries(document.relationships).map(([nodeId, relationship]) => [nodeId, relationship.parentId])),
715
+ affected: /* @__PURE__ */ new Set()
716
+ });
717
+ const directDestination = (input, state) => {
718
+ const destination = (state.children.get(input.parentId) ?? []).filter((nodeId) => nodeId !== input.nodeId);
719
+ return {
720
+ parentId: input.parentId,
721
+ index: Math.max(0, Math.min(input.index ?? destination.length, destination.length))
722
+ };
723
+ };
724
+ const siblingDestination = (input, state) => {
725
+ const siblingId = "before" in input ? input.before : input.after;
726
+ if (siblingId === input.nodeId || state.document.nodes[siblingId] === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is not a valid move target.`, "Choose another current sibling node.");
727
+ const parentId = state.parentOf.get(siblingId);
728
+ if (parentId === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is detached.`, "Choose a reachable sibling from canvas tree.");
729
+ const siblingIndex = (state.children.get(parentId) ?? []).filter((nodeId) => nodeId !== input.nodeId).indexOf(siblingId);
730
+ return {
731
+ parentId,
732
+ index: "before" in input ? siblingIndex : siblingIndex + 1
733
+ };
734
+ };
735
+ const destinationFor = (input, state) => "parentId" in input ? directDestination(input, state) : siblingDestination(input, state);
736
+ const validateMove = (input, destination, state) => {
737
+ if (input.nodeId === "root" || state.document.nodes[input.nodeId] === void 0) throw new CliError("BAD_REQUEST", `Canvas node ${input.nodeId} cannot be moved.`, "Choose a current non-root node.");
738
+ if (canvasDescendantIds(state.document, input.nodeId).has(destination.parentId) || destination.parentId === input.nodeId || !canCanvasNodeContainChildren(state.document.nodes[destination.parentId])) throw new CliError("BAD_REQUEST", `Canvas node ${destination.parentId} is not a valid parent for ${input.nodeId}.`, "Choose a frame, group, or root outside the moving subtree.");
739
+ };
740
+ const applyMove = (input, destination, state) => {
741
+ const oldParentId = state.parentOf.get(input.nodeId);
742
+ if (oldParentId !== void 0) {
743
+ state.children.set(oldParentId, (state.children.get(oldParentId) ?? []).filter((id) => id !== input.nodeId));
744
+ state.affected.add(oldParentId);
745
+ }
746
+ const children = [...state.children.get(destination.parentId) ?? []];
747
+ const operations = [];
748
+ const relationships = { ...state.document.relationships };
749
+ const keyAt = (index) => {
750
+ const id = children[index];
751
+ return id === void 0 ? null : relationships[id]?.sortKey ?? null;
752
+ };
753
+ let sortKey = null;
754
+ try {
755
+ const before = keyAt(destination.index - 1);
756
+ const after = keyAt(destination.index);
757
+ const candidate = generateKeyBetween(before, after);
758
+ if ((before === null || before.localeCompare(candidate) < 0) && (after === null || candidate.localeCompare(after) < 0)) sortKey = candidate;
759
+ } catch {
760
+ sortKey = null;
761
+ }
762
+ if (sortKey === null) {
763
+ const ordered = [...children];
764
+ ordered.splice(destination.index, 0, input.nodeId);
765
+ const keys = generateNKeysBetween(null, null, ordered.length).toSorted((left, right) => left.localeCompare(right));
766
+ for (const [index, id] of ordered.entries()) {
767
+ const key = keys[index];
768
+ if (key === void 0) throw new Error("Missing generated move sort key.");
769
+ const parentage = {
770
+ parentId: destination.parentId,
771
+ sortKey: key
772
+ };
773
+ relationships[id] = parentage;
774
+ operations.push({
775
+ op: "setParentage",
776
+ nodeId: id,
777
+ parentage
778
+ });
779
+ }
780
+ } else {
781
+ const parentage = {
782
+ parentId: destination.parentId,
783
+ sortKey
784
+ };
785
+ relationships[input.nodeId] = parentage;
786
+ operations.push({
787
+ op: "setParentage",
788
+ nodeId: input.nodeId,
789
+ parentage
790
+ });
791
+ }
792
+ children.splice(destination.index, 0, input.nodeId);
793
+ state.children.set(destination.parentId, children);
794
+ state.parentOf.set(input.nodeId, destination.parentId);
795
+ state.affected.add(destination.parentId);
796
+ return {
797
+ operations,
798
+ document: {
799
+ ...state.document,
800
+ relationships
801
+ }
802
+ };
803
+ };
804
+ const moveCanvasNodeOperations = (document, inputs) => {
805
+ if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No moves were provided.", "Pass at least one move operation.");
806
+ const state = moveState(document);
807
+ const moves = [];
808
+ return {
809
+ operations: inputs.flatMap((input) => {
810
+ const destination = destinationFor(input, state);
811
+ validateMove(input, destination, state);
812
+ moves.push({
813
+ nodeId: input.nodeId,
814
+ ...destination
815
+ });
816
+ const applied = applyMove(input, destination, state);
817
+ state.document = applied.document;
818
+ return applied.operations;
819
+ }),
820
+ moves,
821
+ affectedParents: Array.from(state.affected, (parentId) => ({
822
+ parentId,
823
+ children: [...state.children.get(parentId) ?? []]
824
+ }))
825
+ };
826
+ };
827
+
828
+ //#endregion
829
+ //#region src/application/canvas-typography-operations.use-case.ts
830
+ const canvasTypographyOperation = (node, styles) => {
831
+ const clear = canvasCssTypographyOwners(new Set(Object.keys(styles))).filter((property) => node.typography?.[property] !== void 0);
832
+ return clear.length === 0 ? null : {
833
+ op: "patchTypography",
834
+ nodeId: node.id,
835
+ typography: { clear }
836
+ };
837
+ };
838
+
839
+ //#endregion
840
+ //#region src/application/canvas-style-operations.use-case.ts
841
+ const ADDITIONAL_STYLE_ID_LENGTH = 200;
842
+ const ADDITIONAL_STYLE_SUFFIX_LENGTH = 10;
843
+ const camelToKebab = (property) => property.startsWith("--") ? property : property.replace(/^Webkit/u, "-webkit-").replace(/^Moz/u, "-moz-").replaceAll(/([a-z\d])([A-Z])/gu, "$1-$2").toLowerCase();
844
+ const additionalOperation = (node, styles) => {
845
+ const held = new Map((node.additionalStyles?.declarations ?? []).map((declaration) => [declaration.id, declaration]));
846
+ for (const [property, value] of Object.entries(styles)) {
847
+ const replaced = Array.from(held, ([, item]) => item).filter((item) => (property.startsWith("--") ? item.property : item.property.toLowerCase()) === property);
848
+ for (const item of replaced) held.delete(item.id);
849
+ if (value === null || canvasNodeStylePatchSchema.safeParse({ [property]: value }).success) continue;
850
+ const base = replaced[0]?.id ?? `css-${property}`.slice(0, ADDITIONAL_STYLE_ID_LENGTH - ADDITIONAL_STYLE_SUFFIX_LENGTH);
851
+ let id = base;
852
+ for (let suffix = 1; held.has(id); suffix += 1) id = `${base}-${String(suffix)}`;
853
+ const result = canvasAdditionalStyleSchema.safeParse({
854
+ id,
855
+ property,
856
+ value: String(value),
857
+ enabled: true
858
+ });
859
+ if (!result.success) throw new CliError("BAD_REQUEST", `Style ${property} is not safe CSS.`, "Use a valid CSS property without imports, expressions, or executable URLs.");
860
+ held.set(id, result.data);
861
+ }
862
+ const declarations = held.values().toArray();
863
+ const requested = declarations.length === 0 && node.additionalStyles === void 0 ? void 0 : { declarations };
864
+ const patch = canvasAdditionalStylePatchBetween(node.additionalStyles, requested);
865
+ return patch === null ? null : {
866
+ op: "patchAdditionalStyles",
867
+ nodeId: node.id,
868
+ additionalStyles: patch
869
+ };
870
+ };
871
+ const layoutOperation = (document, node, next, styles) => {
872
+ const changed = new Set(Object.keys(styles));
873
+ const properties = (axis) => [...canvasAxisStyleProperties(node, axis, document), ...canvasAxisStyleProperties(next, axis, document)];
874
+ const layout = canvasLayoutWithoutCssProperties(node.layout ?? {}, changed, {
875
+ horizontal: properties("horizontal"),
876
+ vertical: properties("vertical")
877
+ });
878
+ for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
879
+ const value = styles[property];
880
+ if (value === "fill" || value === "hug") layout[axis] = { mode: value };
881
+ }
882
+ return JSON.stringify(layout) === JSON.stringify(node.layout ?? {}) ? null : {
883
+ op: "setLayout",
884
+ nodeId: node.id,
885
+ layout: Object.keys(layout).length === 0 ? "default" : layout
886
+ };
887
+ };
888
+ const cssValues = (document, node, styles) => {
889
+ const result = { ...styles };
890
+ for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
891
+ if (styles[property] !== "fill" && styles[property] !== "hug") continue;
892
+ result[property] = null;
893
+ for (const related of canvasAxisStyleProperties(node, axis, document)) if (node.styles[related] !== void 0 || node.additionalStyles?.declarations.some((declaration) => declaration.property === related) === true) result[related] = null;
894
+ }
895
+ return result;
896
+ };
897
+ const operationsForNode = (document, node, source) => {
898
+ const styles = cssValues(document, node, source);
899
+ const additional = additionalOperation(node, styles);
900
+ const stylePatch = Object.fromEntries(Object.entries(styles).filter(([property, value]) => canvasNodeStylePatchSchema.safeParse({ [property]: value }).success));
901
+ const next = {
902
+ ...node,
903
+ styles: { ...node.styles },
904
+ ...additional !== null && { additionalStyles: applyCanvasAdditionalStylePatch(node.additionalStyles, additional.additionalStyles) ?? void 0 }
905
+ };
906
+ for (const [property, value] of Object.entries(stylePatch)) if (value === null) Reflect.deleteProperty(next.styles, property);
907
+ else next.styles[property] = value;
908
+ const layout = layoutOperation(document, node, next, source);
909
+ const typography = canvasTypographyOperation(node, styles);
910
+ const clearFill = (node.component === "text" ? ["color"] : [
911
+ "background",
912
+ "background-color",
913
+ "background-image"
914
+ ]).some((property) => Object.hasOwn(styles, property)) && node.appearance?.fills !== void 0 ? [{
915
+ op: "setAppearance",
916
+ nodeId: node.id,
917
+ appearance: { clear: ["fills"] }
918
+ }] : [];
919
+ return [
920
+ ...Object.keys(stylePatch).length > 0 ? [{
921
+ op: "setStyles",
922
+ nodeId: node.id,
923
+ styles: canvasNodeStylePatchSchema.parse(stylePatch)
924
+ }] : [],
925
+ ...clearFill,
926
+ ...typography === null ? [] : [typography],
927
+ ...layout === null ? [] : [layout],
928
+ ...additional === null ? [] : [additional]
929
+ ];
930
+ };
931
+ const mergedUpdates = (updates) => {
932
+ const merged = /* @__PURE__ */ new Map();
933
+ for (const update of updates) for (const nodeId of update.nodeIds) {
934
+ const styles = merged.get(nodeId) ?? {};
935
+ for (const [property, value] of Object.entries(update.styles)) {
936
+ const normalized = camelToKebab(property);
937
+ Reflect.deleteProperty(styles, normalized);
938
+ styles[normalized] = value;
939
+ }
940
+ merged.set(nodeId, styles);
941
+ }
942
+ return merged;
943
+ };
944
+ const canvasStyleOperations = (document, updates) => {
945
+ const operations = [...mergedUpdates(updates)].flatMap(([nodeId, styles]) => {
946
+ const node = document.nodes[nodeId];
947
+ if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use current stable node ids.");
948
+ return operationsForNode(document, node, styles);
949
+ });
950
+ if (operations.length === 0) throw new CliError("BAD_REQUEST", "No style changes were provided.", "Pass at least one changed CSS property.");
951
+ return operations;
952
+ };
953
+
954
+ //#endregion
955
+ //#region src/application/canvas-edit-operations.use-case.ts
956
+ const projectStyles = (node, operation) => {
957
+ const styles = { ...node.styles };
958
+ for (const [name, value] of Object.entries(operation.styles)) if (value === null || value === void 0) Reflect.deleteProperty(styles, name);
959
+ else styles[name] = value;
960
+ const cleared = operation.clear ?? [];
961
+ for (const name of cleared) Reflect.deleteProperty(styles, name);
962
+ const typography = applyCanvasTypographyPatch(node.typography, { clear: [...canvasCssTypographyOwners(/* @__PURE__ */ new Set([...Object.keys(operation.styles), ...cleared]))] });
963
+ return projectPresentation({
964
+ ...node,
965
+ styles
966
+ }, "typography", typography ?? "default");
967
+ };
968
+ const PLANNED_OPERATIONS = /* @__PURE__ */ new Set([
969
+ "insertNode",
970
+ "setText",
971
+ "setLabel",
972
+ "setStyles",
973
+ "setAppearance",
974
+ "setTypography",
975
+ "patchTypography",
976
+ "setLayout",
977
+ "setAdditionalStyles",
978
+ "patchAdditionalStyles",
979
+ "setParentage"
980
+ ]);
981
+ const isPlannedOperation = (operation) => PLANNED_OPERATIONS.has(operation.op);
982
+ const projectPresentation = (node, field, value) => {
983
+ const next = { ...node };
984
+ if (value === "default") Reflect.deleteProperty(next, field);
985
+ else Reflect.set(next, field, value);
986
+ return next;
987
+ };
988
+ const projectNode = (node, operation) => {
989
+ switch (operation.op) {
990
+ case "setText":
991
+ if (node.component !== "text") throw new CliError("BAD_REQUEST", `Canvas node ${node.id} is not editable text.`, "Use the text node id from canvas tree.");
992
+ return {
993
+ ...node,
994
+ props: {
995
+ ...node.props,
996
+ text: operation.text
997
+ }
998
+ };
999
+ case "setLabel": return {
1000
+ ...node,
1001
+ label: operation.label,
1002
+ labelOrigin: "user"
1003
+ };
1004
+ case "setStyles": return projectStyles(node, operation);
1005
+ case "setAppearance": {
1006
+ const appearance = { ...node.appearance };
1007
+ const cleared = operation.appearance.clear ?? [];
1008
+ for (const property of cleared) Reflect.deleteProperty(appearance, property);
1009
+ const next = {
1010
+ ...node,
1011
+ appearance
1012
+ };
1013
+ if (Object.keys(appearance).length === 0) Reflect.deleteProperty(next, "appearance");
1014
+ return next;
1015
+ }
1016
+ case "patchTypography": return projectPresentation(node, "typography", applyCanvasTypographyPatch(node.typography, operation.typography) ?? "default");
1017
+ case "setTypography": return projectPresentation(node, "typography", operation.typography);
1018
+ case "setLayout": return projectPresentation(node, "layout", operation.layout);
1019
+ case "patchAdditionalStyles": {
1020
+ const additionalStyles = applyCanvasAdditionalStylePatch(node.additionalStyles, operation.additionalStyles);
1021
+ return projectPresentation(node, "additionalStyles", additionalStyles ?? "default");
1022
+ }
1023
+ case "setAdditionalStyles": return projectPresentation(node, "additionalStyles", operation.additionalStyles);
1024
+ }
1025
+ };
1026
+ const projectOperation = (scene, operation) => {
1027
+ if (!isPlannedOperation(operation)) throw new Error(`Unexpected focused edit operation: ${operation.op}`);
1028
+ if (operation.op === "insertNode") {
1029
+ if (scene.nodes[operation.node.id] !== void 0) throw new CliError("BAD_REQUEST", `Duplicate id ${operation.node.id} already exists.`, "Use a new client token for a new duplication.");
1030
+ return {
1031
+ ...scene,
1032
+ nodes: {
1033
+ ...scene.nodes,
1034
+ [operation.node.id]: operation.node
1035
+ },
1036
+ relationships: {
1037
+ ...scene.relationships,
1038
+ [operation.node.id]: operation.parentage
1039
+ }
1040
+ };
1041
+ }
1042
+ const node = requireCanvasNode(scene, operation.nodeId);
1043
+ if (operation.op === "setParentage") return {
1044
+ ...scene,
1045
+ relationships: {
1046
+ ...scene.relationships,
1047
+ [node.id]: operation.parentage
1048
+ }
1049
+ };
1050
+ return {
1051
+ ...scene,
1052
+ nodes: {
1053
+ ...scene.nodes,
1054
+ [node.id]: projectNode(node, operation)
1055
+ }
1056
+ };
1057
+ };
1058
+ const moveInput = (edit) => {
1059
+ const { nodeId, destination } = edit;
1060
+ switch (destination.kind) {
1061
+ case "before": return {
1062
+ nodeId,
1063
+ before: destination.nodeId
1064
+ };
1065
+ case "after": return {
1066
+ nodeId,
1067
+ after: destination.nodeId
1068
+ };
1069
+ case "parent": return {
1070
+ nodeId,
1071
+ parentId: destination.parentId,
1072
+ ...destination.index !== void 0 && { index: destination.index }
1073
+ };
1074
+ }
1075
+ };
1076
+ const operationsForEdit = (edit, plan, prefix, duplicateIndex) => {
1077
+ switch (edit.kind) {
1078
+ case "set_text": return [{
1079
+ op: "setText",
1080
+ nodeId: edit.nodeId,
1081
+ text: edit.text
1082
+ }];
1083
+ case "rename": return [{
1084
+ op: "setLabel",
1085
+ nodeId: edit.nodeId,
1086
+ label: edit.name,
1087
+ labelOrigin: "user"
1088
+ }];
1089
+ case "set_styles": return canvasStyleOperations(plan.scene, [{
1090
+ nodeIds: edit.nodeIds,
1091
+ styles: edit.styles
1092
+ }]);
1093
+ case "duplicate": {
1094
+ const idPrefix = duplicateIndex === 0 ? prefix : `${String(duplicateIndex + 1)}_${prefix}`;
1095
+ const duplicate = duplicateCanvasNodeOperations(plan.scene, edit.nodeIds.map((id) => ({
1096
+ id,
1097
+ ...edit.parentId !== void 0 && { parentId: edit.parentId }
1098
+ })), idPrefix);
1099
+ plan.duplicatedNodes.push(...duplicate.duplicatedNodes);
1100
+ return duplicate.operations;
1101
+ }
1102
+ case "move": {
1103
+ const move = moveCanvasNodeOperations(plan.scene, [moveInput(edit)]);
1104
+ plan.moves.push(...move.moves);
1105
+ for (const parent of move.affectedParents) plan.affectedParents.add(parent.parentId);
1106
+ return move.operations;
1107
+ }
1108
+ }
1109
+ };
1110
+ const planCanvasEdits = (scene, edits, prefix) => {
1111
+ const plan = {
1112
+ scene,
1113
+ operations: [],
1114
+ duplicatedNodes: [],
1115
+ moves: [],
1116
+ affectedParents: /* @__PURE__ */ new Set()
1117
+ };
1118
+ let duplicateIndex = 0;
1119
+ for (const edit of edits) {
1120
+ const operations = operationsForEdit(edit, plan, prefix, duplicateIndex);
1121
+ if (edit.kind === "duplicate") duplicateIndex += 1;
1122
+ for (const operation of operations) plan.scene = projectOperation(plan.scene, operation);
1123
+ plan.operations.push(...operations);
1124
+ }
1125
+ return {
1126
+ operations: plan.operations,
1127
+ duplicatedNodes: plan.duplicatedNodes,
1128
+ moves: plan.moves,
1129
+ affectedParents: [...plan.affectedParents].map((parentId) => ({
1130
+ parentId,
1131
+ children: canvasChildIds(plan.scene, parentId)
1132
+ }))
1133
+ };
1134
+ };
1135
+
1136
+ //#endregion
1137
+ //#region src/application/canvas-reference-mutation.use-case.ts
1138
+ const outside = (ids) => {
1139
+ throw new CliError("BAD_REQUEST", `These nodes are outside the link selection: ${ids.join(", ")}.`, "Keep the complete link. Edit only its page or selection and preserve the destination page.");
1140
+ };
1141
+ const requiredIds = (operation, document) => {
1142
+ if (operation.op === "insertNode") return [operation.parentage.parentId];
1143
+ if (operation.op === "insertText" || operation.op === "insertPrototype") return [operation.parentId, ...operation.afterId === void 0 ? [] : [operation.afterId]];
1144
+ if (operation.op === "insertConvertedSubtree") {
1145
+ if (operation.destination.kind === "adjacent") return outside(["adjacent conversion"]);
1146
+ return [operation.destination.targetNodeId];
1147
+ }
1148
+ if (operation.op === "move" || operation.op === "setParentage") {
1149
+ const parentId = operation.op === "move" ? operation.parentId : operation.parentage.parentId;
1150
+ return [
1151
+ operation.nodeId,
1152
+ ...parentId === document.relationships[operation.nodeId]?.parentId ? [] : [parentId],
1153
+ ...operation.op === "move" && operation.afterId !== void 0 ? [operation.afterId] : []
1154
+ ];
1155
+ }
1156
+ return [operation.nodeId];
1157
+ };
1158
+ const insertedIds = (operation) => {
1159
+ if (operation.op === "insertNode") return [operation.node.id];
1160
+ if (operation.op === "insertText" || operation.op === "insertPrototype") return [operation.nodeId];
1161
+ if (operation.op === "insertConvertedSubtree") return Object.keys(operation.nodes);
1162
+ return [];
1163
+ };
1164
+ const conversionPatch = (document, operation) => {
1165
+ const destination = operation.destination;
1166
+ if (destination.kind === "adjacent") return outside(["adjacent conversion"]);
1167
+ const parentId = destination.kind === "replace" ? document.relationships[destination.targetNodeId]?.parentId : destination.targetNodeId;
1168
+ if (parentId === void 0) return outside([destination.targetNodeId]);
1169
+ const pageId = destination.kind === "insert-children" && destination.targetNodeId === "root" ? destination.pageId ?? "canvas-page-default" : canvasReferencePageOf(document, destination.targetNodeId);
1170
+ const root = operation.nodes[operation.rootNodeId];
1171
+ if (root === void 0) return outside([operation.rootNodeId]);
1172
+ return {
1173
+ nodes: {
1174
+ ...operation.nodes,
1175
+ [operation.rootNodeId]: {
1176
+ ...root,
1177
+ ...parentId === "root" && pageId !== null && { props: {
1178
+ ...root.props,
1179
+ canvasPageId: pageId
1180
+ } }
1181
+ }
1182
+ },
1183
+ relationships: {
1184
+ ...operation.relationships,
1185
+ [operation.rootNodeId]: {
1186
+ parentId,
1187
+ sortKey: ""
1188
+ }
1189
+ }
1190
+ };
1191
+ };
1192
+ const primitiveScopeNode = (operation) => ({
1193
+ component: operation.op === "insertText" ? "text" : "prototype",
1194
+ props: { ...operation.op === "insertPrototype" && operation.canvasPageId !== void 0 && { canvasPageId: operation.canvasPageId } }
1195
+ });
1196
+ const structurePatch = (document, operation) => {
1197
+ if (operation.op === "insertNode") return {
1198
+ nodes: { [operation.node.id]: operation.node },
1199
+ relationships: { [operation.node.id]: operation.parentage }
1200
+ };
1201
+ if (operation.op === "insertText" || operation.op === "insertPrototype") return {
1202
+ nodes: { [operation.nodeId]: primitiveScopeNode(operation) },
1203
+ relationships: { [operation.nodeId]: {
1204
+ parentId: operation.parentId,
1205
+ sortKey: ""
1206
+ } }
1207
+ };
1208
+ if (operation.op === "insertConvertedSubtree") return conversionPatch(document, operation);
1209
+ if (operation.op === "move" || operation.op === "setParentage") return {
1210
+ nodes: {},
1211
+ relationships: { [operation.nodeId]: operation.op === "move" ? {
1212
+ parentId: operation.parentId,
1213
+ sortKey: ""
1214
+ } : operation.parentage }
1215
+ };
1216
+ if (operation.op === "setProps") {
1217
+ const node = document.nodes[operation.nodeId];
1218
+ if (node !== void 0) return {
1219
+ nodes: { [operation.nodeId]: {
1220
+ ...node,
1221
+ props: operation.props === "default" ? {} : operation.props
1222
+ } },
1223
+ relationships: {}
1224
+ };
1225
+ }
1226
+ return {
1227
+ nodes: {},
1228
+ relationships: {}
1229
+ };
1230
+ };
1231
+ const validateOperation = (reference, held, scope, operation) => {
1232
+ const inserted = insertedIds(operation);
1233
+ const canInsertAtRoot = reference.nodeIds.length === 0 && (inserted.length > 0 || operation.op === "move" || operation.op === "setParentage");
1234
+ const denied = [...requiredIds(operation, held).filter((id) => !canInsertAtRoot || id !== "root"), ...inserted.filter((id) => held.nodes[id] !== void 0)].filter((id) => !scope.has(id));
1235
+ if (denied.length > 0) outside(denied);
1236
+ return inserted;
1237
+ };
1238
+ const assertCanvasReferenceOperations = (reference, document, operations) => {
1239
+ if (!hasCanvasReferenceScope(reference)) return;
1240
+ const scope = new Set(canvasReferenceNodeIds(reference, document));
1241
+ const resolved = resolveCanvasReference(reference, document);
1242
+ if (!resolved.ok) return outside(reference.nodeIds);
1243
+ const held = {
1244
+ nodes: { ...document.nodes },
1245
+ relationships: { ...document.relationships }
1246
+ };
1247
+ for (const operation of operations) {
1248
+ const inserted = validateOperation(reference, held, scope, operation);
1249
+ const patch = structurePatch(held, operation);
1250
+ Object.assign(held.nodes, patch.nodes);
1251
+ Object.assign(held.relationships, patch.relationships);
1252
+ const crossed = [...Object.keys(patch.nodes), ...Object.keys(patch.relationships)].filter((id) => held.nodes[id]?.component === "page" || canvasReferencePageOf(held, id) !== resolved.pageId);
1253
+ if (crossed.length > 0) outside(crossed);
1254
+ for (const id of inserted) scope.add(id);
1255
+ if (operation.op !== "remove") continue;
1256
+ const removed = resolveCanvasReference({
1257
+ ...reference,
1258
+ nodeIds: [operation.nodeId]
1259
+ }, held);
1260
+ if (!removed.ok) continue;
1261
+ for (const id of removed.nodeIds) {
1262
+ scope.delete(id);
1263
+ Reflect.deleteProperty(held.nodes, id);
1264
+ Reflect.deleteProperty(held.relationships, id);
1265
+ }
1266
+ }
1267
+ };
1268
+
1269
+ //#endregion
1270
+ //#region src/application/edit-canvas.composite.ts
1271
+ const targetIds = (edit) => {
1272
+ switch (edit.kind) {
1273
+ case "set_text":
1274
+ case "rename": return [edit.nodeId];
1275
+ case "set_styles": return edit.nodeIds;
1276
+ case "duplicate": return [...edit.nodeIds, ...edit.parentId === void 0 ? [] : [edit.parentId]];
1277
+ case "move": return [edit.nodeId, edit.destination.kind === "parent" ? edit.destination.parentId : edit.destination.nodeId];
1278
+ }
1279
+ };
1280
+ const scopeIds = (edit, scene) => {
1281
+ if (edit.kind === "duplicate") return [...edit.nodeIds, ...edit.parentId === void 0 || edit.nodeIds.every((id) => scene.relationships[id]?.parentId === edit.parentId) ? [] : [edit.parentId]];
1282
+ if (edit.kind === "move" && edit.destination.kind === "parent" && scene.relationships[edit.nodeId]?.parentId === edit.destination.parentId) return [edit.nodeId];
1283
+ return targetIds(edit);
1284
+ };
1285
+ const validateTargets = (input, scene) => {
1286
+ const ids = new Set(input.edits.flatMap((edit) => targetIds(edit)));
1287
+ for (const id of ids) requireCanvasNode(scene, id);
1288
+ const reference = {
1289
+ canvasId: input.canvasId,
1290
+ nodeIds: input.nodeIds ?? [],
1291
+ ...input.pageId !== void 0 && { pageId: input.pageId }
1292
+ };
1293
+ for (const edit of input.edits) assertCanvasReferenceNodes(reference, scene, scopeIds(edit, scene));
1294
+ };
1295
+ const createEditCanvasComposite = (remote) => ({ execute: async (input) => {
1296
+ const scene = await sceneAtVersion({ remote }, input.canvasId, input.baseVersion);
1297
+ validateTargets(input, scene);
1298
+ const plan = planCanvasEdits(scene, input.edits, input.idPrefix ?? `copy_${input.mutationId.replaceAll("-", "")}`);
1299
+ assertCanvasReferenceOperations({
1300
+ canvasId: input.canvasId,
1301
+ nodeIds: input.nodeIds ?? [],
1302
+ ...input.pageId !== void 0 && { pageId: input.pageId }
1303
+ }, scene, plan.operations.filter((operation) => "nodeId" in operation && scene.nodes[operation.nodeId] !== void 0));
1304
+ const parsed = applyCanvasOperationsInputSchema.safeParse({
1305
+ canvasId: input.canvasId,
1306
+ mutationId: input.mutationId,
1307
+ documentFormatVersion: 7,
1308
+ baseVersion: input.baseVersion,
1309
+ operations: plan.operations
1310
+ });
1311
+ if (!parsed.success) throw new CliError("BAD_REQUEST", "The edit contains an invalid canvas operation.", parsed.error.issues[0]?.message ?? "Check the edit’s node references and values.");
1312
+ const result = applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(parsed.data));
1313
+ return {
1314
+ ...result,
1315
+ next: [`Reuse version ${String(result.version)} as baseVersion for the next edit; no extra read is required.`, `Render the affected screen at version ${String(result.version)} when ready for visual review.`],
1316
+ ...plan.duplicatedNodes.length > 0 && { duplicatedNodes: plan.duplicatedNodes },
1317
+ ...plan.moves.length > 0 && {
1318
+ moves: plan.moves,
1319
+ affectedParents: plan.affectedParents
1320
+ }
1321
+ };
1322
+ } });
1323
+
1324
+ //#endregion
1325
+ //#region src/infrastructure/capability-reference.mapper.ts
1326
+ const fromCapabilityReference = (catalog, id) => {
1327
+ const capability = catalog.find((candidate) => candidate.id === id);
1328
+ if (capability === void 0) throw new TypeError(`${id} is missing from the capability catalogue`);
1329
+ return capability;
1330
+ };
1331
+
1332
+ //#endregion
1333
+ //#region src/application/result-page.use-case.ts
1334
+ const TARGET_PAGE_BYTES = 48e3;
1335
+ const boundedResultPage = (entries, offset, limit, maxBytes = TARGET_PAGE_BYTES) => {
1336
+ if (offset > entries.length) throw new CliError("BAD_REQUEST", "The result page offset is out of range.", "Restart pagination at offset 0.");
1337
+ const selected = [];
1338
+ let bytes = 2;
1339
+ const offered = entries.slice(offset, offset + limit);
1340
+ for (const entry of offered) {
1341
+ const size = Buffer.byteLength(JSON.stringify(entry)) + 1;
1342
+ if (selected.length > 0 && bytes + size > maxBytes) break;
1343
+ selected.push(entry);
1344
+ bytes += size;
1345
+ }
1346
+ const nextOffset = offset + selected.length;
1347
+ return {
1348
+ entries: selected,
1349
+ total: entries.length,
1350
+ offset,
1351
+ nextOffset: nextOffset < entries.length ? nextOffset : null,
1352
+ complete: nextOffset === entries.length
1353
+ };
1354
+ };
1355
+
1356
+ //#endregion
1357
+ //#region src/application/canvas-conversion-status.use-case.ts
1358
+ const conversionEntries = (job) => {
1359
+ if (job.state !== "succeeded") return [];
1360
+ return [
1361
+ ...job.result.insertedNodeIds.map((nodeId) => ({
1362
+ kind: "inserted",
1363
+ nodeId
1364
+ })),
1365
+ ...job.result.removedNodeIds.map((nodeId) => ({
1366
+ kind: "removed",
1367
+ nodeId
1368
+ })),
1369
+ ...Object.entries(job.result.idMap).map(([temporaryId, nodeId]) => ({
1370
+ kind: "identity",
1371
+ temporaryId,
1372
+ nodeId
1373
+ })),
1374
+ ...job.result.report.issues.map((issue) => ({
1375
+ kind: "issue",
1376
+ issue
1377
+ }))
1378
+ ];
1379
+ };
1380
+ const conversionSummary = (job) => {
1381
+ if (job.state !== "succeeded") return null;
1382
+ return {
1383
+ mutationId: job.result.mutationId,
1384
+ previousVersion: job.result.previousVersion,
1385
+ version: job.result.version,
1386
+ rootNodeId: job.result.rootNodeId,
1387
+ affectedBounds: job.result.affectedBounds,
1388
+ insertedCount: job.result.insertedNodeIds.length,
1389
+ removedCount: job.result.removedNodeIds.length,
1390
+ identityCount: Object.keys(job.result.idMap).length,
1391
+ issueCount: job.result.report.issues.length
1392
+ };
1393
+ };
1394
+ const canvasConversionStatus = (job, page) => ({
1395
+ kind: "canvas-conversion",
1396
+ operation: {
1397
+ kind: "canvas-conversion",
1398
+ canvasId: job.canvasId,
1399
+ jobId: job.id
1400
+ },
1401
+ state: job.state,
1402
+ phase: job.phase,
1403
+ requestedVersion: job.requestedVersion,
1404
+ destination: job.destination,
1405
+ result: conversionSummary(job),
1406
+ failure: job.failure,
1407
+ details: boundedResultPage(conversionEntries(job), page.offset, page.limit),
1408
+ warnings: job.state === "succeeded" ? ["This receipt does not verify visual fidelity. Render the committed root to inspect it."] : []
1409
+ });
1410
+
1411
+ //#endregion
1412
+ //#region src/application/canvas-conversion.use-case.ts
1413
+ const CREATE_IMPORT_PROCEDURE = "canvas.render.importSource";
1414
+ const READ_IMPORT_PROCEDURE$1 = "canvas.render.getImport";
1415
+ const POLL_MS$2 = 250;
1416
+ const invalidResponse$2 = (operation) => new CliError("INTERNAL", `The API returned an invalid ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
1417
+ const wait$1 = async (milliseconds) => new Promise((resolve) => {
1418
+ globalThis.setTimeout(resolve, milliseconds);
1419
+ });
1420
+ const terminalFailure = (job) => {
1421
+ const failure = job.failure;
1422
+ return new CliError(failure.reason === "VERSION_CHANGED" ? "CONFLICT" : failure.reason === "TARGET_NOT_FOUND" ? "NOT_FOUND" : failure.reason === "TARGET_INVALID" || failure.reason === "CONVERSION_FAILED" ? "BAD_REQUEST" : "INTERNAL", failure.message, failure.retryable ? "Retry the exact write. If it repeats, run `enhance doctor` and report the job id." : "Inspect the current canvas and correct the conversion source or destination before retrying.", {
1423
+ jobId: job.id,
1424
+ phase: failure.phase,
1425
+ reason: failure.reason
1426
+ });
1427
+ };
1428
+ const readImport = async (remote, jobId) => {
1429
+ const parsed = getCanvasConversionOutputSchema.safeParse(await remote.query(READ_IMPORT_PROCEDURE$1, { jobId }));
1430
+ if (!parsed.success) throw invalidResponse$2("conversion status");
1431
+ if (parsed.data.job.id !== jobId) throw invalidResponse$2("conversion identity");
1432
+ return parsed.data.job;
1433
+ };
1434
+ const awaitImport = async (remote, initial, timeoutMs) => {
1435
+ const deadline = Date.now() + timeoutMs;
1436
+ let job = initial;
1437
+ while (job.state === "queued" || job.state === "running") {
1438
+ if (Date.now() >= deadline) return job;
1439
+ await wait$1(POLL_MS$2);
1440
+ job = await readImport(remote, job.id);
1441
+ }
1442
+ if (job.state !== "succeeded") throw terminalFailure(job);
1443
+ return job;
1444
+ };
1445
+ const isMatchingDestination = (job, input) => {
1446
+ const actual = job.destination;
1447
+ const expected = input.request.destination;
1448
+ if (actual.kind !== expected.kind) return false;
1449
+ if (actual.kind === "adjacent" || expected.kind === "adjacent") return true;
1450
+ return actual.targetNodeId === expected.targetNodeId && (actual.kind !== "insert-children" || expected.kind !== "insert-children" || actual.pageId === expected.pageId);
1451
+ };
1452
+ const assertConversionIdentity = (job, input) => {
1453
+ const expected = input.request;
1454
+ if (job.canvasId !== expected.canvasId || job.requestedVersion !== expected.expectedVersion || !isMatchingDestination(job, input)) throw invalidResponse$2("conversion destination or revision");
1455
+ const source = job.source;
1456
+ if (source.kind !== expected.source.kind || source.kind === "screen" && expected.source.kind === "screen" && source.nodeId !== expected.source.nodeId || source.kind === "html" && expected.source.kind === "html" && source.label !== expected.source.label) throw invalidResponse$2("conversion source");
1457
+ if (job.state === "succeeded" && (job.result.canvasId !== expected.canvasId || expected.revisionPolicy === "strict" && job.result.previousVersion !== expected.expectedVersion)) throw invalidResponse$2("conversion commitment");
1458
+ };
1459
+ const runCanvasConversion = async (remote, input) => {
1460
+ const made = createCanvasConversionOutputSchema.safeParse(await remote.mutate(CREATE_IMPORT_PROCEDURE, input.request));
1461
+ if (!made.success) throw invalidResponse$2("conversion creation");
1462
+ assertConversionIdentity(made.data.job, input);
1463
+ const job = await awaitImport(remote, made.data.job, input.waitMs);
1464
+ assertConversionIdentity(job, input);
1465
+ return job;
1466
+ };
1467
+ const makeCanvasEditable = async (remote, offered) => {
1468
+ const input = canvasMakeEditableCapabilityInputSchema.parse(offered);
1469
+ const reference = parseCanvasReference(input.canvasRef);
1470
+ return canvasConversionStatus(await runCanvasConversion(remote, {
1471
+ request: {
1472
+ canvasId: reference.canvasId,
1473
+ expectedVersion: input.baseVersion,
1474
+ revisionPolicy: "strict",
1475
+ scope: {
1476
+ pageId: reference.pageId,
1477
+ nodeIds: [...reference.nodeIds]
1478
+ },
1479
+ source: {
1480
+ kind: "screen",
1481
+ nodeId: input.sourceNodeId
1482
+ },
1483
+ destination: input.placement
1484
+ },
1485
+ waitMs: input.waitMs
1486
+ }), {
1487
+ offset: 0,
1488
+ limit: 40
1489
+ });
1490
+ };
1491
+
1492
+ //#endregion
1493
+ //#region src/application/write-html-canvas.composite.ts
1494
+ const READ_IMPORT_PROCEDURE = "canvas.render.getImport";
1495
+ const MAX_ACTIVITY_NODE_IDS = 100;
1496
+ const MAX_RECEIPT_ENTRIES = 40;
1497
+ const failedReview = (error, input, version) => {
1498
+ return {
1499
+ state: "failed",
1500
+ mutationCommitted: true,
1501
+ requestedVersion: version,
1502
+ ...error instanceof CliError ? {
1503
+ code: error.code,
1504
+ message: error.message,
1505
+ remediation: error.remediation,
1506
+ ...error.fields !== void 0 && { fields: error.fields }
1507
+ } : {
1508
+ code: "INTERNAL",
1509
+ message: "The post-write review render failed.",
1510
+ remediation: "Render the committed version and affected area again; do not replay the write."
1511
+ },
1512
+ next: [`enhance canvas render --canvas ${input.canvasId} --expected-version ${String(version)}`, "Do not replay the committed write with a new mutation id."]
1513
+ };
1514
+ };
1515
+ const renderReview = async (render, input, imported) => {
1516
+ try {
1517
+ return await render.execute({
1518
+ canvasId: input.canvasId,
1519
+ expectedVersion: imported.result.version,
1520
+ target: {
1521
+ kind: "node",
1522
+ nodeId: imported.result.rootNodeId
1523
+ },
1524
+ sourceState: null,
1525
+ scale: input.renderScale,
1526
+ outputPath: input.renderOutputPath,
1527
+ overwrite: input.overwriteRender,
1528
+ timeoutMs: input.renderTimeoutMs,
1529
+ retryClientToken: input.renderClientToken
1530
+ });
1531
+ } catch (error) {
1532
+ return failedReview(error, input, imported.result.version);
1533
+ }
1534
+ };
1535
+ const createdNodes = async (remote, imported) => {
1536
+ const scene = await sceneAtVersion({ remote }, imported.canvasId, imported.result.version);
1537
+ return imported.result.insertedNodeIds.map((nodeId) => {
1538
+ const node = scene.nodes[nodeId];
1539
+ return {
1540
+ id: nodeId,
1541
+ name: node?.label ?? "",
1542
+ component: node?.component ?? ""
1543
+ };
1544
+ });
1545
+ };
1546
+ const committedResponse = (input, imported) => ({
1547
+ canvasId: input.canvasId,
1548
+ mutationCommitted: true,
1549
+ jobId: imported.id,
1550
+ mutationId: imported.result.mutationId,
1551
+ rootNodeId: imported.result.rootNodeId,
1552
+ mode: input.mode,
1553
+ targetNodeId: input.targetNodeId,
1554
+ previousVersion: imported.result.previousVersion,
1555
+ version: imported.result.version,
1556
+ insertedNodeIds: imported.result.insertedNodeIds,
1557
+ removedNodeIds: imported.result.removedNodeIds,
1558
+ affected: {
1559
+ inserted: imported.result.insertedNodeIds.length,
1560
+ changed: 0,
1561
+ removed: imported.result.removedNodeIds.length
1562
+ },
1563
+ affectedBounds: imported.result.affectedBounds
1564
+ });
1565
+ const pendingResponse = (job) => ({
1566
+ state: "pending",
1567
+ canvasId: job.canvasId,
1568
+ jobId: job.id,
1569
+ phase: job.phase,
1570
+ status: {
1571
+ tool: "capability_query",
1572
+ arguments: {
1573
+ capability: READ_IMPORT_PROCEDURE,
1574
+ input: { jobId: job.id }
1575
+ }
1576
+ },
1577
+ next: ["Read the existing import status; do not start another import."]
1578
+ });
1579
+ const conversionInput = (input) => ({
1580
+ waitMs: input.renderTimeoutMs,
1581
+ request: {
1582
+ canvasId: input.canvasId,
1583
+ expectedVersion: input.baseVersion,
1584
+ ...input.revisionPolicy !== void 0 && { revisionPolicy: input.revisionPolicy },
1585
+ ...(input.pageId !== void 0 || (input.selectionNodeIds?.length ?? 0) > 0) && { scope: {
1586
+ pageId: input.pageId,
1587
+ nodeIds: [...input.selectionNodeIds ?? []]
1588
+ } },
1589
+ source: {
1590
+ kind: "html",
1591
+ html: input.html,
1592
+ label: "Agent-authored HTML",
1593
+ ...input.idPrefix !== void 0 && { idPrefix: input.idPrefix }
1594
+ },
1595
+ destination: {
1596
+ kind: input.mode,
1597
+ targetNodeId: input.targetNodeId,
1598
+ ...input.mode === "insert-children" && input.pageId !== void 0 && { pageId: input.pageId }
1599
+ }
1600
+ }
1601
+ });
1602
+ const createWriteHtmlCanvasComposite = (remote, render) => ({ execute: async (input) => {
1603
+ const activity = await createCanvasActivityComposite(remote).begin({
1604
+ canvasId: input.canvasId,
1605
+ phase: "creating",
1606
+ nodeIds: [input.targetNodeId],
1607
+ bounds: null
1608
+ });
1609
+ try {
1610
+ const imported = await runCanvasConversion(remote, conversionInput(input));
1611
+ if (input.responseMode === "bounded") return canvasConversionStatus(imported, {
1612
+ offset: 0,
1613
+ limit: MAX_RECEIPT_ENTRIES
1614
+ });
1615
+ if (imported.state !== "succeeded") return pendingResponse(imported);
1616
+ if (input.review === "none") return committedResponse(input, imported);
1617
+ await activity?.update({
1618
+ phase: "rendering",
1619
+ nodeIds: imported.result.insertedNodeIds.slice(0, MAX_ACTIVITY_NODE_IDS),
1620
+ bounds: imported.result.affectedBounds
1621
+ });
1622
+ const review = await renderReview(render, input, imported);
1623
+ let nodes = [];
1624
+ try {
1625
+ nodes = await createdNodes(remote, imported);
1626
+ } catch {
1627
+ nodes = [];
1628
+ }
1629
+ return {
1630
+ ...committedResponse(input, imported),
1631
+ createdNodes: nodes,
1632
+ review,
1633
+ next: ["Inspect the review PNG before continuing."]
1634
+ };
1635
+ } finally {
1636
+ await activity?.finish();
1637
+ }
1638
+ } });
1639
+
1640
+ //#endregion
1641
+ //#region src/application/read-canvas-reference.use-case.ts
1642
+ const readCanvasReferenceScene = async (remote, input) => {
1643
+ const reference = parseCanvasReference(input.canvas);
1644
+ const held = getCanvasDocumentOutputSchema.parse(await remote.query("canvas.document.get", { canvasId: reference.canvasId }));
1645
+ const document = canvasReadableSceneDocumentSchema.parse(held.document);
1646
+ if (hasCanvasReferenceScope(reference)) canvasReferenceNodeIds(reference, document);
1647
+ if (input.nodeId !== void 0) assertCanvasReferenceNodes(reference, document, [input.nodeId]);
1648
+ const scope = resolveCanvasReference(input.nodeId === void 0 ? reference : {
1649
+ ...reference,
1650
+ nodeIds: [input.nodeId]
1651
+ }, document);
1652
+ if (!scope.ok) throw new CliError("NOT_FOUND", "The requested canvas scope is unavailable.", "Copy a current page or selection link. Do not broaden the request.");
1653
+ const children = Object.groupBy(Object.entries(document.relationships), ([, relation]) => relation.parentId);
1654
+ const nodes = Object.values(document.nodes).filter((node) => scope.nodeIds.has(node.id)).map((node) => ({
1655
+ ...node,
1656
+ kind: node.component,
1657
+ parentId: document.relationships[node.id]?.parentId ?? null,
1658
+ children: (children[node.id] ?? []).map(([id]) => id)
1659
+ }));
1660
+ return {
1661
+ canvasId: reference.canvasId,
1662
+ version: held.version,
1663
+ pageId: scope.pageId,
1664
+ source: reference.nodeIds.length > 0 ? "selection-link" : reference.pageId === void 0 ? "canvas-link" : "page-link",
1665
+ selectedNodeIds: reference.nodeIds,
1666
+ rootNodeIds: scope.rootNodeIds,
1667
+ nodeCount: nodes.length,
1668
+ nodes,
1669
+ next: ["Keep the complete supplied canvas link for subsequent reads, edits and renders. Use this version as baseVersion; edit only these nodes or descendants."]
1670
+ };
1671
+ };
1672
+
1673
+ //#endregion
1674
+ //#region src/infrastructure/render-file.adapter.ts
1675
+ const DIRECTORY_MODE = 448;
1676
+ const FILE_MODE = 384;
1677
+ const TEMPORARY_TTL_MS = 36e5;
1678
+ const write = (filePath, body, shouldOverwrite) => {
1679
+ try {
1680
+ writeFileSync(filePath, body, {
1681
+ flag: shouldOverwrite ? "w" : "wx",
1682
+ mode: FILE_MODE
1683
+ });
1684
+ chmodSync(filePath, FILE_MODE);
1685
+ } catch (error) {
1686
+ const code = typeof error === "object" && error !== null && Reflect.get(error, "code") === "EEXIST" ? "CONFLICT" : "INTERNAL";
1687
+ throw new CliError(code, code === "CONFLICT" ? `Refusing to replace ${filePath}.` : `Could not write ${filePath}.`, code === "CONFLICT" ? "Choose another --output path or pass --force deliberately." : "Create the parent directory and verify it is writable, then retry.");
1688
+ }
1689
+ };
1690
+ const createRenderFileAdapter = (configDirectory) => ({ write: (input) => {
1691
+ if (input.outputPath !== null) {
1692
+ const outputPath = path.resolve(input.outputPath);
1693
+ write(outputPath, input.body, input.overwrite);
1694
+ return {
1695
+ path: outputPath,
1696
+ temporary: false,
1697
+ deleteAfter: null
1698
+ };
1699
+ }
1700
+ const directory = path.join(configDirectory, "sensitive");
1701
+ mkdirSync(directory, {
1702
+ recursive: true,
1703
+ mode: DIRECTORY_MODE
1704
+ });
1705
+ chmodSync(directory, DIRECTORY_MODE);
1706
+ const outputPath = path.join(directory, `render-${globalThis.crypto.randomUUID()}.png`);
1707
+ write(outputPath, input.body, false);
1708
+ return {
1709
+ path: outputPath,
1710
+ temporary: true,
1711
+ deleteAfter: new Date(input.at.getTime() + TEMPORARY_TTL_MS)
1712
+ };
1713
+ } });
1714
+
1715
+ //#endregion
1716
+ //#region src/application/import-canvas-asset.composite.ts
1717
+ const ASSET_PROCEDURES = [
1718
+ "canvas.asset.reserve",
1719
+ "canvas.asset.complete",
1720
+ "canvas.document.get"
1721
+ ];
1722
+ const importFailure = (error, operation) => new CliError(error instanceof CliError ? error.code : "INTERNAL", error instanceof CliError ? error.message : "The asset import did not return a confirmed result.", error instanceof CliError ? error.remediation : "Read operation_status for this import or retry the same file and clientToken. No canvas placement was requested.", {
1723
+ ...error instanceof CliError && error.fields,
1724
+ operation: JSON.stringify(operation),
1725
+ outcome: "not_confirmed"
1726
+ });
1727
+ const assertIdentity = (asset, intent) => {
1728
+ if (asset.canvasId !== intent.canvasId || asset.clientToken !== intent.clientToken || asset.kind !== intent.kind || asset.contentType !== intent.contentType || asset.bytes !== intent.bytes || asset.sha256 !== intent.sha256) throw new CliError("INTERNAL", "The returned asset does not match this import intent.", "Check the API and CLI versions. Do not insert an unverified resource.");
1729
+ };
1730
+ const createImportCanvasAssetComposite = (remote, files) => ({ execute: async (input) => {
1731
+ const reference = parseCanvasReference(input.canvasRef);
1732
+ if (hasCanvasReferenceScope(reference)) {
1733
+ const held = getCanvasDocumentOutputSchema.parse(await remote.query(ASSET_PROCEDURES[2], { canvasId: reference.canvasId }));
1734
+ canvasReferenceNodeIds(reference, canvasReadableSceneDocumentSchema.parse(held.document));
1735
+ }
1736
+ const { body, ...file } = await files.read();
1737
+ const intent = reserveCanvasAssetInputSchema.parse({
1738
+ ...file,
1739
+ canvasId: reference.canvasId,
1740
+ clientToken: input.clientToken
1741
+ });
1742
+ const operation = {
1743
+ kind: "canvas-asset",
1744
+ canvasId: reference.canvasId,
1745
+ clientToken: input.clientToken
1746
+ };
1747
+ try {
1748
+ const reserved = reserveCanvasAssetOutputSchema.parse(await remote.mutate(ASSET_PROCEDURES[0], intent));
1749
+ assertIdentity(reserved, intent);
1750
+ if (reserved.upload !== null) await remote.upload({
1751
+ ...reserved.upload,
1752
+ body
1753
+ });
1754
+ const completed = canvasAssetUploadOutputSchema.parse(await remote.mutate(ASSET_PROCEDURES[1], {
1755
+ canvasId: reference.canvasId,
1756
+ clientToken: input.clientToken
1757
+ }));
1758
+ assertIdentity(completed, intent);
1759
+ if (completed.assetId !== reserved.assetId || completed.path !== reserved.path) throw new CliError("INTERNAL", "The completed asset identity changed.", "Read operation_status and do not place an unconfirmed resource.");
1760
+ return canvasAssetImportOutputSchema.parse({
1761
+ operation,
1762
+ resource: completed,
1763
+ placement: "not_requested"
1764
+ });
1765
+ } catch (error) {
1766
+ throw importFailure(error, operation);
1767
+ }
1768
+ } });
1769
+
1770
+ //#endregion
1771
+ //#region src/application/prototype-publication.use-case.ts
1772
+ const STATUS_TIMEOUT_MS = 15e3;
1773
+ const delay = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1774
+ const INITIAL_POLL_MS = 50;
1775
+ const MAX_POLL_MS = 1e3;
1776
+ const TERMINAL_STATES = /* @__PURE__ */ new Set([
1777
+ "ready",
1778
+ "failed",
1779
+ "abandoned"
1780
+ ]);
1781
+ const PUBLICATION_PROCEDURES = [
1782
+ "prototype.getArtifactCapabilities",
1783
+ "prototype.createArtifact",
1784
+ "prototype.submitArtifact",
1785
+ "prototype.getPublishStatus"
1786
+ ];
1787
+ const invalidResponse$1 = (operation) => new CliError("INTERNAL", `The API returned an invalid prototype ${operation} response.`, "Check the existing deployment status before retrying with the same publication token.");
1788
+ const reserveAndUpload = async (remote, input, artifact, reserved) => {
1789
+ const created = createPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLICATION_PROCEDURES[1], {
1790
+ canvasId: input.canvasId,
1791
+ ...input.prototypeId !== null && { prototypeId: input.prototypeId },
1792
+ clientToken: input.clientToken,
1793
+ nodeId: input.nodeId,
1794
+ ...input.targetMode !== void 0 && { targetMode: input.targetMode },
1795
+ ...input.canvasPageId !== void 0 && { canvasPageId: input.canvasPageId },
1796
+ title: input.title,
1797
+ entryPath: artifact.manifest.entryPath,
1798
+ artifact: artifact.identity,
1799
+ box: input.box
1800
+ }));
1801
+ if (!created.success) throw invalidResponse$1("artifact creation");
1802
+ reserved(created.data.deploymentId);
1803
+ if (created.data.state === "uploading") await remote.upload({
1804
+ url: created.data.upload.url,
1805
+ headers: created.data.upload.headers,
1806
+ body: artifact.open()
1807
+ });
1808
+ if (created.data.state === "uploading" || created.data.state === "queued") {
1809
+ const submitted = submitPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLICATION_PROCEDURES[2], {
1810
+ canvasId: input.canvasId,
1811
+ deploymentId: created.data.deploymentId
1812
+ }));
1813
+ if (!submitted.success || submitted.data.deploymentId !== created.data.deploymentId) throw invalidResponse$1("artifact submission");
1814
+ }
1815
+ return created.data;
1816
+ };
1817
+ const preparePrototypePublication = async (remote, artifacts, input, reserved) => {
1818
+ const capabilities = getPrototypeArtifactCapabilitiesOutputSchema.safeParse(await remote.query(PUBLICATION_PROCEDURES[0], {}));
1819
+ if (!capabilities.success) throw invalidResponse$1("capabilities");
1820
+ const artifact = await artifacts.package({
1821
+ entryPath: input.entryPath,
1822
+ limits: capabilities.data.limits
1823
+ });
1824
+ try {
1825
+ return await reserveAndUpload(remote, input, artifact, reserved);
1826
+ } finally {
1827
+ await artifact.dispose();
1828
+ }
1829
+ };
1830
+ const readPublication = async (remote, input, timeoutMs) => {
1831
+ const abort = new AbortController();
1832
+ const expired = Promise.withResolvers();
1833
+ const timer = setTimeout(() => {
1834
+ abort.abort();
1835
+ expired.reject(new CliError("INTERNAL", "The prototype status request timed out.", "Check this deployment again; keep its existing client token.", {
1836
+ reason: "STATUS_TIMEOUT",
1837
+ deploymentId: input.deploymentId
1838
+ }));
1839
+ }, timeoutMs);
1840
+ try {
1841
+ const response = await Promise.race([remote.query(PUBLICATION_PROCEDURES[3], input, { signal: abort.signal }), expired.promise]);
1842
+ const parsed = getPrototypePublishStatusOutputSchema.safeParse(response);
1843
+ if (!parsed.success || parsed.data.deploymentId !== input.deploymentId) throw invalidResponse$1("status");
1844
+ return parsed.data;
1845
+ } finally {
1846
+ clearTimeout(timer);
1847
+ }
1848
+ };
1849
+ const waitForPrototypePublication = async (remote, input, waitMs) => {
1850
+ const deadline = performance.now() + waitMs;
1851
+ let pollMs = INITIAL_POLL_MS;
1852
+ let status = await readPublication(remote, input, waitMs > 0 ? Math.min(STATUS_TIMEOUT_MS, waitMs) : STATUS_TIMEOUT_MS);
1853
+ while (!TERMINAL_STATES.has(status.state)) {
1854
+ const remainingMs = deadline - performance.now();
1855
+ if (remainingMs <= 0) return status;
1856
+ await delay(Math.min(pollMs, remainingMs));
1857
+ pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
1858
+ const timeLeft = deadline - performance.now();
1859
+ if (timeLeft <= 0) return status;
1860
+ try {
1861
+ status = await readPublication(remote, input, Math.min(STATUS_TIMEOUT_MS, timeLeft));
1862
+ } catch (error) {
1863
+ if (error instanceof CliError && error.fields?.["reason"] === "STATUS_TIMEOUT") return status;
1864
+ throw error;
1865
+ }
1866
+ }
1867
+ return status;
1868
+ };
1869
+
1870
+ //#endregion
1871
+ //#region src/application/prototype-publication-outcome.use-case.ts
1872
+ const SOURCE_FAILURES = [
1873
+ "BAD_ARTIFACT",
1874
+ "ARTIFACT_INTEGRITY",
1875
+ "FILE_INTEGRITY",
1876
+ "FILE_TOO_LARGE",
1877
+ "FILE_COUNT_",
1878
+ "MANIFEST_",
1879
+ "PATH_",
1880
+ "ENTRY_",
1881
+ "EXPANDED_",
1882
+ "ZIP_INVALID",
1883
+ "ZIP_ENCRYPTED",
1884
+ "ZIP_PATH_ENCODING",
1885
+ "ZIP_COMPRESSION",
1886
+ "ZIP_ENTRY_TYPE"
1887
+ ];
1888
+ const toPrototypePublicationFailure = (publication) => {
1889
+ const failure = publication.failure;
1890
+ const isBuildFailure = SOURCE_FAILURES.some((prefix) => failure.code.startsWith(prefix));
1891
+ return {
1892
+ isBuildFailure,
1893
+ nextAction: isBuildFailure ? "fix_build" : "retry_new_publication",
1894
+ failure: {
1895
+ code: failure.code,
1896
+ message: failure.message,
1897
+ remediation: isBuildFailure ? "Correct the named build problem and publish a new artifact with a new clientToken." : "This ingestion attempt is terminal. Restore storage or service access, then explicitly publish the same valid build with a new clientToken. Do not change the source to repair a service failure."
1898
+ }
1899
+ };
1900
+ };
1901
+ const prototypePublicationWarnings = (publication) => publication.unavailableFiles?.map((file) => `Unavailable published file: ${file.path} (${file.code}).`) ?? [];
1902
+
1903
+ //#endregion
1904
+ //#region src/application/publish-canvas-prototype.composite.ts
1905
+ const PROCEDURES = ["prototype.getArtifactCapabilities", "prototype.attach"];
1906
+ const REJECTED_CODES = /* @__PURE__ */ new Set([
1907
+ "BAD_REQUEST",
1908
+ "FORBIDDEN",
1909
+ "UNAUTHORIZED",
1910
+ "NOT_FOUND"
1911
+ ]);
1912
+ const requireScopedAttachment = async (remote) => {
1913
+ const capabilities = getPrototypeArtifactCapabilitiesOutputSchema.safeParse(await remote.query(PROCEDURES[0], {}));
1914
+ if (!capabilities.success || capabilities.data.attachmentProtocolVersion !== 1) throw new CliError("BAD_REQUEST", "This API does not advertise revision-checked prototype attachment.", "Upgrade the API before publishing through the canvas profile. No artifact was created or attached.");
1915
+ };
1916
+ const failureOf$1 = (error) => error instanceof CliError ? {
1917
+ code: error.code,
1918
+ message: error.message,
1919
+ remediation: error.remediation
1920
+ } : {
1921
+ code: "INTERNAL",
1922
+ message: "The publication request did not return a confirmed outcome.",
1923
+ remediation: "Retry the identical request with its original clientToken; do not assume the canvas is unchanged."
1924
+ };
1925
+ const attach = async (remote, input, publication) => {
1926
+ const reference = parseCanvasReference(input.canvasRef);
1927
+ const parsed = attachPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PROCEDURES[1], {
1928
+ canvasId: reference.canvasId,
1929
+ deploymentId: publication.deploymentId,
1930
+ baseVersion: input.baseVersion,
1931
+ ...reference.pageId !== void 0 && { canvasPageId: reference.pageId },
1932
+ attachment: {
1933
+ clientToken: input.clientToken,
1934
+ scope: {
1935
+ ...reference.pageId !== void 0 && { pageId: reference.pageId },
1936
+ nodeIds: reference.nodeIds
1937
+ }
1938
+ }
1939
+ }));
1940
+ if (!parsed.success) throw new Error("Invalid prototype attachment response");
1941
+ const result = parsed.data;
1942
+ const receipt = result.attachment;
1943
+ if (receipt === void 0 || result.canvasId !== reference.canvasId || result.deploymentId !== publication.deploymentId || result.prototypeId !== publication.prototypeId || result.nodeId !== publication.nodeId || result.version !== receipt.version || receipt.outcome === "committed" && (receipt.mutationId !== input.clientToken || receipt.version !== receipt.previousVersion + 1) || receipt.outcome === "no_op" && receipt.version !== input.baseVersion) throw new Error("Unconfirmed prototype attachment receipt");
1944
+ return {
1945
+ ...result,
1946
+ attachment: receipt
1947
+ };
1948
+ };
1949
+ const attachReady = async (remote, input, base, publication) => {
1950
+ try {
1951
+ const attachment = await attach(remote, input, publication);
1952
+ return {
1953
+ ...base,
1954
+ attachmentStatus: attachment.attachment.outcome,
1955
+ attachment,
1956
+ nextAction: "inspect_result"
1957
+ };
1958
+ } catch (error) {
1959
+ const failure = failureOf$1(error);
1960
+ const isConflict = failure.code === "CONFLICT";
1961
+ const isRejected = REJECTED_CODES.has(failure.code);
1962
+ return {
1963
+ ...base,
1964
+ attachmentStatus: isConflict ? "conflict" : isRejected ? "not_attempted" : "not_confirmed",
1965
+ failure,
1966
+ nextAction: failure.code === "UNAUTHORIZED" || failure.code === "FORBIDDEN" ? "restore_access" : isConflict || isRejected ? "replan_attachment" : "retry_same_request",
1967
+ warnings: [...base.warnings, "The ready deployment is reusable. A status read never attaches it. Retry uncertainty with the original attachment intent; refresh baseVersion after an unrelated canvas edit and keep the same clientToken. A changed scope or destination requires a new attachment intent."]
1968
+ };
1969
+ }
1970
+ };
1971
+ const finishPublication = async (remote, input, canvasId, publication) => {
1972
+ const base = {
1973
+ operation: {
1974
+ kind: "prototype-deployment",
1975
+ canvasId,
1976
+ deploymentId: publication.deploymentId
1977
+ },
1978
+ deploymentStatus: publication.state,
1979
+ publication,
1980
+ attachmentStatus: "pending",
1981
+ attachment: null,
1982
+ failure: null,
1983
+ nextAction: "check_status",
1984
+ warnings: prototypePublicationWarnings(publication)
1985
+ };
1986
+ if (publication.state === "failed") {
1987
+ const { nextAction, failure } = toPrototypePublicationFailure(publication);
1988
+ return {
1989
+ ...base,
1990
+ attachmentStatus: "not_attempted",
1991
+ nextAction,
1992
+ failure
1993
+ };
1994
+ }
1995
+ if (publication.state === "abandoned") return {
1996
+ ...base,
1997
+ attachmentStatus: "not_attempted",
1998
+ nextAction: "retry_new_publication",
1999
+ failure: {
2000
+ code: "NOT_FOUND",
2001
+ message: "The deployment was abandoned.",
2002
+ remediation: "Publish the same build explicitly with a new clientToken if it is still needed."
2003
+ }
2004
+ };
2005
+ if (publication.state !== "ready") return base;
2006
+ return attachReady(remote, input, base, publication);
2007
+ };
2008
+ const createPublishCanvasPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => {
2009
+ const reference = parseCanvasReference(input.canvasRef);
2010
+ await requireScopedAttachment(remote);
2011
+ let deploymentId = input.source.kind === "deployment" ? input.source.deploymentId : null;
2012
+ try {
2013
+ if (input.source.kind === "build") deploymentId = (await preparePrototypePublication(remote, artifacts, {
2014
+ ...input.source,
2015
+ canvasId: reference.canvasId,
2016
+ ...reference.pageId !== void 0 && { canvasPageId: reference.pageId },
2017
+ clientToken: input.clientToken
2018
+ }, (reservedId) => {
2019
+ deploymentId = reservedId;
2020
+ })).deploymentId;
2021
+ if (deploymentId === null) throw new Error("Publication has no deployment");
2022
+ const publication = await waitForPrototypePublication(remote, {
2023
+ canvasId: reference.canvasId,
2024
+ deploymentId
2025
+ }, input.waitMs);
2026
+ return await finishPublication(remote, input, reference.canvasId, publication);
2027
+ } catch (error) {
2028
+ if (deploymentId === null) throw error;
2029
+ return {
2030
+ operation: {
2031
+ kind: "prototype-deployment",
2032
+ canvasId: reference.canvasId,
2033
+ deploymentId
2034
+ },
2035
+ deploymentStatus: "unknown",
2036
+ publication: null,
2037
+ attachmentStatus: "not_attempted",
2038
+ attachment: null,
2039
+ failure: failureOf$1(error),
2040
+ nextAction: error instanceof CliError && (error.code === "UNAUTHORIZED" || error.code === "FORBIDDEN") ? "restore_access" : "retry_same_request",
2041
+ warnings: ["An existing deployment may still be processing. Retry the same source and clientToken to recover or finish upload; do not reserve a new publication."]
2042
+ };
2043
+ }
2044
+ } });
2045
+
2046
+ //#endregion
2047
+ //#region src/application/publish-prototype.composite.ts
2048
+ const PUBLISH_WAIT_MS = 3e5;
2049
+ const PUBLISH_PROTOTYPE_PROCEDURES = ["prototype.attach"];
2050
+ const invalidResponse = (operation) => new CliError("INTERNAL", `The API returned an invalid prototype ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
2051
+ const requireReadyPublication = (status) => {
2052
+ if (status.state === "failed") {
2053
+ const failure = toPrototypePublicationFailure(status);
2054
+ throw new CliError(failure.isBuildFailure ? "BAD_REQUEST" : "INTERNAL", failure.failure.message, failure.failure.remediation, {
2055
+ reason: failure.failure.code,
2056
+ deploymentId: status.deploymentId,
2057
+ nextAction: failure.nextAction,
2058
+ ...status.failure.path !== void 0 && { path: status.failure.path }
2059
+ });
2060
+ }
2061
+ if (status.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${status.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
2062
+ if (status.state !== "ready") throw new CliError("INTERNAL", "Prototype ingestion is still processing.", "Check this deployment status, then resume the same source and client token; do not reserve a second publication.", {
2063
+ reason: "INGESTION_PENDING",
2064
+ state: status.state,
2065
+ processedFiles: String(status.processedFiles),
2066
+ deploymentId: status.deploymentId
2067
+ });
2068
+ };
2069
+ const executePublish = async (remote, artifacts, input) => {
2070
+ const progress = { deploymentId: null };
2071
+ try {
2072
+ const created = await preparePrototypePublication(remote, artifacts, input, (reservedId) => {
2073
+ progress.deploymentId = reservedId;
2074
+ });
2075
+ const status = await waitForPrototypePublication(remote, {
2076
+ canvasId: input.canvasId,
2077
+ deploymentId: created.deploymentId
2078
+ }, PUBLISH_WAIT_MS);
2079
+ requireReadyPublication(status);
2080
+ const attached = attachPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[0], {
2081
+ canvasId: input.canvasId,
2082
+ deploymentId: created.deploymentId,
2083
+ baseVersion: input.baseVersion
2084
+ }));
2085
+ if (!attached.success) throw invalidResponse("attachment");
2086
+ return {
2087
+ ...attached.data,
2088
+ fileCount: status.fileCount,
2089
+ totalBytes: status.totalBytes,
2090
+ alreadyExists: created.alreadyExists,
2091
+ warnings: prototypePublicationWarnings(status),
2092
+ next: [attached.data.canvasUrl ?? attached.data.openUrl, `enhance canvas render --canvas ${input.canvasId} --node-id ${attached.data.nodeId} --expected-version ${String(attached.data.version)}`]
2093
+ };
2094
+ } catch (error) {
2095
+ if (error instanceof CliError && (error.code === "BAD_REQUEST" || error.code === "NOT_FOUND")) throw error;
2096
+ if (progress.deploymentId === null) throw error;
2097
+ throw new PartialBatchError(error instanceof CliError ? error.message : `Prototype deployment ${progress.deploymentId} has no confirmed completion.`, `${error instanceof CliError ? `${error.remediation} ` : ""}Retry 'enhance prototype publish' with the same --client-token ${input.clientToken}.`, {
2098
+ code: error instanceof CliError ? error.code : "INTERNAL",
2099
+ fields: {
2100
+ ...error instanceof CliError && error.fields,
2101
+ canvasId: input.canvasId,
2102
+ deploymentId: progress.deploymentId,
2103
+ clientToken: input.clientToken
2104
+ }
2105
+ });
2106
+ }
2107
+ };
2108
+ const createPublishPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => executePublish(remote, artifacts, input) });
2109
+
2110
+ //#endregion
2111
+ //#region src/application/canvas-preparation-status.use-case.ts
2112
+ const canvasPreparationStatus = (job, operation) => {
2113
+ if (job.id !== operation.jobId || job.canvasId !== operation.canvasId) throw new CliError("NOT_FOUND", "The preparation does not belong to this operation.", "Use the complete operation reference returned by the original action.");
2114
+ return {
2115
+ kind: "canvas-preparation",
2116
+ operation,
2117
+ state: job.state,
2118
+ phase: job.phase,
2119
+ requestedVersion: job.requestedVersion,
2120
+ failure: job.failure,
2121
+ outcome: "not_confirmed",
2122
+ prepared: job.state === "succeeded",
2123
+ warnings: ["Preparation is not a canvas commit. Repeat the original tool with identical arguments and clientToken to finish; status reads never commit."]
2124
+ };
2125
+ };
2126
+ const readCanvasPreparationStatus = async (remote, operation) => {
2127
+ const { job } = getCanvasPreparationOutputSchema.parse(await remote.query("canvas.render.preparation.get", { jobId: operation.jobId }));
2128
+ return canvasPreparationStatus(job, operation);
2129
+ };
2130
+
2131
+ //#endregion
2132
+ //#region src/application/canvas-receipt.use-case.ts
2133
+ const MAX_RECEIPT_NODE_IDS = 40;
2134
+ const canvasWriteReceipt = (commit, fingerprint) => {
2135
+ let remaining = MAX_RECEIPT_NODE_IDS;
2136
+ const take = (ids) => {
2137
+ const selected = ids.slice(0, remaining);
2138
+ remaining -= selected.length;
2139
+ return selected;
2140
+ };
2141
+ const insertedNodeIds = take(commit.insertedNodeIds);
2142
+ const changedNodeIds = take(commit.changedNodeIds);
2143
+ const removedNodeIds = take(commit.removedNodeIds);
2144
+ const total = commit.insertedNodeIds.length + commit.changedNodeIds.length + commit.removedNodeIds.length;
2145
+ return {
2146
+ outcome: "committed",
2147
+ canvasId: commit.canvasId,
2148
+ mutationId: commit.mutationId,
2149
+ previousVersion: commit.previousVersion,
2150
+ version: commit.version,
2151
+ operation: {
2152
+ kind: "canvas-mutation",
2153
+ canvasId: commit.canvasId,
2154
+ mutationId: commit.mutationId,
2155
+ fingerprint
2156
+ },
2157
+ affected: {
2158
+ insertedNodeIds,
2159
+ changedNodeIds,
2160
+ removedNodeIds,
2161
+ complete: total <= MAX_RECEIPT_NODE_IDS,
2162
+ total
2163
+ },
2164
+ ...commit.copiedNodeIds !== void 0 && { identities: {
2165
+ entries: Object.entries(commit.copiedNodeIds).toSorted(([left], [right]) => left.localeCompare(right, "en")).slice(0, MAX_RECEIPT_NODE_IDS).map(([sourceNodeId, nodeId]) => ({
2166
+ sourceNodeId,
2167
+ nodeId
2168
+ })),
2169
+ complete: Object.keys(commit.copiedNodeIds).length <= MAX_RECEIPT_NODE_IDS,
2170
+ total: Object.keys(commit.copiedNodeIds).length
2171
+ } },
2172
+ verification: { rendered: false },
2173
+ warnings: []
2174
+ };
2175
+ };
2176
+
2177
+ //#endregion
2178
+ //#region src/application/operation-image.use-case.ts
2179
+ const deliverOperationImage = async (remote, files, status) => {
2180
+ if (status.kind !== "canvas-render" || status.state !== "succeeded") return status;
2181
+ try {
2182
+ const { job } = getCanvasRenderOutputSchema.parse(await remote.query("canvas.render.get", { jobId: status.operation.jobId }));
2183
+ if (job.id !== status.operation.jobId || job.canvasId !== status.operation.canvasId || job.state !== "succeeded") return {
2184
+ ...status,
2185
+ warnings: ["The stored result is unavailable for image delivery. Read this operation again."]
2186
+ };
2187
+ return {
2188
+ status,
2189
+ localImage: await writeRenderArtifact(remote, files, job, {
2190
+ at: /* @__PURE__ */ new Date(),
2191
+ outputPath: null,
2192
+ overwrite: false
2193
+ })
2194
+ };
2195
+ } catch {
2196
+ return {
2197
+ ...status,
2198
+ warnings: ["The render completed, but its image could not be delivered. Check access and artifact expiry before retrying this operation reference."]
2199
+ };
2200
+ }
2201
+ };
2202
+
2203
+ //#endregion
2204
+ //#region src/application/read-operation-status.composite.ts
2205
+ const STATUS_PROCEDURES = [
2206
+ "canvas.mutation.get",
2207
+ "canvas.render.get",
2208
+ "canvas.render.getImport",
2209
+ "prototype.getPublishStatus",
2210
+ "canvas.asset.get"
2211
+ ];
2212
+ const assertCanvas = (actual, expected) => {
2213
+ if (actual !== expected) throw new CliError("NOT_FOUND", "The operation does not belong to this canvas.", "Use the operation reference returned by the original action.");
2214
+ };
2215
+ const affectedEntries = (commit) => [
2216
+ ...commit.insertedNodeIds.map((nodeId) => ({
2217
+ nodeId,
2218
+ change: "inserted"
2219
+ })),
2220
+ ...commit.changedNodeIds.map((nodeId) => ({
2221
+ nodeId,
2222
+ change: "changed"
2223
+ })),
2224
+ ...commit.removedNodeIds.map((nodeId) => ({
2225
+ nodeId,
2226
+ change: "removed"
2227
+ })),
2228
+ ...Object.entries(commit.copiedNodeIds ?? {}).toSorted(([left], [right]) => left.localeCompare(right, "en")).map(([sourceNodeId, nodeId]) => ({
2229
+ nodeId,
2230
+ sourceNodeId,
2231
+ change: "copied"
2232
+ }))
2233
+ ];
2234
+ const mutationStatus = async (remote, input) => {
2235
+ const { operation, offset, limit } = input;
2236
+ const found = getCanvasMutationOutputSchema.parse(await remote.query(STATUS_PROCEDURES[0], {
2237
+ canvasId: operation.canvasId,
2238
+ mutationId: operation.mutationId,
2239
+ fingerprint: operation.fingerprint
2240
+ }));
2241
+ return found.state === "not-found" ? {
2242
+ kind: "canvas-mutation",
2243
+ state: "not_found",
2244
+ operation,
2245
+ outcome: "unknown",
2246
+ warnings: ["No durable receipt was found. The original request may still be running."]
2247
+ } : {
2248
+ kind: "canvas-mutation",
2249
+ state: "committed",
2250
+ receipt: canvasWriteReceipt(found.result, operation.fingerprint),
2251
+ affected: boundedResultPage(affectedEntries(found.result), offset, limit)
2252
+ };
2253
+ };
2254
+ const renderStatus = async (remote, input) => {
2255
+ const { operation, offset, limit } = input;
2256
+ const { job } = getCanvasRenderOutputSchema.parse(await remote.query(STATUS_PROCEDURES[1], { jobId: operation.jobId }));
2257
+ assertCanvas(job.canvasId, operation.canvasId);
2258
+ const evidence = job.result === null ? null : renderEvidence(job.result);
2259
+ return {
2260
+ kind: "canvas-render",
2261
+ operation,
2262
+ state: job.state,
2263
+ phase: job.phase,
2264
+ requestedVersion: job.requestedVersion,
2265
+ attempt: job.attempt,
2266
+ target: job.target,
2267
+ sourceState: job.sourceState ?? null,
2268
+ evidence,
2269
+ details: boundedResultPage(renderEntries(job), offset, limit),
2270
+ failure: job.failure,
2271
+ pixelsDelivered: false,
2272
+ warnings: ["Status reports stored render evidence. It does not deliver or inspect the image."]
2273
+ };
2274
+ };
2275
+ const renderEvidence = (result) => {
2276
+ const { warnings, timings, ...evidence } = result;
2277
+ return {
2278
+ ...evidence,
2279
+ warningCount: warnings.length,
2280
+ timingCount: timings.length
2281
+ };
2282
+ };
2283
+ const renderEntries = (job) => job.result === null ? [] : [...job.result.warnings.map((warning) => ({
2284
+ kind: "warning",
2285
+ warning
2286
+ })), ...job.result.timings.map((timing) => ({
2287
+ kind: "timing",
2288
+ timing
2289
+ }))];
2290
+ const assetStatus = async (remote, operation) => {
2291
+ const resource = canvasAssetUploadOutputSchema.parse(await remote.query(STATUS_PROCEDURES[4], {
2292
+ canvasId: operation.canvasId,
2293
+ clientToken: operation.clientToken
2294
+ }));
2295
+ assertCanvas(resource.canvasId, operation.canvasId);
2296
+ if (resource.clientToken !== operation.clientToken) throw new CliError("NOT_FOUND", "The resource does not belong to this import.", "Use the operation reference returned by the original import.");
2297
+ return {
2298
+ kind: "canvas-asset",
2299
+ operation,
2300
+ resource,
2301
+ placement: "not_checked"
2302
+ };
2303
+ };
2304
+ const readStatus = async (remote, input) => {
2305
+ const { operation, offset, limit } = input;
2306
+ switch (operation.kind) {
2307
+ case "canvas-asset":
2308
+ boundedResultPage([], offset, limit);
2309
+ return assetStatus(remote, operation);
2310
+ case "canvas-mutation": return mutationStatus(remote, {
2311
+ ...input,
2312
+ operation
2313
+ });
2314
+ case "canvas-preparation": {
2315
+ const mutation = await mutationStatus(remote, {
2316
+ ...input,
2317
+ operation: {
2318
+ kind: "canvas-mutation",
2319
+ canvasId: operation.canvasId,
2320
+ mutationId: operation.mutationId,
2321
+ fingerprint: operation.fingerprint
2322
+ }
2323
+ });
2324
+ return mutation.kind === "canvas-mutation" && mutation.state === "committed" ? mutation : readCanvasPreparationStatus(remote, operation);
2325
+ }
2326
+ case "canvas-render": return renderStatus(remote, {
2327
+ ...input,
2328
+ operation
2329
+ });
2330
+ case "canvas-conversion": {
2331
+ const { job } = getCanvasConversionOutputSchema.parse(await remote.query(STATUS_PROCEDURES[2], { jobId: operation.jobId }));
2332
+ assertCanvas(job.canvasId, operation.canvasId);
2333
+ return canvasConversionStatus(job, {
2334
+ offset,
2335
+ limit
2336
+ });
2337
+ }
2338
+ case "prototype-deployment":
2339
+ boundedResultPage([], offset, limit);
2340
+ return {
2341
+ kind: "prototype-deployment",
2342
+ operation,
2343
+ publication: getPrototypePublishStatusOutputSchema.parse(await remote.query(STATUS_PROCEDURES[3], {
2344
+ canvasId: operation.canvasId,
2345
+ deploymentId: operation.deploymentId
2346
+ })),
2347
+ attachment: "not_checked",
2348
+ warnings: ["Publication readiness does not establish canvas attachment or successful interactive verification."]
2349
+ };
2350
+ }
2351
+ };
2352
+ const createReadOperationStatusComposite = (remote, files) => ({ execute: async (input) => {
2353
+ const status = await readStatus(remote, input);
2354
+ return files !== void 0 && input.includeImage ? deliverOperationImage(remote, files, status) : status;
2355
+ } });
2356
+
2357
+ //#endregion
2358
+ //#region src/application/read-transcript.composite.ts
2359
+ const MAX_PREVIEW_COMMANDS = 3;
2360
+ const READ_TRANSCRIPT_PROCEDURES = ["transcript.get"];
2361
+ const previewCommands = (canvasId, recordingId, cueTimes) => [...new Set(cueTimes)].slice(0, MAX_PREVIEW_COMMANDS).map((atMs) => `enhance canvas render --canvas ${canvasId} --node-id rec_${recordingId} --at-ms ${String(atMs)}`);
2362
+ const createReadTranscriptComposite = (remote) => ({ execute: async (input) => {
2363
+ const parsed = transcriptOutputSchema.safeParse(await remote.query(READ_TRANSCRIPT_PROCEDURES[0], input));
2364
+ if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid transcript response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
2365
+ if (parsed.data.state !== "ready") return parsed.data;
2366
+ return {
2367
+ ...parsed.data,
2368
+ guidance: "Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.",
2369
+ next: previewCommands(input.canvasId, input.recordingId, parsed.data.cues.map((cue) => cue.startMs))
2370
+ };
2371
+ } });
2372
+
2373
+ //#endregion
2374
+ //#region src/application/snapshot-recording.composite.ts
2375
+ const POLL_MS$1 = 250;
2376
+ const PROGRESS_HEARTBEAT_MS = 5e3;
2377
+ const SNAPSHOT_RECORDING_PROCEDURES = ["canvas.render.get", "canvas.render.snapshot"];
2378
+ const wait = async () => new Promise((resolve) => {
2379
+ globalThis.setTimeout(resolve, POLL_MS$1);
2380
+ });
2381
+ const failureOf = (job) => new CliError(job.failure?.reason === "VERSION_CHANGED" ? "CONFLICT" : job.failure?.reason === "TARGET_NOT_FOUND" ? "NOT_FOUND" : job.failure?.reason === "TARGET_INVALID" || job.failure?.reason === "OUTPUT_TOO_LARGE" ? "BAD_REQUEST" : "INTERNAL", job.failure?.message ?? "The snapshot job ended without a result.", `Run 'enhance canvas tree --canvas ${job.canvasId}' and retry the exact snapshot if its recording node still exists.`, {
2382
+ jobId: job.id,
2383
+ phase: job.phase
2384
+ });
2385
+ const readSnapshotJob = async (remote, jobId) => {
2386
+ const read = getCanvasRenderOutputSchema.safeParse(await remote.query(SNAPSHOT_RECORDING_PROCEDURES[0], { jobId }));
2387
+ if (!read.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot status response.", `Run \`enhance doctor\` and report snapshot job ${jobId}.`);
2388
+ return read.data.job;
2389
+ };
2390
+ const awaitSnapshot = async (remote, initial, input, progress) => {
2391
+ const deadline = Date.now() + input.timeoutMs;
2392
+ const startedAt = Date.now();
2393
+ let job = initial;
2394
+ let lastReportedAt = 0;
2395
+ let lastReportedState = "";
2396
+ while (job.state === "queued" || job.state === "running") {
2397
+ const currentTime = Date.now();
2398
+ const stateKey = `${job.state}:${job.phase}`;
2399
+ if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS) {
2400
+ progress({
2401
+ event: "snapshot.progress",
2402
+ jobId: job.id,
2403
+ state: job.state,
2404
+ phase: job.phase,
2405
+ elapsedMs: currentTime - startedAt,
2406
+ timeoutMs: input.timeoutMs,
2407
+ retryClientToken: input.retryClientToken
2408
+ });
2409
+ lastReportedAt = currentTime;
2410
+ lastReportedState = stateKey;
2411
+ }
2412
+ if (currentTime >= deadline) {
2413
+ if (input.bounded === true) return job;
2414
+ throw new CliError("INTERNAL", `Snapshot ${job.id} did not finish before the local timeout.`, `Retry this exact command with --client-token ${input.retryClientToken} and a larger --timeout-ms.`, {
2415
+ jobId: job.id,
2416
+ phase: job.phase
2417
+ });
2418
+ }
2419
+ await wait();
2420
+ const next = await readSnapshotJob(remote, job.id);
2421
+ if (next.id !== initial.id) throw invalidSnapshot();
2422
+ assertSnapshotIdentity(next, input);
2423
+ job = next;
2424
+ }
2425
+ return job;
2426
+ };
2427
+ const invalidSnapshot = () => new CliError("INTERNAL", "The snapshot response does not match the requested source or revision.", "Run enhance doctor and report the capture job ID.");
2428
+ const assertSnapshotIdentity = (job, input) => {
2429
+ if (job.canvasId !== input.canvasId || job.purpose !== "snapshot" || job.sourceState?.recordingId !== input.recordingId || job.sourceState.atMs !== input.atMs || input.context !== void 0 && job.requestedVersion !== input.context.expectedVersion) throw invalidSnapshot();
2430
+ if (job.state !== "succeeded") return;
2431
+ const result = job.result.snapshot;
2432
+ const source = job.result.sourceState;
2433
+ if (job.result.canvasId !== input.canvasId || job.result.loadedVersion !== job.requestedVersion || job.result.requestedVersion !== job.requestedVersion || source?.recordingId !== input.recordingId || source.requestedAtMs !== input.atMs || source.settledAtMs !== input.atMs || result?.recordingId !== input.recordingId || result.atMs !== input.atMs || result.screenId !== job.id || result.screenNodeId !== `scr_${input.recordingId}_${String(input.atMs)}` || input.context !== void 0 && result.version !== input.context.expectedVersion + 1) throw invalidSnapshot();
2434
+ };
2435
+ const captureReceipt = (job, input) => ({
2436
+ operation: {
2437
+ kind: "canvas-render",
2438
+ canvasId: job.canvasId,
2439
+ jobId: job.id
2440
+ },
2441
+ state: job.state,
2442
+ requestedVersion: job.requestedVersion,
2443
+ source: {
2444
+ kind: "recording",
2445
+ recordingId: input.recordingId,
2446
+ atMs: input.atMs
2447
+ },
2448
+ attachment: job.state === "succeeded" ? "committed" : job.state === "queued" || job.state === "running" ? "pending" : "not_confirmed",
2449
+ result: job.result?.snapshot ?? null,
2450
+ failure: job.failure,
2451
+ warningCount: job.result?.warnings.length ?? 0,
2452
+ warnings: [job.state === "succeeded" ? "The durable screen is attached. Render the returned node at its committed version to verify placement; use operation_status for source warnings." : "Follow operation_status for this job. An incomplete job is not proof of attachment or proof that no durable screen was created."]
2453
+ });
2454
+ const captureCanvasRecording = async (remote, offered, clientToken) => {
2455
+ const input = canvasCaptureCapabilityInputSchema.parse(offered);
2456
+ const reference = parseCanvasReference(input.canvasRef);
2457
+ return createSnapshotRecordingComposite(remote, () => null).execute({
2458
+ canvasId: reference.canvasId,
2459
+ recordingId: input.source.recordingId,
2460
+ atMs: input.source.atMs,
2461
+ retryClientToken: clientToken,
2462
+ timeoutMs: input.waitMs,
2463
+ bounded: true,
2464
+ context: {
2465
+ expectedVersion: input.baseVersion,
2466
+ request: {
2467
+ previewJobId: input.previewJobId,
2468
+ scope: {
2469
+ pageId: reference.pageId,
2470
+ nodeIds: [...reference.nodeIds]
2471
+ },
2472
+ placement: input.placement
2473
+ }
2474
+ }
2475
+ });
2476
+ };
2477
+ const executeSnapshot = async (remote, progress, input) => {
2478
+ const made = createRecordingSnapshotOutputSchema.safeParse(await remote.mutate(SNAPSHOT_RECORDING_PROCEDURES[1], {
2479
+ canvasId: input.canvasId,
2480
+ recordingId: input.recordingId,
2481
+ atMs: input.atMs,
2482
+ ...input.context !== void 0 && { context: input.context }
2483
+ }));
2484
+ if (!made.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot creation response.", "Run `enhance doctor` and report the API and CLI versions.");
2485
+ assertSnapshotIdentity(made.data.job, input);
2486
+ const held = await awaitSnapshot(remote, made.data.job, input, progress);
2487
+ if (input.bounded === true) return captureReceipt(held, input);
2488
+ if (held.state !== "succeeded" || held.result.snapshot === void 0) throw failureOf(held);
2489
+ const job = {
2490
+ ...held,
2491
+ result: {
2492
+ ...held.result,
2493
+ snapshot: held.result.snapshot
2494
+ }
2495
+ };
2496
+ const snapshot = job.result.snapshot;
2497
+ return {
2498
+ jobId: job.id,
2499
+ canvasId: job.canvasId,
2500
+ ...snapshot,
2501
+ warnings: job.result.warnings,
2502
+ retryClientToken: input.retryClientToken,
2503
+ next: [`enhance canvas node --canvas ${job.canvasId} --node-id ${snapshot.screenNodeId}`, `enhance canvas render --canvas ${job.canvasId} --node-id ${snapshot.screenNodeId} --expected-version ${String(snapshot.version)}`]
2504
+ };
2505
+ };
2506
+ const createSnapshotRecordingComposite = (remote, progress) => ({ execute: async (input) => executeSnapshot(remote, progress, input) });
2507
+
2508
+ //#endregion
2509
+ //#region src/infrastructure/canvas-asset-file.adapter.ts
2510
+ const CONTENT_TYPES$1 = {
2511
+ ".avif": "image/avif",
2512
+ ".gif": "image/gif",
2513
+ ".jpeg": "image/jpeg",
2514
+ ".jpg": "image/jpeg",
2515
+ ".png": "image/png",
2516
+ ".webp": "image/webp",
2517
+ ".ttf": "font/ttf",
2518
+ ".otf": "font/otf",
2519
+ ".woff": "font/woff",
2520
+ ".woff2": "font/woff2"
2521
+ };
2522
+ const badFile = () => new CliError("BAD_REQUEST", "Choose one supported regular image or font file.", "Use an explicit local PNG, JPEG, GIF, WebP, AVIF, TTF, OTF, WOFF or WOFF2 file.");
2523
+ const readFile$1 = async (filePath) => {
2524
+ const contentType = CONTENT_TYPES$1[path.extname(filePath).toLowerCase()];
2525
+ if (contentType === void 0) throw badFile();
2526
+ const file = await open(filePath, constants.O_RDONLY | constants.O_NONBLOCK);
2527
+ try {
2528
+ const stats = await file.stat();
2529
+ if (!stats.isFile() || stats.size === 0) throw badFile();
2530
+ const buffer = Buffer.alloc(stats.size + 1);
2531
+ let bytes = 0;
2532
+ while (bytes < buffer.byteLength) {
2533
+ const read = await file.read(buffer, bytes, buffer.byteLength - bytes, bytes);
2534
+ if (read.bytesRead === 0) break;
2535
+ bytes += read.bytesRead;
2536
+ }
2537
+ if (bytes !== stats.size) throw new CliError("CONFLICT", "The selected asset changed while it was being read.", "Finish writing the file, then retry the unchanged import intent.");
2538
+ const body = buffer.subarray(0, bytes);
2539
+ return {
2540
+ body,
2541
+ kind: contentType.startsWith("image/") ? "image" : "font",
2542
+ contentType,
2543
+ bytes,
2544
+ sha256: createHash("sha256").update(body).digest("hex")
2545
+ };
2546
+ } finally {
2547
+ await file.close();
2548
+ }
2549
+ };
2550
+ const createCanvasAssetFileAdapter = (filePath) => ({ read: async () => {
2551
+ try {
2552
+ return await readFile$1(filePath);
2553
+ } catch (error) {
2554
+ if (error instanceof CliError) throw error;
2555
+ throw new CliError("BAD_REQUEST", "The selected asset file cannot be read.", "Choose an existing readable image or font file on this computer.");
2556
+ }
2557
+ } });
2558
+
2559
+ //#endregion
2560
+ //#region src/application/find-canvas.composite.ts
2561
+ const MAX_PAGE_BYTES = 48e3;
2562
+ const DISCOVERY_PROCEDURES = ["canvas.list", "organisation.list"];
2563
+ const readItems = async (remote, input) => {
2564
+ const [canvasValue, teamValue] = await Promise.all([remote.query(DISCOVERY_PROCEDURES[0], {
2565
+ collection: input.collection,
2566
+ ...input.title !== void 0 && { title: input.title },
2567
+ scope: "all",
2568
+ deleted: false,
2569
+ hasUnresolved: false
2570
+ }), input.includeDestinations ? remote.query(DISCOVERY_PROCEDURES[1], {}) : {
2571
+ items: [],
2572
+ truncated: false
2573
+ }]);
2574
+ const canvases = listCanvasesOutputSchema.parse(canvasValue);
2575
+ const teams = listOrganisationsOutputSchema.parse(teamValue);
2576
+ const items = canvases.items.map((canvas) => ({
2577
+ kind: "canvas",
2578
+ canvasRef: canvas.id,
2579
+ title: canvas.title,
2580
+ organisationId: canvas.organisationId,
2581
+ accessState: canvas.accessState,
2582
+ viewerCan: canvas.viewerCan,
2583
+ openPath: `/c/${canvas.id}`
2584
+ }));
2585
+ if (input.includeDestinations) items.push({
2586
+ kind: "destination",
2587
+ destination: { kind: "personal" },
2588
+ name: "Personal"
2589
+ }, ...teams.items.filter((team) => input.collection === "everything" || input.collection === team.id).map((team) => ({
2590
+ kind: "destination",
2591
+ destination: {
2592
+ kind: "team",
2593
+ organisationId: team.id
2594
+ },
2595
+ name: team.name
2596
+ })));
2597
+ return {
2598
+ items,
2599
+ sourceTruncated: {
2600
+ canvases: canvases.truncated,
2601
+ destinations: teams.truncated
2602
+ }
2603
+ };
2604
+ };
2605
+ const boundedItems = (items) => {
2606
+ const selected = [];
2607
+ let bytes = 2;
2608
+ for (const entry of items) {
2609
+ const size = Buffer.byteLength(JSON.stringify(entry)) + 1;
2610
+ if (bytes + size > MAX_PAGE_BYTES) break;
2611
+ selected.push(entry);
2612
+ bytes += size;
2613
+ }
2614
+ return selected;
2615
+ };
2616
+ const createFindCanvasComposite = (remote) => ({ execute: async (input) => {
2617
+ const { items, sourceTruncated } = await readItems(remote, input);
2618
+ const { cursor, ...query } = input;
2619
+ const queryDigest = canvasExchangeDigest(query);
2620
+ const snapshotDigest = canvasExchangeDigest({
2621
+ items,
2622
+ sourceTruncated
2623
+ });
2624
+ const decoded = cursor === void 0 ? null : decodeCanvasExchangeToken(cursor, canvasFindCursorSchema);
2625
+ if (decoded !== null && decoded.queryDigest !== queryDigest) throw new CliError("BAD_REQUEST", "This cursor belongs to another canvas search.", "Restart discovery with the requested query.");
2626
+ if (decoded !== null && decoded.snapshotDigest !== snapshotDigest) throw new CliError("CONFLICT", "The accessible canvases or destinations changed between pages.", "Restart discovery so results are not silently skipped or combined across permissions.");
2627
+ const offset = decoded?.offset ?? 0;
2628
+ if (offset > items.length) throw new CliError("BAD_REQUEST", "The discovery cursor is out of range.", "Restart discovery.");
2629
+ const selected = boundedItems(items.slice(offset, offset + input.limit));
2630
+ const nextOffset = offset + selected.length;
2631
+ const hasMore = nextOffset < items.length;
2632
+ const isTruncated = sourceTruncated.canvases || sourceTruncated.destinations;
2633
+ return {
2634
+ items: selected,
2635
+ returnedCount: selected.length,
2636
+ totalAvailable: items.length,
2637
+ complete: !hasMore && !isTruncated,
2638
+ sourceTruncated,
2639
+ nextCursor: hasMore ? encodeCanvasExchangeToken({
2640
+ protocol: "enhance-canvas-find/1",
2641
+ queryDigest,
2642
+ snapshotDigest,
2643
+ offset: nextOffset
2644
+ }) : null,
2645
+ warnings: isTruncated ? ["The source collection reached its existing limit. Refine the title or team; these results are not a complete inventory."] : []
2646
+ };
2647
+ } });
2648
+
2649
+ //#endregion
2650
+ //#region src/application/canvas-preparation.use-case.ts
2651
+ const POLL_MS = 250;
2652
+ const readPreparation = async (remote, jobId) => {
2653
+ try {
2654
+ return { value: await remote.query("canvas.render.preparation.get", { jobId }) };
2655
+ } catch (error) {
2656
+ if (error instanceof CliError && !["INTERNAL", "RATE_LIMITED"].includes(error.code)) throw error;
2657
+ return null;
2658
+ }
2659
+ };
2660
+ const waitForPreparation = async (remote, initial, waitMs) => {
2661
+ const deadline = Date.now() + waitMs;
2662
+ let job = initial;
2663
+ while (job.state === "queued" || job.state === "running") {
2664
+ const remaining = deadline - Date.now();
2665
+ if (remaining <= 0) break;
2666
+ await setTimeout$1(Math.min(POLL_MS, remaining));
2667
+ const status = await readPreparation(remote, initial.id);
2668
+ if (status === null) return job;
2669
+ job = getCanvasPreparationOutputSchema.parse(status.value).job;
2670
+ if (job.id !== initial.id) throw new CliError("INTERNAL", "Preparation identity changed.", "Retry the original request.");
2671
+ }
2672
+ return job;
2673
+ };
2674
+ const runCanvasPreparation = async (remote, input, waitMs) => {
2675
+ const made = createCanvasPreparationOutputSchema.parse(await remote.mutate("canvas.render.preparation.create", input));
2676
+ const job = await waitForPreparation(remote, made.job, waitMs);
2677
+ if (job.canvasId !== input.canvasId || job.requestedVersion !== input.expectedVersion || !isDeepStrictEqual(job.scope, input.scope) || !isDeepStrictEqual(job.request, input.request)) throw new CliError("CONFLICT", "The native preparation does not match this request.", "Read the canvas and prepare a new intent; do not apply this plan.");
2678
+ if (job.state === "succeeded" && job.result.loadedVersion !== input.expectedVersion) throw new CliError("CONFLICT", "The native preparation measured a different revision.", "Read the canvas and prepare a new intent.");
2679
+ return job;
2680
+ };
2681
+
2682
+ //#endregion
2683
+ //#region src/application/prepare-canvas-command.composite.ts
2684
+ const RECOVER_MUTATION = "canvas.mutation.get";
2685
+ const applyPreparedOperations = async (remote, request) => {
2686
+ try {
2687
+ return applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request));
2688
+ } catch (error) {
2689
+ throw new CliError(error instanceof CliError ? error.code : "INTERNAL", error instanceof CliError ? error.message : "The canvas commit could not be confirmed.", "Read operation_status or repeat the original action with identical arguments and clientToken.", {
2690
+ ...error instanceof CliError && error.fields,
2691
+ outcome: "not_confirmed",
2692
+ operation: JSON.stringify({
2693
+ kind: "canvas-mutation",
2694
+ canvasId: request.canvasId,
2695
+ mutationId: request.mutationId,
2696
+ fingerprint: request.requestContext?.fingerprint
2697
+ })
2698
+ });
2699
+ }
2700
+ };
2701
+ const commitPreparation = async (remote, input, job, fingerprint) => {
2702
+ if (job.result.loadedVersion !== input.baseVersion) throw new CliError("CONFLICT", "The native preparation measured a different revision.", "Read the canvas and prepare a new intent.");
2703
+ if (job.result.operations.length === 0) return {
2704
+ outcome: "no_op",
2705
+ canvasId: job.canvasId,
2706
+ version: input.baseVersion,
2707
+ verification: { rendered: false },
2708
+ warnings: []
2709
+ };
2710
+ const request = applyCanvasOperationsInputSchema.parse({
2711
+ canvasId: job.canvasId,
2712
+ mutationId: input.clientToken,
2713
+ documentFormatVersion: 7,
2714
+ baseVersion: input.baseVersion,
2715
+ operations: job.result.operations,
2716
+ requestContext: {
2717
+ fingerprint,
2718
+ revisionPolicy: "strict",
2719
+ ...input.request.kind === "duplicate" && { copiedNodeIds: job.result.idMap }
2720
+ }
2721
+ });
2722
+ const result = await applyPreparedOperations(remote, request);
2723
+ if (result.canvasId !== job.canvasId || result.mutationId !== input.clientToken || result.previousVersion !== input.baseVersion || result.version !== input.baseVersion + 1 || input.request.kind === "duplicate" && !isDeepStrictEqual(result.copiedNodeIds, job.result.idMap)) throw new CliError("INTERNAL", "The canvas commit receipt could not be verified.", "Check operation_status using the original mutation reference before retrying.", {
2724
+ outcome: "not_confirmed",
2725
+ operation: JSON.stringify({
2726
+ kind: "canvas-mutation",
2727
+ canvasId: job.canvasId,
2728
+ mutationId: input.clientToken,
2729
+ fingerprint
2730
+ })
2731
+ });
2732
+ return canvasWriteReceipt(result, fingerprint);
2733
+ };
2734
+ const createPrepareCanvasCommandComposite = (remote) => ({ execute: async (input) => {
2735
+ const reference = parseCanvasReference(input.canvasRef);
2736
+ const scope = {
2737
+ ...reference.pageId !== void 0 && { pageId: reference.pageId },
2738
+ nodeIds: [...reference.nodeIds]
2739
+ };
2740
+ const fingerprint = canvasExchangeDigest({
2741
+ operation: "canvas.prepare/1",
2742
+ reference,
2743
+ baseVersion: input.baseVersion,
2744
+ request: input.request
2745
+ });
2746
+ const recovered = getCanvasMutationOutputSchema.parse(await remote.query(RECOVER_MUTATION, {
2747
+ canvasId: reference.canvasId,
2748
+ mutationId: input.clientToken,
2749
+ fingerprint
2750
+ }));
2751
+ if (recovered.state === "committed") return canvasWriteReceipt(recovered.result, fingerprint);
2752
+ const job = await runCanvasPreparation(remote, {
2753
+ canvasId: reference.canvasId,
2754
+ expectedVersion: input.baseVersion,
2755
+ request: input.request,
2756
+ scope
2757
+ }, input.waitMs);
2758
+ const operation = {
2759
+ kind: "canvas-preparation",
2760
+ canvasId: reference.canvasId,
2761
+ jobId: job.id,
2762
+ mutationId: input.clientToken,
2763
+ fingerprint
2764
+ };
2765
+ if (job.state !== "succeeded") return canvasPreparationStatus(job, operation);
2766
+ return commitPreparation(remote, input, job, fingerprint);
2767
+ } });
2768
+
2769
+ //#endregion
2770
+ //#region src/application/canvas-editable-html.use-case.ts
2771
+ const ATTRIBUTES = /* @__PURE__ */ new Set([
2772
+ "data-enhance-id",
2773
+ "data-enhance-name",
2774
+ "data-enhance-opaque",
2775
+ "style"
2776
+ ]);
2777
+ const fail = (message) => {
2778
+ throw new CliError("BAD_REQUEST", message, "Use a complete current editable read and preserve its identity and opaque markers.");
2779
+ };
2780
+ const escape = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
2781
+ const styleValues = (source) => {
2782
+ const ast = parse(source, {
2783
+ context: "declarationList",
2784
+ onParseError: (error) => fail(error.message)
2785
+ });
2786
+ if (ast.type !== "DeclarationList") return fail("Expected an inline CSS declaration list.");
2787
+ const styles = /* @__PURE__ */ new Map();
2788
+ ast.children.forEach((declaration) => {
2789
+ if (declaration.type !== "Declaration" || declaration.important !== false) return fail("Use ordinary inline CSS properties without !important or at-rules.");
2790
+ const property = declaration.property.startsWith("--") ? declaration.property : declaration.property.toLowerCase();
2791
+ if (styles.has(property)) return fail(`Duplicate CSS property: ${property}.`);
2792
+ styles.set(property, generate(declaration.value));
2793
+ });
2794
+ return Object.fromEntries(styles);
2795
+ };
2796
+ const serialize$1 = (node) => {
2797
+ const style = Object.entries(node.styles).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}:${value}`).join(";");
2798
+ const attrs = `data-enhance-id="${escape(node.id)}" data-enhance-name="${escape(node.label)}"${node.opaque ? " data-enhance-opaque=\"true\"" : ""}${style === "" ? "" : ` style="${escape(style)}"`}`;
2799
+ return `<${node.tag} ${attrs}>${escape(node.text)}${node.children.map((child) => serialize$1(child)).join("")}</${node.tag}>`;
2800
+ };
2801
+ const projectCanvasEditableHtml = (document, rootNodeId) => {
2802
+ const seen = /* @__PURE__ */ new Set();
2803
+ const opaqueNodeIds = [];
2804
+ const childrenByParent = canvasChildrenByParent(document);
2805
+ const visit = (nodeId) => {
2806
+ if (seen.has(nodeId)) return fail("The document contains repeated node identity.");
2807
+ seen.add(nodeId);
2808
+ const node = requireCanvasNode(document, nodeId);
2809
+ const children = childrenByParent.get(nodeId) ?? [];
2810
+ const isOpaque = isCanvasNodeLocked(document, nodeId) || node.component === "text" && children.length > 0 || ![
2811
+ "root",
2812
+ "frame",
2813
+ "group",
2814
+ "text"
2815
+ ].includes(node.component);
2816
+ if (isOpaque) opaqueNodeIds.push(node.id);
2817
+ const styles = isOpaque ? {} : styleValues(Object.entries(canvasAuthoredStyleDeclarations(node)).map(([property, value]) => `${property}:${canvasCssValue(property, value)}`).join(";"));
2818
+ return {
2819
+ id: node.id,
2820
+ tag: node.component === "text" ? "span" : "div",
2821
+ label: node.label,
2822
+ opaque: isOpaque,
2823
+ styles,
2824
+ text: isOpaque || node.component !== "text" ? "" : textOf(node) ?? "",
2825
+ children: isOpaque ? [] : children.map((id) => visit(id))
2826
+ };
2827
+ };
2828
+ const root = visit(rootNodeId);
2829
+ return {
2830
+ projectionVersion: 1,
2831
+ root,
2832
+ html: serialize$1(root),
2833
+ opaqueNodeIds
2834
+ };
2835
+ };
2836
+ const elements = (children) => children.flatMap((child) => {
2837
+ if ("tagName" in child) return [child];
2838
+ if (child.nodeName === "#text" && "value" in child && child.value.trim() === "") return [];
2839
+ return fail("Container content must contain identified elements; text belongs inside its retained span.");
2840
+ });
2841
+ const canvasEditableHtmlFragment = (html) => {
2842
+ const fragment = parseFragment(html, {
2843
+ sourceCodeLocationInfo: true,
2844
+ onParseError: (error) => fail(`Invalid HTML at line ${String(error.startLine)}: ${error.code}.`)
2845
+ });
2846
+ const pending = [fragment];
2847
+ while (pending.length > 0) {
2848
+ const parent = pending.pop();
2849
+ if (parent === void 0) break;
2850
+ parent.childNodes = parent.childNodes.filter((child) => !("tagName" in child) || canRetainCanvasHtmlElement(child.tagName));
2851
+ const children = parent.childNodes.filter((child) => "tagName" in child);
2852
+ for (const child of children) {
2853
+ child.attrs = child.attrs.filter((attribute) => canRetainCanvasHtmlAttribute(attribute.name, attribute.value));
2854
+ pending.push(child);
2855
+ }
2856
+ }
2857
+ return fragment;
2858
+ };
2859
+ const parseCanvasEditableHtml = (html) => {
2860
+ const fragment = canvasEditableHtmlFragment(html);
2861
+ const seen = /* @__PURE__ */ new Set();
2862
+ const visit = (element) => {
2863
+ if (element.tagName !== "div" && element.tagName !== "span") return fail(`Unsupported retained element: ${element.tagName}.`);
2864
+ const attrs = Object.fromEntries(element.attrs.map((attr) => {
2865
+ if (!ATTRIBUTES.has(attr.name) || attr.namespace !== void 0) return fail(`Unsupported attribute: ${attr.name}.`);
2866
+ return [attr.name, attr.value];
2867
+ }));
2868
+ const id = attrs["data-enhance-id"];
2869
+ const label = attrs["data-enhance-name"];
2870
+ if (id === void 0 || id === "" || label === void 0) return fail("Every retained element requires its identity and name.");
2871
+ if (seen.has(id)) return fail(`Duplicate node identity: ${id}.`);
2872
+ seen.add(id);
2873
+ const marker = attrs["data-enhance-opaque"];
2874
+ if (marker !== void 0 && marker !== "true") return fail(`Invalid opaque marker on ${id}.`);
2875
+ const text = element.tagName === "span" ? element.childNodes.map((child) => {
2876
+ if ("value" in child) return child.value;
2877
+ return fail(`Retained text ${id} must contain text only; its existing rich formatting is preserved by the text owner.`);
2878
+ }).join("") : "";
2879
+ return {
2880
+ id,
2881
+ tag: element.tagName,
2882
+ label,
2883
+ opaque: marker === "true",
2884
+ text,
2885
+ styles: styleValues(attrs["style"] ?? ""),
2886
+ children: element.tagName === "span" ? [] : elements(element.childNodes).map((child) => visit(child))
2887
+ };
2888
+ };
2889
+ const roots = elements(fragment.childNodes);
2890
+ const root = roots[0];
2891
+ if (root === void 0 || roots.length !== 1) return fail("An editable update must contain exactly its original root.");
2892
+ return visit(root);
2893
+ };
2894
+
2895
+ //#endregion
2896
+ //#region src/application/canvas-outline-read.use-case.ts
2897
+ const rootsFor = (input, reference, scene) => {
2898
+ if (input.rootNodeIds !== void 0) return input.rootNodeIds;
2899
+ if (reference.nodeIds.length > 0) return reference.nodeIds;
2900
+ if (reference.pageId === void 0) return ["root"];
2901
+ const resolved = resolveCanvasReference(reference, scene);
2902
+ if (resolved.ok) return resolved.rootNodeIds;
2903
+ canvasReferenceNodeIds(reference, scene);
2904
+ throw new CliError("NOT_FOUND", "The linked page is unavailable.", "Copy a current page link.");
2905
+ };
2906
+ const assertDisjointRoots = (scene, roots) => {
2907
+ const requested = new Set(roots);
2908
+ for (const root of roots) {
2909
+ const visited = /* @__PURE__ */ new Set();
2910
+ let parent = scene.relationships[root]?.parentId;
2911
+ while (parent !== void 0) {
2912
+ if (visited.has(parent) || requested.has(parent)) throw new CliError("BAD_REQUEST", "Outline roots overlap or contain a parent cycle.", "Choose disjoint roots so each depth and coverage statement has one meaning.");
2913
+ visited.add(parent);
2914
+ parent = scene.relationships[parent]?.parentId;
2915
+ }
2916
+ }
2917
+ if (requested.size !== roots.length) throw new CliError("BAD_REQUEST", "Outline roots repeat.", "Choose each root once.");
2918
+ };
2919
+ const outlineNodes = (scene, roots, depth, isCurrent) => {
2920
+ const nodes = [];
2921
+ const seen = /* @__PURE__ */ new Set();
2922
+ const childrenByParent = canvasChildrenByParent(scene);
2923
+ const visit = (id, at) => {
2924
+ if (seen.has(id)) return;
2925
+ seen.add(id);
2926
+ const node = requireCanvasNode(scene, id);
2927
+ const children = childrenByParent.get(id) ?? [];
2928
+ const isLocked = isCanvasNodeLocked(scene, id);
2929
+ nodes.push({
2930
+ id,
2931
+ label: node.label,
2932
+ kind: node.component,
2933
+ parentId: scene.relationships[id]?.parentId ?? null,
2934
+ sortKey: scene.relationships[id]?.sortKey ?? null,
2935
+ depth: at,
2936
+ childCount: children.length,
2937
+ childrenOmitted: at === depth && children.length > 0,
2938
+ locked: isLocked,
2939
+ visible: node.visible !== false,
2940
+ editable: isCurrent && !isLocked && [
2941
+ "root",
2942
+ "frame",
2943
+ "group",
2944
+ "text"
2945
+ ].includes(node.component),
2946
+ bounds: node.box ?? null
2947
+ });
2948
+ if (at < depth) for (const child of children) visit(child, at + 1);
2949
+ };
2950
+ for (const root of roots) visit(root, 0);
2951
+ return nodes;
2952
+ };
2953
+ const outlineOffset = (cursorToken, snapshot, queryDigest) => {
2954
+ if (cursorToken === void 0) return 0;
2955
+ const cursor = decodeCanvasExchangeToken(cursorToken, canvasOutlineCursorSchema);
2956
+ if (cursor.canvasId !== snapshot.reference.canvasId || cursor.queryDigest !== queryDigest) throw new CliError("BAD_REQUEST", "This cursor belongs to another outline query.", "Restart the outline read with the requested scope.");
2957
+ if (cursor.version !== snapshot.version) throw new CliError("CONFLICT", "The canvas changed between outline pages.", "Restart the scoped read at the current revision. Do not combine pages from different revisions.", {
2958
+ currentVersion: String(snapshot.version),
2959
+ outcome: "not_committed"
2960
+ });
2961
+ return cursor.offset;
2962
+ };
2963
+ const readCanvasOutline = (input, snapshot) => {
2964
+ const { reference, scene, version, isCurrent } = snapshot;
2965
+ const roots = rootsFor(input, reference, scene);
2966
+ assertCanvasReferenceNodes(reference, scene, roots);
2967
+ assertDisjointRoots(scene, roots);
2968
+ const queryDigest = canvasExchangeDigest({
2969
+ reference,
2970
+ roots: input.rootNodeIds ?? null,
2971
+ depth: input.depth,
2972
+ limit: input.limit
2973
+ });
2974
+ const offset = outlineOffset(input.cursor, snapshot, queryDigest);
2975
+ const all = outlineNodes(scene, roots, input.depth, isCurrent);
2976
+ if (offset > all.length) throw new CliError("BAD_REQUEST", "The outline cursor is out of range.", "Restart the outline read.");
2977
+ const nodes = all.slice(offset, offset + input.limit);
2978
+ const nextOffset = offset + nodes.length;
2979
+ const hasOmittedDescendants = all.some((node) => node.childrenOmitted);
2980
+ return {
2981
+ canvasId: reference.canvasId,
2982
+ version,
2983
+ scope: { rootNodeIds: [...roots] },
2984
+ view: "outline",
2985
+ complete: nextOffset === all.length && !hasOmittedDescendants,
2986
+ returnedCount: nodes.length,
2987
+ total: all.length,
2988
+ nodes,
2989
+ omittedDescendants: hasOmittedDescendants,
2990
+ nextCursor: nextOffset < all.length ? encodeCanvasExchangeToken({
2991
+ protocol: "enhance-canvas-outline/1",
2992
+ canvasId: reference.canvasId,
2993
+ version,
2994
+ queryDigest,
2995
+ offset: nextOffset
2996
+ }) : null,
2997
+ warnings: isCurrent ? [] : ["This legacy document is read-only until the normal editor upgrades it."]
2998
+ };
2999
+ };
3000
+
3001
+ //#endregion
3002
+ //#region src/application/read-canvas-resources.use-case.ts
3003
+ const MAX_RESULT_BYTES = 48e3;
3004
+ const identityOf = (source) => {
3005
+ const image = canvasImageAssetIdentityFromPath(source);
3006
+ if (image !== null) return {
3007
+ storage: "canvas-image",
3008
+ reference: source,
3009
+ ownerId: image.canvasId,
3010
+ assetId: image.assetId
3011
+ };
3012
+ const font = canvasFontAssetIdentityFromPath(source);
3013
+ if (font !== null) return {
3014
+ storage: "canvas-font",
3015
+ reference: source,
3016
+ ownerId: font.canvasId,
3017
+ assetId: font.sha256
3018
+ };
3019
+ const recording = /^\/v1\/recording-assets\/([a-f0-9-]{36})\/([a-f0-9]{32,64})$/u.exec(source);
3020
+ if (recording !== null) return {
3021
+ storage: "recording-asset",
3022
+ reference: source,
3023
+ ownerId: recording[1] ?? null,
3024
+ assetId: recording[2] ?? null
3025
+ };
3026
+ return {
3027
+ storage: source.startsWith("data:") ? "inline" : /^https?:\/\//u.test(source) ? "external" : "opaque",
3028
+ reference: null,
3029
+ ownerId: null,
3030
+ assetId: null
3031
+ };
3032
+ };
3033
+ const textField = (face, key) => typeof face[key] === "string" ? face[key] : null;
3034
+ const resourcesOf = (snapshot, nodeIds) => {
3035
+ const entries = /* @__PURE__ */ new Map();
3036
+ const orderedNodeIds = [...nodeIds].toSorted((left, right) => left.localeCompare(right));
3037
+ for (const nodeId of orderedNodeIds) {
3038
+ const node = snapshot.scene.nodes[nodeId];
3039
+ if (node === void 0) continue;
3040
+ const add = (kind, source, metadata) => {
3041
+ const entry = {
3042
+ nodeId,
3043
+ kind,
3044
+ sourceDigest: canvasExchangeDigest(source),
3045
+ ...identityOf(source),
3046
+ delivery: "not_checked",
3047
+ metadata
3048
+ };
3049
+ entries.set(canvasExchangeDigest(entry), entry);
3050
+ return source;
3051
+ };
3052
+ mapCanvasNodeImageSources(node, (source) => add("image", source, null));
3053
+ mapCanvasFontSources(node.props, (source, face) => add("font", source, {
3054
+ family: textField(face, "family"),
3055
+ style: textField(face, "style"),
3056
+ weight: textField(face, "weight")
3057
+ }));
3058
+ }
3059
+ return Array.from(entries, ([, entry]) => entry);
3060
+ };
3061
+ const offsetOf = (input, snapshot, digest) => {
3062
+ if (input.cursor === void 0) return 0;
3063
+ const cursor = decodeCanvasExchangeToken(input.cursor, canvasResourcesCursorSchema);
3064
+ if (cursor.canvasId !== snapshot.reference.canvasId || cursor.digest !== digest) throw new CliError("BAD_REQUEST", "The resource cursor belongs to another query.", "Restart this scoped resource read.");
3065
+ if (cursor.version !== snapshot.version) throw new CliError("CONFLICT", "The canvas changed between resource pages.", "Restart the read at the current revision.");
3066
+ return cursor.offset;
3067
+ };
3068
+ const readCanvasResources = (input, snapshot) => {
3069
+ const scope = resolveCanvasReference(snapshot.reference, snapshot.scene);
3070
+ if (!scope.ok) throw new CliError("NOT_FOUND", "The requested canvas scope is unavailable.", "Copy a current page or selection link; do not broaden the request.");
3071
+ const digest = canvasExchangeDigest({
3072
+ reference: snapshot.reference,
3073
+ limit: input.limit
3074
+ });
3075
+ const offset = offsetOf(input, snapshot, digest);
3076
+ const all = resourcesOf(snapshot, scope.nodeIds);
3077
+ if (offset > all.length) throw new CliError("BAD_REQUEST", "The resource cursor is out of range.", "Restart the scoped resource read.");
3078
+ const envelope = (resources) => {
3079
+ const next = offset + resources.length;
3080
+ return {
3081
+ view: "resources",
3082
+ canvasId: snapshot.reference.canvasId,
3083
+ version: snapshot.version,
3084
+ scope: { rootNodeIds: [...scope.rootNodeIds] },
3085
+ coverage: "authored-resource-slots",
3086
+ resources,
3087
+ total: all.length,
3088
+ returnedCount: resources.length,
3089
+ complete: next === all.length,
3090
+ nextCursor: next === all.length ? null : encodeCanvasExchangeToken({
3091
+ protocol: "enhance-canvas-resources/1",
3092
+ canvasId: snapshot.reference.canvasId,
3093
+ version: snapshot.version,
3094
+ digest,
3095
+ offset: next
3096
+ }),
3097
+ warnings: [
3098
+ "Inventory includes declared image and font resource slots, including hidden and unused declarations. It does not resolve computed font usage or assets inside opaque screens, recordings, prototypes or raw CSS.",
3099
+ "Resource delivery and availability have not been checked. Protected paths retain product authorization. External URLs and inline bytes are omitted; their digests identify the original source without exposing credentials or blobs.",
3100
+ "Scoped reads include declarations on selected nodes and descendants only. A font declaration owned by an ancestor requires a separate explicit read of that scope."
3101
+ ]
3102
+ };
3103
+ };
3104
+ const budget = MAX_RESULT_BYTES - Buffer.byteLength(JSON.stringify(envelope([])));
3105
+ return envelope(boundedResultPage(all, offset, input.limit, budget).entries);
3106
+ };
3107
+
3108
+ //#endregion
3109
+ //#region src/application/canvas-transcript-page.use-case.ts
3110
+ const canvasTranscriptPage = (transcript, request, scope) => {
3111
+ if (transcript.state !== "ready") {
3112
+ if (request.cursor !== void 0) throw new CliError("CONFLICT", "The transcript changed during pagination.", "Restart the read.");
3113
+ return transcript;
3114
+ }
3115
+ const { cursor, ...range } = request;
3116
+ const digest = canvasExchangeDigest({
3117
+ scope,
3118
+ range,
3119
+ transcript
3120
+ });
3121
+ const held = cursor === void 0 ? null : decodeCanvasExchangeToken(cursor, canvasTranscriptCursorSchema);
3122
+ if (held !== null && held.digest !== digest) throw new CliError("CONFLICT", "The transcript cursor no longer matches this source, range or revision.", "Restart the requested range; do not combine transcript revisions.");
3123
+ const matching = transcript.cues.filter((cue) => cue.endMs >= request.startMs && (request.endMs === void 0 || cue.startMs < request.endMs));
3124
+ const offset = held?.offset ?? 0;
3125
+ if (offset > matching.length) throw new CliError("BAD_REQUEST", "Transcript cursor offset is out of range.", "Restart the read.");
3126
+ const cues = boundedResultPage(matching, offset, request.limit).entries;
3127
+ const nextOffset = offset + cues.length;
3128
+ return {
3129
+ state: "ready",
3130
+ languageCode: transcript.languageCode,
3131
+ integrity: transcript.integrity,
3132
+ isRefreshing: transcript.isRefreshing,
3133
+ requestedRange: {
3134
+ startMs: request.startMs,
3135
+ endMs: request.endMs ?? null
3136
+ },
3137
+ cues,
3138
+ returnedCount: cues.length,
3139
+ totalInRange: matching.length,
3140
+ omittedOutsideRange: transcript.cues.length - matching.length,
3141
+ complete: nextOffset === matching.length,
3142
+ nextCursor: nextOffset < matching.length ? encodeCanvasExchangeToken({
3143
+ protocol: "enhance-canvas-transcript/1",
3144
+ digest,
3145
+ offset: nextOffset
3146
+ }) : null
3147
+ };
3148
+ };
3149
+
3150
+ //#endregion
3151
+ //#region src/application/read-canvas-source.composite.ts
3152
+ const SOURCE_READ_PROCEDURES = [
3153
+ "recording.get",
3154
+ "prototype.getPublishStatus",
3155
+ "transcript.get"
3156
+ ];
3157
+ const capturedSource = (context) => {
3158
+ const capture = canvasCaptureSchema.safeParse(context.node.props?.["capture"]).data;
3159
+ if (capture === void 0) return null;
3160
+ const screen = context.screens.find((item) => item.screenId === capture.screenId);
3161
+ return {
3162
+ kind: "screen",
3163
+ screenId: capture.screenId,
3164
+ availability: screen === void 0 ? capture.html === void 0 ? "unavailable" : "inline-only" : screen.download === null ? "pending" : "available",
3165
+ sourceUrl: screen?.route ?? null,
3166
+ title: screen?.title ?? null,
3167
+ viewport: screen?.viewport ?? capture.viewport,
3168
+ atMs: screen?.atMs ?? capture.atMs,
3169
+ recordingId: screen === void 0 ? capture.provenance?.recordingId ?? null : screen.sourceRecordingId,
3170
+ missingAssetCount: screen?.assetBundle?.missingAssetCount ?? null
3171
+ };
3172
+ };
3173
+ const conversionSource = (node) => {
3174
+ const conversion = canvasConversionMetadataSchema.safeParse(node.props?.["conversion"]).data;
3175
+ if (conversion === void 0) return { kind: "none" };
3176
+ const counts = /* @__PURE__ */ new Map();
3177
+ const issues = conversion.report?.issues ?? [];
3178
+ for (const issue of issues) counts.set(issue.code, (counts.get(issue.code) ?? 0) + 1);
3179
+ return {
3180
+ kind: "conversion",
3181
+ recordingId: conversion.provenance?.recordingId ?? null,
3182
+ nodeCount: conversion.report?.nodeCount ?? null,
3183
+ issueCounts: Object.fromEntries(counts)
3184
+ };
3185
+ };
3186
+ const sourceEvidence = async (remote, context) => {
3187
+ const { node, canvasId } = context;
3188
+ if (node.component === "recording") {
3189
+ const props = canvasRecordingPropsSchema.parse(node.props);
3190
+ const recordingId = z.uuid().parse(props.recordingId);
3191
+ const recording = getRecordingOutputSchema.parse(await remote.query(SOURCE_READ_PROCEDURES[0], {
3192
+ canvasId,
3193
+ recordingId
3194
+ }));
3195
+ return {
3196
+ kind: "recording",
3197
+ recordingId,
3198
+ durationMs: recording.durationMs,
3199
+ viewport: recording.viewport,
3200
+ sourceUrl: recording.sourceUrl,
3201
+ interrupted: recording.interrupted,
3202
+ integrity: recording.integrity,
3203
+ chunkCount: recording.chunks.length,
3204
+ missingChunkCount: recording.chunks.filter((chunk) => chunk.state === "missing").length,
3205
+ hasAudio: recording.audio !== null,
3206
+ missingAssetCount: recording.missingAssetCount
3207
+ };
3208
+ }
3209
+ if (node.component === "prototype") {
3210
+ const props = canvasPrototypePropsSchema.parse(node.props);
3211
+ const status = getPrototypePublishStatusOutputSchema.parse(await remote.query(SOURCE_READ_PROCEDURES[1], {
3212
+ canvasId,
3213
+ deploymentId: props.deploymentId
3214
+ }));
3215
+ if (status.prototypeId !== props.prototypeId) throw new CliError("CONFLICT", "Prototype identity does not match its deployment.", "Read the node again.");
3216
+ return {
3217
+ kind: "prototype",
3218
+ ...props,
3219
+ state: status.state,
3220
+ fileCount: status.fileCount
3221
+ };
3222
+ }
3223
+ return capturedSource(context) ?? conversionSource(node);
3224
+ };
3225
+ const createReadCanvasSourceComposite = (remote) => ({ execute: async (context) => {
3226
+ const source = await sourceEvidence(remote, context);
3227
+ const request = context.input.transcript;
3228
+ const recordingId = "recordingId" in source ? source.recordingId : null;
3229
+ if (request !== void 0 && recordingId === null) throw new CliError("BAD_REQUEST", "This object has no recording transcript source.", "Choose a recording or a capture with recording provenance.");
3230
+ const transcript = request === void 0 ? null : canvasTranscriptPage(transcriptOutputSchema.parse(await remote.query(SOURCE_READ_PROCEDURES[2], {
3231
+ canvasId: context.canvasId,
3232
+ recordingId: z.uuid().parse(recordingId)
3233
+ })), request, {
3234
+ canvasRef: context.input.canvasRef,
3235
+ nodeId: context.node.id,
3236
+ version: context.version
3237
+ });
3238
+ const isUnavailable = source.kind === "screen" && ["pending", "unavailable"].includes(source.availability);
3239
+ return {
3240
+ canvasId: context.canvasId,
3241
+ version: context.version,
3242
+ scope: { rootNodeIds: [context.node.id] },
3243
+ view: "source",
3244
+ nodeId: context.node.id,
3245
+ source,
3246
+ transcript,
3247
+ complete: !isUnavailable && (transcript === null || transcript.state === "empty" || transcript.state === "ready" && transcript.complete),
3248
+ pixelsInspected: false,
3249
+ warnings: [...isUnavailable ? ["The captured source bytes are not currently available."] : [], ...transcript === null ? [] : ["Transcript times describe speech, not verified visual transitions. Render and inspect candidate moments."]]
3250
+ };
3251
+ } });
3252
+
3253
+ //#endregion
3254
+ //#region src/application/read-canvas.composite.ts
3255
+ const READ_CANVAS_PROCEDURES = ["canvas.document.get"];
3256
+ const stale = (version) => {
3257
+ throw new CliError("CONFLICT", `Canvas version ${String(version)} no longer matches this read.`, "Restart the scoped read at the current revision. Do not combine pages from different revisions.", {
3258
+ currentVersion: String(version),
3259
+ outcome: "not_committed"
3260
+ });
3261
+ };
3262
+ const editable = (input, snapshot) => {
3263
+ const { reference, scene, version } = snapshot;
3264
+ if (!snapshot.isCurrent) throw new CliError("BAD_REQUEST", "This document format cannot produce an editable snapshot.", "Open it in the current editor before editing.");
3265
+ assertCanvasReferenceNodes(reference, scene, [input.rootNodeId]);
3266
+ const projection = projectCanvasEditableHtml(scene, input.rootNodeId);
3267
+ return {
3268
+ canvasId: reference.canvasId,
3269
+ version,
3270
+ scope: { rootNodeIds: [input.rootNodeId] },
3271
+ view: "editable",
3272
+ complete: true,
3273
+ projectionVersion: projection.projectionVersion,
3274
+ rootNodeId: input.rootNodeId,
3275
+ html: projection.html,
3276
+ opaqueNodeIds: [...projection.opaqueNodeIds],
3277
+ snapshotToken: canvasSnapshotToken({
3278
+ reference,
3279
+ version,
3280
+ rootNodeId: input.rootNodeId,
3281
+ html: projection.html
3282
+ }),
3283
+ warnings: projection.opaqueNodeIds.length > 0 ? ["Preserve opaque placeholders unchanged; their authored content remains in the canvas."] : []
3284
+ };
3285
+ };
3286
+ const createReadCanvasComposite = (remote) => ({ execute: async (input) => {
3287
+ const reference = parseCanvasReference(input.canvasRef);
3288
+ const held = getCanvasDocumentOutputSchema.parse(await remote.query(READ_CANVAS_PROCEDURES[0], { canvasId: reference.canvasId }));
3289
+ if (input.expectedVersion !== void 0 && input.expectedVersion !== held.version) return stale(held.version);
3290
+ const current = canvasSceneDocumentSchema.safeParse(held.document);
3291
+ const scene = current.success ? current.data : canvasReadableSceneDocumentSchema.parse(held.document);
3292
+ if (input.view === "resources") return readCanvasResources(input, {
3293
+ reference,
3294
+ scene,
3295
+ version: held.version,
3296
+ isCurrent: current.success
3297
+ });
3298
+ if (input.view === "outline") return readCanvasOutline(input, {
3299
+ reference,
3300
+ scene,
3301
+ version: held.version,
3302
+ isCurrent: current.success
3303
+ });
3304
+ if (input.view === "source") {
3305
+ assertCanvasReferenceNodes(reference, scene, [input.nodeId]);
3306
+ return createReadCanvasSourceComposite(remote).execute({
3307
+ canvasId: reference.canvasId,
3308
+ version: held.version,
3309
+ node: requireCanvasNode(scene, input.nodeId),
3310
+ screens: held.screens,
3311
+ input
3312
+ });
3313
+ }
3314
+ return editable(input, {
3315
+ reference,
3316
+ scene,
3317
+ version: held.version,
3318
+ isCurrent: current.success
3319
+ });
3320
+ } });
3321
+
3322
+ //#endregion
3323
+ //#region src/application/revisioned-canvas-command.composite.ts
3324
+ const CANVAS_COMMAND_PROCEDURES = ["canvas.mutation.get"];
3325
+ const createRevisionedCanvasCommandComposite = (remote) => ({ execute: async (input) => {
3326
+ const canvasId = input.reference.canvasId;
3327
+ const recovered = getCanvasMutationOutputSchema.parse(await remote.query(CANVAS_COMMAND_PROCEDURES[0], {
3328
+ canvasId,
3329
+ mutationId: input.clientToken,
3330
+ fingerprint: input.fingerprint
3331
+ }));
3332
+ if (recovered.state === "committed") return canvasWriteReceipt(recovered.result, input.fingerprint);
3333
+ const scene = await sceneAtVersion({ remote }, canvasId, input.baseVersion);
3334
+ const operations = await input.plan(scene);
3335
+ if ("outcome" in operations) return operations;
3336
+ assertCanvasReferenceOperations(input.reference, scene, operations);
3337
+ if (operations.length === 0) return {
3338
+ outcome: "no_op",
3339
+ canvasId,
3340
+ version: input.baseVersion,
3341
+ verification: { rendered: false },
3342
+ warnings: []
3343
+ };
3344
+ const request = applyCanvasOperationsInputSchema.safeParse({
3345
+ canvasId,
3346
+ documentFormatVersion: 7,
3347
+ mutationId: input.clientToken,
3348
+ baseVersion: input.baseVersion,
3349
+ operations,
3350
+ requestContext: {
3351
+ fingerprint: input.fingerprint,
3352
+ revisionPolicy: "strict"
3353
+ }
3354
+ });
3355
+ if (!request.success) throw new CliError("BAD_REQUEST", "The planned edit exceeds the canonical canvas contract.", request.error.issues[0]?.message ?? "Reduce the edit scope.", { outcome: "not_committed" });
3356
+ return canvasWriteReceipt(applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(request.data)), input.fingerprint);
3357
+ } });
3358
+
3359
+ //#endregion
3360
+ //#region src/application/remove-canvas-nodes.composite.ts
3361
+ const removalPlan = (scene, rootNodeIds) => {
3362
+ const children = canvasChildrenByParent(scene);
3363
+ const selected = new Set(rootNodeIds);
3364
+ const removed = /* @__PURE__ */ new Set();
3365
+ const walk = (id) => {
3366
+ if (removed.has(id)) return;
3367
+ removed.add(id);
3368
+ requireCanvasNode(scene, id);
3369
+ if (isCanvasNodeLocked(scene, id)) throw new CliError("BAD_REQUEST", `Removing this subtree would remove locked content: ${id}.`, "Keep the locked subtree, or explicitly unlock it before requesting removal.");
3370
+ const descendants = children.get(id) ?? [];
3371
+ for (const child of descendants) walk(child);
3372
+ };
3373
+ for (const id of selected) {
3374
+ if (id === "root") throw new CliError("BAD_REQUEST", "The canvas root cannot be removed.", "Name its children.");
3375
+ walk(id);
3376
+ }
3377
+ return [...selected].filter((id) => {
3378
+ let parent = scene.relationships[id]?.parentId;
3379
+ while (parent !== void 0) {
3380
+ if (selected.has(parent)) return false;
3381
+ parent = scene.relationships[parent]?.parentId;
3382
+ }
3383
+ return true;
3384
+ }).map((nodeId) => ({
3385
+ op: "remove",
3386
+ nodeId
3387
+ }));
3388
+ };
3389
+ const createRemoveCanvasNodesComposite = (remote) => ({ execute: async ({ clientToken, ...input }) => {
3390
+ const reference = parseCanvasReference(input.canvasRef);
3391
+ return createRevisionedCanvasCommandComposite(remote).execute({
3392
+ reference,
3393
+ baseVersion: input.baseVersion,
3394
+ clientToken,
3395
+ fingerprint: canvasExchangeDigest({
3396
+ operation: "canvas.remove/1",
3397
+ ...input,
3398
+ reference
3399
+ }),
3400
+ plan: (scene) => removalPlan(scene, input.rootNodeIds)
3401
+ });
3402
+ } });
3403
+
3404
+ //#endregion
3405
+ //#region src/application/canvas-html-structure.use-case.ts
3406
+ const place = (plan, nodeId, parentId, index) => {
3407
+ const previousParent = plan.parents.get(nodeId);
3408
+ const siblings = plan.children.get(parentId) ?? [];
3409
+ if (previousParent === parentId && siblings.indexOf(nodeId) === index) return;
3410
+ if (isCanvasNodeLocked(plan.document, nodeId) || isCanvasNodeLocked(plan.document, parentId)) throw new CliError("BAD_REQUEST", `Locked node ${nodeId} cannot be rearranged through HTML.`, "Keep locked placeholders in place or unlock them in the editor before editing.");
3411
+ if (previousParent !== void 0) plan.children.set(previousParent, (plan.children.get(previousParent) ?? []).filter((id) => id !== nodeId));
3412
+ const destination = plan.children.get(parentId) ?? [];
3413
+ destination.splice(index, 0, nodeId);
3414
+ plan.children.set(parentId, destination);
3415
+ plan.parents.set(nodeId, parentId);
3416
+ plan.moves.push({
3417
+ nodeId,
3418
+ parentId,
3419
+ index
3420
+ });
3421
+ };
3422
+ const canvasHtmlStructureOperations = (document, requested, removed) => {
3423
+ const remaining = {
3424
+ ...document,
3425
+ nodes: Object.fromEntries(Object.entries(document.nodes).filter(([id]) => !removed.has(id))),
3426
+ relationships: Object.fromEntries(Object.entries(document.relationships).filter(([id]) => !removed.has(id)))
3427
+ };
3428
+ const plan = {
3429
+ document: remaining,
3430
+ parents: new Map(Object.entries(remaining.relationships).map(([id, relationship]) => [id, relationship.parentId])),
3431
+ children: new Map([...canvasChildrenByParent(remaining)].map(([id, children]) => [id, [...children]])),
3432
+ moves: []
3433
+ };
3434
+ const visit = (parent) => {
3435
+ for (const [index, child] of parent.children.entries()) {
3436
+ place(plan, child.id, parent.id, index);
3437
+ visit(child);
3438
+ }
3439
+ };
3440
+ visit(requested);
3441
+ return plan.moves.length === 0 ? [] : moveCanvasNodeOperations(remaining, plan.moves).operations;
3442
+ };
3443
+
3444
+ //#endregion
3445
+ //#region src/application/canvas-html-compilation.use-case.ts
3446
+ const invalid$2 = (message) => {
3447
+ throw new CliError("BAD_REQUEST", message, "Read the current subtree and reduce or correct the edit. No canvas changes were committed.");
3448
+ };
3449
+ const stagedInsertions = (document, plan, prepared) => {
3450
+ if (Object.keys(plan.idMap).length !== prepared.fragments.length) return invalid$2("Native compilation returned unexpected fragment identities.");
3451
+ if (plan.operations.length !== prepared.fragments.length) return invalid$2("Native compilation returned an incomplete insertion plan.");
3452
+ const staged = {
3453
+ ...document,
3454
+ nodes: { ...document.nodes },
3455
+ relationships: { ...document.relationships }
3456
+ };
3457
+ for (const [index, fragment] of prepared.fragments.entries()) {
3458
+ const operation = plan.operations[index];
3459
+ if (operation?.op !== "insertConvertedSubtree" || operation.destination.kind !== "insert-children" || operation.destination.targetNodeId !== fragment.parentNodeId || operation.rootNodeId !== plan.idMap[fragment.id]) return invalid$2("Native compilation returned a mismatched insertion plan.");
3460
+ for (const id of Object.keys(operation.nodes)) if (staged.nodes[id] !== void 0 || Object.hasOwn(staged.tombstones, id)) return invalid$2(`New HTML identity ${id} already exists.`);
3461
+ const lastId = canvasChildIds(staged, fragment.parentNodeId).at(-1);
3462
+ const lastKey = lastId === void 0 ? null : staged.relationships[lastId]?.sortKey ?? null;
3463
+ Object.assign(staged.nodes, operation.nodes);
3464
+ Object.assign(staged.relationships, operation.relationships, { [operation.rootNodeId]: {
3465
+ parentId: fragment.parentNodeId,
3466
+ sortKey: generateKeyBetween(lastKey, null)
3467
+ } });
3468
+ }
3469
+ return staged;
3470
+ };
3471
+ const boundRoot = (root, idMap) => ({
3472
+ ...root,
3473
+ id: Object.hasOwn(idMap, root.id) ? idMap[root.id] ?? root.id : root.id,
3474
+ children: root.children.map((child) => boundRoot(child, idMap))
3475
+ });
3476
+ const EMPTY_COMPILATION = {
3477
+ operations: [],
3478
+ idMap: {},
3479
+ rootNodeIds: []
3480
+ };
3481
+ const finishCanvasHtmlReconciliation = (document, prepared, compiled = EMPTY_COMPILATION) => {
3482
+ const staged = stagedInsertions(document, compiled, prepared);
3483
+ const root = boundRoot(prepared.root, compiled.idMap);
3484
+ return [
3485
+ ...prepared.operations,
3486
+ ...compiled.operations,
3487
+ ...canvasHtmlStructureOperations(staged, root, prepared.removed)
3488
+ ];
3489
+ };
3490
+
3491
+ //#endregion
3492
+ //#region src/application/canvas-html-update-source.use-case.ts
3493
+ const identity = (element) => element.attrs.find((attribute) => attribute.name === "data-enhance-id")?.value;
3494
+ const invalid$1 = (message) => {
3495
+ throw new CliError("BAD_REQUEST", message, "Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.");
3496
+ };
3497
+ const collectElements = (children) => {
3498
+ return children.flatMap((child) => "tagName" in child ? [child, ...collectElements(child.childNodes)] : []);
3499
+ };
3500
+ const parseCanvasHtmlUpdate = (html) => {
3501
+ const fragment = canvasEditableHtmlFragment(html);
3502
+ const elements = collectElements(fragment.childNodes);
3503
+ const reservedIds = new Set(elements.map((element) => identity(element)));
3504
+ const fragments = [];
3505
+ const visit = (element, parentId) => {
3506
+ const id = identity(element);
3507
+ if (id !== void 0) return {
3508
+ ...element,
3509
+ childNodes: element.childNodes.map((child) => "tagName" in child ? visit(child, id) : child)
3510
+ };
3511
+ if (parentId === void 0) return invalid$1("The submitted HTML must retain its original root identity.");
3512
+ if ([element, ...collectElements(element.childNodes)].some((node) => node.attrs.some((attribute) => ["data-enhance-id", "data-enhance-opaque"].includes(attribute.name)))) return invalid$1("A new HTML subtree cannot wrap retained identities or opaque placeholders. Insert the container and use canvas_arrange to move retained content into it.");
3513
+ let key = `new_${String(fragments.length)}`;
3514
+ while (reservedIds.has(key)) key = `_${key}`;
3515
+ reservedIds.add(key);
3516
+ fragments.push({
3517
+ id: key,
3518
+ parentNodeId: parentId,
3519
+ html: serializeOuter(element)
3520
+ });
3521
+ return {
3522
+ ...element,
3523
+ tagName: "div",
3524
+ nodeName: "div",
3525
+ childNodes: [],
3526
+ attrs: [
3527
+ {
3528
+ name: "data-enhance-id",
3529
+ value: key
3530
+ },
3531
+ {
3532
+ name: "data-enhance-name",
3533
+ value: "New content"
3534
+ },
3535
+ {
3536
+ name: "data-enhance-opaque",
3537
+ value: "true"
3538
+ }
3539
+ ]
3540
+ };
3541
+ };
3542
+ fragment.childNodes = fragment.childNodes.map((element) => "tagName" in element ? visit(element) : element);
3543
+ return {
3544
+ root: parseCanvasEditableHtml(serialize(fragment)),
3545
+ fragments
3546
+ };
3547
+ };
3548
+
3549
+ //#endregion
3550
+ //#region src/application/canvas-html-reconciliation.use-case.ts
3551
+ const invalid = (message) => {
3552
+ throw new CliError("BAD_REQUEST", message, "Read the current editable subtree and apply only the intended change. No changes were committed.");
3553
+ };
3554
+ const indexElements = (root) => {
3555
+ const result = /* @__PURE__ */ new Map();
3556
+ const visit = (element) => {
3557
+ result.set(element.id, element);
3558
+ for (const child of element.children) visit(child);
3559
+ };
3560
+ visit(root);
3561
+ return result;
3562
+ };
3563
+ const arePropertiesEqual = (before, after) => Object.keys(before).length === Object.keys(after).length && Object.entries(before).every(([key, value]) => after[key] === value);
3564
+ const removedIds = (before, after, roots, rootNodeId) => {
3565
+ const removed = /* @__PURE__ */ new Set();
3566
+ const collect = (element) => {
3567
+ if (removed.has(element.id)) return invalid(`Overlapping removal roots include ${element.id}.`);
3568
+ if (after.has(element.id)) return invalid(`Removed node ${element.id} is still present in the HTML.`);
3569
+ removed.add(element.id);
3570
+ for (const child of element.children) collect(child);
3571
+ };
3572
+ for (const id of roots) {
3573
+ const held = before.get(id);
3574
+ if (held === void 0 || id === rootNodeId) return invalid(`Invalid removal root: ${id}.`);
3575
+ collect(held);
3576
+ }
3577
+ for (const id of before.keys()) if (!after.has(id) && !removed.has(id)) return invalid(`Missing retained node ${id}; declare intentional deletion in removeNodeIds.`);
3578
+ return removed;
3579
+ };
3580
+ const fieldOperations = (document, before, after) => {
3581
+ if (before.tag !== after.tag || before.opaque !== after.opaque) return invalid(`The kind or opaque marker of ${before.id} changed.`);
3582
+ const hasStyleChange = !arePropertiesEqual(before.styles, after.styles);
3583
+ if (before.opaque && (hasStyleChange || before.label !== after.label || before.text !== after.text || after.children.length > 0)) return invalid(`Opaque node ${before.id} cannot be changed through HTML.`);
3584
+ const node = document.nodes[before.id];
3585
+ if (node === void 0) return invalid(`Node ${before.id} no longer exists.`);
3586
+ const operations = [];
3587
+ if (before.label !== after.label) operations.push({
3588
+ op: "setLabel",
3589
+ nodeId: before.id,
3590
+ label: after.label,
3591
+ labelOrigin: "user"
3592
+ });
3593
+ if (before.text !== after.text) operations.push({
3594
+ op: "editText",
3595
+ nodeId: before.id,
3596
+ change: canvasTextChangeBetween(node, {
3597
+ ...node,
3598
+ props: canvasTextPropsWithContent(node, after.text)
3599
+ })
3600
+ });
3601
+ if (hasStyleChange) {
3602
+ const properties = /* @__PURE__ */ new Set([...Object.keys(before.styles), ...Object.keys(after.styles)]);
3603
+ const styles = Object.fromEntries([...properties].filter((key) => before.styles[key] !== after.styles[key]).map((key) => [key, after.styles[key] ?? null]));
3604
+ operations.push(...canvasStyleOperations(document, [{
3605
+ nodeIds: [before.id],
3606
+ styles
3607
+ }]));
3608
+ }
3609
+ return operations;
3610
+ };
3611
+ const prepareCanvasHtmlReconciliation = (document, rootNodeId, html, removeNodeIds) => {
3612
+ const baseline = projectCanvasEditableHtml(document, rootNodeId).root;
3613
+ const parsed = parseCanvasHtmlUpdate(html);
3614
+ const requested = parsed.root;
3615
+ if (requested.id !== rootNodeId) return invalid("The submitted HTML must retain its original root identity.");
3616
+ const introduced = new Set(parsed.fragments.map((fragment) => fragment.id));
3617
+ const before = indexElements(baseline);
3618
+ const after = indexElements(requested);
3619
+ const removed = removedIds(before, after, removeNodeIds, rootNodeId);
3620
+ const removedDescendants = /* @__PURE__ */ new Set([...removed, ...removeNodeIds.flatMap((id) => [...canvasDescendantIds(document, id)])]);
3621
+ for (const id of removedDescendants) if (isCanvasNodeLocked(document, id)) return invalid(`Locked node ${id} cannot be removed through HTML.`);
3622
+ const operations = removeNodeIds.map((nodeId) => {
3623
+ if (before.get(nodeId)?.opaque === true) return invalid(`Use explicit canvas removal for opaque node ${nodeId}.`);
3624
+ return {
3625
+ op: "remove",
3626
+ nodeId
3627
+ };
3628
+ });
3629
+ for (const [id, next] of after) {
3630
+ if (introduced.has(id)) continue;
3631
+ const held = before.get(id);
3632
+ if (held === void 0) return invalid(`Unknown or outside-scope identity: ${id}.`);
3633
+ operations.push(...fieldOperations(document, held, next));
3634
+ }
3635
+ for (const fragment of parsed.fragments) {
3636
+ const parent = before.get(fragment.parentNodeId);
3637
+ if (parent === void 0 || parent.opaque || parent.tag !== "div") return invalid(`Node ${fragment.parentNodeId} cannot contain new HTML.`);
3638
+ }
3639
+ return {
3640
+ root: requested,
3641
+ operations,
3642
+ removed: removedDescendants,
3643
+ fragments: parsed.fragments
3644
+ };
3645
+ };
3646
+
3647
+ //#endregion
3648
+ //#region src/application/update-canvas-html.composite.ts
3649
+ const planUpdate = (input, reference, scene) => {
3650
+ const binding = resolveCanvasSnapshot(input.snapshotToken, reference);
3651
+ assertCanvasReferenceNodes(reference, scene, [binding.rootNodeId]);
3652
+ const projection = projectCanvasEditableHtml(scene, binding.rootNodeId);
3653
+ if (canvasSnapshotToken({
3654
+ reference,
3655
+ version: binding.version,
3656
+ rootNodeId: binding.rootNodeId,
3657
+ html: projection.html
3658
+ }) !== input.snapshotToken) throw new CliError("CONFLICT", "The editable snapshot no longer matches the complete source.", "Read the requested subtree again and deliberately reapply the intended change.", { outcome: "not_committed" });
3659
+ return prepareCanvasHtmlReconciliation(scene, binding.rootNodeId, input.html, input.removeNodeIds);
3660
+ };
3661
+ const prepareUpdate = async (remote, input, context) => {
3662
+ const prepared = planUpdate(input, context.reference, context.scene);
3663
+ if (prepared.fragments.length === 0) return finishCanvasHtmlReconciliation(context.scene, prepared);
3664
+ const job = await runCanvasPreparation(remote, {
3665
+ canvasId: context.reference.canvasId,
3666
+ expectedVersion: context.version,
3667
+ scope: {
3668
+ nodeIds: [...context.reference.nodeIds],
3669
+ ...context.reference.pageId !== void 0 && { pageId: context.reference.pageId }
3670
+ },
3671
+ request: {
3672
+ kind: "compile-html",
3673
+ fragments: [...prepared.fragments],
3674
+ contextOperations: prepared.operations.filter((operation) => operation.op !== "remove")
3675
+ }
3676
+ }, input.waitMs);
3677
+ if (job.state !== "succeeded") return canvasPreparationStatus(job, {
3678
+ kind: "canvas-preparation",
3679
+ canvasId: context.reference.canvasId,
3680
+ jobId: job.id,
3681
+ mutationId: input.clientToken,
3682
+ fingerprint: context.fingerprint
3683
+ });
3684
+ return finishCanvasHtmlReconciliation(context.scene, prepared, job.result);
3685
+ };
3686
+ const createUpdateCanvasHtmlComposite = (remote) => ({ execute: async (offered) => {
3687
+ const input = canvasUpdateHtmlInputSchema.parse(offered);
3688
+ const reference = parseCanvasReference(input.canvasRef);
3689
+ const binding = resolveCanvasSnapshot(input.snapshotToken, reference);
3690
+ const fingerprint = canvasExchangeDigest({
3691
+ operation: "canvas.updateHtml/1",
3692
+ snapshotToken: input.snapshotToken,
3693
+ html: input.html,
3694
+ removeNodeIds: input.removeNodeIds
3695
+ });
3696
+ return createRevisionedCanvasCommandComposite(remote).execute({
3697
+ reference,
3698
+ baseVersion: binding.version,
3699
+ clientToken: input.clientToken,
3700
+ fingerprint,
3701
+ plan: async (scene) => prepareUpdate(remote, input, {
3702
+ reference,
3703
+ scene,
3704
+ fingerprint,
3705
+ version: binding.version
3706
+ })
3707
+ });
3708
+ } });
3709
+
3710
+ //#endregion
3711
+ //#region src/infrastructure/canvas-exchange-invocation.adapter.ts
3712
+ const createCanvasExchangeInvocationAdapter = (remote, offered, clientToken) => ({
3713
+ "canvas.arrange": async () => {
3714
+ const { changes, ...input } = canvasArrangeCapabilityInputSchema.parse(offered);
3715
+ return createPrepareCanvasCommandComposite(remote).execute({
3716
+ ...input,
3717
+ clientToken,
3718
+ request: {
3719
+ kind: "arrange",
3720
+ changes
3721
+ }
3722
+ });
3723
+ },
3724
+ "canvas.duplicateNodes": async () => {
3725
+ const { nodeIds, destination, ...input } = canvasDuplicateCapabilityInputSchema.parse(offered);
3726
+ return createPrepareCanvasCommandComposite(remote).execute({
3727
+ ...input,
3728
+ clientToken,
3729
+ request: {
3730
+ kind: "duplicate",
3731
+ nodeIds,
3732
+ destination
3733
+ }
3734
+ });
3735
+ },
3736
+ "canvas.find": async () => createFindCanvasComposite(remote).execute(canvasFindInputSchema.parse(offered)),
3737
+ "canvas.remove": async () => createRemoveCanvasNodesComposite(remote).execute({
3738
+ ...canvasRemoveCapabilityInputSchema.parse(offered),
3739
+ clientToken
3740
+ }),
3741
+ "canvas.read": async () => {
3742
+ const legacy = canvasReadCapabilityInputSchema.safeParse(offered);
3743
+ if (legacy.success) return readCanvasReferenceScene(remote, legacy.data);
3744
+ return createReadCanvasComposite(remote).execute(canvasReadInputSchema.parse(offered));
3745
+ },
3746
+ "canvas.updateHtml": async () => createUpdateCanvasHtmlComposite(remote).execute({
3747
+ ...canvasUpdateHtmlCapabilityInputSchema.parse(offered),
3748
+ clientToken
3749
+ })
3750
+ });
3751
+
3752
+ //#endregion
3753
+ //#region src/application/canvas-render-request.use-case.ts
3754
+ const canvasRenderRequest = (input, retryClientToken) => {
3755
+ const reference = parseCanvasReference(input.canvasRef);
3756
+ const selected = reference.nodeIds;
3757
+ if (input.target.kind === "content" && selected.length > 1) throw new CliError("BAD_REQUEST", "Choose an explicit node within this selection.", "Render the selected screens separately; do not broaden to the whole canvas.");
3758
+ const target = input.target.kind === "content" ? selected[0] === void 0 ? reference.pageId === void 0 ? input.target : {
3759
+ kind: "page",
3760
+ pageId: reference.pageId
3761
+ } : {
3762
+ kind: "node",
3763
+ nodeId: selected[0]
3764
+ } : input.target;
3765
+ return {
3766
+ canvasId: reference.canvasId,
3767
+ expectedVersion: input.expectedVersion,
3768
+ target,
3769
+ sourceState: input.sourceState,
3770
+ scale: input.scale,
3771
+ scope: {
3772
+ nodeIds: selected,
3773
+ ...reference.pageId !== void 0 && { pageId: reference.pageId }
3774
+ },
3775
+ outputPath: null,
3776
+ overwrite: false,
3777
+ timeoutMs: input.waitMs,
3778
+ timeoutOutcome: "pending",
3779
+ retryClientToken
3780
+ };
3781
+ };
3782
+
3783
+ //#endregion
3784
+ //#region src/application/render-canvas-batch.composite.ts
3785
+ const targetFailure = (error, target) => {
3786
+ const operation = canvasRenderPendingSchema.shape.operation.safeParse({
3787
+ kind: "canvas-render",
3788
+ canvasId: target.input.canvasId,
3789
+ jobId: error instanceof CliError ? error.fields?.["jobId"] : void 0
3790
+ });
3791
+ const terminal = canvasRenderStateSchema.extract([
3792
+ "failed",
3793
+ "cancelled",
3794
+ "expired"
3795
+ ]).safeParse(error instanceof CliError ? error.fields?.["renderState"] : void 0);
3796
+ return {
3797
+ ...operation.success && { operation: operation.data },
3798
+ state: terminal.success ? terminal.data : "not_confirmed",
3799
+ error: error instanceof CliError ? {
3800
+ code: error.code,
3801
+ message: error.message,
3802
+ remediation: error.remediation,
3803
+ ...error.fields !== void 0 && { fields: error.fields }
3804
+ } : {
3805
+ code: "INTERNAL",
3806
+ message: "This render outcome could not be confirmed.",
3807
+ remediation: "Retry the identical batch and clientToken to recover its native render jobs."
3808
+ }
3809
+ };
3810
+ };
3811
+ const plannedTargets = (request, clientTokens) => {
3812
+ return request.targets.map(({ id, maxOutputPixels, ...target }) => {
3813
+ const retryClientToken = clientTokens.get(id);
3814
+ if (retryClientToken === void 0) throw new TypeError("A batch target has no native render request key.");
3815
+ return {
3816
+ id,
3817
+ maxOutputPixels,
3818
+ input: canvasRenderRequest({
3819
+ ...request,
3820
+ ...target
3821
+ }, retryClientToken)
3822
+ };
3823
+ });
3824
+ };
3825
+ const renderTarget = async (render, target) => {
3826
+ try {
3827
+ const returned = await render.execute({
3828
+ ...target.input,
3829
+ maxOutputPixels: target.maxOutputPixels
3830
+ });
3831
+ const file = canvasRenderFileSchema.safeParse(returned);
3832
+ if (!file.success) return canvasRenderPendingSchema.parse(returned);
3833
+ const pixels = file.data.width * file.data.height;
3834
+ if (!Number.isSafeInteger(pixels) || pixels <= 0 || target.maxOutputPixels !== void 0 && pixels > target.maxOutputPixels) throw new CliError("INTERNAL", "The render exceeded its allocated pixel budget.", "Update the API and renderer together, then retry.", { reason: "RENDER_BUDGET_UNSUPPORTED" });
3835
+ return file.data;
3836
+ } catch (error) {
3837
+ return targetFailure(error, target);
3838
+ }
3839
+ };
3840
+ const createRenderCanvasBatchComposite = (render) => ({ execute: async (offered, clientTokens) => {
3841
+ const request = canvasRenderBatchRequestSchema.parse(offered);
3842
+ const targets = plannedTargets(request, clientTokens);
3843
+ const results = [];
3844
+ let renderedPixels = 0;
3845
+ for (const target of targets) {
3846
+ const outcome = await renderTarget(render, target);
3847
+ if ("jobId" in outcome) renderedPixels += outcome.width * outcome.height;
3848
+ results.push({
3849
+ id: target.id,
3850
+ target: target.input.target,
3851
+ ...target.maxOutputPixels !== void 0 && { maxOutputPixels: target.maxOutputPixels },
3852
+ outcome
3853
+ });
3854
+ }
3855
+ const first = targets[0];
3856
+ if (first === void 0) throw new TypeError("A render batch requires at least one target.");
3857
+ return {
3858
+ kind: "canvas-render-batch",
3859
+ canvasId: first.input.canvasId,
3860
+ requestedVersion: request.expectedVersion,
3861
+ complete: results.every((result) => "jobId" in result.outcome),
3862
+ renderedPixels,
3863
+ results,
3864
+ next: ["Inspect each delivered image alongside its target id. Collect pending images with operation_status and includeImage true. Retry uncertain outcomes with the identical batch and clientToken."]
3865
+ };
3866
+ } });
3867
+
3868
+ //#endregion
3869
+ //#region src/infrastructure/canvas-render-invocation.adapter.ts
3870
+ const renderFor = (input) => createRenderCanvasComposite(input.remote, createRenderFileAdapter(input.configDirectory), input.now ?? (() => /* @__PURE__ */ new Date()), input.progress ?? (() => null));
3871
+ const renderCanvas = async (dependencies, offered, retryClientToken) => {
3872
+ const batch = canvasRenderBatchRequestSchema.safeParse(offered);
3873
+ if (batch.success) {
3874
+ dependencies.mutationKey.select(retryClientToken, true);
3875
+ const clientTokens = new Map(batch.data.targets.map((target) => [target.id, dependencies.mutationKey.current("canvas.render.create", {
3876
+ batch: {
3877
+ canvasRef: batch.data.canvasRef,
3878
+ expectedVersion: batch.data.expectedVersion,
3879
+ targets: batch.data.targets
3880
+ },
3881
+ targetId: target.id
3882
+ })]));
3883
+ const render = renderFor(dependencies);
3884
+ return createRenderCanvasBatchComposite({ execute: async (input) => {
3885
+ dependencies.mutationKey.select(input.retryClientToken, false);
3886
+ return render.execute(input);
3887
+ } }).execute(batch.data, clientTokens);
3888
+ }
3889
+ const request = canvasRenderRequestSchema.safeParse(offered);
3890
+ if (request.success) return renderFor(dependencies).execute(canvasRenderRequest(request.data, retryClientToken));
3891
+ const input = canvasRenderCapabilityInputSchema.parse(offered);
3892
+ return renderFor(dependencies).execute({
3893
+ ...input,
3894
+ retryClientToken
3895
+ });
3896
+ };
3897
+ const createCanvasRenderInvocationAdapter = (input) => ({
3898
+ render: renderFor(input),
3899
+ execute: async (offered, clientToken) => renderCanvas(input, offered, clientToken)
3900
+ });
3901
+
3902
+ //#endregion
3903
+ //#region src/infrastructure/prototype-zip.adapter.ts
3904
+ const NORMALIZED_MTIME = /* @__PURE__ */ new Date("1980-01-01T00:00:00.000Z");
3905
+ const REGULAR_FILE_MODE = 33188;
3906
+ const ZIP64_ENTRY_FLOOR = 65535;
3907
+ const SMALL_FILE_BYTES = 128;
3908
+ const READ_BATCH_SIZE = 32;
3909
+ const badRequest$1 = (message, remediation) => new CliError("BAD_REQUEST", message, remediation);
3910
+ const hashingTransform = (source, completed) => {
3911
+ const hash = createHash("sha256");
3912
+ let bytes = 0;
3913
+ return new Transform({
3914
+ transform: (chunk, _encoding, callback) => {
3915
+ bytes += chunk.byteLength;
3916
+ hash.update(chunk);
3917
+ callback(null, chunk);
3918
+ },
3919
+ flush: (callback) => {
3920
+ if (bytes !== source.bytes) {
3921
+ callback(/* @__PURE__ */ new Error(`prototype file ${source.path} changed while it was packaged`));
3922
+ return;
3923
+ }
3924
+ try {
3925
+ completed({
3926
+ path: source.path,
3927
+ contentType: source.contentType,
3928
+ bytes,
3929
+ sha256: hash.digest("hex")
3930
+ });
3931
+ callback();
3932
+ } catch (error) {
3933
+ callback(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype manifest failed"));
3934
+ }
3935
+ }
3936
+ });
3937
+ };
3938
+ const addManifest = (input) => {
3939
+ const manifest = prototypeArtifactManifestSchema.parse({
3940
+ version: 1,
3941
+ entryPath: input.entryPath,
3942
+ files: input.files.map((file) => input.completed.get(file.path))
3943
+ });
3944
+ const body = Buffer.from(JSON.stringify(manifest), "utf8");
3945
+ if (input.limits.manifestBytes !== void 0 && body.byteLength > input.limits.manifestBytes) throw badRequest$1("The prototype manifest is too large.", `Shorten paths or reduce metadata below ${String(input.limits.manifestBytes)} bytes.`);
3946
+ input.zip.addBuffer(body, PROTOTYPE_ARTIFACT_MANIFEST_PATH, {
3947
+ mtime: NORMALIZED_MTIME,
3948
+ mode: REGULAR_FILE_MODE,
3949
+ compress: true,
3950
+ forceDosTimestamp: true
3951
+ });
3952
+ input.zip.end({
3953
+ forceZip64Format: input.files.length >= ZIP64_ENTRY_FLOOR,
3954
+ comment: ""
3955
+ });
3956
+ return manifest;
3957
+ };
3958
+ const addPrototypeFile = (zip, input, complete) => {
3959
+ const { source, content } = input;
3960
+ const options = {
3961
+ mtime: NORMALIZED_MTIME,
3962
+ mode: REGULAR_FILE_MODE,
3963
+ compress: content === null,
3964
+ forceDosTimestamp: true
3965
+ };
3966
+ if (content === null) {
3967
+ zip.addReadStreamLazy(source.path, {
3968
+ ...options,
3969
+ size: source.bytes
3970
+ }, (callback) => {
3971
+ const stream = createReadStream(source.absolutePath);
3972
+ const hashing = hashingTransform(source, complete);
3973
+ stream.on("error", (error) => hashing.destroy(error));
3974
+ hashing.on("error", (error) => zip.emit("error", error));
3975
+ hashing.on("close", () => stream.destroy());
3976
+ callback(null, stream.pipe(hashing));
3977
+ });
3978
+ return;
3979
+ }
3980
+ if (content.byteLength !== source.bytes) throw new Error(`prototype file ${source.path} changed while it was packaged`);
3981
+ zip.addBuffer(content, source.path, options);
3982
+ complete({
3983
+ path: source.path,
3984
+ contentType: source.contentType,
3985
+ bytes: content.byteLength,
3986
+ sha256: createHash("sha256").update(content).digest("hex")
3987
+ });
3988
+ };
3989
+ const addAvailableFiles = (zip, batch, complete) => {
3990
+ const included = [];
3991
+ for (const available of batch) {
3992
+ if (available === null) continue;
3993
+ addPrototypeFile(zip, available, complete);
3994
+ included.push(available.source);
3995
+ }
3996
+ return included;
3997
+ };
3998
+ const addPrototypeFiles = async (zip, input, complete) => {
3999
+ const included = [];
4000
+ for (let offset = 0; offset < input.files.length; offset += READ_BATCH_SIZE) {
4001
+ const batch = await Promise.all(input.files.slice(offset, offset + READ_BATCH_SIZE).map(async (source) => {
4002
+ try {
4003
+ const content = source.bytes <= SMALL_FILE_BYTES ? await readFile(source.absolutePath) : null;
4004
+ if (content === null) await access(source.absolutePath, constants.R_OK);
4005
+ if (content !== null && content.byteLength !== source.bytes) throw new Error(`prototype file ${source.path} changed while it was packaged`);
4006
+ return {
4007
+ source,
4008
+ content
4009
+ };
4010
+ } catch (error) {
4011
+ if (source.path === input.entryPath) throw error;
4012
+ return null;
4013
+ }
4014
+ }));
4015
+ included.push(...addAvailableFiles(zip, batch, complete));
4016
+ }
4017
+ return included;
4018
+ };
4019
+ const createPrototypeZipAdapter = async (input) => {
4020
+ const zip = new ZipFile();
4021
+ const hash = createHash("sha256");
4022
+ const hashing = new Transform({ transform: (chunk, _encoding, callback) => {
4023
+ hash.update(chunk);
4024
+ callback(null, chunk);
4025
+ } });
4026
+ const completed = /* @__PURE__ */ new Map();
4027
+ const packaged = { manifest: null };
4028
+ const output = pipeline(zip.outputStream, hashing, createWriteStream(input.artifactPath));
4029
+ zip.on("error", (error) => hashing.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype ZIP failed")));
4030
+ let included = null;
4031
+ const finish = () => {
4032
+ if (included !== null && packaged.manifest === null && completed.size === included.length) packaged.manifest = addManifest({
4033
+ zip,
4034
+ completed,
4035
+ ...input,
4036
+ files: included
4037
+ });
4038
+ };
4039
+ const complete = (file) => {
4040
+ completed.set(file.path, file);
4041
+ finish();
4042
+ };
4043
+ try {
4044
+ included = await addPrototypeFiles(zip, input, complete);
4045
+ finish();
4046
+ } catch (error) {
4047
+ hashing.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype ZIP failed"));
4048
+ await output;
4049
+ }
4050
+ await output;
4051
+ if (packaged.manifest === null) throw new Error("prototype ZIP completed without a manifest");
4052
+ const artifactStats = await stat(input.artifactPath);
4053
+ if (artifactStats.size > input.limits.artifactBytes) throw badRequest$1("The packaged prototype artifact is too large.", `This environment accepts ${String(input.limits.artifactBytes)} compressed bytes.`);
4054
+ return {
4055
+ manifest: packaged.manifest,
4056
+ bytes: artifactStats.size,
4057
+ sha256: hash.digest("hex"),
4058
+ unavailableFileCount: input.files.length - completed.size
4059
+ };
4060
+ };
4061
+
4062
+ //#endregion
4063
+ //#region src/infrastructure/prototype-artifact.adapter.ts
4064
+ const CONTENT_TYPES = {
4065
+ ".avif": "image/avif",
4066
+ ".css": "text/css; charset=utf-8",
4067
+ ".gif": "image/gif",
4068
+ ".html": "text/html; charset=utf-8",
4069
+ ".ico": "image/x-icon",
4070
+ ".jpeg": "image/jpeg",
4071
+ ".jpg": "image/jpeg",
4072
+ ".js": "text/javascript; charset=utf-8",
4073
+ ".json": "application/json; charset=utf-8",
4074
+ ".map": "application/json; charset=utf-8",
4075
+ ".mjs": "text/javascript; charset=utf-8",
4076
+ ".mp3": "audio/mpeg",
4077
+ ".mp4": "video/mp4",
4078
+ ".ogg": "audio/ogg",
4079
+ ".otf": "font/otf",
4080
+ ".png": "image/png",
4081
+ ".svg": "image/svg+xml",
4082
+ ".ttf": "font/ttf",
4083
+ ".txt": "text/plain; charset=utf-8",
4084
+ ".wasm": "application/wasm",
4085
+ ".webm": "video/webm",
4086
+ ".webp": "image/webp",
4087
+ ".woff": "font/woff",
4088
+ ".woff2": "font/woff2",
4089
+ ".xml": "application/xml"
4090
+ };
4091
+ const contentTypeOf = (filePath) => CONTENT_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";
4092
+ const statsFor = async (filePath) => {
4093
+ try {
4094
+ return await stat(filePath);
4095
+ } catch {
4096
+ return null;
4097
+ }
4098
+ };
4099
+ const byteLength = (value) => Buffer.byteLength(value, "utf8");
4100
+ const badRequest = (message, remediation) => new CliError("BAD_REQUEST", message, remediation);
4101
+ const validatePath = (relativePath, limits) => {
4102
+ if (!prototypeArtifactPathSchema.safeParse(relativePath).success) throw badRequest(`Cannot package the prototype path ${relativePath}.`, "Use portable relative NFC paths outside the reserved __enhance directory.");
4103
+ if (byteLength(relativePath) > limits.pathBytes) throw badRequest(`The prototype path ${relativePath} is too long.`, `Shorten it to at most ${String(limits.pathBytes)} UTF-8 bytes.`);
4104
+ };
4105
+ const walk = async (root, directory, ancestors, options) => {
4106
+ const { limits, unavailable } = options;
4107
+ const resolvedDirectory = await realpath(directory);
4108
+ if (ancestors.has(resolvedDirectory)) {
4109
+ unavailable();
4110
+ return [];
4111
+ }
4112
+ const nextAncestors = new Set(ancestors).add(resolvedDirectory);
4113
+ const { readdir } = await import("node:fs/promises");
4114
+ const entries = await readdir(directory, { withFileTypes: true });
4115
+ const files = [];
4116
+ const orderedEntries = entries.toSorted((left, right) => left.name.localeCompare(right.name));
4117
+ for (const entry of orderedEntries) {
4118
+ const absolutePath = path.join(directory, entry.name);
4119
+ const stats = await statsFor(absolutePath);
4120
+ if (stats?.isDirectory() === true) {
4121
+ try {
4122
+ files.push(...await walk(root, absolutePath, nextAncestors, options));
4123
+ } catch {
4124
+ unavailable();
4125
+ }
4126
+ continue;
4127
+ }
4128
+ if (stats?.isFile() !== true) {
4129
+ unavailable();
4130
+ continue;
4131
+ }
4132
+ const relativePath = path.relative(root, absolutePath).split(path.sep).join("/").normalize("NFC");
4133
+ validatePath(relativePath, limits);
4134
+ files.push({
4135
+ absolutePath,
4136
+ path: relativePath,
4137
+ bytes: Number(stats.size),
4138
+ contentType: contentTypeOf(absolutePath)
4139
+ });
4140
+ }
4141
+ return files;
4142
+ };
4143
+ const validateSources = (files, entryPath, limits) => {
4144
+ if (files.length === 0) throw badRequest("The prototype build is empty.", "Build the app before publishing it.");
4145
+ if (limits.fileCount !== void 0 && files.length > limits.fileCount) throw badRequest(`The prototype has ${String(files.length)} files.`, `This environment currently accepts ${String(limits.fileCount)} files per deployment.`);
4146
+ const folded = /* @__PURE__ */ new Set();
4147
+ let totalBytes = 0;
4148
+ for (const file of files) {
4149
+ const key = foldPrototypeArtifactPath(file.path);
4150
+ if (folded.has(key)) throw badRequest(`The prototype path ${file.path} collides by case or Unicode normalization.`, "Rename one of the colliding files so the build is portable.");
4151
+ folded.add(key);
4152
+ if (file.bytes > limits.fileBytes) throw badRequest(`The prototype file ${file.path} is too large.`, `This environment accepts ${String(limits.fileBytes)} bytes in one runtime file.`);
4153
+ totalBytes += file.bytes;
4154
+ if (limits.expandedBytes !== void 0 && totalBytes > limits.expandedBytes) throw badRequest("The prototype build is too large.", `This environment accepts ${String(limits.expandedBytes)} expanded bytes.`);
4155
+ }
4156
+ const entry = files.find((file) => file.path === entryPath);
4157
+ if (entry === void 0) throw badRequest(`The prototype entry ${entryPath} is missing.`, "Pass --entry with an HTML file inside the build directory.");
4158
+ if (!entry.contentType.startsWith("text/html")) throw badRequest(`The prototype entry ${entryPath} is not HTML.`, "Pass an HTML entry file such as index.html.");
4159
+ };
4160
+ const reportPackaging = (fileCount, unavailableFileCount) => {
4161
+ try {
4162
+ performance$1.mark("enhance.prototype.packaging", { detail: {
4163
+ fileCount,
4164
+ unavailableFileCount
4165
+ } });
4166
+ } catch {}
4167
+ };
4168
+ const packageArtifact = async (input) => {
4169
+ const root = path.resolve(input.directory);
4170
+ const rootStats = await statsFor(root);
4171
+ if (rootStats === null) throw new CliError("NOT_FOUND", `The prototype directory ${root} does not exist.`, "Build the app or pass the correct unpacked build directory.");
4172
+ if (!rootStats.isDirectory()) throw badRequest(`${root} is not an unpacked build directory.`, "Pass the build directory; the CLI creates the ZIP artifact automatically.");
4173
+ const entryPath = input.entryPath.split(path.sep).join("/").normalize("NFC");
4174
+ validatePath(entryPath, input.limits);
4175
+ let unavailableFileCount = 0;
4176
+ const files = await walk(root, root, /* @__PURE__ */ new Set(), {
4177
+ limits: input.limits,
4178
+ unavailable: () => {
4179
+ unavailableFileCount += 1;
4180
+ }
4181
+ });
4182
+ validateSources(files, entryPath, input.limits);
4183
+ const tempDirectory = await mkdtemp(path.join(tmpdir(), "enhance-prototype-artifact-"));
4184
+ const artifactPath = path.join(tempDirectory, "artifact.zip");
4185
+ try {
4186
+ const packaged = await createPrototypeZipAdapter({
4187
+ artifactPath,
4188
+ files,
4189
+ entryPath,
4190
+ limits: input.limits
4191
+ });
4192
+ unavailableFileCount += packaged.unavailableFileCount;
4193
+ reportPackaging(packaged.manifest.files.length, unavailableFileCount);
4194
+ return {
4195
+ identity: {
4196
+ protocolVersion: 1,
4197
+ format: "zip",
4198
+ bytes: packaged.bytes,
4199
+ sha256: packaged.sha256,
4200
+ fileCount: packaged.manifest.files.length,
4201
+ expandedBytes: packaged.manifest.files.reduce((total, file) => total + file.bytes, 0)
4202
+ },
4203
+ manifest: packaged.manifest,
4204
+ open: () => createReadStream(artifactPath),
4205
+ dispose: async () => rm(tempDirectory, { recursive: true })
4206
+ };
4207
+ } catch (error) {
4208
+ await rm(tempDirectory, { recursive: true });
4209
+ throw error;
4210
+ }
4211
+ };
4212
+ const createPrototypeArtifactAdapter = (directory) => ({ package: async (input) => {
4213
+ if (directory === void 0) throw badRequest("No build directory was selected.", "Select a build before publishing.");
4214
+ return packageArtifact({
4215
+ ...input,
4216
+ directory
4217
+ });
4218
+ } });
4219
+
4220
+ //#endregion
4221
+ //#region src/infrastructure/capability-invocation.adapter.ts
4222
+ const applyCanvas = async (dependencies, offered) => {
4223
+ const input = canvasApplyCapabilityInputSchema.parse(offered);
4224
+ return createApplyCanvasComposite(dependencies.remote).execute({
4225
+ ...input,
4226
+ mutationId: dependencies.mutationKey.current("canvas.applyOperations", input)
4227
+ });
4228
+ };
4229
+ const writeCanvasHtml = async (dependencies, offered) => {
4230
+ const input = canvasWriteHtmlCapabilityInputSchema.parse(offered);
4231
+ return createWriteHtmlCanvasComposite(dependencies.remote, createCanvasRenderInvocationAdapter(dependencies).render).execute({
4232
+ ...input,
4233
+ renderClientToken: dependencies.mutationKey.current("canvas.render.create", { purpose: "write-html-review" })
4234
+ });
4235
+ };
4236
+ const insertCanvasHtml = async (dependencies, offered, clientToken) => {
4237
+ const input = canvasInsertHtmlCapabilityInputSchema.parse(offered);
4238
+ const reference = parseCanvasReference(input.canvasRef);
4239
+ return createWriteHtmlCanvasComposite(dependencies.remote, createCanvasRenderInvocationAdapter(dependencies).render).execute({
4240
+ canvasId: reference.canvasId,
4241
+ pageId: reference.pageId,
4242
+ selectionNodeIds: reference.nodeIds,
4243
+ targetNodeId: input.destination.parentNodeId,
4244
+ mode: "insert-children",
4245
+ html: input.html,
4246
+ baseVersion: input.baseVersion,
4247
+ revisionPolicy: "strict",
4248
+ responseMode: "bounded",
4249
+ review: "none",
4250
+ renderClientToken: clientToken,
4251
+ renderOutputPath: null,
4252
+ overwriteRender: false,
4253
+ renderScale: 1,
4254
+ renderTimeoutMs: input.waitMs
4255
+ });
4256
+ };
4257
+ const readCommentAttention = async (dependencies, offered) => {
4258
+ const input = commentAttentionCapabilityInputSchema.parse(offered);
4259
+ return dependencies.remote.query("comment.list", {
4260
+ canvasId: input.canvasId,
4261
+ filter: "open",
4262
+ agentActionable: false
4263
+ });
4264
+ };
4265
+ const publishPrototype = async (dependencies, offered, retryClientToken) => {
4266
+ const input = prototypePublishCapabilityInputSchema.parse(offered);
4267
+ return createPublishPrototypeComposite(dependencies.remote, createPrototypeArtifactAdapter(input.directory)).execute({
4268
+ ...input,
4269
+ clientToken: retryClientToken
4270
+ });
4271
+ };
4272
+ const snapshotRecording = async (dependencies, offered, retryClientToken) => {
4273
+ const input = recordingSnapshotCapabilityInputSchema.parse(offered);
4274
+ return createSnapshotRecordingComposite(dependencies.remote, dependencies.progress ?? (() => null)).execute({
4275
+ ...input,
4276
+ retryClientToken
4277
+ });
4278
+ };
4279
+ const readTranscript = async (dependencies, offered) => {
4280
+ const input = transcriptReadCapabilityInputSchema.parse(offered);
4281
+ return createReadTranscriptComposite(dependencies.remote).execute(input);
4282
+ };
4283
+ const editCanvas = async (dependencies, offered) => {
4284
+ const input = canvasEditCapabilityInputSchema.parse(offered);
4285
+ const reference = parseCanvasReference(input.canvas);
4286
+ return createEditCanvasComposite(dependencies.remote).execute({
4287
+ ...reference,
4288
+ baseVersion: input.baseVersion,
4289
+ edits: input.edits,
4290
+ mutationId: dependencies.mutationKey.current("canvas.applyOperations", input)
4291
+ });
4292
+ };
4293
+ const readOperationStatus = async (dependencies, offered) => createReadOperationStatusComposite(dependencies.remote, createRenderFileAdapter(dependencies.configDirectory)).execute(operationStatusInputSchema.parse(offered));
4294
+ const invokeComposite = async (dependencies, capabilityId, offered, retryClientToken) => {
4295
+ const execute = {
4296
+ ...createCanvasExchangeInvocationAdapter(dependencies.remote, offered, retryClientToken),
4297
+ "canvas.importAsset": async () => {
4298
+ const input = canvasAssetImportCapabilityInputSchema.parse(offered);
4299
+ return createImportCanvasAssetComposite(dependencies.remote, createCanvasAssetFileAdapter(input.source.path)).execute({
4300
+ canvasRef: input.canvasRef,
4301
+ clientToken: retryClientToken
4302
+ });
4303
+ },
4304
+ "operation.status": async () => readOperationStatus(dependencies, offered),
4305
+ "canvas.edit": async () => editCanvas(dependencies, offered),
4306
+ "canvas.apply": async () => applyCanvas(dependencies, offered),
4307
+ "canvas.render": async () => createCanvasRenderInvocationAdapter(dependencies).execute(offered, retryClientToken),
4308
+ "canvas.writeHtml": async () => writeCanvasHtml(dependencies, offered),
4309
+ "canvas.insertHtml": async () => insertCanvasHtml(dependencies, offered, retryClientToken),
4310
+ "canvas.capture": async () => captureCanvasRecording(dependencies.remote, offered, retryClientToken),
4311
+ "canvas.makeEditable": async () => makeCanvasEditable(dependencies.remote, offered),
4312
+ "comment.attention": async () => readCommentAttention(dependencies, offered),
4313
+ "prototype.publishCanvas": async () => {
4314
+ const input = canvasPrototypeCapabilityInputSchema.parse(offered);
4315
+ return createPublishCanvasPrototypeComposite(dependencies.remote, createPrototypeArtifactAdapter(input.source.kind === "directory" ? input.source.directory : void 0)).execute({
4316
+ ...input,
4317
+ source: input.source.kind === "directory" ? {
4318
+ ...input.source,
4319
+ kind: "build"
4320
+ } : input.source,
4321
+ clientToken: retryClientToken
4322
+ });
4323
+ },
4324
+ "prototype.publish": async () => publishPrototype(dependencies, offered, retryClientToken),
4325
+ "recording.snapshot": async () => snapshotRecording(dependencies, offered, retryClientToken),
4326
+ "transcript.read": async () => readTranscript(dependencies, offered)
4327
+ }[capabilityId];
4328
+ if (execute === void 0) throw new TypeError(`${capabilityId} has no composite execution`);
4329
+ return execute();
4330
+ };
4331
+ const createCapabilityInvocationAdapter = (input) => ({ invoke: async ({ capability, arguments: offered, clientToken }) => {
4332
+ const parsed = capability.inputSchema.parse(offered);
4333
+ const selectedClientToken = clientToken ?? randomUUID();
4334
+ input.mutationKey.select(selectedClientToken, capability.idempotency === "composite");
4335
+ if (capability.execution.kind === "composite") return invokeComposite(input, capability.id, parsed, selectedClientToken);
4336
+ return capability.operation === "query" ? input.remote.query(capability.execution.procedure, parsed) : input.remote.mutate(capability.execution.procedure, parsed);
4337
+ } });
4338
+
4339
+ //#endregion
4340
+ //#region src/infrastructure/oauth-loopback.adapter.ts
4341
+ const CALLBACK_PATH = "/callback";
4342
+ const AUTHORIZATION_TIMEOUT_MS = 12e4;
4343
+ const ENTROPY_BYTES = 32;
4344
+ const HTTP_OK = 200;
4345
+ const HTTP_BAD_REQUEST = 400;
4346
+ const HTTP_NOT_FOUND = 404;
4347
+ const SUCCESS_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>";
4348
+ const endpoint = (issuer, path) => new URL(path, issuer.endsWith("/") ? issuer : `${issuer}/`);
4349
+ const launchBrowser = (url) => {
4350
+ const command = process.platform === "darwin" ? {
4351
+ executable: "open",
4352
+ arguments: [url]
4353
+ } : process.platform === "win32" ? {
4354
+ executable: "rundll32.exe",
4355
+ arguments: ["url.dll,FileProtocolHandler", url]
4356
+ } : {
4357
+ executable: "xdg-open",
4358
+ arguments: [url]
4359
+ };
4360
+ const child = spawn(command.executable, command.arguments, {
4361
+ detached: true,
4362
+ stdio: "ignore"
4363
+ });
4364
+ child.once("error", () => false);
4365
+ child.unref();
4366
+ };
4367
+ const handleCallback = (input, request, response) => {
4368
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
4369
+ if (request.method !== "GET" || url.pathname !== CALLBACK_PATH) {
4370
+ response.writeHead(HTTP_NOT_FOUND).end();
4371
+ return;
4372
+ }
4373
+ if (url.searchParams.get("state") !== input.state) {
4374
+ response.writeHead(HTTP_BAD_REQUEST).end("The OAuth state did not match. Return to the terminal and retry.");
4375
+ return;
4376
+ }
4377
+ const error = url.searchParams.get("error");
4378
+ const received = url.searchParams.get("code");
4379
+ if (error !== null || received === null || received === "") {
4380
+ response.writeHead(HTTP_BAD_REQUEST).end("Enhance authentication was not approved.");
4381
+ input.completion.reject(new Error(error ?? "the authorization response carried no code"));
4382
+ return;
4383
+ }
4384
+ response.writeHead(HTTP_OK, { "content-type": "text/html; charset=utf-8" }).end(SUCCESS_PAGE);
4385
+ input.completion.resolve(received);
4386
+ };
4387
+ const authorizeUrl = (input) => {
4388
+ const authorize = endpoint(input.issuer, "oauth/authorize");
4389
+ authorize.search = new URLSearchParams({
4390
+ response_type: "code",
4391
+ client_id: input.clientId,
4392
+ redirect_uri: input.redirectUri,
4393
+ scope: input.scope,
4394
+ state: input.state,
4395
+ code_challenge: input.challenge,
4396
+ code_challenge_method: "S256"
4397
+ }).toString();
4398
+ return authorize.href;
4399
+ };
4400
+ const authorizationCode = async (input) => {
4401
+ input.signal?.throwIfAborted();
4402
+ const completion = Promise.withResolvers();
4403
+ const server = createServer((request, response) => {
4404
+ handleCallback({
4405
+ state: input.state,
4406
+ completion
4407
+ }, request, response);
4408
+ });
4409
+ await new Promise((resolve, reject) => {
4410
+ server.once("error", reject);
4411
+ server.listen(0, "127.0.0.1", resolve);
4412
+ });
4413
+ const address = server.address();
4414
+ if (address === null || typeof address === "string") {
4415
+ server.close();
4416
+ throw new Error("the OAuth callback listener has no TCP port");
4417
+ }
4418
+ const redirectUri = `http://127.0.0.1:${String(address.port)}${CALLBACK_PATH}`;
4419
+ const url = authorizeUrl({
4420
+ ...input,
4421
+ redirectUri
4422
+ });
4423
+ const abort = () => {
4424
+ completion.reject(/* @__PURE__ */ new Error("browser authorization cancelled"));
4425
+ };
4426
+ input.signal?.addEventListener("abort", abort, { once: true });
4427
+ const timeout = setTimeout(() => {
4428
+ completion.reject(/* @__PURE__ */ new Error("browser authorization timed out"));
4429
+ }, AUTHORIZATION_TIMEOUT_MS);
4430
+ try {
4431
+ input.signal?.throwIfAborted();
4432
+ input.onReady(url);
4433
+ if (input.openBrowser) launchBrowser(url);
4434
+ return {
4435
+ code: await completion.promise,
4436
+ redirectUri
4437
+ };
4438
+ } finally {
4439
+ clearTimeout(timeout);
4440
+ input.signal?.removeEventListener("abort", abort);
4441
+ await new Promise((resolve) => {
4442
+ server.close(() => {
4443
+ resolve();
4444
+ });
4445
+ });
4446
+ }
4447
+ };
4448
+ const createOauthLoopbackAdapter = (remote) => ({ authorize: async (input) => {
4449
+ try {
4450
+ const verifier = randomBytes(ENTROPY_BYTES).toString("base64url");
4451
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
4452
+ const state = randomBytes(ENTROPY_BYTES).toString("base64url");
4453
+ const authorized = await authorizationCode({
4454
+ ...input,
4455
+ challenge,
4456
+ state
4457
+ });
4458
+ return await remote.exchangeOauthCode({
4459
+ issuer: input.issuer,
4460
+ clientId: input.clientId,
4461
+ code: authorized.code,
4462
+ redirectUri: authorized.redirectUri,
4463
+ verifier
4464
+ });
4465
+ } catch (error) {
4466
+ throw new CliError("UNAUTHORIZED", error instanceof Error ? `Browser authentication failed: ${error.message}.` : "Browser authentication failed.", "Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.");
4467
+ }
4468
+ } });
4469
+
4470
+ //#endregion
4471
+ //#region src/infrastructure/environment-profile.lib.ts
4472
+ const explicitValue = (value) => value === void 0 || value === "" ? void 0 : value;
4473
+ const resolveCliConfig = (variables, homeDirectory, release) => {
4474
+ const requestedEnvironment = explicitValue(variables.ENHANCE3_ENVIRONMENT);
4475
+ if (requestedEnvironment !== void 0 && requestedEnvironment !== release.environment) throw new TypeError(`the Enhance ${release.environment} CLI cannot target ${requestedEnvironment}`);
4476
+ const requestedApi = explicitValue(variables.ENHANCE3_API_URL);
4477
+ const expectedConfigDirectory = path.join(homeDirectory, ".config", release.configDirectoryName);
4478
+ const requestedConfigDirectory = explicitValue(variables.ENHANCE3_CONFIG_DIR);
4479
+ if (release.environment === "development") {
4480
+ if (requestedApi !== void 0 && requestedApi !== release.apiUrl) throw new TypeError(`Enhance development cannot use ${requestedApi}`);
4481
+ if (requestedConfigDirectory !== void 0 && path.resolve(requestedConfigDirectory) !== path.resolve(expectedConfigDirectory)) throw new TypeError(`Enhance development credentials must stay in ${expectedConfigDirectory}`);
4482
+ }
4483
+ return {
4484
+ apiUrl: requestedApi ?? release.apiUrl,
4485
+ commandName: release.commandName,
4486
+ configDirectory: requestedConfigDirectory ?? expectedConfigDirectory,
4487
+ mcpServiceName: release.mcpServiceName
4488
+ };
4489
+ };
4490
+
4491
+ //#endregion
4492
+ //#region src/infrastructure/remote-mcp.config.ts
4493
+ const remoteMcpConfigSchema = z.object({
4494
+ ENHANCE_MCP_PROFILE: z.enum(["legacy", "canvas"]).default("legacy"),
4495
+ ENHANCE_MCP_READ_ONLY: z.enum(["true", "false"]).default("false").transform((value) => value === "true"),
4496
+ MCP_CANVAS_PATH: z.string().startsWith("/").optional(),
4497
+ MCP_CANVAS_READ_ONLY: z.enum(["true", "false"]).default("false").transform((value) => value === "true"),
4498
+ PORT: z.coerce.number().int().min(1).max(65535).default(3e3),
4499
+ MCP_HOST: z.string().min(1).default("0.0.0.0"),
4500
+ ENHANCE_API_URL: z.url(),
4501
+ MCP_AUTH_ISSUER: z.url(),
4502
+ MCP_RESOURCE_URL: z.url(),
4503
+ MCP_SERVICE_DOCUMENTATION_URL: z.url().default("https://enhancelabs.ai"),
4504
+ MCP_ALLOWED_HOSTS: z.string().min(1),
4505
+ MCP_FILE_ORIGINS: z.string().default(""),
4506
+ MCP_UI_URL: z.url().optional(),
4507
+ MCP_ALLOWED_ORIGINS: z.string().min(1).default("claude.ai,claude.com")
4508
+ });
4509
+ const readRemoteMcpConfig = (variables) => remoteMcpConfigSchema.parse(variables);
4510
+
4511
+ //#endregion
4512
+ //#region src/infrastructure/environment.config.ts
4513
+ const releaseProfile = {
4514
+ apiUrl: "https://api.enhancelabs.ai",
4515
+ commandName: "enhance",
4516
+ configDirectoryName: "enhance",
4517
+ environment: "production",
4518
+ mcpServiceName: "enhance-mcp"
4519
+ };
4520
+ const readCliEnvironment = () => resolveCliConfig(process.env, homedir(), releaseProfile);
4521
+ const readRemoteMcpEnvironment = () => readRemoteMcpConfig(process.env);
4522
+ const readLocalMcpEnvironment = () => {
4523
+ const profile = z.enum(["legacy", "canvas"]).default("legacy").parse(process.env["ENHANCE_MCP_PROFILE"]);
4524
+ const isReadOnly = z.enum(["true", "false"]).default("false").parse(process.env["ENHANCE_MCP_READ_ONLY"]) === "true";
4525
+ if (isReadOnly && profile !== "canvas") throw new Error("ENHANCE_MCP_READ_ONLY requires the canvas profile.");
4526
+ return {
4527
+ ...readCliEnvironment(),
4528
+ profile,
4529
+ isReadOnly,
4530
+ workflowsDirectory: process.env["ENHANCE_WORKFLOWS_DIR"]
4531
+ };
4532
+ };
4533
+
4534
+ //#endregion
4535
+ //#region src/infrastructure/http-remote.adapter.ts
4536
+ const DIRECT_CLIENT = { path: "direct_cli" };
4537
+ const HEALTH_TIMEOUT_MS = 4e3;
4538
+ const NOT_FOUND_STATUS = 404;
4539
+ const FORBIDDEN_STATUS = 403;
4540
+ const oauthTokenResponseSchema = z.object({ access_token: z.string().min(1) });
4541
+ const networkCodeSchema = z.object({ code: z.string().regex(/^[A-Z][A-Z_0-9]+$/u) });
4542
+ const NETWORK_REMEDIATION = "Check network access and proxy settings for this API, then run enhance doctor again.";
4543
+ const originOf = (input) => new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).origin;
4544
+ const networkReason = (error) => {
4545
+ const parsed = networkCodeSchema.safeParse(error);
4546
+ if (parsed.success) return parsed.data.code;
4547
+ if (error instanceof Error && error.cause !== void 0) return networkReason(error.cause);
4548
+ return error instanceof Error ? error.name : "Network request failed";
4549
+ };
4550
+ const httpFailure = (url, status) => new CliError("INTERNAL", `${originOf(url)} answered HTTP ${String(status)}.`, NETWORK_REMEDIATION);
4551
+ const fetchNetwork = async (input, init) => {
4552
+ try {
4553
+ return await fetch(input, init);
4554
+ } catch (error) {
4555
+ throw new CliError("INTERNAL", `Could not reach ${originOf(input)}: ${networkReason(error)}.`, NETWORK_REMEDIATION);
4556
+ }
4557
+ };
4558
+ const fetchApi = async (input, init) => {
4559
+ const response = await fetchNetwork(input, init);
4560
+ if (!response.ok && response.headers.get("content-type")?.includes("application/json") !== true) throw httpFailure(input, response.status);
4561
+ return response;
4562
+ };
4563
+ const clientFor = (apiUrl, token, idempotencyKey = null, clientMetadata = DIRECT_CLIENT) => createTRPCUntypedClient({ links: [httpLink({
4564
+ url: `${apiUrl}/trpc`,
4565
+ fetch: async (input, init) => fetchApi(input, {
4566
+ ...init,
4567
+ signal: init?.signal ?? null
4568
+ }),
4569
+ headers: {
4570
+ [AGENT_CLIENT_HEADER]: JSON.stringify(clientMetadata),
4571
+ ...token !== null && { authorization: `Bearer ${token}` },
4572
+ ...idempotencyKey !== null && { "x-enhance-idempotency-key": idempotencyKey }
4573
+ }
4574
+ })] });
4575
+ const remoteRequest = async (action) => {
4576
+ try {
4577
+ return await action();
4578
+ } catch (error) {
4579
+ throw toRemoteError(error);
4580
+ }
4581
+ };
4582
+ const download = async (url) => {
4583
+ const response = await fetch(url);
4584
+ if (!response.ok) throw new CliError(response.status === NOT_FOUND_STATUS || response.status === FORBIDDEN_STATUS ? "NOT_FOUND" : "INTERNAL", `Render download answered HTTP ${String(response.status)}.`, "The result may have expired. Request a new render.");
4585
+ return new Uint8Array(await response.arrayBuffer());
4586
+ };
4587
+ const authenticationConfig = async (apiUrl) => {
4588
+ const response = await fetchNetwork(`${apiUrl}/v1/cli-auth`);
4589
+ if (!response.ok) {
4590
+ if (response.status === NOT_FOUND_STATUS) throw new CliError("BAD_REQUEST", "This Enhance API does not support browser authentication.", "Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.");
4591
+ throw new CliError("INTERNAL", `${originOf(apiUrl)} CLI authentication discovery answered HTTP ${String(response.status)}.`, NETWORK_REMEDIATION);
4592
+ }
4593
+ return response.json();
4594
+ };
4595
+ const oauthMetadata = async (issuer) => {
4596
+ const base = issuer.endsWith("/") ? issuer : `${issuer}/`;
4597
+ const response = await fetchNetwork(new URL(".well-known/oauth-authorization-server", base));
4598
+ if (!response.ok) throw httpFailure(issuer, response.status);
4599
+ return response.json();
4600
+ };
4601
+ const exchangeOauthCode = async (input) => {
4602
+ const response = await fetchNetwork(new URL("oauth/token", input.issuer.endsWith("/") ? input.issuer : `${input.issuer}/`), {
4603
+ method: "POST",
4604
+ headers: { "content-type": "application/x-www-form-urlencoded" },
4605
+ body: new URLSearchParams({
4606
+ grant_type: "authorization_code",
4607
+ client_id: input.clientId,
4608
+ code: input.code,
4609
+ redirect_uri: input.redirectUri,
4610
+ code_verifier: input.verifier
4611
+ })
4612
+ });
4613
+ if (!response.ok) throw new CliError("INTERNAL", `${originOf(input.issuer)} token exchange answered HTTP ${String(response.status)}`, NETWORK_REMEDIATION);
4614
+ return oauthTokenResponseSchema.parse(await response.json()).access_token;
4615
+ };
4616
+ const health = async (apiUrl) => {
4617
+ try {
4618
+ const response = await fetchNetwork(`${apiUrl}/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) });
4619
+ return {
4620
+ url: apiUrl,
4621
+ reachable: response.ok,
4622
+ status: response.status,
4623
+ ...!response.ok && { error: httpFailure(apiUrl, response.status).message }
4624
+ };
4625
+ } catch (error) {
4626
+ return {
4627
+ url: apiUrl,
4628
+ reachable: false,
4629
+ status: null,
4630
+ error: error instanceof Error ? error.message : `Could not reach ${originOf(apiUrl)}.`
4631
+ };
4632
+ }
4633
+ };
4634
+ const upload = async (input) => {
4635
+ const isStreaming = !(input.body instanceof Uint8Array);
4636
+ const body = isStreaming ? Readable.toWeb(input.body) : input.body;
4637
+ const request = {
4638
+ method: "PUT",
4639
+ headers: input.headers,
4640
+ body,
4641
+ ...isStreaming && { duplex: "half" }
4642
+ };
4643
+ const response = await fetch(input.url, request);
4644
+ if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
4645
+ const etag = response.headers.get("etag");
4646
+ if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
4647
+ return etag.replaceAll("\"", "");
4648
+ };
4649
+ const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey, clientMetadata = DIRECT_CLIENT) => {
4650
+ const normalized = apiUrl.replace(/\/$/, "");
4651
+ return {
4652
+ authenticationConfig: async () => authenticationConfig(normalized),
4653
+ oauthMetadata,
4654
+ exchangeOauthCode,
4655
+ query: async (path, input, options) => remoteRequest(async () => clientFor(normalized, await credentials.read(), null, clientMetadata).query(path, input, options)),
4656
+ queryWithToken: async (path, input, token) => remoteRequest(async () => clientFor(normalized, token, null, clientMetadata).query(path, input)),
4657
+ mutate: async (procedure, input) => remoteRequest(async () => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input), clientMetadata).mutation(procedure, input)),
4658
+ mutateWithToken: async (procedure, input, token) => remoteRequest(async () => clientFor(normalized, token, null, clientMetadata).mutation(procedure, input)),
4659
+ download,
4660
+ upload,
4661
+ health: async () => health(normalized)
4662
+ };
4663
+ };
4664
+
4665
+ //#endregion
4666
+ //#region src/infrastructure/mutation-key.adapter.ts
4667
+ const ordered = (value) => {
4668
+ if (Array.isArray(value)) return value.map((entry) => ordered(entry));
4669
+ if (typeof value !== "object" || value === null) return value;
4670
+ return Object.fromEntries(Object.entries(value).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, held]) => [key, ordered(held)]));
4671
+ };
4672
+ const childKey = (selected, procedure, input) => {
4673
+ return createHash("sha256").update(`${selected}\0${procedure}\0${JSON.stringify(ordered(input))}`).digest("hex").replace(/^(.{8})(.{4}).(.{3}).(.{3})(.{12}).*$/u, "$1-$2-5$3-8$4-$5");
4674
+ };
4675
+ const createMutationKeyAdapter = () => {
4676
+ let selected = randomUUID();
4677
+ let isComposite = false;
4678
+ return {
4679
+ current: (procedure, input) => isComposite ? childKey(selected, procedure, input) : selected,
4680
+ select: (clientToken, selectedForComposite) => {
4681
+ selected = clientToken ?? randomUUID();
4682
+ isComposite = selectedForComposite;
4683
+ }
4684
+ };
4685
+ };
4686
+
4687
+ //#endregion
4688
+ export { createAuthUseCase as S, assertCanvasReferenceOperations as _, readRemoteMcpEnvironment as a, createCanvasActivityComposite as b, createPrototypeArtifactAdapter as c, createRenderFileAdapter as d, readCanvasReferenceScene as f, createEditCanvasComposite as g, fromCapabilityReference as h, readLocalMcpEnvironment as i, createPublishCanvasPrototypeComposite as l, boundedResultPage as m, createHttpRemoteAdapter as n, createOauthLoopbackAdapter as o, createWriteHtmlCanvasComposite as p, readCliEnvironment as r, createCapabilityInvocationAdapter as s, createMutationKeyAdapter as t, createImportCanvasAssetComposite as u, sceneAtVersion as v, createRenderCanvasComposite as x, createApplyCanvasComposite as y };