@vite-hub/sandbox 0.0.4 → 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 (58) hide show
  1. package/README.md +327 -34
  2. package/dist/cloudflare-DO0h3Ncf.js +281 -0
  3. package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
  4. package/dist/crabbox-BFCdf41h.js +1106 -0
  5. package/dist/error-diagnostics-BSysPv-D.js +166 -0
  6. package/dist/error-diagnostics-dGQqfgLt.js +99 -0
  7. package/dist/file-listing-DECFTdSl.js +26 -0
  8. package/dist/file-lock-CxyVl4Cv.js +73 -0
  9. package/dist/index-CXej1Bt0.d.ts +519 -0
  10. package/dist/index.d.ts +2 -69
  11. package/dist/index.js +277 -1183
  12. package/dist/internal/cloudflare.d.ts +4 -0
  13. package/dist/internal/cloudflare.js +16 -0
  14. package/dist/internal/host-toolchain.d.ts +22 -0
  15. package/dist/internal/host-toolchain.js +97 -0
  16. package/dist/internal/vercel.d.ts +4 -0
  17. package/dist/internal/vercel.js +16 -0
  18. package/dist/module-types-BfyRBaiP.js +7 -0
  19. package/dist/module-types-Cis4hrF1.d.ts +95 -0
  20. package/dist/remote-1Jz2oUMK.js +247 -0
  21. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  22. package/dist/runtime-DHp6ImeP.js +32 -0
  23. package/dist/runtime-type-DrmrW5m5.js +42 -0
  24. package/dist/session-DD0S1PDC.js +337 -0
  25. package/dist/shell-quote-Q3u3plif.js +6 -0
  26. package/dist/ssh.d.ts +55 -0
  27. package/dist/ssh.js +219 -0
  28. package/dist/task/index.d.ts +67 -0
  29. package/dist/task/index.js +1523 -0
  30. package/dist/task/runtime/empty-registry.d.ts +6 -0
  31. package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
  32. package/dist/task/runtime/provider-loader.d.ts +20 -0
  33. package/dist/task/runtime/provider-loader.js +19 -0
  34. package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
  35. package/dist/task/runtime/providers/cloudflare.js +26 -0
  36. package/dist/task/runtime/providers/vercel.d.ts +12 -0
  37. package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
  38. package/dist/task/runtime/state.d.ts +24 -0
  39. package/dist/task/runtime/state.js +73 -0
  40. package/dist/task/vite.d.ts +360 -0
  41. package/dist/{vite.js → task/vite.js} +964 -645
  42. package/dist/toolchain-BUVXtQ2m.js +527 -0
  43. package/dist/trusted-host-DNMJ-Oig.js +872 -0
  44. package/dist/vercel-Jtxa9TJx.js +279 -0
  45. package/package.json +99 -48
  46. package/dist/cloudflare-env-QQV4uzCT.js +0 -14
  47. package/dist/module-types-DKYItiOu.d.ts +0 -93
  48. package/dist/module-types-Dj1MFmHT.js +0 -7
  49. package/dist/provider-loader-D0UihePq.d.ts +0 -21
  50. package/dist/runtime/empty-registry.d.ts +0 -6
  51. package/dist/runtime/provider-loader.d.ts +0 -2
  52. package/dist/runtime/provider-loader.js +0 -15
  53. package/dist/runtime/providers/cloudflare.d.ts +0 -29
  54. package/dist/runtime/providers/cloudflare.js +0 -25
  55. package/dist/runtime/providers/vercel.d.ts +0 -121
  56. package/dist/runtime/state.d.ts +0 -26
  57. package/dist/runtime/state.js +0 -72
  58. package/dist/vite.d.ts +0 -48
package/dist/index.js CHANGED
@@ -1,1219 +1,313 @@
1
- import { t as getCloudflareEnv } from "./cloudflare-env-QQV4uzCT.js";
2
- import { getSandboxRuntimeConfig, getSandboxRuntimeRegistry } from "./runtime/state.js";
3
- import { t as getSandboxFeatureProvider } from "./module-types-Dj1MFmHT.js";
4
- import { ViteHubError, getViteHubErrorShape } from "@vite-hub/runtime";
5
- import { upperFirst } from "scule";
6
- import { dirname } from "pathe";
7
- //#region src/internal/shared/definition.ts
8
- function assertDefinitionHandler(functionName, handler, label) {
9
- if (typeof handler !== "function") throw new TypeError(`[vitehub] \`${functionName}()\` requires a ${label} as the first argument.`);
10
- }
11
- function validateDefinitionOptions(functionName, options, config) {
12
- if (typeof options === "undefined") return void 0;
13
- if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError(`[vitehub] \`${functionName}()\` accepts one options object.`);
14
- const invalidKeys = Object.keys(options).filter((key) => {
15
- if (config.allowedKeys) return !config.allowedKeys.includes(key);
16
- return config.disallowedKeys?.includes(key);
17
- });
18
- if (invalidKeys.length) throw new TypeError(`[vitehub] \`${functionName}()\` ${config.invalidKeysMessage}. Unsupported keys: ${invalidKeys.join(", ")}.`);
19
- return options;
20
- }
21
- //#endregion
22
- //#region src/runtime/registry.ts
23
- function createSandboxDefinition(functionName, input) {
24
- const validated = validateDefinitionOptions(functionName, input, {
25
- allowedKeys: [
26
- "run",
27
- "timeout",
28
- "env",
29
- "project"
30
- ],
31
- invalidKeysMessage: "supports only portable Sandbox options (run, timeout, env, project)"
32
- });
33
- if (!validated) throw new TypeError(`[vitehub] \`${functionName}()\` requires an options object.`);
34
- if (typeof validated.project !== "undefined" && typeof validated.project !== "boolean") throw new TypeError(`[vitehub] \`${functionName}()\` project must be a boolean.`);
35
- const { project: _project, run, ...options } = validated;
36
- assertDefinitionHandler(functionName, run, "Sandbox handler in `run`");
37
- return {
38
- run,
39
- options: Object.keys(options).length ? options : void 0
40
- };
41
- }
42
- function defineSandbox(input) {
43
- return createSandboxDefinition("defineSandbox", input);
44
- }
45
- //#endregion
46
- //#region src/internal/shared/request-payload.ts
47
- async function readRequestPayload(event, fallback = {}) {
48
- return await event.req.json().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|cloudflare box [a-z][a-z0-9]* timed out after \d+ms/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
- ` if (typeof exported !== 'function')`,
428
- ` throw new TypeError('Sandbox package entrypoint must default-export a function.')`,
429
- ` const result = await exported(input.payload, input.context)`
430
- ] : [
431
- ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
432
- ` const definition = mod?.default`,
433
- ` if (!definition || typeof definition.run !== 'function')`,
434
- ` throw new Error('Sandbox Definition must default-export defineSandbox({ run }).')`,
435
- ` const result = await definition.run(input.payload, input.context)`
436
- ];
437
- return [
438
- `import { mkdir, readFile, writeFile } from 'node:fs/promises'`,
439
- `import { Buffer } from 'node:buffer'`,
440
- `import { pathToFileURL } from 'node:url'`,
441
- ``,
442
- `function normalizeError(error) {`,
443
- ` if (error instanceof Error) {`,
444
- ` return {`,
445
- ` name: error.name,`,
446
- ` message: error.message,`,
447
- ` stack: error.stack,`,
448
- ` cause: error.cause ? String(error.cause) : undefined,`,
449
- ` }`,
450
- ` }`,
451
- ` return {`,
452
- ` name: 'Error',`,
453
- ` message: String(error),`,
454
- ` }`,
455
- `}`,
456
- ``,
457
- `const valueMarker = ${JSON.stringify("vitehub:sandbox:value")}`,
458
- ``,
459
- `function isPlainObject(value) {`,
460
- ` if (!value || typeof value !== 'object') return false`,
461
- ` const prototype = Object.getPrototypeOf(value)`,
462
- ` return prototype === Object.prototype || prototype === null`,
463
- `}`,
464
- ``,
465
- `function hasMarker(value) {`,
466
- ` return Object.prototype.hasOwnProperty.call(value, valueMarker)`,
467
- `}`,
468
- ``,
469
- `function isBoxedJsonPrimitive(value) {`,
470
- ` return value instanceof Boolean`,
471
- ` || value instanceof Number`,
472
- ` || value instanceof String`,
473
- ` || Object.getPrototypeOf(value) === BigInt.prototype`,
474
- `}`,
475
- ``,
476
- `function invalidDescriptor(label) {`,
477
- ` return new TypeError('Sandbox ' + label + ' contains an invalid binary sidecar descriptor.')`,
478
- `}`,
479
- ``,
480
- `async function reviveValue(value, assetsDir, label) {`,
481
- ` if (Array.isArray(value))`,
482
- ` return await Promise.all(value.map(entry => reviveValue(entry, assetsDir, label)))`,
483
- ` if (!value || typeof value !== 'object') return value`,
484
- ` if (!hasMarker(value)) {`,
485
- ` return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, entry]) => [`,
486
- ` key,`,
487
- ` await reviveValue(entry, assetsDir, label),`,
488
- ` ])))`,
489
- ` }`,
490
- ` const descriptor = value[valueMarker]`,
491
- ` if (!isPlainObject(descriptor) || typeof descriptor.tag !== 'string')`,
492
- ` throw invalidDescriptor(label)`,
493
- ` if (descriptor.tag === 'object') {`,
494
- ` if (!Array.isArray(descriptor.entries) || !descriptor.entries.every(entry => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string'))`,
495
- ` throw invalidDescriptor(label)`,
496
- ` return Object.fromEntries(await Promise.all(descriptor.entries.map(async ([key, entry]) => [`,
497
- ` key,`,
498
- ` await reviveValue(entry, assetsDir, label),`,
499
- ` ])))`,
500
- ` }`,
501
- ` if (descriptor.tag !== 'binary'`,
502
- ` || !Number.isSafeInteger(descriptor.id)`,
503
- ` || Object.is(descriptor.id, -0)`,
504
- ` || descriptor.id < 0`,
505
- ` || (descriptor.kind !== 'blob' && descriptor.kind !== 'buffer' && descriptor.kind !== 'uint8array')`,
506
- ` || (typeof descriptor.type !== 'undefined' && typeof descriptor.type !== 'string'))`,
507
- ` throw invalidDescriptor(label)`,
508
- ` const bytes = new Uint8Array(await readFile(assetsDir + '/' + descriptor.id))`,
509
- ` return descriptor.kind === 'blob' ? new Blob([bytes], { type: descriptor.type || '' }) : descriptor.kind === 'buffer' ? Buffer.from(bytes) : bytes`,
510
- `}`,
511
- ``,
512
- `async function extractValue(value, assetsDir, state = { nextId: 0 }, ancestors = new Set(), key = '', applyToJSON = true) {`,
513
- ` const blob = typeof Blob !== 'undefined' && value instanceof Blob`,
514
- ` const buffer = Buffer.isBuffer(value)`,
515
- ` if (blob || value instanceof Uint8Array) {`,
516
- ` const id = state.nextId++`,
517
- ` state.directory ||= mkdir(assetsDir, { recursive: true })`,
518
- ` await state.directory`,
519
- ` const bytes = blob ? new Uint8Array(await value.arrayBuffer()) : value`,
520
- ` await writeFile(assetsDir + '/' + id, bytes)`,
521
- ` return { [valueMarker]: {`,
522
- ` id,`,
523
- ` kind: blob ? 'blob' : buffer ? 'buffer' : 'uint8array',`,
524
- ` ...(blob && value.type ? { type: value.type } : {}),`,
525
- ` tag: 'binary',`,
526
- ` } }`,
527
- ` }`,
528
- ` if (value && typeof value === 'object' && applyToJSON && typeof value.toJSON === 'function')`,
529
- ` return await extractValue(Reflect.apply(value.toJSON, value, [key]), assetsDir, state, ancestors, key, false)`,
530
- ` if (Array.isArray(value)) {`,
531
- ` if (ancestors.has(value))`,
532
- ` throw new TypeError('Sandbox result must be JSON-serializable; cyclic value.')`,
533
- ` const nextAncestors = new Set(ancestors).add(value)`,
534
- ` return await Promise.all(value.map((entry, index) => extractValue(entry, assetsDir, state, nextAncestors, String(index))))`,
535
- ` }`,
536
- ` if (!value || typeof value !== 'object') return value`,
537
- ` if (isBoxedJsonPrimitive(value)) return await extractValue(value.valueOf(), assetsDir, state, ancestors, key, false)`,
538
- ` if (ancestors.has(value))`,
539
- ` throw new TypeError('Sandbox result must be JSON-serializable; cyclic value.')`,
540
- ` const nextAncestors = new Set(ancestors).add(value)`,
541
- ` const sourceEntries = Object.entries(value).filter(([entryKey, entry]) => applyToJSON || entryKey !== 'toJSON' || typeof entry !== 'function')`,
542
- ` const entries = await Promise.all(sourceEntries.map(async ([entryKey, entry]) => [`,
543
- ` entryKey,`,
544
- ` await extractValue(entry, assetsDir, state, nextAncestors, entryKey),`,
545
- ` ]))`,
546
- ` return hasMarker(value) ? { [valueMarker]: { entries, tag: 'object' } } : Object.fromEntries(entries)`,
547
- `}`,
548
- ``,
549
- `async function serializeSuccess(result, assetsDir) {`,
550
- ` try {`,
551
- ` const encoded = await extractValue(result, assetsDir)`,
552
- ` return JSON.stringify({ ok: true, result: encoded }, (key, value) => {`,
553
- ` const type = typeof value`,
554
- ` if (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint')`,
555
- ` throw new TypeError('Sandbox result must be JSON-serializable; unsupported ' + type + (key ? ' at "' + key + '".' : '.'))`,
556
- ` if (type === 'number' && !Number.isFinite(value))`,
557
- ` throw new TypeError('Sandbox result must be JSON-serializable; non-finite number' + (key ? ' at "' + key + '".' : '.'))`,
558
- ` return value`,
559
- ` })`,
560
- ` }`,
561
- ` catch (error) {`,
562
- ` if (error instanceof TypeError && error.message.startsWith('Sandbox result must be JSON-serializable'))`,
563
- ` throw error`,
564
- ` throw new TypeError('Sandbox result must be JSON-serializable.', { cause: error })`,
565
- ` }`,
566
- `}`,
567
- ``,
568
- `export async function main(argv = process.argv.slice(2)) {`,
569
- ` const [inputPath, outputPath] = argv`,
570
- ` try {`,
571
- ` const raw = await readFile(inputPath, 'utf8')`,
572
- ` const input = await reviveValue(JSON.parse(raw || '{}'), inputPath + '.files', 'input')`,
573
- ...invocation,
574
- ` const output = await serializeSuccess(result, outputPath + '.files')`,
575
- ` await writeFile(outputPath, output)`,
576
- ` console.log('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
577
- ` }`,
578
- ` catch (error) {`,
579
- ` const output = JSON.stringify({ ok: false, error: normalizeError(error) })`,
580
- ` await writeFile(outputPath, output)`,
581
- ` console.error('${EXEC_STDIO_OUTPUT_MARKER}' + output)`,
582
- ` process.exitCode = 1`,
583
- ` }`,
584
- `}`,
585
- ``,
586
- `await main()`,
587
- ``
588
- ].join("\n");
589
- }
590
- //#endregion
591
- //#region src/runtime/execution-files.ts
592
- const DEFAULT_DEFINITION_ENTRY = "definition.js";
593
- function normalizeSandboxDefinitionBundle(source) {
594
- if (typeof source === "string") return {
595
- entry: DEFAULT_DEFINITION_ENTRY,
596
- modules: { [DEFAULT_DEFINITION_ENTRY]: source }
597
- };
598
- return source;
599
- }
600
- function createExecutionFiles(definitionName) {
601
- const nonce = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
602
- const baseDir = `/tmp/vitehub-sandbox/${definitionName.replace(/[^a-z0-9/_-]/gi, "_")}-${nonce}`;
603
- return {
604
- baseDir,
605
- entryPath: `${baseDir}/entry.mjs`,
606
- inputAssetsDir: `${baseDir}/input.json.files`,
607
- inputPath: `${baseDir}/input.json`,
608
- outputAssetsDir: `${baseDir}/output.json.files`,
609
- outputPath: `${baseDir}/output.json`
610
- };
611
- }
612
- function resolveSandboxModulePath(baseDir, modulePath) {
613
- if (modulePath === ".") return baseDir;
614
- return `${baseDir}/${modulePath}`;
615
- }
616
- function normalizeSandboxBundlePath(path) {
617
- const slashPath = path.replace(/\\/g, "/");
618
- const normalized = slashPath.replace(/^\/+|\/+$/g, "");
619
- const parts = normalized.split("/").filter(Boolean);
620
- 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}.`);
621
- return parts.join("/");
622
- }
623
- async function writeSandboxDefinitionBundle(sandbox, baseDir, bundle) {
624
- const files = Object.entries({
625
- ...bundle.project ? Object.fromEntries(Object.entries(bundle.project.files).map(([path, file]) => [path, Uint8Array.from(Buffer.from(file.contents, file.encoding))])) : {},
626
- ...bundle.modules
627
- }).map(([path, source]) => ({
628
- path: normalizeSandboxBundlePath(path),
629
- source
630
- }));
631
- const modes = Object.entries(bundle.project?.files || {}).filter(([, file]) => Boolean(file.mode)).map(([path, file]) => ({
632
- mode: file.mode,
633
- path: normalizeSandboxBundlePath(path)
634
- }));
635
- await sandbox.files.remove(baseDir, { recursive: true });
636
- await sandbox.files.mkdir(baseDir, { recursive: true });
637
- await Promise.all(files.map(async ({ path, source }) => {
638
- const parent = dirname(path);
639
- if (parent !== ".") await sandbox.files.mkdir(`${baseDir}/${parent}`, { recursive: true });
640
- await sandbox.files.write(`${baseDir}/${path}`, typeof source === "string" ? new TextEncoder().encode(source) : source);
641
- }));
642
- await Promise.all(modes.map(async ({ mode, path }) => {
643
- await sandbox.exec("chmod", [mode.toString(8), `${baseDir}/${path}`]);
644
- }));
645
- }
646
- //#endregion
647
- //#region src/runtime/output-recovery.ts
648
- const MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 2e4;
649
- const DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 6e4;
650
- const MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS = 12e4;
651
- const EXEC_OUTPUT_RECOVERY_POLL_MS = 1e3;
652
- const EXEC_OUTPUT_PREVIEW_LENGTH = 500;
653
- const HANDLER_DIAGNOSTIC_LENGTH = 16384;
654
- function getErrorMessage(error) {
655
- if (error instanceof Error) return error.message;
656
- if (error && typeof error === "object") {
657
- const candidate = error;
658
- if (typeof candidate.message === "string" && candidate.message) return candidate.message;
659
- if (typeof candidate.stderr === "string" && candidate.stderr) return candidate.stderr;
660
- if (typeof candidate.stdout === "string" && candidate.stdout) return candidate.stdout;
661
- }
662
- if (error === void 0) return void 0;
663
- return String(error);
664
- }
665
- function isRecoverableCloudflareExecError(error) {
666
- const metadata = readSandboxErrorMetadata(error);
667
- if (metadata?.provider && metadata.provider !== "cloudflare") return false;
668
- if (metadata?.code === "SANDBOX_TIMEOUT" || metadata?.code === "SANDBOX_TRANSPORT_ERROR") return true;
669
- return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error));
670
- }
671
- function createHandlerError(message, provider, details) {
672
- const publicDetails = {};
673
- for (const [key, value] of Object.entries(details || {})) if (typeof value === "string") publicDetails[key] = value.slice(0, HANDLER_DIAGNOSTIC_LENGTH);
674
- else if (value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) publicDetails[key] = value;
675
- return sandboxError(message.slice(0, HANDLER_DIAGNOSTIC_LENGTH) || "Sandbox handler failed.", {
676
- code: "SANDBOX_HANDLER_ERROR",
677
- provider,
678
- 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
679
135
  });
680
136
  }
681
- function createTimeoutError(provider, timeout) {
682
- return sandboxError(`Sandbox definition timed out after ${timeout}ms.`, {
683
- code: "SANDBOX_TIMEOUT",
684
- provider,
685
- 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)
686
148
  });
687
149
  }
688
- function tryParseSandboxOutput(outputRaw) {
689
- if (!outputRaw.trim()) return null;
690
- try {
691
- return JSON.parse(outputRaw);
692
- } catch {
693
- return null;
694
- }
695
- }
696
- function extractSandboxOutputFromExecution(execution) {
697
- const streams = [execution?.stdout, execution?.stderr].filter(Boolean);
698
- for (const stream of streams) for (const line of stream.split("\n").reverse()) {
699
- const markerIndex = line.indexOf(EXEC_STDIO_OUTPUT_MARKER);
700
- if (markerIndex < 0) continue;
701
- return line.slice(markerIndex + 18);
702
- }
703
- return null;
704
- }
705
- function previewExecutionStream(stream) {
706
- if (!stream) return void 0;
707
- return stream.slice(0, EXEC_OUTPUT_PREVIEW_LENGTH);
708
- }
709
- function getExecutionDiagnostics(execution) {
710
- return {
711
- args: Array.isArray(execution?.meta?.args) ? execution?.meta?.args : void 0,
712
- command: typeof execution?.meta?.command === "string" ? execution.meta.command : void 0,
713
- cwd: typeof execution?.meta?.cwd === "string" ? execution.meta.cwd : void 0,
714
- exitCode: typeof execution?.code === "undefined" ? void 0 : execution.code,
715
- stderrPreview: previewExecutionStream(execution?.stderr),
716
- stdoutPreview: previewExecutionStream(execution?.stdout)
717
- };
718
- }
719
- function getErrorDiagnostics(error) {
720
- if (!error || typeof error !== "object" || !("details" in error)) return {};
721
- const details = error.details;
722
- if (!details || typeof details !== "object") return {};
723
- return {
724
- args: Array.isArray(details.args) ? details.args : void 0,
725
- command: typeof details.command === "string" ? details.command : void 0,
726
- cwd: typeof details.cwd === "string" ? details.cwd : void 0,
727
- exitCode: typeof details.exitCode === "number" || details.exitCode === null ? details.exitCode : void 0,
728
- spawnErrorCode: typeof details.spawnErrorCode === "string" ? details.spawnErrorCode : void 0,
729
- spawnErrorMessage: typeof details.spawnErrorMessage === "string" ? details.spawnErrorMessage : void 0,
730
- stderrPreview: typeof details.stderrPreview === "string" ? details.stderrPreview : void 0,
731
- stdoutPreview: typeof details.stdoutPreview === "string" ? details.stdoutPreview : void 0
732
- };
733
- }
734
- function resolveExecOutputRecoveryTimeout(timeout) {
735
- if (!timeout || timeout <= 0) return DEFAULT_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS;
736
- return Math.min(MAX_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.max(MIN_EXEC_OUTPUT_RECOVERY_TIMEOUT_MS, Math.floor(timeout * .1)));
737
- }
738
- function createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution, details) {
739
- return createHandlerError("Sandbox definition execution failed before producing an output file.", sandbox.provider, {
740
- outputPath,
741
- cause: getErrorMessage(error),
742
- recoveryTimeout,
743
- ...details,
744
- ...getErrorDiagnostics(error),
745
- ...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)
746
162
  });
747
- }
748
- async function waitForExecOutput(sandbox, outputPath, error, timeout, execution, shouldAccept) {
749
- const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
750
- const deadline = Date.now() + recoveryTimeout;
751
- let lastError = error;
752
- let lastOutput = "";
753
- while (Date.now() < deadline) {
754
- try {
755
- const output = await sandbox.readFile(outputPath);
756
- lastOutput = output;
757
- if (shouldAccept(output)) return output;
758
- } catch (readError) {
759
- lastError = readError;
760
- }
761
- await sleep(EXEC_OUTPUT_RECOVERY_POLL_MS);
762
- }
763
- throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution, {
764
- lastReadError: getErrorMessage(lastError),
765
- 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
+ };
766
187
  });
767
- }
768
- async function recoverExecOutput(sandbox, outputPath, error, timeout, execution) {
769
- if (sandbox.provider !== "cloudflare" || !isRecoverableCloudflareExecError(error)) return null;
770
- return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, (output) => !!tryParseSandboxOutput(output));
771
- }
772
- async function waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution) {
773
- const recoveryTimeout = resolveExecOutputRecoveryTimeout(timeout);
774
- if (sandbox.provider !== "cloudflare") throw createExecOutputFailure(sandbox, outputPath, error, recoveryTimeout, execution);
775
- return await waitForExecOutput(sandbox, outputPath, error, timeout, execution, (output) => !!tryParseSandboxOutput(output));
776
- }
777
- async function readExecOutputWithRecovery(sandbox, outputPath, error, timeout, execution) {
778
- const executionOutput = extractSandboxOutputFromExecution(execution) || extractSandboxOutputFromExecution(error);
779
- if (executionOutput) return executionOutput;
780
- try {
781
- const output = await sandbox.readFile(outputPath);
782
- if (tryParseSandboxOutput(output)) return output;
783
- } catch {
784
- 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);
785
192
  }
786
- return await waitForCloudflareOutput(sandbox, outputPath, error, timeout, execution);
787
- }
788
- //#endregion
789
- //#region src/runtime/execute.ts
790
- const defaultNodeLauncher = "import(process.argv[1])";
791
- const projectPreparations = /* @__PURE__ */ new Map();
792
- function toJson(value, label) {
793
- try {
794
- return JSON.stringify(value);
795
- } catch (error) {
796
- throw sandboxError(`Sandbox ${label} must be JSON-serializable.`, {
797
- code: "SANDBOX_SERIALIZATION_ERROR",
798
- details: { label },
799
- cause: error
800
- });
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`);
801
198
  }
802
- }
803
- function resolveLauncher() {
804
199
  return {
805
- command: "node",
806
- args: ["-e", defaultNodeLauncher]
200
+ env: Object.freeze(env),
201
+ files: Object.freeze(files),
202
+ state: Object.freeze(state)
807
203
  };
808
204
  }
809
- async function prepareSandboxProject(sandbox, bundle, baseDir, options) {
810
- const project = bundle.project;
811
- if (!project) return baseDir;
812
- const projectDir = `/tmp/vitehub-sandbox/projects/${project.digest}`;
813
- const marker = `${projectDir}/.vitehub/prepared`;
814
- await sandbox.mkdir("/tmp/vitehub-sandbox/projects", { recursive: true });
815
- if (await sandbox.exists(marker)) return projectDir;
816
- const preparationKey = `${sandbox.id}:${project.digest}`;
817
- while (!await sandbox.exists(marker)) {
818
- let preparation = projectPreparations.get(preparationKey);
819
- let owned = false;
820
- if (!preparation) {
821
- owned = true;
822
- preparation = prepareSandboxProjectAtomically(sandbox, {
823
- ...bundle,
824
- project
825
- }, projectDir, marker, options);
826
- projectPreparations.set(preparationKey, preparation);
827
- preparation.finally(() => {
828
- if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
829
- }).catch(() => {});
830
- }
831
- try {
832
- await preparation;
833
- } catch (error) {
834
- if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
835
- if (owned || options.signal?.aborted) throw error;
836
- 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) }];
837
218
  }
838
- if (projectPreparations.get(preparationKey) === preparation) projectPreparations.delete(preparationKey);
839
- }
840
- return projectDir;
841
- }
842
- async function prepareSandboxProjectAtomically(sandbox, bundle, projectDir, marker, options) {
843
- if (await sandbox.exists(marker)) return;
844
- const staging = `${projectDir}.staging-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
845
- try {
846
- await sandbox.mkdir(staging, { recursive: true });
847
- await writeSandboxDefinitionBundle(sandbox, staging, bundle);
848
- const result = await executeLauncher(sandbox, bundle.project.install.command, bundle.project.install.args, {
849
- ...options,
850
- cwd: resolveSandboxModulePath(staging, bundle.project.install.cwd)
851
- });
852
- if (!result.ok) throw sandboxError("Sandbox package preparation failed.", {
853
- code: "SANDBOX_EXECUTION_ERROR",
854
- details: {
855
- command: bundle.project.install.command,
856
- exitCode: result.code,
857
- stderr: result.stderr
858
- }
859
- });
860
- await sandbox.mkdir(`${staging}/.vitehub`, { recursive: true });
861
- await sandbox.writeFile(`${staging}/.vitehub/prepared`, bundle.project.digest);
862
- const published = await sandbox.exec("node", [
863
- "-e",
864
- "import(\"node:fs/promises\").then(({ rename }) => rename(process.argv[1], process.argv[2]))",
865
- staging,
866
- projectDir
867
- ], { signal: options.signal });
868
- if (!published.ok && !await sandbox.exists(marker)) throw sandboxError("Sandbox package preparation could not publish its project.", {
869
- code: "SANDBOX_EXECUTION_ERROR",
870
- details: {
871
- exitCode: published.code,
872
- stderr: published.stderr
873
- }
874
- });
875
- } finally {
876
- await sandbox.exec("rm", [
877
- "-rf",
878
- "--",
879
- staging
880
- ]).catch(() => {});
881
- }
882
- }
883
- async function executeLauncher(sandbox, command, args, options) {
884
- return await sandbox.exec(command, args, {
885
- cwd: options.cwd,
886
- env: options.env,
887
- signal: options.signal,
888
- timeout: options.timeout
889
- });
890
- }
891
- async function executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, deadline, lifecycle) {
892
- const bundle = normalizeSandboxDefinitionBundle(source);
893
- const files = createExecutionFiles(definitionName);
894
- const throwIfAborted = () => {
895
- if (signal?.aborted) throw createTimeoutError(sandbox.provider, definitionOptions?.timeout || 0);
896
- };
897
- await sandbox.mkdir(files.baseDir, { recursive: true });
898
- try {
899
- throwIfAborted();
900
- let inputJson = bundle.project ? toJson(await encodeSandboxValue(sandbox, {
901
- payload,
902
- context
903
- }, files.inputAssetsDir, "payload/context", signal), "payload/context") : void 0;
904
- const bundleBaseDir = await prepareSandboxProject(sandbox, bundle, files.baseDir, {
905
- deadline,
906
- signal,
907
- timeout: definitionOptions?.timeout
908
- });
909
- if (!bundle.project) await writeSandboxDefinitionBundle(sandbox, bundleBaseDir, bundle);
910
- inputJson ||= toJson(await encodeSandboxValue(sandbox, {
911
- payload,
912
- context
913
- }, files.inputAssetsDir, "payload/context", signal), "payload/context");
914
- const definitionPath = resolveSandboxModulePath(bundleBaseDir, bundle.entry);
915
- throwIfAborted();
916
- await Promise.all([sandbox.writeFile(files.entryPath, createEntrySource(definitionPath, bundle.execution)), sandbox.writeFile(files.inputPath, inputJson)]);
917
- throwIfAborted();
918
- const launcher = resolveLauncher();
919
- const execArgs = [
920
- ...launcher.args,
921
- files.entryPath,
922
- files.inputPath,
923
- files.outputPath
924
- ];
925
- let outputRaw = "";
926
- let execution;
927
- try {
928
- lifecycle?.onHandlerStart?.();
929
- execution = await executeLauncher(sandbox, launcher.command, execArgs, {
930
- cwd: bundle.project ? resolveSandboxModulePath(bundleBaseDir, bundle.project.packagePath) : files.baseDir,
931
- deadline,
932
- env: definitionOptions?.env,
933
- signal,
934
- timeout: definitionOptions?.timeout
935
- });
936
- outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, execution, definitionOptions?.timeout, execution);
937
- } catch (error) {
938
- if (readSandboxErrorMetadata(error)?.details?.operation === "createSession") throw error;
939
- if (execution) outputRaw = await readExecOutputWithRecovery(sandbox, files.outputPath, error, definitionOptions?.timeout, execution);
940
- else {
941
- const recoveredOutput = await recoverExecOutput(sandbox, files.outputPath, error, definitionOptions?.timeout, execution);
942
- if (recoveredOutput == null) throw error;
943
- outputRaw = recoveredOutput;
944
- }
945
- }
946
- const output = tryParseSandboxOutput(outputRaw) || tryParseSandboxOutput(extractSandboxOutputFromExecution(execution) || "");
947
- if (!output) throw createHandlerError("Sandbox definition output is not valid JSON.", sandbox.provider, {
948
- output: outputRaw,
949
- cause: "Output file was empty or contained incomplete JSON."
950
- });
951
- if (output.ok) return await decodeSandboxValue(sandbox, output.result, files.outputAssetsDir, "result");
952
- throw createHandlerError(output.error?.message || "Sandbox definition failed.", sandbox.provider, {
953
- name: output.error?.name,
954
- stack: output.error?.stack,
955
- cause: output.error?.cause,
956
- stdout: execution?.stdout,
957
- stderr: execution?.stderr,
958
- exitCode: execution?.code
959
- });
960
- } finally {
961
- if (sandbox.provider === "cloudflare") await sandbox.exec("rm", [
962
- "-rf",
963
- "--",
964
- files.baseDir
965
- ]).catch(() => {});
966
- }
967
- }
968
- async function executeSandboxDefinition(sandbox, definitionName, definitionOptions, source, payload, context, lifecycle) {
969
- const timeout = definitionOptions?.timeout;
970
- if (timeout === void 0 || timeout <= 0) return await executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, void 0, void 0, lifecycle);
971
- let timeoutId;
972
- const abortController = new AbortController();
973
- const deadline = Date.now() + timeout;
974
- try {
975
- return await Promise.race([executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, abortController.signal, deadline, lifecycle), new Promise((_, reject) => {
976
- timeoutId = setTimeout(() => {
977
- const timeoutError = createTimeoutError(sandbox.provider, timeout);
978
- abortController.abort(timeoutError);
979
- reject(timeoutError);
980
- }, timeout);
981
- })]);
982
- } finally {
983
- 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));
984
236
  }
985
237
  }
986
- //#endregion
987
- //#region src/runtime/execution-box.ts
988
- function createSandboxExecutionBox(session, provider) {
989
- return {
990
- executionAuthority: session.executionAuthority,
991
- id: session.id,
992
- files: session.files,
993
- provider,
994
- async close() {
995
- await session.close();
996
- },
997
- async exec(command, args, options) {
998
- return await session.exec(command, args, options);
999
- },
1000
- async exists(path) {
1001
- return await session.files.exists(path);
1002
- },
1003
- async mkdir(path, options) {
1004
- await session.files.mkdir(path, options);
1005
- },
1006
- async readFile(path) {
1007
- const contents = await session.files.read(path);
1008
- if (!contents) throw new Error(`[vitehub] Sandbox file does not exist: ${path}`);
1009
- return new TextDecoder().decode(contents);
1010
- },
1011
- async writeFile(path, contents) {
1012
- await session.files.write(path, new TextEncoder().encode(contents));
1013
- }
1014
- };
1015
- }
1016
- //#endregion
1017
- //#region src/internal/shared/provider-detection.ts
1018
- function createProviderDetector(rules) {
1019
- return () => {
1020
- for (const rule of rules) if (rule.when()) return rule.provider;
1021
- };
1022
- }
1023
- function getRuntimeEnv() {
1024
- return typeof process !== "undefined" ? process.env : {};
1025
- }
1026
- const isCloudflare = () => {
1027
- const env = getRuntimeEnv();
1028
- return !!(env.CLOUDFLARE_WORKER || env.CF_PAGES);
1029
- };
1030
- const isVercel = () => {
1031
- const env = getRuntimeEnv();
1032
- return !!(env.VERCEL || env.VERCEL_ENV);
1033
- };
1034
- //#endregion
1035
- //#region src/runtime/provider-loader-resolver.ts
1036
- async function loadSandboxProviderRuntime(provider) {
1037
- return await (await import("vitehub-sandbox-provider-loader").catch(() => {
1038
- return new Function("specifier", "return import(specifier)")("@vite-hub/sandbox/runtime/provider-loader");
1039
- })).loadSandboxRuntimeProvider(provider);
1040
- }
1041
- //#endregion
1042
- //#region src/runtime/provider-resolution.ts
1043
- const allowedDefinitionKeys = new Set(["timeout", "env"]);
1044
- const maxTimeout = 2147483647;
1045
- const detectProvider = createProviderDetector([{
1046
- provider: "cloudflare",
1047
- when: isCloudflare
1048
- }, {
1049
- provider: "vercel",
1050
- when: isVercel
1051
- }]);
1052
- function detectSandbox() {
1053
- const env = typeof process !== "undefined" ? process.env : {};
1054
- const type = detectProvider() || "none";
1055
- if (type === "cloudflare") return {
1056
- type,
1057
- details: { runtime: typeof process === "undefined" ? "workerd" : "node" }
1058
- };
1059
- if (type === "vercel") return {
1060
- type,
1061
- details: { env: env.VERCEL_ENV }
1062
- };
1063
- return { type };
1064
- }
1065
- function hashCloudflareSandboxName(name) {
1066
- let hash = 2166136261;
1067
- for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), 16777619);
1068
- return (hash >>> 0).toString(36);
1069
- }
1070
- function createCloudflareExecutionSandboxId(name, sandboxId) {
1071
- if (sandboxId) return sandboxId;
1072
- const prefix = "vitehub-";
1073
- const suffix = `-${hashCloudflareSandboxName(name)}-${crypto.randomUUID()}`;
1074
- return `${prefix}${encodeURIComponent(name).slice(0, 55 - suffix.length)}${suffix}`;
1075
- }
1076
- function resolveRuntimeProvider(provider, event) {
1077
- if (provider?.provider) return provider.provider;
1078
- const envProvider = typeof process !== "undefined" ? process.env?.SANDBOX_PROVIDER : void 0;
1079
- if (envProvider === "cloudflare" || envProvider === "vercel") return envProvider;
1080
- if (getCloudflareEnv(event)) return "cloudflare";
1081
- const detected = detectSandbox();
1082
- if (detected.type === "cloudflare" || detected.type === "vercel") return detected.type;
1083
- throw sandboxError("Sandbox provider could not be inferred. Configure `sandbox.provider` as `cloudflare` or `vercel`.", { code: "SANDBOX_PROVIDER_REQUIRED" });
1084
- }
1085
- function assertSandboxDefinitionOptions(local) {
1086
- const invalidKeys = Object.keys(local).filter((key) => !allowedDefinitionKeys.has(key));
1087
- if (invalidKeys.length > 0) throw new TypeError(`[vitehub] Sandbox definition options only support timeout and env. Unsupported: ${invalidKeys.join(", ")}`);
1088
- if (local.timeout !== void 0 && (!Number.isInteger(local.timeout) || local.timeout <= 0 || local.timeout > maxTimeout)) throw new TypeError(`[vitehub] Sandbox definition timeout must be a positive integer no greater than ${maxTimeout}.`);
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
- if (metadata?.code === "SANDBOX_TIMEOUT") return false;
1135
- const extraMessage = metadata?.cause instanceof Error ? metadata.cause.message : "";
1136
- return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error, extraMessage));
1137
- }
1138
- const sandboxRuntime = createResourceRuntime({
1139
- feature: "sandbox",
1140
- readConfig(runtimeConfig) {
1141
- return runtimeConfig.sandbox;
1142
- },
1143
- getFallbackConfig: getSandboxRuntimeConfig,
1144
- registry: {
1145
- entries: new Proxy(sandboxRegistry, { get(target, property) {
1146
- if (typeof property !== "string") return Reflect.get(target, property);
1147
- return getSandboxRuntimeRegistry()?.[property] ?? target[property];
1148
- } }),
1149
- validate(definition) {
1150
- 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));
1151
- }
1152
- },
1153
- port: {
1154
- async resolve(context) {
1155
- assertSandboxDefinitionOptions(context.definition.options ?? {});
1156
- const config = getSandboxFeatureProvider(context.config);
1157
- const provider = resolveRuntimeProvider(config, context.event);
1158
- return await resolveSandboxBox(provider, withSandboxProvider(provider, config), context.definition.options ?? {}, { event: context.event });
1159
- },
1160
- async create(provider, context) {
1161
- const packageManager = context.definition.bundle.project?.install.command;
1162
- 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." });
1163
274
  return {
1164
- executionAuthority: box.plan.executionAuthority,
1165
- name: context.name,
1166
- async run(payload, options = {}) {
1167
- const cloudflareSandboxId = provider.provider === "cloudflare" ? createCloudflareExecutionSandboxId(context.name, options.sandboxId || provider.sandboxId) : void 0;
1168
- const attempts = provider.provider === "cloudflare" ? CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length + 1 : 1;
1169
- return await serializeCloudflareRun(cloudflareSandboxId, async () => {
1170
- for (let attempt = 0; attempt < attempts; attempt++) {
1171
- let sandbox;
1172
- let handlerMayHaveStarted = false;
1173
- let runError;
1174
- try {
1175
- sandbox = createSandboxExecutionBox(await box.open({ id: cloudflareSandboxId }), provider.provider);
1176
- return await executeSandboxDefinition(sandbox, context.name, context.definition.options, context.definition.bundle, payload, options.context, { onHandlerStart() {
1177
- handlerMayHaveStarted = true;
1178
- } });
1179
- } catch (error) {
1180
- const sandboxError = toSandboxError(error);
1181
- runError = sandboxError;
1182
- if (!(!handlerMayHaveStarted && provider.provider === "cloudflare" && attempt < CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length && isRetriableCloudflareSandboxError(sandboxError))) throw sandboxError;
1183
- await sleep(CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS[attempt]);
1184
- } finally {
1185
- if (provider.closeAfterRun !== false || provider.provider === "cloudflare" && !options.sandboxId && !provider.sandboxId) try {
1186
- await sandbox?.close();
1187
- } catch (cleanupError) {
1188
- if (runError) throw new AggregateError([runError, cleanupError], `${runError.message} Cleanup failed: ${toSandboxError(cleanupError).message}`);
1189
- throw toSandboxError(cleanupError);
1190
- }
1191
- }
1192
- }
1193
- throw sandboxError("Cloudflare sandbox retries exhausted.", {
1194
- code: "SANDBOX_RUNTIME_ERROR",
1195
- provider: provider.provider
1196
- });
1197
- });
1198
- }
275
+ args: [],
276
+ command,
277
+ name: command
1199
278
  };
1200
279
  }
1201
- }
1202
- });
1203
- async function resolveSandboxRunner(name) {
1204
- 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()];
1205
298
  }
1206
- async function runSandboxRuntime(name, payload, options) {
1207
- try {
1208
- return ok(await (await resolveSandboxRunner(name)).run(payload, options));
1209
- } catch (error) {
1210
- return err(toSandboxError(error));
1211
- }
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;
1212
303
  }
1213
- //#endregion
1214
- //#region src/runtime/public.ts
1215
- async function runSandbox(name, payload, options) {
1216
- 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;
1217
311
  }
1218
312
  //#endregion
1219
- export { defineSandbox, readRequestPayload, readValidatedPayload, resolveSandboxRunner, runSandbox };
313
+ export { resolveSandbox };