@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.
@@ -1,2046 +0,0 @@
1
- #!/usr/bin/env node
2
- import { A as parseCanvasReference, B as PROTOTYPE_ARTIFACT_MANIFEST_PATH, C as transcriptReadCapabilityInputSchema, Ct as downloadCanvasRenderOutputSchema, D as assertCanvasReferenceOperations, E as assertCanvasReferenceNodes, G as getPrototypePublishStatusOutputSchema, H as createPrototypeArtifactOutputSchema, J as submitPrototypeArtifactOutputSchema, K as prototypeArtifactManifestSchema, M as CliError, N as transcriptOutputSchema, Ot as canvasAxisStyleProperties, Q as createAgentTokenOutputSchema, S as recordingSnapshotCapabilityInputSchema, St as createRecordingSnapshotOutputSchema, Tt as canvasReadableSceneDocumentSchema, U as foldPrototypeArtifactPath, V as attachPrototypeArtifactOutputSchema, W as getPrototypeArtifactCapabilitiesOutputSchema, Y as getMeOutputSchema, Z as cliAuthConfigurationSchema, _ as canvasApplyCapabilityInputSchema, at as beginCanvasActivityOutputSchema, b as commentAttentionCapabilityInputSchema, ct as getCanvasDocumentOutputSchema, dt as applyCanvasOperationsInputSchema, ft as applyCanvasOperationsOutputSchema, gt as getCanvasConversionOutputSchema, ht as createCanvasConversionOutputSchema, j as PartialBatchError, jt as canvasAdditionalStyleSchema, mt as canvasNodeStylePatchSchema, nt as applyCanvasTypographyPatch, q as prototypeArtifactPathSchema, rt as canvasCssTypographyOwners, st as canvasLayoutWithoutCssProperties, ut as MAX_CANVAS_OPERATIONS, v as canvasRenderCapabilityInputSchema, w as canvasEditCapabilityInputSchema, wt as getCanvasRenderOutputSchema, x as prototypePublishCapabilityInputSchema, xt as createCanvasRenderOutputSchema, y as canvasWriteHtmlCapabilityInputSchema } from "./cli-output-identity.lib-a1wTreJ6.mjs";
3
- import { z } from "zod";
4
- import { homedir, tmpdir } from "node:os";
5
- import process from "node:process";
6
- import { generateKeyBetween, generateNKeysBetween } from "fractional-indexing";
7
- import { chmodSync, 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, realpath, rm, stat } from "node:fs/promises";
12
- import { Readable, Transform } from "node:stream";
13
- import { pipeline } from "node:stream/promises";
14
- import { ZipFile } from "yazl";
15
- import { createTRPCUntypedClient, httpLink } from "@trpc/client";
16
- import { spawn } from "node:child_process";
17
- import { createServer } from "node:http";
18
-
19
- //#region ../../packages/contract/src/canvas/canvas-additional-style-patch.lib.ts
20
- const reorderedDeclarations = (declarations, order) => {
21
- const ordered = new Set(order);
22
- const prefix = [];
23
- const groups = /* @__PURE__ */ new Map();
24
- let group = prefix;
25
- for (const declaration of declarations) {
26
- if (ordered.has(declaration.id)) {
27
- group = [];
28
- groups.set(declaration.id, group);
29
- }
30
- group.push(declaration);
31
- }
32
- return [...prefix, ...order.flatMap((id) => groups.get(id) ?? [])];
33
- };
34
- /** Peer rows keep their preceding anchor when an explicitly ordered subset moves. */
35
- const applyCanvasAdditionalStylePatch = (before, patch) => {
36
- const removed = new Set(patch.clear);
37
- const values = new Map((before?.declarations ?? []).filter((item) => !removed.has(item.id)).map((item) => [item.id, item]));
38
- const updates = patch.set ?? [];
39
- for (const declaration of updates) values.set(declaration.id, declaration);
40
- const declarations = Array.from(values, ([, value]) => value);
41
- if (declarations.length === 0 && (patch.empty === "remove" || before === void 0 && patch.empty !== "keep")) return null;
42
- return { declarations: patch.order === void 0 ? declarations : reorderedDeclarations(declarations, patch.order) };
43
- };
44
- const canvasAdditionalStylePatchBetween = (before, after) => {
45
- const previous = new Map(before?.declarations.map((item) => [item.id, item]));
46
- const next = after?.declarations ?? [];
47
- const nextIds = new Set(next.map((item) => item.id));
48
- const clear = Array.from(previous, ([id]) => id).filter((id) => !nextIds.has(id));
49
- const set = next.filter((item) => {
50
- const held = previous.get(item.id);
51
- return held?.property !== item.property || held.value !== item.value || held.enabled !== item.enabled;
52
- });
53
- const patch = {
54
- ...clear.length > 0 && { clear },
55
- ...set.length > 0 && { set }
56
- };
57
- const projected = applyCanvasAdditionalStylePatch(before, patch);
58
- const order = next.map((item) => item.id);
59
- const hasOrderChange = JSON.stringify(projected?.declarations.map((item) => item.id) ?? []) !== JSON.stringify(order);
60
- const empty = after === void 0 && before !== void 0 ? "remove" : before === void 0 && after !== void 0 && next.length === 0 ? "keep" : void 0;
61
- return empty === void 0 && !hasOrderChange && set.length === 0 && clear.length === 0 ? null : {
62
- ...patch,
63
- ...hasOrderChange && { order },
64
- ...empty !== void 0 && { empty }
65
- };
66
- };
67
-
68
- //#endregion
69
- //#region src/application/auth.use-case.ts
70
- const TOKEN = /^enh_[\w-]{43}$/;
71
- const authenticated = (value) => {
72
- const parsed = getMeOutputSchema.parse(value);
73
- 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.");
74
- return {
75
- authenticated: true,
76
- personId: parsed.person.id,
77
- displayName: parsed.person.displayName,
78
- tokenId: parsed.authentication.tokenId,
79
- tokenLabel: parsed.authentication.tokenLabel,
80
- expiresAt: parsed.authentication.expiresAt
81
- };
82
- };
83
- const createAuthUseCase = (credentials, remote, browser) => ({
84
- loginWithToken: async (token) => {
85
- 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.");
86
- const status = authenticated(await remote.queryWithToken("person.me", {}, token));
87
- await credentials.write(token);
88
- return status;
89
- },
90
- loginWithBrowser: async (input) => {
91
- const configuration = cliAuthConfigurationSchema.parse(await remote.authenticationConfig());
92
- 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'.");
93
- const accessToken = await browser.authorize({
94
- issuer: configuration.issuer,
95
- clientId: configuration.clientId,
96
- scope: configuration.scope,
97
- openBrowser: input.openBrowser,
98
- onReady: input.onReady,
99
- ...input.signal !== void 0 && { signal: input.signal }
100
- });
101
- input.signal?.throwIfAborted();
102
- const created = createAgentTokenOutputSchema.parse(await remote.mutateWithToken("person.createAgentToken", {
103
- label: input.label,
104
- expiresAt: null
105
- }, accessToken));
106
- const status = authenticated(await remote.queryWithToken("person.me", {}, created.token));
107
- input.signal?.throwIfAborted();
108
- await credentials.write(created.token);
109
- return status;
110
- },
111
- status: async () => {
112
- if (await credentials.read() === null) throw new CliError("UNAUTHORIZED", `No credential exists at ${credentials.path}.`, "A human must run 'enhance auth login'.");
113
- return authenticated(await remote.query("person.me", {}));
114
- },
115
- logout: async () => ({ loggedOut: await credentials.remove() })
116
- });
117
-
118
- //#endregion
119
- //#region src/application/render-png.use-case.ts
120
- const PNG_SIGNATURE = Uint8Array.from(globalThis.atob("iVBORw0KGgo="), (character) => character.codePointAt(0) ?? 0);
121
- const PNG_HEADER_BYTE_LENGTH = 24;
122
- const PNG_WIDTH_OFFSET = 16;
123
- const PNG_HEIGHT_OFFSET = 20;
124
- const pngDimensions = (body) => {
125
- if (body.byteLength < PNG_HEADER_BYTE_LENGTH || PNG_SIGNATURE.some((byte, index) => body[index] !== byte)) return null;
126
- const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
127
- return {
128
- width: view.getUint32(PNG_WIDTH_OFFSET),
129
- height: view.getUint32(PNG_HEIGHT_OFFSET)
130
- };
131
- };
132
- const downloadVerifiedRenderPng = async (remote, job) => {
133
- const signed = downloadCanvasRenderOutputSchema.safeParse(await remote.query("canvas.render.download", { jobId: job.id }));
134
- if (!signed.success) throw new CliError("INTERNAL", "The API returned an invalid render download response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
135
- const body = await remote.download(signed.data.download.url);
136
- const dimensions = pngDimensions(body);
137
- 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}.`);
138
- return body;
139
- };
140
-
141
- //#endregion
142
- //#region src/application/render-canvas.composite.ts
143
- const POLL_MS$2 = 250;
144
- const PROGRESS_HEARTBEAT_MS$1 = 5e3;
145
- const RENDER_CANVAS_PROCEDURES = ["canvas.render.create", "canvas.render.get"];
146
- 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.");
147
- const terminalFailure$1 = (job) => {
148
- const failure = job.failure;
149
- if (failure === null) return invalidResponse$2("render job");
150
- 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";
151
- 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.";
152
- return new CliError(code, failure.message, remediation, {
153
- jobId: job.id,
154
- reason: failure.reason,
155
- phase: failure.phase
156
- });
157
- };
158
- const wait$2 = async (milliseconds) => new Promise((resolve) => {
159
- globalThis.setTimeout(resolve, milliseconds);
160
- });
161
- const readJob = async (remote, jobId) => {
162
- const parsed = getCanvasRenderOutputSchema.safeParse(await remote.query(RENDER_CANVAS_PROCEDURES[1], { jobId }));
163
- if (!parsed.success) throw invalidResponse$2("render status");
164
- return parsed.data.job;
165
- };
166
- const awaitJob = async (remote, input) => {
167
- const startedAt = Date.now();
168
- let lastReportedAt = 0;
169
- let lastReportedState = "";
170
- let job = input.initial;
171
- while (job.state === "queued" || job.state === "running") {
172
- const currentTime = Date.now();
173
- const stateKey = `${job.state}:${job.phase}`;
174
- if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS$1) {
175
- input.progress({
176
- event: "render.progress",
177
- jobId: job.id,
178
- state: job.state,
179
- phase: job.phase,
180
- elapsedMs: currentTime - startedAt,
181
- timeoutMs: input.timeoutMs,
182
- retryClientToken: input.retryClientToken
183
- });
184
- lastReportedAt = currentTime;
185
- lastReportedState = stateKey;
186
- }
187
- if (currentTime >= input.deadline) 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.`, {
188
- jobId: job.id,
189
- phase: job.phase
190
- });
191
- await wait$2(POLL_MS$2);
192
- job = await readJob(remote, job.id);
193
- }
194
- if (job.state !== "succeeded") throw terminalFailure$1(job);
195
- return job;
196
- };
197
- const nextCommands = (job) => {
198
- const inspect = `enhance canvas inspect --canvas ${job.canvasId}`;
199
- if (job.result.sourceState !== void 0) return [
200
- "Inspect the PNG at path before persisting this moment.",
201
- `enhance recording snapshot --canvas ${job.canvasId} --recording-id ${job.result.sourceState.recordingId} --at-ms ${String(job.result.sourceState.settledAtMs)}`,
202
- inspect
203
- ];
204
- if (job.target.kind !== "node") return [inspect];
205
- return [inspect, `enhance canvas node --canvas ${job.canvasId} --node-id ${job.target.nodeId}`];
206
- };
207
- const resultFrom = (job, written) => ({
208
- jobId: job.id,
209
- canvasId: job.canvasId,
210
- requestedVersion: job.requestedVersion,
211
- loadedVersion: job.result.loadedVersion,
212
- target: job.target,
213
- sourceState: job.result.sourceState ?? null,
214
- bounds: job.result.bounds,
215
- width: job.result.width,
216
- height: job.result.height,
217
- scale: job.result.scale,
218
- contentType: job.result.contentType,
219
- bytes: job.result.bytes,
220
- warnings: job.result.warnings,
221
- path: written.path,
222
- sensitive: true,
223
- cleanup: written.temporary ? "unlink-after-use" : "caller-owned",
224
- ...written.deleteAfter !== null && { deleteAfter: written.deleteAfter.toISOString() },
225
- next: nextCommands(job)
226
- });
227
- const executeRender = async (dependencies, input) => {
228
- const made = createCanvasRenderOutputSchema.safeParse(await dependencies.remote.mutate(RENDER_CANVAS_PROCEDURES[0], {
229
- canvasId: input.canvasId,
230
- ...input.expectedVersion !== null && { expectedVersion: input.expectedVersion },
231
- target: input.target,
232
- ...input.sourceState !== null && { sourceState: input.sourceState },
233
- scale: input.scale,
234
- format: "png"
235
- }));
236
- if (!made.success) throw invalidResponse$2("render creation");
237
- const job = await awaitJob(dependencies.remote, {
238
- initial: made.data.job,
239
- deadline: Date.now() + input.timeoutMs,
240
- timeoutMs: input.timeoutMs,
241
- retryClientToken: input.retryClientToken,
242
- progress: dependencies.progress
243
- });
244
- const body = await downloadVerifiedRenderPng(dependencies.remote, job);
245
- const written = dependencies.files.write({
246
- body,
247
- outputPath: input.outputPath,
248
- overwrite: input.overwrite,
249
- at: dependencies.now()
250
- });
251
- return resultFrom(job, written);
252
- };
253
- const createRenderCanvasComposite = (remote, files, now, progress = () => null) => ({ execute: async (input) => executeRender({
254
- remote,
255
- files,
256
- now,
257
- progress
258
- }, input) });
259
-
260
- //#endregion
261
- //#region src/application/canvas-activity.composite.ts
262
- const PROCEDURES = {
263
- begin: "canvas.realtime.activity.begin",
264
- renew: "canvas.realtime.activity.renew",
265
- end: "canvas.realtime.activity.end"
266
- };
267
- const ignoreFailure = async (operation) => {
268
- try {
269
- await operation();
270
- return true;
271
- } catch {
272
- return false;
273
- }
274
- };
275
- const liveHandle = (remote, initial, activityId, renewAfterMs) => {
276
- let target = initial;
277
- let isFinished = false;
278
- let isRenewing = false;
279
- const renew = async () => {
280
- if (isFinished || isRenewing) return;
281
- isRenewing = true;
282
- await ignoreFailure(async () => remote.mutate(PROCEDURES.renew, {
283
- ...target,
284
- nodeIds: [...target.nodeIds],
285
- activityId
286
- }));
287
- isRenewing = false;
288
- };
289
- const timer = setInterval(() => void renew(), renewAfterMs);
290
- return {
291
- activityId,
292
- update: async (next) => {
293
- if (isFinished) return;
294
- target = {
295
- ...target,
296
- ...next
297
- };
298
- await renew();
299
- },
300
- finish: async () => {
301
- if (isFinished) return;
302
- isFinished = true;
303
- clearInterval(timer);
304
- await ignoreFailure(async () => remote.mutate(PROCEDURES.end, {
305
- canvasId: target.canvasId,
306
- activityId
307
- }));
308
- }
309
- };
310
- };
311
- const createCanvasActivityComposite = (remote) => ({
312
- begin: async (target) => {
313
- try {
314
- const parsed = beginCanvasActivityOutputSchema.safeParse(await remote.mutate(PROCEDURES.begin, {
315
- ...target,
316
- nodeIds: [...target.nodeIds]
317
- }));
318
- return parsed.success ? liveHandle(remote, target, parsed.data.activityId, parsed.data.renewAfterMs) : null;
319
- } catch {
320
- return null;
321
- }
322
- },
323
- finish: async (canvasId, activityId) => ignoreFailure(async () => remote.mutate(PROCEDURES.end, {
324
- canvasId,
325
- activityId
326
- }))
327
- });
328
-
329
- //#endregion
330
- //#region src/application/apply-canvas.composite.ts
331
- const APPLY_PROCEDURE = "canvas.applyOperations";
332
- const MAX_ACTIVITY_NODE_IDS$1 = 100;
333
- const BOX_OPERATION_TYPES = /* @__PURE__ */ new Set([
334
- "insertPrototype",
335
- "insertText",
336
- "setBox"
337
- ]);
338
- const hasOperationBox = (operation) => BOX_OPERATION_TYPES.has(operation.op);
339
- const activityPhase = (input) => {
340
- if (input.operations.some((operation) => operation.op === "insertNode" || operation.op === "insertText")) return "creating";
341
- if (input.operations.some((operation) => operation.op === "remove")) return "deleting";
342
- return "writing";
343
- };
344
- const operationNodeIds = (operation) => {
345
- if (operation.op === "insertConvertedSubtree") return Object.keys(operation.nodes);
346
- if (operation.op === "insertNode") return [operation.node.id];
347
- return [operation.nodeId];
348
- };
349
- const activityNodeIds = (input) => [...new Set(input.operations.flatMap((operation) => operationNodeIds(operation)))].slice(0, MAX_ACTIVITY_NODE_IDS$1);
350
- const operationBox = (operation) => {
351
- if (operation.op === "insertConvertedSubtree") return operation.nodes[operation.rootNodeId]?.box ?? null;
352
- if (operation.op === "insertNode") return operation.node.box ?? null;
353
- if (hasOperationBox(operation)) return operation.box === "default" ? null : operation.box;
354
- return null;
355
- };
356
- const union = (boxes) => {
357
- const first = boxes[0];
358
- if (first === void 0) return null;
359
- let x1 = first.x;
360
- let y1 = first.y;
361
- let x2 = first.x + first.width;
362
- let y2 = first.y + first.height;
363
- for (const box of boxes.slice(1)) {
364
- x1 = Math.min(x1, box.x);
365
- y1 = Math.min(y1, box.y);
366
- x2 = Math.max(x2, box.x + box.width);
367
- y2 = Math.max(y2, box.y + box.height);
368
- }
369
- return {
370
- x: x1,
371
- y: y1,
372
- width: x2 - x1,
373
- height: y2 - y1
374
- };
375
- };
376
- const apply = async (remote, input) => {
377
- const response = await remote.mutate(APPLY_PROCEDURE, {
378
- ...input,
379
- documentFormatVersion: 5
380
- });
381
- const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
382
- 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.");
383
- return parsed.data;
384
- };
385
- const createApplyCanvasComposite = (remote) => ({ execute: async (input, options) => {
386
- if (options?.activity === false) return apply(remote, input);
387
- const activity = await createCanvasActivityComposite(remote).begin({
388
- canvasId: input.canvasId,
389
- phase: activityPhase(input),
390
- nodeIds: activityNodeIds(input),
391
- bounds: union(input.operations.flatMap((operation) => {
392
- const box = operationBox(operation);
393
- return box === null ? [] : [box];
394
- }))
395
- });
396
- try {
397
- return await apply(remote, input);
398
- } finally {
399
- await activity?.finish();
400
- }
401
- } });
402
-
403
- //#endregion
404
- //#region src/application/canvas-scene-at-version.use-case.ts
405
- const sceneAtVersion = async (input, canvasId, expectedVersion) => {
406
- const held = getCanvasDocumentOutputSchema.safeParse(await input.remote.query("canvas.document.get", { canvasId }));
407
- if (!held.success) throw new CliError("INTERNAL", "The API returned an invalid canvas document.", "Run `enhance doctor` and report incompatible API and CLI versions.");
408
- 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.`);
409
- const scene = canvasReadableSceneDocumentSchema.safeParse(held.data.document);
410
- if (scene.success) return scene.data;
411
- 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.");
412
- };
413
-
414
- //#endregion
415
- //#region src/application/canvas-structure-document.use-case.ts
416
- const ROOT_CANVAS_NODE_ID = "root";
417
- 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);
418
- const canCanvasNodeContainChildren = (node) => node !== void 0 && [
419
- "root",
420
- "frame",
421
- "group"
422
- ].includes(node.component);
423
- const requireCanvasNode = (document, nodeId) => {
424
- const node = document.nodes[nodeId];
425
- if (node !== void 0) return node;
426
- throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use a current stable node id.");
427
- };
428
- const canvasDescendantIds = (document, nodeId) => {
429
- const found = /* @__PURE__ */ new Set();
430
- const visit = (parentId) => {
431
- for (const childId of canvasChildIds(document, parentId)) {
432
- found.add(childId);
433
- visit(childId);
434
- }
435
- };
436
- visit(nodeId);
437
- return found;
438
- };
439
-
440
- //#endregion
441
- //#region src/application/canvas-duplicate-operations.use-case.ts
442
- const SLUG_LENGTH = 60;
443
- const ID_LENGTH = 200;
444
- const ID_SEQUENCE_LENGTH = 4;
445
- const SORT_KEY_LENGTH = 500;
446
- const FALLBACK_SORT_SEQUENCE_LENGTH = 6;
447
- const slug = (source) => {
448
- const held = source.normalize("NFKD").toLowerCase().replaceAll(/[^a-z0-9_-]+/gu, "-").replaceAll(/^-+|-+$/gu, "").slice(0, SLUG_LENGTH);
449
- return held === "" ? "copy" : held;
450
- };
451
- const createDuplicateId = (prefix) => {
452
- let sequence = 0;
453
- return (label) => {
454
- sequence += 1;
455
- return `${slug(prefix)}_${slug(label)}_${String(sequence).padStart(ID_SEQUENCE_LENGTH, "0")}`.slice(0, ID_LENGTH);
456
- };
457
- };
458
- const subtreeIds = (document, rootId) => {
459
- const ordered = [];
460
- const visit = (nodeId) => {
461
- ordered.push(nodeId);
462
- for (const childId of canvasChildIds(document, nodeId)) visit(childId);
463
- };
464
- visit(rootId);
465
- return ordered;
466
- };
467
- const duplicateMap = (document, rootId, nextId) => Object.fromEntries(subtreeIds(document, rootId).map((nodeId) => [nodeId, nextId(requireCanvasNode(document, nodeId).label)]));
468
- const duplicateInsertOperation = (context, oldId) => {
469
- const { document, rootId, parentId, inputIndex, sourceSortKey, map } = context;
470
- const node = requireCanvasNode(document, oldId);
471
- const newId = map[oldId];
472
- if (newId === void 0) throw new Error(`Missing duplicate id for ${oldId}`);
473
- const oldParentage = document.relationships[oldId];
474
- const isRoot = oldId === rootId;
475
- const clonedParentId = isRoot ? parentId : map[oldParentage?.parentId ?? ""];
476
- if (clonedParentId === void 0) throw new Error(`Missing duplicate parent for ${oldId}`);
477
- const fallbackSort = `agent:${String(inputIndex + 1).padStart(FALLBACK_SORT_SEQUENCE_LENGTH, "0")}`;
478
- return {
479
- op: "insertNode",
480
- node: {
481
- ...structuredClone(node),
482
- id: newId
483
- },
484
- parentage: {
485
- parentId: clonedParentId,
486
- sortKey: isRoot ? `${sourceSortKey}~agent-copy-${String(inputIndex + 1).padStart(ID_SEQUENCE_LENGTH, "0")}`.slice(0, SORT_KEY_LENGTH) : oldParentage?.sortKey ?? fallbackSort
487
- }
488
- };
489
- };
490
- const duplicateOne = (context) => {
491
- const { document, input, inputIndex, nextId } = context;
492
- const source = requireCanvasNode(document, input.id);
493
- if (input.id === "root") throw new CliError("BAD_REQUEST", "The canvas root cannot be duplicated.", "Duplicate one or more root children instead.");
494
- const sourceParentage = document.relationships[input.id];
495
- if (sourceParentage === void 0) throw new CliError("BAD_REQUEST", `Canvas node ${input.id} is detached.`, "Choose a reachable node from canvas tree.");
496
- const parentId = input.parentId ?? sourceParentage.parentId;
497
- 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.");
498
- const map = duplicateMap(document, input.id, nextId);
499
- const treeContext = {
500
- document,
501
- rootId: input.id,
502
- parentId,
503
- inputIndex,
504
- sourceSortKey: sourceParentage.sortKey,
505
- map
506
- };
507
- const operations = subtreeIds(document, input.id).map((oldId) => duplicateInsertOperation(treeContext, oldId));
508
- const newId = map[input.id];
509
- if (newId === void 0) throw new Error(`Missing duplicate root id for ${input.id}`);
510
- return {
511
- operations,
512
- summary: {
513
- sourceId: input.id,
514
- newId,
515
- name: source.label,
516
- component: source.component,
517
- descendantIdMap: Object.fromEntries(Object.entries(map).filter(([oldId]) => oldId !== input.id))
518
- }
519
- };
520
- };
521
- const duplicateCanvasNodeOperations = (document, inputs, idPrefix) => {
522
- if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No nodes were provided to duplicate.", "Pass at least one stable node id.");
523
- const nextId = createDuplicateId(idPrefix);
524
- const duplicates = inputs.map((input, inputIndex) => duplicateOne({
525
- document,
526
- input,
527
- inputIndex,
528
- nextId
529
- }));
530
- return {
531
- operations: duplicates.flatMap((duplicate) => duplicate.operations),
532
- duplicatedNodes: duplicates.map((duplicate) => duplicate.summary)
533
- };
534
- };
535
-
536
- //#endregion
537
- //#region src/application/canvas-move-operations.use-case.ts
538
- const moveState = (document) => ({
539
- document,
540
- children: new Map(Object.keys(document.nodes).map((nodeId) => [nodeId, canvasChildIds(document, nodeId)])),
541
- parentOf: new Map(Object.entries(document.relationships).map(([nodeId, relationship]) => [nodeId, relationship.parentId])),
542
- affected: /* @__PURE__ */ new Set()
543
- });
544
- const directDestination = (input, state) => {
545
- const destination = (state.children.get(input.parentId) ?? []).filter((nodeId) => nodeId !== input.nodeId);
546
- return {
547
- parentId: input.parentId,
548
- index: Math.max(0, Math.min(input.index ?? destination.length, destination.length))
549
- };
550
- };
551
- const siblingDestination = (input, state) => {
552
- const siblingId = "before" in input ? input.before : input.after;
553
- 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.");
554
- const parentId = state.parentOf.get(siblingId);
555
- if (parentId === void 0) throw new CliError("BAD_REQUEST", `Sibling ${siblingId} is detached.`, "Choose a reachable sibling from canvas tree.");
556
- const siblingIndex = (state.children.get(parentId) ?? []).filter((nodeId) => nodeId !== input.nodeId).indexOf(siblingId);
557
- return {
558
- parentId,
559
- index: "before" in input ? siblingIndex : siblingIndex + 1
560
- };
561
- };
562
- const destinationFor = (input, state) => "parentId" in input ? directDestination(input, state) : siblingDestination(input, state);
563
- const validateMove = (input, destination, state) => {
564
- 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.");
565
- 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.");
566
- };
567
- const applyMove = (input, destination, state) => {
568
- const oldParentId = state.parentOf.get(input.nodeId);
569
- if (oldParentId !== void 0) {
570
- state.children.set(oldParentId, (state.children.get(oldParentId) ?? []).filter((id) => id !== input.nodeId));
571
- state.affected.add(oldParentId);
572
- }
573
- const children = [...state.children.get(destination.parentId) ?? []];
574
- const operations = [];
575
- const relationships = { ...state.document.relationships };
576
- const keyAt = (index) => {
577
- const id = children[index];
578
- return id === void 0 ? null : relationships[id]?.sortKey ?? null;
579
- };
580
- let sortKey = null;
581
- try {
582
- const before = keyAt(destination.index - 1);
583
- const after = keyAt(destination.index);
584
- const candidate = generateKeyBetween(before, after);
585
- if ((before === null || before.localeCompare(candidate) < 0) && (after === null || candidate.localeCompare(after) < 0)) sortKey = candidate;
586
- } catch {
587
- sortKey = null;
588
- }
589
- if (sortKey === null) {
590
- const ordered = [...children];
591
- ordered.splice(destination.index, 0, input.nodeId);
592
- const keys = generateNKeysBetween(null, null, ordered.length).toSorted((left, right) => left.localeCompare(right));
593
- for (const [index, id] of ordered.entries()) {
594
- const key = keys[index];
595
- if (key === void 0) throw new Error("Missing generated move sort key.");
596
- const parentage = {
597
- parentId: destination.parentId,
598
- sortKey: key
599
- };
600
- relationships[id] = parentage;
601
- operations.push({
602
- op: "setParentage",
603
- nodeId: id,
604
- parentage
605
- });
606
- }
607
- } else {
608
- const parentage = {
609
- parentId: destination.parentId,
610
- sortKey
611
- };
612
- relationships[input.nodeId] = parentage;
613
- operations.push({
614
- op: "setParentage",
615
- nodeId: input.nodeId,
616
- parentage
617
- });
618
- }
619
- children.splice(destination.index, 0, input.nodeId);
620
- state.children.set(destination.parentId, children);
621
- state.parentOf.set(input.nodeId, destination.parentId);
622
- state.affected.add(destination.parentId);
623
- return {
624
- operations,
625
- document: {
626
- ...state.document,
627
- relationships
628
- }
629
- };
630
- };
631
- const moveCanvasNodeOperations = (document, inputs) => {
632
- if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No moves were provided.", "Pass at least one move operation.");
633
- const state = moveState(document);
634
- const moves = [];
635
- return {
636
- operations: inputs.flatMap((input) => {
637
- const destination = destinationFor(input, state);
638
- validateMove(input, destination, state);
639
- moves.push({
640
- nodeId: input.nodeId,
641
- ...destination
642
- });
643
- const applied = applyMove(input, destination, state);
644
- state.document = applied.document;
645
- return applied.operations;
646
- }),
647
- moves,
648
- affectedParents: Array.from(state.affected, (parentId) => ({
649
- parentId,
650
- children: [...state.children.get(parentId) ?? []]
651
- }))
652
- };
653
- };
654
-
655
- //#endregion
656
- //#region src/application/canvas-typography-operations.use-case.ts
657
- const canvasTypographyOperation = (node, styles) => {
658
- const clear = canvasCssTypographyOwners(new Set(Object.keys(styles))).filter((property) => node.typography?.[property] !== void 0);
659
- return clear.length === 0 ? null : {
660
- op: "patchTypography",
661
- nodeId: node.id,
662
- typography: { clear }
663
- };
664
- };
665
-
666
- //#endregion
667
- //#region src/application/canvas-style-operations.use-case.ts
668
- const ADDITIONAL_STYLE_ID_LENGTH = 200;
669
- const ADDITIONAL_STYLE_SUFFIX_LENGTH = 10;
670
- 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();
671
- const additionalOperation = (node, styles) => {
672
- const held = new Map((node.additionalStyles?.declarations ?? []).map((declaration) => [declaration.id, declaration]));
673
- for (const [property, value] of Object.entries(styles)) {
674
- const replaced = Array.from(held, ([, item]) => item).filter((item) => item.property.toLowerCase() === property);
675
- for (const item of replaced) held.delete(item.id);
676
- if (value === null || canvasNodeStylePatchSchema.safeParse({ [property]: value }).success) continue;
677
- const base = replaced[0]?.id ?? `css-${property}`.slice(0, ADDITIONAL_STYLE_ID_LENGTH - ADDITIONAL_STYLE_SUFFIX_LENGTH);
678
- let id = base;
679
- for (let suffix = 1; held.has(id); suffix += 1) id = `${base}-${String(suffix)}`;
680
- const result = canvasAdditionalStyleSchema.safeParse({
681
- id,
682
- property,
683
- value: String(value),
684
- enabled: true
685
- });
686
- 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.");
687
- held.set(id, result.data);
688
- }
689
- const declarations = [];
690
- for (const declaration of held.values()) {
691
- if (declarations.length === 128) throw new CliError("BAD_REQUEST", "Too many additional CSS declarations.", "Remove unused declarations before adding more; no styles were changed.");
692
- declarations.push(declaration);
693
- }
694
- const requested = declarations.length === 0 && node.additionalStyles === void 0 ? void 0 : { declarations };
695
- const patch = canvasAdditionalStylePatchBetween(node.additionalStyles, requested);
696
- return patch === null ? null : {
697
- op: "patchAdditionalStyles",
698
- nodeId: node.id,
699
- additionalStyles: patch
700
- };
701
- };
702
- const layoutOperation = (document, node, next, styles) => {
703
- const changed = new Set(Object.keys(styles));
704
- const properties = (axis) => [...canvasAxisStyleProperties(node, axis, document), ...canvasAxisStyleProperties(next, axis, document)];
705
- const layout = canvasLayoutWithoutCssProperties(node.layout ?? {}, changed, {
706
- horizontal: properties("horizontal"),
707
- vertical: properties("vertical")
708
- });
709
- for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
710
- const value = styles[property];
711
- if (value === "fill" || value === "hug") layout[axis] = { mode: value };
712
- }
713
- return JSON.stringify(layout) === JSON.stringify(node.layout ?? {}) ? null : {
714
- op: "setLayout",
715
- nodeId: node.id,
716
- layout: Object.keys(layout).length === 0 ? "default" : layout
717
- };
718
- };
719
- const cssValues = (document, node, styles) => {
720
- const result = { ...styles };
721
- for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
722
- if (styles[property] !== "fill" && styles[property] !== "hug") continue;
723
- result[property] = null;
724
- 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;
725
- }
726
- return result;
727
- };
728
- const operationsForNode = (document, node, source) => {
729
- const styles = cssValues(document, node, source);
730
- const additional = additionalOperation(node, styles);
731
- const stylePatch = Object.fromEntries(Object.entries(styles).filter(([property, value]) => canvasNodeStylePatchSchema.safeParse({ [property]: value }).success));
732
- const next = {
733
- ...node,
734
- styles: { ...node.styles },
735
- ...additional !== null && { additionalStyles: applyCanvasAdditionalStylePatch(node.additionalStyles, additional.additionalStyles) ?? void 0 }
736
- };
737
- for (const [property, value] of Object.entries(stylePatch)) if (value === null) Reflect.deleteProperty(next.styles, property);
738
- else next.styles[property] = value;
739
- const layout = layoutOperation(document, node, next, source);
740
- const typography = canvasTypographyOperation(node, styles);
741
- const clearFill = (node.component === "text" ? ["color"] : [
742
- "background",
743
- "background-color",
744
- "background-image"
745
- ]).some((property) => Object.hasOwn(styles, property)) && node.appearance?.fills !== void 0 ? [{
746
- op: "setAppearance",
747
- nodeId: node.id,
748
- appearance: { clear: ["fills"] }
749
- }] : [];
750
- return [
751
- ...Object.keys(stylePatch).length > 0 ? [{
752
- op: "setStyles",
753
- nodeId: node.id,
754
- styles: canvasNodeStylePatchSchema.parse(stylePatch)
755
- }] : [],
756
- ...clearFill,
757
- ...typography === null ? [] : [typography],
758
- ...layout === null ? [] : [layout],
759
- ...additional === null ? [] : [additional]
760
- ];
761
- };
762
- const mergedUpdates = (updates) => {
763
- const merged = /* @__PURE__ */ new Map();
764
- for (const update of updates) for (const nodeId of update.nodeIds) {
765
- const styles = merged.get(nodeId) ?? {};
766
- for (const [property, value] of Object.entries(update.styles)) {
767
- const normalized = camelToKebab(property);
768
- Reflect.deleteProperty(styles, normalized);
769
- styles[normalized] = value;
770
- }
771
- merged.set(nodeId, styles);
772
- }
773
- return merged;
774
- };
775
- const canvasStyleOperations = (document, updates) => {
776
- const operations = [...mergedUpdates(updates)].flatMap(([nodeId, styles]) => {
777
- const node = document.nodes[nodeId];
778
- if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use current stable node ids.");
779
- return operationsForNode(document, node, styles);
780
- });
781
- if (operations.length === 0) throw new CliError("BAD_REQUEST", "No style changes were provided.", "Pass at least one changed CSS property.");
782
- return operations;
783
- };
784
-
785
- //#endregion
786
- //#region src/application/canvas-edit-operations.use-case.ts
787
- const projectStyles = (node, operation) => {
788
- const styles = { ...node.styles };
789
- for (const [name, value] of Object.entries(operation.styles)) if (value === null || value === void 0) Reflect.deleteProperty(styles, name);
790
- else styles[name] = value;
791
- const cleared = operation.clear ?? [];
792
- for (const name of cleared) Reflect.deleteProperty(styles, name);
793
- const typography = applyCanvasTypographyPatch(node.typography, { clear: [...canvasCssTypographyOwners(/* @__PURE__ */ new Set([...Object.keys(operation.styles), ...cleared]))] });
794
- return projectPresentation({
795
- ...node,
796
- styles
797
- }, "typography", typography ?? "default");
798
- };
799
- const PLANNED_OPERATIONS = /* @__PURE__ */ new Set([
800
- "insertNode",
801
- "setText",
802
- "setLabel",
803
- "setStyles",
804
- "setAppearance",
805
- "setTypography",
806
- "patchTypography",
807
- "setLayout",
808
- "setAdditionalStyles",
809
- "patchAdditionalStyles",
810
- "setParentage"
811
- ]);
812
- const isPlannedOperation = (operation) => PLANNED_OPERATIONS.has(operation.op);
813
- const projectPresentation = (node, field, value) => {
814
- const next = { ...node };
815
- if (value === "default") Reflect.deleteProperty(next, field);
816
- else Reflect.set(next, field, value);
817
- return next;
818
- };
819
- const projectNode = (node, operation) => {
820
- switch (operation.op) {
821
- case "setText":
822
- 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.");
823
- return {
824
- ...node,
825
- props: {
826
- ...node.props,
827
- text: operation.text
828
- }
829
- };
830
- case "setLabel": return {
831
- ...node,
832
- label: operation.label,
833
- labelOrigin: "user"
834
- };
835
- case "setStyles": return projectStyles(node, operation);
836
- case "setAppearance": {
837
- const appearance = { ...node.appearance };
838
- const cleared = operation.appearance.clear ?? [];
839
- for (const property of cleared) Reflect.deleteProperty(appearance, property);
840
- const next = {
841
- ...node,
842
- appearance
843
- };
844
- if (Object.keys(appearance).length === 0) Reflect.deleteProperty(next, "appearance");
845
- return next;
846
- }
847
- case "patchTypography": return projectPresentation(node, "typography", applyCanvasTypographyPatch(node.typography, operation.typography) ?? "default");
848
- case "setTypography": return projectPresentation(node, "typography", operation.typography);
849
- case "setLayout": return projectPresentation(node, "layout", operation.layout);
850
- case "patchAdditionalStyles": {
851
- const additionalStyles = applyCanvasAdditionalStylePatch(node.additionalStyles, operation.additionalStyles);
852
- return projectPresentation(node, "additionalStyles", additionalStyles ?? "default");
853
- }
854
- case "setAdditionalStyles": return projectPresentation(node, "additionalStyles", operation.additionalStyles);
855
- }
856
- };
857
- const projectOperation = (scene, operation) => {
858
- if (!isPlannedOperation(operation)) throw new Error(`Unexpected focused edit operation: ${operation.op}`);
859
- if (operation.op === "insertNode") {
860
- 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.");
861
- return {
862
- ...scene,
863
- nodes: {
864
- ...scene.nodes,
865
- [operation.node.id]: operation.node
866
- },
867
- relationships: {
868
- ...scene.relationships,
869
- [operation.node.id]: operation.parentage
870
- }
871
- };
872
- }
873
- const node = requireCanvasNode(scene, operation.nodeId);
874
- if (operation.op === "setParentage") return {
875
- ...scene,
876
- relationships: {
877
- ...scene.relationships,
878
- [node.id]: operation.parentage
879
- }
880
- };
881
- return {
882
- ...scene,
883
- nodes: {
884
- ...scene.nodes,
885
- [node.id]: projectNode(node, operation)
886
- }
887
- };
888
- };
889
- const moveInput = (edit) => {
890
- const { nodeId, destination } = edit;
891
- switch (destination.kind) {
892
- case "before": return {
893
- nodeId,
894
- before: destination.nodeId
895
- };
896
- case "after": return {
897
- nodeId,
898
- after: destination.nodeId
899
- };
900
- case "parent": return {
901
- nodeId,
902
- parentId: destination.parentId,
903
- ...destination.index !== void 0 && { index: destination.index }
904
- };
905
- }
906
- };
907
- const operationsForEdit = (edit, plan, prefix, duplicateIndex) => {
908
- switch (edit.kind) {
909
- case "set_text": return [{
910
- op: "setText",
911
- nodeId: edit.nodeId,
912
- text: edit.text
913
- }];
914
- case "rename": return [{
915
- op: "setLabel",
916
- nodeId: edit.nodeId,
917
- label: edit.name,
918
- labelOrigin: "user"
919
- }];
920
- case "set_styles": return canvasStyleOperations(plan.scene, [{
921
- nodeIds: edit.nodeIds,
922
- styles: edit.styles
923
- }]);
924
- case "duplicate": {
925
- const idPrefix = duplicateIndex === 0 ? prefix : `${String(duplicateIndex + 1)}_${prefix}`;
926
- const duplicate = duplicateCanvasNodeOperations(plan.scene, edit.nodeIds.map((id) => ({
927
- id,
928
- ...edit.parentId !== void 0 && { parentId: edit.parentId }
929
- })), idPrefix);
930
- plan.duplicatedNodes.push(...duplicate.duplicatedNodes);
931
- return duplicate.operations;
932
- }
933
- case "move": {
934
- const move = moveCanvasNodeOperations(plan.scene, [moveInput(edit)]);
935
- plan.moves.push(...move.moves);
936
- for (const parent of move.affectedParents) plan.affectedParents.add(parent.parentId);
937
- return move.operations;
938
- }
939
- }
940
- };
941
- const planCanvasEdits = (scene, edits, prefix) => {
942
- const plan = {
943
- scene,
944
- operations: [],
945
- duplicatedNodes: [],
946
- moves: [],
947
- affectedParents: /* @__PURE__ */ new Set()
948
- };
949
- let duplicateIndex = 0;
950
- for (const edit of edits) {
951
- const operations = operationsForEdit(edit, plan, prefix, duplicateIndex);
952
- if (edit.kind === "duplicate") duplicateIndex += 1;
953
- for (const operation of operations) plan.scene = projectOperation(plan.scene, operation);
954
- plan.operations.push(...operations);
955
- }
956
- return {
957
- operations: plan.operations,
958
- duplicatedNodes: plan.duplicatedNodes,
959
- moves: plan.moves,
960
- affectedParents: [...plan.affectedParents].map((parentId) => ({
961
- parentId,
962
- children: canvasChildIds(plan.scene, parentId)
963
- }))
964
- };
965
- };
966
-
967
- //#endregion
968
- //#region src/application/edit-canvas.composite.ts
969
- const MAX_EDIT_TARGETS = 1e3;
970
- const targetIds = (edit) => {
971
- switch (edit.kind) {
972
- case "set_text":
973
- case "rename": return [edit.nodeId];
974
- case "set_styles": return edit.nodeIds;
975
- case "duplicate": return [...edit.nodeIds, ...edit.parentId === void 0 ? [] : [edit.parentId]];
976
- case "move": return [edit.nodeId, edit.destination.kind === "parent" ? edit.destination.parentId : edit.destination.nodeId];
977
- }
978
- };
979
- const scopeIds = (edit, scene) => {
980
- if (edit.kind === "duplicate") return [...edit.nodeIds, ...edit.parentId === void 0 || edit.nodeIds.every((id) => scene.relationships[id]?.parentId === edit.parentId) ? [] : [edit.parentId]];
981
- if (edit.kind === "move" && edit.destination.kind === "parent" && scene.relationships[edit.nodeId]?.parentId === edit.destination.parentId) return [edit.nodeId];
982
- return targetIds(edit);
983
- };
984
- const validateTargets = (input, scene) => {
985
- 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.");
986
- const ids = new Set(input.edits.flatMap((edit) => targetIds(edit)));
987
- 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.");
988
- for (const id of ids) requireCanvasNode(scene, id);
989
- const reference = {
990
- canvasId: input.canvasId,
991
- nodeIds: input.nodeIds ?? []
992
- };
993
- for (const edit of input.edits) assertCanvasReferenceNodes(reference, scene, scopeIds(edit, scene));
994
- };
995
- const createEditCanvasComposite = (remote) => ({ execute: async (input) => {
996
- const scene = await sceneAtVersion({ remote }, input.canvasId, input.baseVersion);
997
- validateTargets(input, scene);
998
- const plan = planCanvasEdits(scene, input.edits, input.idPrefix ?? `copy_${input.mutationId.replaceAll("-", "")}`);
999
- assertCanvasReferenceOperations({
1000
- canvasId: input.canvasId,
1001
- nodeIds: input.nodeIds ?? []
1002
- }, scene, plan.operations.filter((operation) => "nodeId" in operation && scene.nodes[operation.nodeId] !== void 0));
1003
- const parsed = applyCanvasOperationsInputSchema.safeParse({
1004
- canvasId: input.canvasId,
1005
- mutationId: input.mutationId,
1006
- documentFormatVersion: 5,
1007
- baseVersion: input.baseVersion,
1008
- operations: plan.operations
1009
- });
1010
- if (!parsed.success) throw new CliError("BAD_REQUEST", "The edit exceeds canonical canvas limits.", parsed.error.issues[0]?.message ?? "Reduce the edit batch.");
1011
- const result = applyCanvasOperationsOutputSchema.parse(await createApplyCanvasComposite(remote).execute(parsed.data));
1012
- return {
1013
- ...result,
1014
- 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.`],
1015
- ...plan.duplicatedNodes.length > 0 && { duplicatedNodes: plan.duplicatedNodes },
1016
- ...plan.moves.length > 0 && {
1017
- moves: plan.moves,
1018
- affectedParents: plan.affectedParents
1019
- }
1020
- };
1021
- } });
1022
-
1023
- //#endregion
1024
- //#region src/application/write-html-canvas.composite.ts
1025
- const CREATE_IMPORT_PROCEDURE = "canvas.render.importSource";
1026
- const READ_IMPORT_PROCEDURE = "canvas.render.getImport";
1027
- const POLL_MS$1 = 250;
1028
- const MAX_ACTIVITY_NODE_IDS = 100;
1029
- const invalidResponse$1 = (operation) => new CliError("INTERNAL", `The API returned an invalid ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
1030
- const wait$1 = async (milliseconds) => new Promise((resolve) => {
1031
- globalThis.setTimeout(resolve, milliseconds);
1032
- });
1033
- const terminalFailure = (job) => {
1034
- const failure = job.failure;
1035
- 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 tree and correct the HTML or destination before retrying.", {
1036
- jobId: job.id,
1037
- phase: failure.phase,
1038
- reason: failure.reason
1039
- });
1040
- };
1041
- const readImport = async (remote, jobId) => {
1042
- const parsed = getCanvasConversionOutputSchema.safeParse(await remote.query(READ_IMPORT_PROCEDURE, { jobId }));
1043
- if (!parsed.success) throw invalidResponse$1("HTML import status");
1044
- return parsed.data.job;
1045
- };
1046
- const awaitImport = async (remote, initial, timeoutMs) => {
1047
- const deadline = Date.now() + timeoutMs;
1048
- let job = initial;
1049
- while (job.state === "queued" || job.state === "running") {
1050
- if (Date.now() >= deadline) return job;
1051
- await wait$1(POLL_MS$1);
1052
- job = await readImport(remote, job.id);
1053
- }
1054
- if (job.state !== "succeeded") throw terminalFailure(job);
1055
- return job;
1056
- };
1057
- const createImport = async (remote, input) => {
1058
- const made = createCanvasConversionOutputSchema.safeParse(await remote.mutate(CREATE_IMPORT_PROCEDURE, {
1059
- canvasId: input.canvasId,
1060
- expectedVersion: input.baseVersion,
1061
- source: {
1062
- kind: "html",
1063
- html: input.html,
1064
- label: "Agent-authored HTML",
1065
- ...input.idPrefix !== void 0 && { idPrefix: input.idPrefix }
1066
- },
1067
- destination: {
1068
- kind: input.mode,
1069
- targetNodeId: input.targetNodeId
1070
- }
1071
- }));
1072
- if (!made.success) throw invalidResponse$1("HTML import creation");
1073
- return awaitImport(remote, made.data.job, input.renderTimeoutMs);
1074
- };
1075
- const failedReview = (error, input, version) => {
1076
- return {
1077
- state: "failed",
1078
- mutationCommitted: true,
1079
- requestedVersion: version,
1080
- ...error instanceof CliError ? {
1081
- code: error.code,
1082
- message: error.message,
1083
- remediation: error.remediation,
1084
- ...error.fields !== void 0 && { fields: error.fields }
1085
- } : {
1086
- code: "INTERNAL",
1087
- message: "The post-write review render failed.",
1088
- remediation: "Render the committed version and affected area again; do not replay the write."
1089
- },
1090
- next: [`enhance canvas render --canvas ${input.canvasId} --expected-version ${String(version)}`, "Do not replay the committed write with a new mutation id."]
1091
- };
1092
- };
1093
- const renderReview = async (render, input, imported) => {
1094
- try {
1095
- return await render.execute({
1096
- canvasId: input.canvasId,
1097
- expectedVersion: imported.result.version,
1098
- target: {
1099
- kind: "node",
1100
- nodeId: imported.result.rootNodeId
1101
- },
1102
- sourceState: null,
1103
- scale: input.renderScale,
1104
- outputPath: input.renderOutputPath,
1105
- overwrite: input.overwriteRender,
1106
- timeoutMs: input.renderTimeoutMs,
1107
- retryClientToken: input.renderClientToken
1108
- });
1109
- } catch (error) {
1110
- return failedReview(error, input, imported.result.version);
1111
- }
1112
- };
1113
- const createdNodes = async (remote, imported) => {
1114
- const scene = await sceneAtVersion({ remote }, imported.canvasId, imported.result.version);
1115
- return imported.result.insertedNodeIds.map((nodeId) => {
1116
- const node = scene.nodes[nodeId];
1117
- return {
1118
- id: nodeId,
1119
- name: node?.label ?? "",
1120
- component: node?.component ?? ""
1121
- };
1122
- });
1123
- };
1124
- const committedResponse = (input, imported) => ({
1125
- canvasId: input.canvasId,
1126
- mutationCommitted: true,
1127
- jobId: imported.id,
1128
- mutationId: imported.result.mutationId,
1129
- rootNodeId: imported.result.rootNodeId,
1130
- mode: input.mode,
1131
- targetNodeId: input.targetNodeId,
1132
- previousVersion: imported.result.previousVersion,
1133
- version: imported.result.version,
1134
- insertedNodeIds: imported.result.insertedNodeIds,
1135
- removedNodeIds: imported.result.removedNodeIds,
1136
- affected: {
1137
- inserted: imported.result.insertedNodeIds.length,
1138
- changed: 0,
1139
- removed: imported.result.removedNodeIds.length
1140
- },
1141
- affectedBounds: imported.result.affectedBounds
1142
- });
1143
- const pendingResponse = (job) => ({
1144
- state: "pending",
1145
- canvasId: job.canvasId,
1146
- jobId: job.id,
1147
- phase: job.phase,
1148
- status: {
1149
- tool: "capability_query",
1150
- arguments: {
1151
- capability: READ_IMPORT_PROCEDURE,
1152
- input: { jobId: job.id }
1153
- }
1154
- },
1155
- next: ["Read the existing import status; do not start another import."]
1156
- });
1157
- const createWriteHtmlCanvasComposite = (remote, render) => ({ execute: async (input) => {
1158
- if (input.selectionNodeIds !== void 0 && input.selectionNodeIds.length > 0) {
1159
- const scene = await sceneAtVersion({ remote }, input.canvasId, input.baseVersion);
1160
- assertCanvasReferenceNodes({
1161
- canvasId: input.canvasId,
1162
- nodeIds: input.selectionNodeIds
1163
- }, scene, [input.targetNodeId]);
1164
- }
1165
- const activity = await createCanvasActivityComposite(remote).begin({
1166
- canvasId: input.canvasId,
1167
- phase: "creating",
1168
- nodeIds: [input.targetNodeId],
1169
- bounds: null
1170
- });
1171
- try {
1172
- const imported = await createImport(remote, input);
1173
- if (imported.state !== "succeeded") return pendingResponse(imported);
1174
- if (input.review === "none") return committedResponse(input, imported);
1175
- await activity?.update({
1176
- phase: "rendering",
1177
- nodeIds: imported.result.insertedNodeIds.slice(0, MAX_ACTIVITY_NODE_IDS),
1178
- bounds: imported.result.affectedBounds
1179
- });
1180
- const review = await renderReview(render, input, imported);
1181
- let nodes = [];
1182
- try {
1183
- nodes = await createdNodes(remote, imported);
1184
- } catch {
1185
- nodes = [];
1186
- }
1187
- return {
1188
- ...committedResponse(input, imported),
1189
- createdNodes: nodes,
1190
- review,
1191
- next: ["Inspect the review PNG before continuing."]
1192
- };
1193
- } finally {
1194
- await activity?.finish();
1195
- }
1196
- } });
1197
-
1198
- //#endregion
1199
- //#region src/infrastructure/render-file.adapter.ts
1200
- const DIRECTORY_MODE = 448;
1201
- const FILE_MODE = 384;
1202
- const TEMPORARY_TTL_MS = 36e5;
1203
- const write = (filePath, body, shouldOverwrite) => {
1204
- try {
1205
- writeFileSync(filePath, body, {
1206
- flag: shouldOverwrite ? "w" : "wx",
1207
- mode: FILE_MODE
1208
- });
1209
- chmodSync(filePath, FILE_MODE);
1210
- } catch (error) {
1211
- const code = typeof error === "object" && error !== null && Reflect.get(error, "code") === "EEXIST" ? "CONFLICT" : "INTERNAL";
1212
- 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.");
1213
- }
1214
- };
1215
- const createRenderFileAdapter = (configDirectory) => ({ write: (input) => {
1216
- if (input.outputPath !== null) {
1217
- const outputPath = path.resolve(input.outputPath);
1218
- write(outputPath, input.body, input.overwrite);
1219
- return {
1220
- path: outputPath,
1221
- temporary: false,
1222
- deleteAfter: null
1223
- };
1224
- }
1225
- const directory = path.join(configDirectory, "sensitive");
1226
- mkdirSync(directory, {
1227
- recursive: true,
1228
- mode: DIRECTORY_MODE
1229
- });
1230
- chmodSync(directory, DIRECTORY_MODE);
1231
- const outputPath = path.join(directory, `render-${globalThis.crypto.randomUUID()}.png`);
1232
- write(outputPath, input.body, false);
1233
- return {
1234
- path: outputPath,
1235
- temporary: true,
1236
- deleteAfter: new Date(input.at.getTime() + TEMPORARY_TTL_MS)
1237
- };
1238
- } });
1239
-
1240
- //#endregion
1241
- //#region src/application/publish-prototype.composite.ts
1242
- const PUBLISH_WAIT_MS = 3e5;
1243
- const INITIAL_POLL_MS = 50;
1244
- const MAX_POLL_MS = 1e3;
1245
- const PUBLISH_PROTOTYPE_PROCEDURES = [
1246
- "prototype.getArtifactCapabilities",
1247
- "prototype.createArtifact",
1248
- "prototype.submitArtifact",
1249
- "prototype.getPublishStatus",
1250
- "prototype.attach"
1251
- ];
1252
- 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.");
1253
- const waitUntilSettled = async (remote, input) => {
1254
- const deadline = Date.now() + PUBLISH_WAIT_MS;
1255
- let pollMs = INITIAL_POLL_MS;
1256
- while (Date.now() < deadline) {
1257
- const parsed = getPrototypePublishStatusOutputSchema.safeParse(await remote.query(PUBLISH_PROTOTYPE_PROCEDURES[3], input));
1258
- if (!parsed.success) throw invalidResponse("status");
1259
- if (parsed.data.state === "ready" || parsed.data.state === "failed") return parsed.data;
1260
- if (parsed.data.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${input.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
1261
- await setTimeout$1(pollMs);
1262
- pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
1263
- }
1264
- throw new Error("prototype ingestion is still running");
1265
- };
1266
- const reserveAndUpload = async (remote, input, artifact, reserved) => {
1267
- const created = createPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[1], {
1268
- canvasId: input.canvasId,
1269
- ...input.prototypeId !== null && { prototypeId: input.prototypeId },
1270
- clientToken: input.clientToken,
1271
- nodeId: input.nodeId,
1272
- title: input.title,
1273
- entryPath: artifact.manifest.entryPath,
1274
- artifact: artifact.identity,
1275
- box: input.box
1276
- }));
1277
- if (!created.success) throw invalidResponse("artifact creation");
1278
- reserved(created.data.deploymentId);
1279
- if (created.data.state === "uploading") await remote.upload({
1280
- url: created.data.upload.url,
1281
- headers: created.data.upload.headers,
1282
- body: artifact.open()
1283
- });
1284
- if (created.data.state === "uploading" || created.data.state === "queued") {
1285
- if (!submitPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[2], {
1286
- canvasId: input.canvasId,
1287
- deploymentId: created.data.deploymentId
1288
- })).success) throw invalidResponse("artifact submission");
1289
- }
1290
- return created.data;
1291
- };
1292
- const requireSuccessfulIngestion = (status) => {
1293
- if (status.state !== "failed") return;
1294
- const { failure } = status;
1295
- 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 });
1296
- };
1297
- const executePublish = async (remote, artifacts, input) => {
1298
- const capabilities = getPrototypeArtifactCapabilitiesOutputSchema.safeParse(await remote.query(PUBLISH_PROTOTYPE_PROCEDURES[0], {}));
1299
- if (!capabilities.success) throw invalidResponse("capabilities");
1300
- const artifact = await artifacts.package({
1301
- directory: input.directory,
1302
- entryPath: input.entryPath,
1303
- limits: capabilities.data.limits
1304
- });
1305
- const progress = { deploymentId: null };
1306
- try {
1307
- const created = await reserveAndUpload(remote, input, artifact, (reservedId) => {
1308
- progress.deploymentId = reservedId;
1309
- });
1310
- const status = await waitUntilSettled(remote, {
1311
- canvasId: input.canvasId,
1312
- deploymentId: created.deploymentId
1313
- });
1314
- requireSuccessfulIngestion(status);
1315
- const attached = attachPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[4], {
1316
- canvasId: input.canvasId,
1317
- deploymentId: created.deploymentId,
1318
- baseVersion: input.baseVersion
1319
- }));
1320
- if (!attached.success) throw invalidResponse("attachment");
1321
- return {
1322
- ...attached.data,
1323
- fileCount: status.fileCount,
1324
- totalBytes: status.totalBytes,
1325
- alreadyExists: created.alreadyExists,
1326
- next: [attached.data.openUrl, `enhance canvas render --canvas ${input.canvasId} --node-id ${attached.data.nodeId} --expected-version ${String(attached.data.version)}`]
1327
- };
1328
- } catch (error) {
1329
- if (error instanceof CliError && (error.code === "BAD_REQUEST" || error.code === "NOT_FOUND")) throw error;
1330
- if (progress.deploymentId === null) throw error;
1331
- 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}.`);
1332
- } finally {
1333
- await artifact.dispose();
1334
- }
1335
- };
1336
- const createPublishPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => executePublish(remote, artifacts, input) });
1337
-
1338
- //#endregion
1339
- //#region src/application/read-transcript.composite.ts
1340
- const MAX_PREVIEW_COMMANDS = 3;
1341
- const READ_TRANSCRIPT_PROCEDURES = ["transcript.get"];
1342
- 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)}`);
1343
- const createReadTranscriptComposite = (remote) => ({ execute: async (input) => {
1344
- const parsed = transcriptOutputSchema.safeParse(await remote.query(READ_TRANSCRIPT_PROCEDURES[0], input));
1345
- 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.");
1346
- if (parsed.data.state !== "ready") return parsed.data;
1347
- return {
1348
- ...parsed.data,
1349
- guidance: "Cue times describe speech, not guaranteed visual transitions. Shortlist moments, render candidate timestamps, and inspect each PNG before creating a screen.",
1350
- next: previewCommands(input.canvasId, input.recordingId, parsed.data.cues.map((cue) => cue.startMs))
1351
- };
1352
- } });
1353
-
1354
- //#endregion
1355
- //#region src/application/snapshot-recording.composite.ts
1356
- const POLL_MS = 250;
1357
- const PROGRESS_HEARTBEAT_MS = 5e3;
1358
- const SNAPSHOT_RECORDING_PROCEDURES = ["canvas.render.get", "canvas.render.snapshot"];
1359
- const wait = async () => new Promise((resolve) => {
1360
- globalThis.setTimeout(resolve, POLL_MS);
1361
- });
1362
- 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.`, {
1363
- jobId: job.id,
1364
- phase: job.phase
1365
- });
1366
- const readSnapshotJob = async (remote, jobId) => {
1367
- const read = getCanvasRenderOutputSchema.safeParse(await remote.query(SNAPSHOT_RECORDING_PROCEDURES[0], { jobId }));
1368
- if (!read.success) throw new CliError("INTERNAL", "The API returned an invalid snapshot status response.", `Run \`enhance doctor\` and report snapshot job ${jobId}.`);
1369
- return read.data.job;
1370
- };
1371
- const awaitSnapshot = async (remote, initial, input, progress) => {
1372
- const deadline = Date.now() + input.timeoutMs;
1373
- const startedAt = Date.now();
1374
- let job = initial;
1375
- let lastReportedAt = 0;
1376
- let lastReportedState = "";
1377
- while (job.state === "queued" || job.state === "running") {
1378
- const currentTime = Date.now();
1379
- const stateKey = `${job.state}:${job.phase}`;
1380
- if (stateKey !== lastReportedState || currentTime - lastReportedAt >= PROGRESS_HEARTBEAT_MS) {
1381
- progress({
1382
- event: "snapshot.progress",
1383
- jobId: job.id,
1384
- state: job.state,
1385
- phase: job.phase,
1386
- elapsedMs: currentTime - startedAt,
1387
- timeoutMs: input.timeoutMs,
1388
- retryClientToken: input.retryClientToken
1389
- });
1390
- lastReportedAt = currentTime;
1391
- lastReportedState = stateKey;
1392
- }
1393
- if (currentTime >= deadline) 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.`, {
1394
- jobId: job.id,
1395
- phase: job.phase
1396
- });
1397
- await wait();
1398
- job = await readSnapshotJob(remote, job.id);
1399
- }
1400
- if (job.state !== "succeeded" || job.result.snapshot === void 0) throw failureOf(job);
1401
- return {
1402
- ...job,
1403
- result: {
1404
- ...job.result,
1405
- snapshot: job.result.snapshot
1406
- }
1407
- };
1408
- };
1409
- const executeSnapshot = async (remote, progress, input) => {
1410
- const made = createRecordingSnapshotOutputSchema.safeParse(await remote.mutate(SNAPSHOT_RECORDING_PROCEDURES[1], {
1411
- canvasId: input.canvasId,
1412
- recordingId: input.recordingId,
1413
- atMs: input.atMs
1414
- }));
1415
- 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.");
1416
- const job = await awaitSnapshot(remote, made.data.job, input, progress);
1417
- const snapshot = job.result.snapshot;
1418
- return {
1419
- jobId: job.id,
1420
- canvasId: job.canvasId,
1421
- ...snapshot,
1422
- warnings: job.result.warnings,
1423
- retryClientToken: input.retryClientToken,
1424
- 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)}`]
1425
- };
1426
- };
1427
- const createSnapshotRecordingComposite = (remote, progress) => ({ execute: async (input) => executeSnapshot(remote, progress, input) });
1428
-
1429
- //#endregion
1430
- //#region src/infrastructure/prototype-zip.adapter.ts
1431
- const NORMALIZED_MTIME = /* @__PURE__ */ new Date("1980-01-01T00:00:00.000Z");
1432
- const REGULAR_FILE_MODE = 33188;
1433
- const ZIP64_ENTRY_FLOOR = 65535;
1434
- const badRequest$1 = (message, remediation) => new CliError("BAD_REQUEST", message, remediation);
1435
- const hashingTransform = (source, completed) => {
1436
- const hash = createHash("sha256");
1437
- let bytes = 0;
1438
- return new Transform({
1439
- transform: (chunk, _encoding, callback) => {
1440
- bytes += chunk.byteLength;
1441
- hash.update(chunk);
1442
- callback(null, chunk);
1443
- },
1444
- flush: (callback) => {
1445
- if (bytes !== source.bytes) {
1446
- callback(/* @__PURE__ */ new Error(`prototype file ${source.path} changed while it was packaged`));
1447
- return;
1448
- }
1449
- completed({
1450
- path: source.path,
1451
- contentType: source.contentType,
1452
- bytes,
1453
- sha256: hash.digest("hex")
1454
- });
1455
- callback();
1456
- }
1457
- });
1458
- };
1459
- const addManifest = (input) => {
1460
- const manifest = prototypeArtifactManifestSchema.parse({
1461
- version: 1,
1462
- entryPath: input.entryPath,
1463
- files: input.files.map((file) => input.completed.get(file.path))
1464
- });
1465
- const body = Buffer.from(JSON.stringify(manifest), "utf8");
1466
- 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.`);
1467
- input.zip.addBuffer(body, PROTOTYPE_ARTIFACT_MANIFEST_PATH, {
1468
- mtime: NORMALIZED_MTIME,
1469
- mode: REGULAR_FILE_MODE,
1470
- compress: true,
1471
- forceDosTimestamp: true
1472
- });
1473
- input.zip.end({
1474
- forceZip64Format: input.files.length >= ZIP64_ENTRY_FLOOR,
1475
- comment: ""
1476
- });
1477
- return manifest;
1478
- };
1479
- const createPrototypeZipAdapter = async (input) => {
1480
- const zip = new ZipFile();
1481
- const hash = createHash("sha256");
1482
- const hashing = new Transform({ transform: (chunk, _encoding, callback) => {
1483
- hash.update(chunk);
1484
- callback(null, chunk);
1485
- } });
1486
- const completed = /* @__PURE__ */ new Map();
1487
- const packaged = { manifest: null };
1488
- const output = pipeline(zip.outputStream, hashing, createWriteStream(input.artifactPath));
1489
- zip.on("error", (error) => hashing.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype ZIP failed")));
1490
- const complete = (file) => {
1491
- completed.set(file.path, file);
1492
- if (packaged.manifest === null && completed.size === input.files.length) packaged.manifest = addManifest({
1493
- zip,
1494
- completed,
1495
- ...input
1496
- });
1497
- };
1498
- for (const source of input.files) zip.addReadStreamLazy(source.path, {
1499
- size: source.bytes,
1500
- mtime: NORMALIZED_MTIME,
1501
- mode: REGULAR_FILE_MODE,
1502
- compress: true,
1503
- forceDosTimestamp: true
1504
- }, (callback) => {
1505
- callback(null, createReadStream(source.absolutePath).pipe(hashingTransform(source, complete)));
1506
- });
1507
- await output;
1508
- if (packaged.manifest === null) throw new Error("prototype ZIP completed without a manifest");
1509
- const artifactStats = await stat(input.artifactPath);
1510
- 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.`);
1511
- return {
1512
- manifest: packaged.manifest,
1513
- bytes: artifactStats.size,
1514
- sha256: hash.digest("hex")
1515
- };
1516
- };
1517
-
1518
- //#endregion
1519
- //#region src/infrastructure/prototype-artifact.adapter.ts
1520
- const CONTENT_TYPES = {
1521
- ".avif": "image/avif",
1522
- ".css": "text/css; charset=utf-8",
1523
- ".gif": "image/gif",
1524
- ".html": "text/html; charset=utf-8",
1525
- ".ico": "image/x-icon",
1526
- ".jpeg": "image/jpeg",
1527
- ".jpg": "image/jpeg",
1528
- ".js": "text/javascript; charset=utf-8",
1529
- ".json": "application/json; charset=utf-8",
1530
- ".map": "application/json; charset=utf-8",
1531
- ".mjs": "text/javascript; charset=utf-8",
1532
- ".mp3": "audio/mpeg",
1533
- ".mp4": "video/mp4",
1534
- ".ogg": "audio/ogg",
1535
- ".otf": "font/otf",
1536
- ".png": "image/png",
1537
- ".svg": "image/svg+xml",
1538
- ".ttf": "font/ttf",
1539
- ".txt": "text/plain; charset=utf-8",
1540
- ".wasm": "application/wasm",
1541
- ".webm": "video/webm",
1542
- ".webp": "image/webp",
1543
- ".woff": "font/woff",
1544
- ".woff2": "font/woff2",
1545
- ".xml": "application/xml"
1546
- };
1547
- const contentTypeOf = (filePath) => CONTENT_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";
1548
- const statsFor = async (filePath) => {
1549
- try {
1550
- return await stat(filePath);
1551
- } catch {
1552
- return null;
1553
- }
1554
- };
1555
- const byteLength = (value) => Buffer.byteLength(value, "utf8");
1556
- const badRequest = (message, remediation) => new CliError("BAD_REQUEST", message, remediation);
1557
- const validatePath = (relativePath, limits) => {
1558
- if (!prototypeArtifactPathSchema.safeParse(relativePath).success) throw badRequest(`Cannot package the prototype path ${relativePath}.`, "Use portable relative NFC paths outside the reserved __enhance directory.");
1559
- 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.`);
1560
- };
1561
- const walk = async (root, directory, ancestors, limits) => {
1562
- const resolvedDirectory = await realpath(directory);
1563
- 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.");
1564
- const nextAncestors = new Set(ancestors).add(resolvedDirectory);
1565
- const { readdir } = await import("node:fs/promises");
1566
- const entries = await readdir(directory, { withFileTypes: true });
1567
- const files = [];
1568
- const orderedEntries = entries.toSorted((left, right) => left.name.localeCompare(right.name));
1569
- for (const entry of orderedEntries) {
1570
- const absolutePath = path.join(directory, entry.name);
1571
- const stats = await statsFor(absolutePath);
1572
- if (stats?.isDirectory() === true) {
1573
- files.push(...await walk(root, absolutePath, nextAncestors, limits));
1574
- continue;
1575
- }
1576
- if (stats?.isFile() !== true) throw badRequest(`Cannot read ${absolutePath} as a prototype file.`, "Pass a directory containing only regular files and directory links.");
1577
- const relativePath = path.relative(root, absolutePath).split(path.sep).join("/").normalize("NFC");
1578
- validatePath(relativePath, limits);
1579
- files.push({
1580
- absolutePath,
1581
- path: relativePath,
1582
- bytes: Number(stats.size),
1583
- contentType: contentTypeOf(absolutePath)
1584
- });
1585
- }
1586
- return files;
1587
- };
1588
- const validateSources = (files, entryPath, limits) => {
1589
- if (files.length === 0) throw badRequest("The prototype build is empty.", "Build the app before publishing it.");
1590
- if (files.length > limits.fileCount) throw badRequest(`The prototype has ${String(files.length)} files.`, `This environment currently accepts ${String(limits.fileCount)} files per deployment.`);
1591
- const folded = /* @__PURE__ */ new Set();
1592
- let totalBytes = 0;
1593
- for (const file of files) {
1594
- const key = foldPrototypeArtifactPath(file.path);
1595
- 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.");
1596
- folded.add(key);
1597
- 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.`);
1598
- totalBytes += file.bytes;
1599
- if (totalBytes > limits.expandedBytes) throw badRequest("The prototype build is too large.", `This environment accepts ${String(limits.expandedBytes)} expanded bytes.`);
1600
- }
1601
- const entry = files.find((file) => file.path === entryPath);
1602
- if (entry === void 0) throw badRequest(`The prototype entry ${entryPath} is missing.`, "Pass --entry with an HTML file inside the build directory.");
1603
- if (!entry.contentType.startsWith("text/html")) throw badRequest(`The prototype entry ${entryPath} is not HTML.`, "Pass an HTML entry file such as index.html.");
1604
- };
1605
- const packageArtifact = async (input) => {
1606
- const root = path.resolve(input.directory);
1607
- const rootStats = await statsFor(root);
1608
- 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.");
1609
- if (!rootStats.isDirectory()) throw badRequest(`${root} is not an unpacked build directory.`, "Pass the build directory; the CLI creates the ZIP artifact automatically.");
1610
- const entryPath = input.entryPath.split(path.sep).join("/").normalize("NFC");
1611
- validatePath(entryPath, input.limits);
1612
- const files = await walk(root, root, /* @__PURE__ */ new Set(), input.limits);
1613
- validateSources(files, entryPath, input.limits);
1614
- const tempDirectory = await mkdtemp(path.join(tmpdir(), "enhance-prototype-artifact-"));
1615
- const artifactPath = path.join(tempDirectory, "artifact.zip");
1616
- try {
1617
- const packaged = await createPrototypeZipAdapter({
1618
- artifactPath,
1619
- files,
1620
- entryPath,
1621
- limits: input.limits
1622
- });
1623
- return {
1624
- identity: {
1625
- protocolVersion: 1,
1626
- format: "zip",
1627
- bytes: packaged.bytes,
1628
- sha256: packaged.sha256,
1629
- fileCount: packaged.manifest.files.length,
1630
- expandedBytes: packaged.manifest.files.reduce((total, file) => total + file.bytes, 0)
1631
- },
1632
- manifest: packaged.manifest,
1633
- open: () => createReadStream(artifactPath),
1634
- dispose: async () => rm(tempDirectory, { recursive: true })
1635
- };
1636
- } catch (error) {
1637
- await rm(tempDirectory, { recursive: true });
1638
- throw error;
1639
- }
1640
- };
1641
- const createPrototypeArtifactAdapter = () => ({ package: packageArtifact });
1642
-
1643
- //#endregion
1644
- //#region src/infrastructure/capability-invocation.adapter.ts
1645
- const renderFor = (input) => createRenderCanvasComposite(input.remote, createRenderFileAdapter(input.configDirectory), input.now ?? (() => /* @__PURE__ */ new Date()), input.progress ?? (() => null));
1646
- const applyCanvas = async (dependencies, offered) => {
1647
- const input = canvasApplyCapabilityInputSchema.parse(offered);
1648
- return createApplyCanvasComposite(dependencies.remote).execute({
1649
- ...input,
1650
- mutationId: dependencies.mutationKey.current("canvas.applyOperations", input)
1651
- });
1652
- };
1653
- const renderCanvas = async (dependencies, offered, retryClientToken) => {
1654
- const input = canvasRenderCapabilityInputSchema.parse(offered);
1655
- return renderFor(dependencies).execute({
1656
- ...input,
1657
- retryClientToken
1658
- });
1659
- };
1660
- const writeCanvasHtml = async (dependencies, offered) => {
1661
- const input = canvasWriteHtmlCapabilityInputSchema.parse(offered);
1662
- return createWriteHtmlCanvasComposite(dependencies.remote, renderFor(dependencies)).execute({
1663
- ...input,
1664
- renderClientToken: dependencies.mutationKey.current("canvas.render.create", { purpose: "write-html-review" })
1665
- });
1666
- };
1667
- const readCommentAttention = async (dependencies, offered) => {
1668
- const input = commentAttentionCapabilityInputSchema.parse(offered);
1669
- return dependencies.remote.query("comment.list", {
1670
- canvasId: input.canvasId,
1671
- filter: "open",
1672
- agentActionable: false
1673
- });
1674
- };
1675
- const publishPrototype = async (dependencies, offered, retryClientToken) => {
1676
- const input = prototypePublishCapabilityInputSchema.parse(offered);
1677
- return createPublishPrototypeComposite(dependencies.remote, createPrototypeArtifactAdapter()).execute({
1678
- ...input,
1679
- clientToken: retryClientToken
1680
- });
1681
- };
1682
- const snapshotRecording = async (dependencies, offered, retryClientToken) => {
1683
- const input = recordingSnapshotCapabilityInputSchema.parse(offered);
1684
- return createSnapshotRecordingComposite(dependencies.remote, dependencies.progress ?? (() => null)).execute({
1685
- ...input,
1686
- retryClientToken
1687
- });
1688
- };
1689
- const readTranscript = async (dependencies, offered) => {
1690
- const input = transcriptReadCapabilityInputSchema.parse(offered);
1691
- return createReadTranscriptComposite(dependencies.remote).execute(input);
1692
- };
1693
- const invokeComposite = async (dependencies, capabilityId, offered, retryClientToken) => {
1694
- switch (capabilityId) {
1695
- case "canvas.edit": {
1696
- const input = canvasEditCapabilityInputSchema.parse(offered);
1697
- const reference = parseCanvasReference(input.canvas);
1698
- return createEditCanvasComposite(dependencies.remote).execute({
1699
- canvasId: reference.canvasId,
1700
- nodeIds: reference.nodeIds,
1701
- baseVersion: input.baseVersion,
1702
- edits: input.edits,
1703
- mutationId: dependencies.mutationKey.current("canvas.applyOperations", input)
1704
- });
1705
- }
1706
- case "canvas.apply": return applyCanvas(dependencies, offered);
1707
- case "canvas.render": return renderCanvas(dependencies, offered, retryClientToken);
1708
- case "canvas.writeHtml": return writeCanvasHtml(dependencies, offered);
1709
- case "comment.attention": return readCommentAttention(dependencies, offered);
1710
- case "prototype.publish": return publishPrototype(dependencies, offered, retryClientToken);
1711
- case "recording.snapshot": return snapshotRecording(dependencies, offered, retryClientToken);
1712
- case "transcript.read": return readTranscript(dependencies, offered);
1713
- default: throw new TypeError(`${capabilityId} has no composite execution`);
1714
- }
1715
- };
1716
- const createCapabilityInvocationAdapter = (input) => ({ invoke: async ({ capability, arguments: offered, clientToken }) => {
1717
- const parsed = capability.inputSchema.parse(offered);
1718
- const selectedClientToken = clientToken ?? randomUUID();
1719
- input.mutationKey.select(selectedClientToken, capability.idempotency === "composite");
1720
- if (capability.execution.kind === "composite") return invokeComposite(input, capability.id, parsed, selectedClientToken);
1721
- return capability.operation === "query" ? input.remote.query(capability.execution.procedure, parsed) : input.remote.mutate(capability.execution.procedure, parsed);
1722
- } });
1723
-
1724
- //#endregion
1725
- //#region src/infrastructure/oauth-loopback.adapter.ts
1726
- const CALLBACK_PATH = "/callback";
1727
- const AUTHORIZATION_TIMEOUT_MS = 12e4;
1728
- const ENTROPY_BYTES = 32;
1729
- const HTTP_OK = 200;
1730
- const HTTP_BAD_REQUEST = 400;
1731
- const HTTP_NOT_FOUND = 404;
1732
- const SUCCESS_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>";
1733
- const endpoint = (issuer, path) => new URL(path, issuer.endsWith("/") ? issuer : `${issuer}/`);
1734
- const launchBrowser = (url) => {
1735
- const command = process.platform === "darwin" ? {
1736
- executable: "open",
1737
- arguments: [url]
1738
- } : process.platform === "win32" ? {
1739
- executable: "rundll32.exe",
1740
- arguments: ["url.dll,FileProtocolHandler", url]
1741
- } : {
1742
- executable: "xdg-open",
1743
- arguments: [url]
1744
- };
1745
- const child = spawn(command.executable, command.arguments, {
1746
- detached: true,
1747
- stdio: "ignore"
1748
- });
1749
- child.once("error", () => false);
1750
- child.unref();
1751
- };
1752
- const handleCallback = (input, request, response) => {
1753
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
1754
- if (request.method !== "GET" || url.pathname !== CALLBACK_PATH) {
1755
- response.writeHead(HTTP_NOT_FOUND).end();
1756
- return;
1757
- }
1758
- if (url.searchParams.get("state") !== input.state) {
1759
- response.writeHead(HTTP_BAD_REQUEST).end("The OAuth state did not match. Return to the terminal and retry.");
1760
- return;
1761
- }
1762
- const error = url.searchParams.get("error");
1763
- const received = url.searchParams.get("code");
1764
- if (error !== null || received === null || received === "") {
1765
- response.writeHead(HTTP_BAD_REQUEST).end("Enhance authentication was not approved.");
1766
- input.completion.reject(new Error(error ?? "the authorization response carried no code"));
1767
- return;
1768
- }
1769
- response.writeHead(HTTP_OK, { "content-type": "text/html; charset=utf-8" }).end(SUCCESS_PAGE);
1770
- input.completion.resolve(received);
1771
- };
1772
- const authorizeUrl = (input) => {
1773
- const authorize = endpoint(input.issuer, "oauth/authorize");
1774
- authorize.search = new URLSearchParams({
1775
- response_type: "code",
1776
- client_id: input.clientId,
1777
- redirect_uri: input.redirectUri,
1778
- scope: input.scope,
1779
- state: input.state,
1780
- code_challenge: input.challenge,
1781
- code_challenge_method: "S256"
1782
- }).toString();
1783
- return authorize.href;
1784
- };
1785
- const authorizationCode = async (input) => {
1786
- input.signal?.throwIfAborted();
1787
- const completion = Promise.withResolvers();
1788
- const server = createServer((request, response) => {
1789
- handleCallback({
1790
- state: input.state,
1791
- completion
1792
- }, request, response);
1793
- });
1794
- await new Promise((resolve, reject) => {
1795
- server.once("error", reject);
1796
- server.listen(0, "127.0.0.1", resolve);
1797
- });
1798
- const address = server.address();
1799
- if (address === null || typeof address === "string") {
1800
- server.close();
1801
- throw new Error("the OAuth callback listener has no TCP port");
1802
- }
1803
- const redirectUri = `http://127.0.0.1:${String(address.port)}${CALLBACK_PATH}`;
1804
- const url = authorizeUrl({
1805
- ...input,
1806
- redirectUri
1807
- });
1808
- const abort = () => {
1809
- completion.reject(/* @__PURE__ */ new Error("browser authorization cancelled"));
1810
- };
1811
- input.signal?.addEventListener("abort", abort, { once: true });
1812
- const timeout = setTimeout(() => {
1813
- completion.reject(/* @__PURE__ */ new Error("browser authorization timed out"));
1814
- }, AUTHORIZATION_TIMEOUT_MS);
1815
- try {
1816
- input.signal?.throwIfAborted();
1817
- input.onReady(url);
1818
- if (input.openBrowser) launchBrowser(url);
1819
- return {
1820
- code: await completion.promise,
1821
- redirectUri
1822
- };
1823
- } finally {
1824
- clearTimeout(timeout);
1825
- input.signal?.removeEventListener("abort", abort);
1826
- await new Promise((resolve) => {
1827
- server.close(() => {
1828
- resolve();
1829
- });
1830
- });
1831
- }
1832
- };
1833
- const createOauthLoopbackAdapter = (remote) => ({ authorize: async (input) => {
1834
- try {
1835
- const verifier = randomBytes(ENTROPY_BYTES).toString("base64url");
1836
- const challenge = createHash("sha256").update(verifier).digest("base64url");
1837
- const state = randomBytes(ENTROPY_BYTES).toString("base64url");
1838
- const authorized = await authorizationCode({
1839
- ...input,
1840
- challenge,
1841
- state
1842
- });
1843
- return await remote.exchangeOauthCode({
1844
- issuer: input.issuer,
1845
- clientId: input.clientId,
1846
- code: authorized.code,
1847
- redirectUri: authorized.redirectUri,
1848
- verifier
1849
- });
1850
- } catch (error) {
1851
- 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.");
1852
- }
1853
- } });
1854
-
1855
- //#endregion
1856
- //#region src/infrastructure/environment-profile.lib.ts
1857
- const explicitValue = (value) => value === void 0 || value === "" ? void 0 : value;
1858
- const resolveCliConfig = (variables, homeDirectory, release) => {
1859
- const requestedEnvironment = explicitValue(variables.ENHANCE3_ENVIRONMENT);
1860
- if (requestedEnvironment !== void 0 && requestedEnvironment !== release.environment) throw new TypeError(`the Enhance ${release.environment} CLI cannot target ${requestedEnvironment}`);
1861
- const requestedApi = explicitValue(variables.ENHANCE3_API_URL);
1862
- const expectedConfigDirectory = path.join(homeDirectory, ".config", release.configDirectoryName);
1863
- const requestedConfigDirectory = explicitValue(variables.ENHANCE3_CONFIG_DIR);
1864
- if (release.environment === "development") {
1865
- if (requestedApi !== void 0 && requestedApi !== release.apiUrl) throw new TypeError(`Enhance development cannot use ${requestedApi}`);
1866
- if (requestedConfigDirectory !== void 0 && path.resolve(requestedConfigDirectory) !== path.resolve(expectedConfigDirectory)) throw new TypeError(`Enhance development credentials must stay in ${expectedConfigDirectory}`);
1867
- }
1868
- return {
1869
- apiUrl: requestedApi ?? release.apiUrl,
1870
- commandName: release.commandName,
1871
- configDirectory: requestedConfigDirectory ?? expectedConfigDirectory,
1872
- mcpServiceName: release.mcpServiceName
1873
- };
1874
- };
1875
-
1876
- //#endregion
1877
- //#region src/infrastructure/remote-mcp.config.ts
1878
- const remoteMcpConfigSchema = z.object({
1879
- PORT: z.coerce.number().int().min(1).max(65535).default(3e3),
1880
- MCP_HOST: z.string().min(1).default("0.0.0.0"),
1881
- ENHANCE_API_URL: z.url(),
1882
- MCP_AUTH_ISSUER: z.url(),
1883
- MCP_RESOURCE_URL: z.url(),
1884
- MCP_SERVICE_DOCUMENTATION_URL: z.url().default("https://enhancelabs.ai"),
1885
- MCP_ALLOWED_HOSTS: z.string().min(1),
1886
- MCP_ALLOWED_ORIGINS: z.string().min(1).default("claude.ai,claude.com")
1887
- });
1888
- const readRemoteMcpConfig = (variables) => remoteMcpConfigSchema.parse(variables);
1889
-
1890
- //#endregion
1891
- //#region src/infrastructure/environment.config.ts
1892
- const releaseProfile = {
1893
- apiUrl: "https://api.enhancelabs.ai",
1894
- commandName: "enhance",
1895
- configDirectoryName: "enhance",
1896
- environment: "production",
1897
- mcpServiceName: "enhance-mcp"
1898
- };
1899
- const CLI_CONFIG = resolveCliConfig(process.env, homedir(), releaseProfile);
1900
- const readRemoteMcpEnvironment = () => readRemoteMcpConfig(process.env);
1901
-
1902
- //#endregion
1903
- //#region src/infrastructure/http-remote.adapter.ts
1904
- const HEALTH_TIMEOUT_MS = 4e3;
1905
- const NOT_FOUND_STATUS = 404;
1906
- const FORBIDDEN_STATUS = 403;
1907
- const oauthTokenResponseSchema = z.object({ access_token: z.string().min(1) });
1908
- const networkCodeSchema = z.object({ code: z.string().regex(/^[A-Z][A-Z_0-9]+$/u) });
1909
- const NETWORK_REMEDIATION = "Check network access and proxy settings for this API, then run enhance doctor again.";
1910
- const originOf = (input) => new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).origin;
1911
- const networkReason = (error) => {
1912
- const parsed = networkCodeSchema.safeParse(error);
1913
- if (parsed.success) return parsed.data.code;
1914
- if (error instanceof Error && error.cause !== void 0) return networkReason(error.cause);
1915
- return error instanceof Error ? error.name : "Network request failed";
1916
- };
1917
- const httpFailure = (url, status) => new CliError("INTERNAL", `${originOf(url)} answered HTTP ${String(status)}.`, NETWORK_REMEDIATION);
1918
- const fetchNetwork = async (input, init) => {
1919
- try {
1920
- return await fetch(input, init);
1921
- } catch (error) {
1922
- throw new CliError("INTERNAL", `Could not reach ${originOf(input)}: ${networkReason(error)}.`, NETWORK_REMEDIATION);
1923
- }
1924
- };
1925
- const fetchApi = async (input, init) => {
1926
- const response = await fetchNetwork(input, init);
1927
- if (!response.ok && response.headers.get("content-type")?.includes("application/json") !== true) throw httpFailure(input, response.status);
1928
- return response;
1929
- };
1930
- const clientFor = (apiUrl, token, idempotencyKey = null) => createTRPCUntypedClient({ links: [httpLink({
1931
- url: `${apiUrl}/trpc`,
1932
- fetch: async (input, init) => fetchApi(input, {
1933
- ...init,
1934
- signal: init?.signal ?? null
1935
- }),
1936
- headers: {
1937
- ...token !== null && { authorization: `Bearer ${token}` },
1938
- ...idempotencyKey !== null && { "x-enhance-idempotency-key": idempotencyKey }
1939
- }
1940
- })] });
1941
- const download = async (url) => {
1942
- const response = await fetch(url);
1943
- 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.");
1944
- return new Uint8Array(await response.arrayBuffer());
1945
- };
1946
- const authenticationConfig = async (apiUrl) => {
1947
- const response = await fetchNetwork(`${apiUrl}/v1/cli-auth`);
1948
- if (!response.ok) {
1949
- 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'.");
1950
- throw new CliError("INTERNAL", `${originOf(apiUrl)} CLI authentication discovery answered HTTP ${String(response.status)}.`, NETWORK_REMEDIATION);
1951
- }
1952
- return response.json();
1953
- };
1954
- const oauthMetadata = async (issuer) => {
1955
- const base = issuer.endsWith("/") ? issuer : `${issuer}/`;
1956
- const response = await fetchNetwork(new URL(".well-known/oauth-authorization-server", base));
1957
- if (!response.ok) throw httpFailure(issuer, response.status);
1958
- return response.json();
1959
- };
1960
- const exchangeOauthCode = async (input) => {
1961
- const response = await fetchNetwork(new URL("oauth/token", input.issuer.endsWith("/") ? input.issuer : `${input.issuer}/`), {
1962
- method: "POST",
1963
- headers: { "content-type": "application/x-www-form-urlencoded" },
1964
- body: new URLSearchParams({
1965
- grant_type: "authorization_code",
1966
- client_id: input.clientId,
1967
- code: input.code,
1968
- redirect_uri: input.redirectUri,
1969
- code_verifier: input.verifier
1970
- })
1971
- });
1972
- if (!response.ok) throw new CliError("INTERNAL", `${originOf(input.issuer)} token exchange answered HTTP ${String(response.status)}`, NETWORK_REMEDIATION);
1973
- return oauthTokenResponseSchema.parse(await response.json()).access_token;
1974
- };
1975
- const health = async (apiUrl) => {
1976
- try {
1977
- const response = await fetchNetwork(`${apiUrl}/health`, { signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS) });
1978
- return {
1979
- url: apiUrl,
1980
- reachable: response.ok,
1981
- status: response.status,
1982
- ...!response.ok && { error: httpFailure(apiUrl, response.status).message }
1983
- };
1984
- } catch (error) {
1985
- return {
1986
- url: apiUrl,
1987
- reachable: false,
1988
- status: null,
1989
- error: error instanceof Error ? error.message : `Could not reach ${originOf(apiUrl)}.`
1990
- };
1991
- }
1992
- };
1993
- const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey) => {
1994
- const normalized = apiUrl.replace(/\/$/, "");
1995
- return {
1996
- authenticationConfig: async () => authenticationConfig(normalized),
1997
- oauthMetadata,
1998
- exchangeOauthCode,
1999
- query: async (path, input) => clientFor(normalized, await credentials.read()).query(path, input),
2000
- queryWithToken: async (path, input, token) => clientFor(normalized, token).query(path, input),
2001
- mutate: async (procedure, input) => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input)).mutation(procedure, input),
2002
- mutateWithToken: async (procedure, input, token) => clientFor(normalized, token).mutation(procedure, input),
2003
- download,
2004
- upload: async (input) => {
2005
- const isStreaming = !(input.body instanceof Uint8Array);
2006
- const body = isStreaming ? Readable.toWeb(input.body) : input.body;
2007
- const request = {
2008
- method: "PUT",
2009
- headers: input.headers,
2010
- body,
2011
- ...isStreaming && { duplex: "half" }
2012
- };
2013
- const response = await fetch(input.url, request);
2014
- if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
2015
- const etag = response.headers.get("etag");
2016
- if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
2017
- return etag.replaceAll("\"", "");
2018
- },
2019
- health: async () => health(normalized)
2020
- };
2021
- };
2022
-
2023
- //#endregion
2024
- //#region src/infrastructure/mutation-key.adapter.ts
2025
- const ordered = (value) => {
2026
- if (Array.isArray(value)) return value.map((entry) => ordered(entry));
2027
- if (typeof value !== "object" || value === null) return value;
2028
- return Object.fromEntries(Object.entries(value).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, held]) => [key, ordered(held)]));
2029
- };
2030
- const childKey = (selected, procedure, input) => {
2031
- 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");
2032
- };
2033
- const createMutationKeyAdapter = () => {
2034
- let selected = randomUUID();
2035
- let isComposite = false;
2036
- return {
2037
- current: (procedure, input) => isComposite ? childKey(selected, procedure, input) : selected,
2038
- select: (clientToken, selectedForComposite) => {
2039
- selected = clientToken ?? randomUUID();
2040
- isComposite = selectedForComposite;
2041
- }
2042
- };
2043
- };
2044
-
2045
- //#endregion
2046
- export { createOauthLoopbackAdapter as a, createWriteHtmlCanvasComposite as c, createApplyCanvasComposite as d, createCanvasActivityComposite as f, readRemoteMcpEnvironment as i, createEditCanvasComposite as l, createAuthUseCase as m, createHttpRemoteAdapter as n, createCapabilityInvocationAdapter as o, createRenderCanvasComposite as p, CLI_CONFIG as r, createRenderFileAdapter as s, createMutationKeyAdapter as t, sceneAtVersion as u };