@enhance-eng/enhance 0.1.6 → 0.1.13

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.
package/dist/main.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { B as canvasAgentActivityPhaseSchema, C as completeRecordingOutputSchema, G as getCanvasDocumentOutputSchema, I as cliAuthConfigurationSchema, K as saveCanvasDocumentOutputSchema, L as createAgentTokenOutputSchema, P as getMeOutputSchema, R as createOrganisationOutputSchema, S as appendRecordingChunkOutputSchema, U as canvasOperationSchema, V as MAX_CANVAS_OPERATIONS, W as canvasNodeStylePatchSchema, X as canvasWorldBoundsSchema, Y as RENDER_MIN_SCALE, _ as CliError, a as createRouterShapeAdapter, b as completeScreenOutputSchema, c as PROCEDURE_DESCRIPTIONS, g as PartialBatchError, i as createCapabilityCatalogAdapter, n as toFailurePayload, nt as canvasSchema, o as createCapabilityPolicyAdapter, r as ProcessExitError, s as OPTION_DESCRIPTIONS, t as toExitCode, tt as canvasSceneDocumentSchema, w as startRecordingOutputSchema, x as createScreenOutputSchema, y as appErrorSchema, z as beginCanvasActivityOutputSchema } from "./failure.mapper-CNRVSTrf.mjs";
3
- import { a as createCapabilityInvocationAdapter, c as createApplyCanvasComposite, l as createCanvasActivityComposite, n as createHttpRemoteAdapter, o as createRenderFileAdapter, r as CLI_CONFIG, s as createWriteHtmlCanvasComposite, t as createMutationKeyAdapter, u as createRenderCanvasComposite } from "./mutation-key.adapter-B7Ss_464.mjs";
4
- import { t as toCapabilityInventory } from "./capability-inventory.mapper-DN3TEDbU.mjs";
5
- import { t as createFileCredentialAdapter } from "./file-credential.adapter-WNl4GM58.mjs";
2
+ import { $ as canvasLayoutWithoutCssProperties, A as startRecordingOutputSchema, C as CliError, D as createScreenOutputSchema, E as completeScreenOutputSchema, G as emptyFixtureDocument, J as canvasAgentActivityPhaseSchema, K as withFixtureScreen, O as appendRecordingChunkOutputSchema, Q as canvasNodeStylePatchSchema, S as PartialBatchError, T as appErrorSchema, W as createOrganisationOutputSchema, Y as MAX_CANVAS_OPERATIONS, Z as canvasOperationSchema, _t as canvasSchema, at as canvasWorldBoundsSchema, c as ProcessExitError, d as createCapabilityPolicyAdapter, dt as canvasAdditionalStyleSchema, et as getCanvasDocumentOutputSchema, ft as canvasAuthoredLayoutValueOf, gt as canvasLayoutPriorityDeclarations, ht as canvasLayoutMainAxisOf, i as toFailurePayload, it as RENDER_MIN_SCALE, k as completeRecordingOutputSchema, l as createCapabilityCatalogAdapter, m as PROCEDURE_DESCRIPTIONS, mt as canvasAxisStyleProperties, n as withCommandName, o as toSharedCapabilities, p as OPTION_DESCRIPTIONS, pt as canvasAuthoredStyleDeclarations, q as beginCanvasActivityOutputSchema, r as toExitCode, s as createMcpCapabilityDiscoveryAdapter, t as withCommandInFailure, tt as saveCanvasDocumentOutputSchema, u as createRouterShapeAdapter, ut as canvasReadableSceneDocumentSchema } from "./cli-output-identity.lib-DAJiBMGX.mjs";
3
+ import { a as createOauthLoopbackAdapter, c as createWriteHtmlCanvasComposite, d as createRenderCanvasComposite, f as createAuthUseCase, l as createApplyCanvasComposite, n as createHttpRemoteAdapter, o as createCapabilityInvocationAdapter, r as CLI_CONFIG, s as createRenderFileAdapter, t as createMutationKeyAdapter, u as createCanvasActivityComposite } from "./mutation-key.adapter-BffKsNR-.mjs";
4
+ import { t as toCapabilityInventory } from "./capability-inventory.mapper-DyYXyVBJ.mjs";
5
+ import { t as createFileCredentialAdapter } from "./file-credential.adapter-rI5HpMEo.mjs";
6
6
  import { Command } from "commander";
7
7
  import { createCli, parseRouter } from "trpc-cli";
8
8
  import { z } from "zod";
@@ -11,72 +11,10 @@ import process from "node:process";
11
11
  import { createInterface } from "node:readline";
12
12
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
13
13
  import path from "node:path";
14
- import { createHash, randomBytes, randomUUID } from "node:crypto";
14
+ import { createHash, randomUUID } from "node:crypto";
15
15
  import { readFile } from "node:fs/promises";
16
- import { spawn } from "node:child_process";
17
- import { createServer } from "node:http";
18
16
  import { proxify } from "trpc-cli/dist/proxify.js";
19
- //#region ../../packages/contract/src/canvas/canvas-presentation-defaults.lib.ts
20
- const emptyCanvasNodeLayout = () => ({
21
- rotation: 0,
22
- flipHorizontal: false,
23
- flipVertical: false,
24
- horizontal: {
25
- mode: "fixed",
26
- value: 0
27
- },
28
- vertical: {
29
- mode: "fixed",
30
- value: 0
31
- },
32
- position: "absolute",
33
- clipContent: false
34
- });
35
- //#endregion
36
- //#region ../../packages/contract/src/fixture/canvas-fixture.lib.ts
37
- const ROOT_FIXTURE_NODE_ID = "root";
38
- const SORT_KEY_DIGITS = 4;
39
- const sortKeyAt = (seat) => `a${String(seat).padStart(SORT_KEY_DIGITS, "0")}`;
40
- const emptyFixtureDocument = () => ({
41
- version: 2,
42
- nodes: { [ROOT_FIXTURE_NODE_ID]: {
43
- id: ROOT_FIXTURE_NODE_ID,
44
- label: "Canvas",
45
- component: "root",
46
- styles: {}
47
- } },
48
- relationships: {}
49
- });
50
- const withFixtureNode = (document, node) => ({
51
- ...document,
52
- nodes: {
53
- ...document.nodes,
54
- [node.id]: node
55
- },
56
- relationships: {
57
- ...document.relationships,
58
- [node.id]: {
59
- parentId: ROOT_FIXTURE_NODE_ID,
60
- sortKey: sortKeyAt(Object.keys(document.relationships).length)
61
- }
62
- }
63
- });
64
- const withFixtureScreen = (document, input) => withFixtureNode(document, {
65
- id: input.id,
66
- label: input.label,
67
- component: "screen",
68
- props: { capture: {
69
- viewport: input.viewport,
70
- atMs: 0,
71
- screenId: input.screenId
72
- } },
73
- styles: {},
74
- box: {
75
- ...input.at,
76
- ...input.viewport
77
- }
78
- });
79
- //#endregion
17
+
80
18
  //#region ../../packages/contract/src/recording/event-stream.lib.ts
81
19
  /**
82
20
  * @justified docs/comments.md#intent
@@ -146,52 +84,7 @@ const cutStream = (entries, limit) => {
146
84
  const writer = streamWriter(limit);
147
85
  return [...entries.flatMap((entry) => writer.add(entry)), ...writer.drain()];
148
86
  };
149
- //#endregion
150
- //#region src/application/auth.use-case.ts
151
- const TOKEN = /^enh_[\w-]{43}$/;
152
- const authenticated = (value) => {
153
- const parsed = getMeOutputSchema.parse(value);
154
- 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.");
155
- return {
156
- authenticated: true,
157
- personId: parsed.person.id,
158
- displayName: parsed.person.displayName,
159
- tokenId: parsed.authentication.tokenId,
160
- tokenLabel: parsed.authentication.tokenLabel,
161
- expiresAt: parsed.authentication.expiresAt
162
- };
163
- };
164
- const createAuthUseCase = (credentials, remote, browser) => ({
165
- loginWithToken: async (token) => {
166
- 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.");
167
- const status = authenticated(await remote.queryWithToken("person.me", {}, token));
168
- await credentials.write(token);
169
- return status;
170
- },
171
- loginWithBrowser: async (input) => {
172
- const configuration = cliAuthConfigurationSchema.parse(await remote.authenticationConfig());
173
- 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'.");
174
- const accessToken = await browser.authorize({
175
- issuer: configuration.issuer,
176
- clientId: configuration.clientId,
177
- scope: configuration.scope,
178
- openBrowser: input.openBrowser,
179
- onReady: input.onReady
180
- });
181
- const created = createAgentTokenOutputSchema.parse(await remote.mutateWithToken("person.createAgentToken", {
182
- label: input.label,
183
- expiresAt: null
184
- }, accessToken));
185
- const status = authenticated(await remote.queryWithToken("person.me", {}, created.token));
186
- await credentials.write(created.token);
187
- return status;
188
- },
189
- status: async () => {
190
- if (await credentials.read() === null) throw new CliError("UNAUTHORIZED", `No credential exists at ${credentials.path}.`, "A human must run 'enhance auth login'.");
191
- return authenticated(await remote.query("person.me", {}));
192
- },
193
- logout: async () => ({ loggedOut: await credentials.remove() })
194
- });
87
+
195
88
  //#endregion
196
89
  //#region src/application/recording-fixture.composite.ts
197
90
  const CHUNK_LIMIT = 8 * 1048576;
@@ -243,6 +136,7 @@ const createRecordingFixtureComposite = (remote) => async (input) => {
243
136
  throw new PartialBatchError(`Recording ${started.recordingId} began, but not every chunk was committed.`, `Run 'enhance recording discard --recording-id ${started.recordingId}' to remove the incomplete attempt before retrying the fixture.`);
244
137
  }
245
138
  };
139
+
246
140
  //#endregion
247
141
  //#region src/application/screen-fixture.composite.ts
248
142
  const SCREEN_FIXTURE_PROCEDURES = ["screen.create", "screen.complete"];
@@ -280,6 +174,7 @@ const createScreenFixtureComposite = (remote) => async (input) => {
280
174
  throw new PartialBatchError(`Screen ${created.screenId} was reserved, but its upload did not complete.`, `Retry 'enhance fixture screen' with the same --client-token ${input.clientToken}.`);
281
175
  }
282
176
  };
177
+
283
178
  //#endregion
284
179
  //#region src/application/world-fixture.composite.ts
285
180
  const WORLD_FIXTURE_PROCEDURES = [
@@ -334,6 +229,7 @@ const createWorldFixtureComposite = (remote, createScreen) => async (input) => {
334
229
  throw new PartialBatchError(`Organisation ${organisation.id} and canvas ${canvas.id} exist, but the world is incomplete.`, `Inspect 'enhance canvas get --canvas-id ${canvas.id}' before retrying any missing steps.`);
335
230
  }
336
231
  };
232
+
337
233
  //#endregion
338
234
  //#region src/infrastructure/stdin-token.lib.ts
339
235
  const readToken = async (offered, command) => {
@@ -365,6 +261,7 @@ const readOptionalToken = async (offered) => {
365
261
  }
366
262
  return null;
367
263
  };
264
+
368
265
  //#endregion
369
266
  //#region src/infrastructure/auth.program.ts
370
267
  const MAX_TOKEN_LABEL_CHARACTERS = 120;
@@ -394,6 +291,219 @@ const registerAuthProgram = (program, auth, output) => {
394
291
  output.result(await auth.logout());
395
292
  });
396
293
  };
294
+
295
+ //#endregion
296
+ //#region src/infrastructure/canvas-authoring-input.schema.ts
297
+ const NODE_ID_LENGTH = 200;
298
+ const NODE_NAME_LENGTH = 500;
299
+ const TEXT_LENGTH = 1e5;
300
+ const MAX_NODE_IDS = 1e3;
301
+ const MAX_BATCHES = 100;
302
+ const MAX_DEPTH = 20;
303
+ const MIN_RENDER_SCALE = .1;
304
+ const MAX_RENDER_SCALE = 4;
305
+ const positiveIntegerSchema = z.coerce.number().int().positive();
306
+ const renderScaleSchema = z.coerce.number().min(MIN_RENDER_SCALE).max(MAX_RENDER_SCALE);
307
+ const authoringUuidSchema = z.uuid();
308
+ const styleValueSchema = z.union([
309
+ z.string(),
310
+ z.number(),
311
+ z.null()
312
+ ]);
313
+ const styleObjectSchema = z.record(z.string(), styleValueSchema);
314
+ const textUpdatesSchema = z.array(z.object({
315
+ nodeId: z.string().min(1).max(NODE_ID_LENGTH),
316
+ textContent: z.string().max(TEXT_LENGTH)
317
+ })).min(1).max(MAX_NODE_IDS);
318
+ const renameUpdatesSchema = z.array(z.object({
319
+ nodeId: z.string().min(1).max(NODE_ID_LENGTH),
320
+ name: z.string().max(NODE_NAME_LENGTH)
321
+ })).min(1).max(MAX_NODE_IDS);
322
+ const styleUpdatesSchema = z.array(z.object({
323
+ nodeIds: z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_BATCHES),
324
+ styles: styleObjectSchema
325
+ })).min(1).max(MAX_BATCHES);
326
+ const duplicateInputsSchema = z.array(z.object({
327
+ id: z.string().min(1).max(NODE_ID_LENGTH),
328
+ parentId: z.string().min(1).max(NODE_ID_LENGTH).optional()
329
+ })).min(1).max(MAX_BATCHES);
330
+ const moveInputsSchema = z.array(z.union([
331
+ z.object({
332
+ nodeId: z.string().min(1).max(NODE_ID_LENGTH),
333
+ before: z.string().min(1).max(NODE_ID_LENGTH)
334
+ }),
335
+ z.object({
336
+ nodeId: z.string().min(1).max(NODE_ID_LENGTH),
337
+ after: z.string().min(1).max(NODE_ID_LENGTH)
338
+ }),
339
+ z.object({
340
+ nodeId: z.string().min(1).max(NODE_ID_LENGTH),
341
+ parentId: z.string().min(1).max(NODE_ID_LENGTH),
342
+ index: z.number().int().nonnegative().optional()
343
+ })
344
+ ])).min(1).max(MAX_BATCHES);
345
+ const nodeIdsSchema = z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_NODE_IDS);
346
+ const sourceDepthSchema = z.coerce.number().int().min(0).max(MAX_DEPTH);
347
+
348
+ //#endregion
349
+ //#region src/infrastructure/canvas-reference.lib.ts
350
+ const canvasIdSchema = z.uuid();
351
+ const selectedIdsSchema = z.array(z.string().min(1).max(200)).min(1);
352
+ const CANVAS_PATH = /^\/c\/([^/]+)\/?$/u;
353
+ const urlFrom = (candidate) => {
354
+ try {
355
+ return new URL(candidate);
356
+ } catch {
357
+ return null;
358
+ }
359
+ };
360
+ const parseCanvasReference = (reference) => {
361
+ const candidate = reference.trim();
362
+ const direct = canvasIdSchema.safeParse(candidate);
363
+ if (direct.success) return {
364
+ canvasId: direct.data,
365
+ nodeIds: []
366
+ };
367
+ const url = urlFrom(candidate);
368
+ if (url !== null && (url.protocol === "http:" || url.protocol === "https:")) {
369
+ const id = canvasIdSchema.safeParse(CANVAS_PATH.exec(url.pathname.toLowerCase())?.[1]);
370
+ if (id.success) {
371
+ const selection = new URLSearchParams(url.hash.slice(1)).getAll("selection");
372
+ if (selection.length === 0) return {
373
+ canvasId: id.data,
374
+ nodeIds: []
375
+ };
376
+ const parsed = selectedIdsSchema.safeParse(selection);
377
+ if (!parsed.success) throw new CliError("BAD_REQUEST", "The link contains an invalid selection.", "Copy the selection link again from the canvas.");
378
+ return {
379
+ canvasId: id.data,
380
+ nodeIds: [...new Set(parsed.data)]
381
+ };
382
+ }
383
+ }
384
+ throw new CliError("BAD_REQUEST", "The canvas reference is neither a canvas URL nor a UUID.", "Paste an HTTP(S) URL shaped https://app.example/c/<UUID>, or pass the bare canvas UUID.");
385
+ };
386
+ const fromCanvasReference = (reference) => {
387
+ const parsed = parseCanvasReference(reference);
388
+ if (parsed.nodeIds.length > 0) throw new CliError("BAD_REQUEST", `This command cannot discard the link selection: ${parsed.nodeIds.join(", ")}.`, "Inspect the selection with canvas tree and use a targeted edit. Use a canvas URL without a selection only when the request covers the whole canvas.");
389
+ return parsed.canvasId;
390
+ };
391
+ const canvasReferenceNodeIds = (reference, document) => {
392
+ const missing = reference.nodeIds.filter((id) => document.nodes[id] === void 0);
393
+ if (missing.length > 0) throw new CliError("NOT_FOUND", `The link selection no longer exists: ${missing.join(", ")}.`, "Copy a current selection link; do not substitute other canvas content.");
394
+ const selected = new Set(reference.nodeIds);
395
+ const descendants = (parentId) => {
396
+ for (const [id, relationship] of Object.entries(document.relationships)) {
397
+ if (relationship.parentId !== parentId || selected.has(id)) continue;
398
+ selected.add(id);
399
+ descendants(id);
400
+ }
401
+ };
402
+ for (const id of reference.nodeIds) descendants(id);
403
+ return selected;
404
+ };
405
+ const assertCanvasReferenceNodes = (reference, document, nodeIds) => {
406
+ if (reference.nodeIds.length === 0) return;
407
+ const scope = canvasReferenceNodeIds(reference, document);
408
+ assertNodesInScope(scope, nodeIds);
409
+ };
410
+ const assertNodesInScope = (scope, nodeIds) => {
411
+ const outside = nodeIds.filter((id) => !scope.has(id));
412
+ if (outside.length > 0) throw new CliError("BAD_REQUEST", `These nodes are outside the link selection: ${outside.join(", ")}.`, "Limit the edit to the selected nodes and their descendants. Request a wider selection only when the person wants a wider change.");
413
+ };
414
+ const conversionScope = (operation) => {
415
+ if (operation.destination.kind === "adjacent") throw new CliError("BAD_REQUEST", "Adjacent conversion would insert outside the link selection.", "Use insert-children or replace with a selected target.");
416
+ return {
417
+ required: [operation.destination.targetNodeId],
418
+ inserted: Object.keys(operation.nodes)
419
+ };
420
+ };
421
+ const operationScope = (operation, document) => {
422
+ switch (operation.op) {
423
+ case "insertNode": return {
424
+ required: [operation.parentage.parentId],
425
+ inserted: [operation.node.id]
426
+ };
427
+ case "insertText":
428
+ case "insertPrototype": return {
429
+ required: [operation.parentId, ...operation.afterId === void 0 ? [] : [operation.afterId]],
430
+ inserted: [operation.nodeId]
431
+ };
432
+ case "insertConvertedSubtree": return conversionScope(operation);
433
+ case "move":
434
+ case "setParentage": {
435
+ const parentId = operation.op === "move" ? operation.parentId : operation.parentage.parentId;
436
+ return {
437
+ required: [operation.nodeId, ...parentId === document.relationships[operation.nodeId]?.parentId ? [] : [parentId]],
438
+ inserted: []
439
+ };
440
+ }
441
+ case "setPrototypeDeployment":
442
+ case "setText":
443
+ case "setBox":
444
+ case "setLabel":
445
+ case "setContainerKind":
446
+ case "setVisibility":
447
+ case "setLocked":
448
+ case "setConstraints":
449
+ case "setStyles":
450
+ case "setAppearance":
451
+ case "setLayout":
452
+ case "setTypography":
453
+ case "setAdditionalStyles":
454
+ case "setProps":
455
+ case "remove": return {
456
+ required: [operation.nodeId],
457
+ inserted: []
458
+ };
459
+ }
460
+ };
461
+ const assertCanvasReferenceOperations = (reference, document, operations) => {
462
+ if (reference.nodeIds.length === 0) return;
463
+ const scope = new Set(canvasReferenceNodeIds(reference, document));
464
+ for (const operation of operations) {
465
+ const { required, inserted } = operationScope(operation, document);
466
+ assertNodesInScope(scope, [...required, ...inserted.filter((id) => document.nodes[id] !== void 0)]);
467
+ for (const id of inserted) scope.add(id);
468
+ }
469
+ };
470
+
471
+ //#endregion
472
+ //#region src/infrastructure/canvas-authoring-command.lib.ts
473
+ const uuidNullableSchema = z.uuid().nullable();
474
+ const authoringNumberFrom = (schema, value, option) => {
475
+ const parsed = schema.safeParse(value);
476
+ if (parsed.success) return parsed.data;
477
+ throw new CliError("BAD_REQUEST", `${option} is invalid.`, "Run the command with --help.");
478
+ };
479
+ const authoringBaseVersion = (value) => authoringNumberFrom(positiveIntegerSchema, value, "--base-version");
480
+ const selectAuthoringToken = (input, value, isComposite) => {
481
+ const parsed = uuidNullableSchema.safeParse(value ?? null);
482
+ if (!parsed.success) throw new CliError("BAD_REQUEST", "--client-token must be a UUID.", "Mint one UUID and reuse it only when retrying the exact same command.");
483
+ input.mutationKey.select(parsed.data, isComposite);
484
+ };
485
+ const authoringMutationId = (input, purpose) => input.mutationKey.current("canvas.applyOperations", { purpose });
486
+ const sceneAtVersion = async (input, canvasId, expectedVersion) => {
487
+ const held = getCanvasDocumentOutputSchema.safeParse(await input.remote.query("canvas.document.get", { canvasId }));
488
+ if (!held.success) throw new CliError("INTERNAL", "The API returned an invalid canvas document.", "Run `enhance doctor` and report incompatible API and CLI versions.");
489
+ if (held.data.version !== expectedVersion) throw new CliError("CONFLICT", `Canvas version ${String(held.data.version)} no longer matches --base-version ${String(expectedVersion)}.`, `Run 'enhance canvas tree --canvas ${canvasId}' and recompute against version ${String(held.data.version)}.`);
490
+ const scene = canvasReadableSceneDocumentSchema.safeParse(held.data.document);
491
+ if (scene.success) return scene.data;
492
+ 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.");
493
+ };
494
+ const applyAuthoringOperations = async (input, options, purpose, operations) => {
495
+ selectAuthoringToken(input, options.clientToken, false);
496
+ const reference = parseCanvasReference(options.canvas);
497
+ const baseVersion = authoringBaseVersion(options.baseVersion);
498
+ if (reference.nodeIds.length > 0) assertCanvasReferenceOperations(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), operations);
499
+ return createApplyCanvasComposite(input.remote).execute({
500
+ canvasId: reference.canvasId,
501
+ mutationId: authoringMutationId(input, purpose),
502
+ baseVersion,
503
+ operations: [...operations]
504
+ });
505
+ };
506
+
397
507
  //#endregion
398
508
  //#region src/infrastructure/canvas-operation-input.adapter.ts
399
509
  const MAX_OPERATION_FILE_BYTES = 1048576;
@@ -428,29 +538,7 @@ const createCanvasOperationInputAdapter = (value) => {
428
538
  }
429
539
  return parsed.data;
430
540
  };
431
- //#endregion
432
- //#region src/infrastructure/canvas-reference.mapper.ts
433
- const canvasIdSchema = z.uuid();
434
- const CANVAS_PATH = /^\/c\/([^/]+)\/?$/u;
435
- const fromCanvasUrl = (candidate) => {
436
- try {
437
- const url = new URL(candidate);
438
- if (url.protocol !== "https:" && url.protocol !== "http:") return null;
439
- const match = CANVAS_PATH.exec(url.pathname.toLowerCase());
440
- const fromPath = canvasIdSchema.safeParse(match?.[1]);
441
- return fromPath.success ? fromPath.data : null;
442
- } catch {
443
- return null;
444
- }
445
- };
446
- const fromCanvasReference = (reference) => {
447
- const candidate = reference.trim();
448
- const direct = canvasIdSchema.safeParse(candidate);
449
- if (direct.success) return direct.data;
450
- const fromUrl = fromCanvasUrl(candidate);
451
- if (fromUrl !== null) return fromUrl;
452
- throw new CliError("BAD_REQUEST", "The canvas reference is neither a canvas URL nor a UUID.", "Paste an HTTP(S) URL shaped https://app.example/c/<UUID>, or pass the bare canvas UUID.");
453
- };
541
+
454
542
  //#endregion
455
543
  //#region src/infrastructure/capability-reference.mapper.ts
456
544
  const fromCapabilityReference = (catalog, id) => {
@@ -458,6 +546,7 @@ const fromCapabilityReference = (catalog, id) => {
458
546
  if (capability === void 0) throw new TypeError(`${id} is missing from the capability catalogue`);
459
547
  return capability;
460
548
  };
549
+
461
550
  //#endregion
462
551
  //#region src/infrastructure/canvas-apply.program.ts
463
552
  const positiveInteger$3 = z.coerce.number().int().positive();
@@ -480,70 +569,23 @@ const configureCanvasApply = (canvas, input) => {
480
569
  ` enhance canvas apply --canvas <url-or-id> --base-version 3 --operations '[{"op":"insertText","nodeId":"txt_summary","parentId":"root","text":"Checkout needs an address.","box":{"x":120,"y":594,"width":720,"height":80},"styles":{"font-size":24}}]'`
481
570
  ].join("\n")).action(async (options) => {
482
571
  selectMutationToken(input, options.clientToken);
572
+ const reference = parseCanvasReference(options.canvas);
573
+ const baseVersion = baseVersionFrom(options.baseVersion);
574
+ const operations = createCanvasOperationInputAdapter(options.operations);
575
+ if (reference.nodeIds.length > 0) assertCanvasReferenceOperations(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), operations);
483
576
  const result = await input.invocation.invoke({
484
577
  capability: fromCapabilityReference(input.catalog(), "canvas.apply"),
485
578
  arguments: {
486
- canvasId: fromCanvasReference(options.canvas),
487
- baseVersion: baseVersionFrom(options.baseVersion),
488
- operations: [...createCanvasOperationInputAdapter(options.operations)]
579
+ canvasId: reference.canvasId,
580
+ baseVersion,
581
+ operations: [...operations]
489
582
  },
490
583
  clientToken: options.clientToken ?? null
491
584
  });
492
585
  input.output.result(result);
493
586
  });
494
587
  };
495
- //#endregion
496
- //#region src/infrastructure/canvas-authoring-input.schema.ts
497
- const NODE_ID_LENGTH = 200;
498
- const NODE_NAME_LENGTH = 500;
499
- const TEXT_LENGTH = 1e5;
500
- const MAX_NODE_IDS = 1e3;
501
- const MAX_BATCHES = 100;
502
- const MAX_DEPTH = 20;
503
- const MIN_RENDER_SCALE = .1;
504
- const MAX_RENDER_SCALE = 4;
505
- const positiveIntegerSchema = z.coerce.number().int().positive();
506
- const renderScaleSchema = z.coerce.number().min(MIN_RENDER_SCALE).max(MAX_RENDER_SCALE);
507
- const authoringUuidSchema = z.uuid();
508
- const styleValueSchema = z.union([
509
- z.string(),
510
- z.number(),
511
- z.null()
512
- ]);
513
- const styleObjectSchema = z.record(z.string(), styleValueSchema);
514
- const textUpdatesSchema = z.array(z.object({
515
- nodeId: z.string().min(1).max(NODE_ID_LENGTH),
516
- textContent: z.string().max(TEXT_LENGTH)
517
- })).min(1).max(MAX_NODE_IDS);
518
- const renameUpdatesSchema = z.array(z.object({
519
- nodeId: z.string().min(1).max(NODE_ID_LENGTH),
520
- name: z.string().max(NODE_NAME_LENGTH)
521
- })).min(1).max(MAX_NODE_IDS);
522
- const styleUpdatesSchema = z.array(z.object({
523
- nodeIds: z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_BATCHES),
524
- styles: styleObjectSchema
525
- })).min(1).max(MAX_BATCHES);
526
- const duplicateInputsSchema = z.array(z.object({
527
- id: z.string().min(1).max(NODE_ID_LENGTH),
528
- parentId: z.string().min(1).max(NODE_ID_LENGTH).optional()
529
- })).min(1).max(MAX_BATCHES);
530
- const moveInputsSchema = z.array(z.union([
531
- z.object({
532
- nodeId: z.string().min(1).max(NODE_ID_LENGTH),
533
- before: z.string().min(1).max(NODE_ID_LENGTH)
534
- }),
535
- z.object({
536
- nodeId: z.string().min(1).max(NODE_ID_LENGTH),
537
- after: z.string().min(1).max(NODE_ID_LENGTH)
538
- }),
539
- z.object({
540
- nodeId: z.string().min(1).max(NODE_ID_LENGTH),
541
- parentId: z.string().min(1).max(NODE_ID_LENGTH),
542
- index: z.number().int().nonnegative().optional()
543
- })
544
- ])).min(1).max(MAX_BATCHES);
545
- const nodeIdsSchema = z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_NODE_IDS);
546
- const sourceDepthSchema = z.coerce.number().int().min(0).max(MAX_DEPTH);
588
+
547
589
  //#endregion
548
590
  //#region src/infrastructure/canvas-authoring-activity.program.ts
549
591
  const MAX_ACTIVITY_NODE_IDS = 100;
@@ -604,267 +646,109 @@ const configureCanvasAuthoringActivity = (canvas, input) => {
604
646
  configureUpdate(work, input);
605
647
  configureFinish(canvas, input);
606
648
  };
607
- //#endregion
608
- //#region src/application/canvas-style-layout.use-case.ts
609
- const LAYOUT_PROPERTY$1 = /^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|order|overflow|padding|position|right|row-gap|top|transform|width)/u;
610
- const canvasStyleNumeric = (value) => {
611
- if (typeof value === "number") return Number.isFinite(value) ? value : null;
612
- if (typeof value !== "string") return null;
613
- const match = /^(-?\d+(?:\.\d+)?)(?:px)?$/u.exec(value.trim());
614
- return match === null ? null : Number(match[1]);
615
- };
616
- const sizeIntent = (value, fallback) => {
617
- const number = canvasStyleNumeric(value);
618
- if (number !== null) return {
619
- mode: "fixed",
620
- value: Math.max(0, number)
621
- };
622
- if (["100%", "fill"].includes(String(value))) return { mode: "fill" };
623
- if ([
624
- "fit-content",
625
- "auto",
626
- "hug"
627
- ].includes(String(value))) return { mode: "hug" };
628
- return fallback;
629
- };
630
- const fourSides = (styles, property, current) => {
631
- const shorthand = styles[property];
632
- const [top = current.top, right = top, bottom = top, left = right] = typeof shorthand === "string" ? shorthand.split(/\s+/u).map((value) => canvasStyleNumeric(value) ?? 0) : typeof shorthand === "number" ? [shorthand] : [];
633
- return {
634
- top: Math.max(0, canvasStyleNumeric(styles[`${property}-top`]) ?? top),
635
- right: Math.max(0, canvasStyleNumeric(styles[`${property}-right`]) ?? right),
636
- bottom: Math.max(0, canvasStyleNumeric(styles[`${property}-bottom`]) ?? bottom),
637
- left: Math.max(0, canvasStyleNumeric(styles[`${property}-left`]) ?? left)
638
- };
639
- };
640
- const alignment = (value, fallback) => {
641
- switch (value) {
642
- case "center":
643
- case "start":
644
- case "stretch": return value;
645
- case "end":
646
- case "flex-end": return "end";
647
- case "flex-start": return "start";
648
- default: return fallback;
649
- }
650
- };
651
- const distribution = (value, fallback) => {
652
- switch (value) {
653
- case "center":
654
- case "space-around":
655
- case "space-between":
656
- case "space-evenly":
657
- case "start": return value;
658
- case "end":
659
- case "flex-end": return "end";
660
- case "flex-start": return "start";
661
- default: return fallback;
662
- }
663
- };
664
- const baseContainer = () => ({
665
- direction: "column",
666
- alignItems: "start",
667
- alignContent: "start",
668
- justifyContent: "start",
669
- gap: 0,
670
- rowGap: 0,
671
- columnGap: 0,
672
- wrap: "nowrap",
673
- padding: {
674
- top: 0,
675
- right: 0,
676
- bottom: 0,
677
- left: 0
678
- }
679
- });
680
- const nextContainer = (current, styles) => {
681
- const display = styles["display"];
682
- if (["block", "none"].includes(String(display))) return void 0;
683
- const hasFlexDisplay = ["flex", "inline-flex"].includes(String(display));
684
- if (current === void 0 && !hasFlexDisplay) return void 0;
685
- const container = { ...current ?? baseContainer() };
686
- const direction = styles["flex-direction"];
687
- container.direction = direction === void 0 ? container.direction : String(direction).startsWith("row") ? "row" : "column";
688
- container.alignItems = alignment(styles["align-items"], container.alignItems);
689
- container.justifyContent = distribution(styles["justify-content"], container.justifyContent);
690
- container.alignContent = distribution(styles["align-content"], container.alignContent === "stretch" ? "start" : container.alignContent ?? "start");
691
- container.gap = Math.max(0, canvasStyleNumeric(styles["gap"]) ?? container.gap);
692
- container.rowGap = Math.max(0, canvasStyleNumeric(styles["row-gap"]) ?? container.rowGap ?? container.gap);
693
- container.columnGap = Math.max(0, canvasStyleNumeric(styles["column-gap"]) ?? container.columnGap ?? container.gap);
694
- container.wrap = styles["flex-wrap"] === "wrap" ? "wrap" : container.wrap ?? "nowrap";
695
- container.padding = fourSides(styles, "padding", container.padding);
696
- return container;
697
- };
698
- const itemPatch = (base, styles) => {
699
- const grow = canvasStyleNumeric(styles["flex-grow"]);
700
- const shrink = canvasStyleNumeric(styles["flex-shrink"]);
701
- const order = canvasStyleNumeric(styles["order"]);
702
- return {
703
- horizontal: sizeIntent(styles["width"], base.horizontal),
704
- vertical: sizeIntent(styles["height"], base.vertical),
705
- ...styles["align-self"] !== void 0 && { alignSelf: alignment(styles["align-self"], "start") },
706
- ...grow !== null && { flexGrow: Math.max(0, grow) },
707
- ...shrink !== null && { flexShrink: Math.max(0, shrink) },
708
- ...styles["flex-basis"] !== void 0 && { flexBasis: canvasStyleNumeric(styles["flex-basis"]) ?? "auto" },
709
- ...order !== null && { order: Math.round(order) }
710
- };
711
- };
712
- const nextCanvasLayout = (node, styles) => {
713
- if (Object.keys(styles).every((property) => !LAYOUT_PROPERTY$1.test(property))) return null;
714
- const box = node.box ?? {
715
- x: 0,
716
- y: 0,
717
- width: 1,
718
- height: 1
719
- };
720
- const base = node.layout ?? {
721
- ...emptyCanvasNodeLayout(),
722
- horizontal: {
723
- mode: "fixed",
724
- value: box.width
725
- },
726
- vertical: {
727
- mode: "fixed",
728
- value: box.height
729
- }
730
- };
731
- const rotation = /rotate\(\s*(-?\d+(?:\.\d+)?)deg\s*\)/u.exec(String(styles["transform"] ?? ""))?.[1];
732
- const overflow = `${String(styles["overflow"] ?? "")} ${String(styles["overflow-x"] ?? "")} ${String(styles["overflow-y"] ?? "")}`;
733
- const container = nextContainer(base.container, styles);
734
- const position = styles["position"];
735
- return {
736
- ...base,
737
- ...itemPatch(base, styles),
738
- rotation: rotation === void 0 ? base.rotation : Number(rotation),
739
- position: position === "absolute" ? "absolute" : ["relative", "flow"].includes(String(position)) ? "flow" : base.position,
740
- clipContent: /\b(?:clip|hidden)\b/u.test(overflow) || base.clipContent,
741
- ...container === void 0 ? { container: void 0 } : { container }
742
- };
743
- };
744
- const canvasBoxOperation = (node, styles) => {
745
- if (node.box === void 0) return null;
746
- const x = canvasStyleNumeric(styles["left"]);
747
- const y = canvasStyleNumeric(styles["top"]);
748
- const width = canvasStyleNumeric(styles["width"]);
749
- const height = canvasStyleNumeric(styles["height"]);
750
- if (x === null && y === null && width === null && height === null) return null;
751
- return {
752
- op: "setBox",
753
- nodeId: node.id,
754
- box: {
755
- x: x ?? node.box.x,
756
- y: y ?? node.box.y,
757
- width: Math.max(1, width ?? node.box.width),
758
- height: Math.max(1, height ?? node.box.height)
759
- }
760
- };
761
- };
649
+
762
650
  //#endregion
763
651
  //#region src/application/canvas-style-operations.use-case.ts
764
652
  const ADDITIONAL_STYLE_ID_LENGTH = 200;
765
- const LAYOUT_PROPERTY = /^(?:align|bottom|column-gap|display|flex|gap|height|justify|left|margin|order|overflow|padding|position|right|row-gap|top|transform|width)/u;
766
- const camelToKebab = (property) => property.replace(/^Webkit/u, "-webkit-").replace(/^Moz/u, "-moz-").replaceAll(/([a-z\d])([A-Z])/gu, "$1-$2").toLowerCase();
767
- const isSafeAdditionalValue = (value) => !/javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu.test(value);
653
+ 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();
768
654
  const additionalOperation = (node, styles) => {
769
655
  const held = new Map((node.additionalStyles?.declarations ?? []).map((declaration) => [declaration.property, declaration]));
770
- let isTouched = false;
771
656
  for (const [property, value] of Object.entries(styles)) {
772
- if (canvasNodeStylePatchSchema.safeParse({ [property]: value }).success) continue;
773
- if (LAYOUT_PROPERTY.test(property)) continue;
774
- isTouched = true;
775
- if (value === null) {
657
+ if (value === null || canvasNodeStylePatchSchema.safeParse({ [property]: value }).success) {
776
658
  held.delete(property);
777
659
  continue;
778
660
  }
779
- const normalized = String(value);
780
- if (!isSafeAdditionalValue(normalized)) throw new CliError("BAD_REQUEST", `Style ${property} contains executable CSS.`, "Remove imports, expressions, and executable URL schemes.");
781
- held.set(property, {
661
+ const result = canvasAdditionalStyleSchema.safeParse({
782
662
  id: held.get(property)?.id ?? `css-${property}`.slice(0, ADDITIONAL_STYLE_ID_LENGTH),
783
663
  property,
784
- value: normalized,
664
+ value: String(value),
785
665
  enabled: true
786
666
  });
667
+ 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.");
668
+ held.set(property, result.data);
787
669
  }
788
670
  const declarations = [];
789
671
  for (const declaration of held.values()) {
790
- if (declarations.length >= 128) break;
672
+ if (declarations.length === 128) throw new CliError("BAD_REQUEST", "Too many additional CSS declarations.", "Remove unused declarations before adding more; no styles were changed.");
791
673
  declarations.push(declaration);
792
674
  }
793
- return isTouched ? {
675
+ return JSON.stringify(declarations) === JSON.stringify(node.additionalStyles?.declarations ?? []) ? null : {
794
676
  op: "setAdditionalStyles",
795
677
  nodeId: node.id,
796
678
  additionalStyles: { declarations }
797
- } : null;
798
- };
799
- const normalizedStyles = (input) => Object.fromEntries(Object.entries(input).map(([property, value]) => [camelToKebab(property), value]));
800
- const operationsForNode = (node, source) => {
801
- const styles = normalizedStyles(source);
802
- const operations = [];
803
- const box = canvasBoxOperation(node, styles);
804
- if (box !== null) operations.push(box);
805
- const stylePatch = Object.fromEntries(Object.entries(styles).filter(([property, value]) => canvasNodeStylePatchSchema.safeParse({ [property]: value }).success));
806
- if (Object.keys(stylePatch).length > 0) operations.push({
807
- op: "setStyles",
808
- nodeId: node.id,
809
- styles: canvasNodeStylePatchSchema.parse(stylePatch)
679
+ };
680
+ };
681
+ const layoutOperation = (document, node, next, styles) => {
682
+ const changed = new Set(Object.keys(styles));
683
+ const properties = (axis) => [...canvasAxisStyleProperties(node, axis, document), ...canvasAxisStyleProperties(next, axis, document)];
684
+ const layout = canvasLayoutWithoutCssProperties(node.layout ?? {}, changed, {
685
+ horizontal: properties("horizontal"),
686
+ vertical: properties("vertical")
810
687
  });
811
- const layout = nextCanvasLayout(node, styles);
812
- if (layout !== null) operations.push({
688
+ for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
689
+ const value = styles[property];
690
+ if (value === "fill" || value === "hug") layout[axis] = { mode: value };
691
+ }
692
+ return JSON.stringify(layout) === JSON.stringify(node.layout ?? {}) ? null : {
813
693
  op: "setLayout",
814
694
  nodeId: node.id,
815
- layout
816
- });
817
- const additional = additionalOperation(node, styles);
818
- if (additional !== null) operations.push(additional);
819
- if (styles["display"] === "none") operations.push({
820
- op: "setVisibility",
821
- nodeId: node.id,
822
- visible: false
823
- });
824
- return operations;
825
- };
826
- const requireStyleNode = (nodes, nodeId) => {
827
- const node = nodes[nodeId];
828
- if (node !== void 0) return node;
829
- throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use current stable node ids.");
830
- };
831
- const canvasStyleOperations = (nodes, updates) => {
832
- const operations = updates.flatMap((update) => update.nodeIds.flatMap((nodeId) => operationsForNode(requireStyleNode(nodes, nodeId), update.styles)));
833
- if (operations.length === 0) throw new CliError("BAD_REQUEST", "No style changes were provided.", "Pass at least one changed CSS property.");
834
- return operations;
695
+ layout: Object.keys(layout).length === 0 ? "default" : layout
696
+ };
835
697
  };
836
- //#endregion
837
- //#region src/infrastructure/canvas-authoring-command.lib.ts
838
- const uuidNullableSchema = z.uuid().nullable();
839
- const authoringNumberFrom = (schema, value, option) => {
840
- const parsed = schema.safeParse(value);
841
- if (parsed.success) return parsed.data;
842
- throw new CliError("BAD_REQUEST", `${option} is invalid.`, "Run the command with --help.");
698
+ const cssValues = (document, node, styles) => {
699
+ const result = { ...styles };
700
+ for (const [property, axis] of [["width", "horizontal"], ["height", "vertical"]]) {
701
+ if (styles[property] !== "fill" && styles[property] !== "hug") continue;
702
+ result[property] = null;
703
+ 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;
704
+ }
705
+ return result;
843
706
  };
844
- const authoringBaseVersion = (value) => authoringNumberFrom(positiveIntegerSchema, value, "--base-version");
845
- const selectAuthoringToken = (input, value, isComposite) => {
846
- const parsed = uuidNullableSchema.safeParse(value ?? null);
847
- if (!parsed.success) throw new CliError("BAD_REQUEST", "--client-token must be a UUID.", "Mint one UUID and reuse it only when retrying the exact same command.");
848
- input.mutationKey.select(parsed.data, isComposite);
707
+ const operationsForNode = (document, node, source) => {
708
+ const styles = cssValues(document, node, source);
709
+ const additional = additionalOperation(node, styles);
710
+ const stylePatch = Object.fromEntries(Object.entries(styles).filter(([property, value]) => canvasNodeStylePatchSchema.safeParse({ [property]: value }).success));
711
+ const next = {
712
+ ...node,
713
+ styles: { ...node.styles },
714
+ ...additional !== null && additional.additionalStyles !== "default" && { additionalStyles: additional.additionalStyles }
715
+ };
716
+ for (const [property, value] of Object.entries(stylePatch)) if (value === null) Reflect.deleteProperty(next.styles, property);
717
+ else next.styles[property] = value;
718
+ const layout = layoutOperation(document, node, next, source);
719
+ return [
720
+ ...Object.keys(stylePatch).length > 0 ? [{
721
+ op: "setStyles",
722
+ nodeId: node.id,
723
+ styles: canvasNodeStylePatchSchema.parse(stylePatch)
724
+ }] : [],
725
+ ...layout === null ? [] : [layout],
726
+ ...additional === null ? [] : [additional]
727
+ ];
849
728
  };
850
- const authoringMutationId = (input, purpose) => input.mutationKey.current("canvas.applyOperations", { purpose });
851
- const sceneAtVersion = async (input, canvasId, expectedVersion) => {
852
- const held = getCanvasDocumentOutputSchema.safeParse(await input.remote.query("canvas.document.get", { canvasId }));
853
- if (!held.success) throw new CliError("INTERNAL", "The API returned an invalid canvas document.", "Run `enhance doctor` and report incompatible API and CLI versions.");
854
- if (held.data.version !== expectedVersion) throw new CliError("CONFLICT", `Canvas version ${String(held.data.version)} no longer matches --base-version ${String(expectedVersion)}.`, `Run 'enhance canvas tree --canvas ${canvasId}' and recompute against version ${String(held.data.version)}.`);
855
- const scene = canvasSceneDocumentSchema.safeParse(held.data.document);
856
- if (scene.success) return scene.data;
857
- 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.");
729
+ const mergedUpdates = (updates) => {
730
+ const merged = /* @__PURE__ */ new Map();
731
+ for (const update of updates) for (const nodeId of update.nodeIds) {
732
+ const styles = merged.get(nodeId) ?? {};
733
+ for (const [property, value] of Object.entries(update.styles)) {
734
+ const normalized = camelToKebab(property);
735
+ Reflect.deleteProperty(styles, normalized);
736
+ styles[normalized] = value;
737
+ }
738
+ merged.set(nodeId, styles);
739
+ }
740
+ return merged;
858
741
  };
859
- const applyAuthoringOperations = async (input, options, purpose, operations) => {
860
- selectAuthoringToken(input, options.clientToken, false);
861
- return createApplyCanvasComposite(input.remote).execute({
862
- canvasId: fromCanvasReference(options.canvas),
863
- mutationId: authoringMutationId(input, purpose),
864
- baseVersion: authoringBaseVersion(options.baseVersion),
865
- operations: [...operations]
742
+ const canvasStyleOperations = (document, updates) => {
743
+ const operations = [...mergedUpdates(updates)].flatMap(([nodeId, styles]) => {
744
+ const node = document.nodes[nodeId];
745
+ if (node === void 0) throw new CliError("NOT_FOUND", `Canvas node ${nodeId} does not exist.`, "Run canvas tree and use current stable node ids.");
746
+ return operationsForNode(document, node, styles);
866
747
  });
748
+ if (operations.length === 0) throw new CliError("BAD_REQUEST", "No style changes were provided.", "Pass at least one changed CSS property.");
749
+ return operations;
867
750
  };
751
+
868
752
  //#endregion
869
753
  //#region src/infrastructure/canvas-authoring-bounded-input.lib.ts
870
754
  const boundedCanvasAuthoringInput = (value, bytes, option) => {
@@ -880,6 +764,7 @@ const boundedCanvasAuthoringInput = (value, bytes, option) => {
880
764
  throw new CliError("BAD_REQUEST", `Could not read a bounded file at ${filePath}.`, `Use a regular UTF-8 file no larger than ${String(bytes)} bytes.`);
881
765
  }
882
766
  };
767
+
883
768
  //#endregion
884
769
  //#region src/infrastructure/canvas-json-input.adapter.ts
885
770
  const MAX_JSON_BYTES = 1048576;
@@ -897,6 +782,7 @@ const createCanvasJsonInputAdapter = (value, schema, option) => {
897
782
  const issue = parsed.error.issues[0];
898
783
  throw new CliError("BAD_REQUEST", `${option} is invalid${issue === void 0 || issue.path.length === 0 ? "" : ` at ${issue.path.join(".")}`}.`, issue?.message ?? "Correct the JSON shape and retry.");
899
784
  };
785
+
900
786
  //#endregion
901
787
  //#region src/infrastructure/canvas-authoring-edit.program.ts
902
788
  const configureText = (canvas, input) => {
@@ -931,9 +817,10 @@ const configureDelete = (canvas, input) => {
931
817
  };
932
818
  const configureStyles = (canvas, input) => {
933
819
  canvas.command("update-styles").description("Update visual and layout styles.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--updates <json-or-@path>", "Array of {nodeIds,styles} updates.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => {
934
- const scene = await sceneAtVersion(input, fromCanvasReference(options.canvas), authoringBaseVersion(options.baseVersion));
820
+ const canvasId = parseCanvasReference(options.canvas).canvasId;
821
+ const scene = await sceneAtVersion(input, canvasId, authoringBaseVersion(options.baseVersion));
935
822
  const updates = createCanvasJsonInputAdapter(options.updates, styleUpdatesSchema, "--updates");
936
- input.output.result(await applyAuthoringOperations(input, options, "update-styles", canvasStyleOperations(scene.nodes, updates)));
823
+ input.output.result(await applyAuthoringOperations(input, options, "update-styles", canvasStyleOperations(scene, updates)));
937
824
  });
938
825
  };
939
826
  const configureCanvasAuthoringEdits = (canvas, input) => {
@@ -942,6 +829,169 @@ const configureCanvasAuthoringEdits = (canvas, input) => {
942
829
  configureDelete(canvas, input);
943
830
  configureStyles(canvas, input);
944
831
  };
832
+
833
+ //#endregion
834
+ //#region src/application/canvas-style-layout.use-case.ts
835
+ const PERCENT$1 = 100;
836
+ const UNITLESS = /* @__PURE__ */ new Set([
837
+ "flex-grow",
838
+ "flex-shrink",
839
+ "order",
840
+ "aspect-ratio"
841
+ ]);
842
+ const aligned = (value) => value === "start" || value === "end" ? `flex-${value}` : value;
843
+ const parentBound = (value) => {
844
+ const percentage = `${String(value.ratio * PERCENT$1)}%`;
845
+ const offset = value.offset ?? 0;
846
+ return offset === 0 ? percentage : `calc(${percentage} ${offset < 0 ? "-" : "+"} ${String(Math.abs(offset))}px)`;
847
+ };
848
+ const boundCss = (intent, kind) => {
849
+ const absolute = intent[kind];
850
+ const parent = intent[kind === "min" ? "minParent" : "maxParent"];
851
+ if (parent === void 0) return absolute;
852
+ const relative = parentBound(parent);
853
+ return absolute === void 0 ? relative : `${kind === "min" ? "max" : "min"}(${String(absolute)}px, ${relative})`;
854
+ };
855
+ const sizeCss = (property, intent, isImplicitFill) => {
856
+ if (intent === void 0) return {};
857
+ if (intent.mode === "fixed") return { [property]: intent.value };
858
+ const bounds = {};
859
+ for (const kind of ["min", "max"]) {
860
+ const value = boundCss(intent, kind);
861
+ if (value !== void 0) bounds[`${kind}-${property}`] = value;
862
+ }
863
+ if (intent.mode === "hug") return {
864
+ [property]: "max-content",
865
+ ...bounds
866
+ };
867
+ const offset = intent.offset ?? 0;
868
+ const fill = offset === 0 ? "100%" : `calc(100% + ${String(offset)}px)`;
869
+ return {
870
+ [property]: isImplicitFill && offset === 0 ? "auto" : fill,
871
+ ...bounds
872
+ };
873
+ };
874
+ const boxCss = (node, document) => {
875
+ const box = node.box;
876
+ if (box === void 0) return {};
877
+ const authored = canvasAuthoredStyleDeclarations(node);
878
+ const position = node.layout?.position ?? canvasAuthoredLayoutValueOf(node, "position");
879
+ const isPositioned = position === void 0 || ["absolute", "fixed"].includes(position);
880
+ const hasInset = (axis) => (axis === "horizontal" ? [
881
+ "left",
882
+ "right",
883
+ "inset",
884
+ "inset-inline",
885
+ "inset-inline-start",
886
+ "inset-inline-end"
887
+ ] : [
888
+ "top",
889
+ "bottom",
890
+ "inset",
891
+ "inset-block",
892
+ "inset-block-start",
893
+ "inset-block-end"
894
+ ]).some((property) => authored[property] !== void 0);
895
+ const hasSize = (axis) => canvasAxisStyleProperties(node, axis, document).some((property) => authored[property] !== void 0 || node.additionalStyles?.declarations.some((declaration) => declaration.property.toLowerCase() === property) === true);
896
+ return {
897
+ ...authored["box-sizing"] === void 0 && { "box-sizing": "border-box" },
898
+ ...isPositioned && authored["position"] === void 0 && { position: "absolute" },
899
+ ...isPositioned && !hasInset("horizontal") && { left: box.x },
900
+ ...isPositioned && !hasInset("vertical") && { top: box.y },
901
+ ...isPositioned && node.layout?.horizontal === void 0 && !hasSize("horizontal") && { width: box.width },
902
+ ...isPositioned && node.layout?.vertical === void 0 && !hasSize("vertical") && { height: box.height }
903
+ };
904
+ };
905
+ const gridColumnsCss = (container) => {
906
+ if (container.gridColumns !== void 0) return `repeat(${String(container.gridColumns)}, minmax(0, 1fr))`;
907
+ if (container.gridAutoRepeat === void 0) return void 0;
908
+ return `repeat(${container.gridAutoRepeat.mode}, minmax(${String(container.gridAutoRepeat.minimum)}px, 1fr))`;
909
+ };
910
+ const containerCss = (node) => {
911
+ const layout = node.layout;
912
+ const container = layout?.container;
913
+ const css = layout?.clipContent === void 0 ? {} : { overflow: layout.clipContent ? "hidden" : "visible" };
914
+ if (container === void 0) return css;
915
+ const columns = gridColumnsCss(container);
916
+ const rowGap = container.rowGap ?? container.gap;
917
+ const columnGap = container.columnGap ?? container.gap;
918
+ return {
919
+ ...css,
920
+ ...canvasAuthoredLayoutValueOf(node, "display") === void 0 && { display: columns === void 0 ? "flex" : "grid" },
921
+ ...columns !== void 0 && { "grid-template-columns": columns },
922
+ ...container.direction !== void 0 && { "flex-direction": container.direction },
923
+ ...container.wrap !== void 0 && { "flex-wrap": container.wrap },
924
+ ...container.alignItems !== void 0 && { "align-items": aligned(container.alignItems) },
925
+ ...container.alignContent !== void 0 && { "align-content": aligned(container.alignContent) },
926
+ ...container.justifyContent !== void 0 && { "justify-content": aligned(container.justifyContent) },
927
+ ...rowGap !== void 0 && { "row-gap": rowGap },
928
+ ...columnGap !== void 0 && { "column-gap": columnGap },
929
+ ...Object.fromEntries(Object.entries(container.padding ?? {}).map(([side, value]) => [`padding-${side}`, value]))
930
+ };
931
+ };
932
+ const flowCss = (node, primary) => {
933
+ const layout = node.layout ?? {};
934
+ const hasOwnership = (property) => primary !== void 0 && canvasAuthoredLayoutValueOf(node, property) === void 0;
935
+ const basis = layout.flexBasis ?? (primary?.mode === "fill" ? 0 : "auto");
936
+ return {
937
+ ...(hasOwnership("flex-basis") || layout.flexBasis !== void 0) && { "flex-basis": typeof basis === "object" ? parentBound(basis) : basis },
938
+ ...(hasOwnership("flex-grow") || layout.flexGrow !== void 0) && { "flex-grow": layout.flexGrow ?? (primary?.mode === "fill" ? 1 : 0) },
939
+ ...(hasOwnership("flex-shrink") || layout.flexShrink !== void 0) && { "flex-shrink": layout.flexShrink ?? (primary?.mode === "fill" ? 1 : 0) },
940
+ ...layout.flowOffset !== void 0 && {
941
+ left: layout.flowOffset.x,
942
+ top: layout.flowOffset.y
943
+ },
944
+ ...layout.order !== void 0 && { order: layout.order },
945
+ ...Object.fromEntries(Object.entries(layout.margin ?? {}).map(([side, value]) => [`margin-${side}`, value]))
946
+ };
947
+ };
948
+ const transformCss = (layout) => {
949
+ const transforms = [
950
+ ...layout.rotation === void 0 || layout.rotation === 0 ? [] : [`rotate(${String(layout.rotation)}deg)`],
951
+ ...layout.flipHorizontal === true ? ["scaleX(-1)"] : [],
952
+ ...layout.flipVertical === true ? ["scaleY(-1)"] : []
953
+ ];
954
+ return transforms.length === 0 ? {} : { transform: transforms.join(" ") };
955
+ };
956
+ const childAlignment = (layout, cross) => layout.alignSelf === void 0 || layout.alignSelf === "auto" ? cross?.mode === "fill" ? "stretch" : void 0 : aligned(layout.alignSelf);
957
+ const fillMinimumCss = (node, main) => {
958
+ if (main === void 0) return {};
959
+ const primary = node.layout?.[main];
960
+ const property = main === "horizontal" ? "min-width" : "min-height";
961
+ if (primary?.mode !== "fill" || primary.min !== void 0 || primary.minParent !== void 0 || canvasAuthoredStyleDeclarations(node)[property] !== void 0) return {};
962
+ return { [property]: 0 };
963
+ };
964
+ const placementCss = (node, document) => {
965
+ const layout = node.layout;
966
+ if (layout === void 0) return {};
967
+ const parentId = document?.relationships[node.id]?.parentId;
968
+ const main = canvasLayoutMainAxisOf(parentId === void 0 ? void 0 : document?.nodes[parentId], document);
969
+ const position = layout.position ?? canvasAuthoredLayoutValueOf(node, "position");
970
+ const isFlow = position === "flow" || position !== "absolute" && position !== "fixed" && (position !== void 0 || node.box === void 0);
971
+ const primary = main === "horizontal" ? layout.horizontal : layout.vertical;
972
+ const cross = main === "horizontal" ? layout.vertical : layout.horizontal;
973
+ const alignment = childAlignment(layout, cross);
974
+ return {
975
+ ...layout.position !== void 0 && { position: isFlow ? "relative" : "absolute" },
976
+ ...sizeCss("width", layout.horizontal, isFlow && (main === "horizontal" || alignment === "stretch")),
977
+ ...sizeCss("height", layout.vertical, isFlow && (main === "vertical" || alignment === "stretch")),
978
+ ...isFlow && main !== void 0 && flowCss(node, primary),
979
+ ...isFlow && alignment !== void 0 && { "align-self": alignment },
980
+ ...isFlow && fillMinimumCss(node, main),
981
+ ...alignment === "stretch" && cross?.mode === "hug" && main !== void 0 && { [main === "horizontal" ? "height" : "width"]: "auto" },
982
+ ...layout.aspectRatio !== void 0 && { "aspect-ratio": layout.aspectRatio },
983
+ ...transformCss(layout)
984
+ };
985
+ };
986
+ /** A structural CSS reading, never a measurement of the browser's used geometry. */
987
+ const canvasStyleLayoutCss = (node, document) => Object.fromEntries(Object.entries({
988
+ ...boxCss(node, document),
989
+ ...canvasLayoutPriorityDeclarations(node, {
990
+ ...placementCss(node, document),
991
+ ...containerCss(node)
992
+ })
993
+ }).map(([property, value]) => [property, typeof value === "number" && !UNITLESS.has(property) ? `${String(value)}px` : value]));
994
+
945
995
  //#endregion
946
996
  //#region src/application/canvas-css-projection.use-case.ts
947
997
  const RGB_CHANNEL_MAX = 255;
@@ -1035,80 +1085,18 @@ const typographyCss = (typography) => typography === void 0 ? {} : {
1035
1085
  "text-decoration-style": typography.decoration.style,
1036
1086
  "white-space": typography.wrapping
1037
1087
  };
1038
- const aligned = (value) => value === "start" ? "flex-start" : value === "end" ? "flex-end" : value;
1039
- const sizeCss = (intent, fallback) => {
1040
- if (intent.mode === "fixed") return `${String(intent.value)}px`;
1041
- return intent.mode === "fill" ? "100%" : `${String(fallback)}px`;
1042
- };
1043
- const placementCss = (layout, box) => ({
1044
- position: layout.position === "absolute" ? "absolute" : "relative",
1045
- ...layout.position === "absolute" && {
1046
- left: `${String(box.x)}px`,
1047
- top: `${String(box.y)}px`
1048
- },
1049
- width: sizeCss(layout.horizontal, box.width),
1050
- height: sizeCss(layout.vertical, box.height),
1051
- ...layout.clipContent === true && { overflow: "hidden" }
1052
- });
1053
- const transformCss = (layout) => {
1054
- const transforms = [
1055
- ...layout.rotation === 0 ? [] : [`rotate(${String(layout.rotation)}deg)`],
1056
- ...layout.flipHorizontal === true ? ["scaleX(-1)"] : [],
1057
- ...layout.flipVertical === true ? ["scaleY(-1)"] : []
1058
- ];
1059
- return transforms.length === 0 ? {} : { transform: transforms.join(" ") };
1060
- };
1061
- const flexBasisCss = (basis) => {
1062
- if (typeof basis !== "object") return basis === "auto" ? basis : `${String(basis)}px`;
1063
- const percentage = `${String(basis.ratio * PERCENT)}%`;
1064
- const offset = basis.offset ?? 0;
1065
- return offset === 0 ? percentage : `calc(${percentage} ${offset < 0 ? "-" : "+"} ${String(Math.abs(offset))}px)`;
1066
- };
1067
- const flexItemCss = (layout) => ({
1068
- ...layout.alignSelf !== void 0 && { "align-self": aligned(layout.alignSelf === "auto" ? "start" : layout.alignSelf) },
1069
- ...layout.flexGrow !== void 0 && { "flex-grow": layout.flexGrow },
1070
- ...layout.flexShrink !== void 0 && { "flex-shrink": layout.flexShrink },
1071
- ...layout.flexBasis !== void 0 && { "flex-basis": flexBasisCss(layout.flexBasis) },
1072
- ...layout.order !== void 0 && { order: layout.order }
1088
+ const computedCanvasNodeCss = (node, document) => ({
1089
+ ...Object.fromEntries(Object.entries(canvasAuthoredStyleDeclarations(node)).filter(([property]) => node.layout?.clipContent === void 0 || ![
1090
+ "overflow",
1091
+ "overflow-x",
1092
+ "overflow-y"
1093
+ ].includes(property))),
1094
+ ...typographyCss(node.typography),
1095
+ ...appearanceCss(node.appearance),
1096
+ ...canvasStyleLayoutCss(node, document),
1097
+ ...node.visible === false && { display: "none" }
1073
1098
  });
1074
- const flexContainerCss = (layout) => {
1075
- const container = layout.container;
1076
- if (container === void 0) return {};
1077
- return {
1078
- display: "flex",
1079
- "flex-direction": container.direction,
1080
- "align-items": aligned(container.alignItems),
1081
- "align-content": aligned(container.alignContent ?? "start"),
1082
- "justify-content": aligned(container.justifyContent),
1083
- gap: `${String(container.gap)}px`,
1084
- "row-gap": `${String(container.rowGap ?? container.gap)}px`,
1085
- "column-gap": `${String(container.columnGap ?? container.gap)}px`,
1086
- "flex-wrap": container.wrap ?? "nowrap",
1087
- padding: [
1088
- container.padding.top,
1089
- container.padding.right,
1090
- container.padding.bottom,
1091
- container.padding.left
1092
- ].map((value) => `${String(value)}px`).join(" ")
1093
- };
1094
- };
1095
- const computedCanvasNodeCss = (node) => {
1096
- const additional = Object.fromEntries((node.additionalStyles?.declarations ?? []).filter((declaration) => declaration.enabled).map((declaration) => [declaration.property, declaration.value]));
1097
- const layout = node.layout === void 0 || node.box === void 0 ? {} : {
1098
- ...placementCss(node.layout, node.box),
1099
- ...transformCss(node.layout),
1100
- ...flexItemCss(node.layout),
1101
- ...flexContainerCss(node.layout)
1102
- };
1103
- return {
1104
- ...node.styles,
1105
- ...additional,
1106
- ...typographyCss(node.typography),
1107
- ...appearanceCss(node.appearance),
1108
- ...layout,
1109
- ...node.visible === false && { display: "none" }
1110
- };
1111
- };
1099
+
1112
1100
  //#endregion
1113
1101
  //#region src/application/canvas-source-projection.use-case.ts
1114
1102
  const childrenOf = (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);
@@ -1128,7 +1116,7 @@ const jsxFor = (document, nodeId, depth, maximumDepth) => {
1128
1116
  const properties = [
1129
1117
  `data-node-id=${JSON.stringify(node.id)}`,
1130
1118
  `data-name=${JSON.stringify(node.label)}`,
1131
- `style={${JSON.stringify(computedCanvasNodeCss(node))}}`
1119
+ `style={${JSON.stringify(computedCanvasNodeCss(node, document))}}`
1132
1120
  ];
1133
1121
  if (node.locked === true) properties.push("data-locked=\"true\"");
1134
1122
  if (node.component === "image") return `${indent}<img ${properties.join(" ")} alt=${JSON.stringify(stringProperty(node, "alt"))} src=${JSON.stringify(stringProperty(node, "src"))} />`;
@@ -1152,18 +1140,19 @@ const canvasComputedStyleRecords = (document, nodeIds) => nodeIds.map((nodeId) =
1152
1140
  name: node.label,
1153
1141
  component: node.component,
1154
1142
  box: node.box,
1155
- css: computedCanvasNodeCss(node),
1143
+ css: computedCanvasNodeCss(node, document),
1156
1144
  layout: node.layout,
1157
1145
  appearance: node.appearance,
1158
1146
  typography: node.typography
1159
1147
  };
1160
1148
  });
1149
+
1161
1150
  //#endregion
1162
1151
  //#region src/infrastructure/canvas-authoring-source.program.ts
1163
1152
  const GUIDE = {
1164
1153
  topic: "canvas-agent-authoring",
1165
1154
  workflow: [
1166
- "Run canvas inspect, then canvas tree, before editing.",
1155
+ "Run canvas inspect, then canvas tree, before editing. Keep a pasted selection link intact as --canvas on every read and edit; it limits the request to those nodes and their descendants.",
1167
1156
  "Render the target before changing it and inspect the PNG.",
1168
1157
  "Write small visual groups incrementally with write-html.",
1169
1158
  "Use duplicate-nodes, set-text-content, update-styles, and move-nodes instead of rewriting existing structure.",
@@ -1193,7 +1182,7 @@ const canvasScene = async (input, canvasId) => {
1193
1182
  const held = getCanvasDocumentOutputSchema.parse(await input.remote.query("canvas.document.get", { canvasId }));
1194
1183
  return {
1195
1184
  held,
1196
- document: canvasSceneDocumentSchema.parse(held.document)
1185
+ document: canvasReadableSceneDocumentSchema.parse(held.document)
1197
1186
  };
1198
1187
  };
1199
1188
  const configureCanvasAuthoringSource = (canvas, input) => {
@@ -1201,8 +1190,10 @@ const configureCanvasAuthoringSource = (canvas, input) => {
1201
1190
  input.output.result(GUIDE);
1202
1191
  });
1203
1192
  canvas.command("get-jsx").description("Read concise subtree JSX.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to inspect.").requiredOption("--node-id <id>", "Stable subtree root id.").option("--depth <integer>", "Maximum descendant depth from 0 to 20.", "8").action(async (options) => {
1204
- const canvasId = fromCanvasReference(options.canvas);
1193
+ const reference = parseCanvasReference(options.canvas);
1194
+ const canvasId = reference.canvasId;
1205
1195
  const { held, document } = await canvasScene(input, canvasId);
1196
+ assertCanvasReferenceNodes(reference, document, [options.nodeId]);
1206
1197
  input.output.result({
1207
1198
  canvasId,
1208
1199
  version: held.version,
@@ -1212,16 +1203,23 @@ const configureCanvasAuthoringSource = (canvas, input) => {
1212
1203
  });
1213
1204
  });
1214
1205
  canvas.command("get-computed-styles").description("Read effective node CSS.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to inspect.").requiredOption("--node-ids <json-or-@path>", "JSON array of stable node ids.").action(async (options) => {
1215
- const canvasId = fromCanvasReference(options.canvas);
1206
+ const reference = parseCanvasReference(options.canvas);
1207
+ const canvasId = reference.canvasId;
1216
1208
  const { held, document } = await canvasScene(input, canvasId);
1217
1209
  const nodeIds = createCanvasJsonInputAdapter(options.nodeIds, nodeIdsSchema, "--node-ids");
1210
+ assertCanvasReferenceNodes(reference, document, nodeIds);
1218
1211
  input.output.result({
1219
1212
  canvasId,
1220
1213
  version: held.version,
1221
- nodes: canvasComputedStyleRecords(document, nodeIds)
1214
+ nodes: canvasComputedStyleRecords(document, nodeIds),
1215
+ warning: "These are authored CSS instructions, not measured browser dimensions. Use canvas render as the pixel authority."
1222
1216
  });
1223
1217
  });
1224
1218
  };
1219
+
1220
+ //#endregion
1221
+ //#region src/application/canvas-structure-document.use-case.ts
1222
+ const ROOT_CANVAS_NODE_ID = "root";
1225
1223
  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);
1226
1224
  const canCanvasNodeContainChildren = (node) => node !== void 0 && [
1227
1225
  "root",
@@ -1244,6 +1242,7 @@ const canvasDescendantIds = (document, nodeId) => {
1244
1242
  visit(nodeId);
1245
1243
  return found;
1246
1244
  };
1245
+
1247
1246
  //#endregion
1248
1247
  //#region src/application/canvas-duplicate-operations.use-case.ts
1249
1248
  const SLUG_LENGTH = 60;
@@ -1339,6 +1338,7 @@ const duplicateCanvasNodeOperations = (document, inputs, idPrefix) => {
1339
1338
  duplicatedNodes: duplicates.map((duplicate) => duplicate.summary)
1340
1339
  };
1341
1340
  };
1341
+
1342
1342
  //#endregion
1343
1343
  //#region src/application/canvas-move-operations.use-case.ts
1344
1344
  const moveState = (document) => ({
@@ -1410,16 +1410,20 @@ const moveCanvasNodeOperations = (document, inputs) => {
1410
1410
  }))
1411
1411
  };
1412
1412
  };
1413
+
1413
1414
  //#endregion
1414
1415
  //#region src/infrastructure/canvas-authoring-structure.program.ts
1415
1416
  const configureDuplicate = (canvas, input) => {
1416
1417
  canvas.command("duplicate-nodes").description("Deep-clone node subtrees.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--nodes <json-or-@path>", "Array of {id,parentId?} requests.").option("--id-prefix <prefix>", "Stable namespace for cloned ids.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => {
1417
1418
  selectAuthoringToken(input, options.clientToken, false);
1418
- const canvasId = fromCanvasReference(options.canvas);
1419
+ const reference = parseCanvasReference(options.canvas);
1420
+ const canvasId = reference.canvasId;
1419
1421
  const baseVersion = authoringBaseVersion(options.baseVersion);
1420
1422
  const scene = await sceneAtVersion(input, canvasId, baseVersion);
1421
1423
  const mutationId = authoringMutationId(input, "duplicate-nodes");
1422
- const plan = duplicateCanvasNodeOperations(scene, createCanvasJsonInputAdapter(options.nodes, duplicateInputsSchema, "--nodes"), options.idPrefix ?? `copy_${mutationId.replaceAll("-", "")}`);
1424
+ const nodes = createCanvasJsonInputAdapter(options.nodes, duplicateInputsSchema, "--nodes");
1425
+ assertCanvasReferenceNodes(reference, scene, nodes.flatMap((node) => [node.id, ...node.parentId === void 0 || node.parentId === scene.relationships[node.id]?.parentId ? [] : [node.parentId]]));
1426
+ const plan = duplicateCanvasNodeOperations(scene, nodes, options.idPrefix ?? `copy_${mutationId.replaceAll("-", "")}`);
1423
1427
  const apply = await createApplyCanvasComposite(input.remote).execute({
1424
1428
  canvasId,
1425
1429
  mutationId,
@@ -1435,9 +1439,12 @@ const configureDuplicate = (canvas, input) => {
1435
1439
  const configureMove = (canvas, input) => {
1436
1440
  canvas.command("move-nodes").description("Reorder or reparent nodes.").requiredOption("--canvas <url-or-id>", "Canvas URL or UUID to edit.").requiredOption("--base-version <integer>", "Exact current canvas version.").requiredOption("--moves <json-or-@path>", "Sequential before, after, or parent/index moves.").option("--client-token <uuid>", "Stable UUID for retrying this exact batch.").action(async (options) => {
1437
1441
  selectAuthoringToken(input, options.clientToken, false);
1438
- const canvasId = fromCanvasReference(options.canvas);
1442
+ const reference = parseCanvasReference(options.canvas);
1443
+ const canvasId = reference.canvasId;
1439
1444
  const baseVersion = authoringBaseVersion(options.baseVersion);
1440
- const plan = moveCanvasNodeOperations(await sceneAtVersion(input, canvasId, baseVersion), createCanvasJsonInputAdapter(options.moves, moveInputsSchema, "--moves"));
1445
+ const scene = await sceneAtVersion(input, canvasId, baseVersion);
1446
+ const plan = moveCanvasNodeOperations(scene, createCanvasJsonInputAdapter(options.moves, moveInputsSchema, "--moves"));
1447
+ assertCanvasReferenceOperations(reference, scene, plan.operations);
1441
1448
  const apply = await createApplyCanvasComposite(input.remote).execute({
1442
1449
  canvasId,
1443
1450
  mutationId: authoringMutationId(input, "move-nodes"),
@@ -1455,6 +1462,7 @@ const configureCanvasAuthoringStructure = (canvas, input) => {
1455
1462
  configureDuplicate(canvas, input);
1456
1463
  configureMove(canvas, input);
1457
1464
  };
1465
+
1458
1466
  //#endregion
1459
1467
  //#region src/infrastructure/canvas-html-input.adapter.ts
1460
1468
  const MAX_HTML_BYTES = 262144;
@@ -1463,6 +1471,7 @@ const createCanvasHtmlInputAdapter = (value) => {
1463
1471
  if (Buffer.byteLength(html, "utf8") > MAX_HTML_BYTES) throw new CliError("BAD_REQUEST", `--html exceeds ${String(MAX_HTML_BYTES)} bytes.`, "Write one visual group at a time, as taught by canvas guide.");
1464
1472
  return html;
1465
1473
  };
1474
+
1466
1475
  //#endregion
1467
1476
  //#region src/infrastructure/canvas-authoring-write.program.ts
1468
1477
  const ARTBOARD_GAP = 80;
@@ -1480,15 +1489,18 @@ const configureWriteHtml = (canvas, input) => {
1480
1489
  if (!["insert-children", "replace"].includes(options.mode)) throw new CliError("BAD_REQUEST", "--mode must be insert-children or replace.", "Choose one of the two documented modes.");
1481
1490
  selectAuthoringToken(input, options.clientToken, true);
1482
1491
  const mode = options.mode === "replace" ? "replace" : "insert-children";
1492
+ const reference = parseCanvasReference(options.canvas);
1493
+ const baseVersion = authoringBaseVersion(options.baseVersion);
1494
+ if (reference.nodeIds.length > 0) assertCanvasReferenceNodes(reference, await sceneAtVersion(input, reference.canvasId, baseVersion), [options.targetNodeId]);
1483
1495
  input.output.result(await input.invocation.invoke({
1484
1496
  capability: fromCapabilityReference(input.catalog(), "canvas.writeHtml"),
1485
1497
  arguments: {
1486
- canvasId: fromCanvasReference(options.canvas),
1498
+ canvasId: reference.canvasId,
1487
1499
  targetNodeId: options.targetNodeId,
1488
1500
  mode,
1489
1501
  html: createCanvasHtmlInputAdapter(options.html),
1490
1502
  ...options.idPrefix !== void 0 && { idPrefix: options.idPrefix },
1491
- baseVersion: authoringBaseVersion(options.baseVersion),
1503
+ baseVersion,
1492
1504
  renderOutputPath: options.output ?? null,
1493
1505
  overwriteRender: options.force === true,
1494
1506
  renderScale: authoringNumberFrom(renderScaleSchema, options.scale, "--scale"),
@@ -1545,6 +1557,7 @@ const configureCanvasAuthoringWrites = (canvas, input) => {
1545
1557
  configureWriteHtml(canvas, input);
1546
1558
  configureCreateArtboard(canvas, input);
1547
1559
  };
1560
+
1548
1561
  //#endregion
1549
1562
  //#region src/infrastructure/canvas-authoring.program.ts
1550
1563
  const configureCanvasAuthoring = (canvas, input) => {
@@ -1554,6 +1567,79 @@ const configureCanvasAuthoring = (canvas, input) => {
1554
1567
  configureCanvasAuthoringStructure(canvas, input);
1555
1568
  configureCanvasAuthoringActivity(canvas, input);
1556
1569
  };
1570
+
1571
+ //#endregion
1572
+ //#region src/infrastructure/canvas-inspection.program.ts
1573
+ const referenceFor = (command) => {
1574
+ const reference = command.getOptionValue("canvas");
1575
+ const legacy = command.getOptionValue("canvasId");
1576
+ if (reference !== void 0 && legacy !== void 0) throw new CliError("BAD_REQUEST", "--canvas and --canvas-id cannot be combined.", "Pass the pasted URL or UUID through --canvas.");
1577
+ const selected = reference ?? legacy;
1578
+ if (typeof selected !== "string") throw new CliError("BAD_REQUEST", "--canvas is required.", "Pass a pasted Enhance canvas URL or bare UUID through --canvas.");
1579
+ return {
1580
+ reference: parseCanvasReference(selected),
1581
+ url: selected
1582
+ };
1583
+ };
1584
+ const nodeIdFor = (command, reference) => {
1585
+ const nodeId = command.getOptionValue("nodeId") ?? (reference.nodeIds.length === 1 ? reference.nodeIds[0] : void 0);
1586
+ if (typeof nodeId !== "string" || nodeId === "") throw new CliError("BAD_REQUEST", "--node-id or a single-node selection link is required.", "Choose one node, or use canvas tree to inspect the linked selection.");
1587
+ return nodeId;
1588
+ };
1589
+ const readLinkedSelection = async (command, input, reference, url) => {
1590
+ const held = getCanvasDocumentOutputSchema.parse(await input.remote.query("canvas.document.get", { canvasId: reference.canvasId }));
1591
+ const document = canvasReadableSceneDocumentSchema.parse(held.document);
1592
+ const scope = canvasReferenceNodeIds(reference, document);
1593
+ const nodes = Object.values(document.nodes).filter((node) => scope.has(node.id)).map((node) => ({
1594
+ ...node,
1595
+ kind: node.component,
1596
+ parentId: document.relationships[node.id]?.parentId ?? null,
1597
+ children: Object.entries(document.relationships).filter(([, relation]) => relation.parentId === node.id).map(([id]) => id)
1598
+ }));
1599
+ const context = {
1600
+ canvasId: reference.canvasId,
1601
+ version: held.version,
1602
+ source: "selection-link",
1603
+ selectedNodeIds: reference.nodeIds,
1604
+ next: [`Keep this selection link as --canvas for every edit: ${url}`, "Edit only these nodes or their descendants; other canvas content is outside the request."]
1605
+ };
1606
+ if (command.name() === "node") {
1607
+ const nodeId = nodeIdFor(command, reference);
1608
+ assertCanvasReferenceNodes(reference, document, [nodeId]);
1609
+ return {
1610
+ ...context,
1611
+ node: nodes.find((node) => node.id === nodeId)
1612
+ };
1613
+ }
1614
+ return {
1615
+ ...context,
1616
+ nodes
1617
+ };
1618
+ };
1619
+ const configureCanvasInspection = (canvas, input) => {
1620
+ for (const name of [
1621
+ "inspect",
1622
+ "tree",
1623
+ "node",
1624
+ "selection"
1625
+ ]) {
1626
+ const command = canvas.commands.find((candidate) => candidate.name() === name);
1627
+ const canvasId = command?.options.find((option) => option.long === "--canvas-id");
1628
+ if (command === void 0 || canvasId === void 0) continue;
1629
+ canvasId.makeOptionMandatory(false);
1630
+ command.options.find((option) => option.long === "--node-id")?.makeOptionMandatory(false);
1631
+ command.option("--canvas <url-or-id>", "Pasted canvas URL or UUID. Selection links limit reads and edits to the linked subtree.");
1632
+ command.action(async () => {
1633
+ const { reference, url } = referenceFor(command);
1634
+ const result = reference.nodeIds.length > 0 ? await readLinkedSelection(command, input, reference, url) : await input.remote.query(`canvas.${name}`, {
1635
+ canvasId: reference.canvasId,
1636
+ ...name === "node" && { nodeId: nodeIdFor(command, reference) }
1637
+ });
1638
+ input.output.result(result);
1639
+ });
1640
+ }
1641
+ };
1642
+
1557
1643
  //#endregion
1558
1644
  //#region src/infrastructure/canvas.program.ts
1559
1645
  const positiveInteger$2 = z.coerce.number().int().positive();
@@ -1594,19 +1680,29 @@ const selectClientToken = (input, value) => {
1594
1680
  input.mutationKey.select(clientToken.data, false);
1595
1681
  return input.mutationKey.current("canvas.render.create", {});
1596
1682
  };
1683
+ const selectedRenderNode = async (options, input) => {
1684
+ const reference = parseCanvasReference(options.canvas ?? "");
1685
+ if (reference.nodeIds.length === 0) return options.nodeId;
1686
+ const nodeId = options.nodeId ?? (reference.nodeIds.length === 1 ? reference.nodeIds[0] : void 0);
1687
+ if (nodeId === void 0 || options.bounds !== void 0) throw new CliError("BAD_REQUEST", "A selection link requires one selected node to render.", "Pass --node-id for one node in the selection; bounds and whole-canvas renders would include unrelated content.");
1688
+ const held = getCanvasDocumentOutputSchema.parse(await input.remote.query("canvas.document.get", { canvasId: reference.canvasId }));
1689
+ assertCanvasReferenceNodes(reference, canvasReadableSceneDocumentSchema.parse(held.document), [nodeId]);
1690
+ return nodeId;
1691
+ };
1597
1692
  const executeRender = async (options, input) => {
1598
1693
  if (options.canvas === void 0) throw new CliError("BAD_REQUEST", "--canvas is required.", "Pass a pasted Enhance canvas URL or bare UUID through --canvas.");
1599
1694
  if (options.nodeId !== void 0 && options.bounds !== void 0) throw new CliError("BAD_REQUEST", "--node-id and --bounds cannot be combined.", "Choose one focused target, or omit both to render all authored content.");
1600
- if (options.atMs !== void 0 && options.nodeId === void 0) throw new CliError("BAD_REQUEST", "--at-ms requires --node-id.", "Render the stable recording node returned by `enhance canvas tree`.");
1601
- const recordingId = options.atMs === void 0 ? null : recordingIdFrom(options.nodeId);
1695
+ const nodeId = await selectedRenderNode(options, input);
1696
+ if (nodeId === void 0 && options.atMs !== void 0) throw new CliError("BAD_REQUEST", "--at-ms requires --node-id.", "Render the stable recording node returned by `enhance canvas tree`.");
1697
+ const recordingId = options.atMs === void 0 ? null : recordingIdFrom(nodeId);
1602
1698
  if (recordingId === void 0 && options.atMs !== void 0) throw new CliError("BAD_REQUEST", "--at-ms requires a stable recording node id such as rec_<recording-uuid>.", "Run `enhance canvas tree --canvas <url-or-id>` and choose a recording node.");
1603
1699
  selectClientToken(input, options.clientToken);
1604
1700
  const result = await input.invocation.invoke({
1605
1701
  capability: fromCapabilityReference(input.catalog(), "canvas.render"),
1606
1702
  arguments: {
1607
- canvasId: fromCanvasReference(options.canvas),
1703
+ canvasId: parseCanvasReference(options.canvas).canvasId,
1608
1704
  expectedVersion: options.expectedVersion === void 0 ? null : numberFrom(positiveInteger$2, options.expectedVersion, "--expected-version"),
1609
- target: targetFrom(options.nodeId, boundsFrom(options.bounds)),
1705
+ target: targetFrom(nodeId, boundsFrom(options.bounds)),
1610
1706
  sourceState: recordingId === null || recordingId === void 0 ? null : {
1611
1707
  kind: "recording",
1612
1708
  recordingId,
@@ -1621,20 +1717,6 @@ const executeRender = async (options, input) => {
1621
1717
  });
1622
1718
  input.output.result(result);
1623
1719
  };
1624
- const configureCanvasReference = (command) => {
1625
- const canvasId = command.options.find((option) => option.long === "--canvas-id");
1626
- if (canvasId === void 0) return;
1627
- canvasId.makeOptionMandatory(false);
1628
- command.option("--canvas <url-or-id>", "Pasted Enhance canvas URL or bare canvas UUID.");
1629
- command.hook("preAction", (actionCommand) => {
1630
- const reference = actionCommand.getOptionValue("canvas");
1631
- const legacy = actionCommand.getOptionValue("canvasId");
1632
- if (reference !== void 0 && legacy !== void 0) throw new CliError("BAD_REQUEST", "--canvas and --canvas-id cannot be combined.", "Pass the pasted URL or UUID through --canvas.");
1633
- const selected = reference ?? legacy;
1634
- if (typeof selected !== "string") throw new CliError("BAD_REQUEST", "--canvas is required.", "Pass a pasted Enhance canvas URL or bare UUID through --canvas.");
1635
- actionCommand.setOptionValueWithSource("canvasId", fromCanvasReference(selected), "cli");
1636
- });
1637
- };
1638
1720
  const configureRender = (render, input) => {
1639
1721
  render.option("--canvas <url-or-id>", "Canvas URL or UUID to render.").option("--node-id <id>", "Render one stable canvas node instead of all authored content.").option("--bounds <json>", "Render an explicit rectangle in canvas world coordinates.").option("--expected-version <integer>", "Refuse pixels from any other document version.").option("--at-ms <integer>", "Pause a recording node at this millisecond; inspect the PNG before snapshotting it.").option("--scale <number>", "Output pixels per canvas unit, from 0.1 to 4.", "1").option("--output <path>", "Write the PNG to this path instead of a protected temporary file.").option("--force", "Replace an existing --output file deliberately.", false).option("--timeout-ms <integer>", "Local polling deadline in milliseconds.", "120000").option("--client-token <uuid>", "Stable UUID to reuse only when retrying this render request.").addHelpText("after", "\nFor transcript-led selection, inspect nearby --at-ms renders and reject transitions or duplicate states before running recording snapshot.\n").action(async (options) => executeRender(options, input));
1640
1722
  };
@@ -1649,17 +1731,10 @@ const registerCanvasProgram = (program, input) => {
1649
1731
  ...input,
1650
1732
  render: composite
1651
1733
  });
1652
- for (const name of [
1653
- "inspect",
1654
- "tree",
1655
- "node",
1656
- "selection"
1657
- ]) {
1658
- const command = canvas.commands.find((candidate) => candidate.name() === name);
1659
- if (command !== void 0) configureCanvasReference(command);
1660
- }
1734
+ configureCanvasInspection(canvas, input);
1661
1735
  configureRender(render, input);
1662
1736
  };
1737
+
1663
1738
  //#endregion
1664
1739
  //#region src/infrastructure/command-summaries.consts.ts
1665
1740
  const COMMAND_SUMMARIES = {
@@ -1676,16 +1751,18 @@ const COMMAND_SUMMARIES = {
1676
1751
  "canvas.duplicate": "Copy a canvas into a shelf.",
1677
1752
  "canvas.deletePermanently": "Permanently delete a binned canvas.",
1678
1753
  "canvas.restore": "Restore a binned canvas.",
1679
- "canvas.inspect": "Summarize a canvas and suggest inspection commands.",
1754
+ "canvas.inspect": "Read the canvas browser URL, structure summary, and inspection commands.",
1680
1755
  "canvas.tree": "List canvas node ids, hierarchy, kinds, and boxes.",
1681
1756
  "canvas.node": "Read one canvas node and its children.",
1682
1757
  "canvas.selection": "Read the person’s current live browser selection.",
1683
1758
  "canvas realtime": "Canvas presence and activity.",
1684
1759
  "canvas document": "Read or replace a canvas document.",
1760
+ "canvas version": "Retained canvas history.",
1685
1761
  "canvas render": "Create and inspect faithful canvas renders.",
1686
1762
  "canvas participants": "List and change canvas participants.",
1687
1763
  "canvas invites": "Invite people to a canvas."
1688
1764
  };
1765
+
1689
1766
  //#endregion
1690
1767
  //#region src/infrastructure/option-string.mapper.ts
1691
1768
  const toBareStringOption = (option, canAcceptNull = false) => {
@@ -1706,16 +1783,19 @@ const toBareStringOption = (option, canAcceptNull = false) => {
1706
1783
  });
1707
1784
  return (value) => value === nullMarker;
1708
1785
  };
1786
+
1709
1787
  //#endregion
1710
1788
  //#region src/infrastructure/process.adapter.ts
1711
1789
  const createProcessAdapter = () => ({ exit: (code) => {
1712
1790
  throw new ProcessExitError(code);
1713
1791
  } });
1792
+
1714
1793
  //#endregion
1715
1794
  //#region src/infrastructure/cli-polish.lib.ts
1716
1795
  const NAMESPACES = {
1717
1796
  canvas: "Canvases: create, find, share, and manage review surfaces.",
1718
1797
  "canvas render": "Render production-faithful canvas pixels after inspecting exact structure and geometry.",
1798
+ "canvas version": "Inspect and name retained canvas history.",
1719
1799
  "canvas document": "Read or replace the opaque document stored on a canvas.",
1720
1800
  "canvas invites": "Invite people to a canvas and manage pending invitations.",
1721
1801
  "canvas participants": "List and change the people who can reach a canvas.",
@@ -1844,6 +1924,7 @@ const polishCli = (command, input, path = []) => {
1844
1924
  polishCli(child, input, commandPath);
1845
1925
  }
1846
1926
  };
1927
+
1847
1928
  //#endregion
1848
1929
  //#region src/infrastructure/cli-surface.lib.ts
1849
1930
  const CLI_EXCLUDED_PROCEDURES = createCapabilityPolicyAdapter().excludedProcedures;
@@ -1863,6 +1944,7 @@ const removeExcludedProcedures = (command, path = []) => {
1863
1944
  Reflect.set(command, "commands", visible);
1864
1945
  for (const child of visible) removeExcludedProcedures(child, [...path, child.name()]);
1865
1946
  };
1947
+
1866
1948
  //#endregion
1867
1949
  //#region src/infrastructure/commands.program.ts
1868
1950
  const procedurePathOf = (command) => {
@@ -1883,7 +1965,16 @@ const recordsFrom = (command, path = []) => command.commands.filter((child) => c
1883
1965
  }, ...recordsFrom(child, childPath)];
1884
1966
  });
1885
1967
  const registerCommandsProgram = (program, output, catalog) => {
1886
- program.command("commands").description("Emit the command inventory as NDJSON without walking the help tree.").option("--namespace <path>", "Keep commands at or below this space-separated path.").option("--capabilities", "Emit the transport-neutral capability inventory.", false).action((options) => {
1968
+ program.command("commands").description("Emit the command inventory as NDJSON without walking the help tree.").option("--namespace <path>", "Keep commands at or below this space-separated path.").option("--capabilities", "Emit the transport-neutral capability inventory.", false).option("--reference", "Emit complete shared capability contracts for documentation.", false).action((options) => {
1969
+ if (options.reference) {
1970
+ const shared = toSharedCapabilities(catalog());
1971
+ const discovery = createMcpCapabilityDiscoveryAdapter(shared);
1972
+ output.result({
1973
+ items: shared.map((capability) => discovery.describe(capability.id)),
1974
+ truncated: false
1975
+ });
1976
+ return;
1977
+ }
1887
1978
  if (options.capabilities) {
1888
1979
  output.result({
1889
1980
  items: toCapabilityInventory(catalog()),
@@ -1899,6 +1990,7 @@ const registerCommandsProgram = (program, output, catalog) => {
1899
1990
  });
1900
1991
  });
1901
1992
  };
1993
+
1902
1994
  //#endregion
1903
1995
  //#region src/infrastructure/comment.program.ts
1904
1996
  const registerCommentProgram = (program, invocation, catalog, output) => {
@@ -1912,6 +2004,7 @@ const registerCommentProgram = (program, invocation, catalog, output) => {
1912
2004
  }));
1913
2005
  });
1914
2006
  };
2007
+
1915
2008
  //#endregion
1916
2009
  //#region src/infrastructure/doctor.program.ts
1917
2010
  const registerDoctorProgram = (program, dependencies) => {
@@ -1930,6 +2023,7 @@ const registerDoctorProgram = (program, dependencies) => {
1930
2023
  });
1931
2024
  });
1932
2025
  };
2026
+
1933
2027
  //#endregion
1934
2028
  //#region src/infrastructure/fixture.program.ts
1935
2029
  const positiveInteger$1 = (value) => z.coerce.number().int().positive().parse(value);
@@ -2005,129 +2099,7 @@ const registerFixtureProgram = (program, composites, output) => {
2005
2099
  registerRecordingFixture(fixture, composites.recording, output);
2006
2100
  registerWorldFixture(fixture, composites.world, output);
2007
2101
  };
2008
- //#endregion
2009
- //#region src/infrastructure/oauth-loopback.adapter.ts
2010
- const CALLBACK_PATH = "/callback";
2011
- const AUTHORIZATION_TIMEOUT_MS = 12e4;
2012
- const ENTROPY_BYTES = 32;
2013
- const HTTP_OK = 200;
2014
- const HTTP_BAD_REQUEST = 400;
2015
- const HTTP_NOT_FOUND = 404;
2016
- const SUCCESS_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>";
2017
- const endpoint = (issuer, path) => new URL(path, issuer.endsWith("/") ? issuer : `${issuer}/`);
2018
- const launchBrowser = (url) => {
2019
- const command = process.platform === "darwin" ? {
2020
- executable: "open",
2021
- arguments: [url]
2022
- } : process.platform === "win32" ? {
2023
- executable: "rundll32.exe",
2024
- arguments: ["url.dll,FileProtocolHandler", url]
2025
- } : {
2026
- executable: "xdg-open",
2027
- arguments: [url]
2028
- };
2029
- const child = spawn(command.executable, command.arguments, {
2030
- detached: true,
2031
- stdio: "ignore"
2032
- });
2033
- child.once("error", () => false);
2034
- child.unref();
2035
- };
2036
- const handleCallback = (input, request, response) => {
2037
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
2038
- if (request.method !== "GET" || url.pathname !== CALLBACK_PATH) {
2039
- response.writeHead(HTTP_NOT_FOUND).end();
2040
- return;
2041
- }
2042
- if (url.searchParams.get("state") !== input.state) {
2043
- response.writeHead(HTTP_BAD_REQUEST).end("The OAuth state did not match. Return to the terminal and retry.");
2044
- return;
2045
- }
2046
- const error = url.searchParams.get("error");
2047
- const received = url.searchParams.get("code");
2048
- if (error !== null || received === null || received === "") {
2049
- response.writeHead(HTTP_BAD_REQUEST).end("Enhance authentication was not approved.");
2050
- input.completion.reject(new Error(error ?? "the authorization response carried no code"));
2051
- return;
2052
- }
2053
- response.writeHead(HTTP_OK, { "content-type": "text/html; charset=utf-8" }).end(SUCCESS_PAGE);
2054
- input.completion.resolve(received);
2055
- };
2056
- const authorizeUrl = (input) => {
2057
- const authorize = endpoint(input.issuer, "oauth/authorize");
2058
- authorize.search = new URLSearchParams({
2059
- response_type: "code",
2060
- client_id: input.clientId,
2061
- redirect_uri: input.redirectUri,
2062
- scope: input.scope,
2063
- state: input.state,
2064
- code_challenge: input.challenge,
2065
- code_challenge_method: "S256"
2066
- }).toString();
2067
- return authorize.href;
2068
- };
2069
- const authorizationCode = async (input) => {
2070
- const completion = Promise.withResolvers();
2071
- const server = createServer((request, response) => {
2072
- handleCallback({
2073
- state: input.state,
2074
- completion
2075
- }, request, response);
2076
- });
2077
- await new Promise((resolve, reject) => {
2078
- server.once("error", reject);
2079
- server.listen(0, "127.0.0.1", resolve);
2080
- });
2081
- const address = server.address();
2082
- if (address === null || typeof address === "string") {
2083
- server.close();
2084
- throw new Error("the OAuth callback listener has no TCP port");
2085
- }
2086
- const redirectUri = `http://127.0.0.1:${String(address.port)}${CALLBACK_PATH}`;
2087
- const url = authorizeUrl({
2088
- ...input,
2089
- redirectUri
2090
- });
2091
- input.onReady(url);
2092
- if (input.openBrowser) launchBrowser(url);
2093
- const timeout = setTimeout(() => {
2094
- completion.reject(/* @__PURE__ */ new Error("browser authorization timed out"));
2095
- }, AUTHORIZATION_TIMEOUT_MS);
2096
- try {
2097
- return {
2098
- code: await completion.promise,
2099
- redirectUri
2100
- };
2101
- } finally {
2102
- clearTimeout(timeout);
2103
- await new Promise((resolve) => {
2104
- server.close(() => {
2105
- resolve();
2106
- });
2107
- });
2108
- }
2109
- };
2110
- const createOauthLoopbackAdapter = (remote) => ({ authorize: async (input) => {
2111
- try {
2112
- const verifier = randomBytes(ENTROPY_BYTES).toString("base64url");
2113
- const challenge = createHash("sha256").update(verifier).digest("base64url");
2114
- const state = randomBytes(ENTROPY_BYTES).toString("base64url");
2115
- const authorized = await authorizationCode({
2116
- ...input,
2117
- challenge,
2118
- state
2119
- });
2120
- return await remote.exchangeOauthCode({
2121
- issuer: input.issuer,
2122
- clientId: input.clientId,
2123
- code: authorized.code,
2124
- redirectUri: authorized.redirectUri,
2125
- verifier
2126
- });
2127
- } catch (error) {
2128
- 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.");
2129
- }
2130
- } });
2102
+
2131
2103
  //#endregion
2132
2104
  //#region src/infrastructure/prototype.program.ts
2133
2105
  const finiteNumber = (value) => z.coerce.number().parse(value);
@@ -2160,6 +2132,7 @@ const registerPrototypeProgram = (program, invocation, catalog, output) => {
2160
2132
  }));
2161
2133
  });
2162
2134
  };
2135
+
2163
2136
  //#endregion
2164
2137
  //#region src/infrastructure/recording.program.ts
2165
2138
  const integer = (value, name, isPositive) => {
@@ -2186,6 +2159,7 @@ const registerRecordingProgram = (program, input) => {
2186
2159
  }));
2187
2160
  });
2188
2161
  };
2162
+
2189
2163
  //#endregion
2190
2164
  //#region src/infrastructure/remote-router.adapter.ts
2191
2165
  const refuseDocumentConflict = (path, input, result) => {
@@ -2196,6 +2170,7 @@ const createRemoteRouterAdapter = (source, remote) => proxify(source, (path) =>
2196
2170
  query: async (input) => remote.query(path, input),
2197
2171
  mutate: async (input) => refuseDocumentConflict(path, input, await remote.mutate(path, input))
2198
2172
  } }));
2173
+
2199
2174
  //#endregion
2200
2175
  //#region src/infrastructure/transcript.program.ts
2201
2176
  const registerTranscriptProgram = (program, input) => {
@@ -2214,6 +2189,7 @@ const registerTranscriptProgram = (program, input) => {
2214
2189
  }));
2215
2190
  });
2216
2191
  };
2192
+
2217
2193
  //#endregion
2218
2194
  //#region src/infrastructure/cli.program.ts
2219
2195
  const CLI_ASSEMBLY = {
@@ -2309,7 +2285,7 @@ const createCliProgram = (input) => {
2309
2285
  const { descriptions, mutationPaths } = cliMetadataFrom(source);
2310
2286
  const cli = createCli({
2311
2287
  router: createRemoteRouterAdapter(source, input.remote),
2312
- name: "enhance",
2288
+ name: input.commandName,
2313
2289
  version: input.version,
2314
2290
  description: "Operate Enhance as the authenticated person.",
2315
2291
  jsonInput: CLI_ASSEMBLY.jsonInput
@@ -2345,9 +2321,11 @@ const createCliProgram = (input) => {
2345
2321
  }
2346
2322
  };
2347
2323
  };
2324
+
2348
2325
  //#endregion
2349
2326
  //#region src/infrastructure/exit-process.lib.ts
2350
2327
  const exitProcess = (code) => process.exit(code);
2328
+
2351
2329
  //#endregion
2352
2330
  //#region src/infrastructure/ndjson.logger.ts
2353
2331
  const MAX_INLINE_CHARACTERS = 25e3;
@@ -2513,21 +2491,23 @@ const writeResult = (value, sensitiveDirectory) => {
2513
2491
  const writeFailure = (value) => {
2514
2492
  process.stderr.write(`${JSON.stringify(value)}\n`);
2515
2493
  };
2516
- const createNdjsonLoggerAdapter = (state, configDirectory) => {
2494
+ const createNdjsonLoggerAdapter = (state, configDirectory, commandName = "enhance") => {
2517
2495
  const failureState = state;
2518
2496
  const sensitiveDirectory = path.join(configDirectory, "sensitive");
2519
2497
  sweepExpiredSensitiveFiles(sensitiveDirectory);
2520
2498
  return {
2521
2499
  result: (value) => {
2522
- writeResult(value, sensitiveDirectory);
2500
+ writeResult(withCommandName(value, commandName), sensitiveDirectory);
2501
+ },
2502
+ failure: (value) => {
2503
+ writeFailure(withCommandInFailure(value, commandName));
2523
2504
  },
2524
- failure: writeFailure,
2525
2505
  logger: {
2526
2506
  info: (...args) => {
2527
- writeResult(args.length === 1 ? args[0] : args, sensitiveDirectory);
2507
+ writeResult(withCommandName(args.length === 1 ? args[0] : args, commandName), sensitiveDirectory);
2528
2508
  },
2529
2509
  error: (...args) => {
2530
- const message = args.map(String).join("");
2510
+ const message = String(withCommandName(args.map(String).join(""), commandName));
2531
2511
  const parsed = parsedFailure(message);
2532
2512
  if (parsed === null) failureState.pendingParserMessage = message;
2533
2513
  else writeFailure(parsed);
@@ -2535,6 +2515,7 @@ const createNdjsonLoggerAdapter = (state, configDirectory) => {
2535
2515
  }
2536
2516
  };
2537
2517
  };
2518
+
2538
2519
  //#endregion
2539
2520
  //#region src/main.ts
2540
2521
  const main = async () => {
@@ -2542,17 +2523,18 @@ const main = async () => {
2542
2523
  exitCode: 1,
2543
2524
  pendingParserMessage: null
2544
2525
  };
2545
- const output = createNdjsonLoggerAdapter(state, CLI_CONFIG.configDirectory);
2526
+ const output = createNdjsonLoggerAdapter(state, CLI_CONFIG.configDirectory, CLI_CONFIG.commandName);
2546
2527
  const credentials = createFileCredentialAdapter(CLI_CONFIG.configDirectory);
2547
2528
  const mutationKey = createMutationKeyAdapter();
2548
2529
  const cli = createCliProgram({
2549
- version: "0.1.6",
2530
+ version: "0.1.13",
2550
2531
  credentials,
2551
2532
  remote: createHttpRemoteAdapter(CLI_CONFIG.apiUrl, credentials, mutationKey),
2552
2533
  mutationKey,
2553
2534
  output,
2554
2535
  state,
2555
- configDirectory: CLI_CONFIG.configDirectory
2536
+ configDirectory: CLI_CONFIG.configDirectory,
2537
+ commandName: CLI_CONFIG.commandName
2556
2538
  });
2557
2539
  try {
2558
2540
  await cli.run();
@@ -2563,5 +2545,6 @@ const main = async () => {
2563
2545
  }
2564
2546
  };
2565
2547
  main();
2548
+
2566
2549
  //#endregion
2567
- export {};
2550
+ export { };