@enhance-eng/sdk 0.1.0-dev.sha-3f7dd0acb078

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,226 @@
1
+ import { _ as reserveCaptureBlobsOutputSchema, d as beginCaptureRunInputSchema, f as beginCaptureRunOutputSchema, g as getCaptureRunOutputSchema, h as captureRunDescriptorSchema, i as writeCapturePayload, l as captureBlobs, n as readCaptureManifest, o as captureManifestDigest, r as writeCaptureJson, s as captureError, t as readCaptureBlob, u as selectedCaptures } from "./capture-files.lib-BA_KBz9W.mjs";
2
+ import { mkdir } from "node:fs/promises";
3
+ import nodePath from "node:path";
4
+ //#region src/node/capture-publication.client.ts
5
+ const UPLOAD_BATCH_SIZE = 400;
6
+ const POLL_INTERVAL_MS = 250;
7
+ const uploadBlob = async (input) => {
8
+ if (input.held === void 0) throw captureError("transport", "Enhance omitted a requested blob reservation.", input.runId);
9
+ const upload = input.held.upload;
10
+ if (upload === null) return;
11
+ const bytes = await readCaptureBlob(input.directory, input.blob);
12
+ try {
13
+ if (!(await fetch(upload.url, {
14
+ method: "PUT",
15
+ headers: upload.headers,
16
+ body: new Blob([Uint8Array.from(bytes)]),
17
+ signal: AbortSignal.timeout(input.transport.timeoutMs),
18
+ redirect: "error"
19
+ })).ok) throw captureError("transport", "Upload refused.", input.runId);
20
+ } catch {
21
+ throw captureError("transport", "Capture upload was not confirmed. Resume the same manifest.", input.runId);
22
+ }
23
+ };
24
+ const uploadBlobs = async (transport, manifest, directory, blobs) => {
25
+ for (let start = 0; start < blobs.length; start += UPLOAD_BATCH_SIZE) {
26
+ const batch = blobs.slice(start, start + UPLOAD_BATCH_SIZE);
27
+ for (const blob of batch) await readCaptureBlob(directory, blob);
28
+ const reserved = await transport.request("captureRun.reserveAssets", {
29
+ runId: manifest.run.id,
30
+ blobs: batch
31
+ }, reserveCaptureBlobsOutputSchema);
32
+ for (const blob of batch) await uploadBlob({
33
+ transport,
34
+ runId: manifest.run.id,
35
+ directory,
36
+ blob,
37
+ held: reserved.uploads.find((item) => item.sha256 === blob.sha256)
38
+ });
39
+ }
40
+ };
41
+ const committedRun = async (transport, runId) => {
42
+ let status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
43
+ const deadline = Date.now() + transport.publicationTimeoutMs;
44
+ while (status.receipt === null && status.failure === null && !["cancelled", "failed"].includes(status.state)) {
45
+ if (Date.now() >= deadline) throw captureError("transport", `Capture run ${runId} is still processing. Resume the same manifest.`, runId);
46
+ await new Promise((resolve) => {
47
+ setTimeout(resolve, POLL_INTERVAL_MS);
48
+ });
49
+ status = await transport.request("captureRun.publish", { runId }, getCaptureRunOutputSchema);
50
+ }
51
+ if (status.receipt === null) throw captureError(status.failure?.code === "conflict" ? "conflict" : "conversion", status.failure?.message ?? "The capture run was cancelled.", runId);
52
+ return status.receipt;
53
+ };
54
+ const checkedReceipt = (receipt, manifest) => {
55
+ 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);
56
+ return receipt;
57
+ };
58
+ const publishManifest = async (transport, manifest, directory) => {
59
+ const artifacts = selectedCaptures(manifest);
60
+ if (typeof artifacts === "string") throw captureError("artifact", artifacts);
61
+ const blobs = captureBlobs(artifacts);
62
+ if (typeof blobs === "string") throw captureError("artifact", blobs);
63
+ const current = await transport.request("captureRun.get", { runId: manifest.run.id }, getCaptureRunOutputSchema, true);
64
+ if (current.receipt !== null) {
65
+ const receipt = checkedReceipt(current.receipt, manifest);
66
+ await writeCaptureJson(nodePath.join(directory, "receipt.json"), receipt);
67
+ return receipt;
68
+ }
69
+ if (current.state === "collecting") await uploadBlobs(transport, manifest, directory, blobs);
70
+ await transport.request("captureRun.seal", { manifest }, getCaptureRunOutputSchema);
71
+ const receipt = checkedReceipt(await committedRun(transport, manifest.run.id), manifest);
72
+ await writeCaptureJson(nodePath.join(directory, "receipt.json"), receipt);
73
+ return receipt;
74
+ };
75
+ const publishCaptureManifest = async (transport, manifest, directory) => {
76
+ try {
77
+ return await publishManifest(transport, manifest, directory);
78
+ } catch (error) {
79
+ if (error instanceof Error) throw Object.assign(error, { runId: manifest.run.id });
80
+ throw captureError("transport", "Capture publication was not confirmed. Resume the same manifest.", manifest.run.id);
81
+ }
82
+ };
83
+ //#endregion
84
+ //#region src/node/capture-transport.client.ts
85
+ const MAX_ERROR_LENGTH = 1e3;
86
+ const DEFAULT_TIMEOUT_MS = 3e4;
87
+ const DEFAULT_PUBLICATION_TIMEOUT_MS = 6e5;
88
+ const MAX_PUBLICATION_TIMEOUT_MS = 36e5;
89
+ const MAX_TIMEOUT_MS = 3e5;
90
+ const HTTP_ERRORS = /* @__PURE__ */ new Map([
91
+ [401, "authorization"],
92
+ [403, "authorization"],
93
+ [409, "conflict"],
94
+ [400, "artifact"]
95
+ ]);
96
+ const requestResponse = async (url, options) => {
97
+ try {
98
+ return await fetch(url, options);
99
+ } catch {
100
+ throw captureError("transport", "Enhance did not confirm the request. Resume the same run to recover its result.");
101
+ }
102
+ };
103
+ const responseBody = async (response) => {
104
+ try {
105
+ return await response.json();
106
+ } catch {
107
+ return null;
108
+ }
109
+ };
110
+ const call = async (url, options, schema, procedure) => {
111
+ const response = await requestResponse(url, options);
112
+ const body = await responseBody(response);
113
+ if (!response.ok) {
114
+ const error = typeof body === "object" && body !== null ? Reflect.get(body, "error") : null;
115
+ const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : null;
116
+ throw captureError(HTTP_ERRORS.get(response.status) ?? "transport", typeof message === "string" ? message.slice(0, MAX_ERROR_LENGTH) : `Enhance rejected ${procedure} (HTTP ${String(response.status)}).`);
117
+ }
118
+ const result = typeof body === "object" && body !== null ? Reflect.get(body, "result") : null;
119
+ const data = typeof result === "object" && result !== null ? Reflect.get(result, "data") : void 0;
120
+ const parsed = schema.safeParse(data);
121
+ if (!parsed.success) throw captureError("transport", `Enhance returned an incompatible ${procedure} response.`);
122
+ return parsed.data;
123
+ };
124
+ const captureTransport = (options) => {
125
+ const base = URL.parse(options.apiUrl);
126
+ 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.");
127
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
128
+ const publicationTimeoutMs = options.publicationTimeoutMs ?? DEFAULT_PUBLICATION_TIMEOUT_MS;
129
+ if (!Number.isSafeInteger(publicationTimeoutMs) || publicationTimeoutMs < 1 || publicationTimeoutMs > MAX_PUBLICATION_TIMEOUT_MS) throw captureError("configuration", "Enhance publication timeout must be between 1 and 3600000 milliseconds.");
130
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_TIMEOUT_MS) throw captureError("configuration", "Enhance timeout must be between 1 and 300000 milliseconds.");
131
+ return {
132
+ timeoutMs,
133
+ publicationTimeoutMs,
134
+ request: async (procedure, input, schema, isQuery = false) => {
135
+ const url = new URL(`${base.pathname.replace(/\/$/u, "")}/trpc/${procedure}`, base.origin);
136
+ if (isQuery) url.searchParams.set("input", JSON.stringify(input));
137
+ return call(url, {
138
+ method: isQuery ? "GET" : "POST",
139
+ headers: {
140
+ authorization: `Bearer ${options.token}`,
141
+ "content-type": "application/json"
142
+ },
143
+ ...!isQuery && { body: JSON.stringify(input) },
144
+ signal: AbortSignal.timeout(timeoutMs),
145
+ redirect: "error"
146
+ }, schema, procedure);
147
+ }
148
+ };
149
+ };
150
+ //#endregion
151
+ //#region src/node/capture-client.client.ts
152
+ const nodeManifest = (descriptor, captured) => {
153
+ const participant = descriptor.participants[0];
154
+ if (participant === void 0) throw captureError("configuration", "No capture participant was reserved.");
155
+ return {
156
+ format: "enhance-capture-run",
157
+ version: 1,
158
+ run: descriptor,
159
+ ordering: "partial",
160
+ participants: [{
161
+ id: participant,
162
+ status: "passed"
163
+ }],
164
+ attempts: [{
165
+ participant,
166
+ testId: "node",
167
+ project: "node",
168
+ retry: 0,
169
+ status: "passed",
170
+ captures: captured
171
+ }]
172
+ };
173
+ };
174
+ const createRun = (transport, input, directory) => {
175
+ const descriptor = captureRunDescriptorSchema.parse(input);
176
+ const artifacts = [];
177
+ let isClosed = false;
178
+ return {
179
+ descriptor,
180
+ directory,
181
+ add: async (payload) => {
182
+ if (isClosed) throw captureError("configuration", "This run no longer accepts captures.");
183
+ const written = writeCapturePayload(directory, payload);
184
+ artifacts.push(written);
185
+ await written;
186
+ },
187
+ publish: async () => {
188
+ isClosed = true;
189
+ const captured = await Promise.all(artifacts);
190
+ if (descriptor.participants.length !== 1) throw captureError("configuration", "Multi-participant runs must publish a complete merged manifest.");
191
+ const manifest = nodeManifest(descriptor, captured);
192
+ const selected = selectedCaptures(manifest);
193
+ if (typeof selected === "string") throw captureError("artifact", selected);
194
+ await mkdir(directory, { recursive: true });
195
+ await writeCaptureJson(nodePath.join(directory, "manifest.json"), manifest);
196
+ return publishCaptureManifest(transport, manifest, directory);
197
+ },
198
+ cancel: async () => {
199
+ isClosed = true;
200
+ return (await transport.request("captureRun.cancel", { runId: descriptor.id }, getCaptureRunOutputSchema)).receipt;
201
+ }
202
+ };
203
+ };
204
+ const createEnhance = (options) => {
205
+ const transport = captureTransport(options);
206
+ const get = async (runId) => transport.request("captureRun.get", { runId }, getCaptureRunOutputSchema, true);
207
+ return { captures: {
208
+ begin: async (input) => {
209
+ const request = beginCaptureRunInputSchema.parse({
210
+ canvasId: input.canvas,
211
+ source: input.source,
212
+ runKey: input.runKey,
213
+ participants: input.participants
214
+ });
215
+ const { run } = await transport.request("captureRun.begin", request, beginCaptureRunOutputSchema);
216
+ const directory = input.directory ?? nodePath.join(".enhance", "captures", run.id);
217
+ await mkdir(directory, { recursive: true });
218
+ await writeCaptureJson(nodePath.join(directory, "run.json"), run);
219
+ return createRun(transport, run, directory);
220
+ },
221
+ publishManifest: async (path) => publishCaptureManifest(transport, await readCaptureManifest(path), nodePath.dirname(path)),
222
+ get
223
+ } };
224
+ };
225
+ //#endregion
226
+ export { createEnhance as t };
@@ -0,0 +1,406 @@
1
+ import { z } from "zod";
2
+ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
3
+ import nodePath from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ //#region ../contract/src/capture/capture.schema.ts
6
+ const CAPTURE_KEY_LENGTH = 160;
7
+ const CAPTURE_MAX_EDGE = 32768;
8
+ const CAPTURE_METADATA_LENGTH = 200;
9
+ const CAPTURE_MAX_ORDER = 1e5;
10
+ const CAPTURE_MAX_PIXEL_RATIO = 8;
11
+ const CAPTURE_URL_LENGTH = 8192;
12
+ const CAPTURE_MAX_ASSETS = 2e3;
13
+ const CAPTURE_ISSUE_LENGTH = 500;
14
+ const CAPTURE_MAX_ISSUES = 100;
15
+ const CAPTURE_MAX_PARTICIPANTS = 128;
16
+ const CAPTURE_MAX_ATTEMPTS = 1e4;
17
+ const CAPTURE_FAILURE_LENGTH = 1e3;
18
+ const CAPTURE_UPLOAD_BATCH_SIZE = 400;
19
+ const CAPTURE_MAX_BLOB_BYTES = 16777216;
20
+ const key = z.string().trim().min(1).max(CAPTURE_KEY_LENGTH);
21
+ const digest = z.string().regex(/^[a-f0-9]{64}$/u);
22
+ const dimension = z.number().int().positive().max(CAPTURE_MAX_EDGE);
23
+ const captureKeySchema = z.strictObject({
24
+ source: key,
25
+ journey: key,
26
+ step: key,
27
+ variant: key
28
+ });
29
+ const captureBlobSchema = z.strictObject({
30
+ sha256: digest,
31
+ bytes: z.number().int().positive().max(CAPTURE_MAX_BLOB_BYTES),
32
+ mediaType: z.string().min(1).max(CAPTURE_METADATA_LENGTH)
33
+ });
34
+ const captureArtifactSchema = z.strictObject({
35
+ format: z.literal("enhance-capture"),
36
+ version: z.literal(1),
37
+ key: captureKeySchema,
38
+ label: key,
39
+ journeyLabel: key,
40
+ order: z.number().int().nonnegative().max(CAPTURE_MAX_ORDER),
41
+ viewport: z.strictObject({
42
+ width: dimension,
43
+ height: dimension,
44
+ deviceScaleFactor: z.number().positive().max(CAPTURE_MAX_PIXEL_RATIO)
45
+ }),
46
+ extent: z.enum(["viewport", "full-page"]),
47
+ source: z.strictObject({
48
+ format: z.literal("rrweb-screen"),
49
+ version: z.literal(1),
50
+ blob: captureBlobSchema
51
+ }),
52
+ preview: z.strictObject({
53
+ blob: captureBlobSchema,
54
+ width: dimension,
55
+ height: dimension,
56
+ pixelRatio: z.number().positive().max(CAPTURE_MAX_PIXEL_RATIO)
57
+ }),
58
+ assets: z.array(z.strictObject({
59
+ url: z.url().max(CAPTURE_URL_LENGTH),
60
+ blob: captureBlobSchema
61
+ })).max(CAPTURE_MAX_ASSETS),
62
+ provenance: z.strictObject({
63
+ adapter: key,
64
+ sdkVersion: key,
65
+ kernelVersion: key,
66
+ browser: key,
67
+ capturedAt: z.iso.datetime(),
68
+ sourceUrl: z.url().max(CAPTURE_URL_LENGTH).optional(),
69
+ commit: z.string().min(1).max(CAPTURE_METADATA_LENGTH).optional()
70
+ }),
71
+ issues: z.array(z.strictObject({
72
+ code: key,
73
+ message: z.string().min(1).max(CAPTURE_ISSUE_LENGTH)
74
+ })).max(CAPTURE_MAX_ISSUES)
75
+ }).superRefine((artifact, ctx) => {
76
+ if (artifact.preview.width * artifact.preview.height > 16e6) ctx.addIssue({
77
+ code: "custom",
78
+ path: ["preview"],
79
+ message: "Capture previews are limited to 16 million pixels."
80
+ });
81
+ if (artifact.preview.width / artifact.preview.pixelRatio !== artifact.viewport.width || artifact.preview.height / artifact.preview.pixelRatio !== artifact.viewport.height) ctx.addIssue({
82
+ code: "custom",
83
+ path: ["preview"],
84
+ message: "The preview and captured CSS extent must match."
85
+ });
86
+ if (artifact.source.blob.mediaType !== "application/json") ctx.addIssue({
87
+ code: "custom",
88
+ path: [
89
+ "source",
90
+ "blob",
91
+ "mediaType"
92
+ ],
93
+ message: "Capture sources must be frozen JSON."
94
+ });
95
+ if (artifact.preview.blob.mediaType !== "image/png") ctx.addIssue({
96
+ code: "custom",
97
+ path: [
98
+ "preview",
99
+ "blob",
100
+ "mediaType"
101
+ ],
102
+ message: "Capture previews must be PNG."
103
+ });
104
+ if (new Set(artifact.assets.map((asset) => asset.url)).size !== artifact.assets.length) ctx.addIssue({
105
+ code: "custom",
106
+ path: ["assets"],
107
+ message: "Capture resource URLs must be unique."
108
+ });
109
+ });
110
+ const captureRunDescriptorSchema = z.strictObject({
111
+ id: z.uuid(),
112
+ canvasId: z.uuid(),
113
+ source: key,
114
+ runKey: key,
115
+ generation: z.number().int().nonnegative(),
116
+ participants: z.array(key).min(1).max(CAPTURE_MAX_PARTICIPANTS),
117
+ expiresAt: z.iso.datetime(),
118
+ formatVersion: z.literal(1)
119
+ });
120
+ const captureAttemptSchema = z.strictObject({
121
+ participant: key,
122
+ testId: key,
123
+ project: key,
124
+ retry: z.number().int().nonnegative().max(CAPTURE_MAX_ISSUES),
125
+ status: z.enum([
126
+ "passed",
127
+ "failed",
128
+ "skipped",
129
+ "interrupted",
130
+ "timedOut"
131
+ ]),
132
+ captures: z.array(captureArtifactSchema).max(64)
133
+ });
134
+ const captureManifestSchema = z.strictObject({
135
+ format: z.literal("enhance-capture-run"),
136
+ version: z.literal(1),
137
+ run: captureRunDescriptorSchema,
138
+ participants: z.array(z.strictObject({
139
+ id: key,
140
+ status: z.enum([
141
+ "passed",
142
+ "failed",
143
+ "interrupted"
144
+ ])
145
+ })).min(1).max(CAPTURE_MAX_PARTICIPANTS),
146
+ attempts: z.array(captureAttemptSchema).max(CAPTURE_MAX_ATTEMPTS),
147
+ ordering: z.enum(["partial", "complete"])
148
+ });
149
+ const captureReceiptSchema = z.strictObject({
150
+ runId: z.uuid(),
151
+ canvasId: z.uuid(),
152
+ canvasUrl: z.url(),
153
+ version: z.number().int().positive(),
154
+ manifestDigest: digest,
155
+ frames: z.array(z.strictObject({
156
+ key: captureKeySchema,
157
+ frameId: key,
158
+ captureId: z.uuid()
159
+ })).max(64),
160
+ issues: z.array(z.strictObject({
161
+ code: key,
162
+ message: z.string().max(CAPTURE_ISSUE_LENGTH)
163
+ })).max(CAPTURE_MAX_ISSUES)
164
+ });
165
+ const beginCaptureRunInputSchema = z.strictObject({
166
+ canvasId: z.uuid(),
167
+ source: key.default("default"),
168
+ runKey: key,
169
+ participants: z.array(key).min(1).max(CAPTURE_MAX_PARTICIPANTS).default(["local"]),
170
+ formatVersion: z.literal(1).default(1)
171
+ });
172
+ const beginCaptureRunOutputSchema = z.strictObject({ run: captureRunDescriptorSchema });
173
+ z.strictObject({ runId: z.uuid() });
174
+ const captureRunStateSchema = z.enum([
175
+ "collecting",
176
+ "sealed",
177
+ "converting",
178
+ "committed",
179
+ "failed",
180
+ "cancelled"
181
+ ]);
182
+ const getCaptureRunOutputSchema = z.strictObject({
183
+ run: captureRunDescriptorSchema,
184
+ state: captureRunStateSchema,
185
+ receipt: captureReceiptSchema.nullable(),
186
+ failure: z.strictObject({
187
+ code: key,
188
+ message: z.string().max(CAPTURE_FAILURE_LENGTH)
189
+ }).nullable()
190
+ });
191
+ z.strictObject({
192
+ runId: z.uuid(),
193
+ blobs: z.array(captureBlobSchema).min(1).max(CAPTURE_UPLOAD_BATCH_SIZE)
194
+ });
195
+ const reserveCaptureBlobsOutputSchema = z.strictObject({ uploads: z.array(z.strictObject({
196
+ sha256: digest,
197
+ upload: z.strictObject({
198
+ url: z.url(),
199
+ headers: z.record(z.string(), z.string()),
200
+ expiresAt: z.iso.datetime()
201
+ }).nullable()
202
+ })).max(CAPTURE_UPLOAD_BATCH_SIZE) });
203
+ z.strictObject({ manifest: captureManifestSchema });
204
+ //#endregion
205
+ //#region ../contract/src/capture/capture-comparison.schema.ts
206
+ const COMMIT_LENGTH = 200;
207
+ z.strictObject({
208
+ canvasId: z.uuid(),
209
+ frameId: z.string().min(1),
210
+ captureId: z.uuid()
211
+ });
212
+ const preview = z.strictObject({
213
+ captureId: z.uuid(),
214
+ capturedAt: z.iso.datetime(),
215
+ commit: z.string().max(COMMIT_LENGTH).optional(),
216
+ url: z.string().min(1),
217
+ width: z.number().positive(),
218
+ height: z.number().positive(),
219
+ pixelRatio: z.number().positive()
220
+ });
221
+ z.strictObject({
222
+ frameId: z.string(),
223
+ before: preview,
224
+ after: preview
225
+ });
226
+ //#endregion
227
+ //#region ../contract/src/capture/capture-manifest.lib.ts
228
+ const captureKeyString = (key) => JSON.stringify([
229
+ key.source,
230
+ key.journey,
231
+ key.step,
232
+ key.variant
233
+ ]);
234
+ const compare = (left, right) => left < right ? -1 : left === right ? 0 : 1;
235
+ const MAX_JSON_DEPTH = 64;
236
+ const canonical = (value, ancestors) => {
237
+ if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
238
+ if (typeof value === "number" && Number.isFinite(value)) return JSON.stringify(value);
239
+ if (typeof value !== "object" || ancestors.has(value) || ancestors.size >= MAX_JSON_DEPTH) return null;
240
+ const next = new Set(ancestors);
241
+ next.add(value);
242
+ if (Array.isArray(value)) {
243
+ const entries = value.map((entry) => canonical(entry, next));
244
+ return entries.includes(null) ? null : `[${entries.join(",")}]`;
245
+ }
246
+ if (Object.getPrototypeOf(value) !== Object.prototype) return null;
247
+ const entries = Object.keys(value).toSorted(compare).map((key) => {
248
+ const child = canonical(Reflect.get(value, key), next);
249
+ return child === null ? null : `${JSON.stringify(key)}:${child}`;
250
+ });
251
+ return entries.includes(null) ? null : `{${entries.join(",")}}`;
252
+ };
253
+ /** Null means a value would be lost or coerced by JSON; it must never be hashed. */
254
+ const canonicalCaptureJson = (value) => canonical(value, /* @__PURE__ */ new Set());
255
+ const captureBlobs = (artifacts) => {
256
+ const blobs = /* @__PURE__ */ new Map();
257
+ const unique = [];
258
+ let totalBytes = 0;
259
+ for (const artifact of artifacts) {
260
+ const references = [
261
+ artifact.source.blob,
262
+ artifact.preview.blob,
263
+ ...artifact.assets.map((asset) => asset.blob)
264
+ ];
265
+ for (const blob of references) {
266
+ const previous = blobs.get(blob.sha256);
267
+ if (previous !== void 0 && canonicalCaptureJson(previous) !== canonicalCaptureJson(blob)) return "The same capture digest has conflicting blob metadata.";
268
+ if (previous === void 0) {
269
+ unique.push(blob);
270
+ totalBytes += blob.bytes;
271
+ blobs.set(blob.sha256, blob);
272
+ }
273
+ }
274
+ }
275
+ if (totalBytes > 268435456) return "Capture run exceeds the retained byte budget.";
276
+ return unique.toSorted((a, b) => compare(a.sha256, b.sha256));
277
+ };
278
+ const finalAttempts = (manifest) => {
279
+ const expected = new Set(manifest.run.participants);
280
+ 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.";
281
+ const attempts = /* @__PURE__ */ new Map();
282
+ const terminal = /* @__PURE__ */ new Map();
283
+ for (const attempt of manifest.attempts) {
284
+ if (!expected.has(attempt.participant)) return "Capture attempt belongs to an unreserved participant.";
285
+ const identity = JSON.stringify([
286
+ attempt.participant,
287
+ attempt.project,
288
+ attempt.testId
289
+ ]);
290
+ const attemptKey = JSON.stringify([identity, attempt.retry]);
291
+ const content = canonicalCaptureJson(attempt);
292
+ if (content === null) return "Capture attempts must contain finite JSON values.";
293
+ const previous = terminal.get(attemptKey);
294
+ if (previous !== void 0 && previous !== content) return "Conflicting terminal records for the same test attempt.";
295
+ terminal.set(attemptKey, content);
296
+ const selected = attempts.get(identity);
297
+ if (selected === void 0 || selected.retry < attempt.retry) attempts.set(identity, attempt);
298
+ }
299
+ return manifest.attempts.filter((attempt) => attempts.get(JSON.stringify([
300
+ attempt.participant,
301
+ attempt.project,
302
+ attempt.testId
303
+ ])) === attempt);
304
+ };
305
+ const uniqueCaptures = (source, artifacts) => {
306
+ const keys = /* @__PURE__ */ new Set();
307
+ const orders = /* @__PURE__ */ new Set();
308
+ for (const artifact of artifacts) {
309
+ if (artifact.key.source !== source) return "Capture source differs from its reserved run.";
310
+ const identity = captureKeyString(artifact.key);
311
+ if (keys.has(identity)) return `Duplicate capture key: ${identity}`;
312
+ const order = JSON.stringify([
313
+ artifact.key.journey,
314
+ artifact.key.variant,
315
+ artifact.order
316
+ ]);
317
+ if (orders.has(order)) return `Duplicate step order in journey ${artifact.key.journey}.`;
318
+ keys.add(identity);
319
+ orders.add(order);
320
+ }
321
+ return null;
322
+ };
323
+ const compareCaptureArtifacts = (left, right) => {
324
+ const journey = compare(left.key.journey, right.key.journey);
325
+ if (journey !== 0) return journey;
326
+ const variant = compare(left.key.variant, right.key.variant);
327
+ return variant === 0 ? left.order - right.order : variant;
328
+ };
329
+ /** All publishers select whole terminal attempts with the same completeness rules. */
330
+ const selectedCaptures = (input) => {
331
+ const parsed = captureManifestSchema.safeParse(input);
332
+ if (!parsed.success) return "Invalid capture manifest.";
333
+ const manifest = parsed.data;
334
+ const attempts = finalAttempts(manifest);
335
+ if (typeof attempts === "string") return attempts;
336
+ const artifacts = attempts.flatMap((attempt) => attempt.status === "passed" ? attempt.captures : []);
337
+ if (artifacts.length === 0 || artifacts.length > 64) return `A run must contain 1–${String(64)} successful captures.`;
338
+ const conflict = uniqueCaptures(manifest.run.source, artifacts);
339
+ if (conflict !== null) return conflict;
340
+ const blobs = captureBlobs(artifacts);
341
+ return typeof blobs === "string" ? blobs : artifacts.toSorted(compareCaptureArtifacts);
342
+ };
343
+ const captureManifestContent = (manifest) => {
344
+ const serialized = canonicalCaptureJson(manifest);
345
+ return serialized === null ? null : `enhance-capture-run:v1\0${serialized}`;
346
+ };
347
+ //#endregion
348
+ //#region src/core/capture-error.error.ts
349
+ const captureError = (code, message, runId) => Object.assign(new Error(message), {
350
+ code,
351
+ ...runId !== void 0 && { runId }
352
+ });
353
+ //#endregion
354
+ //#region src/node/capture-digest.lib.ts
355
+ const captureBlobDigest = (bytes) => createHash("sha256").update(bytes).digest("hex");
356
+ const captureManifestDigest = (manifest) => {
357
+ const canonical = captureManifestContent(manifest);
358
+ if (canonical === null) throw new Error("A capture manifest must contain only finite JSON values.");
359
+ return createHash("sha256").update(canonical).digest("hex");
360
+ };
361
+ //#endregion
362
+ //#region src/node/capture-files.lib.ts
363
+ const captureBlobPath = (directory, digest) => {
364
+ if (!/^[a-f0-9]{64}$/u.test(digest)) throw captureError("artifact", "Invalid capture blob digest.");
365
+ return nodePath.join(nodePath.resolve(directory), "blobs", digest);
366
+ };
367
+ const readCaptureBlob = async (directory, description) => {
368
+ const path = captureBlobPath(directory, description.sha256);
369
+ const info = await stat(path);
370
+ if (!info.isFile() || info.size !== description.bytes || info.size > 16777216) throw captureError("artifact", `Capture blob size does not match ${description.sha256}.`);
371
+ const bytes = await readFile(path);
372
+ if (captureBlobDigest(bytes) !== description.sha256) throw captureError("artifact", `Capture blob checksum does not match ${description.sha256}.`);
373
+ return bytes;
374
+ };
375
+ const writeCapturePayload = async (directory, payload) => {
376
+ const artifact = captureArtifactSchema.parse(payload.artifact);
377
+ await mkdir(nodePath.join(directory, "blobs"), { recursive: true });
378
+ for (const blob of payload.blobs) {
379
+ if (blob.description.bytes !== blob.bytes.byteLength || blob.bytes.byteLength > 16777216 || captureBlobDigest(blob.bytes) !== blob.description.sha256) throw captureError("artifact", "Capture blob bytes do not match their descriptor.");
380
+ const path = captureBlobPath(directory, blob.description.sha256);
381
+ const temporary = `${path}.${globalThis.crypto.randomUUID()}.tmp`;
382
+ await writeFile(temporary, blob.bytes, {
383
+ flag: "wx",
384
+ mode: 384
385
+ });
386
+ await rename(temporary, path);
387
+ }
388
+ for (const blob of [
389
+ artifact.source.blob,
390
+ artifact.preview.blob,
391
+ ...artifact.assets.map((asset) => asset.blob)
392
+ ]) await readCaptureBlob(directory, blob);
393
+ return artifact;
394
+ };
395
+ const writeCaptureJson = async (path, value) => {
396
+ const temporary = `${path}.${globalThis.crypto.randomUUID()}.tmp`;
397
+ await writeFile(temporary, JSON.stringify(value), { mode: 384 });
398
+ await rename(temporary, path);
399
+ };
400
+ const readCaptureManifest = async (path) => {
401
+ if ((await stat(path)).size > 16777216) throw captureError("artifact", "Capture manifest exceeds its byte budget.");
402
+ const raw = JSON.parse(await readFile(path, "utf8"));
403
+ return captureManifestSchema.parse(raw);
404
+ };
405
+ //#endregion
406
+ export { reserveCaptureBlobsOutputSchema as _, captureBlobDigest as a, canonicalCaptureJson as c, beginCaptureRunInputSchema as d, beginCaptureRunOutputSchema as f, getCaptureRunOutputSchema as g, captureRunDescriptorSchema as h, writeCapturePayload as i, captureBlobs as l, captureManifestSchema as m, readCaptureManifest as n, captureManifestDigest as o, captureArtifactSchema as p, writeCaptureJson as r, captureError as s, readCaptureBlob as t, selectedCaptures as u };
@@ -0,0 +1,11 @@
1
+ import { n as CaptureArtifact, r as CaptureBlob } from "./index-PIb9iIwo.mjs";
2
+ //#region src/node/capture-files.lib.d.ts
3
+ interface CapturePayload {
4
+ readonly artifact: CaptureArtifact;
5
+ readonly blobs: readonly {
6
+ readonly description: CaptureBlob;
7
+ readonly bytes: Uint8Array;
8
+ }[];
9
+ }
10
+ //#endregion
11
+ export { CapturePayload as t };
@@ -0,0 +1,14 @@
1
+ import { s as captureError } from "./capture-files.lib-BA_KBz9W.mjs";
2
+ import process from "node:process";
3
+ //#region src/playwright/environment.config.ts
4
+ const captureEnvironment = () => ({
5
+ apiUrl: process.env["ENHANCE_API_URL"] ?? "https://api.enhancelabs.ai",
6
+ token: process.env["ENHANCE_TOKEN"] ?? "",
7
+ directory: process.env["ENHANCE_CAPTURE_DIRECTORY"] ?? ""
8
+ });
9
+ const setCaptureDirectory = (directory) => {
10
+ if (directory === "") throw captureError("configuration", "Capture output directory must not be empty.");
11
+ process.env["ENHANCE_CAPTURE_DIRECTORY"] = directory;
12
+ };
13
+ //#endregion
14
+ export { setCaptureDirectory as n, captureEnvironment as t };