@enhance-eng/enhance 0.1.21 → 0.1.25

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