@vite-hub/sandbox 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +35 -37
  2. package/dist/cloudflare-env-2NctU8i7.js +12 -0
  3. package/dist/index.d.ts +23 -32
  4. package/dist/index.js +688 -265
  5. package/dist/module-types-DfXe133f.d.ts +91 -0
  6. package/dist/provider-loader-hL7uHVWp.d.ts +21 -0
  7. package/dist/runtime/provider-loader.d.ts +2 -17
  8. package/dist/runtime/provider-loader.js +4 -10
  9. package/dist/runtime/providers/cloudflare.d.ts +5 -11
  10. package/dist/runtime/providers/cloudflare.js +14 -11
  11. package/dist/runtime/providers/vercel.d.ts +103 -12
  12. package/dist/runtime/providers/vercel.js +16 -30
  13. package/dist/runtime/state.d.ts +1 -1
  14. package/dist/vite.d.ts +12 -28
  15. package/dist/vite.js +2280 -354
  16. package/package.json +60 -59
  17. package/dist/_shared-CJ2_pS4E.js +0 -53
  18. package/dist/cloudflare-retry-Cfra7MvS.js +0 -21
  19. package/dist/common-CS4FcWrh.d.ts +0 -369
  20. package/dist/index-B4j3Mvzr.d.ts +0 -146
  21. package/dist/integration-wkNE8jMO.js +0 -2032
  22. package/dist/module-types-CUcY8iuI.d.ts +0 -88
  23. package/dist/nitro.d.ts +0 -19
  24. package/dist/nitro.js +0 -488
  25. package/dist/provider-detection-IbezCeoR.js +0 -25
  26. package/dist/runtime/nitro-plugin.d.ts +0 -4
  27. package/dist/runtime/nitro-plugin.js +0 -8
  28. package/dist/sandbox/providers/cloudflare.d.ts +0 -7
  29. package/dist/sandbox/providers/cloudflare.js +0 -339
  30. package/dist/sandbox/providers/vercel.d.ts +0 -17
  31. package/dist/sandbox/providers/vercel.js +0 -538
  32. package/dist/shared-pqTHYWg1.d.ts +0 -8
  33. package/dist/utils-V7ODsDW_.js +0 -44
  34. package/dist/vercel-runtime-BPzvh_6V.js +0 -11
  35. /package/dist/{module-types-BomzaqnM.js → module-types-Dj1MFmHT.js} +0 -0
package/dist/index.js CHANGED
@@ -1,13 +1,9 @@
1
- import { i as VitehubError, n as SandboxError, t as sleep } from "./utils-V7ODsDW_.js";
2
- import { n as CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS, r as collectCloudflareErrorMessages, t as CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE } from "./cloudflare-retry-Cfra7MvS.js";
3
- import { i as isVercel, n as getCloudflareEnv, r as isCloudflare, t as createProviderDetector } from "./provider-detection-IbezCeoR.js";
4
- import { t as isSupportedVercelSandboxRuntime } from "./vercel-runtime-BPzvh_6V.js";
1
+ import { t as getCloudflareEnv } from "./cloudflare-env-2NctU8i7.js";
5
2
  import { getSandboxRuntimeConfig, getSandboxRuntimeRegistry } from "./runtime/state.js";
6
- import { t as getSandboxFeatureProvider } from "./module-types-BomzaqnM.js";
3
+ import { t as getSandboxFeatureProvider } from "./module-types-Dj1MFmHT.js";
7
4
  import { readBody } from "h3";
5
+ import { ViteHubError, getViteHubErrorShape } from "@vite-hub/runtime";
8
6
  import { upperFirst } from "scule";
9
- import { useRuntimeConfig } from "nitro/runtime-config";
10
- import { getContext } from "unctx";
11
7
  import { dirname } from "pathe";
12
8
  //#region src/internal/shared/definition.ts
13
9
  function assertDefinitionHandler(functionName, handler, label) {
@@ -15,7 +11,7 @@ function assertDefinitionHandler(functionName, handler, label) {
15
11
  }
16
12
  function validateDefinitionOptions(functionName, options, config) {
17
13
  if (typeof options === "undefined") return void 0;
18
- if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError(`[vitehub] \`${functionName}()\` accepts \`(handler, options?)\`.`);
14
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError(`[vitehub] \`${functionName}()\` accepts one options object.`);
19
15
  const invalidKeys = Object.keys(options).filter((key) => {
20
16
  if (config.allowedKeys) return !config.allowedKeys.includes(key);
21
17
  return config.disallowedKeys?.includes(key);
@@ -25,39 +21,25 @@ function validateDefinitionOptions(functionName, options, config) {
25
21
  }
26
22
  //#endregion
27
23
  //#region src/runtime/registry.ts
28
- function validateRuntimeOptions(functionName, runtime) {
29
- if (typeof runtime === "undefined") return void 0;
30
- if (!runtime || typeof runtime !== "object" || Array.isArray(runtime)) throw new TypeError(`[vitehub] \`${functionName}()\` expects \`options.runtime\` to be an object with \`command\` and optional \`args\`.`);
31
- const { command, args, ...rest } = runtime;
32
- const invalidKeys = Object.keys(rest);
33
- if (invalidKeys.length > 0) throw new TypeError(`[vitehub] \`${functionName}()\` supports only \`options.runtime.command\` and \`options.runtime.args\`. Unsupported keys: ${invalidKeys.join(", ")}.`);
34
- if (typeof command !== "string" || !command.trim()) throw new TypeError(`[vitehub] \`${functionName}()\` expects \`options.runtime.command\` to be a non-empty string.`);
35
- if (typeof args !== "undefined" && (!Array.isArray(args) || args.some((arg) => typeof arg !== "string"))) throw new TypeError(`[vitehub] \`${functionName}()\` expects \`options.runtime.args\` to be a string array.`);
36
- return {
37
- command,
38
- ...Array.isArray(args) ? { args: [...args] } : {}
39
- };
40
- }
41
- function createSandboxDefinition(functionName, run, options) {
42
- const validated = validateDefinitionOptions(functionName, options, {
24
+ function createSandboxDefinition(functionName, input) {
25
+ const validated = validateDefinitionOptions(functionName, input, {
43
26
  allowedKeys: [
27
+ "run",
44
28
  "timeout",
45
- "env",
46
- "runtime"
29
+ "env"
47
30
  ],
48
- invalidKeysMessage: "supports only portable sandbox options (timeout, env, runtime)"
31
+ invalidKeysMessage: "supports only portable Sandbox options (run, timeout, env)"
49
32
  });
50
- assertDefinitionHandler(functionName, run, "sandbox handler");
33
+ if (!validated) throw new TypeError(`[vitehub] \`${functionName}()\` requires an options object.`);
34
+ const { run, ...options } = validated;
35
+ assertDefinitionHandler(functionName, run, "Sandbox handler in `run`");
51
36
  return {
52
37
  run,
53
- options: validated ? {
54
- ...validated,
55
- runtime: validateRuntimeOptions(functionName, validated.runtime)
56
- } : void 0
38
+ options: Object.keys(options).length ? options : void 0
57
39
  };
58
40
  }
59
- function defineSandbox(run, options) {
60
- return createSandboxDefinition("defineSandbox", run, options);
41
+ function defineSandbox(input) {
42
+ return createSandboxDefinition("defineSandbox", input);
61
43
  }
62
44
  //#endregion
63
45
  //#region src/internal/shared/request-payload.ts
@@ -66,6 +48,51 @@ async function readRequestPayload(event, fallback = {}) {
66
48
  return await readBody(event).catch(() => fallback);
67
49
  }
68
50
  //#endregion
51
+ //#region src/sandbox/errors.ts
52
+ function sanitizeSandboxDetail(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
53
+ if (value === null || typeof value === "boolean") return value;
54
+ if (typeof value === "string") return value.slice(0, 16384);
55
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
56
+ if (!value || typeof value !== "object" || depth >= 8 || seen.has(value)) return void 0;
57
+ seen.add(value);
58
+ try {
59
+ if (Array.isArray(value)) return value.slice(0, 128).flatMap((item) => {
60
+ const sanitized = sanitizeSandboxDetail(item, depth + 1, seen);
61
+ return sanitized === void 0 ? [] : [sanitized];
62
+ });
63
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return void 0;
64
+ const result = {};
65
+ for (const [key, item] of Object.entries(value).slice(0, 128)) {
66
+ if (!key || key.length > 128) continue;
67
+ result[key] = sanitizeSandboxDetail(item, depth + 1, seen);
68
+ }
69
+ return result;
70
+ } catch {
71
+ return;
72
+ } finally {
73
+ seen.delete(value);
74
+ }
75
+ }
76
+ function sanitizeSandboxDetails(details) {
77
+ const sanitized = sanitizeSandboxDetail(details);
78
+ return sanitized && !Array.isArray(sanitized) && typeof sanitized === "object" ? sanitized : void 0;
79
+ }
80
+ function sandboxError(message, metadata = {}) {
81
+ const { cause, code = "SANDBOX_RUNTIME_ERROR", details, httpStatus, method, provider } = metadata;
82
+ return new ViteHubError(code, message.slice(0, 16384) || "Sandbox execution failed.", {
83
+ cause,
84
+ details: sanitizeSandboxDetails({
85
+ ...provider === void 0 ? {} : { provider },
86
+ ...method === void 0 ? {} : { method },
87
+ ...httpStatus === void 0 ? {} : { httpStatus },
88
+ ...sanitizeSandboxDetails(details)
89
+ })
90
+ });
91
+ }
92
+ function isSandboxError(value) {
93
+ return getViteHubErrorShape(value)?.code.startsWith("SANDBOX_") === true;
94
+ }
95
+ //#endregion
69
96
  //#region src/internal/shared/validation.ts
70
97
  const VALIDATION_FAILED = "Validation failed";
71
98
  function isObject(value) {
@@ -110,34 +137,23 @@ function readData(value, issues) {
110
137
  ...issues ? { issues } : {}
111
138
  };
112
139
  }
113
- var VitehubValidationError = class extends VitehubError {
114
- status;
115
- statusCode;
116
- statusText;
117
- statusMessage;
118
- data;
119
- constructor(cause) {
120
- const statusCode = readStatusCode(cause);
121
- const statusText = readStatusText(cause);
122
- const message = readMessage(cause);
123
- const data = readData(cause, readIssues(cause));
124
- super(message, {
125
- cause,
126
- code: "VALIDATION_ERROR",
127
- details: data,
128
- httpStatus: statusCode
129
- });
130
- this.name = "VitehubValidationError";
131
- this.status = statusCode;
132
- this.statusCode = statusCode;
133
- this.statusText = statusText;
134
- this.statusMessage = statusText;
135
- this.data = data;
136
- }
137
- };
138
140
  function createValidationError(cause) {
139
141
  if (isErrorWithHttpMetadata(cause)) return cause;
140
- return new VitehubValidationError(cause);
142
+ const statusCode = readStatusCode(cause);
143
+ const statusText = readStatusText(cause);
144
+ const data = readData(cause, readIssues(cause));
145
+ return Object.assign(sandboxError(readMessage(cause), {
146
+ cause,
147
+ code: "SANDBOX_VALIDATION_ERROR",
148
+ details: data,
149
+ httpStatus: statusCode
150
+ }), {
151
+ status: statusCode,
152
+ statusCode,
153
+ statusText,
154
+ statusMessage: statusText,
155
+ data
156
+ });
141
157
  }
142
158
  async function readValidatedPayload(payload, validate, options) {
143
159
  if (hasStandardValidator(validate)) {
@@ -164,9 +180,26 @@ async function readValidatedPayload(payload, validate, options) {
164
180
  }
165
181
  }
166
182
  //#endregion
183
+ //#region src/internal/shared/cloudflare-retry.ts
184
+ const CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS = [
185
+ 1e3,
186
+ 2e3,
187
+ 5e3,
188
+ 1e4,
189
+ 15e3
190
+ ];
191
+ const CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE = /container is starting|currently provisioning|retry in a moment|network connection lost|not listening in the tcp address|durable object reset|code was updated|aborterror|aborted|maximum number of running container instances exceeded|there is no container instance that can be provided to this durable object/i;
192
+ function collectCloudflareErrorMessages(error, ...extraMessages) {
193
+ return [
194
+ error instanceof Error ? error.message : String(error),
195
+ error instanceof Error && error.cause instanceof Error ? error.cause.message : "",
196
+ ...extraMessages
197
+ ].filter(Boolean).join("\n");
198
+ }
199
+ //#endregion
167
200
  //#region src/internal/shared/named-resource.ts
168
201
  function resolveNamedResourceName(feature, name) {
169
- if (!name) throw new Error(`[vitehub] ${upperFirst(feature)} name is required. Pass an explicit name.`);
202
+ if (!name) throw new Error(`[vitehub] ${upperFirst(feature)} name is required. An explicit name is required.`);
170
203
  return name;
171
204
  }
172
205
  function createUnknownNamedResourceError(feature, name) {
@@ -175,22 +208,9 @@ function createUnknownNamedResourceError(feature, name) {
175
208
  function createInvalidNamedResourceError(feature, name) {
176
209
  return /* @__PURE__ */ new Error(`[vitehub] ${upperFirst(feature)} "${name}" is invalid.`);
177
210
  }
178
- const nitroAsyncContext = getContext("nitro-app");
179
- function safeUseRequest() {
180
- try {
181
- return nitroAsyncContext.use().request;
182
- } catch {
183
- return;
184
- }
185
- }
186
211
  function readRuntimeValue(read, fallback) {
187
- try {
188
- const value = read(useRuntimeConfig());
189
- if (typeof value !== "undefined") return value;
190
- } catch {
191
- return fallback();
192
- }
193
- return fallback();
212
+ const value = read({});
213
+ return typeof value === "undefined" ? fallback() : value;
194
214
  }
195
215
  async function loadRegistryEntry(registry, name) {
196
216
  const entry = registry[name];
@@ -211,7 +231,7 @@ async function loadResourceRuntimeContext(options, name) {
211
231
  return {
212
232
  feature: options.feature,
213
233
  name: resolvedName,
214
- event: safeUseRequest(),
234
+ event: void 0,
215
235
  config,
216
236
  definition
217
237
  };
@@ -255,53 +275,171 @@ async function createHandleWithoutConstruct(context, port) {
255
275
  return { provider };
256
276
  }
257
277
  //#endregion
258
- //#region src/sandbox/providers/shared.ts
259
- const detect = createProviderDetector([{
260
- provider: "cloudflare",
261
- when: isCloudflare
262
- }, {
263
- provider: "vercel",
264
- when: isVercel
265
- }]);
266
- function detectSandbox() {
267
- const env = typeof process !== "undefined" ? process.env : {};
268
- const type = detect() || "none";
269
- if (type === "cloudflare") return {
270
- type,
271
- details: { runtime: typeof process === "undefined" ? "workerd" : "node" }
272
- };
273
- if (type === "vercel") return {
274
- type,
275
- details: { env: env.VERCEL_ENV }
278
+ //#region src/internal/shared/utils.ts
279
+ async function sleep(ms) {
280
+ await new Promise((resolve) => setTimeout(resolve, ms));
281
+ }
282
+ //#endregion
283
+ //#region src/runtime/binary-sidecars.ts
284
+ const SANDBOX_VALUE_MARKER = "vitehub:sandbox:value";
285
+ function isPlainObject(value) {
286
+ if (!value || typeof value !== "object") return false;
287
+ const prototype = Object.getPrototypeOf(value);
288
+ return prototype === Object.prototype || prototype === null;
289
+ }
290
+ function isObjectRecord(value) {
291
+ return !!value && typeof value === "object";
292
+ }
293
+ function isBoxedJsonPrimitive(value) {
294
+ return value instanceof Boolean || value instanceof Number || value instanceof String || Object.getPrototypeOf(value) === BigInt.prototype;
295
+ }
296
+ function hasMarker(value) {
297
+ return Object.prototype.hasOwnProperty.call(value, SANDBOX_VALUE_MARKER);
298
+ }
299
+ function tagged(value) {
300
+ return { [SANDBOX_VALUE_MARKER]: value };
301
+ }
302
+ function serializationError(message, details, cause) {
303
+ return sandboxError(message, {
304
+ code: "SANDBOX_SERIALIZATION_ERROR",
305
+ cause,
306
+ details
307
+ });
308
+ }
309
+ async function encodeSandboxValue(sandbox, value, assetsDir, label, signal) {
310
+ const state = { nextId: 0 };
311
+ const throwIfAborted = () => signal?.throwIfAborted();
312
+ const abortable = async (operation) => {
313
+ try {
314
+ return await operation;
315
+ } catch (error) {
316
+ throwIfAborted();
317
+ throw error;
318
+ }
276
319
  };
277
- return { type };
320
+ async function encode(entry, ancestors, key = "", applyToJSON = true) {
321
+ const blob = typeof Blob !== "undefined" && entry instanceof Blob;
322
+ const buffer = typeof Buffer !== "undefined" && Buffer.isBuffer(entry);
323
+ if (blob || entry instanceof Uint8Array) {
324
+ throwIfAborted();
325
+ const id = state.nextId++;
326
+ state.directory ||= abortable(sandbox.files.mkdir(assetsDir, {
327
+ recursive: true,
328
+ signal
329
+ }));
330
+ await state.directory;
331
+ const bytes = blob ? new Uint8Array(await entry.arrayBuffer()) : entry;
332
+ throwIfAborted();
333
+ await abortable(sandbox.files.write(`${assetsDir}/${id}`, bytes, { signal }));
334
+ return tagged({
335
+ id,
336
+ kind: blob ? "blob" : buffer ? "buffer" : "uint8array",
337
+ ...blob && entry.type ? { type: entry.type } : {},
338
+ tag: "binary"
339
+ });
340
+ }
341
+ if (isObjectRecord(entry) && applyToJSON && typeof entry.toJSON === "function") try {
342
+ return await encode(Reflect.apply(entry.toJSON, entry, [key]), ancestors, key, false);
343
+ } catch (error) {
344
+ if (isSandboxError(error)) throw error;
345
+ throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
346
+ }
347
+ if (Array.isArray(entry)) {
348
+ if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
349
+ const nextAncestors = new Set(ancestors).add(entry);
350
+ return await Promise.all(entry.map((item, index) => encode(item, nextAncestors, String(index))));
351
+ }
352
+ if (!isObjectRecord(entry)) return entry;
353
+ if (isBoxedJsonPrimitive(entry)) return await encode(entry.valueOf(), ancestors, key, false);
354
+ if (ancestors.has(entry)) throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label });
355
+ const nextAncestors = new Set(ancestors).add(entry);
356
+ let sourceEntries;
357
+ try {
358
+ sourceEntries = Object.entries(entry).filter(([entryKey, item]) => applyToJSON || entryKey !== "toJSON" || typeof item !== "function");
359
+ } catch (error) {
360
+ throw serializationError(`Sandbox ${label} must be JSON-serializable.`, { label }, error);
361
+ }
362
+ const entries = await Promise.all(sourceEntries.map(async ([entryKey, item]) => [entryKey, await encode(item, nextAncestors, entryKey)]));
363
+ return hasMarker(entry) ? tagged({
364
+ entries,
365
+ tag: "object"
366
+ }) : Object.fromEntries(entries);
367
+ }
368
+ return await encode(value, /* @__PURE__ */ new Set());
369
+ }
370
+ async function decodeSandboxValue(sandbox, value, assetsDir, label) {
371
+ if (Array.isArray(value)) return await Promise.all(value.map((entry) => decodeSandboxValue(sandbox, entry, assetsDir, label)));
372
+ if (!isPlainObject(value)) return value;
373
+ if (!hasMarker(value)) return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [key, await decodeSandboxValue(sandbox, entry, assetsDir, label)])));
374
+ const descriptor = value[SANDBOX_VALUE_MARKER];
375
+ if (!isPlainObject(descriptor) || typeof descriptor.tag !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
376
+ if (descriptor.tag === "object") {
377
+ if (!Array.isArray(descriptor.entries) || !descriptor.entries.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string")) throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
378
+ return Object.fromEntries(await Promise.all(descriptor.entries.map(async ([key, entry]) => [key, await decodeSandboxValue(sandbox, entry, assetsDir, label)])));
379
+ }
380
+ if (descriptor.tag !== "binary" || !Number.isSafeInteger(descriptor.id) || Object.is(descriptor.id, -0) || descriptor.id < 0 || descriptor.kind !== "blob" && descriptor.kind !== "buffer" && descriptor.kind !== "uint8array" || typeof descriptor.type !== "undefined" && typeof descriptor.type !== "string") throw serializationError(`Sandbox ${label} contains an invalid binary sidecar descriptor.`, { label });
381
+ const bytes = await sandbox.files.read(`${assetsDir}/${descriptor.id}`);
382
+ if (!bytes) throw serializationError(`Sandbox ${label} binary sidecar ${descriptor.id} does not exist.`, {
383
+ id: descriptor.id,
384
+ label
385
+ });
386
+ return descriptor.kind === "blob" ? new Blob([bytes], { type: descriptor.type || "" }) : descriptor.kind === "buffer" ? Buffer.from(bytes) : bytes;
278
387
  }
279
388
  //#endregion
280
- //#region src/sandbox/validation.ts
281
- function validateVercel(provider) {
282
- if (!provider.runtime || isSupportedVercelSandboxRuntime(provider.runtime)) return [];
283
- return [{
284
- code: "VERCEL_SANDBOX_RUNTIME_INVALID",
285
- field: "runtime",
286
- severity: "error",
287
- message: `[vercel] Unsupported sandbox runtime "${provider.runtime}". Use one of: node22, node24.`
288
- }];
289
- }
290
- function validateSandboxConfig(provider) {
291
- const issues = [];
292
- if (provider.provider === "vercel") issues.push(...validateVercel(provider));
389
+ //#region src/runtime/error-normalization.ts
390
+ function readSandboxErrorMetadata(error) {
391
+ if (!error || typeof error !== "object") return void 0;
392
+ const metadata = error;
393
+ const shape = getViteHubErrorShape(error);
293
394
  return {
294
- provider: provider.provider,
295
- ok: issues.every((issue) => issue.severity !== "error"),
296
- issues
395
+ code: shape?.code || (typeof metadata.code === "string" ? metadata.code : void 0),
396
+ provider: typeof shape?.details?.provider === "string" ? shape.details.provider : typeof metadata.provider === "string" ? metadata.provider : void 0,
397
+ cause: metadata.cause,
398
+ details: shape?.details || (typeof metadata.details === "object" && metadata.details !== null ? metadata.details : void 0)
297
399
  };
298
400
  }
401
+ function toSandboxError(error) {
402
+ if (isSandboxError(error)) return error;
403
+ const metadata = readSandboxErrorMetadata(error);
404
+ if (error instanceof Error) return sandboxError(error.message || "Sandbox execution failed.", {
405
+ code: sandboxCode(metadata?.code),
406
+ provider: metadata?.provider,
407
+ details: metadata?.details,
408
+ cause: metadata?.cause ?? error
409
+ });
410
+ return sandboxError(String(error) || "Sandbox execution failed.", {
411
+ code: sandboxCode(metadata?.code),
412
+ provider: metadata?.provider,
413
+ details: metadata?.details,
414
+ cause: metadata?.cause ?? error
415
+ });
416
+ }
417
+ function sandboxCode(code) {
418
+ return code?.startsWith("SANDBOX_") ? code : "SANDBOX_RUNTIME_ERROR";
419
+ }
299
420
  //#endregion
300
421
  //#region src/runtime/entry-script.ts
301
422
  const EXEC_STDIO_OUTPUT_MARKER = "__VITEHUB_OUTPUT__";
302
- function createEntrySource(definitionPath) {
423
+ function createEntrySource(definitionPath, execution = "definition") {
424
+ const invocation = execution === "module" ? [
425
+ ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
426
+ ` const exported = await mod.default`,
427
+ ` const callable = typeof exported === 'function'`,
428
+ ` const result = callable ? await exported(input.payload, input.context) : exported`,
429
+ ` if (!callable && result && typeof result === 'object' && typeof result.run === 'function')`,
430
+ ` throw new TypeError('Sandbox package entrypoints execute at module top level; remove defineSandbox({ run }).')`,
431
+ ` if (typeof result === 'undefined')`,
432
+ ` throw new TypeError('Sandbox package entrypoint must default-export a result.')`
433
+ ] : [
434
+ ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
435
+ ` const definition = mod?.default`,
436
+ ` if (!definition || typeof definition.run !== 'function')`,
437
+ ` throw new Error('Sandbox Definition must default-export defineSandbox({ run }).')`,
438
+ ` const result = await definition.run(input.payload, input.context)`
439
+ ];
303
440
  return [
304
- `import { readFile, writeFile } from 'node:fs/promises'`,
441
+ `import { mkdir, readFile, writeFile } from 'node:fs/promises'`,
442
+ `import { Buffer } from 'node:buffer'`,
305
443
  `import { pathToFileURL } from 'node:url'`,
306
444
  ``,
307
445
  `function normalizeError(error) {`,
@@ -319,17 +457,124 @@ function createEntrySource(definitionPath) {
319
457
  ` }`,
320
458
  `}`,
321
459
  ``,
460
+ `const valueMarker = ${JSON.stringify("vitehub:sandbox:value")}`,
461
+ ``,
462
+ `function isPlainObject(value) {`,
463
+ ` if (!value || typeof value !== 'object') return false`,
464
+ ` const prototype = Object.getPrototypeOf(value)`,
465
+ ` return prototype === Object.prototype || prototype === null`,
466
+ `}`,
467
+ ``,
468
+ `function hasMarker(value) {`,
469
+ ` return Object.prototype.hasOwnProperty.call(value, valueMarker)`,
470
+ `}`,
471
+ ``,
472
+ `function isBoxedJsonPrimitive(value) {`,
473
+ ` return value instanceof Boolean`,
474
+ ` || value instanceof Number`,
475
+ ` || value instanceof String`,
476
+ ` || Object.getPrototypeOf(value) === BigInt.prototype`,
477
+ `}`,
478
+ ``,
479
+ `function invalidDescriptor(label) {`,
480
+ ` return new TypeError('Sandbox ' + label + ' contains an invalid binary sidecar descriptor.')`,
481
+ `}`,
482
+ ``,
483
+ `async function reviveValue(value, assetsDir, label) {`,
484
+ ` if (Array.isArray(value))`,
485
+ ` return await Promise.all(value.map(entry => reviveValue(entry, assetsDir, label)))`,
486
+ ` if (!value || typeof value !== 'object') return value`,
487
+ ` if (!hasMarker(value)) {`,
488
+ ` return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [`,
489
+ ` key,`,
490
+ ` await reviveValue(entry, assetsDir, label),`,
491
+ ` ])))`,
492
+ ` }`,
493
+ ` const descriptor = value[valueMarker]`,
494
+ ` if (!isPlainObject(descriptor) || typeof descriptor.tag !== 'string')`,
495
+ ` throw invalidDescriptor(label)`,
496
+ ` if (descriptor.tag === 'object') {`,
497
+ ` if (!Array.isArray(descriptor.entries) || !descriptor.entries.every(entry => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string'))`,
498
+ ` throw invalidDescriptor(label)`,
499
+ ` return Object.fromEntries(await Promise.all(descriptor.entries.map(async ([key, entry]) => [`,
500
+ ` key,`,
501
+ ` await reviveValue(entry, assetsDir, label),`,
502
+ ` ])))`,
503
+ ` }`,
504
+ ` if (descriptor.tag !== 'binary'`,
505
+ ` || !Number.isSafeInteger(descriptor.id)`,
506
+ ` || Object.is(descriptor.id, -0)`,
507
+ ` || descriptor.id < 0`,
508
+ ` || (descriptor.kind !== 'blob' && descriptor.kind !== 'buffer' && descriptor.kind !== 'uint8array')`,
509
+ ` || (typeof descriptor.type !== 'undefined' && typeof descriptor.type !== 'string'))`,
510
+ ` throw invalidDescriptor(label)`,
511
+ ` const bytes = new Uint8Array(await readFile(assetsDir + '/' + descriptor.id))`,
512
+ ` return descriptor.kind === 'blob' ? new Blob([bytes], { type: descriptor.type || '' }) : descriptor.kind === 'buffer' ? Buffer.from(bytes) : bytes`,
513
+ `}`,
514
+ ``,
515
+ `async function extractValue(value, assetsDir, state = { nextId: 0 }, ancestors = new Set(), key = '', applyToJSON = true) {`,
516
+ ` const blob = typeof Blob !== 'undefined' && value instanceof Blob`,
517
+ ` const buffer = Buffer.isBuffer(value)`,
518
+ ` if (blob || value instanceof Uint8Array) {`,
519
+ ` const id = state.nextId++`,
520
+ ` state.directory ||= mkdir(assetsDir, { recursive: true })`,
521
+ ` await state.directory`,
522
+ ` const bytes = blob ? new Uint8Array(await value.arrayBuffer()) : value`,
523
+ ` await writeFile(assetsDir + '/' + id, bytes)`,
524
+ ` return { [valueMarker]: {`,
525
+ ` id,`,
526
+ ` kind: blob ? 'blob' : buffer ? 'buffer' : 'uint8array',`,
527
+ ` ...(blob && value.type ? { type: value.type } : {}),`,
528
+ ` tag: 'binary',`,
529
+ ` } }`,
530
+ ` }`,
531
+ ` if (value && typeof value === 'object' && applyToJSON && typeof value.toJSON === 'function')`,
532
+ ` return await extractValue(Reflect.apply(value.toJSON, value, [key]), assetsDir, state, ancestors, key, false)`,
533
+ ` if (Array.isArray(value)) {`,
534
+ ` if (ancestors.has(value))`,
535
+ ` throw new TypeError('Sandbox result must be JSON-serializable; cyclic value.')`,
536
+ ` const nextAncestors = new Set(ancestors).add(value)`,
537
+ ` return await Promise.all(value.map((entry, index) => extractValue(entry, assetsDir, state, nextAncestors, String(index))))`,
538
+ ` }`,
539
+ ` if (!value || typeof value !== 'object') return value`,
540
+ ` if (isBoxedJsonPrimitive(value)) return await extractValue(value.valueOf(), assetsDir, state, ancestors, key, false)`,
541
+ ` if (ancestors.has(value))`,
542
+ ` throw new TypeError('Sandbox result must be JSON-serializable; cyclic value.')`,
543
+ ` const nextAncestors = new Set(ancestors).add(value)`,
544
+ ` const sourceEntries = Object.entries(value).filter(([entryKey, entry]) => applyToJSON || entryKey !== 'toJSON' || typeof entry !== 'function')`,
545
+ ` const entries = await Promise.all(sourceEntries.map(async ([entryKey, entry]) => [`,
546
+ ` entryKey,`,
547
+ ` await extractValue(entry, assetsDir, state, nextAncestors, entryKey),`,
548
+ ` ]))`,
549
+ ` return hasMarker(value) ? { [valueMarker]: { entries, tag: 'object' } } : Object.fromEntries(entries)`,
550
+ `}`,
551
+ ``,
552
+ `async function serializeSuccess(result, assetsDir) {`,
553
+ ` try {`,
554
+ ` const encoded = await extractValue(result, assetsDir)`,
555
+ ` return JSON.stringify({ ok: true, result: encoded }, (key, value) => {`,
556
+ ` const type = typeof value`,
557
+ ` if (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint')`,
558
+ ` throw new TypeError('Sandbox result must be JSON-serializable; unsupported ' + type + (key ? ' at "' + key + '".' : '.'))`,
559
+ ` if (type === 'number' && !Number.isFinite(value))`,
560
+ ` throw new TypeError('Sandbox result must be JSON-serializable; non-finite number' + (key ? ' at "' + key + '".' : '.'))`,
561
+ ` return value`,
562
+ ` })`,
563
+ ` }`,
564
+ ` catch (error) {`,
565
+ ` if (error instanceof TypeError && error.message.startsWith('Sandbox result must be JSON-serializable'))`,
566
+ ` throw error`,
567
+ ` throw new TypeError('Sandbox result must be JSON-serializable.', { cause: error })`,
568
+ ` }`,
569
+ `}`,
570
+ ``,
322
571
  `export async function main(argv = process.argv.slice(2)) {`,
323
572
  ` const [inputPath, outputPath] = argv`,
324
573
  ` try {`,
325
- ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
326
- ` const definition = mod?.default`,
327
- ` if (!definition || typeof definition.run !== 'function')`,
328
- ` throw new Error('Sandbox definition must default-export defineSandbox(...).')`,
329
574
  ` const raw = await readFile(inputPath, 'utf8')`,
330
- ` const input = JSON.parse(raw || '{}')`,
331
- ` const result = await definition.run(input.payload, input.context)`,
332
- ` const output = JSON.stringify({ ok: true, result })`,
575
+ ` const input = await reviveValue(JSON.parse(raw || '{}'), inputPath + '.files', 'input')`,
576
+ ...invocation,
577
+ ` const output = await serializeSuccess(result, outputPath + '.files')`,
333
578
  ` await writeFile(outputPath, output)`,
334
579
  ` console.log('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
335
580
  ` }`,
@@ -361,18 +606,44 @@ function createExecutionFiles(definitionName) {
361
606
  return {
362
607
  baseDir,
363
608
  entryPath: `${baseDir}/entry.mjs`,
609
+ inputAssetsDir: `${baseDir}/input.json.files`,
364
610
  inputPath: `${baseDir}/input.json`,
611
+ outputAssetsDir: `${baseDir}/output.json.files`,
365
612
  outputPath: `${baseDir}/output.json`
366
613
  };
367
614
  }
368
615
  function resolveSandboxModulePath(baseDir, modulePath) {
616
+ if (modulePath === ".") return baseDir;
369
617
  return `${baseDir}/${modulePath}`;
370
618
  }
619
+ function normalizeSandboxBundlePath(path) {
620
+ const slashPath = path.replace(/\\/g, "/");
621
+ const normalized = slashPath.replace(/^\/+|\/+$/g, "");
622
+ const parts = normalized.split("/").filter(Boolean);
623
+ if (!normalized || slashPath.startsWith("/") || /^[A-Za-z]:\//.test(slashPath) || parts.some((part) => part === "." || part === "..")) throw new Error(`[vitehub] Sandbox bundle path must stay inside the project: ${path}.`);
624
+ return parts.join("/");
625
+ }
371
626
  async function writeSandboxDefinitionBundle(sandbox, baseDir, bundle) {
372
- await Promise.all(Object.entries(bundle.modules).map(async ([modulePath, source]) => {
373
- const filePath = resolveSandboxModulePath(baseDir, modulePath);
374
- await sandbox.mkdir(dirname(filePath), { recursive: true });
375
- await sandbox.writeFile(filePath, source);
627
+ const files = Object.entries({
628
+ ...bundle.project ? Object.fromEntries(Object.entries(bundle.project.files).map(([path, file]) => [path, Uint8Array.from(Buffer.from(file.contents, file.encoding))])) : {},
629
+ ...bundle.modules
630
+ }).map(([path, source]) => ({
631
+ path: normalizeSandboxBundlePath(path),
632
+ source
633
+ }));
634
+ const modes = Object.entries(bundle.project?.files || {}).filter(([, file]) => Boolean(file.mode)).map(([path, file]) => ({
635
+ mode: file.mode,
636
+ path: normalizeSandboxBundlePath(path)
637
+ }));
638
+ await sandbox.files.remove(baseDir, { recursive: true });
639
+ await sandbox.files.mkdir(baseDir, { recursive: true });
640
+ await Promise.all(files.map(async ({ path, source }) => {
641
+ const parent = dirname(path);
642
+ if (parent !== ".") await sandbox.files.mkdir(`${baseDir}/${parent}`, { recursive: true });
643
+ await sandbox.files.write(`${baseDir}/${path}`, typeof source === "string" ? new TextEncoder().encode(source) : source);
644
+ }));
645
+ await Promise.all(modes.map(async ({ mode, path }) => {
646
+ await sandbox.exec("chmod", [mode.toString(8), `${baseDir}/${path}`]);
376
647
  }));
377
648
  }
378
649
  //#endregion
@@ -382,6 +653,7 @@ const DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 6e4;
382
653
  const MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 12e4;
383
654
  const EXEC_OUTPUT_RECOVERY_POLL_MS = 1e3;
384
655
  const EXEC_OUTPUT_PREVIEW_LENGTH = 500;
656
+ const HANDLER_DIAGNOSTIC_LENGTH = 16384;
385
657
  function getErrorMessage(error) {
386
658
  if (error instanceof Error) return error.message;
387
659
  if (error && typeof error === "object") {
@@ -394,21 +666,24 @@ function getErrorMessage(error) {
394
666
  return String(error);
395
667
  }
396
668
  function isRecoverableCloudflareExecError(error) {
397
- const sandboxError = error instanceof SandboxError ? error : void 0;
398
- if (sandboxError?.provider && sandboxError.provider !== "cloudflare") return false;
399
- if (sandboxError?.code === "TIMEOUT" || sandboxError?.code === "SANDBOX_TRANSPORT_ERROR") return true;
669
+ const metadata = readSandboxErrorMetadata(error);
670
+ if (metadata?.provider && metadata.provider !== "cloudflare") return false;
671
+ if (metadata?.code === "SANDBOX_TIMEOUT" || metadata?.code === "SANDBOX_TRANSPORT_ERROR") return true;
400
672
  return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error));
401
673
  }
402
674
  function createHandlerError(message, provider, details) {
403
- return new SandboxError(message, {
675
+ const publicDetails = {};
676
+ for (const [key, value] of Object.entries(details || {})) if (typeof value === "string") publicDetails[key] = value.slice(0, HANDLER_DIAGNOSTIC_LENGTH);
677
+ else if (value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) publicDetails[key] = value;
678
+ return sandboxError(message.slice(0, HANDLER_DIAGNOSTIC_LENGTH) || "Sandbox handler failed.", {
404
679
  code: "SANDBOX_HANDLER_ERROR",
405
680
  provider,
406
- details
681
+ details: Object.keys(publicDetails).length ? publicDetails : void 0
407
682
  });
408
683
  }
409
684
  function createTimeoutError(provider, timeout) {
410
- return new SandboxError(`Sandbox definition timed out after ${timeout}ms.`, {
411
- code: "TIMEOUT",
685
+ return sandboxError(`Sandbox definition timed out after ${timeout}ms.`, {
686
+ code: "SANDBOX_TIMEOUT",
412
687
  provider,
413
688
  details: { timeout }
414
689
  });
@@ -516,116 +791,248 @@ async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, e
516
791
  //#endregion
517
792
  //#region src/runtime/execute.ts
518
793
  const defaultNodeLauncher = "import(process.argv[1])";
794
+ const projectPreparations = /* @__PURE__ */ new Map();
519
795
  function toJson(value, label) {
520
796
  try {
521
797
  return JSON.stringify(value);
522
798
  } catch (error) {
523
- throw new SandboxError(`Sandbox ${label} must be JSON-serializable.`, {
524
- code: "SERIALIZATION_ERROR",
799
+ throw sandboxError(`Sandbox ${label} must be JSON-serializable.`, {
800
+ code: "SANDBOX_SERIALIZATION_ERROR",
525
801
  details: { label },
526
802
  cause: error
527
803
  });
528
804
  }
529
805
  }
530
- function resolveLauncher(_provider, runtime) {
531
- if (runtime) return {
532
- command: runtime.command,
533
- args: [...runtime.args || []]
534
- };
806
+ function resolveLauncher() {
535
807
  return {
536
808
  command: "node",
537
809
  args: ["-e", defaultNodeLauncher]
538
810
  };
539
811
  }
540
- async function executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context) {
812
+ async function prepareSandboxProject(sandbox, bundle, baseDir, options) {
813
+ const project = bundle.project;
814
+ if (!project) return baseDir;
815
+ const projectDir = `/tmp/vitehub-sandbox/projects/${project.digest}`;
816
+ const marker = `${projectDir}/.vitehub/prepared`;
817
+ await sandbox.mkdir("/tmp/vitehub-sandbox/projects", { recursive: true });
818
+ if (await sandbox.exists(marker)) return projectDir;
819
+ const preparationKey = `${sandbox.id}:${project.digest}`;
820
+ while (!await sandbox.exists(marker)) {
821
+ let preparation = projectPreparations.get(preparationKey);
822
+ let owned = false;
823
+ if (!preparation) {
824
+ owned = true;
825
+ preparation = prepareSandboxProjectAtomically(sandbox, {
826
+ ...bundle,
827
+ project
828
+ }, projectDir, marker, options);
829
+ projectPreparations.set(preparationKey, preparation);
830
+ preparation.finally(() => {
831
+ if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
832
+ }).catch(() => {});
833
+ }
834
+ try {
835
+ await preparation;
836
+ } catch (error) {
837
+ if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
838
+ if (owned || options.signal?.aborted) throw error;
839
+ continue;
840
+ }
841
+ if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
842
+ }
843
+ return projectDir;
844
+ }
845
+ async function prepareSandboxProjectAtomically(sandbox, bundle, projectDir, marker, options) {
846
+ if (await sandbox.exists(marker)) return;
847
+ const staging = `${projectDir}.staging-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
848
+ try {
849
+ await sandbox.mkdir(staging, { recursive: true });
850
+ await writeSandboxDefinitionBundle(sandbox, staging, bundle);
851
+ const result = await executeLauncher(sandbox, bundle.project.install.command, bundle.project.install.args, {
852
+ ...options,
853
+ cwd: resolveSandboxModulePath(staging, bundle.project.install.cwd)
854
+ });
855
+ if (!result.ok) throw sandboxError("Sandbox package preparation failed.", {
856
+ code: "SANDBOX_EXECUTION_ERROR",
857
+ details: {
858
+ command: bundle.project.install.command,
859
+ exitCode: result.code,
860
+ stderr: result.stderr
861
+ }
862
+ });
863
+ await sandbox.mkdir(`${staging}/.vitehub`, { recursive: true });
864
+ await sandbox.writeFile(`${staging}/.vitehub/prepared`, bundle.project.digest);
865
+ const published = await sandbox.exec("node", [
866
+ "-e",
867
+ "import(\"node:fs/promises\").then(({ rename }) => rename(process.argv[1], process.argv[2]))",
868
+ staging,
869
+ projectDir
870
+ ], { signal: options.signal });
871
+ if (!published.ok && !await sandbox.exists(marker)) throw sandboxError("Sandbox package preparation could not publish its project.", {
872
+ code: "SANDBOX_EXECUTION_ERROR",
873
+ details: {
874
+ exitCode: published.code,
875
+ stderr: published.stderr
876
+ }
877
+ });
878
+ } finally {
879
+ await sandbox.exec("rm", [
880
+ "-rf",
881
+ "--",
882
+ staging
883
+ ]).catch(() => {});
884
+ }
885
+ }
886
+ async function executeLauncher(sandbox, command, args, options) {
887
+ return await sandbox.exec(command, args, {
888
+ cwd: options.cwd,
889
+ env: options.env,
890
+ signal: options.signal,
891
+ timeout: options.timeout
892
+ });
893
+ }
894
+ async function executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, deadline) {
541
895
  const bundle = normalizeSandboxDefinitionBundle(source);
542
896
  const files = createExecutionFiles(definitionName);
543
- const definitionPath = resolveSandboxModulePath(files.baseDir, bundle.entry);
544
- const inputJson = toJson({
545
- payload,
546
- context
547
- }, "payload/context");
897
+ const throwIfAborted = () => {
898
+ if (signal?.aborted) throw createTimeoutError(sandbox.provider, definitionOptions?.timeout || 0);
899
+ };
548
900
  await sandbox.mkdir(files.baseDir, { recursive: true });
549
- await writeSandboxDefinitionBundle(sandbox, files.baseDir, bundle);
550
- await Promise.all([sandbox.writeFile(files.entryPath, createEntrySource(definitionPath)), sandbox.writeFile(files.inputPath, inputJson)]);
551
- const launcher = resolveLauncher(sandbox.provider, definitionOptions?.runtime);
552
- const execArgs = [
553
- ...launcher.args,
554
- files.entryPath,
555
- files.inputPath,
556
- files.outputPath
557
- ];
558
- let outputRaw = "";
559
- let execution;
560
901
  try {
561
- execution = await sandbox.exec(launcher.command, execArgs, {
562
- env: definitionOptions?.env,
902
+ throwIfAborted();
903
+ let inputJson = bundle.project ? toJson(await encodeSandboxValue(sandbox, {
904
+ payload,
905
+ context
906
+ }, files.inputAssetsDir, "payload/context", signal), "payload/context") : void 0;
907
+ const bundleBaseDir = await prepareSandboxProject(sandbox, bundle, files.baseDir, {
908
+ deadline,
909
+ signal,
563
910
  timeout: definitionOptions?.timeout
564
911
  });
565
- outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, execution, definitionOptions?.timeout, execution);
566
- } catch (error) {
567
- if (execution) outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, error, definitionOptions?.timeout, execution);
568
- else {
569
- const recoveredOutput = await recoverExecOutput(sandbox, files.outputPath, error, definitionOptions?.timeout, execution);
570
- if (recoveredOutput == null) throw error;
571
- outputRaw = recoveredOutput;
912
+ if (!bundle.project) await writeSandboxDefinitionBundle(sandbox, bundleBaseDir, bundle);
913
+ inputJson ||= toJson(await encodeSandboxValue(sandbox, {
914
+ payload,
915
+ context
916
+ }, files.inputAssetsDir, "payload/context", signal), "payload/context");
917
+ const definitionPath = resolveSandboxModulePath(bundleBaseDir, bundle.entry);
918
+ throwIfAborted();
919
+ await Promise.all([sandbox.writeFile(files.entryPath, createEntrySource(definitionPath, bundle.execution)), sandbox.writeFile(files.inputPath, inputJson)]);
920
+ throwIfAborted();
921
+ const launcher = resolveLauncher();
922
+ const execArgs = [
923
+ ...launcher.args,
924
+ files.entryPath,
925
+ files.inputPath,
926
+ files.outputPath
927
+ ];
928
+ let outputRaw = "";
929
+ let execution;
930
+ try {
931
+ execution = await executeLauncher(sandbox, launcher.command, execArgs, {
932
+ cwd: bundle.project ? resolveSandboxModulePath(bundleBaseDir, bundle.project.packagePath) : files.baseDir,
933
+ deadline,
934
+ env: definitionOptions?.env,
935
+ signal,
936
+ timeout: definitionOptions?.timeout
937
+ });
938
+ outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, execution, definitionOptions?.timeout, execution);
939
+ } catch (error) {
940
+ if (readSandboxErrorMetadata(error)?.details?.operation === "createSession") throw error;
941
+ if (execution) outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, error, definitionOptions?.timeout, execution);
942
+ else {
943
+ const recoveredOutput = await recoverExecOutput(sandbox, files.outputPath, error, definitionOptions?.timeout, execution);
944
+ if (recoveredOutput == null) throw error;
945
+ outputRaw = recoveredOutput;
946
+ }
572
947
  }
948
+ const output = tryParseSandboxOutput(outputRaw) || tryParseSandboxOutput(extractSandboxOutputFromExecution(execution) || "");
949
+ if (!output) throw createHandlerError("Sandbox definition output is not valid JSON.", sandbox.provider, {
950
+ output: outputRaw,
951
+ cause: "Output file was empty or contained incomplete JSON."
952
+ });
953
+ if (output.ok) return await decodeSandboxValue(sandbox, output.result, files.outputAssetsDir, "result");
954
+ throw createHandlerError(output.error?.message || "Sandbox definition failed.", sandbox.provider, {
955
+ name: output.error?.name,
956
+ stack: output.error?.stack,
957
+ cause: output.error?.cause,
958
+ stdout: execution?.stdout,
959
+ stderr: execution?.stderr,
960
+ exitCode: execution?.code
961
+ });
962
+ } finally {
963
+ if (sandbox.provider === "cloudflare") await sandbox.exec("rm", [
964
+ "-rf",
965
+ "--",
966
+ files.baseDir
967
+ ]).catch(() => {});
573
968
  }
574
- const output = tryParseSandboxOutput(outputRaw) || tryParseSandboxOutput(extractSandboxOutputFromExecution(execution) || "");
575
- if (!output) throw createHandlerError("Sandbox definition output is not valid JSON.", sandbox.provider, {
576
- output: outputRaw,
577
- cause: "Output file was empty or contained incomplete JSON."
578
- });
579
- if (output.ok) return output.result;
580
- throw createHandlerError(output.error?.message || "Sandbox definition failed.", sandbox.provider, {
581
- name: output.error?.name,
582
- stack: output.error?.stack,
583
- cause: output.error?.cause,
584
- stdout: execution?.stdout,
585
- stderr: execution?.stderr,
586
- exitCode: execution?.code
587
- });
588
969
  }
589
970
  async function executeSandboxDefinition(sandbox, definitionName, definitionOptions, source, payload, context) {
590
971
  const timeout = definitionOptions?.timeout;
591
- if (typeof timeout !== "number" || timeout <= 0 || sandbox.provider === "cloudflare") return await executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context);
972
+ if (typeof timeout !== "number" || timeout <= 0) return await executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context);
592
973
  let timeoutId;
974
+ const abortController = new AbortController();
975
+ const deadline = Date.now() + timeout;
593
976
  try {
594
- return await Promise.race([executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context), new Promise((_, reject) => {
595
- timeoutId = setTimeout(() => reject(createTimeoutError(sandbox.provider, timeout)), timeout);
977
+ return await Promise.race([executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, abortController.signal, deadline), new Promise((_, reject) => {
978
+ timeoutId = setTimeout(() => {
979
+ const timeoutError = createTimeoutError(sandbox.provider, timeout);
980
+ abortController.abort(timeoutError);
981
+ reject(timeoutError);
982
+ }, timeout);
596
983
  })]);
597
984
  } finally {
598
985
  if (timeoutId) clearTimeout(timeoutId);
599
986
  }
600
987
  }
601
988
  //#endregion
602
- //#region src/runtime/error-normalization.ts
603
- function readSandboxErrorMetadata(error) {
604
- if (!error || typeof error !== "object") return void 0;
605
- const metadata = error;
989
+ //#region src/runtime/execution-box.ts
990
+ function createSandboxExecutionBox(session, provider) {
606
991
  return {
607
- code: typeof metadata.code === "string" ? metadata.code : void 0,
608
- provider: typeof metadata.provider === "string" ? metadata.provider : void 0,
609
- cause: metadata.cause,
610
- details: typeof metadata.details === "object" && metadata.details !== null ? metadata.details : void 0
992
+ executionAuthority: session.executionAuthority,
993
+ id: session.id,
994
+ files: session.files,
995
+ provider,
996
+ async close() {
997
+ await session.close();
998
+ },
999
+ async exec(command, args, options) {
1000
+ return await session.exec(command, args, options);
1001
+ },
1002
+ async exists(path) {
1003
+ return await session.files.exists(path);
1004
+ },
1005
+ async mkdir(path, options) {
1006
+ await session.files.mkdir(path, options);
1007
+ },
1008
+ async readFile(path) {
1009
+ const contents = await session.files.read(path);
1010
+ if (!contents) throw new Error(`[vitehub] Sandbox file does not exist: ${path}`);
1011
+ return new TextDecoder().decode(contents);
1012
+ },
1013
+ async writeFile(path, contents) {
1014
+ await session.files.write(path, new TextEncoder().encode(contents));
1015
+ }
611
1016
  };
612
1017
  }
613
- function toSandboxError(error) {
614
- if (error instanceof SandboxError) return error;
615
- const metadata = readSandboxErrorMetadata(error);
616
- if (error instanceof Error) return new SandboxError(error.message, {
617
- code: metadata?.code || "SANDBOX_RUNTIME_ERROR",
618
- provider: metadata?.provider,
619
- details: metadata?.details,
620
- cause: metadata?.cause ?? error
621
- });
622
- return new SandboxError(String(error), {
623
- code: metadata?.code || "SANDBOX_RUNTIME_ERROR",
624
- provider: metadata?.provider,
625
- details: metadata?.details,
626
- cause: metadata?.cause ?? error
627
- });
1018
+ //#endregion
1019
+ //#region src/internal/shared/provider-detection.ts
1020
+ function createProviderDetector(rules) {
1021
+ return () => {
1022
+ for (const rule of rules) if (rule.when()) return rule.provider;
1023
+ };
628
1024
  }
1025
+ function getRuntimeEnv() {
1026
+ return typeof process !== "undefined" ? process.env : {};
1027
+ }
1028
+ const isCloudflare = () => {
1029
+ const env = getRuntimeEnv();
1030
+ return !!(env.CLOUDFLARE_WORKER || env.CF_PAGES);
1031
+ };
1032
+ const isVercel = () => {
1033
+ const env = getRuntimeEnv();
1034
+ return !!(env.VERCEL || env.VERCEL_ENV);
1035
+ };
629
1036
  //#endregion
630
1037
  //#region src/runtime/provider-loader-resolver.ts
631
1038
  async function loadSandboxProviderRuntime(provider) {
@@ -635,15 +1042,37 @@ async function loadSandboxProviderRuntime(provider) {
635
1042
  }
636
1043
  //#endregion
637
1044
  //#region src/runtime/provider-resolution.ts
638
- const allowedDefinitionKeys = new Set([
639
- "timeout",
640
- "env",
641
- "runtime"
642
- ]);
1045
+ const allowedDefinitionKeys = new Set(["timeout", "env"]);
1046
+ const detectProvider = createProviderDetector([{
1047
+ provider: "cloudflare",
1048
+ when: isCloudflare
1049
+ }, {
1050
+ provider: "vercel",
1051
+ when: isVercel
1052
+ }]);
1053
+ function detectSandbox() {
1054
+ const env = typeof process !== "undefined" ? process.env : {};
1055
+ const type = detectProvider() || "none";
1056
+ if (type === "cloudflare") return {
1057
+ type,
1058
+ details: { runtime: typeof process === "undefined" ? "workerd" : "node" }
1059
+ };
1060
+ if (type === "vercel") return {
1061
+ type,
1062
+ details: { env: env.VERCEL_ENV }
1063
+ };
1064
+ return { type };
1065
+ }
1066
+ function hashCloudflareSandboxName(name) {
1067
+ let hash = 2166136261;
1068
+ for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), 16777619);
1069
+ return (hash >>> 0).toString(36);
1070
+ }
643
1071
  function createCloudflareExecutionSandboxId(name, sandboxId) {
644
1072
  if (sandboxId) return sandboxId;
645
- const hash = globalThis.crypto.randomUUID().replace(/-/g, "").slice(0, 24);
646
- return `vitehub-${name.replace(/[^a-z0-9-]/gi, "-").toLowerCase()}-${hash}`;
1073
+ const prefix = "vitehub-";
1074
+ const suffix = `-${hashCloudflareSandboxName(name)}-definition`;
1075
+ return `${prefix}${encodeURIComponent(name).slice(0, 248 - suffix.length)}${suffix}`;
647
1076
  }
648
1077
  function resolveRuntimeProvider(provider, event) {
649
1078
  if (provider?.provider) return provider.provider;
@@ -652,22 +1081,17 @@ function resolveRuntimeProvider(provider, event) {
652
1081
  if (getCloudflareEnv(event)) return "cloudflare";
653
1082
  const detected = detectSandbox();
654
1083
  if (detected.type === "cloudflare" || detected.type === "vercel") return detected.type;
655
- throw new SandboxError("Sandbox provider could not be inferred. Configure `sandbox.provider` as `cloudflare` or `vercel`.", { code: "SANDBOX_PROVIDER_REQUIRED" });
1084
+ throw sandboxError("Sandbox provider could not be inferred. Configure `sandbox.provider` as `cloudflare` or `vercel`.", { code: "SANDBOX_PROVIDER_REQUIRED" });
656
1085
  }
657
1086
  function assertSandboxDefinitionOptions(local) {
658
1087
  const invalidKeys = Object.keys(local).filter((key) => !allowedDefinitionKeys.has(key));
659
- if (invalidKeys.length > 0) throw new TypeError(`[vitehub] Sandbox definition options only support timeout, env, runtime. Unsupported: ${invalidKeys.join(", ")}`);
1088
+ if (invalidKeys.length > 0) throw new TypeError(`[vitehub] Sandbox definition options only support timeout and env. Unsupported: ${invalidKeys.join(", ")}`);
660
1089
  }
661
- async function resolveSandboxProvider(provider, providerOptions, local, context) {
662
- const runtimeProvider = await loadSandboxProviderRuntime(provider);
663
- const resolvedProvider = await runtimeProvider.resolveSandboxProvider({
1090
+ async function resolveSandboxBox(provider, providerOptions, local, context) {
1091
+ return await (await loadSandboxProviderRuntime(provider)).resolveSandboxBox({
664
1092
  local,
665
1093
  provider: providerOptions
666
1094
  }, context);
667
- return {
668
- createSandboxClient: runtimeProvider.createSandboxClient,
669
- resolvedProvider
670
- };
671
1095
  }
672
1096
  function withSandboxProvider(provider, options) {
673
1097
  return {
@@ -678,40 +1102,38 @@ function withSandboxProvider(provider, options) {
678
1102
  //#endregion
679
1103
  //#region src/runtime/result.ts
680
1104
  function ok(value) {
681
- return {
682
- isOk: () => true,
683
- isErr: () => false,
684
- value
685
- };
1105
+ return [null, value];
686
1106
  }
687
1107
  function err(error) {
688
- return {
689
- isOk: () => false,
690
- isErr: () => true,
691
- error
692
- };
1108
+ return [error, void 0];
693
1109
  }
694
1110
  //#endregion
695
1111
  //#region src/runtime/runtime.ts
1112
+ const cloudflareRunQueues = /* @__PURE__ */ new Map();
1113
+ async function serializeCloudflareRun(id, run) {
1114
+ if (!id) return await run();
1115
+ const previous = cloudflareRunQueues.get(id) ?? Promise.resolve();
1116
+ let release;
1117
+ const current = new Promise((resolve) => {
1118
+ release = resolve;
1119
+ });
1120
+ cloudflareRunQueues.set(id, current);
1121
+ await previous;
1122
+ try {
1123
+ return await run();
1124
+ } finally {
1125
+ release();
1126
+ if (cloudflareRunQueues.get(id) === current) cloudflareRunQueues.delete(id);
1127
+ }
1128
+ }
696
1129
  const sandboxRegistry = {};
697
1130
  function isRetriableCloudflareSandboxError(error) {
698
- const sandboxError = error instanceof SandboxError ? error : void 0;
699
1131
  const metadata = readSandboxErrorMetadata(error);
700
- const provider = sandboxError?.provider || metadata?.provider;
1132
+ const provider = metadata?.provider;
701
1133
  if (provider && provider !== "cloudflare") return false;
702
1134
  const extraMessage = metadata?.cause instanceof Error ? metadata.cause.message : "";
703
1135
  return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error, extraMessage));
704
1136
  }
705
- async function createSandboxWithConfig(config, local = {}, context = {}) {
706
- assertSandboxDefinitionOptions(local);
707
- const event = context.event ?? safeUseRequest();
708
- const resolvedProviderConfig = getSandboxFeatureProvider(config);
709
- const provider = resolveRuntimeProvider(resolvedProviderConfig, event);
710
- const { createSandboxClient, resolvedProvider } = await resolveSandboxProvider(provider, withSandboxProvider(provider, resolvedProviderConfig), local, { event });
711
- const validation = validateSandboxConfig(resolvedProvider);
712
- if (!validation.ok) throw new SandboxError((validation.issues.find((issue) => issue.severity === "error") || validation.issues[0])?.message || `[${provider}] invalid sandbox config`);
713
- return await createSandboxClient(resolvedProvider);
714
- }
715
1137
  const sandboxRuntime = createResourceRuntime({
716
1138
  feature: "sandbox",
717
1139
  readConfig(runtimeConfig) {
@@ -724,42 +1146,43 @@ const sandboxRuntime = createResourceRuntime({
724
1146
  return getSandboxRuntimeRegistry()?.[property] ?? target[property];
725
1147
  } }),
726
1148
  validate(definition) {
727
- return !!definition.bundle && typeof definition.bundle === "object" && typeof definition.bundle.entry === "string" && definition.bundle.entry.length > 0 && !!definition.bundle.modules && typeof definition.bundle.modules === "object" && Object.keys(definition.bundle.modules).length > 0;
1149
+ return !!definition.bundle && typeof definition.bundle === "object" && typeof definition.bundle.entry === "string" && definition.bundle.entry.length > 0 && !!definition.bundle.modules && typeof definition.bundle.modules === "object" && (Object.hasOwn(definition.bundle.modules, definition.bundle.entry) || !!definition.bundle.project?.files && typeof definition.bundle.project.files === "object" && Object.hasOwn(definition.bundle.project.files, definition.bundle.entry));
728
1150
  }
729
1151
  },
730
1152
  port: {
731
1153
  async resolve(context) {
1154
+ assertSandboxDefinitionOptions(context.definition.options ?? {});
732
1155
  const config = getSandboxFeatureProvider(context.config);
733
1156
  const provider = resolveRuntimeProvider(config, context.event);
734
- return (await resolveSandboxProvider(provider, withSandboxProvider(provider, config), context.definition.options ?? {}, { event: context.event })).resolvedProvider;
1157
+ return await resolveSandboxBox(provider, withSandboxProvider(provider, config), context.definition.options ?? {}, { event: context.event });
735
1158
  },
736
1159
  async create(provider, context) {
737
- const runtimeProvider = await loadSandboxProviderRuntime(provider.provider);
1160
+ const packageManager = context.definition.bundle.project?.install.command;
1161
+ const box = await provider.resolveBox(["node", ...packageManager ? [packageManager] : []]);
738
1162
  return {
1163
+ executionAuthority: box.plan.executionAuthority,
739
1164
  name: context.name,
740
1165
  async run(payload, options = {}) {
741
1166
  const cloudflareSandboxId = provider.provider === "cloudflare" ? createCloudflareExecutionSandboxId(context.name, options.sandboxId || provider.sandboxId) : void 0;
742
1167
  const attempts = provider.provider === "cloudflare" ? CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length + 1 : 1;
743
- for (let attempt = 0; attempt < attempts; attempt++) {
744
- let sandbox;
745
- try {
746
- const createdSandbox = await runtimeProvider.createSandboxClient(cloudflareSandboxId ? {
747
- ...provider,
748
- sandboxId: cloudflareSandboxId
749
- } : provider);
750
- sandbox = createdSandbox;
751
- return await executeSandboxDefinition(createdSandbox, context.name, context.definition.options, context.definition.bundle, payload, options.context);
752
- } catch (error) {
753
- const sandboxError = toSandboxError(error);
754
- if (!(provider.provider === "cloudflare" && attempt < CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length && isRetriableCloudflareSandboxError(sandboxError))) throw sandboxError;
755
- await sleep(CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS[attempt]);
756
- } finally {
757
- await sandbox?.stop().catch(() => {});
1168
+ return await serializeCloudflareRun(cloudflareSandboxId, async () => {
1169
+ for (let attempt = 0; attempt < attempts; attempt++) {
1170
+ let sandbox;
1171
+ try {
1172
+ sandbox = createSandboxExecutionBox(await box.open({ id: cloudflareSandboxId }), provider.provider);
1173
+ return await executeSandboxDefinition(sandbox, context.name, context.definition.options, context.definition.bundle, payload, options.context);
1174
+ } catch (error) {
1175
+ const sandboxError = toSandboxError(error);
1176
+ if (!(provider.provider === "cloudflare" && attempt < CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length && isRetriableCloudflareSandboxError(sandboxError))) throw sandboxError;
1177
+ await sleep(CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS[attempt]);
1178
+ } finally {
1179
+ if (provider.closeAfterRun !== false) await sandbox?.close().catch(() => {});
1180
+ }
758
1181
  }
759
- }
760
- throw new SandboxError("Cloudflare sandbox retries exhausted.", {
761
- code: "SANDBOX_RUNTIME_ERROR",
762
- provider: provider.provider
1182
+ throw sandboxError("Cloudflare sandbox retries exhausted.", {
1183
+ code: "SANDBOX_RUNTIME_ERROR",
1184
+ provider: provider.provider
1185
+ });
763
1186
  });
764
1187
  }
765
1188
  };
@@ -782,4 +1205,4 @@ async function runSandbox(name, payload, options) {
782
1205
  return await runSandboxRuntime(name, payload, options);
783
1206
  }
784
1207
  //#endregion
785
- export { createSandboxWithConfig, defineSandbox, readRequestPayload, readValidatedPayload, runSandbox };
1208
+ export { defineSandbox, readRequestPayload, readValidatedPayload, resolveSandboxRunner, runSandbox };