@vite-hub/sandbox 0.0.4 → 0.3.0

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.
Files changed (67) hide show
  1. package/README.md +395 -37
  2. package/dist/abortable-CR01hzfi.js +57 -0
  3. package/dist/cloudflare-Cog_r2Me.js +910 -0
  4. package/dist/cloudflare-env-lookup-DzI6Xv1Y.js +16 -0
  5. package/dist/cloudflare-failure-CFQhalfh.js +50 -0
  6. package/dist/container-CqfD8yuE.js +868 -0
  7. package/dist/crabbox-sbV3Zjuo.js +1110 -0
  8. package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
  9. package/dist/error-diagnostics-BJtLRL9w.js +536 -0
  10. package/dist/file-listing-CHtRrfo1.js +26 -0
  11. package/dist/file-lock-D0-XPogS.js +74 -0
  12. package/dist/index-DsoQAUb7.d.ts +594 -0
  13. package/dist/index.d.ts +2 -69
  14. package/dist/index.js +281 -1182
  15. package/dist/internal/cloudflare.d.ts +176 -0
  16. package/dist/internal/cloudflare.js +8 -0
  17. package/dist/internal/host-toolchain.d.ts +22 -0
  18. package/dist/internal/host-toolchain.js +96 -0
  19. package/dist/internal/vercel.d.ts +4 -0
  20. package/dist/internal/vercel.js +8 -0
  21. package/dist/invariant-DolT9EEx.js +22 -0
  22. package/dist/module-types-B0LQ5H2S.js +7 -0
  23. package/dist/module-types-DCeJbS9Z.d.ts +110 -0
  24. package/dist/process-sweep-CMaujWE5.js +33 -0
  25. package/dist/provider-resolution-C6AQzuFG.js +133 -0
  26. package/dist/remote-70ZVZZlq.js +265 -0
  27. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  28. package/dist/runtime-DHp6ImeP.js +32 -0
  29. package/dist/runtime-type-Deo4qzxN.js +9 -0
  30. package/dist/session-e0lyzjJ3.js +338 -0
  31. package/dist/shell-quote-Q3u3plif.js +6 -0
  32. package/dist/size-7AkVwGZb.js +118 -0
  33. package/dist/ssh.d.ts +63 -0
  34. package/dist/ssh.js +286 -0
  35. package/dist/task/index.d.ts +69 -0
  36. package/dist/task/index.js +1414 -0
  37. package/dist/task/runtime/empty-registry.d.ts +6 -0
  38. package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
  39. package/dist/task/runtime/provider-loader.d.ts +18 -0
  40. package/dist/task/runtime/provider-loader.js +16 -0
  41. package/dist/task/runtime/providers/cloudflare.d.ts +14 -0
  42. package/dist/task/runtime/providers/cloudflare.js +27 -0
  43. package/dist/task/runtime/providers/vercel.d.ts +12 -0
  44. package/dist/task/runtime/providers/vercel.js +85 -0
  45. package/dist/task/runtime/state.d.ts +27 -0
  46. package/dist/task/runtime/state.js +82 -0
  47. package/dist/task/vite.d.ts +486 -0
  48. package/dist/task/vite.js +3966 -0
  49. package/dist/toolchain-BIVGMRty.js +528 -0
  50. package/dist/trusted-host-kxkpaQcs.js +714 -0
  51. package/dist/vercel-BGGrNpza.js +352 -0
  52. package/package.json +105 -51
  53. package/dist/cloudflare-env-QQV4uzCT.js +0 -14
  54. package/dist/module-types-DKYItiOu.d.ts +0 -93
  55. package/dist/module-types-Dj1MFmHT.js +0 -7
  56. package/dist/provider-loader-D0UihePq.d.ts +0 -21
  57. package/dist/runtime/empty-registry.d.ts +0 -6
  58. package/dist/runtime/provider-loader.d.ts +0 -2
  59. package/dist/runtime/provider-loader.js +0 -15
  60. package/dist/runtime/providers/cloudflare.d.ts +0 -29
  61. package/dist/runtime/providers/cloudflare.js +0 -25
  62. package/dist/runtime/providers/vercel.d.ts +0 -121
  63. package/dist/runtime/providers/vercel.js +0 -51
  64. package/dist/runtime/state.d.ts +0 -26
  65. package/dist/runtime/state.js +0 -72
  66. package/dist/vite.d.ts +0 -48
  67. package/dist/vite.js +0 -3324
@@ -0,0 +1,910 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
+ import { r as markBuiltInSandboxRuntime } from "./runtime-DHp6ImeP.js";
3
+ import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
4
+ import { n as invariantError } from "./invariant-DolT9EEx.js";
5
+ import { t as shellQuote } from "./shell-quote-Q3u3plif.js";
6
+ import { t as listCommandFiles } from "./file-listing-CHtRrfo1.js";
7
+ import { i as resolveRemoteEnvironment, n as openRemoteSandbox, o as snapshotStream, r as remoteSandboxPlan } from "./remote-70ZVZZlq.js";
8
+ import { n as cloudflareRetryDelays, r as readCloudflareFailure, t as canRetryCloudflareRequest } from "./cloudflare-failure-CFQhalfh.js";
9
+ import { n as killOnAbort } from "./abortable-CR01hzfi.js";
10
+ //#region src/internal/cloudflare-transport.ts
11
+ const cloudflareControlPlaneTimeout = 15e3;
12
+ const cloudflareReadTimeout = 15e3;
13
+ const cloudflareStopTimeout = 1e4;
14
+ /**
15
+ * Runs one Sandbox Durable Object request with a deadline.
16
+ * A failure exposes the host's `retryable` flag as `error.data.retryable` and the host error as `cause`.
17
+ */
18
+ async function withCloudflareRequest(operation, options, run) {
19
+ const { signal, timeout } = options;
20
+ signal?.throwIfAborted();
21
+ for (let attempt = 0; attempt <= cloudflareRetryDelays.length; attempt++) try {
22
+ return await withDeadline(operation, timeout, run, signal);
23
+ } catch (error) {
24
+ if (signal?.aborted) throw signal.reason;
25
+ const failure = readCloudflareFailure(error);
26
+ if (attempt === cloudflareRetryDelays.length || !canRetryCloudflareRequest(failure, options.idempotent)) throw sandboxErrorDiagnostics.SANDBOX_R0088({
27
+ message: `[vitehub] Cloudflare Sandbox ${operation} failed: ${failure.message.trim()}`,
28
+ cause: error,
29
+ retryable: failure.retryable
30
+ });
31
+ await waitForRetry(cloudflareRetryDelays[attempt], signal);
32
+ }
33
+ throw invariantError("the last Cloudflare Sandbox attempt returns or throws SANDBOX_R0088, so the retry loop never ends");
34
+ }
35
+ async function withDeadline(operation, timeout, run, signal) {
36
+ signal?.throwIfAborted();
37
+ let timer;
38
+ let onAbort;
39
+ try {
40
+ return await Promise.race([
41
+ run(),
42
+ new Promise((_, reject) => {
43
+ timer = setTimeout(() => reject(sandboxErrorDiagnostics.SANDBOX_R0090({ message: `[vitehub] Cloudflare Sandbox ${operation} timed out after ${timeout}ms.` })), timeout);
44
+ }),
45
+ ...signal ? [new Promise((_, reject) => {
46
+ onAbort = () => reject(signal.reason);
47
+ signal.addEventListener("abort", onAbort, { once: true });
48
+ })] : []
49
+ ]);
50
+ } finally {
51
+ if (timer) clearTimeout(timer);
52
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
53
+ }
54
+ }
55
+ async function waitForRetry(timeout, signal) {
56
+ if (!signal) return await new Promise((resolve) => setTimeout(resolve, timeout));
57
+ await new Promise((resolve, reject) => {
58
+ const timer = setTimeout(() => {
59
+ signal.removeEventListener("abort", onAbort);
60
+ resolve();
61
+ }, timeout);
62
+ const onAbort = () => {
63
+ clearTimeout(timer);
64
+ reject(signal.reason);
65
+ };
66
+ signal.addEventListener("abort", onAbort, { once: true });
67
+ });
68
+ }
69
+ //#endregion
70
+ //#region src/internal/cloudflare-durable-object.ts
71
+ const configurationKey = "vitehub:configuration";
72
+ const defaultSleepAfter = 6e5;
73
+ const keepAliveTimeout = 216e5;
74
+ const fileOptions = { cwd: "/workspace" };
75
+ const maxBufferedOutput = 8388608;
76
+ const maxCancelledExecs = 1024;
77
+ const signals = {
78
+ ALRM: 14,
79
+ HUP: 1,
80
+ INT: 2,
81
+ KILL: 9,
82
+ QUIT: 3,
83
+ TERM: 15,
84
+ USR1: 10,
85
+ USR2: 12
86
+ };
87
+ const timedExecShell = `
88
+ exec 3> >(cat)
89
+ stdoutPid=$!
90
+ exec 4> >(cat >&2 3>&-)
91
+ stderrPid=$!
92
+ /bin/bash -c "$1" >&3 2>&4 3>&- 4>&-
93
+ status=$?
94
+ exec 3>&- 4>&-
95
+ wait "$stdoutPid" "$stderrPid"
96
+ exit "$status"
97
+ `;
98
+ const processGroupShell = `
99
+ { exec 5<&0; } 2>/dev/null || exec 5</dev/null
100
+ set -m
101
+ /bin/bash -c "$1" <&5 5<&- &
102
+ printf '%s' "$!" > "$2"
103
+ exec 2>/dev/null 5<&-
104
+ wait "$!"
105
+ status=$?
106
+ rm -f -- "$2"
107
+ exit "$status"
108
+ `;
109
+ const killProcessGroupShell = `
110
+ for _ in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do test -s "$2" && break; sleep 0.1; done
111
+ test -s "$2" || exit 0
112
+ kill -"$1" -- "-$(cat -- "$2")" 2>/dev/null || true
113
+ `;
114
+ var SandboxProcessRecord = class {
115
+ process;
116
+ exited;
117
+ finished = false;
118
+ #events = [];
119
+ #listeners = /* @__PURE__ */ new Set();
120
+ #output = {
121
+ stderr: "",
122
+ stdout: ""
123
+ };
124
+ #buffered = 0;
125
+ #done = false;
126
+ constructor(process) {
127
+ this.process = process;
128
+ const pumps = ["stdout", "stderr"].map((type) => this.#pump(type, process[type]));
129
+ this.exited = process.exitCode;
130
+ this.exited.finally(() => {
131
+ this.finished = true;
132
+ }).catch(() => void 0);
133
+ Promise.allSettled(pumps).then(async (results) => {
134
+ for (const result of results) if (result.status === "rejected") throw result.reason;
135
+ return {
136
+ exitCode: await process.exitCode,
137
+ type: "exit"
138
+ };
139
+ }).catch((error) => ({
140
+ data: error instanceof Error ? error.message : String(error),
141
+ type: "error"
142
+ })).then((event) => {
143
+ this.#emit(event);
144
+ this.#done = true;
145
+ this.#listeners.clear();
146
+ });
147
+ }
148
+ logs() {
149
+ return { ...this.#output };
150
+ }
151
+ /** Server-sent events: buffered output, then live output, then `exit`. Same format as @cloudflare/sandbox 0.12. */
152
+ stream() {
153
+ const encoder = new TextEncoder();
154
+ let listener;
155
+ return new ReadableStream({
156
+ type: "bytes",
157
+ start: (controller) => {
158
+ const send = (event) => {
159
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
160
+ if (event.type === "exit" || event.type === "error") controller.close();
161
+ };
162
+ for (const event of this.#events) send(event);
163
+ if (this.#done) return;
164
+ listener = send;
165
+ this.#listeners.add(listener);
166
+ },
167
+ cancel: () => {
168
+ if (listener) this.#listeners.delete(listener);
169
+ }
170
+ });
171
+ }
172
+ async #pump(type, stream) {
173
+ if (!stream) return;
174
+ const decoder = new TextDecoder();
175
+ for await (const chunk of stream) {
176
+ const data = decoder.decode(chunk, { stream: true });
177
+ if (data) this.#append(type, data);
178
+ }
179
+ const rest = decoder.decode();
180
+ if (rest) this.#append(type, rest);
181
+ }
182
+ #append(type, data) {
183
+ this.#output[type] += data;
184
+ if (this.#output[type].length > maxBufferedOutput) this.#output[type] = this.#output[type].slice(-8388608);
185
+ this.#emit({
186
+ data,
187
+ type
188
+ });
189
+ }
190
+ #emit(event) {
191
+ this.#events.push(event);
192
+ this.#buffered += "data" in event ? event.data.length : 0;
193
+ while (this.#buffered > 2 * maxBufferedOutput && this.#events.length > 1) {
194
+ const dropped = this.#events.shift();
195
+ this.#buffered -= "data" in dropped ? dropped.data.length : 0;
196
+ }
197
+ for (const listener of this.#listeners) listener(event);
198
+ }
199
+ };
200
+ /**
201
+ * The Worker entrypoint that receives the intercepted HTTP and HTTPS requests of a Sandbox Container.
202
+ * Cloudflare picks an HTTPS intercept by TLS SNI, but the request URL comes from the Host header that the
203
+ * Container sends. So the entrypoint checks the URL against the allowlist again before it fetches.
204
+ */
205
+ function createCloudflareSandboxOutbound(dependencies) {
206
+ const { WorkerEntrypoint } = dependencies;
207
+ return class ViteHubCloudflareSandboxOutbound extends WorkerEntrypoint {
208
+ #allow;
209
+ constructor(ctx, env) {
210
+ super(ctx, env);
211
+ this.#allow = ctx.props?.allow ?? [];
212
+ }
213
+ async fetch(request) {
214
+ const host = new URL(request.url).hostname;
215
+ if (!allowsHost(this.#allow, host)) return new Response(`[vitehub] ${host} is not in the Sandbox networkPolicy.\n`, { status: 403 });
216
+ return await fetch(request);
217
+ }
218
+ };
219
+ }
220
+ /** Whether an allowlist entry matches the host. `*.example.com` matches subdomains only. */
221
+ function allowsHost(allow, hostname) {
222
+ const host = hostname.toLowerCase().replace(/\.$/, "");
223
+ return allow.some((entry) => entry.startsWith("*.") ? host.endsWith(entry.slice(1)) && host.length > entry.length - 1 : host === entry);
224
+ }
225
+ function createCloudflareSandboxDurableObject(dependencies) {
226
+ const { DurableObject, Files, outboundEntrypoint, SandboxFileError } = dependencies;
227
+ const missing = (cause) => SandboxFileError.is(cause) && cause.code === "ENOENT";
228
+ return class ViteHubCloudflareSandbox extends DurableObject {
229
+ #ctx;
230
+ #processes = /* @__PURE__ */ new Map();
231
+ #execs = /* @__PURE__ */ new Map();
232
+ #cancelled = /* @__PURE__ */ new Set();
233
+ #configuration;
234
+ #files;
235
+ #starting;
236
+ constructor(ctx, env) {
237
+ super(ctx, env);
238
+ this.#ctx = ctx;
239
+ }
240
+ /**
241
+ * Stores the idle and network policy. The idle policy applies now when the Container runs, otherwise when it starts.
242
+ * The network is fixed when the Container starts, so a running Container with another network policy stops.
243
+ */
244
+ async configure(configuration) {
245
+ const running = this.#ctx.container?.running === true;
246
+ const previous = running ? await this.#readConfiguration() : void 0;
247
+ this.#configuration = Promise.resolve(configuration);
248
+ await this.#ctx.storage.put(configurationKey, configuration);
249
+ if (!running) return;
250
+ if (networkKey(previous?.networkPolicy) !== networkKey(configuration.networkPolicy)) await this.destroy();
251
+ else await this.#applyIdlePolicy(configuration);
252
+ }
253
+ async destroy() {
254
+ for (const record of this.#processes.values()) record.process.kill(signals.KILL);
255
+ this.#processes.clear();
256
+ const container = this.#container();
257
+ if (container.running) await container.destroy();
258
+ }
259
+ async cancelExec(id) {
260
+ const exec = this.#execs.get(id);
261
+ if (!exec) {
262
+ this.#cancelled.add(id);
263
+ if (this.#cancelled.size > maxCancelledExecs) this.#cancelled.delete(this.#cancelled.values().next().value);
264
+ return;
265
+ }
266
+ exec.process.kill(exec.timed ? signals.ALRM : signals.KILL);
267
+ }
268
+ async exec(command, options = {}) {
269
+ const container = await this.#running();
270
+ if (options.id && this.#cancelled.delete(options.id)) throw new DOMException("Command was cancelled before it started.", "AbortError");
271
+ let timedOut = false;
272
+ const timer = options.timeout ? setTimeout(() => {
273
+ timedOut = true;
274
+ }, options.timeout) : void 0;
275
+ try {
276
+ const commandLine = [
277
+ "/bin/bash",
278
+ "-c",
279
+ command
280
+ ];
281
+ const process = await container.exec(options.timeout ? [
282
+ "timeout",
283
+ "--signal=KILL",
284
+ `${options.timeout / 1e3}s`,
285
+ "/bin/bash",
286
+ "-c",
287
+ timedExecShell,
288
+ "--",
289
+ command
290
+ ] : commandLine, execOptions(options));
291
+ if (options.id) {
292
+ this.#execs.set(options.id, {
293
+ process,
294
+ timed: Boolean(options.timeout)
295
+ });
296
+ if (this.#cancelled.delete(options.id)) await this.cancelExec(options.id);
297
+ }
298
+ const output = await process.output();
299
+ if (timedOut) throw sandboxErrorDiagnostics.SANDBOX_CLOUDFLARE_COMMAND_TIMED_OUT({ timeout: options.timeout ?? 0 });
300
+ const decoder = new TextDecoder();
301
+ return {
302
+ exitCode: output.exitCode,
303
+ stderr: decoder.decode(output.stderr),
304
+ stdout: decoder.decode(output.stdout),
305
+ success: output.exitCode === 0
306
+ };
307
+ } finally {
308
+ clearTimeout(timer);
309
+ if (options.id) this.#execs.delete(options.id);
310
+ }
311
+ }
312
+ async deleteFile(path) {
313
+ try {
314
+ await (await this.#fileOperations()).remove(path, fileOptions);
315
+ } catch (error) {
316
+ if (!missing(error)) throw error;
317
+ }
318
+ return { success: true };
319
+ }
320
+ async exists(path) {
321
+ try {
322
+ await (await this.#fileOperations()).stat(path, fileOptions);
323
+ return { exists: true };
324
+ } catch (error) {
325
+ if (missing(error)) return { exists: false };
326
+ throw error;
327
+ }
328
+ }
329
+ async mkdir(path, options = {}) {
330
+ await (await this.#fileOperations()).mkdir(path, {
331
+ ...fileOptions,
332
+ recursive: options.recursive
333
+ });
334
+ return { success: true };
335
+ }
336
+ async moveFile(source, destination) {
337
+ await (await this.#fileOperations()).rename(source, destination, fileOptions);
338
+ return { success: true };
339
+ }
340
+ async readFile(path, options = {}) {
341
+ let response;
342
+ try {
343
+ response = await (await this.#fileOperations()).readFile(path, fileOptions);
344
+ } catch (error) {
345
+ if (missing(error)) return {
346
+ content: "",
347
+ success: false
348
+ };
349
+ throw error;
350
+ }
351
+ const bytes = new Uint8Array(await response.arrayBuffer());
352
+ return {
353
+ content: options.encoding === "base64" ? encodeBase64$1(bytes) : new TextDecoder().decode(bytes),
354
+ success: true
355
+ };
356
+ }
357
+ async writeFile(path, contents, options = {}) {
358
+ const bytes = options.encoding === "base64" ? decodeBase64$1(contents) : new TextEncoder().encode(contents);
359
+ await (await this.#fileOperations()).writeFile(path, bytes, fileOptions);
360
+ return { success: true };
361
+ }
362
+ async startProcess(command, options = {}) {
363
+ const container = await this.#running();
364
+ const id = crypto.randomUUID();
365
+ const groupFile = `/tmp/vitehub-process-${id}.pgid`;
366
+ const process = await container.exec([
367
+ "/bin/bash",
368
+ "-c",
369
+ processGroupShell,
370
+ "--",
371
+ command,
372
+ groupFile
373
+ ], {
374
+ ...execOptions(options),
375
+ ...options.stdin ? { stdin: "pipe" } : {}
376
+ });
377
+ const record = new SandboxProcessRecord(process);
378
+ this.#processes.set(id, record);
379
+ const kill = async (signal) => {
380
+ const number = signalNumber(signal);
381
+ if (record.finished) return;
382
+ await (await container.exec([
383
+ "/bin/bash",
384
+ "-c",
385
+ killProcessGroupShell,
386
+ "--",
387
+ String(number),
388
+ groupFile
389
+ ], {
390
+ stderr: "ignore",
391
+ stdout: "ignore"
392
+ })).exitCode;
393
+ };
394
+ return {
395
+ id,
396
+ getLogs: async () => record.logs(),
397
+ kill,
398
+ ...options.stdin && process.stdin ? { stdin: process.stdin } : {},
399
+ waitForExit: async () => ({ exitCode: await record.exited })
400
+ };
401
+ }
402
+ async streamProcessLogs(processId) {
403
+ const record = this.#processes.get(processId);
404
+ if (!record) throw sandboxErrorDiagnostics.SANDBOX_CLOUDFLARE_PROCESS_NOT_FOUND({ processId });
405
+ const stream = record.stream();
406
+ record.exited.finally(() => this.#processes.delete(processId)).catch(() => void 0);
407
+ return stream;
408
+ }
409
+ #container() {
410
+ const container = this.#ctx.container;
411
+ if (!container) throw sandboxErrorDiagnostics.SANDBOX_CLOUDFLARE_CONTAINER_MISSING();
412
+ return container;
413
+ }
414
+ async #running() {
415
+ const container = this.#container();
416
+ if (!this.#starting && !container.running) this.#starting = this.#start(container).finally(() => {
417
+ this.#starting = void 0;
418
+ });
419
+ if (this.#starting) await this.#starting;
420
+ return container;
421
+ }
422
+ async #start(container) {
423
+ const configuration = await this.#readConfiguration();
424
+ const network = configuration.networkPolicy ?? "allow-all";
425
+ const outbound = typeof network === "object" ? this.#outboundHandler(container, network.allow) : void 0;
426
+ container.start({ enableInternet: network === "allow-all" });
427
+ try {
428
+ if (typeof network === "object") for (const host of network.allow) {
429
+ await container.interceptOutboundHttp(host, outbound);
430
+ await container.interceptOutboundHttps(host, outbound);
431
+ }
432
+ await this.#applyIdlePolicy(configuration);
433
+ } catch (error) {
434
+ if (typeof network === "object") await container.destroy().catch(() => void 0);
435
+ throw error;
436
+ }
437
+ }
438
+ #outboundHandler(container, allow) {
439
+ const entrypoint = outboundEntrypoint ? this.#ctx.exports?.[outboundEntrypoint] : void 0;
440
+ if (typeof entrypoint !== "function") throw new Error(`[vitehub] Cloudflare Sandbox networkPolicy { allow } needs the ${JSON.stringify(outboundEntrypoint ?? "SandboxOutbound")} entrypoint in ctx.exports. Set compatibility_date to 2025-11-17 or later, or add the enable_ctx_exports compatibility flag, and build the Worker with ViteHub.`);
441
+ if (!container.interceptOutboundHttp || !container.interceptOutboundHttps) throw new Error("[vitehub] This Workers runtime cannot intercept Container traffic, so Cloudflare Sandbox networkPolicy { allow } is not available. Update Wrangler.");
442
+ return entrypoint({ props: { allow: [...allow] } });
443
+ }
444
+ async #fileOperations() {
445
+ const container = await this.#running();
446
+ this.#files ??= new Files(container);
447
+ return this.#files;
448
+ }
449
+ async #readConfiguration() {
450
+ if (!this.#configuration) {
451
+ const reading = this.#ctx.storage.get(configurationKey).then((value) => value ?? {}).catch((error) => {
452
+ if (this.#configuration === reading) this.#configuration = void 0;
453
+ throw error;
454
+ });
455
+ this.#configuration = reading;
456
+ }
457
+ return await this.#configuration;
458
+ }
459
+ async #applyIdlePolicy(configuration) {
460
+ await this.#container().setInactivityTimeout(configuration.keepAlive ? keepAliveTimeout : parseDuration(configuration.sleepAfter) ?? defaultSleepAfter);
461
+ }
462
+ };
463
+ }
464
+ function networkKey(policy) {
465
+ return JSON.stringify(policy ?? "allow-all");
466
+ }
467
+ function execOptions(options) {
468
+ const env = Object.fromEntries(Object.entries(options.env ?? {}).filter((entry) => typeof entry[1] === "string"));
469
+ return {
470
+ ...options.cwd ? { cwd: options.cwd } : {},
471
+ ...Object.keys(env).length ? { env } : {}
472
+ };
473
+ }
474
+ /** Same units as @cloudflare/sandbox 0.12 `sleepAfter`: a number of seconds or `"30s"`, `"5m"`, `"1h"`. */
475
+ function parseDuration(value) {
476
+ if (value === void 0) return void 0;
477
+ if (typeof value === "number") return value * 1e3;
478
+ const match = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h)?$/.exec(value.trim());
479
+ if (!match) throw sandboxErrorDiagnostics.SANDBOX_CLOUDFLARE_SLEEP_AFTER_INVALID({ value: JSON.stringify(value) });
480
+ return Number(match[1]) * {
481
+ h: 36e5,
482
+ m: 6e4,
483
+ ms: 1,
484
+ s: 1e3
485
+ }[match[2] ?? "s"];
486
+ }
487
+ /** The number of a signal name such as `"SIGTERM"` or `"TERM"`, or of a number. Undefined when this Sandbox cannot send it. */
488
+ function cloudflareSignalNumber(signal) {
489
+ if (!signal) return signals.TERM;
490
+ if (/^\d+$/.test(signal)) return Number(signal);
491
+ return signals[signal.toUpperCase().replace(/^SIG/, "")];
492
+ }
493
+ function signalNumber(signal) {
494
+ const number = cloudflareSignalNumber(signal);
495
+ if (number === void 0) throw sandboxErrorDiagnostics.SANDBOX_R0165({
496
+ runtime: "Cloudflare",
497
+ signal: String(signal)
498
+ });
499
+ return number;
500
+ }
501
+ function decodeBase64$1(value) {
502
+ return Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
503
+ }
504
+ function encodeBase64$1(value) {
505
+ let binary = "";
506
+ for (let offset = 0; offset < value.length; offset += 8192) binary += String.fromCharCode(...value.subarray(offset, offset + 8192));
507
+ return btoa(binary);
508
+ }
509
+ //#endregion
510
+ //#region src/internal/network-policy.ts
511
+ const maxCloudflareAllowedHosts = 64;
512
+ const label = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
513
+ const hostPattern = new RegExp(`^(?:\\*\\.)?(?:${label}\\.)+${label}$|^${label}$`);
514
+ /** Validates a policy for the `cloudflare` runtime, which takes only the portable form. */
515
+ function normalizeCloudflareNetworkPolicy(value) {
516
+ if (value === void 0 || value === "allow-all") return "allow-all";
517
+ if (value === "deny-all") return "deny-all";
518
+ const invalid = (problem) => sandboxErrorDiagnostics.SANDBOX_NETWORK_POLICY_INVALID({ problem });
519
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid(`networkPolicy must be "allow-all", "deny-all", or { allow: string[] }, not ${JSON.stringify(value)}.`);
520
+ const extra = Object.keys(value).filter((key) => key !== "allow");
521
+ if (extra.length) throw invalid(`Cloudflare does not support networkPolicy.${extra[0]}. Only Vercel supports subnets.`);
522
+ const allow = value.allow;
523
+ if (!Array.isArray(allow)) throw invalid("networkPolicy.allow must be an array of hostnames.");
524
+ const hosts = /* @__PURE__ */ new Set();
525
+ for (const entry of allow) {
526
+ const host = typeof entry === "string" ? entry.trim().toLowerCase().replace(/\.$/, "") : void 0;
527
+ if (host === "*") return "allow-all";
528
+ if (host === void 0 || !hostPattern.test(host)) throw invalid(`networkPolicy.allow entry ${JSON.stringify(entry)} is not a hostname. Use a name such as "api.example.com" or "*.example.com". IP addresses are not supported.`);
529
+ if (/^[\d.]+$/.test(host)) throw invalid(`networkPolicy.allow entry ${JSON.stringify(entry)} is an IP address. Cloudflare filters HTTPS by hostname only.`);
530
+ hosts.add(host);
531
+ }
532
+ if (hosts.size > maxCloudflareAllowedHosts) throw invalid(`networkPolicy.allow has ${hosts.size} hostnames. Cloudflare allows at most ${maxCloudflareAllowedHosts}. Use a pattern such as "*.example.com".`);
533
+ if (hosts.size === 0) return "deny-all";
534
+ return { allow: [...hosts].sort() };
535
+ }
536
+ /** The `network` fact of `executionAuthority` for a validated policy. */
537
+ function sandboxNetworkAuthority(policy) {
538
+ if (policy === "allow-all") return "unrestricted";
539
+ if (policy === "deny-all") return "none";
540
+ return "restricted";
541
+ }
542
+ /**
543
+ * Cloudflare decrypts HTTPS to allowed hosts and signs it again with this CA. It exists while HTTPS interception is on.
544
+ * `exec()` does not inherit the environment of the Container start, so every command gets these variables.
545
+ */
546
+ const cloudflareContainerCa = "/etc/cloudflare/certs/cloudflare-containers-ca.crt";
547
+ const cloudflareInterceptedHttpsEnv = Object.freeze({
548
+ CURL_CA_BUNDLE: cloudflareContainerCa,
549
+ GIT_SSL_CAINFO: cloudflareContainerCa,
550
+ NODE_EXTRA_CA_CERTS: cloudflareContainerCa,
551
+ REQUESTS_CA_BUNDLE: cloudflareContainerCa,
552
+ SSL_CERT_FILE: cloudflareContainerCa
553
+ });
554
+ //#endregion
555
+ //#region src/cloudflare.ts
556
+ var cloudflare_exports = /* @__PURE__ */ __exportAll({ createCloudflareRuntime: () => createCloudflareRuntime });
557
+ const cloudflareExecutionAuthority = {
558
+ credentials: "unknown",
559
+ environment: "selected",
560
+ filesystem: {
561
+ access: "read-write",
562
+ scope: "sandbox"
563
+ },
564
+ isolation: "container",
565
+ network: "unknown",
566
+ processes: "arbitrary"
567
+ };
568
+ function createCloudflareRuntime(options) {
569
+ if (!options?.namespace) throw sandboxErrorDiagnostics.SANDBOX_R0020({ message: "[vitehub] The cloudflare Sandbox runtime requires a Durable Objects namespace." });
570
+ const networkPolicy = normalizeCloudflareNetworkPolicy(options.networkPolicy);
571
+ if (options.getSandbox && options.networkPolicy !== void 0) throw sandboxErrorDiagnostics.SANDBOX_NETWORK_POLICY_INVALID({ problem: "A custom getSandbox starts the Container, so ViteHub cannot apply networkPolicy." });
572
+ const executionAuthority = options.getSandbox ? cloudflareExecutionAuthority : {
573
+ ...cloudflareExecutionAuthority,
574
+ network: sandboxNetworkAuthority(networkPolicy)
575
+ };
576
+ const commandEnv = typeof networkPolicy === "object" ? cloudflareInterceptedHttpsEnv : {};
577
+ return markBuiltInSandboxRuntime({
578
+ name: "cloudflare",
579
+ async prepare(input) {
580
+ return remoteSandboxPlan(input, {
581
+ executionAuthority,
582
+ runtime: "cloudflare"
583
+ });
584
+ },
585
+ async open(input, openOptions) {
586
+ const env = {
587
+ ...commandEnv,
588
+ ...await resolveRemoteEnvironment(input, {})
589
+ };
590
+ const id = openOptions?.id ?? options.sandboxId ?? `vitehub-${crypto.randomUUID()}`;
591
+ const runtimeSession = createCloudflareSession(id, options.getSandbox ? options.getSandbox(options.namespace, id, options.cloudflare) : getCloudflareSandbox(options.namespace, id, options.cloudflare, networkPolicy), env, options.hostname, !options.getSandbox);
592
+ return await openRemoteSandbox(input, runtimeSession, {
593
+ executionAuthority: openOptions.executionAuthority,
594
+ initialize: openOptions?.initialize,
595
+ preserveHome: true,
596
+ preserveWorkspace: !input.checkout,
597
+ runtime: "cloudflare",
598
+ signal: openOptions?.signal
599
+ }, env);
600
+ }
601
+ });
602
+ }
603
+ /**
604
+ * Reaches the Sandbox Durable Object that the ViteHub Cloudflare host integration exports.
605
+ * @cloudflare/sandbox 1.0 has no `getSandbox`; the generated class implements this stub over RPC.
606
+ */
607
+ function getCloudflareSandbox(namespace, id, options = {}, networkPolicy = "allow-all") {
608
+ const target = namespace.get(namespace.idFromName(options.normalizeId ? id.toLowerCase() : id));
609
+ let configured;
610
+ const ready = async () => {
611
+ configured ??= target.configure({
612
+ keepAlive: options.keepAlive,
613
+ networkPolicy,
614
+ sleepAfter: options.sleepAfter
615
+ }).catch((error) => {
616
+ configured = void 0;
617
+ throw error;
618
+ });
619
+ await configured;
620
+ };
621
+ return {
622
+ cancelExec: async (id) => (await ready(), await target.cancelExec(id)),
623
+ deleteFile: async (path) => (await ready(), await target.deleteFile(path)),
624
+ destroy: async () => (await ready(), await target.destroy()),
625
+ exec: async (command, execOptions) => (await ready(), await target.exec(command, execOptions)),
626
+ exists: async (path) => (await ready(), await target.exists(path)),
627
+ mkdir: async (path, mkdirOptions) => (await ready(), await target.mkdir(path, mkdirOptions)),
628
+ moveFile: async (source, destination) => (await ready(), await target.moveFile(source, destination)),
629
+ readFile: async (path, readOptions) => (await ready(), await target.readFile(path, readOptions)),
630
+ startProcess: async (command, processOptions) => (await ready(), await target.startProcess(command, processOptions)),
631
+ streamProcessLogs: async (processId) => (await ready(), await target.streamProcessLogs(processId)),
632
+ writeFile: async (path, contents, writeOptions) => (await ready(), await target.writeFile(path, contents, writeOptions))
633
+ };
634
+ }
635
+ function createCloudflareSession(id, stub, baseEnv, hostname, builtIn) {
636
+ let destroyPromise;
637
+ const destroy = async () => {
638
+ if (destroyPromise) return await destroyPromise;
639
+ destroyPromise = withCloudflareRequest("destroy", {
640
+ idempotent: true,
641
+ timeout: cloudflareStopTimeout
642
+ }, async () => await stub.destroy());
643
+ try {
644
+ await destroyPromise;
645
+ } catch (error) {
646
+ destroyPromise = void 0;
647
+ throw error;
648
+ }
649
+ };
650
+ const request = (operation, { idempotent, signal, timeout = cloudflareControlPlaneTimeout }, run) => withCloudflareRequest(operation, {
651
+ idempotent,
652
+ signal,
653
+ timeout
654
+ }, run);
655
+ const run = async (options, idempotent = false) => {
656
+ const timeout = options.timeout ?? 18e4;
657
+ const execId = crypto.randomUUID();
658
+ const executions = [];
659
+ try {
660
+ const result = await abortable(request("exec", {
661
+ idempotent,
662
+ timeout
663
+ }, async () => {
664
+ const execution = stub.exec(options.command, {
665
+ cwd: options.workingDirectory ?? "/workspace",
666
+ env: {
667
+ ...baseEnv,
668
+ ...options.env
669
+ },
670
+ id: execId,
671
+ timeout
672
+ });
673
+ executions.push(execution);
674
+ return await execution;
675
+ }), options.abortSignal, () => request("cancelExec", {
676
+ idempotent: true,
677
+ timeout: cloudflareStopTimeout
678
+ }, async () => await stub.cancelExec(execId)));
679
+ return {
680
+ exitCode: result.exitCode,
681
+ stderr: result.stderr,
682
+ stdout: result.stdout
683
+ };
684
+ } finally {
685
+ if (options.abortSignal?.aborted) await Promise.allSettled(executions);
686
+ }
687
+ };
688
+ return {
689
+ defaultWorkingDirectory: "/workspace",
690
+ id,
691
+ async destroy() {
692
+ await destroy();
693
+ },
694
+ async existsFile({ abortSignal, path }) {
695
+ abortSignal?.throwIfAborted();
696
+ if (stub.exists) return (await request("exists", { idempotent: true }, async () => await stub.exists(path))).exists;
697
+ return (await run({
698
+ abortSignal,
699
+ command: `test -e ${shellQuote(path)}`
700
+ }, true)).exitCode === 0;
701
+ },
702
+ ...hostname && stub.exposePort ? { async getPortUrl({ port, protocol = "http" }) {
703
+ const result = await request("exposePort", { idempotent: false }, async () => await stub.exposePort(port, {
704
+ hostname,
705
+ protocol: protocol === "ws" ? "http" : protocol
706
+ }));
707
+ return protocol === "ws" ? result.url.replace(/^http/, "ws") : result.url;
708
+ } } : {},
709
+ async listFiles({ abortSignal, path, recursive }) {
710
+ abortSignal?.throwIfAborted();
711
+ if (stub.listFiles) return (await request("listFiles", { idempotent: true }, async () => await stub.listFiles(path, { recursive }))).files.filter((file) => file.type === "directory" || file.type === "file" || file.type === "symlink").map((file) => ({
712
+ path: file.absolutePath,
713
+ size: file.size,
714
+ type: file.type
715
+ })).sort((left, right) => left.path.localeCompare(right.path));
716
+ return await listCommandFiles((options) => run(options, true), {
717
+ abortSignal,
718
+ path,
719
+ recursive
720
+ }, (result) => sandboxErrorDiagnostics.SANDBOX_R0029({ message: result.stderr }));
721
+ },
722
+ async makeDirectory({ abortSignal, path, recursive }) {
723
+ abortSignal?.throwIfAborted();
724
+ if (stub.mkdir) {
725
+ const result = await request("mkdir", { idempotent: recursive === true }, async () => await stub.mkdir(path, { recursive }));
726
+ if (result && !result.success) throw sandboxErrorDiagnostics.SANDBOX_R0022({ message: `[vitehub] Cloudflare failed to create ${path}.` });
727
+ return;
728
+ }
729
+ const result = await run({
730
+ abortSignal,
731
+ command: `mkdir ${recursive ? "-p " : ""}-- ${shellQuote(path)}`
732
+ });
733
+ if (result.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0023({ message: result.stderr });
734
+ },
735
+ ...stub.moveFile ? { async moveFile({ abortSignal, destination, source }) {
736
+ abortSignal?.throwIfAborted();
737
+ const result = await request("moveFile", { idempotent: false }, async () => await stub.moveFile(source, destination));
738
+ if (result && !result.success) throw sandboxErrorDiagnostics.SANDBOX_R0024({ message: `[vitehub] Cloudflare failed to move ${source}.` });
739
+ } } : void 0,
740
+ async readBinaryFile({ abortSignal, path }) {
741
+ abortSignal?.throwIfAborted();
742
+ const result = await abortable(request("readFile", {
743
+ idempotent: true,
744
+ signal: abortSignal,
745
+ timeout: cloudflareReadTimeout
746
+ }, async () => await stub.readFile(path, { encoding: "base64" })), abortSignal);
747
+ if (result.success === false) {
748
+ if (!(stub.exists ? (await abortable(request("exists", {
749
+ idempotent: true,
750
+ signal: abortSignal
751
+ }, async () => await stub.exists(path)), abortSignal)).exists : false)) return null;
752
+ throw sandboxErrorDiagnostics.SANDBOX_R0025({ message: `[vitehub] Cloudflare failed to read ${path}.` });
753
+ }
754
+ return decodeBase64(result.content);
755
+ },
756
+ async removeFile({ abortSignal, path, recursive }) {
757
+ abortSignal?.throwIfAborted();
758
+ if (!recursive && stub.deleteFile) {
759
+ const result = await request("deleteFile", { idempotent: true }, async () => await stub.deleteFile(path));
760
+ if (result && !result.success) throw sandboxErrorDiagnostics.SANDBOX_R0026({ message: `[vitehub] Cloudflare failed to remove ${path}.` });
761
+ return;
762
+ }
763
+ const result = await run({
764
+ abortSignal,
765
+ command: recursive ? `rm -rf -- ${shellQuote(path)}` : `if test -d ${shellQuote(path)}; then rmdir -- ${shellQuote(path)}; else rm -f -- ${shellQuote(path)}; fi`
766
+ });
767
+ if (result.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0027({ message: result.stderr });
768
+ },
769
+ run,
770
+ ...stub.startProcess ? { async spawn(commandOptions) {
771
+ commandOptions.abortSignal?.throwIfAborted();
772
+ const process = await request("startProcess", { idempotent: false }, async () => await stub.startProcess(commandOptions.command, {
773
+ cwd: commandOptions.workingDirectory ?? "/workspace",
774
+ env: {
775
+ ...baseEnv,
776
+ ...commandOptions.env
777
+ },
778
+ ...commandOptions.stdin ? { stdin: true } : {}
779
+ }));
780
+ const logs = stub.streamProcessLogs ? request("streamProcessLogs", { idempotent: true }, async () => await stub.streamProcessLogs(process.id)) : void 0;
781
+ return killOnAbort(cloudflareProcess(process, logs, builtIn), commandOptions.abortSignal);
782
+ } } : {},
783
+ async stop() {},
784
+ async writeBinaryFile({ abortSignal, content, path }) {
785
+ abortSignal?.throwIfAborted();
786
+ const result = await request("writeFile", { idempotent: true }, async () => await stub.writeFile(path, encodeBase64(content), { encoding: "base64" }));
787
+ if (result && !result.success) throw sandboxErrorDiagnostics.SANDBOX_R0028({ message: `[vitehub] Cloudflare failed to write ${path}.` });
788
+ }
789
+ };
790
+ }
791
+ function decodeBase64(value) {
792
+ const decoded = atob(value);
793
+ return Uint8Array.from(decoded, (character) => character.charCodeAt(0));
794
+ }
795
+ function encodeBase64(value) {
796
+ let binary = "";
797
+ for (let offset = 0; offset < value.length; offset += 8192) binary += String.fromCharCode(...value.subarray(offset, offset + 8192));
798
+ return btoa(binary);
799
+ }
800
+ function cloudflareProcess(process, logs, builtIn) {
801
+ const wait = process.waitForExit();
802
+ return {
803
+ ...logs ? processLogStreams(logs) : exitedProcessLogs(wait.then(async () => await process.getLogs())),
804
+ ...process.stdin ? { stdin: process.stdin } : {},
805
+ async kill(signal) {
806
+ if (builtIn && cloudflareSignalNumber(signal) === void 0) throw sandboxErrorDiagnostics.SANDBOX_R0165({
807
+ runtime: "Cloudflare",
808
+ signal: String(signal)
809
+ });
810
+ await process.kill(signal);
811
+ },
812
+ async wait() {
813
+ return await wait;
814
+ }
815
+ };
816
+ }
817
+ function exitedProcessLogs(logs) {
818
+ return {
819
+ stderr: snapshotStream(async () => (await logs).stderr),
820
+ stdout: snapshotStream(async () => (await logs).stdout)
821
+ };
822
+ }
823
+ /** Bounds each channel independently so an unread channel cannot stall its sibling. */
824
+ function processLogStreams(logs) {
825
+ const bufferLimit = 1048576;
826
+ const encoder = new TextEncoder();
827
+ const open = /* @__PURE__ */ new Map();
828
+ let reader;
829
+ let stopped = false;
830
+ const stop = async () => {
831
+ if (stopped) return;
832
+ stopped = true;
833
+ await reader?.cancel().catch(() => void 0);
834
+ };
835
+ const stream = (name) => new ReadableStream({
836
+ cancel() {
837
+ open.delete(name);
838
+ if (open.size === 0) return stop();
839
+ },
840
+ start(controller) {
841
+ open.set(name, controller);
842
+ }
843
+ }, new ByteLengthQueuingStrategy({ highWaterMark: bufferLimit }));
844
+ const output = {
845
+ stderr: stream("stderr"),
846
+ stdout: stream("stdout")
847
+ };
848
+ const forward = (name, data) => {
849
+ const controller = open.get(name);
850
+ if (!controller || data.length === 0) return;
851
+ const chunk = new Uint8Array(Math.min(data.length * 3, controller.desiredSize ?? 0));
852
+ const { read, written } = encoder.encodeInto(data, chunk);
853
+ if (read < data.length) {
854
+ controller.error(sandboxErrorDiagnostics.SANDBOX_R0159({ message: `Cloudflare ${name} exceeded the ${bufferLimit}-byte output buffer limit. Consume both streams concurrently or cancel unused output.` }));
855
+ open.delete(name);
856
+ } else controller.enqueue(written === chunk.byteLength ? chunk : chunk.slice(0, written));
857
+ };
858
+ (async () => {
859
+ try {
860
+ reader = (await logs).getReader();
861
+ if (stopped) return;
862
+ const decoder = new TextDecoder();
863
+ let buffered = "";
864
+ while (open.size > 0) {
865
+ const { done, value } = await reader.read();
866
+ buffered += done ? decoder.decode() : decoder.decode(value, { stream: true });
867
+ const events = buffered.split(/\r?\n\r?\n/);
868
+ buffered = done ? "" : events.pop();
869
+ for (const event of events) {
870
+ const data = event.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n");
871
+ if (!data) continue;
872
+ const log = JSON.parse(data);
873
+ if (log.type === "stdout" || log.type === "stderr") forward(log.type, log.data ?? "");
874
+ else if (log.type === "exit") return;
875
+ else if (log.type === "error") throw sandboxErrorDiagnostics.SANDBOX_CLOUDFLARE_LOG_STREAM_FAILED({ detail: log.data ?? "unknown error" });
876
+ }
877
+ if (done) return;
878
+ }
879
+ } catch (error) {
880
+ for (const controller of open.values()) controller.error(error);
881
+ open.clear();
882
+ } finally {
883
+ for (const controller of open.values()) controller.close();
884
+ open.clear();
885
+ await stop();
886
+ }
887
+ })();
888
+ return output;
889
+ }
890
+ async function abortable(operation, signal, abort) {
891
+ if (!signal) return await operation;
892
+ signal.throwIfAborted();
893
+ return await new Promise((resolve, reject) => {
894
+ const onAbort = () => {
895
+ signal.removeEventListener("abort", onAbort);
896
+ if (abort) abort().catch(() => void 0).then(() => reject(signal.reason));
897
+ else reject(signal.reason);
898
+ };
899
+ signal.addEventListener("abort", onAbort, { once: true });
900
+ operation.then((value) => {
901
+ signal.removeEventListener("abort", onAbort);
902
+ if (!signal.aborted) resolve(value);
903
+ }, (error) => {
904
+ signal.removeEventListener("abort", onAbort);
905
+ if (!signal.aborted) reject(error);
906
+ });
907
+ });
908
+ }
909
+ //#endregion
910
+ export { createCloudflareSandboxOutbound as i, createCloudflareRuntime as n, createCloudflareSandboxDurableObject as r, cloudflare_exports as t };