@crvouga/mockingbird-preview 0.0.0-reserved → 0.0.1

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/index.js ADDED
@@ -0,0 +1,1018 @@
1
+ import {
2
+ SANDBOX_KEY_HEADER,
3
+ createSandboxProxy,
4
+ safeEqual,
5
+ sandboxProviders,
6
+ sandboxProxyWorker
7
+ } from "./chunk-CFLI52WY.js";
8
+
9
+ // src/artifacts.ts
10
+ var legacyArtifact = (value) => {
11
+ if (!value || typeof value !== "object" || !("version" in value)) return void 0;
12
+ const artifact = value;
13
+ if (artifact.version !== 1) throw new Error("Unsupported preview artifact version");
14
+ if (typeof artifact.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(artifact.sha256) || typeof artifact.url !== "string" || !artifact.url || artifact.compression !== void 0 && artifact.compression !== "gzip")
15
+ throw new Error("Invalid legacy preview artifact manifest");
16
+ return artifact;
17
+ };
18
+ var HEX = /^[0-9a-f]{64}$/;
19
+ function parsePreviewArtifact(value) {
20
+ if (!value || typeof value !== "object") throw new Error("Invalid preview artifact manifest");
21
+ const item = value;
22
+ if (item.format !== 1 || typeof item.commit !== "string" || !item.commit || typeof item.sha256 !== "string" || !HEX.test(item.sha256) || !Number.isSafeInteger(item.bytes) || (item.bytes ?? -1) < 0 || !["identity", "gzip"].includes(item.encoding ?? "") || typeof item.url !== "string" || !item.url)
23
+ throw new Error("Unsupported or invalid preview artifact manifest");
24
+ return item;
25
+ }
26
+ async function digestPreviewBytes(bytes) {
27
+ const hash = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
28
+ return [...new Uint8Array(hash)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
29
+ }
30
+ async function createPreviewArtifact(bytes, options) {
31
+ return parsePreviewArtifact({
32
+ format: 1,
33
+ commit: options.commit,
34
+ url: options.url,
35
+ encoding: options.encoding ?? "identity",
36
+ bytes: bytes.length,
37
+ sha256: await digestPreviewBytes(bytes)
38
+ });
39
+ }
40
+ var boundedBytes = async (stream, maximum) => {
41
+ const reader = stream.getReader();
42
+ const chunks = [];
43
+ let size = 0;
44
+ try {
45
+ for (; ; ) {
46
+ const next = await reader.read();
47
+ if (next.done) break;
48
+ size += next.value.byteLength;
49
+ if (size > maximum) throw new Error("Preview asset exceeds size limit");
50
+ chunks.push(next.value);
51
+ }
52
+ } catch (error) {
53
+ await reader.cancel().catch(() => {
54
+ });
55
+ throw error;
56
+ } finally {
57
+ reader.releaseLock();
58
+ }
59
+ const bytes = new Uint8Array(size);
60
+ let offset = 0;
61
+ for (const chunk of chunks) {
62
+ bytes.set(chunk, offset);
63
+ offset += chunk.byteLength;
64
+ }
65
+ return bytes;
66
+ };
67
+ async function loadPreviewArtifact(manifest, options = {}) {
68
+ const legacy = legacyArtifact(manifest);
69
+ const artifact = legacy ? {
70
+ url: legacy.url,
71
+ commit: void 0,
72
+ bytes: void 0,
73
+ sha256: legacy.sha256,
74
+ encoding: legacy.compression ?? "identity"
75
+ } : parsePreviewArtifact(manifest);
76
+ if (options.expectedCommit !== void 0 && artifact.commit !== options.expectedCommit)
77
+ throw new Error("Stale preview artifact commit");
78
+ const maximum = options.maximumBytes ?? 128 * 1024 * 1024;
79
+ if (!Number.isSafeInteger(maximum) || maximum < 1 || artifact.bytes !== void 0 && artifact.bytes > maximum)
80
+ throw new Error("Preview asset exceeds size limit");
81
+ let response;
82
+ try {
83
+ response = await (options.fetch ?? fetch)(artifact.url, {
84
+ cache: "no-store",
85
+ redirect: "error",
86
+ credentials: "omit",
87
+ ...options.signal ? { signal: options.signal } : {}
88
+ });
89
+ } catch {
90
+ throw new Error("Preview asset download failed");
91
+ }
92
+ if (!response.ok || !response.body)
93
+ throw new Error(`Preview asset download failed (${response.status})`);
94
+ const bytes = await boundedBytes(response.body, maximum);
95
+ if (!legacy && (bytes.byteLength !== artifact.bytes || await digestPreviewBytes(bytes) !== artifact.sha256))
96
+ throw new Error("Preview asset integrity mismatch");
97
+ let decoded = bytes;
98
+ if (artifact.encoding === "gzip") {
99
+ try {
100
+ decoded = await boundedBytes(
101
+ new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")),
102
+ maximum
103
+ );
104
+ } catch {
105
+ throw new Error("Preview asset decompression failed or exceeds size limit");
106
+ }
107
+ }
108
+ if (legacy && await digestPreviewBytes(decoded) !== artifact.sha256)
109
+ throw new Error("Preview artifact identity mismatch");
110
+ return decoded;
111
+ }
112
+
113
+ // src/bridge.ts
114
+ var PROTOCOL = "mockingbird-preview/1";
115
+ var envelope = (data) => {
116
+ if (!data || typeof data !== "object") return false;
117
+ const value = data;
118
+ return value.protocol === PROTOCOL && Number.isSafeInteger(value.id) && typeof value.kind === "string";
119
+ };
120
+ var failure = (message) => new Error(`Preview bridge: ${message}`);
121
+ var post = (port, id, kind, fields = {}, transfer = []) => port.postMessage({ protocol: PROTOCOL, id, kind, ...fields }, transfer);
122
+ var safeHeaders = (headers, cookies) => [...headers].filter(([name]) => cookies || !["cookie", "set-cookie"].includes(name.toLowerCase()));
123
+ function createPreviewClient(port, options = {}) {
124
+ const pending = /* @__PURE__ */ new Map();
125
+ const timeoutMs = options.timeoutMs ?? 3e4;
126
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw failure("timeout must be positive");
127
+ let next = 1;
128
+ let closed = false;
129
+ const finish = (id, error) => {
130
+ const entry = pending.get(id);
131
+ if (!entry) return;
132
+ pending.delete(id);
133
+ entry.cleanup();
134
+ if (error) {
135
+ entry.reject(error);
136
+ entry.controller?.error(error);
137
+ } else entry.controller?.close();
138
+ };
139
+ const dispose = (reason = failure("connection closed (disconnected)")) => {
140
+ if (closed) return;
141
+ closed = true;
142
+ try {
143
+ post(port, 0, "disconnect");
144
+ } catch {
145
+ }
146
+ for (const id of pending.keys()) finish(id, reason);
147
+ port.removeEventListener("message", receive);
148
+ port.removeEventListener("messageerror", broken);
149
+ port.close();
150
+ };
151
+ const broken = () => dispose();
152
+ const receive = (event) => {
153
+ if (!envelope(event.data)) return;
154
+ const message = event.data;
155
+ if (message.kind === "disconnect") {
156
+ dispose();
157
+ return;
158
+ }
159
+ const entry = pending.get(message.id);
160
+ if (!entry) return;
161
+ try {
162
+ if (message.kind === "error")
163
+ finish(
164
+ message.id,
165
+ failure(
166
+ options.exposeErrors && typeof message.error === "string" ? message.error : "remote request failed"
167
+ )
168
+ );
169
+ else if (message.kind === "end") finish(message.id);
170
+ else if (message.kind === "chunk" && message.bytes instanceof ArrayBuffer) {
171
+ entry.controller?.enqueue(new Uint8Array(message.bytes));
172
+ } else if (message.kind === "response") {
173
+ if (typeof message.status !== "number" || !Array.isArray(message.headers))
174
+ throw failure("invalid response");
175
+ const body = message.body === true ? new ReadableStream(
176
+ {
177
+ start(controller) {
178
+ entry.controller = controller;
179
+ },
180
+ pull() {
181
+ post(port, message.id, "pull");
182
+ },
183
+ cancel() {
184
+ post(port, message.id, "abort");
185
+ pending.delete(message.id);
186
+ entry.cleanup();
187
+ }
188
+ },
189
+ { highWaterMark: 0 }
190
+ ) : null;
191
+ const response = new Response(body, {
192
+ status: message.status,
193
+ statusText: typeof message.statusText === "string" ? message.statusText : "",
194
+ headers: message.headers
195
+ });
196
+ setTimeout(() => entry.resolve(response), 0);
197
+ if (!body) finish(message.id);
198
+ }
199
+ } catch {
200
+ finish(message.id, failure("invalid response"));
201
+ post(port, message.id, "abort");
202
+ }
203
+ };
204
+ port.addEventListener("message", receive);
205
+ port.addEventListener("messageerror", broken);
206
+ port.start();
207
+ const fetch2 = async (input, init) => {
208
+ if (closed) throw failure("connection closed");
209
+ const request = new Request(input, init);
210
+ if (options.allow && !options.allow(new URL(request.url))) throw failure("target refused");
211
+ request.signal.throwIfAborted();
212
+ const body = request.body ? await request.arrayBuffer() : void 0;
213
+ request.signal.throwIfAborted();
214
+ if (closed) throw failure("connection closed");
215
+ const id = next++;
216
+ return new Promise((resolve, reject) => {
217
+ const abort = () => {
218
+ post(port, id, "abort");
219
+ finish(id, failure("request aborted"));
220
+ };
221
+ const timer = setTimeout(() => {
222
+ post(port, id, "abort");
223
+ finish(id, failure("request deadline exceeded"));
224
+ }, timeoutMs);
225
+ pending.set(id, {
226
+ resolve,
227
+ reject,
228
+ cleanup: () => {
229
+ clearTimeout(timer);
230
+ request.signal.removeEventListener("abort", abort);
231
+ }
232
+ });
233
+ request.signal.addEventListener("abort", abort, { once: true });
234
+ try {
235
+ post(
236
+ port,
237
+ id,
238
+ "request",
239
+ {
240
+ url: request.url,
241
+ method: request.method,
242
+ headers: safeHeaders(request.headers, options.cookies === true),
243
+ body
244
+ },
245
+ body ? [body] : []
246
+ );
247
+ } catch {
248
+ finish(id, failure("could not send request"));
249
+ }
250
+ });
251
+ };
252
+ return {
253
+ fetch: fetch2,
254
+ dispose,
255
+ get pending() {
256
+ return pending.size;
257
+ }
258
+ };
259
+ }
260
+ function servePreviewPort(port, fetch2, options = {}) {
261
+ const active = /* @__PURE__ */ new Map();
262
+ let closed = false;
263
+ const stop = (id) => {
264
+ const entry = active.get(id);
265
+ if (!entry) return;
266
+ active.delete(id);
267
+ entry.abort.abort();
268
+ void entry.reader?.cancel().catch(() => {
269
+ });
270
+ };
271
+ const dispose = () => {
272
+ if (closed) return;
273
+ closed = true;
274
+ try {
275
+ post(port, 0, "disconnect");
276
+ } catch {
277
+ }
278
+ for (const id of active.keys()) stop(id);
279
+ port.removeEventListener("message", receive);
280
+ port.removeEventListener("messageerror", broken);
281
+ port.close();
282
+ options.onClose?.();
283
+ };
284
+ const broken = () => dispose();
285
+ const request = async (message) => {
286
+ if (active.has(message.id) || active.size >= (options.maxRequests ?? 128)) {
287
+ post(port, message.id, "error");
288
+ return;
289
+ }
290
+ const abort = new AbortController();
291
+ const entry = { abort, reading: false };
292
+ active.set(message.id, entry);
293
+ try {
294
+ if (typeof message.url !== "string" || typeof message.method !== "string" || !Array.isArray(message.headers))
295
+ throw failure("invalid request");
296
+ const url = new URL(message.url);
297
+ if (options.allow && !options.allow(url)) throw failure("target refused");
298
+ const headers = new Headers(message.headers);
299
+ if (!options.cookies) headers.delete("cookie");
300
+ const input = new Request(url, {
301
+ method: message.method,
302
+ headers,
303
+ body: message.body instanceof ArrayBuffer ? message.body : null,
304
+ signal: abort.signal,
305
+ redirect: "manual",
306
+ credentials: "omit"
307
+ });
308
+ const response = await fetch2(input);
309
+ if (!active.has(message.id)) {
310
+ await response.body?.cancel();
311
+ return;
312
+ }
313
+ if (response.body) entry.reader = response.body.getReader();
314
+ post(port, message.id, "response", {
315
+ status: response.status,
316
+ statusText: response.statusText,
317
+ headers: safeHeaders(response.headers, options.cookies === true),
318
+ body: !!entry.reader
319
+ });
320
+ if (!entry.reader) active.delete(message.id);
321
+ } catch (error) {
322
+ stop(message.id);
323
+ if (!closed)
324
+ post(
325
+ port,
326
+ message.id,
327
+ "error",
328
+ options.exposeErrors ? { error: error instanceof Error ? error.message : String(error) } : {}
329
+ );
330
+ }
331
+ };
332
+ const pull = async (id) => {
333
+ const entry = active.get(id);
334
+ if (!entry?.reader || entry.reading) return;
335
+ entry.reading = true;
336
+ try {
337
+ const chunk = await entry.reader.read();
338
+ if (!active.has(id)) return;
339
+ if (chunk.done) {
340
+ active.delete(id);
341
+ entry.reader.releaseLock();
342
+ post(port, id, "end");
343
+ } else {
344
+ const bytes = new Uint8Array(chunk.value).buffer;
345
+ post(port, id, "chunk", { bytes }, [bytes]);
346
+ }
347
+ } catch (error) {
348
+ stop(id);
349
+ if (!closed)
350
+ post(
351
+ port,
352
+ id,
353
+ "error",
354
+ options.exposeErrors ? { error: error instanceof Error ? error.message : String(error) } : {}
355
+ );
356
+ } finally {
357
+ entry.reading = false;
358
+ }
359
+ };
360
+ const receive = (event) => {
361
+ if (!envelope(event.data)) return;
362
+ const message = event.data;
363
+ if (message.kind === "disconnect") dispose();
364
+ else if (message.kind === "request") void request(message);
365
+ else if (message.kind === "abort") stop(message.id);
366
+ else if (message.kind === "pull") void pull(message.id);
367
+ };
368
+ port.addEventListener("message", receive);
369
+ port.addEventListener("messageerror", broken);
370
+ port.start();
371
+ return {
372
+ dispose,
373
+ get active() {
374
+ return active.size;
375
+ }
376
+ };
377
+ }
378
+
379
+ // src/lifecycle.ts
380
+ function selectPreviewAction(facts, builtCommit) {
381
+ if (facts.state === "closed") return "remove";
382
+ if (!builtCommit || facts.head !== builtCommit || facts.repository !== facts.headRepository)
383
+ return "skip";
384
+ return "deploy";
385
+ }
386
+ function planPreviewSweep(options) {
387
+ if (!Number.isFinite(options.now) || !Number.isFinite(options.retentionMs) || options.retentionMs < 0 || !Number.isSafeInteger(options.capacity) || options.capacity < 0)
388
+ throw new Error("Invalid preview retention policy");
389
+ const candidates = options.previews.filter((preview2) => options.owns(preview2.name));
390
+ if (candidates.some((preview2) => !Number.isFinite(preview2.updatedAt)))
391
+ throw new Error("Invalid preview timestamp");
392
+ const removed = /* @__PURE__ */ new Map();
393
+ for (const preview2 of candidates) {
394
+ if (!options.openNames.has(preview2.name)) removed.set(preview2.name, "orphaned");
395
+ else if (options.now - preview2.updatedAt > options.retentionMs)
396
+ removed.set(preview2.name, "expired");
397
+ }
398
+ const retained = candidates.filter((preview2) => !removed.has(preview2.name)).sort((a, b) => b.updatedAt - a.updatedAt || a.name.localeCompare(b.name));
399
+ for (const preview2 of retained.slice(options.capacity)) removed.set(preview2.name, "capacity");
400
+ return [...removed].map(([name, reason]) => ({ name, reason })).sort((a, b) => a.name.localeCompare(b.name));
401
+ }
402
+
403
+ // src/cloudflare.ts
404
+ var object = (value) => {
405
+ if (!value || typeof value !== "object" || Array.isArray(value))
406
+ throw new Error("Invalid Cloudflare preview response");
407
+ return value;
408
+ };
409
+ var identifier = (value) => {
410
+ if (!value || value === "." || value === ".." || [...value].some((character) => character.charCodeAt(0) < 32))
411
+ throw new Error("Invalid Cloudflare preview identifier");
412
+ return encodeURIComponent(value);
413
+ };
414
+ var preview = (value) => {
415
+ const item = object(value);
416
+ if (typeof item.id !== "string" || typeof item.name !== "string" || typeof item.updated_on !== "string")
417
+ throw new Error("Invalid Cloudflare preview response");
418
+ return {
419
+ id: item.id,
420
+ name: item.name,
421
+ updatedAt: item.updated_on,
422
+ urls: Array.isArray(item.urls) ? item.urls.filter((url) => typeof url === "string") : []
423
+ };
424
+ };
425
+ var base64 = (bytes) => {
426
+ let result = "";
427
+ for (let offset = 0; offset < bytes.length; offset += 8192)
428
+ result += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
429
+ return btoa(result);
430
+ };
431
+ function createCloudflarePreviews(options) {
432
+ const account = identifier(options.accountId);
433
+ const worker = identifier(options.workerName);
434
+ if (!options.token) throw new Error("Cloudflare preview token is required");
435
+ const base = `/accounts/${account}/workers/workers/${worker}/previews`;
436
+ const api = async (operation, path, init = {}, token = options.token, missing = false) => {
437
+ let response;
438
+ try {
439
+ response = await (options.fetch ?? fetch)(`https://api.cloudflare.com/client/v4${path}`, {
440
+ ...init,
441
+ redirect: "error",
442
+ headers: {
443
+ ...Object.fromEntries(new Headers(init.headers)),
444
+ Authorization: `Bearer ${token}`
445
+ }
446
+ });
447
+ } catch {
448
+ throw new Error(`Cloudflare preview ${operation} failed (network)`);
449
+ }
450
+ if (missing && response.status === 404) return void 0;
451
+ if (!response.ok)
452
+ throw new Error(`Cloudflare preview ${operation} failed (HTTP ${response.status})`);
453
+ if (response.status === 204) return { success: true, result: null };
454
+ let parsed;
455
+ try {
456
+ parsed = object(await response.json());
457
+ } catch {
458
+ throw new Error(`Cloudflare preview ${operation} returned invalid JSON`);
459
+ }
460
+ if (parsed.success !== true) throw new Error(`Cloudflare preview ${operation} was refused`);
461
+ return parsed;
462
+ };
463
+ const json = (body) => ({
464
+ method: "POST",
465
+ headers: { "content-type": "application/json" },
466
+ body: JSON.stringify(body)
467
+ });
468
+ const remove = async (name) => {
469
+ await api("delete", `${base}/${identifier(name)}`, { method: "DELETE" }, options.token, true);
470
+ };
471
+ const list = async () => {
472
+ const all = [];
473
+ const seen = /* @__PURE__ */ new Set();
474
+ for (let page = 1; page <= 1e3; page++) {
475
+ const response = await api("list", `${base}?page=${page}&per_page=100`);
476
+ if (!response || !Array.isArray(response.result))
477
+ throw new Error("Cloudflare preview list returned invalid results");
478
+ const results = response.result.map(preview);
479
+ for (const item of results) {
480
+ if (seen.has(item.id)) throw new Error("Cloudflare preview list repeated a page");
481
+ seen.add(item.id);
482
+ all.push(item);
483
+ }
484
+ const info = response.result_info ? object(response.result_info) : void 0;
485
+ if (typeof info?.total_pages === "number") {
486
+ if (page >= info.total_pages) return all;
487
+ } else if (results.length < 100) return all;
488
+ }
489
+ throw new Error("Cloudflare preview list exceeded pagination limit");
490
+ };
491
+ const deploy = async (input) => {
492
+ const name = identifier(input.name);
493
+ const current = async () => selectPreviewAction(await input.currentPullRequest(), input.commit);
494
+ const initial = await current();
495
+ if (initial !== "deploy") {
496
+ if (initial === "remove") await remove(input.name);
497
+ return { action: initial };
498
+ }
499
+ const manifest = {};
500
+ const blobs = /* @__PURE__ */ new Map();
501
+ for (const file of input.files) {
502
+ if (!file.path.startsWith("/") || file.path.includes("\\") || file.path.split("/").some((part) => part === "." || part === "..") || [...file.path].some((character) => character.charCodeAt(0) < 32) || !file.contentType || manifest[file.path])
503
+ throw new Error("Invalid or duplicate preview asset path");
504
+ const type = new TextEncoder().encode(file.contentType);
505
+ const identity = new Uint8Array(file.bytes.length + type.length + 1);
506
+ identity.set(file.bytes);
507
+ identity.set(type, file.bytes.length + 1);
508
+ const hash = (await digestPreviewBytes(identity)).slice(0, 32);
509
+ manifest[file.path] = { hash, size: file.bytes.length };
510
+ blobs.set(hash, file);
511
+ }
512
+ const configuration = {
513
+ compatibility_date: input.compatibilityDate ?? "2026-01-01",
514
+ assets: {
515
+ html_handling: input.htmlHandling ?? "auto-trailing-slash",
516
+ not_found_handling: input.notFoundHandling ?? "none"
517
+ }
518
+ };
519
+ const tag = await digestPreviewBytes(
520
+ new TextEncoder().encode(
521
+ JSON.stringify([
522
+ input.commit,
523
+ Object.entries(manifest).sort(([a], [b]) => a.localeCompare(b)),
524
+ input.headers ?? "",
525
+ configuration
526
+ ])
527
+ )
528
+ );
529
+ let found = await api("get", `${base}/${name}`, {}, options.token, true);
530
+ if (!found)
531
+ found = await api("create", `${base}?ignore_base_config=true`, json({ name: input.name }));
532
+ if (!found) throw new Error("Cloudflare preview creation failed");
533
+ const resource = preview(found.result);
534
+ const target = `${base}/${identifier(resource.id)}/deployments`;
535
+ const latest = await api("get latest deployment", `${target}/latest`, {}, options.token, true);
536
+ if (latest) {
537
+ const deployment2 = object(latest.result);
538
+ const annotations = deployment2.annotations ? object(deployment2.annotations) : {};
539
+ if (annotations["workers/tag"] === tag && annotations["workers/commit_sha"] === input.commit)
540
+ return { action: "unchanged", preview: resource };
541
+ }
542
+ const session = await api(
543
+ "asset session",
544
+ `/accounts/${account}/workers/scripts/${worker}/assets-upload-session`,
545
+ json({ manifest })
546
+ );
547
+ const upload = object(session?.result);
548
+ if (typeof upload.jwt !== "string" || !Array.isArray(upload.buckets))
549
+ throw new Error("Invalid Cloudflare asset upload session");
550
+ let completion = upload.buckets.length === 0 ? upload.jwt : void 0;
551
+ for (const bucket of upload.buckets) {
552
+ if (!Array.isArray(bucket) || bucket.some((hash) => typeof hash !== "string" || !blobs.has(hash)))
553
+ throw new Error("Cloudflare requested an unknown preview asset");
554
+ const form2 = new FormData();
555
+ for (const hash of bucket) {
556
+ const file = blobs.get(hash);
557
+ if (!file) throw new Error("Missing preview asset");
558
+ form2.append(hash, new Blob([base64(file.bytes)], { type: file.contentType }), hash);
559
+ }
560
+ const result = await api(
561
+ "asset upload",
562
+ `/accounts/${account}/workers/assets/upload?base64=true`,
563
+ { method: "POST", body: form2 },
564
+ upload.jwt
565
+ );
566
+ const body = object(result?.result);
567
+ if (typeof body.jwt === "string") completion = body.jwt;
568
+ }
569
+ if (!completion) throw new Error("Cloudflare asset upload did not complete");
570
+ const final = await current();
571
+ if (final !== "deploy") {
572
+ if (final === "remove") await remove(input.name);
573
+ return { action: final };
574
+ }
575
+ const form = new FormData();
576
+ form.set(
577
+ "metadata",
578
+ JSON.stringify({
579
+ compatibility_date: configuration.compatibility_date,
580
+ assets: { jwt: completion, config: configuration.assets },
581
+ env: {},
582
+ annotations: { "workers/commit_sha": input.commit, "workers/tag": tag }
583
+ })
584
+ );
585
+ if (input.headers !== void 0)
586
+ form.append("files", new File([input.headers], "_headers", { type: "text/plain" }));
587
+ const deployed = await api("deploy", target, { method: "POST", body: form });
588
+ const deployment = object(deployed?.result);
589
+ if (typeof deployment.id !== "string") throw new Error("Invalid Cloudflare deployment response");
590
+ return { action: "deployed", preview: resource, deploymentId: deployment.id };
591
+ };
592
+ return { deploy, list, remove };
593
+ }
594
+
595
+ // src/host.ts
596
+ function createPreviewHost(options) {
597
+ if (!options.artifact) throw new Error("Preview artifact identity is required");
598
+ let state = "starting";
599
+ let generation = 0;
600
+ let system;
601
+ let abort = new AbortController();
602
+ const clients = /* @__PURE__ */ new Set();
603
+ const start = async () => {
604
+ state = "starting";
605
+ try {
606
+ system = await options.boot({ generation, signal: abort.signal });
607
+ if (abort.signal.aborted) {
608
+ await system.dispose?.();
609
+ system = void 0;
610
+ return;
611
+ }
612
+ state = "ready";
613
+ } catch {
614
+ if (!abort.signal.aborted) state = "failed";
615
+ }
616
+ };
617
+ let settled = start();
618
+ const status = () => ({
619
+ state,
620
+ generation,
621
+ artifact: options.artifact,
622
+ clients: clients.size
623
+ });
624
+ const disconnect = () => {
625
+ for (const client of clients) client.dispose();
626
+ clients.clear();
627
+ };
628
+ const fetch2 = async (request) => {
629
+ await settled.catch(() => {
630
+ });
631
+ request.signal.throwIfAborted();
632
+ if (state !== "ready" || !system)
633
+ return Response.json({ error: "preview_not_ready", ...status() }, { status: 503 });
634
+ return system.fetch(request);
635
+ };
636
+ const connect = (port) => {
637
+ if (state === "disposed") throw new Error("Preview host is disposed");
638
+ const client = servePreviewPort(port, fetch2, {
639
+ ...options.allow ? { allow: options.allow } : {},
640
+ onClose: () => clients.delete(client)
641
+ });
642
+ clients.add(client);
643
+ return () => {
644
+ clients.delete(client);
645
+ client.dispose();
646
+ };
647
+ };
648
+ const reset = () => {
649
+ if (state === "disposed") return Promise.reject(new Error("Preview host is disposed"));
650
+ disconnect();
651
+ abort.abort();
652
+ settled = settled.catch(() => {
653
+ }).then(async () => {
654
+ try {
655
+ await system?.dispose?.();
656
+ system = void 0;
657
+ if (state === "disposed") return;
658
+ generation++;
659
+ abort = new AbortController();
660
+ await start();
661
+ } catch (error) {
662
+ if (state !== "disposed") state = "failed";
663
+ throw error;
664
+ }
665
+ });
666
+ return settled;
667
+ };
668
+ const dispose = async () => {
669
+ state = "disposed";
670
+ disconnect();
671
+ abort.abort();
672
+ await settled.catch(() => {
673
+ });
674
+ try {
675
+ await system?.dispose?.();
676
+ system = void 0;
677
+ } finally {
678
+ state = "disposed";
679
+ }
680
+ };
681
+ return { connect, fetch: fetch2, reset, dispose, status, ready: () => settled };
682
+ }
683
+ function sharedPreviewWorkerName(identity) {
684
+ if (!identity.application || !identity.artifact || !Number.isSafeInteger(identity.generation) || identity.generation < 0)
685
+ throw new Error("Invalid preview worker identity");
686
+ return JSON.stringify([
687
+ "mockingbird-preview",
688
+ identity.application,
689
+ identity.artifact,
690
+ identity.generation
691
+ ]);
692
+ }
693
+
694
+ // src/sandbox.ts
695
+ var withoutTrailingSlashes = (value) => {
696
+ let end = value.length;
697
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end--;
698
+ return value.slice(0, end);
699
+ };
700
+ var SANDBOX_STORAGE_KEYS = {
701
+ accessKey: "mockingbird.sandbox.access-key",
702
+ modes: "mockingbird.sandbox.modes"
703
+ };
704
+ var SANDBOX_MESSAGES = {
705
+ none: "No sandbox proxy is configured for this preview",
706
+ off: "The proxy has no SANDBOX_PROXY_TOKEN, so sandbox mode is off",
707
+ locked: "Enter the sandbox access key",
708
+ ready: "Sandbox access is granted: switch a service to send its requests to the vendor's sandbox"
709
+ };
710
+ var unreachableMessage = (endpoint) => `The sandbox proxy at ${endpoint} did not answer`;
711
+ var memoryStorage = () => {
712
+ const values = /* @__PURE__ */ new Map();
713
+ return {
714
+ getItem: (key) => values.get(key) ?? null,
715
+ setItem: (key, value) => void values.set(key, value),
716
+ removeItem: (key) => void values.delete(key)
717
+ };
718
+ };
719
+ var safeStorage = (storage) => {
720
+ const fallback = memoryStorage();
721
+ const resolve = () => {
722
+ if (storage) return storage;
723
+ try {
724
+ const local = globalThis.localStorage;
725
+ if (local) return local;
726
+ } catch {
727
+ }
728
+ return fallback;
729
+ };
730
+ return {
731
+ getItem: (key) => {
732
+ try {
733
+ return resolve().getItem(key);
734
+ } catch {
735
+ return fallback.getItem(key);
736
+ }
737
+ },
738
+ setItem: (key, value) => {
739
+ try {
740
+ resolve().setItem(key, value);
741
+ } catch {
742
+ fallback.setItem(key, value);
743
+ }
744
+ },
745
+ removeItem: (key) => {
746
+ try {
747
+ resolve().removeItem(key);
748
+ } catch {
749
+ }
750
+ fallback.removeItem(key);
751
+ }
752
+ };
753
+ };
754
+ var resolveProxyUrl = (proxyUrl) => {
755
+ if (proxyUrl === void 0 || proxyUrl.trim() === "") return void 0;
756
+ const origin = globalThis.location?.origin;
757
+ let url;
758
+ try {
759
+ url = origin ? new URL(proxyUrl, origin) : new URL(proxyUrl);
760
+ } catch {
761
+ throw new Error(
762
+ `sandbox proxyUrl ${JSON.stringify(proxyUrl)} must be absolute outside a browser page`
763
+ );
764
+ }
765
+ url.search = "";
766
+ url.hash = "";
767
+ return withoutTrailingSlashes(url.toString());
768
+ };
769
+ var NO_PROXY_BASE = "https://sandbox-proxy.invalid";
770
+ var errorMessage = async (response, fallback) => {
771
+ try {
772
+ const body = await response.json();
773
+ const error = body.error;
774
+ if (typeof error === "string") return error;
775
+ if (error && typeof error === "object" && "message" in error)
776
+ return String(error.message);
777
+ } catch {
778
+ }
779
+ return fallback;
780
+ };
781
+ var readMode = async (spec) => {
782
+ try {
783
+ const response = await spec.admin(new Request("http://mockingbird.local/__admin/upstream"));
784
+ if (!response.ok) return "emulated";
785
+ const body = await response.json();
786
+ return body.mode === "forward" ? "sandbox" : "emulated";
787
+ } catch {
788
+ return "emulated";
789
+ }
790
+ };
791
+ var writeMode = (spec, mode) => spec.admin(
792
+ new Request("http://mockingbird.local/__admin/upstream", {
793
+ method: "PUT",
794
+ headers: { "content-type": "application/json" },
795
+ body: JSON.stringify({ mode: mode === "sandbox" ? "forward" : "emulated" })
796
+ })
797
+ );
798
+ var createSandbox = (options = {}) => {
799
+ const endpoint = resolveProxyUrl(options.proxyUrl);
800
+ const storage = safeStorage(options.storage);
801
+ const send = options.fetch ?? ((request) => globalThis.fetch(request));
802
+ const accessKey = () => storage.getItem(SANDBOX_STORAGE_KEYS.accessKey) || null;
803
+ const storedModes = () => {
804
+ try {
805
+ const value = JSON.parse(storage.getItem(SANDBOX_STORAGE_KEYS.modes) ?? "{}");
806
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
807
+ return Object.fromEntries(
808
+ Object.entries(value).filter(([, mode]) => mode === "sandbox")
809
+ );
810
+ } catch {
811
+ return {};
812
+ }
813
+ };
814
+ const storeMode = (id, mode) => {
815
+ const modes = storedModes();
816
+ if (mode === "sandbox") modes[id] = "sandbox";
817
+ else delete modes[id];
818
+ storage.setItem(SANDBOX_STORAGE_KEYS.modes, JSON.stringify(modes));
819
+ };
820
+ const withKey = (request) => {
821
+ const out = new Request(request);
822
+ const key = accessKey();
823
+ if (key) out.headers.set(SANDBOX_KEY_HEADER, key);
824
+ else out.headers.delete(SANDBOX_KEY_HEADER);
825
+ return out;
826
+ };
827
+ const upstream = (id) => ({
828
+ baseUrl: `${endpoint ?? NO_PROXY_BASE}/${encodeURIComponent(id)}`,
829
+ fetch: async (request) => {
830
+ if (!endpoint)
831
+ return Response.json(
832
+ { error: { code: "sandbox_unavailable", message: SANDBOX_MESSAGES.none } },
833
+ { status: 503 }
834
+ );
835
+ return send(withKey(request));
836
+ },
837
+ rewriteAuth: (request) => {
838
+ const out = new Request(request);
839
+ out.headers.delete("authorization");
840
+ out.headers.delete("cookie");
841
+ return out;
842
+ }
843
+ });
844
+ const readManifest = async () => {
845
+ if (!endpoint) return { status: { state: "none", message: SANDBOX_MESSAGES.none } };
846
+ let manifest;
847
+ try {
848
+ const response = await send(withKey(new Request(`${endpoint}/`)));
849
+ if (!response.ok) throw new Error(`status ${response.status}`);
850
+ manifest = await response.json();
851
+ if (!manifest || !Array.isArray(manifest.providers)) throw new Error("not a manifest");
852
+ } catch {
853
+ return {
854
+ status: { state: "unreachable", message: unreachableMessage(endpoint), endpoint }
855
+ };
856
+ }
857
+ const status = manifest.access === "granted" ? { state: "ready", message: SANDBOX_MESSAGES.ready, endpoint } : manifest.access === "denied" ? { state: "locked", message: SANDBOX_MESSAGES.locked, endpoint } : { state: "off", message: SANDBOX_MESSAGES.off, endpoint };
858
+ return { status, manifest };
859
+ };
860
+ const reason = (spec, { status, manifest }) => {
861
+ if (spec.unsupported) return spec.unsupported;
862
+ if (status.state !== "ready") return status.message;
863
+ const provider = manifest?.providers.find((candidate) => candidate.id === spec.id);
864
+ if (!provider) return `The sandbox proxy does not offer ${spec.label}`;
865
+ if (provider.missing.length > 0) return `Missing ${provider.missing.join(", ")} on the proxy`;
866
+ if (provider.error) return provider.error;
867
+ if (!provider.configured) return `${spec.label} is not configured on the sandbox proxy`;
868
+ return void 0;
869
+ };
870
+ const controls = (services) => {
871
+ const specs = new Map(services.map((spec) => [spec.id, spec]));
872
+ let restored = false;
873
+ const find = (id) => {
874
+ const spec = specs.get(id);
875
+ if (!spec) throw new Error(`Unknown service ${id}`);
876
+ return spec;
877
+ };
878
+ const apply = async (spec, mode) => {
879
+ const response = await writeMode(spec, mode);
880
+ if (response.ok) return;
881
+ if (mode === "emulated" && await readMode(spec) === "emulated") return;
882
+ throw new Error(
883
+ await errorMessage(
884
+ response,
885
+ `${spec.label} could not switch to ${mode} (status ${response.status})`
886
+ )
887
+ );
888
+ };
889
+ return {
890
+ list: async () => {
891
+ const state = await readManifest();
892
+ if (!restored) {
893
+ restored = true;
894
+ const stored = storedModes();
895
+ await Promise.all(
896
+ services.map(async (spec) => {
897
+ if (stored[spec.id] !== "sandbox" || reason(spec, state) !== void 0) return;
898
+ if (await readMode(spec) === "sandbox") return;
899
+ await apply(spec, "sandbox").catch(() => {
900
+ });
901
+ })
902
+ );
903
+ }
904
+ const rows = await Promise.all(
905
+ services.map(async (spec) => {
906
+ const unavailable = reason(spec, state);
907
+ return {
908
+ id: spec.id,
909
+ label: spec.label,
910
+ ...spec.category !== void 0 ? { category: spec.category } : {},
911
+ mode: await readMode(spec),
912
+ ...unavailable !== void 0 ? { unavailable } : {}
913
+ };
914
+ })
915
+ );
916
+ return { sandbox: state.status, services: rows };
917
+ },
918
+ setMode: async (id, mode) => {
919
+ const spec = find(id);
920
+ if (mode === "sandbox") {
921
+ const why = reason(spec, await readManifest());
922
+ if (why !== void 0) throw new Error(why);
923
+ } else if (mode !== "emulated") throw new Error(`Unknown mode ${String(mode)}`);
924
+ await apply(spec, mode);
925
+ storeMode(id, mode);
926
+ },
927
+ setAccessKey: async (key) => {
928
+ const value = key?.trim();
929
+ if (value) storage.setItem(SANDBOX_STORAGE_KEYS.accessKey, value);
930
+ else storage.removeItem(SANDBOX_STORAGE_KEYS.accessKey);
931
+ },
932
+ hasAccessKey: () => accessKey() !== null
933
+ };
934
+ };
935
+ return { upstream, controls };
936
+ };
937
+
938
+ // src/worker.ts
939
+ function connectSharedPreviewWorker(url, options) {
940
+ const worker = new SharedWorker(url, { type: "module", name: sharedPreviewWorkerName(options) });
941
+ const client = createPreviewClient(
942
+ worker.port,
943
+ options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
944
+ );
945
+ const failed = () => client.dispose();
946
+ worker.addEventListener("error", failed);
947
+ return {
948
+ fetch: client.fetch,
949
+ get pending() {
950
+ return client.pending;
951
+ },
952
+ worker,
953
+ dispose: () => {
954
+ worker.removeEventListener("error", failed);
955
+ client.dispose();
956
+ }
957
+ };
958
+ }
959
+ function connectDedicatedPreviewWorker(url, options = {}) {
960
+ const worker = new Worker(url, { type: "module" });
961
+ const channel = new MessageChannel();
962
+ const client = createPreviewClient(channel.port1, options);
963
+ const failed = () => client.dispose();
964
+ worker.addEventListener("error", failed);
965
+ worker.postMessage({ type: "mockingbird-preview-connect" }, [channel.port2]);
966
+ return {
967
+ fetch: client.fetch,
968
+ get pending() {
969
+ return client.pending;
970
+ },
971
+ worker,
972
+ dispose: () => {
973
+ worker.removeEventListener("error", failed);
974
+ client.dispose();
975
+ worker.terminate();
976
+ }
977
+ };
978
+ }
979
+ function installPreviewWorkerHost(host, scope) {
980
+ const shared = (event) => {
981
+ for (const port of event.ports) host.connect(port);
982
+ };
983
+ const dedicated = (event) => {
984
+ if (event.data?.type === "mockingbird-preview-connect") shared(event);
985
+ };
986
+ scope.addEventListener("connect", shared);
987
+ scope.addEventListener("message", dedicated);
988
+ return async () => {
989
+ scope.removeEventListener("connect", shared);
990
+ scope.removeEventListener("message", dedicated);
991
+ await host.dispose();
992
+ };
993
+ }
994
+ export {
995
+ SANDBOX_KEY_HEADER,
996
+ SANDBOX_MESSAGES,
997
+ SANDBOX_STORAGE_KEYS,
998
+ connectDedicatedPreviewWorker,
999
+ connectSharedPreviewWorker,
1000
+ createCloudflarePreviews,
1001
+ createPreviewArtifact,
1002
+ createPreviewClient,
1003
+ createPreviewHost,
1004
+ createSandbox,
1005
+ createSandboxProxy,
1006
+ digestPreviewBytes,
1007
+ installPreviewWorkerHost,
1008
+ loadPreviewArtifact,
1009
+ parsePreviewArtifact,
1010
+ planPreviewSweep,
1011
+ safeEqual,
1012
+ sandboxProviders,
1013
+ sandboxProxyWorker,
1014
+ selectPreviewAction,
1015
+ servePreviewPort,
1016
+ sharedPreviewWorkerName
1017
+ };
1018
+ //# sourceMappingURL=index.js.map