@vite-hub/sandbox 0.0.0 → 0.0.2
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 +54 -1
- package/dist/cloudflare-env-2NctU8i7.js +12 -0
- package/dist/index-DiH4OGAU.d.ts +101 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +1208 -0
- package/dist/module-types-Cjqo67ay.d.ts +91 -0
- package/dist/module-types-Dj1MFmHT.js +7 -0
- package/dist/provider-loader-3ml65ZFy.d.ts +21 -0
- package/dist/runtime/empty-registry.d.ts +6 -0
- package/dist/runtime/empty-registry.js +20 -0
- package/dist/runtime/provider-loader.d.ts +2 -0
- package/dist/runtime/provider-loader.js +15 -0
- package/dist/runtime/providers/cloudflare.d.ts +30 -0
- package/dist/runtime/providers/cloudflare.js +25 -0
- package/dist/runtime/providers/vercel.d.ts +14 -0
- package/dist/runtime/providers/vercel.js +51 -0
- package/dist/runtime/state.d.ts +17 -0
- package/dist/runtime/state.js +21 -0
- package/dist/vite.d.ts +24 -0
- package/dist/vite.js +2363 -0
- package/package.json +112 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,1208 @@
|
|
|
1
|
+
import { t as getCloudflareEnv } from "./cloudflare-env-2NctU8i7.js";
|
|
2
|
+
import { getSandboxRuntimeConfig, getSandboxRuntimeRegistry } from "./runtime/state.js";
|
|
3
|
+
import { t as getSandboxFeatureProvider } from "./module-types-Dj1MFmHT.js";
|
|
4
|
+
import { readBody } from "h3";
|
|
5
|
+
import { ViteHubError, getViteHubErrorShape } from "@vite-hub/runtime";
|
|
6
|
+
import { upperFirst } from "scule";
|
|
7
|
+
import { dirname } from "pathe";
|
|
8
|
+
//#region src/internal/shared/definition.ts
|
|
9
|
+
function assertDefinitionHandler(functionName, handler, label) {
|
|
10
|
+
if (typeof handler !== "function") throw new TypeError(`[vitehub] \`${functionName}()\` requires a ${label} as the first argument.`);
|
|
11
|
+
}
|
|
12
|
+
function validateDefinitionOptions(functionName, options, config) {
|
|
13
|
+
if (typeof options === "undefined") return void 0;
|
|
14
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError(`[vitehub] \`${functionName}()\` accepts one options object.`);
|
|
15
|
+
const invalidKeys = Object.keys(options).filter((key) => {
|
|
16
|
+
if (config.allowedKeys) return !config.allowedKeys.includes(key);
|
|
17
|
+
return config.disallowedKeys?.includes(key);
|
|
18
|
+
});
|
|
19
|
+
if (invalidKeys.length) throw new TypeError(`[vitehub] \`${functionName}()\` ${config.invalidKeysMessage}. Unsupported keys: ${invalidKeys.join(", ")}.`);
|
|
20
|
+
return options;
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/runtime/registry.ts
|
|
24
|
+
function createSandboxDefinition(functionName, input) {
|
|
25
|
+
const validated = validateDefinitionOptions(functionName, input, {
|
|
26
|
+
allowedKeys: [
|
|
27
|
+
"run",
|
|
28
|
+
"timeout",
|
|
29
|
+
"env"
|
|
30
|
+
],
|
|
31
|
+
invalidKeysMessage: "supports only portable Sandbox options (run, timeout, env)"
|
|
32
|
+
});
|
|
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`");
|
|
36
|
+
return {
|
|
37
|
+
run,
|
|
38
|
+
options: Object.keys(options).length ? options : void 0
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function defineSandbox(input) {
|
|
42
|
+
return createSandboxDefinition("defineSandbox", input);
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region src/internal/shared/request-payload.ts
|
|
46
|
+
async function readRequestPayload(event, fallback = {}) {
|
|
47
|
+
if (typeof event.req?.json === "function") return await event.req.json().catch(() => fallback);
|
|
48
|
+
return await readBody(event).catch(() => fallback);
|
|
49
|
+
}
|
|
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
|
|
96
|
+
//#region src/internal/shared/validation.ts
|
|
97
|
+
const VALIDATION_FAILED = "Validation failed";
|
|
98
|
+
function isObject(value) {
|
|
99
|
+
return !!value && typeof value === "object";
|
|
100
|
+
}
|
|
101
|
+
function hasStandardValidator(value) {
|
|
102
|
+
return isObject(value) && "~standard" in value && isObject(value["~standard"]) && typeof value["~standard"].validate === "function";
|
|
103
|
+
}
|
|
104
|
+
function isErrorWithHttpMetadata(error) {
|
|
105
|
+
if (!(error instanceof Error)) return false;
|
|
106
|
+
const e = error;
|
|
107
|
+
return typeof e.status === "number" || typeof e.statusCode === "number" || typeof e.statusText === "string" || typeof e.statusMessage === "string";
|
|
108
|
+
}
|
|
109
|
+
function readIssues(value) {
|
|
110
|
+
if (!isObject(value)) return void 0;
|
|
111
|
+
if (Array.isArray(value.issues)) return value.issues;
|
|
112
|
+
if (isObject(value.data) && Array.isArray(value.data.issues)) return value.data.issues;
|
|
113
|
+
}
|
|
114
|
+
function readStatusCode(value) {
|
|
115
|
+
if (!isObject(value)) return 400;
|
|
116
|
+
if (typeof value.statusCode === "number") return value.statusCode;
|
|
117
|
+
if (typeof value.status === "number") return value.status;
|
|
118
|
+
return 400;
|
|
119
|
+
}
|
|
120
|
+
function readStatusText(value) {
|
|
121
|
+
if (!isObject(value)) return VALIDATION_FAILED;
|
|
122
|
+
if (typeof value.statusMessage === "string" && value.statusMessage) return value.statusMessage;
|
|
123
|
+
if (typeof value.statusText === "string" && value.statusText) return value.statusText;
|
|
124
|
+
return VALIDATION_FAILED;
|
|
125
|
+
}
|
|
126
|
+
function readMessage(value) {
|
|
127
|
+
if (value instanceof Error) return value.message || "Validation failed";
|
|
128
|
+
if (isObject(value) && typeof value.message === "string" && value.message) return value.message;
|
|
129
|
+
return VALIDATION_FAILED;
|
|
130
|
+
}
|
|
131
|
+
function readData(value, issues) {
|
|
132
|
+
const base = isObject(value) && isObject(value.data) ? { ...value.data } : {};
|
|
133
|
+
const message = value instanceof Error ? VALIDATION_FAILED : typeof base.message === "string" && base.message || readMessage(value);
|
|
134
|
+
return {
|
|
135
|
+
...base,
|
|
136
|
+
message,
|
|
137
|
+
...issues ? { issues } : {}
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function createValidationError(cause) {
|
|
141
|
+
if (isErrorWithHttpMetadata(cause)) return 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
|
+
});
|
|
157
|
+
}
|
|
158
|
+
async function readValidatedPayload(payload, validate, options) {
|
|
159
|
+
if (hasStandardValidator(validate)) {
|
|
160
|
+
const result = await validate["~standard"].validate(payload);
|
|
161
|
+
if (result.issues?.length) throw createValidationError(options?.onError?.({
|
|
162
|
+
issues: result.issues,
|
|
163
|
+
value: payload
|
|
164
|
+
}) || {
|
|
165
|
+
issues: result.issues,
|
|
166
|
+
message: "Validation failed"
|
|
167
|
+
});
|
|
168
|
+
return result.value;
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
const result = await validate(payload);
|
|
172
|
+
if (result === false) throw createValidationError(options?.onError?.({
|
|
173
|
+
issues: [{ message: "Validation failed" }],
|
|
174
|
+
value: payload
|
|
175
|
+
}) || { message: "Validation failed" });
|
|
176
|
+
if (result === true || result == null) return payload;
|
|
177
|
+
return result;
|
|
178
|
+
} catch (error) {
|
|
179
|
+
throw createValidationError(error);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
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
|
|
200
|
+
//#region src/internal/shared/named-resource.ts
|
|
201
|
+
function resolveNamedResourceName(feature, name) {
|
|
202
|
+
if (!name) throw new Error(`[vitehub] ${upperFirst(feature)} name is required. An explicit name is required.`);
|
|
203
|
+
return name;
|
|
204
|
+
}
|
|
205
|
+
function createUnknownNamedResourceError(feature, name) {
|
|
206
|
+
return /* @__PURE__ */ new Error(`[vitehub] Unknown ${feature} "${name}".`);
|
|
207
|
+
}
|
|
208
|
+
function createInvalidNamedResourceError(feature, name) {
|
|
209
|
+
return /* @__PURE__ */ new Error(`[vitehub] ${upperFirst(feature)} "${name}" is invalid.`);
|
|
210
|
+
}
|
|
211
|
+
function readRuntimeValue(read, fallback) {
|
|
212
|
+
const value = read({});
|
|
213
|
+
return typeof value === "undefined" ? fallback() : value;
|
|
214
|
+
}
|
|
215
|
+
async function loadRegistryEntry(registry, name) {
|
|
216
|
+
const entry = registry[name];
|
|
217
|
+
if (!entry) return void 0;
|
|
218
|
+
if (typeof entry === "function") return (await entry()).default;
|
|
219
|
+
return entry;
|
|
220
|
+
}
|
|
221
|
+
//#endregion
|
|
222
|
+
//#region src/internal/shared/resource-runtime.ts
|
|
223
|
+
function readFeatureRuntimeConfig(readConfig, getFallbackConfig) {
|
|
224
|
+
return readRuntimeValue((config) => readConfig(config), getFallbackConfig);
|
|
225
|
+
}
|
|
226
|
+
async function loadResourceRuntimeContext(options, name) {
|
|
227
|
+
const resolvedName = resolveNamedResourceName(options.feature, name);
|
|
228
|
+
const [config, definition] = await Promise.all([Promise.resolve(readFeatureRuntimeConfig(options.readConfig, options.getFallbackConfig)), loadRegistryEntry(options.registry.entries, resolvedName)]);
|
|
229
|
+
if (!definition) throw createUnknownNamedResourceError(options.feature, resolvedName);
|
|
230
|
+
if (options.registry.validate && !options.registry.validate(definition)) throw createInvalidNamedResourceError(options.feature, resolvedName);
|
|
231
|
+
return {
|
|
232
|
+
feature: options.feature,
|
|
233
|
+
name: resolvedName,
|
|
234
|
+
event: void 0,
|
|
235
|
+
config,
|
|
236
|
+
definition
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function createResourceRuntime(options) {
|
|
240
|
+
async function load(name) {
|
|
241
|
+
return await loadResourceRuntimeContext(options, name);
|
|
242
|
+
}
|
|
243
|
+
async function createHandle(context) {
|
|
244
|
+
const provider = await options.port.resolve(context);
|
|
245
|
+
await options.port.validate?.(provider, context);
|
|
246
|
+
return {
|
|
247
|
+
provider,
|
|
248
|
+
handle: await options.port.create(provider, context)
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
async function get(name) {
|
|
252
|
+
const context = await load(name);
|
|
253
|
+
const cache = options.cache;
|
|
254
|
+
if (!cache) return (await createHandle(context)).handle;
|
|
255
|
+
const { provider } = await createHandleWithoutConstruct(context, options.port);
|
|
256
|
+
if (!cache.isSafe(provider, context)) return await options.port.create(provider, context);
|
|
257
|
+
const cacheKey = cache.getKey?.(context) ?? context.name;
|
|
258
|
+
const existing = cache.store.get(cacheKey);
|
|
259
|
+
if (existing) return await existing;
|
|
260
|
+
const pending = Promise.resolve(options.port.create(provider, context)).catch((error) => {
|
|
261
|
+
cache.store.delete(cacheKey);
|
|
262
|
+
throw error;
|
|
263
|
+
});
|
|
264
|
+
cache.store.set(cacheKey, pending);
|
|
265
|
+
return await pending;
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
load,
|
|
269
|
+
get
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
async function createHandleWithoutConstruct(context, port) {
|
|
273
|
+
const provider = await port.resolve(context);
|
|
274
|
+
await port.validate?.(provider, context);
|
|
275
|
+
return { provider };
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
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
|
+
}
|
|
319
|
+
};
|
|
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;
|
|
387
|
+
}
|
|
388
|
+
//#endregion
|
|
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);
|
|
394
|
+
return {
|
|
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)
|
|
399
|
+
};
|
|
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
|
+
}
|
|
420
|
+
//#endregion
|
|
421
|
+
//#region src/runtime/entry-script.ts
|
|
422
|
+
const EXEC_STDIO_OUTPUT_MARKER = "__VITEHUB_OUTPUT__";
|
|
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
|
+
];
|
|
440
|
+
return [
|
|
441
|
+
`import { mkdir, readFile, writeFile } from 'node:fs/promises'`,
|
|
442
|
+
`import { Buffer } from 'node:buffer'`,
|
|
443
|
+
`import { pathToFileURL } from 'node:url'`,
|
|
444
|
+
``,
|
|
445
|
+
`function normalizeError(error) {`,
|
|
446
|
+
` if (error instanceof Error) {`,
|
|
447
|
+
` return {`,
|
|
448
|
+
` name: error.name,`,
|
|
449
|
+
` message: error.message,`,
|
|
450
|
+
` stack: error.stack,`,
|
|
451
|
+
` cause: error.cause ? String(error.cause) : undefined,`,
|
|
452
|
+
` }`,
|
|
453
|
+
` }`,
|
|
454
|
+
` return {`,
|
|
455
|
+
` name: 'Error',`,
|
|
456
|
+
` message: String(error),`,
|
|
457
|
+
` }`,
|
|
458
|
+
`}`,
|
|
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
|
+
``,
|
|
571
|
+
`export async function main(argv = process.argv.slice(2)) {`,
|
|
572
|
+
` const [inputPath, outputPath] = argv`,
|
|
573
|
+
` try {`,
|
|
574
|
+
` const raw = await readFile(inputPath, 'utf8')`,
|
|
575
|
+
` const input = await reviveValue(JSON.parse(raw || '{}'), inputPath + '.files', 'input')`,
|
|
576
|
+
...invocation,
|
|
577
|
+
` const output = await serializeSuccess(result, outputPath + '.files')`,
|
|
578
|
+
` await writeFile(outputPath, output)`,
|
|
579
|
+
` console.log('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
|
|
580
|
+
` }`,
|
|
581
|
+
` catch (error) {`,
|
|
582
|
+
` const output = JSON.stringify({ ok: false, error: normalizeError(error) })`,
|
|
583
|
+
` await writeFile(outputPath, output)`,
|
|
584
|
+
` console.error('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
|
|
585
|
+
` process.exitCode = 1`,
|
|
586
|
+
` }`,
|
|
587
|
+
`}`,
|
|
588
|
+
``,
|
|
589
|
+
`await main()`,
|
|
590
|
+
``
|
|
591
|
+
].join("\n");
|
|
592
|
+
}
|
|
593
|
+
//#endregion
|
|
594
|
+
//#region src/runtime/execution-files.ts
|
|
595
|
+
const DEFAULT_DEFINITION_ENTRY = "definition.js";
|
|
596
|
+
function normalizeSandboxDefinitionBundle(source) {
|
|
597
|
+
if (typeof source === "string") return {
|
|
598
|
+
entry: DEFAULT_DEFINITION_ENTRY,
|
|
599
|
+
modules: { [DEFAULT_DEFINITION_ENTRY]: source }
|
|
600
|
+
};
|
|
601
|
+
return source;
|
|
602
|
+
}
|
|
603
|
+
function createExecutionFiles(definitionName) {
|
|
604
|
+
const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
605
|
+
const baseDir = `/tmp/vitehub-sandbox/${definitionName.replace(/[^a-z0-9/_-]/gi, "_")}-${nonce}`;
|
|
606
|
+
return {
|
|
607
|
+
baseDir,
|
|
608
|
+
entryPath: `${baseDir}/entry.mjs`,
|
|
609
|
+
inputAssetsDir: `${baseDir}/input.json.files`,
|
|
610
|
+
inputPath: `${baseDir}/input.json`,
|
|
611
|
+
outputAssetsDir: `${baseDir}/output.json.files`,
|
|
612
|
+
outputPath: `${baseDir}/output.json`
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
function resolveSandboxModulePath(baseDir, modulePath) {
|
|
616
|
+
if (modulePath === ".") return baseDir;
|
|
617
|
+
return `${baseDir}/${modulePath}`;
|
|
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
|
+
}
|
|
626
|
+
async function writeSandboxDefinitionBundle(sandbox, baseDir, bundle) {
|
|
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}`]);
|
|
647
|
+
}));
|
|
648
|
+
}
|
|
649
|
+
//#endregion
|
|
650
|
+
//#region src/runtime/output-recovery.ts
|
|
651
|
+
const MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 2e4;
|
|
652
|
+
const DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 6e4;
|
|
653
|
+
const MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 12e4;
|
|
654
|
+
const EXEC_OUTPUT_RECOVERY_POLL_MS = 1e3;
|
|
655
|
+
const EXEC_OUTPUT_PREVIEW_LENGTH = 500;
|
|
656
|
+
const HANDLER_DIAGNOSTIC_LENGTH = 16384;
|
|
657
|
+
function getErrorMessage(error) {
|
|
658
|
+
if (error instanceof Error) return error.message;
|
|
659
|
+
if (error && typeof error === "object") {
|
|
660
|
+
const candidate = error;
|
|
661
|
+
if (typeof candidate.message === "string" && candidate.message) return candidate.message;
|
|
662
|
+
if (typeof candidate.stderr === "string" && candidate.stderr) return candidate.stderr;
|
|
663
|
+
if (typeof candidate.stdout === "string" && candidate.stdout) return candidate.stdout;
|
|
664
|
+
}
|
|
665
|
+
if (error === void 0) return void 0;
|
|
666
|
+
return String(error);
|
|
667
|
+
}
|
|
668
|
+
function isRecoverableCloudflareExecError(error) {
|
|
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;
|
|
672
|
+
return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error));
|
|
673
|
+
}
|
|
674
|
+
function createHandlerError(message, provider, details) {
|
|
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.", {
|
|
679
|
+
code: "SANDBOX_HANDLER_ERROR",
|
|
680
|
+
provider,
|
|
681
|
+
details: Object.keys(publicDetails).length ? publicDetails : void 0
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
function createTimeoutError(provider, timeout) {
|
|
685
|
+
return sandboxError(`Sandbox definition timed out after ${timeout}ms.`, {
|
|
686
|
+
code: "SANDBOX_TIMEOUT",
|
|
687
|
+
provider,
|
|
688
|
+
details: { timeout }
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
function tryParseSandboxOutput(outputRaw) {
|
|
692
|
+
if (!outputRaw.trim()) return null;
|
|
693
|
+
try {
|
|
694
|
+
return JSON.parse(outputRaw);
|
|
695
|
+
} catch {
|
|
696
|
+
return null;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
function extractSandboxOutputFromExecution(execution) {
|
|
700
|
+
const streams = [execution?.stdout, execution?.stderr].filter(Boolean);
|
|
701
|
+
for (const stream of streams) for (const line of stream.split("\n").reverse()) {
|
|
702
|
+
const markerIndex = line.indexOf(EXEC_STDIO_OUTPUT_MARKER);
|
|
703
|
+
if (markerIndex < 0) continue;
|
|
704
|
+
return line.slice(markerIndex + 18);
|
|
705
|
+
}
|
|
706
|
+
return null;
|
|
707
|
+
}
|
|
708
|
+
function previewExecutionStream(stream) {
|
|
709
|
+
if (!stream) return void 0;
|
|
710
|
+
return stream.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH);
|
|
711
|
+
}
|
|
712
|
+
function getExecutionDiagnostics(execution) {
|
|
713
|
+
return {
|
|
714
|
+
args: Array.isArray(execution?.meta?.args) ? execution?.meta?.args : void 0,
|
|
715
|
+
command: typeof execution?.meta?.command === "string" ? execution.meta.command : void 0,
|
|
716
|
+
cwd: typeof execution?.meta?.cwd === "string" ? execution.meta.cwd : void 0,
|
|
717
|
+
exitCode: typeof execution?.code === "undefined" ? void 0 : execution.code,
|
|
718
|
+
stderrPreview: previewExecutionStream(execution?.stderr),
|
|
719
|
+
stdoutPreview: previewExecutionStream(execution?.stdout)
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
function getErrorDiagnostics(error) {
|
|
723
|
+
if (!error || typeof error !== "object" || !("details" in error)) return {};
|
|
724
|
+
const details = error.details;
|
|
725
|
+
if (!details || typeof details !== "object") return {};
|
|
726
|
+
return {
|
|
727
|
+
args: Array.isArray(details.args) ? details.args : void 0,
|
|
728
|
+
command: typeof details.command === "string" ? details.command : void 0,
|
|
729
|
+
cwd: typeof details.cwd === "string" ? details.cwd : void 0,
|
|
730
|
+
exitCode: typeof details.exitCode === "number" || details.exitCode === null ? details.exitCode : void 0,
|
|
731
|
+
spawnErrorCode: typeof details.spawnErrorCode === "string" ? details.spawnErrorCode : void 0,
|
|
732
|
+
spawnErrorMessage: typeof details.spawnErrorMessage === "string" ? details.spawnErrorMessage : void 0,
|
|
733
|
+
stderrPreview: typeof details.stderrPreview === "string" ? details.stderrPreview : void 0,
|
|
734
|
+
stdoutPreview: typeof details.stdoutPreview === "string" ? details.stdoutPreview : void 0
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
function resolveExecOutputRecoveryTimeout(timeout) {
|
|
738
|
+
if (!timeout || timeout <= 0) return DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS;
|
|
739
|
+
return Math.min(MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.max(MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.floor(timeout * .1)));
|
|
740
|
+
}
|
|
741
|
+
function createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution, details) {
|
|
742
|
+
return createHandlerError("Sandbox definition execution failed before producing an output file.", sandbox.provider, {
|
|
743
|
+
outputPath,
|
|
744
|
+
cause: getErrorMessage(error),
|
|
745
|
+
recoveryTimeout,
|
|
746
|
+
...details,
|
|
747
|
+
...getErrorDiagnostics(error),
|
|
748
|
+
...getExecutionDiagnostics(execution)
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
async function waitForExecOutput(sandbox, outputPath, error, timeout, execution, shouldAccept) {
|
|
752
|
+
const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
|
|
753
|
+
const deadline = Date.now() + recoveryTimeout;
|
|
754
|
+
let lastError = error;
|
|
755
|
+
let lastOutput = "";
|
|
756
|
+
while (Date.now() < deadline) {
|
|
757
|
+
try {
|
|
758
|
+
const output = await sandbox.readFile(outputPath);
|
|
759
|
+
lastOutput = output;
|
|
760
|
+
if (shouldAccept(output)) return output;
|
|
761
|
+
} catch (readError) {
|
|
762
|
+
lastError = readError;
|
|
763
|
+
}
|
|
764
|
+
await sleep(EXEC_OUTPUT_RECOVERY_POLL_MS);
|
|
765
|
+
}
|
|
766
|
+
throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution, {
|
|
767
|
+
lastReadError: getErrorMessage(lastError),
|
|
768
|
+
outputPreview: lastOutput.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH) || void 0
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
async function recoverExecOutput(sandbox, outputPath, error, timeout, execution) {
|
|
772
|
+
if (sandbox.provider !== "cloudflare" || !isRecoverableCloudflareExecError(error)) return null;
|
|
773
|
+
return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, (output) => !!tryParseSandboxOutput(output));
|
|
774
|
+
}
|
|
775
|
+
async function waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution) {
|
|
776
|
+
const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
|
|
777
|
+
if (sandbox.provider !== "cloudflare") throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution);
|
|
778
|
+
return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, (output) => !!tryParseSandboxOutput(output));
|
|
779
|
+
}
|
|
780
|
+
async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, execution) {
|
|
781
|
+
const executionOutput = extractSandboxOutputFromExecution(execution) || extractSandboxOutputFromExecution(error);
|
|
782
|
+
if (executionOutput) return executionOutput;
|
|
783
|
+
try {
|
|
784
|
+
const output = await sandbox.readFile(outputPath);
|
|
785
|
+
if (tryParseSandboxOutput(output)) return output;
|
|
786
|
+
} catch {
|
|
787
|
+
return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution);
|
|
788
|
+
}
|
|
789
|
+
return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution);
|
|
790
|
+
}
|
|
791
|
+
//#endregion
|
|
792
|
+
//#region src/runtime/execute.ts
|
|
793
|
+
const defaultNodeLauncher = "import(process.argv[1])";
|
|
794
|
+
const projectPreparations = /* @__PURE__ */ new Map();
|
|
795
|
+
function toJson(value, label) {
|
|
796
|
+
try {
|
|
797
|
+
return JSON.stringify(value);
|
|
798
|
+
} catch (error) {
|
|
799
|
+
throw sandboxError(`Sandbox ${label} must be JSON-serializable.`, {
|
|
800
|
+
code: "SANDBOX_SERIALIZATION_ERROR",
|
|
801
|
+
details: { label },
|
|
802
|
+
cause: error
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
function resolveLauncher() {
|
|
807
|
+
return {
|
|
808
|
+
command: "node",
|
|
809
|
+
args: ["-e", defaultNodeLauncher]
|
|
810
|
+
};
|
|
811
|
+
}
|
|
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) {
|
|
895
|
+
const bundle = normalizeSandboxDefinitionBundle(source);
|
|
896
|
+
const files = createExecutionFiles(definitionName);
|
|
897
|
+
const throwIfAborted = () => {
|
|
898
|
+
if (signal?.aborted) throw createTimeoutError(sandbox.provider, definitionOptions?.timeout || 0);
|
|
899
|
+
};
|
|
900
|
+
await sandbox.mkdir(files.baseDir, { recursive: true });
|
|
901
|
+
try {
|
|
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,
|
|
910
|
+
timeout: definitionOptions?.timeout
|
|
911
|
+
});
|
|
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
|
+
}
|
|
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(() => {});
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
async function executeSandboxDefinition(sandbox, definitionName, definitionOptions, source, payload, context) {
|
|
971
|
+
const timeout = definitionOptions?.timeout;
|
|
972
|
+
if (typeof timeout !== "number" || timeout <= 0) return await executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context);
|
|
973
|
+
let timeoutId;
|
|
974
|
+
const abortController = new AbortController();
|
|
975
|
+
const deadline = Date.now() + timeout;
|
|
976
|
+
try {
|
|
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);
|
|
983
|
+
})]);
|
|
984
|
+
} finally {
|
|
985
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
//#endregion
|
|
989
|
+
//#region src/runtime/execution-box.ts
|
|
990
|
+
function createSandboxExecutionBox(session, provider) {
|
|
991
|
+
return {
|
|
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
|
+
}
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
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
|
+
};
|
|
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
|
+
};
|
|
1036
|
+
//#endregion
|
|
1037
|
+
//#region src/runtime/provider-loader-resolver.ts
|
|
1038
|
+
async function loadSandboxProviderRuntime(provider) {
|
|
1039
|
+
return await (await import("vitehub-sandbox-provider-loader").catch(() => {
|
|
1040
|
+
return new Function("specifier", "return import(specifier)")("@vite-hub/sandbox/runtime/provider-loader");
|
|
1041
|
+
})).loadSandboxRuntimeProvider(provider);
|
|
1042
|
+
}
|
|
1043
|
+
//#endregion
|
|
1044
|
+
//#region src/runtime/provider-resolution.ts
|
|
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
|
+
}
|
|
1071
|
+
function createCloudflareExecutionSandboxId(name, sandboxId) {
|
|
1072
|
+
if (sandboxId) return sandboxId;
|
|
1073
|
+
const prefix = "vitehub-";
|
|
1074
|
+
const suffix = `-${hashCloudflareSandboxName(name)}-definition`;
|
|
1075
|
+
return `${prefix}${encodeURIComponent(name).slice(0, 248 - suffix.length)}${suffix}`;
|
|
1076
|
+
}
|
|
1077
|
+
function resolveRuntimeProvider(provider, event) {
|
|
1078
|
+
if (provider?.provider) return provider.provider;
|
|
1079
|
+
const envProvider = typeof process !== "undefined" ? process.env?.SANDBOX_PROVIDER : void 0;
|
|
1080
|
+
if (envProvider === "cloudflare" || envProvider === "vercel") return envProvider;
|
|
1081
|
+
if (getCloudflareEnv(event)) return "cloudflare";
|
|
1082
|
+
const detected = detectSandbox();
|
|
1083
|
+
if (detected.type === "cloudflare" || detected.type === "vercel") return detected.type;
|
|
1084
|
+
throw sandboxError("Sandbox provider could not be inferred. Configure `sandbox.provider` as `cloudflare` or `vercel`.", { code: "SANDBOX_PROVIDER_REQUIRED" });
|
|
1085
|
+
}
|
|
1086
|
+
function assertSandboxDefinitionOptions(local) {
|
|
1087
|
+
const invalidKeys = Object.keys(local).filter((key) => !allowedDefinitionKeys.has(key));
|
|
1088
|
+
if (invalidKeys.length > 0) throw new TypeError(`[vitehub] Sandbox definition options only support timeout and env. Unsupported: ${invalidKeys.join(", ")}`);
|
|
1089
|
+
}
|
|
1090
|
+
async function resolveSandboxBox(provider, providerOptions, local, context) {
|
|
1091
|
+
return await (await loadSandboxProviderRuntime(provider)).resolveSandboxBox({
|
|
1092
|
+
local,
|
|
1093
|
+
provider: providerOptions
|
|
1094
|
+
}, context);
|
|
1095
|
+
}
|
|
1096
|
+
function withSandboxProvider(provider, options) {
|
|
1097
|
+
return {
|
|
1098
|
+
...options,
|
|
1099
|
+
provider
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
1102
|
+
//#endregion
|
|
1103
|
+
//#region src/runtime/result.ts
|
|
1104
|
+
function ok(value) {
|
|
1105
|
+
return [null, value];
|
|
1106
|
+
}
|
|
1107
|
+
function err(error) {
|
|
1108
|
+
return [error, void 0];
|
|
1109
|
+
}
|
|
1110
|
+
//#endregion
|
|
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
|
+
}
|
|
1129
|
+
const sandboxRegistry = {};
|
|
1130
|
+
function isRetriableCloudflareSandboxError(error) {
|
|
1131
|
+
const metadata = readSandboxErrorMetadata(error);
|
|
1132
|
+
const provider = metadata?.provider;
|
|
1133
|
+
if (provider && provider !== "cloudflare") return false;
|
|
1134
|
+
const extraMessage = metadata?.cause instanceof Error ? metadata.cause.message : "";
|
|
1135
|
+
return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error, extraMessage));
|
|
1136
|
+
}
|
|
1137
|
+
const sandboxRuntime = createResourceRuntime({
|
|
1138
|
+
feature: "sandbox",
|
|
1139
|
+
readConfig(runtimeConfig) {
|
|
1140
|
+
return runtimeConfig.sandbox;
|
|
1141
|
+
},
|
|
1142
|
+
getFallbackConfig: getSandboxRuntimeConfig,
|
|
1143
|
+
registry: {
|
|
1144
|
+
entries: new Proxy(sandboxRegistry, { get(target, property) {
|
|
1145
|
+
if (typeof property !== "string") return Reflect.get(target, property);
|
|
1146
|
+
return getSandboxRuntimeRegistry()?.[property] ?? target[property];
|
|
1147
|
+
} }),
|
|
1148
|
+
validate(definition) {
|
|
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));
|
|
1150
|
+
}
|
|
1151
|
+
},
|
|
1152
|
+
port: {
|
|
1153
|
+
async resolve(context) {
|
|
1154
|
+
assertSandboxDefinitionOptions(context.definition.options ?? {});
|
|
1155
|
+
const config = getSandboxFeatureProvider(context.config);
|
|
1156
|
+
const provider = resolveRuntimeProvider(config, context.event);
|
|
1157
|
+
return await resolveSandboxBox(provider, withSandboxProvider(provider, config), context.definition.options ?? {}, { event: context.event });
|
|
1158
|
+
},
|
|
1159
|
+
async create(provider, context) {
|
|
1160
|
+
const packageManager = context.definition.bundle.project?.install.command;
|
|
1161
|
+
const box = await provider.resolveBox(["node", ...packageManager ? [packageManager] : []]);
|
|
1162
|
+
return {
|
|
1163
|
+
executionAuthority: box.plan.executionAuthority,
|
|
1164
|
+
name: context.name,
|
|
1165
|
+
async run(payload, options = {}) {
|
|
1166
|
+
const cloudflareSandboxId = provider.provider === "cloudflare" ? createCloudflareExecutionSandboxId(context.name, options.sandboxId || provider.sandboxId) : void 0;
|
|
1167
|
+
const attempts = provider.provider === "cloudflare" ? CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length + 1 : 1;
|
|
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
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
throw sandboxError("Cloudflare sandbox retries exhausted.", {
|
|
1183
|
+
code: "SANDBOX_RUNTIME_ERROR",
|
|
1184
|
+
provider: provider.provider
|
|
1185
|
+
});
|
|
1186
|
+
});
|
|
1187
|
+
}
|
|
1188
|
+
};
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
});
|
|
1192
|
+
async function resolveSandboxRunner(name) {
|
|
1193
|
+
return await sandboxRuntime.get(name);
|
|
1194
|
+
}
|
|
1195
|
+
async function runSandboxRuntime(name, payload, options) {
|
|
1196
|
+
try {
|
|
1197
|
+
return ok(await (await resolveSandboxRunner(name)).run(payload, options));
|
|
1198
|
+
} catch (error) {
|
|
1199
|
+
return err(toSandboxError(error));
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
//#endregion
|
|
1203
|
+
//#region src/runtime/public.ts
|
|
1204
|
+
async function runSandbox(name, payload, options) {
|
|
1205
|
+
return await runSandboxRuntime(name, payload, options);
|
|
1206
|
+
}
|
|
1207
|
+
//#endregion
|
|
1208
|
+
export { defineSandbox, readRequestPayload, readValidatedPayload, resolveSandboxRunner, runSandbox };
|