@vite-hub/sandbox 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +388 -22
  3. package/dist/cloudflare-DO0h3Ncf.js +281 -0
  4. package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
  5. package/dist/crabbox-BFCdf41h.js +1106 -0
  6. package/dist/error-diagnostics-BSysPv-D.js +166 -0
  7. package/dist/error-diagnostics-dGQqfgLt.js +99 -0
  8. package/dist/file-listing-DECFTdSl.js +26 -0
  9. package/dist/file-lock-CxyVl4Cv.js +73 -0
  10. package/dist/index-CXej1Bt0.d.ts +519 -0
  11. package/dist/index.d.ts +2 -65
  12. package/dist/index.js +277 -1172
  13. package/dist/internal/cloudflare.d.ts +4 -0
  14. package/dist/internal/cloudflare.js +16 -0
  15. package/dist/internal/host-toolchain.d.ts +22 -0
  16. package/dist/internal/host-toolchain.js +97 -0
  17. package/dist/internal/vercel.d.ts +4 -0
  18. package/dist/internal/vercel.js +16 -0
  19. package/dist/module-types-BfyRBaiP.js +7 -0
  20. package/dist/module-types-Cis4hrF1.d.ts +95 -0
  21. package/dist/remote-1Jz2oUMK.js +247 -0
  22. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  23. package/dist/runtime-DHp6ImeP.js +32 -0
  24. package/dist/runtime-type-DrmrW5m5.js +42 -0
  25. package/dist/session-DD0S1PDC.js +337 -0
  26. package/dist/shell-quote-Q3u3plif.js +6 -0
  27. package/dist/ssh.d.ts +55 -0
  28. package/dist/ssh.js +219 -0
  29. package/dist/task/index.d.ts +67 -0
  30. package/dist/task/index.js +1523 -0
  31. package/dist/task/runtime/empty-registry.d.ts +6 -0
  32. package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
  33. package/dist/task/runtime/provider-loader.d.ts +20 -0
  34. package/dist/task/runtime/provider-loader.js +19 -0
  35. package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
  36. package/dist/task/runtime/providers/cloudflare.js +26 -0
  37. package/dist/task/runtime/providers/vercel.d.ts +12 -0
  38. package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
  39. package/dist/task/runtime/state.d.ts +24 -0
  40. package/dist/task/runtime/state.js +73 -0
  41. package/dist/task/vite.d.ts +360 -0
  42. package/dist/task/vite.js +3643 -0
  43. package/dist/toolchain-BUVXtQ2m.js +527 -0
  44. package/dist/trusted-host-DNMJ-Oig.js +872 -0
  45. package/dist/vercel-Jtxa9TJx.js +279 -0
  46. package/package.json +103 -39
  47. package/dist/cloudflare-env-2NctU8i7.js +0 -12
  48. package/dist/module-types-DfXe133f.d.ts +0 -91
  49. package/dist/module-types-Dj1MFmHT.js +0 -7
  50. package/dist/provider-loader-hL7uHVWp.d.ts +0 -21
  51. package/dist/runtime/empty-registry.d.ts +0 -6
  52. package/dist/runtime/provider-loader.d.ts +0 -2
  53. package/dist/runtime/provider-loader.js +0 -15
  54. package/dist/runtime/providers/cloudflare.d.ts +0 -29
  55. package/dist/runtime/providers/cloudflare.js +0 -25
  56. package/dist/runtime/providers/vercel.d.ts +0 -112
  57. package/dist/runtime/state.d.ts +0 -17
  58. package/dist/runtime/state.js +0 -21
  59. package/dist/vite.d.ts +0 -24
  60. package/dist/vite.js +0 -2367
package/dist/index.js CHANGED
@@ -1,1208 +1,313 @@
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);
1
+ import { n as isBuiltInSandboxRuntime, t as hasDeclaredSandboxRuntimeMember } from "./runtime-DHp6ImeP.js";
2
+ import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { readFile, realpath } from "node:fs/promises";
5
+ import { isAbsolute, posix, relative, resolve } from "node:path";
6
+ import { normalizeExecutionAuthority } from "@vite-hub/runtime";
7
+ //#region src/index.ts
8
+ const reservedRuntimeNames = /* @__PURE__ */ new Set([
9
+ "cloudflare",
10
+ "crabbox",
11
+ "trusted-host",
12
+ "vercel"
13
+ ]);
14
+ async function resolveSandboxRuntime(value) {
15
+ if (isSandboxRuntime(value)) {
16
+ if (reservedRuntimeNames.has(value.name) && !isBuiltInSandboxRuntime(value)) throw sandboxErrorDiagnostics.SANDBOX_R0030({ message: `[vitehub] Custom Sandbox runtimes cannot use the reserved name "${value.name}". Select the built-in runtime by value instead.` });
17
+ return value;
18
+ }
19
+ if (typeof value === "string") {
20
+ if (value === "crabbox") {
21
+ const { createCrabboxRuntime } = await import("./crabbox-BFCdf41h.js");
22
+ return createCrabboxRuntime();
68
23
  }
69
- return result;
70
- } catch {
71
- return;
72
- } finally {
73
- seen.delete(value);
24
+ if (value === "trusted-host") {
25
+ const { createTrustedHostRuntime } = await import("./trusted-host-DNMJ-Oig.js");
26
+ return createTrustedHostRuntime();
27
+ }
28
+ if (value === "vercel") {
29
+ const { createVercelRuntime } = await import("./vercel-Jtxa9TJx.js").then((n) => n.n);
30
+ return createVercelRuntime();
31
+ }
32
+ throw sandboxErrorDiagnostics.SANDBOX_R0031({ message: `[vitehub] Unknown Sandbox runtime "${value}". Expected "crabbox", "trusted-host", "vercel", a tagged built-in configuration, or a custom runtime.` });
74
33
  }
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;
34
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw sandboxErrorDiagnostics.SANDBOX_R0032({ message: "[vitehub] Sandbox requires an explicit built-in runtime value or custom runtime object." });
35
+ const { kind, ...options } = value;
36
+ if (kind === "crabbox") {
37
+ const { createCrabboxRuntime } = await import("./crabbox-BFCdf41h.js");
38
+ return createCrabboxRuntime(options);
169
39
  }
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);
40
+ if (kind === "trusted-host") {
41
+ const { createTrustedHostRuntime } = await import("./trusted-host-DNMJ-Oig.js");
42
+ return createTrustedHostRuntime(options);
180
43
  }
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);
44
+ if (kind === "cloudflare") {
45
+ const { createCloudflareRuntime } = await import("./cloudflare-DO0h3Ncf.js").then((n) => n.t);
46
+ return createCloudflareRuntime(options);
242
47
  }
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;
48
+ if (kind === "vercel") {
49
+ const { createVercelRuntime } = await import("./vercel-Jtxa9TJx.js").then((n) => n.n);
50
+ return createVercelRuntime(options);
266
51
  }
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 };
52
+ throw sandboxErrorDiagnostics.SANDBOX_R0033({ message: `[vitehub] Unknown Sandbox runtime kind "${String(kind)}". Expected "crabbox", "trusted-host", "cloudflare", or "vercel".` });
276
53
  }
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) {
54
+ function isSandboxRuntime(value) {
286
55
  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
- }
56
+ const runtime = value;
57
+ return hasDeclaredSandboxRuntimeMember(runtime, "name") && hasDeclaredSandboxRuntimeMember(runtime, "open") && hasDeclaredSandboxRuntimeMember(runtime, "prepare") && typeof runtime.name === "string" && typeof runtime.open === "function" && typeof runtime.prepare === "function";
58
+ }
59
+ const reservedEnvironment = /* @__PURE__ */ new Set([
60
+ "CODEX_HOME",
61
+ "HOME",
62
+ "INIT_CWD",
63
+ "OLDPWD",
64
+ "PWD",
65
+ "XDG_CACHE_HOME",
66
+ "XDG_CONFIG_HOME",
67
+ "XDG_STATE_HOME"
68
+ ]);
69
+ async function resolveSandbox(definition, context, options = {}) {
70
+ if (!definition || typeof definition !== "object") throw sandboxErrorDiagnostics.SANDBOX_R0034({ message: "[vitehub] Sandbox requires a definition." });
71
+ const runtime = await resolveSandboxRuntime(definition.runtime);
72
+ if (definition.cwd !== void 0 && definition.checkout !== void 0) throw sandboxErrorDiagnostics.SANDBOX_R0035({ message: "[vitehub] Sandbox checkout cannot be combined with cwd." });
73
+ const cwdValue = await resolveValue(definition.cwd, context);
74
+ const cwd = cwdValue === void 0 ? void 0 : resolve(resolveString(cwdValue, "cwd"));
75
+ const checkout = definition.checkout ? {
76
+ ref: resolveString(await resolveValue(definition.checkout.ref, context), "checkout ref"),
77
+ remote: resolveString(await resolveValue(definition.checkout.remote, context), "checkout remote"),
78
+ sha: resolveSha(await resolveValue(definition.checkout.sha, context))
79
+ } : void 0;
80
+ const plan = resolvePlan(definition, context, cwd || process.cwd());
81
+ const toolchain = await resolveToolchain(definition.toolchain, checkout ? void 0 : cwd || process.cwd());
82
+ const requirements = normalizeRequirements([
83
+ ...checkout ? ["git"] : [],
84
+ ...toolchain ? ["node", ...toolchain.pins?.packageManager ? [toolchain.pins.packageManager.name] : []] : [],
85
+ ...definition.requires || [],
86
+ ...options.requires || []
87
+ ]);
88
+ const input = {
89
+ ...checkout ? { checkout } : {},
90
+ ...cwd ? { cwd } : {},
91
+ identity: planIdentity(plan, requirements, checkout, toolchain),
92
+ plan,
93
+ requirements,
94
+ ...toolchain ? { toolchain } : {}
319
95
  };
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)])));
96
+ const prepared = await runtime.prepare(input);
97
+ let executionAuthority;
98
+ try {
99
+ executionAuthority = normalizeExecutionAuthority(prepared.executionAuthority);
100
+ } catch {
101
+ throw sandboxErrorDiagnostics.SANDBOX_R0036({ message: `[vitehub] Sandbox runtime ${runtime.name} must declare executionAuthority.` });
379
102
  }
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
103
+ const homeState = plan.state.map((state) => {
104
+ const preparedState = prepared.home?.state.find((target) => target.path === state.path);
105
+ if (typeof preparedState?.identity !== "string" || !preparedState.identity) throw sandboxErrorDiagnostics.SANDBOX_R0037({ message: `[vitehub] Sandbox runtime ${runtime.name} must declare an opaque Home state identity for ${state.path}.` });
106
+ return Object.freeze({
107
+ identity: preparedState.identity,
108
+ path: state.path
109
+ });
409
110
  });
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
111
+ const sandboxPlan = Object.freeze({
112
+ ...prepared,
113
+ executionAuthority,
114
+ home: Object.freeze({ state: Object.freeze(homeState) }),
115
+ ...toolchain ? { toolchain: Object.freeze({
116
+ ...toolchain.pins?.node ? { node: toolchain.pins.node } : {},
117
+ ...toolchain.pins?.packageManager ? { packageManager: toolchain.pins.packageManager } : {},
118
+ source: toolchain.pins ? "project" : "checkout"
119
+ }) } : {}
415
120
  });
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
121
+ return Object.freeze({
122
+ async open(options) {
123
+ options?.signal?.throwIfAborted();
124
+ const session = await runtime.open(input, {
125
+ ...options,
126
+ executionAuthority: sandboxPlan.executionAuthority
127
+ });
128
+ if (toolchain && !session.toolchain) {
129
+ await session.close().catch(() => void 0);
130
+ throw sandboxErrorDiagnostics.SANDBOX_R0156({ message: `[vitehub] Sandbox runtime ${runtime.name} does not provision toolchains. Use a built-in runtime or remove sandbox.toolchain.` });
131
+ }
132
+ return session;
133
+ },
134
+ plan: sandboxPlan
682
135
  });
683
136
  }
684
- function createTimeoutError(provider, timeout) {
685
- return sandboxError(`Sandbox definition timed out after ${timeout}ms.`, {
686
- code: "SANDBOX_TIMEOUT",
687
- provider,
688
- details: { timeout }
137
+ /** Read toolchain pins now unless they come from a checkout that exists only after open. */
138
+ async function resolveToolchain(declaration, projectRoot) {
139
+ if (declaration === void 0) return;
140
+ const [{ normalizeToolchain, readToolchainPins, toolchainReadsProject }, { readHostProjectFiles }] = await Promise.all([import("./toolchain-BUVXtQ2m.js").then((n) => n.i), import("./internal/host-toolchain.js")]);
141
+ const toolchain = normalizeToolchain(declaration, "sandbox.toolchain");
142
+ if (!toolchain) return;
143
+ if (!projectRoot && toolchainReadsProject(toolchain)) return toolchain;
144
+ const files = toolchainReadsProject(toolchain) ? await readHostProjectFiles(projectRoot) : {};
145
+ return Object.freeze({
146
+ ...toolchain,
147
+ pins: readToolchainPins(toolchain, files)
689
148
  });
690
149
  }
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)
150
+ function planIdentity(plan, requirements, checkout, toolchain) {
151
+ const value = JSON.stringify({
152
+ checkout,
153
+ toolchain,
154
+ env: Object.keys(plan.env).toSorted(),
155
+ files: Object.keys(plan.files).toSorted(),
156
+ requirements,
157
+ state: plan.state.map(({ key, path, seed }) => ({
158
+ key,
159
+ path,
160
+ seed: Object.keys(seed).toSorted()
161
+ })).toSorted((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
749
162
  });
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
163
+ const fingerprint = createHash("sha256").update(value).digest("hex");
164
+ return Object.keys(plan.env).length > 0 || Object.keys(plan.files).length > 0 || plan.state.some(({ seed }) => Object.keys(seed).length > 0) ? `${fingerprint}-${randomUUID()}` : fingerprint;
165
+ }
166
+ function resolvePlan(definition, context, sourceRoot) {
167
+ if (definition.home !== void 0 && (!definition.home || typeof definition.home !== "object" || Array.isArray(definition.home))) throw sandboxErrorDiagnostics.SANDBOX_R0038({ message: "[vitehub] Sandbox home must be a declarative object." });
168
+ const env = Object.fromEntries(Object.entries(optionalRecord(definition.env, "env")).map(([name, value]) => {
169
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw sandboxErrorDiagnostics.SANDBOX_R0039({ message: `[vitehub] Invalid Sandbox environment variable: ${name}` });
170
+ if (reservedEnvironment.has(name)) throw sandboxErrorDiagnostics.SANDBOX_R0040({ message: `[vitehub] ${name} is managed by the Sandbox runtime.` });
171
+ return [name, async () => {
172
+ const resolved = await resolveValue(value, context);
173
+ if (resolved === void 0) throw sandboxErrorDiagnostics.SANDBOX_R0041({ message: `[vitehub] Sandbox environment value ${name} is required.` });
174
+ return resolveString(resolved, `environment value ${name}`);
175
+ }];
176
+ }));
177
+ const files = normalizeFiles(definition.home?.files, context, "home.files", sourceRoot);
178
+ const state = Object.entries(optionalRecord(definition.home?.state, "home.state")).map(([path, value]) => {
179
+ const target = relativePath(path, "home.state target");
180
+ if (!value || typeof value !== "object" || typeof value.key !== "string" || !value.key.trim()) throw sandboxErrorDiagnostics.SANDBOX_R0042({ message: `[vitehub] Sandbox state ${path} requires a non-empty key.` });
181
+ return {
182
+ key: value.key.trim(),
183
+ path: target,
184
+ projections: [],
185
+ seed: normalizeFiles(value.seed, context, `home.state ${path} seed`, sourceRoot)
186
+ };
769
187
  });
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);
188
+ const stateKeys = /* @__PURE__ */ new Set();
189
+ for (const value of state) {
190
+ if (stateKeys.has(value.key)) throw sandboxErrorDiagnostics.SANDBOX_R0043({ message: `[vitehub] Sandbox state keys must be unique: ${value.key}` });
191
+ stateKeys.add(value.key);
788
192
  }
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
- });
193
+ validateTargets(Object.keys(files), state.map((value) => value.path));
194
+ for (const value of state) {
195
+ const projectedFiles = Object.keys(files).filter((file) => isDescendant(file, value.path)).map((file) => file.slice(value.path.length + 1));
196
+ value.projections.push(...projectedFiles.toSorted());
197
+ validateFileTargets([...Object.keys(value.seed), ...projectedFiles], `home.state ${value.path} projected`);
804
198
  }
805
- }
806
- function resolveLauncher() {
807
199
  return {
808
- command: "node",
809
- args: ["-e", defaultNodeLauncher]
200
+ env: Object.freeze(env),
201
+ files: Object.freeze(files),
202
+ state: Object.freeze(state)
810
203
  };
811
204
  }
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;
205
+ function normalizeFiles(input, context, label, sourceRoot) {
206
+ const files = Object.fromEntries(Object.entries(optionalRecord(input, label)).map(([path, value]) => {
207
+ const target = relativePath(path, `${label} target`);
208
+ if (!value || typeof value !== "object") throw sandboxErrorDiagnostics.SANDBOX_R0044({ message: `[vitehub] Sandbox file ${path} requires from or contents.` });
209
+ const hasFrom = "from" in value;
210
+ const hasContents = "contents" in value;
211
+ const ownsFrom = Object.hasOwn(value, "from");
212
+ const ownsContents = Object.hasOwn(value, "contents");
213
+ if (hasFrom !== ownsFrom || hasContents !== ownsContents) throw sandboxErrorDiagnostics.SANDBOX_R0046({ message: `[vitehub] Sandbox file ${path} requires exactly one of from or contents.` });
214
+ if (hasFrom && ownsFrom) {
215
+ if (Object.keys(value).length !== 1 || typeof value.from !== "string") throw sandboxErrorDiagnostics.SANDBOX_R0045({ message: `[vitehub] Sandbox file ${path} requires exactly one of from or contents.` });
216
+ const source = relativePath(value.from, `${label} source`);
217
+ return [target, { resolve: async () => await readProjectFile(source) }];
840
218
  }
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);
219
+ if (!(hasContents && ownsContents) || Object.keys(value).length !== 1) throw sandboxErrorDiagnostics.SANDBOX_R0046({ message: `[vitehub] Sandbox file ${path} requires exactly one of from or contents.` });
220
+ return [target, { resolve: async () => {
221
+ const resolved = await resolveValue(value.contents, context);
222
+ if (resolved === void 0) throw sandboxErrorDiagnostics.SANDBOX_R0047({ message: `[vitehub] Sandbox file ${path} is required.` });
223
+ if (typeof resolved === "string") return new TextEncoder().encode(resolved);
224
+ if (isUint8ArrayValue(resolved)) return resolved;
225
+ throw sandboxErrorDiagnostics.SANDBOX_R0048({ message: `[vitehub] Sandbox file ${path} must resolve to text or bytes.` });
226
+ } }];
227
+ }));
228
+ validateFileTargets(Object.keys(files), label);
229
+ return files;
230
+ async function readProjectFile(path) {
231
+ const root = await realpath(sourceRoot).catch(() => resolve(sourceRoot));
232
+ const source = await realpath(resolve(root, path)).catch(() => void 0);
233
+ const sourcePath = source ? relative(root, source) : void 0;
234
+ if (!source || !sourcePath || sourcePath.startsWith("..") || isAbsolute(sourcePath)) throw sandboxErrorDiagnostics.SANDBOX_R0049({ message: `[vitehub] Sandbox project file is unavailable: ${path}` });
235
+ return new Uint8Array(await readFile(source));
986
236
  }
987
237
  }
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;
238
+ function isUint8ArrayValue(value) {
239
+ if (!ArrayBuffer.isView(value)) return false;
1122
240
  try {
1123
- return await run();
1124
- } finally {
1125
- release();
1126
- if (cloudflareRunQueues.get(id) === current) cloudflareRunQueues.delete(id);
241
+ const elementType = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
242
+ return !!elementType && Reflect.apply(elementType, value, []) === "Uint8Array";
243
+ } catch {
244
+ return false;
1127
245
  }
1128
246
  }
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] : []]);
247
+ function validateFileTargets(files, label) {
248
+ for (let index = 0; index < files.length; index++) for (let other = index + 1; other < files.length; other++) if (files[index] === files[other] || isDescendant(files[index], files[other]) || isDescendant(files[other], files[index])) throw sandboxErrorDiagnostics.SANDBOX_R0050({ message: `[vitehub] Sandbox ${label} targets conflict: ${files[index]} and ${files[other]}` });
249
+ }
250
+ function validateTargets(files, state) {
251
+ for (let index = 0; index < state.length; index++) for (let other = index + 1; other < state.length; other++) if (isDescendant(state[index], state[other]) || isDescendant(state[other], state[index])) throw sandboxErrorDiagnostics.SANDBOX_R0051({ message: `[vitehub] Sandbox state targets overlap: ${state[index]} and ${state[other]}` });
252
+ for (const file of files) for (const directory of state) if (file === directory || isDescendant(directory, file)) throw sandboxErrorDiagnostics.SANDBOX_R0052({ message: `[vitehub] Sandbox file and state targets conflict: ${file} and ${directory}` });
253
+ }
254
+ function isDescendant(path, parent) {
255
+ return path.startsWith(`${parent}/`);
256
+ }
257
+ function optionalRecord(value, label) {
258
+ if (value === void 0) return {};
259
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw sandboxErrorDiagnostics.SANDBOX_R0053({ message: `[vitehub] Sandbox ${label} must be an object.` });
260
+ return value;
261
+ }
262
+ function relativePath(value, label) {
263
+ if (typeof value !== "string" || !value || value.includes("\0") || value.includes("\\") || isAbsolute(value)) throw sandboxErrorDiagnostics.SANDBOX_R0054({ message: `[vitehub] Sandbox ${label} must be a non-empty relative POSIX path.` });
264
+ const normalized = posix.normalize(value);
265
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../") || normalized !== value) throw sandboxErrorDiagnostics.SANDBOX_R0055({ message: `[vitehub] Sandbox ${label} must be a non-empty relative POSIX path.` });
266
+ return normalized;
267
+ }
268
+ function normalizeRequirements(input) {
269
+ const requirements = input.map((value) => {
270
+ if (typeof value === "string") {
271
+ if (!value.trim()) throw sandboxErrorDiagnostics.SANDBOX_R0056({ message: "[vitehub] Sandbox requirements must be non-empty commands." });
272
+ const command = value.trim();
273
+ if (command.includes("\0")) throw sandboxErrorDiagnostics.SANDBOX_R0057({ message: "[vitehub] Sandbox requirement commands and arguments cannot contain NUL." });
1162
274
  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
- }
275
+ args: [],
276
+ command,
277
+ name: command
1188
278
  };
1189
279
  }
1190
- }
1191
- });
1192
- async function resolveSandboxRunner(name) {
1193
- return await sandboxRuntime.get(name);
280
+ if (!value || typeof value !== "object" || typeof value.command !== "string" || !value.command.trim()) throw sandboxErrorDiagnostics.SANDBOX_R0058({ message: "[vitehub] Sandbox requirements must be commands or direct command checks." });
281
+ const rawArgs = value.args;
282
+ if (rawArgs !== void 0 && !Array.isArray(rawArgs)) throw sandboxErrorDiagnostics.SANDBOX_R0059({ message: "[vitehub] Sandbox requirement arguments must be an array of strings." });
283
+ const args = rawArgs === void 0 ? [] : [...rawArgs];
284
+ if (args.some((argument) => typeof argument !== "string")) throw sandboxErrorDiagnostics.SANDBOX_R0059({ message: "[vitehub] Sandbox requirement arguments must be strings." });
285
+ const command = value.command.trim();
286
+ if (command.includes("\0") || args.some((argument) => argument.includes("\0"))) throw sandboxErrorDiagnostics.SANDBOX_R0060({ message: "[vitehub] Sandbox requirement commands and arguments cannot contain NUL." });
287
+ const name = value.name?.trim() || [command, ...args].join(" ");
288
+ const timeout = value.timeout;
289
+ if (timeout !== void 0 && (!Number.isInteger(timeout) || timeout <= 0 || timeout > 2 ** 31 - 1)) throw sandboxErrorDiagnostics.SANDBOX_R0061({ message: "[vitehub] Sandbox requirement timeout must be a positive integer no greater than 2147483647ms." });
290
+ return {
291
+ args,
292
+ command,
293
+ name,
294
+ ...timeout === void 0 ? {} : { timeout }
295
+ };
296
+ });
297
+ return [...new Map(requirements.map((value) => [JSON.stringify(value), value])).values()];
1194
298
  }
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
- }
299
+ function resolveString(value, label) {
300
+ if (typeof value !== "string" || !value) throw sandboxErrorDiagnostics.SANDBOX_R0062({ message: `[vitehub] Sandbox ${label} must resolve to a non-empty string.` });
301
+ if (value.includes("\0")) throw sandboxErrorDiagnostics.SANDBOX_R0063({ message: `[vitehub] Sandbox ${label} cannot contain NUL.` });
302
+ return value;
1201
303
  }
1202
- //#endregion
1203
- //#region src/runtime/public.ts
1204
- async function runSandbox(name, payload, options) {
1205
- return await runSandboxRuntime(name, payload, options);
304
+ function resolveSha(value) {
305
+ const sha = resolveString(value, "checkout sha").toLowerCase();
306
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(sha)) throw sandboxErrorDiagnostics.SANDBOX_R0064({ message: "[vitehub] Sandbox checkout sha must be a full Git object id." });
307
+ return sha;
308
+ }
309
+ async function resolveValue(value, context) {
310
+ return typeof value === "function" ? await value(context) : value;
1206
311
  }
1207
312
  //#endregion
1208
- export { defineSandbox, readRequestPayload, readValidatedPayload, resolveSandboxRunner, runSandbox };
313
+ export { resolveSandbox };