@enhance-eng/enhance 0.1.25 → 0.1.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { At as fromCanvasReference, Bt as completeRecordingOutputSchema, Dn as canvasTextRunsOf, Dt as assertCanvasReferenceNodes, Et as canvasEditsSchema, Fn as beginCanvasActivityOutputSchema, Gn as getCanvasDocumentOutputSchema, Ht as startRecordingOutputSchema, In as canvasAgentActivityPhaseSchema, It as appErrorSchema, Jn as canvasOperationSchema, Kn as saveCanvasDocumentOutputSchema, Lt as completeScreenOutputSchema, Mt as parseCanvasReference, Nt as PartialBatchError, Pt as CliError, Rt as createScreenOutputSchema, _ as PROCEDURE_DESCRIPTIONS, a as toFailurePayload, an as withFixtureScreen, d as ProcessExitError, dr as canvasAuthoredLayoutValueOf, et as canvasRenderScopedInputSchema, f as createCapabilityCatalogAdapter, fr as canvasAuthoredStyleDeclarations, g as OPTION_DESCRIPTIONS, gt as canvasFindInputSchema, hr as canvasLayoutPriorityDeclarations, i as toExitCode, in as emptyFixtureDocument, it as canvasRemoveCapabilityInputSchema, jt as hasCanvasReferenceScope, k as operationStatusInputSchema, kt as canvasReferenceRenderTarget, l as toSharedCapabilities, lr as canvasReadableSceneDocumentSchema, lt as canvasUpdateHtmlCapabilityInputSchema, m as createCapabilityPolicyAdapter, mr as canvasLayoutMainAxisOf, n as withCommandName, nn as createOrganisationOutputSchema, p as createRouterShapeAdapter, pr as canvasAxisStyleProperties, qn as MAX_CANVAS_OPERATIONS, r as toCanvasAuthoringResult, sr as RENDER_MIN_SCALE, st as canvasReadInputSchema, t as withCommandInFailure, tr as canvasWorldBoundsSchema, u as createMcpCapabilityDiscoveryAdapter, wr as canvasSchema, zt as appendRecordingChunkOutputSchema } from "./cli-output-identity.lib-DpON8As5.mjs";
3
- import { _ as sceneAtVersion, b as createRenderCanvasComposite, d as createRenderFileAdapter, f as readCanvasReferenceScene, g as assertCanvasReferenceOperations, h as createEditCanvasComposite, m as fromCapabilityReference, n as createHttpRemoteAdapter, o as createOauthLoopbackAdapter, p as createWriteHtmlCanvasComposite, r as readCliEnvironment, s as createCapabilityInvocationAdapter, t as createMutationKeyAdapter, v as createApplyCanvasComposite, x as createAuthUseCase, y as createCanvasActivityComposite } from "./mutation-key.adapter-CXQ08HQY.mjs";
2
+ import { $t as createOrganisationOutputSchema, At as PartialBatchError, Ct as canvasEditsSchema, Dt as fromCanvasReference, Et as canvasReferenceRenderTarget, Ft as createScreenOutputSchema, Gn as getCanvasDocumentOutputSchema, It as appendRecordingChunkOutputSchema, Kn as saveCanvasDocumentOutputSchema, Lt as completeRecordingOutputSchema, Mn as beginCanvasActivityOutputSchema, Nn as canvasAgentActivityPhaseSchema, Nt as appErrorSchema, Ot as hasCanvasReferenceScope, Pt as completeScreenOutputSchema, _ as PROCEDURE_DESCRIPTIONS, a as toFailurePayload, ar as canvasReadableSceneDocumentSchema, cr as canvasAuthoredStyleDeclarations, d as ProcessExitError, dr as canvasLayoutPriorityDeclarations, er as canvasWorldBoundsSchema, et as canvasRenderScopedInputSchema, f as createCapabilityCatalogAdapter, g as OPTION_DESCRIPTIONS, gt as canvasFindInputSchema, i as toExitCode, it as canvasRemoveCapabilityInputSchema, jt as CliError, k as operationStatusInputSchema, kt as parseCanvasReference, l as toSharedCapabilities, lr as canvasAxisStyleProperties, lt as canvasUpdateHtmlCapabilityInputSchema, m as createCapabilityPolicyAdapter, n as withCommandName, nn as withFixtureScreen, p as createRouterShapeAdapter, qn as canvasOperationSchema, r as toCanvasAuthoringResult, sr as canvasAuthoredLayoutValueOf, st as canvasReadInputSchema, t as withCommandInFailure, tn as emptyFixtureDocument, u as createMcpCapabilityDiscoveryAdapter, ur as canvasLayoutMainAxisOf, wn as canvasTextRunsOf, wt as assertCanvasReferenceNodes, yr as canvasSchema, zt as startRecordingOutputSchema } from "./cli-output-identity.lib-CWNAXho4.mjs";
3
+ import { S as createAuthUseCase, _ as assertCanvasReferenceOperations, b as createCanvasActivityComposite, d as createRenderFileAdapter, f as readCanvasReferenceScene, g as createEditCanvasComposite, h as fromCapabilityReference, n as createHttpRemoteAdapter, o as createOauthLoopbackAdapter, p as createWriteHtmlCanvasComposite, r as readCliEnvironment, s as createCapabilityInvocationAdapter, t as createMutationKeyAdapter, v as sceneAtVersion, x as createRenderCanvasComposite, y as createApplyCanvasComposite } from "./mutation-key.adapter-A1d27TVY.mjs";
4
4
  import { t as toCapabilityInventory } from "./capability-inventory.mapper-DyYXyVBJ.mjs";
5
5
  import { t as createFileCredentialAdapter } from "./file-credential.adapter-C78gc9OK.mjs";
6
6
  import process from "node:process";
@@ -12,7 +12,9 @@ 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
14
  import { createHash, randomUUID } from "node:crypto";
15
- import { readFile } from "node:fs/promises";
15
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
16
+ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
17
+ import { channel } from "node:diagnostics_channel";
16
18
  import { proxify } from "trpc-cli/dist/proxify.js";
17
19
 
18
20
  //#region ../../packages/contract/src/canvas/canvas-color-css.lib.ts
@@ -365,15 +367,8 @@ const registerAuthProgram = (program, auth, output) => {
365
367
  //#endregion
366
368
  //#region src/infrastructure/canvas-authoring-input.schema.ts
367
369
  const NODE_ID_LENGTH = 200;
368
- const NODE_NAME_LENGTH = 500;
369
- const TEXT_LENGTH = 1e5;
370
- const MAX_NODE_IDS = 1e3;
371
- const MAX_BATCHES = 100;
372
- const MAX_DEPTH = 20;
373
- const MIN_RENDER_SCALE = .1;
374
- const MAX_RENDER_SCALE = 4;
375
370
  const positiveIntegerSchema = z.coerce.number().int().positive();
376
- const renderScaleSchema = z.coerce.number().min(MIN_RENDER_SCALE).max(MAX_RENDER_SCALE);
371
+ const renderScaleSchema = z.coerce.number().positive();
377
372
  const authoringUuidSchema = z.uuid();
378
373
  const styleValueSchema = z.union([
379
374
  z.string(),
@@ -383,20 +378,20 @@ const styleValueSchema = z.union([
383
378
  const styleObjectSchema = z.record(z.string(), styleValueSchema);
384
379
  const textUpdatesSchema = z.array(z.object({
385
380
  nodeId: z.string().min(1).max(NODE_ID_LENGTH),
386
- textContent: z.string().max(TEXT_LENGTH)
387
- })).min(1).max(MAX_NODE_IDS);
381
+ textContent: z.string()
382
+ })).min(1);
388
383
  const renameUpdatesSchema = z.array(z.object({
389
384
  nodeId: z.string().min(1).max(NODE_ID_LENGTH),
390
- name: z.string().max(NODE_NAME_LENGTH)
391
- })).min(1).max(MAX_NODE_IDS);
385
+ name: z.string()
386
+ })).min(1);
392
387
  const styleUpdatesSchema = z.array(z.object({
393
- nodeIds: z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_BATCHES),
388
+ nodeIds: z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1),
394
389
  styles: styleObjectSchema
395
- })).min(1).max(MAX_BATCHES);
390
+ })).min(1);
396
391
  const duplicateInputsSchema = z.array(z.object({
397
392
  id: z.string().min(1).max(NODE_ID_LENGTH),
398
393
  parentId: z.string().min(1).max(NODE_ID_LENGTH).optional()
399
- })).min(1).max(MAX_BATCHES);
394
+ })).min(1);
400
395
  const moveInputsSchema = z.array(z.union([
401
396
  z.object({
402
397
  nodeId: z.string().min(1).max(NODE_ID_LENGTH),
@@ -411,9 +406,9 @@ const moveInputsSchema = z.array(z.union([
411
406
  parentId: z.string().min(1).max(NODE_ID_LENGTH),
412
407
  index: z.number().int().nonnegative().optional()
413
408
  })
414
- ])).min(1).max(MAX_BATCHES);
415
- const nodeIdsSchema = z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1).max(MAX_NODE_IDS);
416
- const sourceDepthSchema = z.coerce.number().int().min(0).max(MAX_DEPTH);
409
+ ])).min(1);
410
+ const nodeIdsSchema = z.array(z.string().min(1).max(NODE_ID_LENGTH)).min(1);
411
+ const sourceDepthSchema = z.coerce.number().int().min(0);
417
412
 
418
413
  //#endregion
419
414
  //#region src/infrastructure/canvas-authoring-command.lib.ts
@@ -455,25 +450,26 @@ const applyAuthoringEdits = async (input, options, edits, idPrefix) => {
455
450
  };
456
451
 
457
452
  //#endregion
458
- //#region src/infrastructure/canvas-operation-input.adapter.ts
459
- const MAX_OPERATION_FILE_BYTES = 1048576;
460
- const operationBatchSchema = z.array(canvasOperationSchema).min(1).max(MAX_CANVAS_OPERATIONS);
461
- const textFrom = (value) => {
453
+ //#region src/infrastructure/canvas-authoring-input.lib.ts
454
+ const canvasAuthoringInput = (value, option) => {
462
455
  if (!value.startsWith("@")) return value;
463
456
  const selected = value.slice(1);
464
- if (selected === "") throw new CliError("BAD_REQUEST", "--operations @ must name a JSON file.", "Pass --operations @/absolute/path/layout.json or an inline JSON array.");
457
+ if (selected === "") throw new CliError("BAD_REQUEST", `${option} @ must name a file.`, `Pass ${option} @/absolute/path/to/file or an inline value.`);
465
458
  const filePath = path.resolve(selected);
466
459
  try {
467
- const stats = statSync(filePath);
468
- if (!stats.isFile() || stats.size > MAX_OPERATION_FILE_BYTES) throw new Error("invalid size");
460
+ if (!statSync(filePath).isFile()) throw new Error("not a regular file");
469
461
  return readFileSync(filePath, "utf8");
470
462
  } catch {
471
- throw new CliError("BAD_REQUEST", `Could not read a bounded operations file at ${filePath}.`, "Use a regular JSON file no larger than 1 MiB.");
463
+ throw new CliError("BAD_REQUEST", `Could not read the file at ${filePath}.`, "Use a readable regular UTF-8 file.");
472
464
  }
473
465
  };
466
+
467
+ //#endregion
468
+ //#region src/infrastructure/canvas-operation-input.adapter.ts
469
+ const operationBatchSchema = z.array(canvasOperationSchema).min(1);
474
470
  const decodedFrom = (value) => {
475
471
  try {
476
- return JSON.parse(textFrom(value));
472
+ return JSON.parse(canvasAuthoringInput(value, "--operations"));
477
473
  } catch (error) {
478
474
  if (error instanceof CliError) throw error;
479
475
  throw new CliError("BAD_REQUEST", "--operations must be one valid JSON array.", "Pass inline JSON or @/absolute/path/layout.json; run 'enhance canvas apply --help' for examples.");
@@ -590,29 +586,12 @@ const configureCanvasAuthoringActivity = (canvas, input) => {
590
586
  configureFinish(canvas, input);
591
587
  };
592
588
 
593
- //#endregion
594
- //#region src/infrastructure/canvas-authoring-bounded-input.lib.ts
595
- const boundedCanvasAuthoringInput = (value, bytes, option) => {
596
- if (!value.startsWith("@")) return value;
597
- const selected = value.slice(1);
598
- if (selected === "") throw new CliError("BAD_REQUEST", `${option} @ must name a file.`, `Pass ${option} @/absolute/path/to/file or an inline value.`);
599
- const filePath = path.resolve(selected);
600
- try {
601
- const stats = statSync(filePath);
602
- if (!stats.isFile() || stats.size > bytes) throw new Error("invalid size");
603
- return readFileSync(filePath, "utf8");
604
- } catch {
605
- 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.`);
606
- }
607
- };
608
-
609
589
  //#endregion
610
590
  //#region src/infrastructure/canvas-json-input.adapter.ts
611
- const MAX_JSON_BYTES = 1048576;
612
591
  const createCanvasJsonInputAdapter = (value, schema, option) => {
613
592
  const decoded = (() => {
614
593
  try {
615
- return JSON.parse(boundedCanvasAuthoringInput(value, MAX_JSON_BYTES, option));
594
+ return JSON.parse(canvasAuthoringInput(value, option));
616
595
  } catch (error) {
617
596
  if (error instanceof CliError) throw error;
618
597
  throw new CliError("BAD_REQUEST", `${option} must be valid JSON.`, `Pass inline JSON or @/absolute/path/to/input.json; run the command with --help.`);
@@ -1241,12 +1220,7 @@ const configureCanvasAuthoringStructure = (canvas, input) => {
1241
1220
 
1242
1221
  //#endregion
1243
1222
  //#region src/infrastructure/canvas-html-input.adapter.ts
1244
- const MAX_HTML_BYTES = 262144;
1245
- const createCanvasHtmlInputAdapter = (value) => {
1246
- const html = boundedCanvasAuthoringInput(value, MAX_HTML_BYTES, "--html");
1247
- 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.");
1248
- return html;
1249
- };
1223
+ const createCanvasHtmlInputAdapter = (value) => canvasAuthoringInput(value, "--html");
1250
1224
 
1251
1225
  //#endregion
1252
1226
  //#region src/infrastructure/canvas-authoring-write.program.ts
@@ -1514,7 +1488,7 @@ const createCanvasRenderInputAdapter = (options) => {
1514
1488
  //#region src/infrastructure/canvas.program.ts
1515
1489
  const positiveInteger$2 = z.coerce.number().int().positive();
1516
1490
  const nonnegativeInteger = z.coerce.number().int().nonnegative();
1517
- const renderScale = z.coerce.number().min(RENDER_MIN_SCALE).max(4);
1491
+ const renderScale = z.coerce.number().positive();
1518
1492
  const RECORDING_NODE_PREFIX = "rec_";
1519
1493
  const numberFrom = (schema, value, option, command = "canvas render") => {
1520
1494
  const parsed = schema.safeParse(value);
@@ -1619,6 +1593,689 @@ const registerCanvasProgram = (program, input) => {
1619
1593
  configureRender(render, input);
1620
1594
  };
1621
1595
 
1596
+ //#endregion
1597
+ //#region ../../packages/sdk/dist/capture-files.lib-DmLQGNWF.mjs
1598
+ const CAPTURE_KEY_LENGTH = 160;
1599
+ const CAPTURE_METADATA_LENGTH = 200;
1600
+ const CAPTURE_ISSUE_LENGTH = 500;
1601
+ const CAPTURE_FAILURE_LENGTH = 1e3;
1602
+ const CAPTURE_UPLOAD_BATCH_SIZE = 400;
1603
+ const key = z.string().trim().min(1).max(CAPTURE_KEY_LENGTH);
1604
+ const digest = z.string().regex(/^[a-f0-9]{64}$/u);
1605
+ const dimension = z.number().int().positive();
1606
+ const captureKeySchema = z.strictObject({
1607
+ source: key,
1608
+ journey: key,
1609
+ step: key,
1610
+ variant: key
1611
+ });
1612
+ const captureBlobSchema = z.strictObject({
1613
+ sha256: digest,
1614
+ bytes: z.number().int().positive(),
1615
+ mediaType: z.string().min(1).max(CAPTURE_METADATA_LENGTH)
1616
+ });
1617
+ const captureArtifactSchema = z.strictObject({
1618
+ format: z.literal("enhance-capture"),
1619
+ version: z.literal(1),
1620
+ key: captureKeySchema,
1621
+ label: key,
1622
+ journeyLabel: key,
1623
+ order: z.number().int().nonnegative(),
1624
+ viewport: z.strictObject({
1625
+ width: dimension,
1626
+ height: dimension,
1627
+ deviceScaleFactor: z.number().positive()
1628
+ }),
1629
+ extent: z.enum(["viewport", "full-page"]),
1630
+ source: z.strictObject({
1631
+ format: z.literal("rrweb-screen"),
1632
+ version: z.literal(1),
1633
+ blob: captureBlobSchema
1634
+ }),
1635
+ preview: z.strictObject({
1636
+ blob: captureBlobSchema,
1637
+ width: dimension,
1638
+ height: dimension,
1639
+ pixelRatio: z.number().positive()
1640
+ }),
1641
+ assets: z.array(z.strictObject({
1642
+ url: z.url(),
1643
+ blob: captureBlobSchema
1644
+ })),
1645
+ provenance: z.strictObject({
1646
+ adapter: key,
1647
+ sdkVersion: key,
1648
+ kernelVersion: key,
1649
+ browser: key,
1650
+ capturedAt: z.iso.datetime(),
1651
+ sourceUrl: z.url().optional(),
1652
+ commit: z.string().min(1).max(CAPTURE_METADATA_LENGTH).optional()
1653
+ }),
1654
+ issues: z.array(z.strictObject({
1655
+ code: key,
1656
+ message: z.string().min(1).max(CAPTURE_ISSUE_LENGTH)
1657
+ }))
1658
+ }).superRefine((artifact, ctx) => {
1659
+ if (artifact.preview.width / artifact.preview.pixelRatio !== artifact.viewport.width || artifact.preview.height / artifact.preview.pixelRatio !== artifact.viewport.height) ctx.addIssue({
1660
+ code: "custom",
1661
+ path: ["preview"],
1662
+ message: "The preview and captured CSS extent must match."
1663
+ });
1664
+ if (artifact.source.blob.mediaType !== "application/json") ctx.addIssue({
1665
+ code: "custom",
1666
+ path: [
1667
+ "source",
1668
+ "blob",
1669
+ "mediaType"
1670
+ ],
1671
+ message: "Capture sources must be frozen JSON."
1672
+ });
1673
+ if (artifact.preview.blob.mediaType !== "image/png") ctx.addIssue({
1674
+ code: "custom",
1675
+ path: [
1676
+ "preview",
1677
+ "blob",
1678
+ "mediaType"
1679
+ ],
1680
+ message: "Capture previews must be PNG."
1681
+ });
1682
+ if (new Set(artifact.assets.map((asset) => asset.url)).size !== artifact.assets.length) ctx.addIssue({
1683
+ code: "custom",
1684
+ path: ["assets"],
1685
+ message: "Capture resource URLs must be unique."
1686
+ });
1687
+ });
1688
+ const captureRunDescriptorSchema = z.strictObject({
1689
+ id: z.uuid(),
1690
+ canvasId: z.uuid(),
1691
+ source: key,
1692
+ runKey: key,
1693
+ generation: z.number().int().nonnegative(),
1694
+ participants: z.array(key).min(1),
1695
+ expiresAt: z.iso.datetime(),
1696
+ formatVersion: z.literal(1)
1697
+ });
1698
+ const captureAttemptSchema = z.strictObject({
1699
+ participant: key,
1700
+ testId: key,
1701
+ project: key,
1702
+ retry: z.number().int().nonnegative(),
1703
+ status: z.enum([
1704
+ "passed",
1705
+ "failed",
1706
+ "skipped",
1707
+ "interrupted",
1708
+ "timedOut"
1709
+ ]),
1710
+ captures: z.array(captureArtifactSchema)
1711
+ });
1712
+ const captureManifestSchema = z.strictObject({
1713
+ format: z.literal("enhance-capture-run"),
1714
+ version: z.literal(1),
1715
+ run: captureRunDescriptorSchema,
1716
+ participants: z.array(z.strictObject({
1717
+ id: key,
1718
+ status: z.enum([
1719
+ "passed",
1720
+ "failed",
1721
+ "interrupted"
1722
+ ])
1723
+ })).min(1),
1724
+ attempts: z.array(captureAttemptSchema),
1725
+ ordering: z.enum(["partial", "complete"])
1726
+ });
1727
+ const captureReceiptSchema = z.strictObject({
1728
+ runId: z.uuid(),
1729
+ canvasId: z.uuid(),
1730
+ canvasUrl: z.url(),
1731
+ version: z.number().int().positive(),
1732
+ manifestDigest: digest,
1733
+ frames: z.array(z.strictObject({
1734
+ key: captureKeySchema,
1735
+ frameId: key,
1736
+ captureId: z.uuid()
1737
+ })),
1738
+ issues: z.array(z.strictObject({
1739
+ code: key,
1740
+ message: z.string().max(CAPTURE_ISSUE_LENGTH)
1741
+ }))
1742
+ });
1743
+ const beginCaptureRunInputSchema = z.strictObject({
1744
+ canvasId: z.uuid(),
1745
+ source: key.default("default"),
1746
+ runKey: key,
1747
+ participants: z.array(key).min(1).default(["local"]),
1748
+ formatVersion: z.literal(1).default(1)
1749
+ });
1750
+ const beginCaptureRunOutputSchema = z.strictObject({ run: captureRunDescriptorSchema });
1751
+ z.strictObject({ runId: z.uuid() });
1752
+ const captureRunStateSchema = z.enum([
1753
+ "collecting",
1754
+ "sealed",
1755
+ "converting",
1756
+ "committed",
1757
+ "failed",
1758
+ "cancelled"
1759
+ ]);
1760
+ const getCaptureRunOutputSchema = z.strictObject({
1761
+ run: captureRunDescriptorSchema,
1762
+ state: captureRunStateSchema,
1763
+ receipt: captureReceiptSchema.nullable(),
1764
+ failure: z.strictObject({
1765
+ code: key,
1766
+ message: z.string().max(CAPTURE_FAILURE_LENGTH)
1767
+ }).nullable()
1768
+ });
1769
+ z.strictObject({
1770
+ runId: z.uuid(),
1771
+ blobs: z.array(captureBlobSchema).min(1).max(CAPTURE_UPLOAD_BATCH_SIZE)
1772
+ });
1773
+ const reserveCaptureBlobsOutputSchema = z.strictObject({ uploads: z.array(z.strictObject({
1774
+ sha256: digest,
1775
+ upload: z.strictObject({
1776
+ url: z.url(),
1777
+ headers: z.record(z.string(), z.string()),
1778
+ expiresAt: z.iso.datetime()
1779
+ }).nullable()
1780
+ })).max(CAPTURE_UPLOAD_BATCH_SIZE) });
1781
+ z.strictObject({ manifest: captureManifestSchema });
1782
+ const COMMIT_LENGTH = 200;
1783
+ z.strictObject({
1784
+ canvasId: z.uuid(),
1785
+ frameId: z.string().min(1),
1786
+ captureId: z.uuid()
1787
+ });
1788
+ const preview = z.strictObject({
1789
+ captureId: z.uuid(),
1790
+ capturedAt: z.iso.datetime(),
1791
+ commit: z.string().max(COMMIT_LENGTH).optional(),
1792
+ url: z.string().min(1),
1793
+ width: z.number().positive(),
1794
+ height: z.number().positive(),
1795
+ pixelRatio: z.number().positive()
1796
+ });
1797
+ z.strictObject({
1798
+ frameId: z.string(),
1799
+ before: preview,
1800
+ after: preview
1801
+ });
1802
+ const captureKeyString = (key) => JSON.stringify([
1803
+ key.source,
1804
+ key.journey,
1805
+ key.step,
1806
+ key.variant
1807
+ ]);
1808
+ const compare = (left, right) => left < right ? -1 : left === right ? 0 : 1;
1809
+ const enqueueJsonObject = (item, state) => {
1810
+ const keys = Object.keys(item).toSorted(compare);
1811
+ state.output.push("{");
1812
+ state.pending.push({ text: "}" });
1813
+ for (let index = keys.length - 1; index >= 0; index--) {
1814
+ const key = keys[index];
1815
+ if (key === void 0) continue;
1816
+ state.pending.push({ value: Reflect.get(item, key) }, { text: `${JSON.stringify(key)}:` });
1817
+ if (index > 0) state.pending.push({ text: "," });
1818
+ }
1819
+ };
1820
+ const canAppendJsonValue = (item, state) => {
1821
+ if (item === null || typeof item === "boolean" || typeof item === "string" || typeof item === "number" && Number.isFinite(item)) {
1822
+ state.output.push(JSON.stringify(item));
1823
+ return true;
1824
+ }
1825
+ if (typeof item !== "object" || state.active.has(item)) return false;
1826
+ if (!Array.isArray(item) && Object.getPrototypeOf(item) !== Object.prototype) return false;
1827
+ state.active.add(item);
1828
+ state.pending.push({ leave: item });
1829
+ if (Array.isArray(item)) {
1830
+ state.output.push("[");
1831
+ state.pending.push({ text: "]" });
1832
+ for (let index = item.length - 1; index >= 0; index--) {
1833
+ state.pending.push({ value: item[index] });
1834
+ if (index > 0) state.pending.push({ text: "," });
1835
+ }
1836
+ } else enqueueJsonObject(item, state);
1837
+ return true;
1838
+ };
1839
+ /** Null means a value would be lost or coerced by JSON; it must never be hashed. */
1840
+ const canonicalCaptureJson = (value) => {
1841
+ const state = {
1842
+ pending: [{ value }],
1843
+ active: /* @__PURE__ */ new Set(),
1844
+ output: []
1845
+ };
1846
+ while (state.pending.length > 0) {
1847
+ const task = state.pending.pop();
1848
+ if (task === void 0) break;
1849
+ if ("text" in task) state.output.push(task.text);
1850
+ else if ("leave" in task) state.active.delete(task.leave);
1851
+ else if (!canAppendJsonValue(task.value, state)) return null;
1852
+ }
1853
+ return state.output.join("");
1854
+ };
1855
+ const captureBlobs = (artifacts) => {
1856
+ const blobs = /* @__PURE__ */ new Map();
1857
+ const unique = [];
1858
+ for (const artifact of artifacts) {
1859
+ const references = [
1860
+ artifact.source.blob,
1861
+ artifact.preview.blob,
1862
+ ...artifact.assets.map((asset) => asset.blob)
1863
+ ];
1864
+ for (const blob of references) {
1865
+ const previous = blobs.get(blob.sha256);
1866
+ if (previous !== void 0 && canonicalCaptureJson(previous) !== canonicalCaptureJson(blob)) return "The same capture digest has conflicting blob metadata.";
1867
+ if (previous === void 0) {
1868
+ unique.push(blob);
1869
+ blobs.set(blob.sha256, blob);
1870
+ }
1871
+ }
1872
+ }
1873
+ return unique.toSorted((a, b) => compare(a.sha256, b.sha256));
1874
+ };
1875
+ const finalAttempts = (manifest) => {
1876
+ const expected = new Set(manifest.run.participants);
1877
+ if (expected.size !== manifest.run.participants.length || manifest.participants.length !== expected.size || new Set(manifest.participants.map((part) => part.id)).size !== expected.size || manifest.participants.some((part) => !expected.has(part.id) || part.status !== "passed")) return "Every reserved participant must finish successfully exactly once.";
1878
+ const attempts = /* @__PURE__ */ new Map();
1879
+ const terminal = /* @__PURE__ */ new Map();
1880
+ for (const attempt of manifest.attempts) {
1881
+ if (!expected.has(attempt.participant)) return "Capture attempt belongs to an unreserved participant.";
1882
+ const identity = JSON.stringify([
1883
+ attempt.participant,
1884
+ attempt.project,
1885
+ attempt.testId
1886
+ ]);
1887
+ const attemptKey = JSON.stringify([identity, attempt.retry]);
1888
+ const content = canonicalCaptureJson(attempt);
1889
+ if (content === null) return "Capture attempts must contain finite JSON values.";
1890
+ const previous = terminal.get(attemptKey);
1891
+ if (previous !== void 0 && previous !== content) return "Conflicting terminal records for the same test attempt.";
1892
+ terminal.set(attemptKey, content);
1893
+ const selected = attempts.get(identity);
1894
+ if (selected === void 0 || selected.retry < attempt.retry) attempts.set(identity, attempt);
1895
+ }
1896
+ return manifest.attempts.filter((attempt) => attempts.get(JSON.stringify([
1897
+ attempt.participant,
1898
+ attempt.project,
1899
+ attempt.testId
1900
+ ])) === attempt);
1901
+ };
1902
+ const uniqueCaptures = (source, artifacts) => {
1903
+ const keys = /* @__PURE__ */ new Set();
1904
+ const orders = /* @__PURE__ */ new Set();
1905
+ for (const artifact of artifacts) {
1906
+ if (artifact.key.source !== source) return "Capture source differs from its reserved run.";
1907
+ const identity = captureKeyString(artifact.key);
1908
+ if (keys.has(identity)) return `Duplicate capture key: ${identity}`;
1909
+ const order = JSON.stringify([
1910
+ artifact.key.journey,
1911
+ artifact.key.variant,
1912
+ artifact.order
1913
+ ]);
1914
+ if (orders.has(order)) return `Duplicate step order in journey ${artifact.key.journey}.`;
1915
+ keys.add(identity);
1916
+ orders.add(order);
1917
+ }
1918
+ return null;
1919
+ };
1920
+ const compareCaptureArtifacts = (left, right) => {
1921
+ const journey = compare(left.key.journey, right.key.journey);
1922
+ if (journey !== 0) return journey;
1923
+ const variant = compare(left.key.variant, right.key.variant);
1924
+ return variant === 0 ? left.order - right.order : variant;
1925
+ };
1926
+ /** All publishers select whole terminal attempts with the same completeness rules. */
1927
+ const selectedCaptures = (input) => {
1928
+ const parsed = captureManifestSchema.safeParse(input);
1929
+ if (!parsed.success) return "Invalid capture manifest.";
1930
+ const manifest = parsed.data;
1931
+ const attempts = finalAttempts(manifest);
1932
+ if (typeof attempts === "string") return attempts;
1933
+ const artifacts = attempts.flatMap((attempt) => attempt.status === "passed" ? attempt.captures : []);
1934
+ if (artifacts.length === 0) return "A run must contain at least one successful capture.";
1935
+ const conflict = uniqueCaptures(manifest.run.source, artifacts);
1936
+ if (conflict !== null) return conflict;
1937
+ const blobs = captureBlobs(artifacts);
1938
+ return typeof blobs === "string" ? blobs : artifacts.toSorted(compareCaptureArtifacts);
1939
+ };
1940
+ const captureManifestContent = (manifest) => {
1941
+ const serialized = canonicalCaptureJson(manifest);
1942
+ return serialized === null ? null : `enhance-capture-run:v1\0${serialized}`;
1943
+ };
1944
+ const captureError = (code, message, runId) => Object.assign(new Error(message), {
1945
+ code,
1946
+ ...runId !== void 0 && { runId }
1947
+ });
1948
+ const captureBlobDigest = (bytes) => createHash("sha256").update(bytes).digest("hex");
1949
+ const captureManifestDigest = (manifest) => {
1950
+ const canonical = captureManifestContent(manifest);
1951
+ if (canonical === null) throw new Error("A capture manifest must contain only finite JSON values.");
1952
+ return createHash("sha256").update(canonical).digest("hex");
1953
+ };
1954
+ const captureBlobPath = (directory, digest) => {
1955
+ if (!/^[a-f0-9]{64}$/u.test(digest)) throw captureError("artifact", "Invalid capture blob digest.");
1956
+ return path.join(path.resolve(directory), "blobs", digest);
1957
+ };
1958
+ const readCaptureBlob = async (directory, description) => {
1959
+ const path = captureBlobPath(directory, description.sha256);
1960
+ const info = await stat(path);
1961
+ if (!info.isFile() || info.size !== description.bytes) throw captureError("artifact", `Capture blob size does not match ${description.sha256}.`);
1962
+ const bytes = await readFile(path);
1963
+ if (captureBlobDigest(bytes) !== description.sha256) throw captureError("artifact", `Capture blob checksum does not match ${description.sha256}.`);
1964
+ return bytes;
1965
+ };
1966
+ const writeCapturePayload = async (directory, payload) => {
1967
+ const artifact = captureArtifactSchema.parse(payload.artifact);
1968
+ await mkdir(path.join(directory, "blobs"), { recursive: true });
1969
+ let unavailable = 0;
1970
+ for (const blob of payload.blobs) try {
1971
+ if (blob.description.bytes !== blob.bytes.byteLength || captureBlobDigest(blob.bytes) !== blob.description.sha256) throw captureError("artifact", "Capture blob bytes do not match their descriptor.");
1972
+ const path = captureBlobPath(directory, blob.description.sha256);
1973
+ const temporary = `${path}.${globalThis.crypto.randomUUID()}.tmp`;
1974
+ await writeFile(temporary, blob.bytes, {
1975
+ flag: "wx",
1976
+ mode: 384
1977
+ });
1978
+ await rename(temporary, path);
1979
+ } catch {
1980
+ unavailable++;
1981
+ }
1982
+ try {
1983
+ await readCaptureBlob(directory, artifact.source.blob);
1984
+ } catch {
1985
+ await readCaptureBlob(directory, artifact.preview.blob);
1986
+ }
1987
+ if (unavailable > 0) channel("enhance.capture.resources").publish({
1988
+ stage: "local-write",
1989
+ unavailable
1990
+ });
1991
+ return artifact;
1992
+ };
1993
+ const writeCaptureJson = async (path, value) => {
1994
+ const temporary = `${path}.${globalThis.crypto.randomUUID()}.tmp`;
1995
+ await writeFile(temporary, JSON.stringify(value), { mode: 384 });
1996
+ await rename(temporary, path);
1997
+ };
1998
+ const readCaptureManifest = async (path) => {
1999
+ const raw = JSON.parse(await readFile(path, "utf8"));
2000
+ return captureManifestSchema.parse(raw);
2001
+ };
2002
+
2003
+ //#endregion
2004
+ //#region ../../packages/sdk/dist/capture-client.client-D7YPcnYK.mjs
2005
+ const UPLOAD_BATCH_SIZE = 400;
2006
+ const POLL_INTERVAL_MS = 250;
2007
+ const uploadBlob = async (input) => {
2008
+ if (input.held === void 0) throw captureError("transport", "Enhance omitted a requested blob reservation.", input.runId);
2009
+ const upload = input.held.upload;
2010
+ if (upload === null) return;
2011
+ const bytes = await readCaptureBlob(input.directory, input.blob);
2012
+ try {
2013
+ if (!(await fetch(upload.url, {
2014
+ method: "PUT",
2015
+ headers: upload.headers,
2016
+ body: new Blob([Uint8Array.from(bytes)]),
2017
+ signal: AbortSignal.timeout(input.transport.timeoutMs),
2018
+ redirect: "error"
2019
+ })).ok) throw captureError("transport", "Upload refused.", input.runId);
2020
+ } catch {
2021
+ throw captureError("transport", "Capture upload was not confirmed. Resume the same manifest.", input.runId);
2022
+ }
2023
+ };
2024
+ const uploadBlobs = async (transport, manifest, directory, blobs) => {
2025
+ let unavailable = 0;
2026
+ const available = [];
2027
+ for (const blob of blobs) try {
2028
+ await readCaptureBlob(directory, blob);
2029
+ available.push(blob);
2030
+ } catch {
2031
+ unavailable++;
2032
+ }
2033
+ for (let start = 0; start < available.length; start += UPLOAD_BATCH_SIZE) {
2034
+ const batch = available.slice(start, start + UPLOAD_BATCH_SIZE);
2035
+ const reserved = await transport.request("captureRun.reserveAssets", {
2036
+ runId: manifest.run.id,
2037
+ blobs: batch
2038
+ }, reserveCaptureBlobsOutputSchema);
2039
+ const uploads = new Map(reserved.uploads.map((item) => [item.sha256, item]));
2040
+ for (const blob of batch) try {
2041
+ await uploadBlob({
2042
+ transport,
2043
+ runId: manifest.run.id,
2044
+ directory,
2045
+ blob,
2046
+ held: uploads.get(blob.sha256)
2047
+ });
2048
+ } catch {
2049
+ unavailable++;
2050
+ }
2051
+ }
2052
+ if (unavailable > 0) channel("enhance.capture.resources").publish({
2053
+ stage: "upload",
2054
+ runId: manifest.run.id,
2055
+ unavailable
2056
+ });
2057
+ };
2058
+ const committedRun = async (transport, runId) => {
2059
+ let status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
2060
+ const deadline = Date.now() + transport.publicationTimeoutMs;
2061
+ while (status.receipt === null && status.failure === null && !["cancelled", "failed"].includes(status.state)) {
2062
+ if (Date.now() >= deadline) throw captureError("transport", `Capture run ${runId} is still processing. Resume the same manifest.`, runId);
2063
+ await new Promise((resolve) => {
2064
+ setTimeout(resolve, POLL_INTERVAL_MS);
2065
+ });
2066
+ status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
2067
+ }
2068
+ if (status.receipt === null) throw captureError(status.failure?.code === "conflict" ? "conflict" : "conversion", status.failure?.message ?? "The capture run was cancelled.", runId);
2069
+ return status.receipt;
2070
+ };
2071
+ const checkedReceipt = (receipt, manifest) => {
2072
+ if (receipt.runId !== manifest.run.id || receipt.canvasId !== manifest.run.canvasId || receipt.manifestDigest !== captureManifestDigest(manifest)) throw captureError("conflict", "This run committed a different manifest.", manifest.run.id);
2073
+ return receipt;
2074
+ };
2075
+ const publishManifest = async (transport, manifest, directory) => {
2076
+ const artifacts = selectedCaptures(manifest);
2077
+ if (typeof artifacts === "string") throw captureError("artifact", artifacts);
2078
+ const blobs = captureBlobs(artifacts);
2079
+ if (typeof blobs === "string") throw captureError("artifact", blobs);
2080
+ const current = await transport.request("captureRun.get", { runId: manifest.run.id }, getCaptureRunOutputSchema, true);
2081
+ if (current.receipt !== null) {
2082
+ const receipt = checkedReceipt(current.receipt, manifest);
2083
+ await writeCaptureJson(path.join(directory, "receipt.json"), receipt);
2084
+ return receipt;
2085
+ }
2086
+ if (current.state === "collecting") await uploadBlobs(transport, manifest, directory, blobs);
2087
+ await transport.request("captureRun.seal", { manifest }, getCaptureRunOutputSchema);
2088
+ const receipt = checkedReceipt(await committedRun(transport, manifest.run.id), manifest);
2089
+ await writeCaptureJson(path.join(directory, "receipt.json"), receipt);
2090
+ return receipt;
2091
+ };
2092
+ const publishCaptureManifest = async (transport, manifest, directory) => {
2093
+ try {
2094
+ return await publishManifest(transport, manifest, directory);
2095
+ } catch (error) {
2096
+ if (error instanceof Error) throw Object.assign(error, { runId: manifest.run.id });
2097
+ throw captureError("transport", "Capture publication was not confirmed. Resume the same manifest.", manifest.run.id);
2098
+ }
2099
+ };
2100
+ const RATE_LIMIT_STATUS = 429;
2101
+ const MILLISECONDS_PER_SECOND = 1e3;
2102
+ const MAX_ERROR_LENGTH = 1e3;
2103
+ const DEFAULT_TIMEOUT_MS = 3e4;
2104
+ const DEFAULT_PUBLICATION_TIMEOUT_MS = 6e5;
2105
+ const NODE_TIMER_MAX_MS = 2147483647;
2106
+ const HTTP_ERRORS = /* @__PURE__ */ new Map([
2107
+ [401, "authorization"],
2108
+ [403, "authorization"],
2109
+ [409, "conflict"],
2110
+ [400, "artifact"]
2111
+ ]);
2112
+ const requestResponse = async (url, options, timeoutMs, retryDeadline) => {
2113
+ try {
2114
+ for (;;) {
2115
+ const response = await fetch(url, {
2116
+ ...options,
2117
+ signal: AbortSignal.timeout(timeoutMs)
2118
+ });
2119
+ if (response.status !== RATE_LIMIT_STATUS) return response;
2120
+ const header = response.headers.get("retry-after");
2121
+ if (header === null) return response;
2122
+ const seconds = Number(header);
2123
+ const wait = Number.isFinite(seconds) ? seconds * MILLISECONDS_PER_SECOND : Date.parse(header) - Date.now();
2124
+ if (!Number.isFinite(wait) || wait < 0 || Date.now() + wait >= retryDeadline) return response;
2125
+ await response.body?.cancel();
2126
+ await setTimeout$1(wait);
2127
+ }
2128
+ } catch {
2129
+ throw captureError("transport", "Enhance did not confirm the request. Resume the same run to recover its result.");
2130
+ }
2131
+ };
2132
+ const responseBody = async (response) => {
2133
+ try {
2134
+ return await response.json();
2135
+ } catch {
2136
+ return null;
2137
+ }
2138
+ };
2139
+ const call = async (url, options, schema, request) => {
2140
+ const { procedure, timeoutMs, publicationTimeoutMs } = request;
2141
+ const response = await requestResponse(url, options, timeoutMs, Date.now() + publicationTimeoutMs);
2142
+ const body = await responseBody(response);
2143
+ if (!response.ok) {
2144
+ const error = typeof body === "object" && body !== null ? Reflect.get(body, "error") : null;
2145
+ const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : null;
2146
+ throw captureError(HTTP_ERRORS.get(response.status) ?? "transport", typeof message === "string" ? message.slice(0, MAX_ERROR_LENGTH) : `Enhance rejected ${procedure} (HTTP ${String(response.status)}).`);
2147
+ }
2148
+ const result = typeof body === "object" && body !== null ? Reflect.get(body, "result") : null;
2149
+ const data = typeof result === "object" && result !== null ? Reflect.get(result, "data") : void 0;
2150
+ const parsed = schema.safeParse(data);
2151
+ if (!parsed.success) throw captureError("transport", `Enhance returned an incompatible ${procedure} response.`);
2152
+ return parsed.data;
2153
+ };
2154
+ const captureTransport = (options) => {
2155
+ const base = URL.parse(options.apiUrl);
2156
+ if (base === null || !["http:", "https:"].includes(base.protocol) || base.username !== "" || base.password !== "" || options.token.trim() === "") throw captureError("configuration", "Enhance needs an HTTP API URL and an explicit token.");
2157
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2158
+ const publicationTimeoutMs = options.publicationTimeoutMs ?? DEFAULT_PUBLICATION_TIMEOUT_MS;
2159
+ if (!Number.isSafeInteger(publicationTimeoutMs) || publicationTimeoutMs < 1) throw captureError("configuration", "Enhance publication timeout must be a positive integer in milliseconds.");
2160
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > NODE_TIMER_MAX_MS) throw captureError("configuration", `Enhance timeout must fit the Node timer range of 1 to ${String(NODE_TIMER_MAX_MS)} milliseconds.`);
2161
+ return {
2162
+ timeoutMs,
2163
+ publicationTimeoutMs,
2164
+ request: async (procedure, input, schema, isQuery = false) => {
2165
+ const url = new URL(`${base.pathname.replace(/\/$/u, "")}/trpc/${procedure}`, base.origin);
2166
+ if (isQuery) url.searchParams.set("input", JSON.stringify(input));
2167
+ return call(url, {
2168
+ method: isQuery ? "GET" : "POST",
2169
+ headers: {
2170
+ authorization: `Bearer ${options.token}`,
2171
+ "content-type": "application/json"
2172
+ },
2173
+ ...!isQuery && { body: JSON.stringify(input) },
2174
+ redirect: "error"
2175
+ }, schema, {
2176
+ procedure,
2177
+ timeoutMs,
2178
+ publicationTimeoutMs
2179
+ });
2180
+ }
2181
+ };
2182
+ };
2183
+ const nodeManifest = (descriptor, captured) => {
2184
+ const participant = descriptor.participants[0];
2185
+ if (participant === void 0) throw captureError("configuration", "No capture participant was reserved.");
2186
+ return {
2187
+ format: "enhance-capture-run",
2188
+ version: 1,
2189
+ run: descriptor,
2190
+ ordering: "partial",
2191
+ participants: [{
2192
+ id: participant,
2193
+ status: "passed"
2194
+ }],
2195
+ attempts: [{
2196
+ participant,
2197
+ testId: "node",
2198
+ project: "node",
2199
+ retry: 0,
2200
+ status: "passed",
2201
+ captures: captured
2202
+ }]
2203
+ };
2204
+ };
2205
+ const createRun = (transport, input, directory) => {
2206
+ const descriptor = captureRunDescriptorSchema.parse(input);
2207
+ const artifacts = [];
2208
+ let isClosed = false;
2209
+ return {
2210
+ descriptor,
2211
+ directory,
2212
+ add: async (payload) => {
2213
+ if (isClosed) throw captureError("configuration", "This run no longer accepts captures.");
2214
+ const written = writeCapturePayload(directory, payload);
2215
+ artifacts.push(written);
2216
+ await written;
2217
+ },
2218
+ publish: async () => {
2219
+ isClosed = true;
2220
+ const captured = await Promise.all(artifacts);
2221
+ if (descriptor.participants.length !== 1) throw captureError("configuration", "Multi-participant runs must publish a complete merged manifest.");
2222
+ const manifest = nodeManifest(descriptor, captured);
2223
+ const selected = selectedCaptures(manifest);
2224
+ if (typeof selected === "string") throw captureError("artifact", selected);
2225
+ await mkdir(directory, { recursive: true });
2226
+ await writeCaptureJson(path.join(directory, "manifest.json"), manifest);
2227
+ return publishCaptureManifest(transport, manifest, directory);
2228
+ },
2229
+ cancel: async () => {
2230
+ isClosed = true;
2231
+ return (await transport.request("captureRun.cancel", { runId: descriptor.id }, getCaptureRunOutputSchema)).receipt;
2232
+ }
2233
+ };
2234
+ };
2235
+ const createEnhance = (options) => {
2236
+ const transport = captureTransport(options);
2237
+ const get = async (runId) => transport.request("captureRun.get", { runId }, getCaptureRunOutputSchema, true);
2238
+ return { captures: {
2239
+ begin: async (input) => {
2240
+ const request = beginCaptureRunInputSchema.parse({
2241
+ canvasId: input.canvas,
2242
+ source: input.source,
2243
+ runKey: input.runKey,
2244
+ participants: input.participants
2245
+ });
2246
+ const { run } = await transport.request("captureRun.begin", request, beginCaptureRunOutputSchema);
2247
+ const directory = input.directory ?? path.join(".enhance", "captures", run.id);
2248
+ await mkdir(directory, { recursive: true });
2249
+ await writeCaptureJson(path.join(directory, "run.json"), run);
2250
+ return createRun(transport, run, directory);
2251
+ },
2252
+ publishManifest: async (path$1) => publishCaptureManifest(transport, await readCaptureManifest(path$1), path.dirname(path$1)),
2253
+ get
2254
+ } };
2255
+ };
2256
+
2257
+ //#endregion
2258
+ //#region src/infrastructure/captures.program.ts
2259
+ const publicationError = (error, manifest) => {
2260
+ const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
2261
+ return new CliError(code === "authorization" ? "UNAUTHORIZED" : code === "conflict" ? "CONFLICT" : ["configuration", "artifact"].includes(String(code)) ? "BAD_REQUEST" : "INTERNAL", error instanceof Error ? error.message : "Capture publication was not confirmed.", `Retry enhance captures publish with the same manifest: ${manifest}`);
2262
+ };
2263
+ const registerCapturesProgram = (program, dependencies) => {
2264
+ program.command("captures").description("Publish SDK captures as editable canvas journeys.").command("publish <manifest>").description("Publish or resume a reserved capture manifest and print its durable receipt.").action(async (manifest) => {
2265
+ const token = await dependencies.credentials.read();
2266
+ if (token === null) throw new CliError("UNAUTHORIZED", "Capture publication requires an agent token.", "Run enhance auth login, then retry the same manifest.");
2267
+ const enhance = createEnhance({
2268
+ apiUrl: dependencies.apiUrl,
2269
+ token
2270
+ });
2271
+ try {
2272
+ dependencies.output.result(await enhance.captures.publishManifest(manifest));
2273
+ } catch (error) {
2274
+ throw publicationError(error, manifest);
2275
+ }
2276
+ });
2277
+ };
2278
+
1622
2279
  //#endregion
1623
2280
  //#region src/infrastructure/command-summaries.consts.ts
1624
2281
  const COMMAND_SUMMARIES = {
@@ -2027,13 +2684,14 @@ const DEFAULT_POSITION = 48;
2027
2684
  const DEFAULT_WIDTH = 1440;
2028
2685
  const DEFAULT_HEIGHT = 900;
2029
2686
  const registerPrototypeProgram = (program, invocation, catalog, output) => {
2030
- (program.commands.find((command) => command.name() === "prototype") ?? program.command("prototype").description("Publish static frontend prototypes.")).command("publish").description("Package and publish an unpacked static build directory. The CLI creates the upload artifact.").requiredOption("--canvas-id <uuid>", "Canvas that receives the prototype.").requiredOption("--directory <path>", "Unpacked static build directory; do not pass a ZIP file.").requiredOption("--title <title>", "Label above the prototype frame.").requiredOption("--base-version <number>", "Current canvas document version.", positiveInteger).option("--prototype-id <uuid>", "Existing prototype identity to publish a new deployment.").option("--client-token <uuid>", "Stable retry token for this exact build.").option("--node-id <id>", "Stable canvas node id for a new prototype.").option("--entry <path>", "HTML entry relative to the uploaded directory.", "index.html").option("--x <pixels>", "Canvas x coordinate.", finiteNumber, DEFAULT_POSITION).option("--y <pixels>", "Canvas y coordinate.", finiteNumber, DEFAULT_POSITION).option("--width <pixels>", "Prototype viewport width.", positiveNumber, DEFAULT_WIDTH).option("--height <pixels>", "Prototype viewport height.", positiveNumber, DEFAULT_HEIGHT).action(async (options) => {
2687
+ (program.commands.find((command) => command.name() === "prototype") ?? program.command("prototype").description("Publish static frontend prototypes.")).command("publish").description("Package and publish an unpacked static build directory. The CLI creates the upload artifact.").requiredOption("--canvas-id <uuid>", "Canvas that receives the prototype.").requiredOption("--directory <path>", "Unpacked static build directory; do not pass a ZIP file.").requiredOption("--title <title>", "Label above the prototype frame.").requiredOption("--base-version <number>", "Current canvas document version.", positiveInteger).option("--prototype-id <uuid>", "Existing prototype identity to publish a new deployment.").option("--client-token <uuid>", "Stable retry token for this exact build.").option("--node-id <id>", "Exact canvas node to create, update, or fork when it is a copy.").option("--entry <path>", "HTML entry relative to the uploaded directory.", "index.html").option("--x <pixels>", "Canvas x coordinate.", finiteNumber, DEFAULT_POSITION).option("--y <pixels>", "Canvas y coordinate.", finiteNumber, DEFAULT_POSITION).option("--width <pixels>", "Prototype viewport width.", positiveNumber, DEFAULT_WIDTH).option("--height <pixels>", "Prototype viewport height.", positiveNumber, DEFAULT_HEIGHT).action(async (options) => {
2031
2688
  const clientToken = options.clientToken ?? randomUUID();
2032
2689
  output.result(await invocation.invoke({
2033
2690
  capability: fromCapabilityReference(catalog(), "prototype.publish"),
2034
2691
  arguments: {
2035
2692
  canvasId: options.canvasId,
2036
2693
  prototypeId: options.prototypeId ?? null,
2694
+ targetMode: options.prototypeId !== void 0 && options.nodeId === void 0 ? "prototype" : "node",
2037
2695
  nodeId: options.nodeId ?? `proto_${clientToken.replaceAll("-", "")}`,
2038
2696
  title: options.title,
2039
2697
  directory: options.directory,
@@ -2163,6 +2821,7 @@ const registerUtilityPrograms = (program, input, catalog) => {
2163
2821
  });
2164
2822
  registerAuthProgram(program, createAuthUseCase(input.credentials, input.remote, createOauthLoopbackAdapter(input.remote)), input.output);
2165
2823
  registerCommentProgram(program, invocation, catalog, input.output);
2824
+ registerCapturesProgram(program, input);
2166
2825
  registerOperationProgram(program, {
2167
2826
  invocation,
2168
2827
  catalog,
@@ -2473,10 +3132,12 @@ const main = async () => {
2473
3132
  const output = createNdjsonLoggerAdapter(state, config.configDirectory, config.commandName);
2474
3133
  const credentials = createFileCredentialAdapter(config.configDirectory);
2475
3134
  const mutationKey = createMutationKeyAdapter();
3135
+ const remote = createHttpRemoteAdapter(config.apiUrl, credentials, mutationKey);
2476
3136
  const cli = createCliProgram({
2477
- version: "0.1.25",
3137
+ apiUrl: config.apiUrl,
3138
+ version: "0.1.33",
2478
3139
  credentials,
2479
- remote: createHttpRemoteAdapter(config.apiUrl, credentials, mutationKey),
3140
+ remote,
2480
3141
  mutationKey,
2481
3142
  output,
2482
3143
  state,