@vite-hub/sandbox 0.0.0 → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -1
- package/dist/_shared-CJ2_pS4E.js +53 -0
- package/dist/cloudflare-retry-Cfra7MvS.js +21 -0
- package/dist/common-CS4FcWrh.d.ts +369 -0
- package/dist/index-B4j3Mvzr.d.ts +146 -0
- package/dist/index.d.ts +74 -0
- package/dist/index.js +785 -0
- package/dist/integration-wkNE8jMO.js +2032 -0
- package/dist/module-types-BomzaqnM.js +7 -0
- package/dist/module-types-CUcY8iuI.d.ts +88 -0
- package/dist/nitro.d.ts +19 -0
- package/dist/nitro.js +488 -0
- package/dist/provider-detection-IbezCeoR.js +25 -0
- package/dist/runtime/empty-registry.d.ts +6 -0
- package/dist/runtime/empty-registry.js +20 -0
- package/dist/runtime/nitro-plugin.d.ts +4 -0
- package/dist/runtime/nitro-plugin.js +8 -0
- package/dist/runtime/provider-loader.d.ts +17 -0
- package/dist/runtime/provider-loader.js +21 -0
- package/dist/runtime/providers/cloudflare.d.ts +35 -0
- package/dist/runtime/providers/cloudflare.js +22 -0
- package/dist/runtime/providers/vercel.d.ts +21 -0
- package/dist/runtime/providers/vercel.js +65 -0
- package/dist/runtime/state.d.ts +17 -0
- package/dist/runtime/state.js +21 -0
- package/dist/sandbox/providers/cloudflare.d.ts +7 -0
- package/dist/sandbox/providers/cloudflare.js +339 -0
- package/dist/sandbox/providers/vercel.d.ts +17 -0
- package/dist/sandbox/providers/vercel.js +538 -0
- package/dist/shared-pqTHYWg1.d.ts +8 -0
- package/dist/utils-V7ODsDW_.js +44 -0
- package/dist/vercel-runtime-BPzvh_6V.js +11 -0
- package/dist/vite.d.ts +40 -0
- package/dist/vite.js +441 -0
- package/package.json +103 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,785 @@
|
|
|
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";
|
|
5
|
+
import { getSandboxRuntimeConfig, getSandboxRuntimeRegistry } from "./runtime/state.js";
|
|
6
|
+
import { t as getSandboxFeatureProvider } from "./module-types-BomzaqnM.js";
|
|
7
|
+
import { readBody } from "h3";
|
|
8
|
+
import { upperFirst } from "scule";
|
|
9
|
+
import { useRuntimeConfig } from "nitro/runtime-config";
|
|
10
|
+
import { getContext } from "unctx";
|
|
11
|
+
import { dirname } from "pathe";
|
|
12
|
+
//#region src/internal/shared/definition.ts
|
|
13
|
+
function assertDefinitionHandler(functionName, handler, label) {
|
|
14
|
+
if (typeof handler !== "function") throw new TypeError(`[vitehub] \`${functionName}()\` requires a ${label} as the first argument.`);
|
|
15
|
+
}
|
|
16
|
+
function validateDefinitionOptions(functionName, options, config) {
|
|
17
|
+
if (typeof options === "undefined") return void 0;
|
|
18
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError(`[vitehub] \`${functionName}()\` accepts \`(handler, options?)\`.`);
|
|
19
|
+
const invalidKeys = Object.keys(options).filter((key) => {
|
|
20
|
+
if (config.allowedKeys) return !config.allowedKeys.includes(key);
|
|
21
|
+
return config.disallowedKeys?.includes(key);
|
|
22
|
+
});
|
|
23
|
+
if (invalidKeys.length) throw new TypeError(`[vitehub] \`${functionName}()\` ${config.invalidKeysMessage}. Unsupported keys: ${invalidKeys.join(", ")}.`);
|
|
24
|
+
return options;
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
//#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, {
|
|
43
|
+
allowedKeys: [
|
|
44
|
+
"timeout",
|
|
45
|
+
"env",
|
|
46
|
+
"runtime"
|
|
47
|
+
],
|
|
48
|
+
invalidKeysMessage: "supports only portable sandbox options (timeout, env, runtime)"
|
|
49
|
+
});
|
|
50
|
+
assertDefinitionHandler(functionName, run, "sandbox handler");
|
|
51
|
+
return {
|
|
52
|
+
run,
|
|
53
|
+
options: validated ? {
|
|
54
|
+
...validated,
|
|
55
|
+
runtime: validateRuntimeOptions(functionName, validated.runtime)
|
|
56
|
+
} : void 0
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function defineSandbox(run, options) {
|
|
60
|
+
return createSandboxDefinition("defineSandbox", run, options);
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/internal/shared/request-payload.ts
|
|
64
|
+
async function readRequestPayload(event, fallback = {}) {
|
|
65
|
+
if (typeof event.req?.json === "function") return await event.req.json().catch(() => fallback);
|
|
66
|
+
return await readBody(event).catch(() => fallback);
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region src/internal/shared/validation.ts
|
|
70
|
+
const VALIDATION_FAILED = "Validation failed";
|
|
71
|
+
function isObject(value) {
|
|
72
|
+
return !!value && typeof value === "object";
|
|
73
|
+
}
|
|
74
|
+
function hasStandardValidator(value) {
|
|
75
|
+
return isObject(value) && "~standard" in value && isObject(value["~standard"]) && typeof value["~standard"].validate === "function";
|
|
76
|
+
}
|
|
77
|
+
function isErrorWithHttpMetadata(error) {
|
|
78
|
+
if (!(error instanceof Error)) return false;
|
|
79
|
+
const e = error;
|
|
80
|
+
return typeof e.status === "number" || typeof e.statusCode === "number" || typeof e.statusText === "string" || typeof e.statusMessage === "string";
|
|
81
|
+
}
|
|
82
|
+
function readIssues(value) {
|
|
83
|
+
if (!isObject(value)) return void 0;
|
|
84
|
+
if (Array.isArray(value.issues)) return value.issues;
|
|
85
|
+
if (isObject(value.data) && Array.isArray(value.data.issues)) return value.data.issues;
|
|
86
|
+
}
|
|
87
|
+
function readStatusCode(value) {
|
|
88
|
+
if (!isObject(value)) return 400;
|
|
89
|
+
if (typeof value.statusCode === "number") return value.statusCode;
|
|
90
|
+
if (typeof value.status === "number") return value.status;
|
|
91
|
+
return 400;
|
|
92
|
+
}
|
|
93
|
+
function readStatusText(value) {
|
|
94
|
+
if (!isObject(value)) return VALIDATION_FAILED;
|
|
95
|
+
if (typeof value.statusMessage === "string" && value.statusMessage) return value.statusMessage;
|
|
96
|
+
if (typeof value.statusText === "string" && value.statusText) return value.statusText;
|
|
97
|
+
return VALIDATION_FAILED;
|
|
98
|
+
}
|
|
99
|
+
function readMessage(value) {
|
|
100
|
+
if (value instanceof Error) return value.message || "Validation failed";
|
|
101
|
+
if (isObject(value) && typeof value.message === "string" && value.message) return value.message;
|
|
102
|
+
return VALIDATION_FAILED;
|
|
103
|
+
}
|
|
104
|
+
function readData(value, issues) {
|
|
105
|
+
const base = isObject(value) && isObject(value.data) ? { ...value.data } : {};
|
|
106
|
+
const message = value instanceof Error ? VALIDATION_FAILED : typeof base.message === "string" && base.message || readMessage(value);
|
|
107
|
+
return {
|
|
108
|
+
...base,
|
|
109
|
+
message,
|
|
110
|
+
...issues ? { issues } : {}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
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
|
+
function createValidationError(cause) {
|
|
139
|
+
if (isErrorWithHttpMetadata(cause)) return cause;
|
|
140
|
+
return new VitehubValidationError(cause);
|
|
141
|
+
}
|
|
142
|
+
async function readValidatedPayload(payload, validate, options) {
|
|
143
|
+
if (hasStandardValidator(validate)) {
|
|
144
|
+
const result = await validate["~standard"].validate(payload);
|
|
145
|
+
if (result.issues?.length) throw createValidationError(options?.onError?.({
|
|
146
|
+
issues: result.issues,
|
|
147
|
+
value: payload
|
|
148
|
+
}) || {
|
|
149
|
+
issues: result.issues,
|
|
150
|
+
message: "Validation failed"
|
|
151
|
+
});
|
|
152
|
+
return result.value;
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const result = await validate(payload);
|
|
156
|
+
if (result === false) throw createValidationError(options?.onError?.({
|
|
157
|
+
issues: [{ message: "Validation failed" }],
|
|
158
|
+
value: payload
|
|
159
|
+
}) || { message: "Validation failed" });
|
|
160
|
+
if (result === true || result == null) return payload;
|
|
161
|
+
return result;
|
|
162
|
+
} catch (error) {
|
|
163
|
+
throw createValidationError(error);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
//#endregion
|
|
167
|
+
//#region src/internal/shared/named-resource.ts
|
|
168
|
+
function resolveNamedResourceName(feature, name) {
|
|
169
|
+
if (!name) throw new Error(`[vitehub] ${upperFirst(feature)} name is required. Pass an explicit name.`);
|
|
170
|
+
return name;
|
|
171
|
+
}
|
|
172
|
+
function createUnknownNamedResourceError(feature, name) {
|
|
173
|
+
return /* @__PURE__ */ new Error(`[vitehub] Unknown ${feature} "${name}".`);
|
|
174
|
+
}
|
|
175
|
+
function createInvalidNamedResourceError(feature, name) {
|
|
176
|
+
return /* @__PURE__ */ new Error(`[vitehub] ${upperFirst(feature)} "${name}" is invalid.`);
|
|
177
|
+
}
|
|
178
|
+
const nitroAsyncContext = getContext("nitro-app");
|
|
179
|
+
function safeUseRequest() {
|
|
180
|
+
try {
|
|
181
|
+
return nitroAsyncContext.use().request;
|
|
182
|
+
} catch {
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
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();
|
|
194
|
+
}
|
|
195
|
+
async function loadRegistryEntry(registry, name) {
|
|
196
|
+
const entry = registry[name];
|
|
197
|
+
if (!entry) return void 0;
|
|
198
|
+
if (typeof entry === "function") return (await entry()).default;
|
|
199
|
+
return entry;
|
|
200
|
+
}
|
|
201
|
+
//#endregion
|
|
202
|
+
//#region src/internal/shared/resource-runtime.ts
|
|
203
|
+
function readFeatureRuntimeConfig(readConfig, getFallbackConfig) {
|
|
204
|
+
return readRuntimeValue((config) => readConfig(config), getFallbackConfig);
|
|
205
|
+
}
|
|
206
|
+
async function loadResourceRuntimeContext(options, name) {
|
|
207
|
+
const resolvedName = resolveNamedResourceName(options.feature, name);
|
|
208
|
+
const [config, definition] = await Promise.all([Promise.resolve(readFeatureRuntimeConfig(options.readConfig, options.getFallbackConfig)), loadRegistryEntry(options.registry.entries, resolvedName)]);
|
|
209
|
+
if (!definition) throw createUnknownNamedResourceError(options.feature, resolvedName);
|
|
210
|
+
if (options.registry.validate && !options.registry.validate(definition)) throw createInvalidNamedResourceError(options.feature, resolvedName);
|
|
211
|
+
return {
|
|
212
|
+
feature: options.feature,
|
|
213
|
+
name: resolvedName,
|
|
214
|
+
event: safeUseRequest(),
|
|
215
|
+
config,
|
|
216
|
+
definition
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function createResourceRuntime(options) {
|
|
220
|
+
async function load(name) {
|
|
221
|
+
return await loadResourceRuntimeContext(options, name);
|
|
222
|
+
}
|
|
223
|
+
async function createHandle(context) {
|
|
224
|
+
const provider = await options.port.resolve(context);
|
|
225
|
+
await options.port.validate?.(provider, context);
|
|
226
|
+
return {
|
|
227
|
+
provider,
|
|
228
|
+
handle: await options.port.create(provider, context)
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
async function get(name) {
|
|
232
|
+
const context = await load(name);
|
|
233
|
+
const cache = options.cache;
|
|
234
|
+
if (!cache) return (await createHandle(context)).handle;
|
|
235
|
+
const { provider } = await createHandleWithoutConstruct(context, options.port);
|
|
236
|
+
if (!cache.isSafe(provider, context)) return await options.port.create(provider, context);
|
|
237
|
+
const cacheKey = cache.getKey?.(context) ?? context.name;
|
|
238
|
+
const existing = cache.store.get(cacheKey);
|
|
239
|
+
if (existing) return await existing;
|
|
240
|
+
const pending = Promise.resolve(options.port.create(provider, context)).catch((error) => {
|
|
241
|
+
cache.store.delete(cacheKey);
|
|
242
|
+
throw error;
|
|
243
|
+
});
|
|
244
|
+
cache.store.set(cacheKey, pending);
|
|
245
|
+
return await pending;
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
load,
|
|
249
|
+
get
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
async function createHandleWithoutConstruct(context, port) {
|
|
253
|
+
const provider = await port.resolve(context);
|
|
254
|
+
await port.validate?.(provider, context);
|
|
255
|
+
return { provider };
|
|
256
|
+
}
|
|
257
|
+
//#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 }
|
|
276
|
+
};
|
|
277
|
+
return { type };
|
|
278
|
+
}
|
|
279
|
+
//#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));
|
|
293
|
+
return {
|
|
294
|
+
provider: provider.provider,
|
|
295
|
+
ok: issues.every((issue) => issue.severity !== "error"),
|
|
296
|
+
issues
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
//#endregion
|
|
300
|
+
//#region src/runtime/entry-script.ts
|
|
301
|
+
const EXEC_STDIO_OUTPUT_MARKER = "__VITEHUB_OUTPUT__";
|
|
302
|
+
function createEntrySource(definitionPath) {
|
|
303
|
+
return [
|
|
304
|
+
`import { readFile, writeFile } from 'node:fs/promises'`,
|
|
305
|
+
`import { pathToFileURL } from 'node:url'`,
|
|
306
|
+
``,
|
|
307
|
+
`function normalizeError(error) {`,
|
|
308
|
+
` if (error instanceof Error) {`,
|
|
309
|
+
` return {`,
|
|
310
|
+
` name: error.name,`,
|
|
311
|
+
` message: error.message,`,
|
|
312
|
+
` stack: error.stack,`,
|
|
313
|
+
` cause: error.cause ? String(error.cause) : undefined,`,
|
|
314
|
+
` }`,
|
|
315
|
+
` }`,
|
|
316
|
+
` return {`,
|
|
317
|
+
` name: 'Error',`,
|
|
318
|
+
` message: String(error),`,
|
|
319
|
+
` }`,
|
|
320
|
+
`}`,
|
|
321
|
+
``,
|
|
322
|
+
`export async function main(argv = process.argv.slice(2)) {`,
|
|
323
|
+
` const [inputPath, outputPath] = argv`,
|
|
324
|
+
` 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
|
+
` 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 })`,
|
|
333
|
+
` await writeFile(outputPath, output)`,
|
|
334
|
+
` console.log('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
|
|
335
|
+
` }`,
|
|
336
|
+
` catch (error) {`,
|
|
337
|
+
` const output = JSON.stringify({ ok: false, error: normalizeError(error) })`,
|
|
338
|
+
` await writeFile(outputPath, output)`,
|
|
339
|
+
` console.error('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
|
|
340
|
+
` process.exitCode = 1`,
|
|
341
|
+
` }`,
|
|
342
|
+
`}`,
|
|
343
|
+
``,
|
|
344
|
+
`await main()`,
|
|
345
|
+
``
|
|
346
|
+
].join("\n");
|
|
347
|
+
}
|
|
348
|
+
//#endregion
|
|
349
|
+
//#region src/runtime/execution-files.ts
|
|
350
|
+
const DEFAULT_DEFINITION_ENTRY = "definition.js";
|
|
351
|
+
function normalizeSandboxDefinitionBundle(source) {
|
|
352
|
+
if (typeof source === "string") return {
|
|
353
|
+
entry: DEFAULT_DEFINITION_ENTRY,
|
|
354
|
+
modules: { [DEFAULT_DEFINITION_ENTRY]: source }
|
|
355
|
+
};
|
|
356
|
+
return source;
|
|
357
|
+
}
|
|
358
|
+
function createExecutionFiles(definitionName) {
|
|
359
|
+
const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
360
|
+
const baseDir = `/tmp/vitehub-sandbox/${definitionName.replace(/[^a-z0-9/_-]/gi, "_")}-${nonce}`;
|
|
361
|
+
return {
|
|
362
|
+
baseDir,
|
|
363
|
+
entryPath: `${baseDir}/entry.mjs`,
|
|
364
|
+
inputPath: `${baseDir}/input.json`,
|
|
365
|
+
outputPath: `${baseDir}/output.json`
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function resolveSandboxModulePath(baseDir, modulePath) {
|
|
369
|
+
return `${baseDir}/${modulePath}`;
|
|
370
|
+
}
|
|
371
|
+
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);
|
|
376
|
+
}));
|
|
377
|
+
}
|
|
378
|
+
//#endregion
|
|
379
|
+
//#region src/runtime/output-recovery.ts
|
|
380
|
+
const MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 2e4;
|
|
381
|
+
const DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 6e4;
|
|
382
|
+
const MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 12e4;
|
|
383
|
+
const EXEC_OUTPUT_RECOVERY_POLL_MS = 1e3;
|
|
384
|
+
const EXEC_OUTPUT_PREVIEW_LENGTH = 500;
|
|
385
|
+
function getErrorMessage(error) {
|
|
386
|
+
if (error instanceof Error) return error.message;
|
|
387
|
+
if (error && typeof error === "object") {
|
|
388
|
+
const candidate = error;
|
|
389
|
+
if (typeof candidate.message === "string" && candidate.message) return candidate.message;
|
|
390
|
+
if (typeof candidate.stderr === "string" && candidate.stderr) return candidate.stderr;
|
|
391
|
+
if (typeof candidate.stdout === "string" && candidate.stdout) return candidate.stdout;
|
|
392
|
+
}
|
|
393
|
+
if (error === void 0) return void 0;
|
|
394
|
+
return String(error);
|
|
395
|
+
}
|
|
396
|
+
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;
|
|
400
|
+
return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error));
|
|
401
|
+
}
|
|
402
|
+
function createHandlerError(message, provider, details) {
|
|
403
|
+
return new SandboxError(message, {
|
|
404
|
+
code: "SANDBOX_HANDLER_ERROR",
|
|
405
|
+
provider,
|
|
406
|
+
details
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
function createTimeoutError(provider, timeout) {
|
|
410
|
+
return new SandboxError(`Sandbox definition timed out after ${timeout}ms.`, {
|
|
411
|
+
code: "TIMEOUT",
|
|
412
|
+
provider,
|
|
413
|
+
details: { timeout }
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
function tryParseSandboxOutput(outputRaw) {
|
|
417
|
+
if (!outputRaw.trim()) return null;
|
|
418
|
+
try {
|
|
419
|
+
return JSON.parse(outputRaw);
|
|
420
|
+
} catch {
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
function extractSandboxOutputFromExecution(execution) {
|
|
425
|
+
const streams = [execution?.stdout, execution?.stderr].filter(Boolean);
|
|
426
|
+
for (const stream of streams) for (const line of stream.split("\n").reverse()) {
|
|
427
|
+
const markerIndex = line.indexOf(EXEC_STDIO_OUTPUT_MARKER);
|
|
428
|
+
if (markerIndex < 0) continue;
|
|
429
|
+
return line.slice(markerIndex + 18);
|
|
430
|
+
}
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
function previewExecutionStream(stream) {
|
|
434
|
+
if (!stream) return void 0;
|
|
435
|
+
return stream.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH);
|
|
436
|
+
}
|
|
437
|
+
function getExecutionDiagnostics(execution) {
|
|
438
|
+
return {
|
|
439
|
+
args: Array.isArray(execution?.meta?.args) ? execution?.meta?.args : void 0,
|
|
440
|
+
command: typeof execution?.meta?.command === "string" ? execution.meta.command : void 0,
|
|
441
|
+
cwd: typeof execution?.meta?.cwd === "string" ? execution.meta.cwd : void 0,
|
|
442
|
+
exitCode: typeof execution?.code === "undefined" ? void 0 : execution.code,
|
|
443
|
+
stderrPreview: previewExecutionStream(execution?.stderr),
|
|
444
|
+
stdoutPreview: previewExecutionStream(execution?.stdout)
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
function getErrorDiagnostics(error) {
|
|
448
|
+
if (!error || typeof error !== "object" || !("details" in error)) return {};
|
|
449
|
+
const details = error.details;
|
|
450
|
+
if (!details || typeof details !== "object") return {};
|
|
451
|
+
return {
|
|
452
|
+
args: Array.isArray(details.args) ? details.args : void 0,
|
|
453
|
+
command: typeof details.command === "string" ? details.command : void 0,
|
|
454
|
+
cwd: typeof details.cwd === "string" ? details.cwd : void 0,
|
|
455
|
+
exitCode: typeof details.exitCode === "number" || details.exitCode === null ? details.exitCode : void 0,
|
|
456
|
+
spawnErrorCode: typeof details.spawnErrorCode === "string" ? details.spawnErrorCode : void 0,
|
|
457
|
+
spawnErrorMessage: typeof details.spawnErrorMessage === "string" ? details.spawnErrorMessage : void 0,
|
|
458
|
+
stderrPreview: typeof details.stderrPreview === "string" ? details.stderrPreview : void 0,
|
|
459
|
+
stdoutPreview: typeof details.stdoutPreview === "string" ? details.stdoutPreview : void 0
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
function resolveExecOutputRecoveryTimeout(timeout) {
|
|
463
|
+
if (!timeout || timeout <= 0) return DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS;
|
|
464
|
+
return Math.min(MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.max(MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.floor(timeout * .1)));
|
|
465
|
+
}
|
|
466
|
+
function createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution, details) {
|
|
467
|
+
return createHandlerError("Sandbox definition execution failed before producing an output file.", sandbox.provider, {
|
|
468
|
+
outputPath,
|
|
469
|
+
cause: getErrorMessage(error),
|
|
470
|
+
recoveryTimeout,
|
|
471
|
+
...details,
|
|
472
|
+
...getErrorDiagnostics(error),
|
|
473
|
+
...getExecutionDiagnostics(execution)
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
async function waitForExecOutput(sandbox, outputPath, error, timeout, execution, shouldAccept) {
|
|
477
|
+
const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
|
|
478
|
+
const deadline = Date.now() + recoveryTimeout;
|
|
479
|
+
let lastError = error;
|
|
480
|
+
let lastOutput = "";
|
|
481
|
+
while (Date.now() < deadline) {
|
|
482
|
+
try {
|
|
483
|
+
const output = await sandbox.readFile(outputPath);
|
|
484
|
+
lastOutput = output;
|
|
485
|
+
if (shouldAccept(output)) return output;
|
|
486
|
+
} catch (readError) {
|
|
487
|
+
lastError = readError;
|
|
488
|
+
}
|
|
489
|
+
await sleep(EXEC_OUTPUT_RECOVERY_POLL_MS);
|
|
490
|
+
}
|
|
491
|
+
throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution, {
|
|
492
|
+
lastReadError: getErrorMessage(lastError),
|
|
493
|
+
outputPreview: lastOutput.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH) || void 0
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
async function recoverExecOutput(sandbox, outputPath, error, timeout, execution) {
|
|
497
|
+
if (sandbox.provider !== "cloudflare" || !isRecoverableCloudflareExecError(error)) return null;
|
|
498
|
+
return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, (output) => !!tryParseSandboxOutput(output));
|
|
499
|
+
}
|
|
500
|
+
async function waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution) {
|
|
501
|
+
const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
|
|
502
|
+
if (sandbox.provider !== "cloudflare") throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution);
|
|
503
|
+
return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, (output) => !!tryParseSandboxOutput(output));
|
|
504
|
+
}
|
|
505
|
+
async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, execution) {
|
|
506
|
+
const executionOutput = extractSandboxOutputFromExecution(execution) || extractSandboxOutputFromExecution(error);
|
|
507
|
+
if (executionOutput) return executionOutput;
|
|
508
|
+
try {
|
|
509
|
+
const output = await sandbox.readFile(outputPath);
|
|
510
|
+
if (tryParseSandboxOutput(output)) return output;
|
|
511
|
+
} catch {
|
|
512
|
+
return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution);
|
|
513
|
+
}
|
|
514
|
+
return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution);
|
|
515
|
+
}
|
|
516
|
+
//#endregion
|
|
517
|
+
//#region src/runtime/execute.ts
|
|
518
|
+
const defaultNodeLauncher = "import(process.argv[1])";
|
|
519
|
+
function toJson(value, label) {
|
|
520
|
+
try {
|
|
521
|
+
return JSON.stringify(value);
|
|
522
|
+
} catch (error) {
|
|
523
|
+
throw new SandboxError(`Sandbox ${label} must be JSON-serializable.`, {
|
|
524
|
+
code: "SERIALIZATION_ERROR",
|
|
525
|
+
details: { label },
|
|
526
|
+
cause: error
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
function resolveLauncher(_provider, runtime) {
|
|
531
|
+
if (runtime) return {
|
|
532
|
+
command: runtime.command,
|
|
533
|
+
args: [...runtime.args || []]
|
|
534
|
+
};
|
|
535
|
+
return {
|
|
536
|
+
command: "node",
|
|
537
|
+
args: ["-e", defaultNodeLauncher]
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
async function executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context) {
|
|
541
|
+
const bundle = normalizeSandboxDefinitionBundle(source);
|
|
542
|
+
const files = createExecutionFiles(definitionName);
|
|
543
|
+
const definitionPath = resolveSandboxModulePath(files.baseDir, bundle.entry);
|
|
544
|
+
const inputJson = toJson({
|
|
545
|
+
payload,
|
|
546
|
+
context
|
|
547
|
+
}, "payload/context");
|
|
548
|
+
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
|
+
try {
|
|
561
|
+
execution = await sandbox.exec(launcher.command, execArgs, {
|
|
562
|
+
env: definitionOptions?.env,
|
|
563
|
+
timeout: definitionOptions?.timeout
|
|
564
|
+
});
|
|
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;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
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
|
+
}
|
|
589
|
+
async function executeSandboxDefinition(sandbox, definitionName, definitionOptions, source, payload, context) {
|
|
590
|
+
const timeout = definitionOptions?.timeout;
|
|
591
|
+
if (typeof timeout !== "number" || timeout <= 0 || sandbox.provider === "cloudflare") return await executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context);
|
|
592
|
+
let timeoutId;
|
|
593
|
+
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);
|
|
596
|
+
})]);
|
|
597
|
+
} finally {
|
|
598
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
//#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;
|
|
606
|
+
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
|
|
611
|
+
};
|
|
612
|
+
}
|
|
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
|
+
});
|
|
628
|
+
}
|
|
629
|
+
//#endregion
|
|
630
|
+
//#region src/runtime/provider-loader-resolver.ts
|
|
631
|
+
async function loadSandboxProviderRuntime(provider) {
|
|
632
|
+
return await (await import("vitehub-sandbox-provider-loader").catch(() => {
|
|
633
|
+
return new Function("specifier", "return import(specifier)")("@vite-hub/sandbox/runtime/provider-loader");
|
|
634
|
+
})).loadSandboxRuntimeProvider(provider);
|
|
635
|
+
}
|
|
636
|
+
//#endregion
|
|
637
|
+
//#region src/runtime/provider-resolution.ts
|
|
638
|
+
const allowedDefinitionKeys = new Set([
|
|
639
|
+
"timeout",
|
|
640
|
+
"env",
|
|
641
|
+
"runtime"
|
|
642
|
+
]);
|
|
643
|
+
function createCloudflareExecutionSandboxId(name, sandboxId) {
|
|
644
|
+
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}`;
|
|
647
|
+
}
|
|
648
|
+
function resolveRuntimeProvider(provider, event) {
|
|
649
|
+
if (provider?.provider) return provider.provider;
|
|
650
|
+
const envProvider = typeof process !== "undefined" ? process.env?.SANDBOX_PROVIDER : void 0;
|
|
651
|
+
if (envProvider === "cloudflare" || envProvider === "vercel") return envProvider;
|
|
652
|
+
if (getCloudflareEnv(event)) return "cloudflare";
|
|
653
|
+
const detected = detectSandbox();
|
|
654
|
+
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" });
|
|
656
|
+
}
|
|
657
|
+
function assertSandboxDefinitionOptions(local) {
|
|
658
|
+
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(", ")}`);
|
|
660
|
+
}
|
|
661
|
+
async function resolveSandboxProvider(provider, providerOptions, local, context) {
|
|
662
|
+
const runtimeProvider = await loadSandboxProviderRuntime(provider);
|
|
663
|
+
const resolvedProvider = await runtimeProvider.resolveSandboxProvider({
|
|
664
|
+
local,
|
|
665
|
+
provider: providerOptions
|
|
666
|
+
}, context);
|
|
667
|
+
return {
|
|
668
|
+
createSandboxClient: runtimeProvider.createSandboxClient,
|
|
669
|
+
resolvedProvider
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
function withSandboxProvider(provider, options) {
|
|
673
|
+
return {
|
|
674
|
+
...options,
|
|
675
|
+
provider
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
//#endregion
|
|
679
|
+
//#region src/runtime/result.ts
|
|
680
|
+
function ok(value) {
|
|
681
|
+
return {
|
|
682
|
+
isOk: () => true,
|
|
683
|
+
isErr: () => false,
|
|
684
|
+
value
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
function err(error) {
|
|
688
|
+
return {
|
|
689
|
+
isOk: () => false,
|
|
690
|
+
isErr: () => true,
|
|
691
|
+
error
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
//#endregion
|
|
695
|
+
//#region src/runtime/runtime.ts
|
|
696
|
+
const sandboxRegistry = {};
|
|
697
|
+
function isRetriableCloudflareSandboxError(error) {
|
|
698
|
+
const sandboxError = error instanceof SandboxError ? error : void 0;
|
|
699
|
+
const metadata = readSandboxErrorMetadata(error);
|
|
700
|
+
const provider = sandboxError?.provider || metadata?.provider;
|
|
701
|
+
if (provider && provider !== "cloudflare") return false;
|
|
702
|
+
const extraMessage = metadata?.cause instanceof Error ? metadata.cause.message : "";
|
|
703
|
+
return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error, extraMessage));
|
|
704
|
+
}
|
|
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
|
+
const sandboxRuntime = createResourceRuntime({
|
|
716
|
+
feature: "sandbox",
|
|
717
|
+
readConfig(runtimeConfig) {
|
|
718
|
+
return runtimeConfig.sandbox;
|
|
719
|
+
},
|
|
720
|
+
getFallbackConfig: getSandboxRuntimeConfig,
|
|
721
|
+
registry: {
|
|
722
|
+
entries: new Proxy(sandboxRegistry, { get(target, property) {
|
|
723
|
+
if (typeof property !== "string") return Reflect.get(target, property);
|
|
724
|
+
return getSandboxRuntimeRegistry()?.[property] ?? target[property];
|
|
725
|
+
} }),
|
|
726
|
+
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;
|
|
728
|
+
}
|
|
729
|
+
},
|
|
730
|
+
port: {
|
|
731
|
+
async resolve(context) {
|
|
732
|
+
const config = getSandboxFeatureProvider(context.config);
|
|
733
|
+
const provider = resolveRuntimeProvider(config, context.event);
|
|
734
|
+
return (await resolveSandboxProvider(provider, withSandboxProvider(provider, config), context.definition.options ?? {}, { event: context.event })).resolvedProvider;
|
|
735
|
+
},
|
|
736
|
+
async create(provider, context) {
|
|
737
|
+
const runtimeProvider = await loadSandboxProviderRuntime(provider.provider);
|
|
738
|
+
return {
|
|
739
|
+
name: context.name,
|
|
740
|
+
async run(payload, options = {}) {
|
|
741
|
+
const cloudflareSandboxId = provider.provider === "cloudflare" ? createCloudflareExecutionSandboxId(context.name, options.sandboxId || provider.sandboxId) : void 0;
|
|
742
|
+
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(() => {});
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
throw new SandboxError("Cloudflare sandbox retries exhausted.", {
|
|
761
|
+
code: "SANDBOX_RUNTIME_ERROR",
|
|
762
|
+
provider: provider.provider
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
async function resolveSandboxRunner(name) {
|
|
770
|
+
return await sandboxRuntime.get(name);
|
|
771
|
+
}
|
|
772
|
+
async function runSandboxRuntime(name, payload, options) {
|
|
773
|
+
try {
|
|
774
|
+
return ok(await (await resolveSandboxRunner(name)).run(payload, options));
|
|
775
|
+
} catch (error) {
|
|
776
|
+
return err(toSandboxError(error));
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
//#endregion
|
|
780
|
+
//#region src/runtime/public.ts
|
|
781
|
+
async function runSandbox(name, payload, options) {
|
|
782
|
+
return await runSandboxRuntime(name, payload, options);
|
|
783
|
+
}
|
|
784
|
+
//#endregion
|
|
785
|
+
export { createSandboxWithConfig, defineSandbox, readRequestPayload, readValidatedPayload, runSandbox };
|