@enhance-eng/enhance 0.1.2 → 0.1.3

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
@@ -2,17 +2,21 @@
2
2
  import { Command } from "commander";
3
3
  import { FailedToExitError, createCli, parseRouter } from "trpc-cli";
4
4
  import { z } from "zod";
5
+ import { setTimeout } from "node:timers/promises";
5
6
  import process from "node:process";
6
7
  import { createInterface } from "node:readline";
7
- import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
8
+ import { chmodSync, createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
8
9
  import path from "node:path";
9
10
  import { TRPCClientError, createTRPCUntypedClient, httpLink } from "@trpc/client";
10
11
  import { createHash, randomUUID } from "node:crypto";
11
- import { chmod, mkdir, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
12
+ import { chmod, mkdir, mkdtemp, readFile, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
13
+ import { homedir, tmpdir } from "node:os";
14
+ import { Readable, Transform } from "node:stream";
15
+ import { pipeline } from "node:stream/promises";
16
+ import { ZipFile } from "yazl";
12
17
  import { proxify } from "trpc-cli/dist/proxify.js";
13
18
  import { TRPCError, initTRPC } from "@trpc/server";
14
19
  import { middlewareMarker } from "@trpc/server/unstable-core-do-not-import";
15
- import { homedir, tmpdir } from "node:os";
16
20
  //#region \0rolldown/runtime.js
17
21
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
18
22
  //#endregion
@@ -2752,6 +2756,141 @@ const requestPrototypeRuntimeTicketOutputSchema = z.object({
2752
2756
  bootUrl: z.url(),
2753
2757
  expiresAt: z.iso.datetime()
2754
2758
  });
2759
+ const PROTOTYPE_ARTIFACT_MANIFEST_PATH = "__enhance/manifest.json";
2760
+ const SHA256_HEX_LENGTH = 64;
2761
+ const CONTENT_TYPE_LENGTH = 200;
2762
+ const LAST_C0_CONTROL = 31;
2763
+ const DELETE_CONTROL = 127;
2764
+ const sha256Schema = z.string().length(SHA256_HEX_LENGTH).refine((value) => {
2765
+ for (const character of value) if (!/[\da-f]/u.test(character)) return false;
2766
+ return true;
2767
+ });
2768
+ const hasControlCharacter = (value) => {
2769
+ for (const character of value) {
2770
+ const point = character.codePointAt(0);
2771
+ if (point !== void 0 && (point === DELETE_CONTROL || point <= LAST_C0_CONTROL)) return true;
2772
+ }
2773
+ return false;
2774
+ };
2775
+ const foldPrototypeArtifactPath = (value) => value.normalize("NFKC").toUpperCase().toLowerCase();
2776
+ const prototypeArtifactPathSchema = z.string().min(1).refine((value) => value === value.normalize("NFC"), { message: "prototype paths must use NFC Unicode normalization" }).refine((value) => !value.startsWith("/") && !/^[A-Za-z]:\//u.test(value) && !value.endsWith("/") && !value.includes("\\") && !hasControlCharacter(value) && !value.startsWith("__enhance/") && value.split("/").every((part) => part !== "" && part !== "." && part !== ".."), { message: "prototype paths must be portable relative file paths" });
2777
+ const prototypeArtifactManifestFileSchema = z.object({
2778
+ path: prototypeArtifactPathSchema,
2779
+ contentType: z.string().trim().min(1).max(CONTENT_TYPE_LENGTH).refine((value) => !hasControlCharacter(value)),
2780
+ bytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
2781
+ sha256: sha256Schema
2782
+ });
2783
+ const prototypeArtifactManifestSchema = z.object({
2784
+ version: z.literal(1),
2785
+ entryPath: prototypeArtifactPathSchema,
2786
+ files: z.array(prototypeArtifactManifestFileSchema).min(1)
2787
+ });
2788
+ const prototypeArtifactLimitsSchema = z.object({
2789
+ artifactBytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
2790
+ expandedBytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
2791
+ fileBytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
2792
+ manifestBytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
2793
+ fileCount: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
2794
+ pathBytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
2795
+ });
2796
+ const getPrototypeArtifactCapabilitiesInputSchema = z.object({});
2797
+ const getPrototypeArtifactCapabilitiesOutputSchema = z.object({
2798
+ protocolVersion: z.literal(1),
2799
+ format: z.literal("zip"),
2800
+ limits: prototypeArtifactLimitsSchema
2801
+ });
2802
+ const prototypeArtifactIdentitySchema = z.object({
2803
+ protocolVersion: z.literal(1),
2804
+ format: z.literal("zip"),
2805
+ bytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
2806
+ sha256: sha256Schema,
2807
+ fileCount: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
2808
+ expandedBytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
2809
+ });
2810
+ const createPrototypeArtifactInputSchema = z.object({
2811
+ canvasId: z.uuid(),
2812
+ prototypeId: z.uuid().optional(),
2813
+ clientToken: z.uuid(),
2814
+ nodeId: z.string().min(1),
2815
+ title: z.string().trim().min(1).max(200),
2816
+ entryPath: prototypeArtifactPathSchema,
2817
+ artifact: prototypeArtifactIdentitySchema,
2818
+ box: canvasSceneBoxSchema.extend({
2819
+ width: z.number().positive(),
2820
+ height: z.number().positive()
2821
+ })
2822
+ });
2823
+ const prototypeArtifactDeploymentStateSchema = z.enum([
2824
+ "uploading",
2825
+ "queued",
2826
+ "ingesting",
2827
+ "ready",
2828
+ "failed",
2829
+ "abandoned"
2830
+ ]);
2831
+ const createPrototypeArtifactOutputBaseSchema = z.object({
2832
+ prototypeId: z.uuid(),
2833
+ deploymentId: z.uuid(),
2834
+ nodeId: z.string().min(1),
2835
+ alreadyExists: z.boolean(),
2836
+ artifact: prototypeArtifactIdentitySchema
2837
+ });
2838
+ const createPrototypeArtifactOutputSchema = z.discriminatedUnion("state", [createPrototypeArtifactOutputBaseSchema.extend({
2839
+ state: z.literal("uploading"),
2840
+ upload: signedUploadSchema
2841
+ }), createPrototypeArtifactOutputBaseSchema.extend({ state: z.enum([
2842
+ "queued",
2843
+ "ingesting",
2844
+ "ready",
2845
+ "failed",
2846
+ "abandoned"
2847
+ ]) })]);
2848
+ const submitPrototypeArtifactInputSchema = z.object({
2849
+ canvasId: z.uuid(),
2850
+ deploymentId: z.uuid()
2851
+ });
2852
+ const submitPrototypeArtifactOutputSchema = z.object({
2853
+ deploymentId: z.uuid(),
2854
+ state: prototypeArtifactDeploymentStateSchema
2855
+ });
2856
+ const getPrototypePublishStatusInputSchema = z.object(submitPrototypeArtifactInputSchema.shape);
2857
+ const getPrototypePublishStatusBaseSchema = z.object({
2858
+ prototypeId: z.uuid(),
2859
+ deploymentId: z.uuid(),
2860
+ nodeId: z.string().min(1),
2861
+ fileCount: z.number().int().nonnegative(),
2862
+ totalBytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
2863
+ processedFiles: z.number().int().nonnegative()
2864
+ });
2865
+ const getPrototypePublishStatusOutputSchema = z.discriminatedUnion("state", [getPrototypePublishStatusBaseSchema.extend({
2866
+ state: z.literal("failed"),
2867
+ failure: z.object({
2868
+ code: z.string().min(1),
2869
+ message: z.string().min(1),
2870
+ path: prototypeArtifactPathSchema.optional()
2871
+ })
2872
+ }), getPrototypePublishStatusBaseSchema.extend({ state: z.enum([
2873
+ "uploading",
2874
+ "queued",
2875
+ "ingesting",
2876
+ "ready",
2877
+ "abandoned"
2878
+ ]) })]);
2879
+ const attachPrototypeArtifactInputSchema = z.object({
2880
+ canvasId: z.uuid(),
2881
+ deploymentId: z.uuid(),
2882
+ baseVersion: z.number().int().positive()
2883
+ });
2884
+ const attachPrototypeArtifactOutputSchema = z.object({
2885
+ canvasId: z.uuid(),
2886
+ prototypeId: z.uuid(),
2887
+ deploymentId: z.uuid(),
2888
+ nodeId: z.string().min(1),
2889
+ version: z.number().int().positive(),
2890
+ state: z.literal("ready"),
2891
+ origin: z.url(),
2892
+ openUrl: z.string().startsWith("/c/")
2893
+ });
2755
2894
  z.object({
2756
2895
  protocol: z.literal(1),
2757
2896
  type: z.literal("enhance.prototype.capture"),
@@ -2765,6 +2904,17 @@ z.object({
2765
2904
  protocol: z.literal(1),
2766
2905
  type: z.literal("enhance.prototype.escape")
2767
2906
  });
2907
+ z.object({
2908
+ protocol: z.literal(1),
2909
+ type: z.literal("enhance.prototype.navigate"),
2910
+ direction: z.enum(["back", "forward"])
2911
+ });
2912
+ z.object({
2913
+ protocol: z.literal(1),
2914
+ type: z.literal("enhance.prototype.navigation"),
2915
+ canGoBack: z.boolean(),
2916
+ canGoForward: z.boolean()
2917
+ });
2768
2918
  const capturedPrototypeScreenSchema = z.object({
2769
2919
  artifact: z.string().min(1),
2770
2920
  viewport: z.object({
@@ -3638,83 +3788,101 @@ var PartialBatchError = class extends CliError {
3638
3788
  };
3639
3789
  //#endregion
3640
3790
  //#region src/application/publish-prototype.composite.ts
3641
- const UPLOAD_CONCURRENCY = 8;
3791
+ const PUBLISH_WAIT_MS = 3e5;
3792
+ const INITIAL_POLL_MS = 50;
3793
+ const MAX_POLL_MS = 1e3;
3642
3794
  const PUBLISH_PROTOTYPE_PROCEDURES = [
3643
- "prototype.create",
3644
- "prototype.reserveUploads",
3645
- "prototype.complete"
3795
+ "prototype.getArtifactCapabilities",
3796
+ "prototype.createArtifact",
3797
+ "prototype.submitArtifact",
3798
+ "prototype.getPublishStatus",
3799
+ "prototype.attach"
3646
3800
  ];
3647
3801
  const invalidResponse$2 = (operation) => new CliError("INTERNAL", `The API returned an invalid prototype ${operation} response.`, "Run `enhance doctor`; report the API and CLI versions if they differ.");
3648
- const filesFor = (sources) => sources.map((file) => ({
3649
- path: file.path,
3650
- contentType: file.contentType,
3651
- bytes: file.body.byteLength
3652
- }));
3653
- const uploadPage = async (remote, sources, uploads) => {
3654
- for (let offset = 0; offset < uploads.length; offset += UPLOAD_CONCURRENCY) await Promise.all(uploads.slice(offset, offset + UPLOAD_CONCURRENCY).map(async (reserved) => {
3655
- const source = sources.get(reserved.path);
3656
- if (source === void 0) throw invalidResponse$2("upload reservation");
3657
- await remote.upload({
3658
- url: reserved.upload.url,
3659
- headers: reserved.upload.headers,
3660
- body: source.body
3661
- });
3662
- }));
3663
- };
3664
- const readFiles = async (files, input) => {
3665
- const sources = await files.read(input.directory);
3666
- return {
3667
- sources,
3668
- uploadedFiles: filesFor(sources)
3669
- };
3670
- };
3671
- const uploadDeployment = async (remote, input, deploymentId, sources) => {
3672
- const byPath = new Map(sources.map((source) => [source.path, source]));
3673
- let cursor = 0;
3674
- while (cursor !== null) {
3675
- const reserved = reservePrototypeUploadsOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[1], {
3676
- canvasId: input.canvasId,
3677
- deploymentId,
3678
- cursor
3679
- }));
3680
- if (!reserved.success) throw invalidResponse$2("upload reservation");
3681
- await uploadPage(remote, byPath, reserved.data.uploads);
3682
- cursor = reserved.data.nextCursor ?? null;
3802
+ const waitUntilSettled = async (remote, input) => {
3803
+ const deadline = Date.now() + PUBLISH_WAIT_MS;
3804
+ let pollMs = INITIAL_POLL_MS;
3805
+ while (Date.now() < deadline) {
3806
+ const parsed = getPrototypePublishStatusOutputSchema.safeParse(await remote.query(PUBLISH_PROTOTYPE_PROCEDURES[3], input));
3807
+ if (!parsed.success) throw invalidResponse$2("status");
3808
+ if (parsed.data.state === "ready" || parsed.data.state === "failed") return parsed.data;
3809
+ if (parsed.data.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${input.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
3810
+ await setTimeout(pollMs);
3811
+ pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
3683
3812
  }
3813
+ throw new Error("prototype ingestion is still running");
3684
3814
  };
3685
- const executePublish = async (remote, files, input) => {
3686
- const { sources, uploadedFiles } = await readFiles(files, input);
3687
- const created = createPrototypeDeploymentOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[0], {
3815
+ const reserveAndUpload = async (remote, input, artifact, reserved) => {
3816
+ const created = createPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[1], {
3688
3817
  canvasId: input.canvasId,
3689
3818
  ...input.prototypeId !== null && { prototypeId: input.prototypeId },
3690
3819
  clientToken: input.clientToken,
3691
3820
  nodeId: input.nodeId,
3692
3821
  title: input.title,
3693
- entryPath: input.entryPath,
3694
- files: uploadedFiles,
3822
+ entryPath: artifact.manifest.entryPath,
3823
+ artifact: artifact.identity,
3695
3824
  box: input.box
3696
3825
  }));
3697
- if (!created.success) throw invalidResponse$2("creation");
3826
+ if (!created.success) throw invalidResponse$2("artifact creation");
3827
+ reserved(created.data.deploymentId);
3828
+ if (created.data.state === "uploading") await remote.upload({
3829
+ url: created.data.upload.url,
3830
+ headers: created.data.upload.headers,
3831
+ body: artifact.open()
3832
+ });
3833
+ if (created.data.state === "uploading" || created.data.state === "queued") {
3834
+ if (!submitPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[2], {
3835
+ canvasId: input.canvasId,
3836
+ deploymentId: created.data.deploymentId
3837
+ })).success) throw invalidResponse$2("artifact submission");
3838
+ }
3839
+ return created.data;
3840
+ };
3841
+ const requireSuccessfulIngestion = (status) => {
3842
+ if (status.state !== "failed") return;
3843
+ const { failure } = status;
3844
+ throw new CliError("BAD_REQUEST", failure.message, "Fix the build and publish it with a new client token.", failure.path === void 0 ? void 0 : { path: failure.path });
3845
+ };
3846
+ const executePublish = async (remote, artifacts, input) => {
3847
+ const capabilities = getPrototypeArtifactCapabilitiesOutputSchema.safeParse(await remote.query(PUBLISH_PROTOTYPE_PROCEDURES[0], {}));
3848
+ if (!capabilities.success) throw invalidResponse$2("capabilities");
3849
+ const artifact = await artifacts.package({
3850
+ directory: input.directory,
3851
+ entryPath: input.entryPath,
3852
+ limits: capabilities.data.limits
3853
+ });
3854
+ const progress = { deploymentId: null };
3698
3855
  try {
3699
- if (created.data.state !== "ready") await uploadDeployment(remote, input, created.data.deploymentId, sources);
3700
- const completed = completePrototypeDeploymentOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[2], {
3856
+ const created = await reserveAndUpload(remote, input, artifact, (reservedId) => {
3857
+ progress.deploymentId = reservedId;
3858
+ });
3859
+ const status = await waitUntilSettled(remote, {
3860
+ canvasId: input.canvasId,
3861
+ deploymentId: created.deploymentId
3862
+ });
3863
+ requireSuccessfulIngestion(status);
3864
+ const attached = attachPrototypeArtifactOutputSchema.safeParse(await remote.mutate(PUBLISH_PROTOTYPE_PROCEDURES[4], {
3701
3865
  canvasId: input.canvasId,
3702
- deploymentId: created.data.deploymentId,
3866
+ deploymentId: created.deploymentId,
3703
3867
  baseVersion: input.baseVersion
3704
3868
  }));
3705
- if (!completed.success) throw invalidResponse$2("completion");
3869
+ if (!attached.success) throw invalidResponse$2("attachment");
3706
3870
  return {
3707
- ...completed.data,
3708
- fileCount: created.data.fileCount,
3709
- totalBytes: created.data.totalBytes,
3710
- alreadyExists: created.data.alreadyExists,
3711
- next: [completed.data.openUrl, `enhance canvas render --canvas ${input.canvasId} --node-id ${completed.data.nodeId} --expected-version ${String(completed.data.version)}`]
3871
+ ...attached.data,
3872
+ fileCount: status.fileCount,
3873
+ totalBytes: status.totalBytes,
3874
+ alreadyExists: created.alreadyExists,
3875
+ next: [attached.data.openUrl, `enhance canvas render --canvas ${input.canvasId} --node-id ${attached.data.nodeId} --expected-version ${String(attached.data.version)}`]
3712
3876
  };
3713
- } catch {
3714
- throw new PartialBatchError(`Prototype deployment ${created.data.deploymentId} was created, but publishing did not complete.`, `Retry 'enhance prototype publish' with the same --client-token ${input.clientToken}.`);
3877
+ } catch (error) {
3878
+ if (error instanceof CliError && (error.code === "BAD_REQUEST" || error.code === "NOT_FOUND")) throw error;
3879
+ if (progress.deploymentId === null) throw error;
3880
+ throw new PartialBatchError(`Prototype deployment ${progress.deploymentId} was created, but publishing did not complete.`, `Retry 'enhance prototype publish' with the same --client-token ${input.clientToken}.`);
3881
+ } finally {
3882
+ await artifact.dispose();
3715
3883
  }
3716
3884
  };
3717
- const createPublishPrototypeComposite = (remote, files) => ({ execute: async (input) => executePublish(remote, files, input) });
3885
+ const createPublishPrototypeComposite = (remote, artifacts) => ({ execute: async (input) => executePublish(remote, artifacts, input) });
3718
3886
  //#endregion
3719
3887
  //#region src/application/recording-fixture.composite.ts
3720
3888
  const CHUNK_LIMIT = 8 * 1048576;
@@ -5991,9 +6159,14 @@ const CLI_EXCLUDED_PROCEDURES = /* @__PURE__ */ new Set([
5991
6159
  "person.signOut",
5992
6160
  "person.signUp",
5993
6161
  "prototype.complete",
6162
+ "prototype.attach",
5994
6163
  "prototype.create",
6164
+ "prototype.createArtifact",
6165
+ "prototype.getArtifactCapabilities",
6166
+ "prototype.getPublishStatus",
5995
6167
  "prototype.requestRuntimeTicket",
5996
6168
  "prototype.reserveUploads",
6169
+ "prototype.submitArtifact",
5997
6170
  "telemetry.lifecycle",
5998
6171
  "telemetry.performance",
5999
6172
  "transcript.get"
@@ -6237,7 +6410,7 @@ const DEFAULT_POSITION = 48;
6237
6410
  const DEFAULT_WIDTH = 1440;
6238
6411
  const DEFAULT_HEIGHT = 900;
6239
6412
  const registerPrototypeProgram = (program, publish, mutationKey, output) => {
6240
- (program.commands.find((command) => command.name() === "prototype") ?? program.command("prototype").description("Publish static frontend prototypes.")).command("publish").description("Upload a built frontend and attach its interactive frame to a canvas.").requiredOption("--canvas-id <uuid>", "Canvas that receives the prototype.").requiredOption("--directory <path>", "Directory whose files should be uploaded.").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) => {
6413
+ (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) => {
6241
6414
  const clientToken = options.clientToken ?? randomUUID();
6242
6415
  mutationKey.select(clientToken, true);
6243
6416
  output.result(await publish.execute({
@@ -6259,7 +6432,95 @@ const registerPrototypeProgram = (program, publish, mutationKey, output) => {
6259
6432
  });
6260
6433
  };
6261
6434
  //#endregion
6262
- //#region src/infrastructure/prototype-files.adapter.ts
6435
+ //#region src/infrastructure/prototype-zip.adapter.ts
6436
+ const NORMALIZED_MTIME = /* @__PURE__ */ new Date("1980-01-01T00:00:00.000Z");
6437
+ const REGULAR_FILE_MODE = 33188;
6438
+ const ZIP64_ENTRY_FLOOR = 65535;
6439
+ const badRequest$1 = (message, remediation) => new CliError("BAD_REQUEST", message, remediation);
6440
+ const hashingTransform = (source, completed) => {
6441
+ const hash = createHash("sha256");
6442
+ let bytes = 0;
6443
+ return new Transform({
6444
+ transform: (chunk, _encoding, callback) => {
6445
+ bytes += chunk.byteLength;
6446
+ hash.update(chunk);
6447
+ callback(null, chunk);
6448
+ },
6449
+ flush: (callback) => {
6450
+ if (bytes !== source.bytes) {
6451
+ callback(/* @__PURE__ */ new Error(`prototype file ${source.path} changed while it was packaged`));
6452
+ return;
6453
+ }
6454
+ completed({
6455
+ path: source.path,
6456
+ contentType: source.contentType,
6457
+ bytes,
6458
+ sha256: hash.digest("hex")
6459
+ });
6460
+ callback();
6461
+ }
6462
+ });
6463
+ };
6464
+ const addManifest = (input) => {
6465
+ const manifest = prototypeArtifactManifestSchema.parse({
6466
+ version: 1,
6467
+ entryPath: input.entryPath,
6468
+ files: input.files.map((file) => input.completed.get(file.path))
6469
+ });
6470
+ const body = Buffer.from(JSON.stringify(manifest), "utf8");
6471
+ if (body.byteLength > input.limits.manifestBytes) throw badRequest$1("The prototype manifest is too large.", `Shorten paths or reduce metadata below ${String(input.limits.manifestBytes)} bytes.`);
6472
+ input.zip.addBuffer(body, PROTOTYPE_ARTIFACT_MANIFEST_PATH, {
6473
+ mtime: NORMALIZED_MTIME,
6474
+ mode: REGULAR_FILE_MODE,
6475
+ compress: true,
6476
+ forceDosTimestamp: true
6477
+ });
6478
+ input.zip.end({
6479
+ forceZip64Format: input.files.length >= ZIP64_ENTRY_FLOOR,
6480
+ comment: ""
6481
+ });
6482
+ return manifest;
6483
+ };
6484
+ const createPrototypeZipAdapter = async (input) => {
6485
+ const zip = new ZipFile();
6486
+ const hash = createHash("sha256");
6487
+ const hashing = new Transform({ transform: (chunk, _encoding, callback) => {
6488
+ hash.update(chunk);
6489
+ callback(null, chunk);
6490
+ } });
6491
+ const completed = /* @__PURE__ */ new Map();
6492
+ const packaged = { manifest: null };
6493
+ const output = pipeline(zip.outputStream, hashing, createWriteStream(input.artifactPath));
6494
+ zip.on("error", (error) => hashing.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("prototype ZIP failed")));
6495
+ const complete = (file) => {
6496
+ completed.set(file.path, file);
6497
+ if (packaged.manifest === null && completed.size === input.files.length) packaged.manifest = addManifest({
6498
+ zip,
6499
+ completed,
6500
+ ...input
6501
+ });
6502
+ };
6503
+ for (const source of input.files) zip.addReadStreamLazy(source.path, {
6504
+ size: source.bytes,
6505
+ mtime: NORMALIZED_MTIME,
6506
+ mode: REGULAR_FILE_MODE,
6507
+ compress: true,
6508
+ forceDosTimestamp: true
6509
+ }, (callback) => {
6510
+ callback(null, createReadStream(source.absolutePath).pipe(hashingTransform(source, complete)));
6511
+ });
6512
+ await output;
6513
+ if (packaged.manifest === null) throw new Error("prototype ZIP completed without a manifest");
6514
+ const artifactStats = await stat(input.artifactPath);
6515
+ if (artifactStats.size > input.limits.artifactBytes) throw badRequest$1("The packaged prototype artifact is too large.", `This environment accepts ${String(input.limits.artifactBytes)} compressed bytes.`);
6516
+ return {
6517
+ manifest: packaged.manifest,
6518
+ bytes: artifactStats.size,
6519
+ sha256: hash.digest("hex")
6520
+ };
6521
+ };
6522
+ //#endregion
6523
+ //#region src/infrastructure/prototype-artifact.adapter.ts
6263
6524
  const CONTENT_TYPES = {
6264
6525
  ".avif": "image/avif",
6265
6526
  ".css": "text/css; charset=utf-8",
@@ -6295,37 +6556,93 @@ const statsFor = async (filePath) => {
6295
6556
  return null;
6296
6557
  }
6297
6558
  };
6298
- const walk = async (root, directory, ancestors) => {
6559
+ const byteLength = (value) => Buffer.byteLength(value, "utf8");
6560
+ const badRequest = (message, remediation) => new CliError("BAD_REQUEST", message, remediation);
6561
+ const validatePath = (relativePath, limits) => {
6562
+ if (!prototypeArtifactPathSchema.safeParse(relativePath).success) throw badRequest(`Cannot package the prototype path ${relativePath}.`, "Use portable relative NFC paths outside the reserved __enhance directory.");
6563
+ if (byteLength(relativePath) > limits.pathBytes) throw badRequest(`The prototype path ${relativePath} is too long.`, `Shorten it to at most ${String(limits.pathBytes)} UTF-8 bytes.`);
6564
+ };
6565
+ const walk = async (root, directory, ancestors, limits) => {
6299
6566
  const resolvedDirectory = await realpath(directory);
6300
- if (ancestors.has(resolvedDirectory)) throw new CliError("BAD_REQUEST", `Cannot upload the circular directory link at ${directory}.`, "Pass a directory tree that can be read once from top to bottom.");
6567
+ if (ancestors.has(resolvedDirectory)) throw badRequest(`Cannot package the circular directory link at ${directory}.`, "Pass a directory tree that can be read once from top to bottom.");
6301
6568
  const nextAncestors = new Set(ancestors).add(resolvedDirectory);
6302
- const readEntries = await readdir(directory, { withFileTypes: true });
6569
+ const { readdir } = await import("node:fs/promises");
6570
+ const entries = await readdir(directory, { withFileTypes: true });
6303
6571
  const files = [];
6304
- for (const entry of readEntries) {
6305
- const absolute = path.join(directory, entry.name);
6306
- const stats = await statsFor(absolute);
6572
+ const orderedEntries = entries.toSorted((left, right) => left.name.localeCompare(right.name));
6573
+ for (const entry of orderedEntries) {
6574
+ const absolutePath = path.join(directory, entry.name);
6575
+ const stats = await statsFor(absolutePath);
6307
6576
  if (stats?.isDirectory() === true) {
6308
- files.push(...await walk(root, absolute, nextAncestors));
6577
+ files.push(...await walk(root, absolutePath, nextAncestors, limits));
6309
6578
  continue;
6310
6579
  }
6311
- if (stats?.isFile() !== true) throw new CliError("BAD_REQUEST", `Cannot read ${absolute} as an uploadable file.`, "Pass a directory containing regular files.");
6312
- const relativePath = path.relative(root, absolute).split(path.sep).join("/");
6313
- const body = await readFile(absolute);
6580
+ if (stats?.isFile() !== true) throw badRequest(`Cannot read ${absolutePath} as a prototype file.`, "Pass a directory containing only regular files and directory links.");
6581
+ const relativePath = path.relative(root, absolutePath).split(path.sep).join("/").normalize("NFC");
6582
+ validatePath(relativePath, limits);
6314
6583
  files.push({
6584
+ absolutePath,
6315
6585
  path: relativePath,
6316
- contentType: contentTypeOf(absolute),
6317
- body
6586
+ bytes: Number(stats.size),
6587
+ contentType: contentTypeOf(absolutePath)
6318
6588
  });
6319
6589
  }
6320
6590
  return files;
6321
6591
  };
6322
- const createPrototypeFilesAdapter = () => ({ read: async (directory) => {
6323
- const root = path.resolve(directory);
6324
- const stats = await statsFor(root);
6325
- if (stats === null) throw new CliError("NOT_FOUND", `The prototype directory ${root} does not exist.`, "Build the app or pass the correct build directory.");
6326
- if (!stats.isDirectory()) throw new CliError("BAD_REQUEST", `${root} is not a directory.`, "Pass the directory produced by the frontend build.");
6327
- return walk(root, root, /* @__PURE__ */ new Set());
6328
- } });
6592
+ const validateSources = (files, entryPath, limits) => {
6593
+ if (files.length === 0) throw badRequest("The prototype build is empty.", "Build the app before publishing it.");
6594
+ if (files.length > limits.fileCount) throw badRequest(`The prototype has ${String(files.length)} files.`, `This environment currently accepts ${String(limits.fileCount)} files per deployment.`);
6595
+ const folded = /* @__PURE__ */ new Set();
6596
+ let totalBytes = 0;
6597
+ for (const file of files) {
6598
+ const key = foldPrototypeArtifactPath(file.path);
6599
+ if (folded.has(key)) throw badRequest(`The prototype path ${file.path} collides by case or Unicode normalization.`, "Rename one of the colliding files so the build is portable.");
6600
+ folded.add(key);
6601
+ if (file.bytes > limits.fileBytes) throw badRequest(`The prototype file ${file.path} is too large.`, `This environment accepts ${String(limits.fileBytes)} bytes in one runtime file.`);
6602
+ totalBytes += file.bytes;
6603
+ if (totalBytes > limits.expandedBytes) throw badRequest("The prototype build is too large.", `This environment accepts ${String(limits.expandedBytes)} expanded bytes.`);
6604
+ }
6605
+ const entry = files.find((file) => file.path === entryPath);
6606
+ if (entry === void 0) throw badRequest(`The prototype entry ${entryPath} is missing.`, "Pass --entry with an HTML file inside the build directory.");
6607
+ if (!entry.contentType.startsWith("text/html")) throw badRequest(`The prototype entry ${entryPath} is not HTML.`, "Pass an HTML entry file such as index.html.");
6608
+ };
6609
+ const packageArtifact = async (input) => {
6610
+ const root = path.resolve(input.directory);
6611
+ const rootStats = await statsFor(root);
6612
+ if (rootStats === null) throw new CliError("NOT_FOUND", `The prototype directory ${root} does not exist.`, "Build the app or pass the correct unpacked build directory.");
6613
+ if (!rootStats.isDirectory()) throw badRequest(`${root} is not an unpacked build directory.`, "Pass the build directory; the CLI creates the ZIP artifact automatically.");
6614
+ const entryPath = input.entryPath.split(path.sep).join("/").normalize("NFC");
6615
+ validatePath(entryPath, input.limits);
6616
+ const files = await walk(root, root, /* @__PURE__ */ new Set(), input.limits);
6617
+ validateSources(files, entryPath, input.limits);
6618
+ const tempDirectory = await mkdtemp(path.join(tmpdir(), "enhance-prototype-artifact-"));
6619
+ const artifactPath = path.join(tempDirectory, "artifact.zip");
6620
+ try {
6621
+ const packaged = await createPrototypeZipAdapter({
6622
+ artifactPath,
6623
+ files,
6624
+ entryPath,
6625
+ limits: input.limits
6626
+ });
6627
+ return {
6628
+ identity: {
6629
+ protocolVersion: 1,
6630
+ format: "zip",
6631
+ bytes: packaged.bytes,
6632
+ sha256: packaged.sha256,
6633
+ fileCount: packaged.manifest.files.length,
6634
+ expandedBytes: packaged.manifest.files.reduce((total, file) => total + file.bytes, 0)
6635
+ },
6636
+ manifest: packaged.manifest,
6637
+ open: () => createReadStream(artifactPath),
6638
+ dispose: async () => rm(tempDirectory, { recursive: true })
6639
+ };
6640
+ } catch (error) {
6641
+ await rm(tempDirectory, { recursive: true });
6642
+ throw error;
6643
+ }
6644
+ };
6645
+ const createPrototypeArtifactAdapter = () => ({ package: packageArtifact });
6329
6646
  //#endregion
6330
6647
  //#region src/application/snapshot-recording.composite.ts
6331
6648
  const POLL_MS = 250;
@@ -8887,7 +9204,101 @@ const runtimeTicketProcedure = (handlers) => canvasReaderProcedure.input(request
8887
9204
  expiresAt: issued.ticket.expiresAt.toISOString()
8888
9205
  };
8889
9206
  });
9207
+ const artifactCapabilitiesProcedure = (handlers) => agentProcedure.input(getPrototypeArtifactCapabilitiesInputSchema).output(getPrototypeArtifactCapabilitiesOutputSchema).query(() => ({
9208
+ protocolVersion: 1,
9209
+ format: "zip",
9210
+ limits: handlers.artifactPublishing.capabilities()
9211
+ }));
9212
+ const createArtifactProcedure = (handlers) => agentCanvasEditorProcedure.input(createPrototypeArtifactInputSchema).output(createPrototypeArtifactOutputSchema).mutation(async ({ input, ctx }) => {
9213
+ const created = orThrow(await handlers.artifactPublishing.create({
9214
+ ...input,
9215
+ prototypeId: input.prototypeId ?? null,
9216
+ personId: agentPersonId(ctx.viewer)
9217
+ }));
9218
+ const response = {
9219
+ prototypeId: created.prototype.id,
9220
+ deploymentId: created.deployment.id,
9221
+ nodeId: created.prototype.nodeId,
9222
+ alreadyExists: created.alreadyExists,
9223
+ artifact: created.deployment.artifact
9224
+ };
9225
+ if (created.deployment.state !== "uploading") return {
9226
+ ...response,
9227
+ state: created.deployment.state
9228
+ };
9229
+ if (created.upload === null) throw new TypeError("an uploading artifact has no upload");
9230
+ return {
9231
+ ...response,
9232
+ state: created.deployment.state,
9233
+ upload: {
9234
+ ...created.upload,
9235
+ expiresAt: created.upload.expiresAt.toISOString()
9236
+ }
9237
+ };
9238
+ });
9239
+ const submitArtifactProcedure = (handlers) => agentCanvasEditorProcedure.input(submitPrototypeArtifactInputSchema).output(submitPrototypeArtifactOutputSchema).mutation(async ({ input, ctx }) => {
9240
+ const deployment = orThrow(await handlers.artifactPublishing.submit({
9241
+ ...input,
9242
+ personId: agentPersonId(ctx.viewer)
9243
+ }));
9244
+ return {
9245
+ deploymentId: deployment.id,
9246
+ state: deployment.state
9247
+ };
9248
+ });
9249
+ const artifactStatusProcedure = (handlers) => agentCanvasEditorProcedure.input(getPrototypePublishStatusInputSchema).output(getPrototypePublishStatusOutputSchema).query(async ({ input, ctx }) => {
9250
+ const status = orThrow(await handlers.artifactPublishing.status({
9251
+ ...input,
9252
+ personId: agentPersonId(ctx.viewer)
9253
+ }));
9254
+ const response = {
9255
+ prototypeId: status.prototype.id,
9256
+ deploymentId: status.deployment.id,
9257
+ nodeId: status.prototype.nodeId,
9258
+ fileCount: status.deployment.artifact.fileCount,
9259
+ totalBytes: status.deployment.artifact.expandedBytes,
9260
+ processedFiles: status.deployment.processedFiles
9261
+ };
9262
+ if (status.deployment.state !== "failed") return {
9263
+ ...response,
9264
+ state: status.deployment.state
9265
+ };
9266
+ const failure = status.deployment.failure;
9267
+ if (failure === null) throw new TypeError("a failed artifact has no failure");
9268
+ return {
9269
+ ...response,
9270
+ state: status.deployment.state,
9271
+ failure: {
9272
+ code: failure.code,
9273
+ message: failure.message,
9274
+ ...failure.path !== null && { path: failure.path }
9275
+ }
9276
+ };
9277
+ });
9278
+ const attachArtifactProcedure = (handlers) => agentCanvasEditorProcedure.input(attachPrototypeArtifactInputSchema).output(attachPrototypeArtifactOutputSchema).mutation(async ({ input, ctx }) => {
9279
+ const publisher = agentPublisher(ctx.viewer);
9280
+ const completed = orThrow(await handlers.upload.complete({
9281
+ ...input,
9282
+ ...publisher
9283
+ }));
9284
+ const origin = handlers.runtimeConfig.originFor(completed.deployment.id);
9285
+ return {
9286
+ canvasId: input.canvasId,
9287
+ prototypeId: completed.prototype.id,
9288
+ deploymentId: completed.deployment.id,
9289
+ nodeId: completed.prototype.nodeId,
9290
+ version: completed.version,
9291
+ state: "ready",
9292
+ origin,
9293
+ openUrl: `/c/${input.canvasId}?prototype=${completed.prototype.id}`
9294
+ };
9295
+ });
8890
9296
  const createPrototypeRouter = (handlers) => trpcRouter({
9297
+ getArtifactCapabilities: artifactCapabilitiesProcedure(handlers),
9298
+ createArtifact: createArtifactProcedure(handlers),
9299
+ submitArtifact: submitArtifactProcedure(handlers),
9300
+ getPublishStatus: artifactStatusProcedure(handlers),
9301
+ attach: attachArtifactProcedure(handlers),
8891
9302
  create: createProcedure(handlers),
8892
9303
  reserveUploads: reserveProcedure(handlers),
8893
9304
  complete: completeProcedure(handlers),
@@ -9408,6 +9819,12 @@ const handlers = {
9408
9819
  },
9409
9820
  prototype: {
9410
9821
  publishing: { create: unavailable.execute },
9822
+ artifactPublishing: {
9823
+ capabilities: unavailable.execute,
9824
+ create: unavailable.execute,
9825
+ submit: unavailable.execute,
9826
+ status: unavailable.execute
9827
+ },
9411
9828
  upload: {
9412
9829
  reserve: unavailable.execute,
9413
9830
  complete: unavailable.execute
@@ -9553,7 +9970,7 @@ const registerUtilityPrograms = (program, input) => {
9553
9970
  mutationKey: input.mutationKey,
9554
9971
  output: input.output
9555
9972
  });
9556
- registerPrototypeProgram(program, createPublishPrototypeComposite(input.remote, createPrototypeFilesAdapter()), input.mutationKey, input.output);
9973
+ registerPrototypeProgram(program, createPublishPrototypeComposite(input.remote, createPrototypeArtifactAdapter()), input.mutationKey, input.output);
9557
9974
  registerTranscriptProgram(program, {
9558
9975
  remote: input.remote,
9559
9976
  output: input.output
@@ -9679,11 +10096,15 @@ const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey) => {
9679
10096
  mutate: async (procedure, input) => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input)).mutation(procedure, input),
9680
10097
  download,
9681
10098
  upload: async (input) => {
9682
- const response = await fetch(input.url, {
10099
+ const isStreaming = !(input.body instanceof Uint8Array);
10100
+ const body = isStreaming ? Readable.toWeb(input.body) : input.body;
10101
+ const request = {
9683
10102
  method: "PUT",
9684
10103
  headers: input.headers,
9685
- body: input.body
9686
- });
10104
+ body,
10105
+ ...isStreaming && { duplex: "half" }
10106
+ };
10107
+ const response = await fetch(input.url, request);
9687
10108
  if (!response.ok) throw new CliError("INTERNAL", `Signed upload answered HTTP ${String(response.status)}.`, "Retry the fixture command with the same source file.");
9688
10109
  const etag = response.headers.get("etag");
9689
10110
  if (etag === null || etag === "") throw new CliError("INTERNAL", "Signed upload returned no ETag.", "Report the storage response and stop.");
@@ -9926,7 +10347,7 @@ const main = async () => {
9926
10347
  const credentials = createFileCredentialAdapter(CLI_CONFIG.configDirectory);
9927
10348
  const mutationKey = createMutationKeyAdapter();
9928
10349
  const cli = createCliProgram({
9929
- version: "0.1.2",
10350
+ version: "0.1.3",
9930
10351
  credentials,
9931
10352
  remote: createHttpRemoteAdapter(CLI_CONFIG.apiUrl, credentials, mutationKey),
9932
10353
  mutationKey,
@@ -9945,5 +10366,3 @@ const main = async () => {
9945
10366
  main();
9946
10367
  //#endregion
9947
10368
  export {};
9948
-
9949
- //# sourceMappingURL=main.mjs.map