@vite-hub/sandbox 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,19 +1,39 @@
1
1
  # @vite-hub/sandbox
2
2
 
3
- `@vite-hub/sandbox` discovers and runs named work by composing a package project and a Box. Sandbox owns discovery, orchestration, and project staging; Box owns provider-specific execution.
3
+ Run a discovered Sandbox Definition inside a provider-backed Box. Sandbox owns discovery, package staging, typed invocation, timeouts, and result transport. Box owns the execution environment and its isolation.
4
4
 
5
- ```ts
6
- // server/sandboxes/release-notes/index.ts
7
- interface SandboxPayload {
8
- notes?: string
9
- }
5
+ Most applications should install [`vite-hub`](https://vitehub.dev/docs/getting-started/installation) and import APIs such as `runSandbox` from `vite-hub/sandbox`. Install `@vite-hub/sandbox` directly when you are building a library, a custom Vite composition, or package-level tooling.
10
6
 
11
- export default async function releaseNotes(payload: SandboxPayload = {}) {
12
- return { summary: payload.notes?.split("\n")[0] ?? "" }
13
- }
7
+ ## Install
8
+
9
+ Install Sandbox, Vite, and the Box provider used by your deployment. This first run uses Vercel Sandbox:
10
+
11
+ ```sh
12
+ pnpm add @vite-hub/sandbox @vercel/sandbox vite
13
+ ```
14
+
15
+ Sandbox requires Node.js 24 or newer. Vercel execution also requires a Vercel project with Sandbox access. At runtime, use the project's environment or set `VERCEL_TOKEN`, `VERCEL_TEAM_ID`, and `VERCEL_PROJECT_ID`.
16
+
17
+ For Cloudflare, install `@cloudflare/sandbox` instead and use the ViteHub Cloudflare host integration so it can emit the required Container, Durable Object binding, migration, and Worker exports. Both providers run remote, potentially billed infrastructure; Sandbox does not include a local in-process provider.
18
+
19
+ ## Run one Sandbox
20
+
21
+ Register discovery and select the provider in Vite:
22
+
23
+ ```ts
24
+ // vite.config.ts
25
+ import { hubSandbox } from "@vite-hub/sandbox/vite";
26
+ import { defineConfig } from "vite";
27
+
28
+ export default defineConfig({
29
+ plugins: [hubSandbox({ provider: "vercel" })],
30
+ build: {
31
+ ssr: "src/server.ts",
32
+ },
33
+ });
14
34
  ```
15
35
 
16
- The folder supplies the Definition name, and the adjacent manifest owns portable lifecycle metadata:
36
+ Create a package-backed Definition at `server/sandboxes/release-notes/package.json`. The folder path supplies the name `release-notes`, and its manifest owns the timeout for each execution attempt:
17
37
 
18
38
  ```json
19
39
  {
@@ -27,30 +47,83 @@ The folder supplies the Definition name, and the adjacent manifest owns portable
27
47
  }
28
48
  ```
29
49
 
30
- ViteHub calls the default function with `(payload, context)` and infers the `runSandbox()` payload and result types from it. Nested `Blob` and `Uint8Array` values cross the Box boundary through binary sidecars rather than application JSON; Node.js `Buffer` values retain their `Buffer` type. Existing non-function default exports remain supported; their optional exported `SandboxPayload` type is the payload fallback. The entrypoint needs no `@vite-hub/sandbox` runtime dependency.
31
-
32
- ViteHub uses the manifest's `packageManager`, then a lockfile at that package root, then npm. A matching `pnpm-workspace.yaml` selects pnpm, moves preparation to the pnpm workspace root, and carries the transitive `workspace:*` dependency closure into the Box while the entrypoint still runs from its package directory.
50
+ ```ts
51
+ // server/sandboxes/release-notes/index.ts
52
+ interface ReleaseNotesPayload {
53
+ notes?: string;
54
+ }
33
55
 
34
- Package entrypoints are ESM projects. Keep `"type": "module"`, use explicit relative ESM imports for local `.ts` and `.mts` source, and depend on packages that expose runtime-ready JavaScript. ViteHub compiles the reachable local TypeScript graph without bundling package dependencies or moving relative assets. It rejects CommonJS/CTS, package import aliases and self-references for local source, imports that escape the selected package, and workspace dependencies that expose TypeScript runtime entries.
56
+ export default async function releaseNotes(payload: ReleaseNotesPayload = {}) {
57
+ return { summary: payload.notes?.split("\n")[0] ?? "" };
58
+ }
59
+ ```
35
60
 
36
- Use `<path>.sandbox.ts` with `defineSandbox()` for free-form Definitions outside `server/sandboxes`.
61
+ Invoke the discovered name from server code. `runSandbox()` returns an error-first tuple and infers its payload and result from the Definition:
37
62
 
38
63
  ```ts
39
- import { runSandbox } from "@vite-hub/sandbox"
64
+ // src/server.ts
65
+ import { runSandbox } from "@vite-hub/sandbox";
66
+
67
+ const [error, result] = await runSandbox("release-notes", {
68
+ notes: "ship it\nadd tests",
69
+ });
40
70
 
41
- const [error, result] = await runSandbox("release-notes", { notes: "ship it" })
42
- if (error) throw error
71
+ if (error) throw error;
72
+
73
+ console.log(JSON.stringify(result));
74
+ ```
75
+
76
+ Build through Vite so discovery and the runtime registry are generated, then run the server entry:
77
+
78
+ ```sh
79
+ pnpm vite build
80
+ node dist/server.js
81
+ ```
82
+
83
+ The process prints:
84
+
85
+ ```json
86
+ { "summary": "ship it" }
43
87
  ```
44
88
 
45
- Resolve a runner when orchestration needs to inspect the provider boundary before execution:
89
+ The Definition entrypoint does not import `@vite-hub/sandbox`. ViteHub calls its default function with `(payload, context)` and returns its awaited result.
90
+
91
+ ## Provider and lifecycle limits
92
+
93
+ - Provider selection belongs to application or host configuration, not to a Definition. `hubSandbox({ provider: "vercel" })` and `hubSandbox({ provider: "cloudflare" })` are the direct-package forms. The `vite-hub` distribution can infer these from its Vercel and Cloudflare presets.
94
+ - `vitehub.sandbox.timeout` must be a positive integer no greater than `2_147_483_647`. It bounds one execution attempt after provider startup, including package preparation, staging, and execution. Queueing, Box startup, and retry delays can make the complete `runSandbox()` call take longer. An elapsed attempt timeout sends an internal abort signal to cancellable provider operations and returns a `SANDBOX_TIMEOUT` error in the tuple.
95
+ - Callers cannot currently pass an `AbortSignal` to `runSandbox()`. A disconnected request does not by itself cancel the run; configure a Definition timeout to bound each execution attempt.
96
+ - Vercel Box sessions are closed in a `finally` block after success or failure. Cloudflare also creates and closes a unique Box for each run unless you configure `sandboxId` or pass one to `runSandbox()`. Cleanup failures are surfaced through the `runSandbox()` error tuple; they are not suppressed after a successful handler.
97
+ - An explicit Cloudflare `sandboxId` opts into a shared Box identity. ViteHub deletes invocation-local files after each attempt, caches prepared projects by digest inside that Box, and serializes runs with the same ID within one runtime isolate. Separate Worker isolates can still enter the Box concurrently, so use external coordination when deployment-wide serialization is required. The provider normally leaves an explicitly named Box for idle shutdown; setting `keepAlive: true` makes ViteHub close its session after the run.
98
+
99
+ ## Security and isolation
100
+
101
+ A Sandbox Definition name and its typed arguments select work; they are not a permission boundary. Code inside the Box can use whatever filesystem, environment, network, credentials, executables, and child-process authority the selected provider exposes.
102
+
103
+ Inspect that authority before execution when application policy depends on it:
46
104
 
47
105
  ```ts
48
- import { resolveSandboxRunner } from "@vite-hub/sandbox"
106
+ import { resolveSandboxRunner } from "@vite-hub/sandbox";
49
107
 
50
- const runner = await resolveSandboxRunner("release-notes")
51
- console.log(runner.executionAuthority)
108
+ const runner = await resolveSandboxRunner("release-notes");
109
+ console.log(runner.executionAuthority);
52
110
  ```
53
111
 
54
- The runner exposes the selected Box provider's complete `ExecutionAuthority` descriptor. A Sandbox Definition name and its structural command arguments choose work to run; they do not limit what that process can read, reach, inherit, or spawn.
112
+ The descriptor reports the provider's complete `ExecutionAuthority`, including dimensions it cannot establish as `unknown`. Apply provider controls such as Vercel `networkPolicy`, keep secrets in server environment or provider configuration, and do not treat container execution alone as authorization for untrusted code.
113
+
114
+ Payloads, context, and results must be JSON-serializable. Nested `Blob` and `Uint8Array` values cross the Box boundary through invocation-local binary files, and Node.js `Buffer` values retain their type.
115
+
116
+ ## Package projects
117
+
118
+ ViteHub uses the package manifest's `packageManager`, then a lockfile at that package root, then npm. A matching `pnpm-workspace.yaml` moves preparation to the pnpm Workspace root and carries the transitive `workspace:*` dependency closure into the Box while the entrypoint still runs from its package directory.
119
+
120
+ Package entrypoints are ESM projects. Keep `"type": "module"`, use explicit relative ESM imports for local `.ts` and `.mts` source, and depend on packages that expose runtime-ready JavaScript. ViteHub compiles reachable local TypeScript without bundling package dependencies or moving relative assets. It rejects CommonJS/CTS, local package aliases and self-references, imports that escape the selected package, and Workspace dependencies that expose TypeScript runtime entries.
121
+
122
+ Use `<path>.sandbox.ts` with `defineSandbox()` for a free-form Definition outside `server/sandboxes`. Free-form Definitions use their nearest package project.
123
+
124
+ ## Read more
55
125
 
56
- Add `hubSandbox()` to Vite for discovery, typed registry generation, package preparation plans, and host output. Provider images and full Dockerfile overrides belong to the selected Box adapter or host configuration; Sandbox Definitions stay portable.
126
+ - [Sandbox guide](https://vitehub.dev/docs/server-primitives/sandbox)
127
+ - [Box execution and security model](https://vitehub.dev/docs/agents/boxes)
128
+ - [Runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix)
129
+ - [ViteHub security policy](https://github.com/vite-hub/vitehub/blob/main/SECURITY.md)
@@ -1,12 +1,14 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- const activeEnvStorage = new AsyncLocalStorage();
2
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
3
+ const runtimeGlobal = globalThis;
4
+ const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
3
5
  function getActiveCloudflareEnv() {
4
6
  const scoped = activeEnvStorage.getStore();
5
7
  return scoped ? scoped.env : globalThis.__env__;
6
8
  }
7
9
  function getCloudflareEnv(event) {
8
10
  const target = event;
9
- return target?.env || target?.context?.cloudflare?.env || target?.context?._platform?.cloudflare?.env || target?.req?.runtime?.cloudflare?.env || getActiveCloudflareEnv();
11
+ return target?.env || target?.context?.cloudflare?.env || target?.context?._platform?.cloudflare?.env || target?.req?.runtime?.cloudflare?.env || target?.node?.req?.runtime?.cloudflare?.env || getActiveCloudflareEnv();
10
12
  }
11
13
  //#endregion
12
14
  export { getCloudflareEnv as t };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { a as SandboxDefinitionBundle, c as SandboxDefinitionInput, d as SandboxExecutionOptions, f as SandboxProjectOptions, g as getSandboxFeatureProvider, h as VercelSandboxProviderOptions, i as SandboxDefinition, l as SandboxDefinitionOptions, m as SandboxRunResult, n as CloudflareSandboxDefinitionProviderOptions, o as SandboxDefinitionFromHandler, p as SandboxProvider, r as CloudflareSandboxOptions, s as SandboxDefinitionHandler, t as AgentSandboxConfig, u as SandboxDefinitionProviderOptions } from "./module-types-Cjqo67ay.js";
2
- import { H3Event } from "h3";
1
+ import { a as SandboxDefinitionBundle, c as SandboxDefinitionInput, d as SandboxExecutionOptions, f as SandboxProjectOptions, g as getSandboxFeatureProvider, h as VercelSandboxProviderOptions, i as SandboxDefinition, l as SandboxDefinitionOptions, m as SandboxRunResult, n as CloudflareSandboxDefinitionProviderOptions, o as SandboxDefinitionFromHandler, p as SandboxProvider, r as CloudflareSandboxOptions, s as SandboxDefinitionHandler, t as AgentSandboxConfig, u as SandboxDefinitionProviderOptions } from "./module-types-DKYItiOu.js";
3
2
  import { ExecutionAuthority } from "@vite-hub/runtime";
4
3
  import { SandboxDefinitionModules } from "#vitehub-sandbox-registry";
5
4
 
@@ -9,7 +8,12 @@ declare function defineSandbox<THandler extends (...args: any[]) => any>(input:
9
8
  }): SandboxDefinitionFromHandler<THandler>;
10
9
  //#endregion
11
10
  //#region src/internal/shared/request-payload.d.ts
12
- declare function readRequestPayload<TPayload = Record<string, never>>(event: H3Event, fallback?: TPayload): Promise<TPayload | unknown>;
11
+ interface RequestPayloadEvent {
12
+ req: {
13
+ json: () => Promise<unknown>;
14
+ };
15
+ }
16
+ declare function readRequestPayload(event: RequestPayloadEvent, fallback?: unknown): Promise<unknown>;
13
17
  //#endregion
14
18
  //#region src/internal/shared/validation.d.ts
15
19
  interface ValidationIssue {
@@ -62,4 +66,4 @@ declare function resolveSandboxRunner<TPayload = unknown, TResult = unknown>(nam
62
66
  run: (payload?: TPayload, options?: SandboxExecutionOptions) => Promise<TResult>;
63
67
  }>;
64
68
  //#endregion
65
- export { type AgentSandboxConfig, type CloudflareSandboxDefinitionProviderOptions, type CloudflareSandboxOptions, type SandboxDefinition, type SandboxDefinitionBundle, type SandboxDefinitionFromHandler, type SandboxDefinitionHandler, type SandboxDefinitionInput, type SandboxDefinitionOptions, type SandboxDefinitionProviderOptions, type SandboxExecutionOptions, type SandboxProjectOptions, type SandboxProvider, type SandboxRunResult, type SandboxRunner, type VercelSandboxProviderOptions, defineSandbox, type getSandboxFeatureProvider, readRequestPayload, readValidatedPayload, resolveSandboxRunner, runSandbox };
69
+ export { type AgentSandboxConfig, type CloudflareSandboxDefinitionProviderOptions, type CloudflareSandboxOptions, type RequestPayloadEvent, type SandboxDefinition, type SandboxDefinitionBundle, type SandboxDefinitionFromHandler, type SandboxDefinitionHandler, type SandboxDefinitionInput, type SandboxDefinitionOptions, type SandboxDefinitionProviderOptions, type SandboxExecutionOptions, type SandboxProjectOptions, type SandboxProvider, type SandboxRunResult, type SandboxRunner, type VercelSandboxProviderOptions, defineSandbox, type getSandboxFeatureProvider, readRequestPayload, readValidatedPayload, resolveSandboxRunner, runSandbox };
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
- import { t as getCloudflareEnv } from "./cloudflare-env-2NctU8i7.js";
1
+ import { t as getCloudflareEnv } from "./cloudflare-env-QQV4uzCT.js";
2
2
  import { getSandboxRuntimeConfig, getSandboxRuntimeRegistry } from "./runtime/state.js";
3
3
  import { t as getSandboxFeatureProvider } from "./module-types-Dj1MFmHT.js";
4
- import { readBody } from "h3";
5
4
  import { ViteHubError, getViteHubErrorShape } from "@vite-hub/runtime";
6
5
  import { upperFirst } from "scule";
7
6
  import { dirname } from "pathe";
@@ -26,12 +25,14 @@ function createSandboxDefinition(functionName, input) {
26
25
  allowedKeys: [
27
26
  "run",
28
27
  "timeout",
29
- "env"
28
+ "env",
29
+ "project"
30
30
  ],
31
- invalidKeysMessage: "supports only portable Sandbox options (run, timeout, env)"
31
+ invalidKeysMessage: "supports only portable Sandbox options (run, timeout, env, project)"
32
32
  });
33
33
  if (!validated) throw new TypeError(`[vitehub] \`${functionName}()\` requires an options object.`);
34
- const { run, ...options } = validated;
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;
35
36
  assertDefinitionHandler(functionName, run, "Sandbox handler in `run`");
36
37
  return {
37
38
  run,
@@ -44,8 +45,7 @@ function defineSandbox(input) {
44
45
  //#endregion
45
46
  //#region src/internal/shared/request-payload.ts
46
47
  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);
48
+ return await event.req.json().catch(() => fallback);
49
49
  }
50
50
  //#endregion
51
51
  //#region src/sandbox/errors.ts
@@ -188,7 +188,7 @@ const CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS = [
188
188
  1e4,
189
189
  15e3
190
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;
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
192
  function collectCloudflareErrorMessages(error, ...extraMessages) {
193
193
  return [
194
194
  error instanceof Error ? error.message : String(error),
@@ -424,12 +424,9 @@ function createEntrySource(definitionPath, execution = "definition") {
424
424
  const invocation = execution === "module" ? [
425
425
  ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
426
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.')`
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)`
433
430
  ] : [
434
431
  ` const mod = await import(pathToFileURL(${JSON.stringify(definitionPath)}).href)`,
435
432
  ` const definition = mod?.default`,
@@ -891,7 +888,7 @@ async function executeLauncher(sandbox, command, args, options) {
891
888
  timeout: options.timeout
892
889
  });
893
890
  }
894
- async function executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, deadline) {
891
+ async function executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, signal, deadline, lifecycle) {
895
892
  const bundle = normalizeSandboxDefinitionBundle(source);
896
893
  const files = createExecutionFiles(definitionName);
897
894
  const throwIfAborted = () => {
@@ -928,6 +925,7 @@ async function executeSandboxDefinitionOnce(sandbox, definitionName, definitionO
928
925
  let outputRaw = "";
929
926
  let execution;
930
927
  try {
928
+ lifecycle?.onHandlerStart?.();
931
929
  execution = await executeLauncher(sandbox, launcher.command, execArgs, {
932
930
  cwd: bundle.project ? resolveSandboxModulePath(bundleBaseDir, bundle.project.packagePath) : files.baseDir,
933
931
  deadline,
@@ -967,14 +965,14 @@ async function executeSandboxDefinitionOnce(sandbox, definitionName, definitionO
967
965
  ]).catch(() => {});
968
966
  }
969
967
  }
970
- async function executeSandboxDefinition(sandbox, definitionName, definitionOptions, source, payload, context) {
968
+ async function executeSandboxDefinition(sandbox, definitionName, definitionOptions, source, payload, context, lifecycle) {
971
969
  const timeout = definitionOptions?.timeout;
972
- if (typeof timeout !== "number" || timeout <= 0) return await executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context);
970
+ if (timeout === void 0 || timeout <= 0) return await executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, void 0, void 0, lifecycle);
973
971
  let timeoutId;
974
972
  const abortController = new AbortController();
975
973
  const deadline = Date.now() + timeout;
976
974
  try {
977
- return await Promise.race([executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, abortController.signal, deadline), new Promise((_, reject) => {
975
+ return await Promise.race([executeSandboxDefinitionOnce(sandbox, definitionName, definitionOptions, source, payload, context, abortController.signal, deadline, lifecycle), new Promise((_, reject) => {
978
976
  timeoutId = setTimeout(() => {
979
977
  const timeoutError = createTimeoutError(sandbox.provider, timeout);
980
978
  abortController.abort(timeoutError);
@@ -1043,6 +1041,7 @@ async function loadSandboxProviderRuntime(provider) {
1043
1041
  //#endregion
1044
1042
  //#region src/runtime/provider-resolution.ts
1045
1043
  const allowedDefinitionKeys = new Set(["timeout", "env"]);
1044
+ const maxTimeout = 2147483647;
1046
1045
  const detectProvider = createProviderDetector([{
1047
1046
  provider: "cloudflare",
1048
1047
  when: isCloudflare
@@ -1071,8 +1070,8 @@ function hashCloudflareSandboxName(name) {
1071
1070
  function createCloudflareExecutionSandboxId(name, sandboxId) {
1072
1071
  if (sandboxId) return sandboxId;
1073
1072
  const prefix = "vitehub-";
1074
- const suffix = `-${hashCloudflareSandboxName(name)}-definition`;
1075
- return `${prefix}${encodeURIComponent(name).slice(0, 248 - suffix.length)}${suffix}`;
1073
+ const suffix = `-${hashCloudflareSandboxName(name)}-${crypto.randomUUID()}`;
1074
+ return `${prefix}${encodeURIComponent(name).slice(0, 55 - suffix.length)}${suffix}`;
1076
1075
  }
1077
1076
  function resolveRuntimeProvider(provider, event) {
1078
1077
  if (provider?.provider) return provider.provider;
@@ -1086,6 +1085,7 @@ function resolveRuntimeProvider(provider, event) {
1086
1085
  function assertSandboxDefinitionOptions(local) {
1087
1086
  const invalidKeys = Object.keys(local).filter((key) => !allowedDefinitionKeys.has(key));
1088
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
1089
  }
1090
1090
  async function resolveSandboxBox(provider, providerOptions, local, context) {
1091
1091
  return await (await loadSandboxProviderRuntime(provider)).resolveSandboxBox({
@@ -1131,6 +1131,7 @@ function isRetriableCloudflareSandboxError(error) {
1131
1131
  const metadata = readSandboxErrorMetadata(error);
1132
1132
  const provider = metadata?.provider;
1133
1133
  if (provider && provider !== "cloudflare") return false;
1134
+ if (metadata?.code === "SANDBOX_TIMEOUT") return false;
1134
1135
  const extraMessage = metadata?.cause instanceof Error ? metadata.cause.message : "";
1135
1136
  return CLOUDFLARE_RETRIABLE_STARTUP_ERROR_RE.test(collectCloudflareErrorMessages(error, extraMessage));
1136
1137
  }
@@ -1168,15 +1169,25 @@ const sandboxRuntime = createResourceRuntime({
1168
1169
  return await serializeCloudflareRun(cloudflareSandboxId, async () => {
1169
1170
  for (let attempt = 0; attempt < attempts; attempt++) {
1170
1171
  let sandbox;
1172
+ let handlerMayHaveStarted = false;
1173
+ let runError;
1171
1174
  try {
1172
1175
  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);
1176
+ return await executeSandboxDefinition(sandbox, context.name, context.definition.options, context.definition.bundle, payload, options.context, { onHandlerStart() {
1177
+ handlerMayHaveStarted = true;
1178
+ } });
1174
1179
  } catch (error) {
1175
1180
  const sandboxError = toSandboxError(error);
1176
- if (!(provider.provider === "cloudflare" && attempt < CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length && isRetriableCloudflareSandboxError(sandboxError))) throw sandboxError;
1181
+ runError = sandboxError;
1182
+ if (!(!handlerMayHaveStarted && provider.provider === "cloudflare" && attempt < CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS.length && isRetriableCloudflareSandboxError(sandboxError))) throw sandboxError;
1177
1183
  await sleep(CLOUDFLARE_SANDBOX_RETRY_DELAYS_MS[attempt]);
1178
1184
  } finally {
1179
- if (provider.closeAfterRun !== false) await sandbox?.close().catch(() => {});
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
+ }
1180
1191
  }
1181
1192
  }
1182
1193
  throw sandboxError("Cloudflare sandbox retries exhausted.", {
@@ -1,5 +1,5 @@
1
1
  import { ViteHubError } from "@vite-hub/runtime";
2
- import { VercelBoxNetworkPolicy, VercelBoxSource } from "@vite-hub/box/vercel";
2
+ import { VercelBoxNetworkPolicy, VercelBoxSource } from "@vite-hub/box";
3
3
 
4
4
  //#region src/project.d.ts
5
5
  type SandboxPackageManager = 'bun' | 'npm' | 'pnpm' | 'yarn';
@@ -76,6 +76,8 @@ interface SandboxProjectOptions {
76
76
  timeout?: number;
77
77
  }
78
78
  interface SandboxDefinitionInput<TPayload = unknown, TResult = unknown> extends SandboxDefinitionOptions {
79
+ /** Force project packaging on or off. Omit to detect project use automatically. */
80
+ project?: boolean;
79
81
  run: SandboxDefinitionHandler<TPayload, TResult>;
80
82
  }
81
83
  interface SandboxDefinition<TPayload = unknown, TResult = unknown> {
@@ -1,4 +1,4 @@
1
- import { l as SandboxDefinitionOptions, p as SandboxProvider, u as SandboxDefinitionProviderOptions } from "./module-types-Cjqo67ay.js";
1
+ import { l as SandboxDefinitionOptions, p as SandboxProvider, u as SandboxDefinitionProviderOptions } from "./module-types-DKYItiOu.js";
2
2
  import { Box } from "@vite-hub/box";
3
3
 
4
4
  //#region src/runtime/provider-loader.d.ts
@@ -1,2 +1,2 @@
1
- import { n as SandboxRuntimeProvider, r as loadSandboxRuntimeProvider, t as ResolvedSandboxBox } from "../provider-loader-3ml65ZFy.js";
1
+ import { n as SandboxRuntimeProvider, r as loadSandboxRuntimeProvider, t as ResolvedSandboxBox } from "../provider-loader-D0UihePq.js";
2
2
  export { ResolvedSandboxBox, SandboxRuntimeProvider, loadSandboxRuntimeProvider };
@@ -2,12 +2,12 @@
2
2
  const dynamicImport = new Function("specifier", "return import(specifier)");
3
3
  async function loadSandboxRuntimeProvider(provider) {
4
4
  if (provider === "cloudflare") {
5
- const { resolveSandboxBox } = await dynamicImport("./providers/cloudflare.js");
6
- return { resolveSandboxBox };
5
+ const { resolveCloudflareSandboxBox } = await dynamicImport("./providers/cloudflare.js");
6
+ return { resolveSandboxBox: resolveCloudflareSandboxBox };
7
7
  }
8
8
  if (provider === "vercel") {
9
- const { resolveSandboxBox } = await dynamicImport("./providers/vercel.js");
10
- return { resolveSandboxBox };
9
+ const { resolveVercelSandboxBox } = await dynamicImport("./providers/vercel.js");
10
+ return { resolveSandboxBox: resolveVercelSandboxBox };
11
11
  }
12
12
  throw new Error(`[vitehub] Unsupported sandbox provider: ${provider}`);
13
13
  }
@@ -1,5 +1,4 @@
1
- import { l as SandboxDefinitionOptions, n as CloudflareSandboxDefinitionProviderOptions } from "../../module-types-Cjqo67ay.js";
2
- import { t as Box } from "../../index-DiH4OGAU.js";
1
+ import { l as SandboxDefinitionOptions, n as CloudflareSandboxDefinitionProviderOptions } from "../../module-types-DKYItiOu.js";
3
2
 
4
3
  //#region src/runtime/providers/cloudflare.d.ts
5
4
  type SandboxOptions = {
@@ -18,13 +17,13 @@ type SandboxEvent = {
18
17
  };
19
18
  };
20
19
  };
21
- declare function resolveSandboxBox(options: SandboxOptions, context?: {
20
+ declare function resolveCloudflareSandboxBox(options: SandboxOptions, context?: {
22
21
  event?: SandboxEvent;
23
22
  }): Promise<{
24
23
  closeAfterRun: boolean;
25
24
  provider: "cloudflare";
26
25
  sandboxId: string | undefined;
27
- resolveBox: (requirements: readonly string[]) => Promise<Box>;
26
+ resolveBox: (requirements: readonly string[]) => Promise<import("@vite-hub/box").Box>;
28
27
  }>;
29
28
  //#endregion
30
- export { resolveSandboxBox };
29
+ export { resolveCloudflareSandboxBox };