@vite-hub/sandbox 0.1.0 → 0.3.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 (54) hide show
  1. package/README.md +118 -53
  2. package/dist/abortable-CR01hzfi.js +57 -0
  3. package/dist/cloudflare-Cog_r2Me.js +910 -0
  4. package/dist/cloudflare-env-lookup-DzI6Xv1Y.js +16 -0
  5. package/dist/cloudflare-failure-CFQhalfh.js +50 -0
  6. package/dist/container-CqfD8yuE.js +868 -0
  7. package/dist/{crabbox-BFCdf41h.js → crabbox-sbV3Zjuo.js} +10 -6
  8. package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
  9. package/dist/error-diagnostics-BJtLRL9w.js +536 -0
  10. package/dist/{file-listing-DECFTdSl.js → file-listing-CHtRrfo1.js} +1 -1
  11. package/dist/{file-lock-CxyVl4Cv.js → file-lock-D0-XPogS.js} +3 -2
  12. package/dist/{index-CXej1Bt0.d.ts → index-DsoQAUb7.d.ts} +94 -19
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +15 -10
  15. package/dist/internal/cloudflare.d.ts +173 -1
  16. package/dist/internal/cloudflare.js +4 -12
  17. package/dist/internal/host-toolchain.d.ts +1 -1
  18. package/dist/internal/host-toolchain.js +6 -7
  19. package/dist/internal/vercel.d.ts +1 -1
  20. package/dist/internal/vercel.js +3 -11
  21. package/dist/invariant-DolT9EEx.js +22 -0
  22. package/dist/module-types-B0LQ5H2S.js +7 -0
  23. package/dist/module-types-DCeJbS9Z.d.ts +110 -0
  24. package/dist/process-sweep-CMaujWE5.js +33 -0
  25. package/dist/provider-resolution-C6AQzuFG.js +133 -0
  26. package/dist/{remote-1Jz2oUMK.js → remote-70ZVZZlq.js} +32 -14
  27. package/dist/runtime-type-Deo4qzxN.js +9 -0
  28. package/dist/{session-DD0S1PDC.js → session-e0lyzjJ3.js} +2 -1
  29. package/dist/size-7AkVwGZb.js +118 -0
  30. package/dist/ssh.d.ts +8 -0
  31. package/dist/ssh.js +107 -40
  32. package/dist/task/index.d.ts +19 -17
  33. package/dist/task/index.js +92 -201
  34. package/dist/task/runtime/provider-loader.d.ts +7 -9
  35. package/dist/task/runtime/provider-loader.js +2 -5
  36. package/dist/task/runtime/providers/cloudflare.d.ts +5 -19
  37. package/dist/task/runtime/providers/cloudflare.js +7 -6
  38. package/dist/task/runtime/providers/vercel.d.ts +3 -3
  39. package/dist/task/runtime/providers/vercel.js +35 -4
  40. package/dist/task/runtime/state.d.ts +4 -1
  41. package/dist/task/runtime/state.js +11 -2
  42. package/dist/task/vite.d.ts +143 -17
  43. package/dist/task/vite.js +723 -400
  44. package/dist/{toolchain-BUVXtQ2m.js → toolchain-BIVGMRty.js} +12 -11
  45. package/dist/{trusted-host-DNMJ-Oig.js → trusted-host-kxkpaQcs.js} +21 -179
  46. package/dist/{vercel-Jtxa9TJx.js → vercel-BGGrNpza.js} +107 -34
  47. package/package.json +15 -12
  48. package/dist/cloudflare-DO0h3Ncf.js +0 -281
  49. package/dist/cloudflare-env-BBJaBbuQ.js +0 -39
  50. package/dist/error-diagnostics-BSysPv-D.js +0 -166
  51. package/dist/error-diagnostics-dGQqfgLt.js +0 -99
  52. package/dist/module-types-BfyRBaiP.js +0 -7
  53. package/dist/module-types-Cis4hrF1.d.ts +0 -95
  54. package/dist/runtime-type-DrmrW5m5.js +0 -42
@@ -0,0 +1,110 @@
1
+ import { Q as VercelSandboxSource, X as VercelSandboxNetworkPolicy, st as SandboxNetworkPolicy } from "./index-DsoQAUb7.js";
2
+ //#region src/task/project.d.ts
3
+ type SandboxTaskPackageManager = 'bun' | 'npm' | 'pnpm' | 'yarn';
4
+ interface SandboxTaskProjectFile {
5
+ contents: string;
6
+ encoding: 'base64';
7
+ mode?: number;
8
+ }
9
+ interface SandboxTaskProject {
10
+ digest: string;
11
+ files: Record<string, SandboxTaskProjectFile>;
12
+ install: {
13
+ args: string[];
14
+ command: SandboxTaskPackageManager;
15
+ cwd: string;
16
+ };
17
+ options?: SandboxTaskProjectOptions;
18
+ packagePath: string;
19
+ }
20
+ //#endregion
21
+ //#region src/task/size.d.ts
22
+ /** The size of the machine that runs every Sandbox Task. Both values are minimums. */
23
+ interface SandboxTaskSizeOptions {
24
+ /** Minimum vCPUs. ViteHub picks the smallest provider size that gives at least this many. */
25
+ cpu?: number;
26
+ /** Minimum memory in MiB. ViteHub picks the smallest provider size that gives at least this much. */
27
+ memory?: number;
28
+ }
29
+ //#endregion
30
+ //#region src/task/module-types.d.ts
31
+ type SandboxTaskDriver = 'cloudflare' | 'vercel';
32
+ interface CloudflareSandboxTaskOptions {
33
+ sleepAfter?: string | number;
34
+ keepAlive?: boolean;
35
+ normalizeId?: boolean;
36
+ }
37
+ interface VercelSandboxTaskDriverOptions extends SandboxTaskSizeOptions {
38
+ driver: 'vercel';
39
+ runtime?: string;
40
+ ports?: number[];
41
+ source?: VercelSandboxSource;
42
+ /** `"allow-all"` (default), `"deny-all"`, or `{ allow: hostnames }`. Vercel also takes `subnets`. */
43
+ networkPolicy?: VercelSandboxNetworkPolicy;
44
+ token?: string;
45
+ teamId?: string;
46
+ projectId?: string;
47
+ }
48
+ interface CloudflareSandboxTaskDefinitionDriverOptions extends SandboxTaskSizeOptions {
49
+ driver: 'cloudflare';
50
+ /** Maximum number of Containers that run at once. Defaults to 12. */
51
+ maxInstances?: number;
52
+ binding?: string;
53
+ className?: string;
54
+ migrationTag?: string;
55
+ name?: string;
56
+ sandboxId?: string;
57
+ sleepAfter?: CloudflareSandboxTaskOptions['sleepAfter'];
58
+ keepAlive?: CloudflareSandboxTaskOptions['keepAlive'];
59
+ normalizeId?: CloudflareSandboxTaskOptions['normalizeId'];
60
+ /** `"allow-all"` (default), `"deny-all"`, or `{ allow: hostnames }`. Applies when the Container starts. */
61
+ networkPolicy?: SandboxNetworkPolicy;
62
+ }
63
+ type SandboxTaskDefinitionDriverOptions = VercelSandboxTaskDriverOptions | CloudflareSandboxTaskDefinitionDriverOptions;
64
+ type AgentSandboxTaskConfig = SandboxTaskDefinitionDriverOptions | ({
65
+ driver?: undefined;
66
+ name?: string;
67
+ } & SandboxTaskSizeOptions);
68
+ interface SandboxTaskDefinitionBundle {
69
+ entry: string;
70
+ execution?: 'definition' | 'module';
71
+ modules: Record<string, string>;
72
+ project?: SandboxTaskProject;
73
+ }
74
+ interface SandboxTaskExecutionOptions {
75
+ /** Passed to the handler; defaults to an empty object. */
76
+ context?: Record<string, unknown>;
77
+ /** Abort this invocation and propagate the caller's abort reason. */
78
+ signal?: AbortSignal;
79
+ sandboxId?: string;
80
+ }
81
+ type SandboxTaskRunArguments<TPayload> = undefined extends TPayload ? [payload?: TPayload, options?: SandboxTaskExecutionOptions] : [payload: TPayload, options?: SandboxTaskExecutionOptions];
82
+ /** The handler of a Sandbox Task. The runtime calls it with the payload of the run and the run context. */
83
+ type SandboxTaskDefinitionHandler<TPayload = unknown, TResult = unknown> = (payload: TPayload, context: Record<string, unknown>) => TResult | Promise<TResult>;
84
+ type SandboxTaskDefinitionPayload<THandler extends (...args: any[]) => any> = Parameters<THandler> extends [infer TPayload, ...unknown[]] ? TPayload : unknown;
85
+ type SandboxTaskDefinitionResult<THandler extends (...args: any[]) => any> = Awaited<ReturnType<THandler>>;
86
+ interface SandboxTaskDefinitionOptions {
87
+ timeout?: number;
88
+ env?: Record<string, string>;
89
+ }
90
+ interface SandboxTaskProjectOptions {
91
+ timeout?: number;
92
+ }
93
+ interface SandboxTaskDefinitionInput<TPayload = unknown, TResult = unknown> extends SandboxTaskDefinitionOptions {
94
+ /** Force project packaging on or off. Omit to detect project use automatically. */
95
+ project?: boolean;
96
+ handler: SandboxTaskDefinitionHandler<TPayload, TResult>;
97
+ }
98
+ interface SandboxTaskDefinition<TPayload = unknown, TResult = unknown> {
99
+ handler: SandboxTaskDefinitionHandler<TPayload, TResult>;
100
+ options?: SandboxTaskDefinitionOptions;
101
+ }
102
+ type SandboxTaskDefinitionFromHandler<THandler extends (...args: any[]) => any> = SandboxTaskDefinition<SandboxTaskDefinitionPayload<THandler>, SandboxTaskDefinitionResult<THandler>> & {
103
+ handler: THandler;
104
+ };
105
+ /** The result of a sandbox invocation. HTTP semantics are used for both
106
+ * successful values and failures. */
107
+ type SandboxTaskRunResult = Response;
108
+ declare function getSandboxTaskFeatureDriver(config?: AgentSandboxTaskConfig | false): SandboxTaskDefinitionDriverOptions | undefined;
109
+ //#endregion
110
+ export { getSandboxTaskFeatureDriver as _, SandboxTaskDefinitionBundle as a, SandboxTaskDefinitionHandler as c, SandboxTaskDriver as d, SandboxTaskExecutionOptions as f, VercelSandboxTaskDriverOptions as g, SandboxTaskRunResult as h, SandboxTaskDefinition as i, SandboxTaskDefinitionInput as l, SandboxTaskRunArguments as m, CloudflareSandboxTaskDefinitionDriverOptions as n, SandboxTaskDefinitionDriverOptions as o, SandboxTaskProjectOptions as p, CloudflareSandboxTaskOptions as r, SandboxTaskDefinitionFromHandler as s, AgentSandboxTaskConfig as t, SandboxTaskDefinitionOptions as u, SandboxTaskSizeOptions as v };
@@ -0,0 +1,33 @@
1
+ import { readFile, readdir } from "node:fs/promises";
2
+ import { setTimeout } from "node:timers/promises";
3
+ //#region ../internal/src/process-sweep.ts
4
+ const maxRounds = 10;
5
+ /**
6
+ * Stops every process of this user that started with `name=value` in its environment: SIGTERM, then
7
+ * SIGKILL after `graceMs`. It repeats while marked processes remain, because a dying process can start
8
+ * another one. Does nothing outside Linux.
9
+ */
10
+ async function stopMarkedProcesses(name, value, options = {}) {
11
+ if (process.platform !== "linux") return;
12
+ const marker = `\0${name}=${value}\0`;
13
+ for (let round = 0; round < maxRounds; round++) {
14
+ const marked = await markedProcesses(marker);
15
+ if (!marked.length) return;
16
+ for (const pid of marked) signal(pid, "SIGTERM");
17
+ await setTimeout(options.graceMs ?? 250);
18
+ for (const pid of await markedProcesses(marker)) signal(pid, "SIGKILL");
19
+ await setTimeout(10);
20
+ }
21
+ }
22
+ async function markedProcesses(marker) {
23
+ const pids = (await readdir("/proc")).filter((entry) => /^\d+$/.test(entry)).map(Number).filter((pid) => pid !== process.pid);
24
+ const environments = await Promise.all(pids.map((pid) => readFile(`/proc/${pid}/environ`, "latin1").catch(() => "")));
25
+ return pids.filter((_, index) => `\0${environments[index]}`.includes(marker));
26
+ }
27
+ function signal(pid, name) {
28
+ try {
29
+ process.kill(pid, name);
30
+ } catch {}
31
+ }
32
+ //#endregion
33
+ export { stopMarkedProcesses as t };
@@ -0,0 +1,133 @@
1
+ import { t as sandboxTaskErrorDiagnostics } from "./error-diagnostics-5QT_BjbQ.js";
2
+ import { t as getActiveCloudflareEnv } from "./cloudflare-env-lookup-DzI6Xv1Y.js";
3
+ import { ViteHubError, getViteHubErrorShape } from "@vite-hub/runtime";
4
+ //#region src/task/sandbox-task/errors.ts
5
+ function sanitizeSandboxTaskDetail(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
6
+ if (value === null || typeof value === "boolean") return value;
7
+ if (typeof value === "string") return value.slice(0, 16384);
8
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
9
+ if (!value || typeof value !== "object" || depth >= 8 || seen.has(value)) return void 0;
10
+ seen.add(value);
11
+ try {
12
+ if (Array.isArray(value)) return value.slice(0, 128).flatMap((item) => {
13
+ const sanitized = sanitizeSandboxTaskDetail(item, depth + 1, seen);
14
+ return sanitized === void 0 ? [] : [sanitized];
15
+ });
16
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return void 0;
17
+ const result = {};
18
+ for (const [key, item] of Object.entries(value).slice(0, 128)) {
19
+ if (!key || key.length > 128) continue;
20
+ result[key] = sanitizeSandboxTaskDetail(item, depth + 1, seen);
21
+ }
22
+ return result;
23
+ } catch {
24
+ return;
25
+ } finally {
26
+ seen.delete(value);
27
+ }
28
+ }
29
+ function sanitizeSandboxTaskDetails(details) {
30
+ const sanitized = sanitizeSandboxTaskDetail(details);
31
+ return sanitized && !Array.isArray(sanitized) && typeof sanitized === "object" ? sanitized : void 0;
32
+ }
33
+ function sandboxTaskError(message, metadata = {}) {
34
+ const { cause, code = "SANDBOX_TASK_RUNTIME_ERROR", details, httpStatus, method, provider } = metadata;
35
+ return new ViteHubError(code, message.slice(0, 16384) || "Sandbox execution failed.", {
36
+ cause,
37
+ details: sanitizeSandboxTaskDetails({
38
+ ...provider === void 0 ? {} : { provider },
39
+ ...method === void 0 ? {} : { method },
40
+ ...httpStatus === void 0 ? {} : { httpStatus },
41
+ ...sanitizeSandboxTaskDetails(details)
42
+ })
43
+ });
44
+ }
45
+ function isSandboxTaskError(value) {
46
+ return getViteHubErrorShape(value)?.code.startsWith("SANDBOX_TASK_") === true;
47
+ }
48
+ //#endregion
49
+ //#region src/task/internal/shared/provider-detection.ts
50
+ function createProviderDetector(rules) {
51
+ return () => {
52
+ for (const rule of rules) if (rule.when()) return rule.provider;
53
+ };
54
+ }
55
+ function getRuntimeEnv() {
56
+ return typeof process !== "undefined" ? process.env : {};
57
+ }
58
+ const isCloudflare = () => {
59
+ const env = getRuntimeEnv();
60
+ return !!(env.CLOUDFLARE_WORKER || env.CF_PAGES);
61
+ };
62
+ const isVercel = () => {
63
+ const env = getRuntimeEnv();
64
+ return !!(env.VERCEL || env.VERCEL_ENV);
65
+ };
66
+ //#endregion
67
+ //#region src/task/runtime/provider-resolution.ts
68
+ const allowedDefinitionKeys = /* @__PURE__ */ new Set(["timeout", "env"]);
69
+ const maxTimeout = 2147483647;
70
+ /** The timeout of a Sandbox Task run that sets no `timeout`, on every provider. */
71
+ const DEFAULT_SANDBOX_TASK_TIMEOUT_MS = 3e5;
72
+ const detectProvider = createProviderDetector([{
73
+ provider: "cloudflare",
74
+ when: isCloudflare
75
+ }, {
76
+ provider: "vercel",
77
+ when: isVercel
78
+ }]);
79
+ function detectSandbox() {
80
+ const env = typeof process !== "undefined" ? process.env : {};
81
+ const type = detectProvider() || "none";
82
+ if (type === "cloudflare") return {
83
+ type,
84
+ details: { runtime: typeof process === "undefined" ? "workerd" : "node" }
85
+ };
86
+ if (type === "vercel") return {
87
+ type,
88
+ details: { env: env.VERCEL_ENV }
89
+ };
90
+ return { type };
91
+ }
92
+ function hashCloudflareSandboxName(name) {
93
+ let hash = 2166136261;
94
+ for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), 16777619);
95
+ return (hash >>> 0).toString(36);
96
+ }
97
+ function createCloudflareExecutionSandboxId(name, sandboxId) {
98
+ if (sandboxId) return sandboxId;
99
+ const prefix = "vitehub-";
100
+ const suffix = `-${hashCloudflareSandboxName(name)}-${crypto.randomUUID()}`;
101
+ return `${prefix}${encodeURIComponent(name).slice(0, 55 - suffix.length)}${suffix}`;
102
+ }
103
+ function resolveRuntimeProvider(options) {
104
+ if (options?.driver) return options.driver;
105
+ const envProvider = typeof process !== "undefined" ? process.env?.SANDBOX_PROVIDER : void 0;
106
+ if (envProvider === "cloudflare" || envProvider === "vercel") return envProvider;
107
+ if (getActiveCloudflareEnv()) return "cloudflare";
108
+ const detected = detectSandbox();
109
+ if (detected.type === "cloudflare" || detected.type === "vercel") return detected.type;
110
+ throw sandboxTaskError("Sandbox provider could not be inferred. Configure `sandboxTask.driver` as `cloudflare` or `vercel`.", { code: "SANDBOX_TASK_PROVIDER_REQUIRED" });
111
+ }
112
+ function unsupportedHostedSandboxTaskProviderError(provider) {
113
+ return sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0076({ message: `[vitehub] Unsupported sandbox provider for this hosted build: ${String(provider)}` });
114
+ }
115
+ function assertSandboxTaskDefinitionOptions(local) {
116
+ const invalidKeys = Object.keys(local).filter((key) => !allowedDefinitionKeys.has(key));
117
+ if (invalidKeys.length > 0) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0069({ message: `[vitehub] Sandbox Task Definition options only support timeout and env. Unsupported: ${invalidKeys.join(", ")}` });
118
+ if (local.timeout !== void 0 && (!Number.isInteger(local.timeout) || local.timeout <= 0 || local.timeout > maxTimeout)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_R0070({ message: `[vitehub] Sandbox Task Definition timeout must be a positive integer no greater than ${maxTimeout}.` });
119
+ }
120
+ async function resolveTaskSandbox(provider, providerOptions, local) {
121
+ return await (await (await import("#vitehub-sandbox-task-provider-loader")).loadSandboxTaskRuntimeProvider(provider)).resolveTaskSandbox({
122
+ local,
123
+ provider: providerOptions
124
+ });
125
+ }
126
+ function withSandboxTaskProvider(provider, options) {
127
+ return {
128
+ ...options,
129
+ driver: provider
130
+ };
131
+ }
132
+ //#endregion
133
+ export { resolveTaskSandbox as a, isSandboxTaskError as c, resolveRuntimeProvider as i, sandboxTaskError as l, assertSandboxTaskDefinitionOptions as n, unsupportedHostedSandboxTaskProviderError as o, createCloudflareExecutionSandboxId as r, withSandboxTaskProvider as s, DEFAULT_SANDBOX_TASK_TIMEOUT_MS as t };
@@ -1,6 +1,6 @@
1
- import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
1
+ import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
2
2
  import { t as shellQuote } from "./shell-quote-Q3u3plif.js";
3
- import { a as sandboxRequirementSecrets, i as sandboxRequirementPlan, o as sandboxRequirementSignal, r as sandboxRequirementError, s as materializeGitCheckout, t as createSandboxSession } from "./session-DD0S1PDC.js";
3
+ import { a as sandboxRequirementSecrets, i as sandboxRequirementPlan, o as sandboxRequirementSignal, r as sandboxRequirementError, s as materializeGitCheckout, t as createSandboxSession } from "./session-e0lyzjJ3.js";
4
4
  import { normalizeExecutionAuthority } from "@vite-hub/runtime";
5
5
  //#region src/internal/remote.ts
6
6
  async function resolveRemoteSandboxRuntime(runtime, requirements) {
@@ -94,7 +94,7 @@ async function materializeRemotePlan(input, session, options, environment) {
94
94
  const workspace = options.workspace ?? "/workspace";
95
95
  const abortSignal = options.signal;
96
96
  const diagnosticSecrets = [...sandboxRequirementSecrets(Object.keys(input.plan.env).map((name) => environment[name]))];
97
- for (const path of /* @__PURE__ */ new Set([home, ...options.preserveWorkspace ? [] : [workspace]])) if (await session.existsFile({
97
+ for (const path of /* @__PURE__ */ new Set([...options.preserveHome ? [] : [home], ...options.preserveWorkspace ? [] : [workspace]])) if (await session.existsFile({
98
98
  abortSignal,
99
99
  path
100
100
  })) await session.removeFile({
@@ -112,19 +112,31 @@ async function materializeRemotePlan(input, session, options, environment) {
112
112
  path: workspace,
113
113
  recursive: true
114
114
  });
115
- for (const [path, file] of Object.entries(input.plan.files)) {
116
- const content = await file.resolve();
117
- diagnosticSecrets.push(...sandboxRequirementSecrets([content]));
118
- await session.makeDirectory({
115
+ const entries = Object.entries(input.plan.files);
116
+ const directories = /* @__PURE__ */ new Set([home, workspace]);
117
+ const fileConcurrency = 8;
118
+ for (let offset = 0; offset < entries.length; offset += fileConcurrency) {
119
+ const files = [];
120
+ for (const [path, file] of entries.slice(offset, offset + fileConcurrency)) {
121
+ abortSignal?.throwIfAborted();
122
+ const content = await file.resolve();
123
+ diagnosticSecrets.push(...sandboxRequirementSecrets([content]));
124
+ files.push({
125
+ content: Uint8Array.from(content),
126
+ path: joinRemotePath(home, path)
127
+ });
128
+ }
129
+ const missingDirectories = [...new Set(files.map((file) => dirnameRemotePath(file.path)))].filter((path) => !directories.has(path));
130
+ await settleFileOperations(missingDirectories.map((path) => session.makeDirectory({
119
131
  abortSignal,
120
- path: dirnameRemotePath(joinRemotePath(home, path)),
132
+ path,
121
133
  recursive: true
122
- });
123
- await session.writeBinaryFile({
134
+ })), abortSignal);
135
+ for (const path of missingDirectories) directories.add(path);
136
+ await settleFileOperations(files.map((file) => session.writeBinaryFile({
124
137
  abortSignal,
125
- content,
126
- path: joinRemotePath(home, path)
127
- });
138
+ ...file
139
+ })), abortSignal);
128
140
  }
129
141
  if (input.checkout) await materializeGitCheckout(input.checkout, workspace, {
130
142
  abortSignal,
@@ -145,13 +157,19 @@ async function materializeRemotePlan(input, session, options, environment) {
145
157
  }, environment);
146
158
  await validateRequirements(session, input.requirements, workspace, abortSignal, diagnosticSecrets);
147
159
  }
160
+ async function settleFileOperations(operations, signal) {
161
+ const results = await Promise.allSettled(operations);
162
+ signal?.throwIfAborted();
163
+ const failure = results.find((result) => result.status === "rejected");
164
+ if (failure?.status === "rejected") throw failure.reason;
165
+ }
148
166
  /**
149
167
  * Remote Sandboxes do not share a cache. Reuse an exact image node, otherwise upload
150
168
  * the verified toolchain into the Sandbox Home cache for this session.
151
169
  */
152
170
  async function provisionRemoteToolchain(input, session, options, environment) {
153
171
  const { abortSignal, home, workspace } = options;
154
- const { provisionToolchain, readProjectFilesWithShell, verifyToolchain } = await import("./toolchain-BUVXtQ2m.js").then((n) => n.i);
172
+ const { provisionToolchain, readProjectFilesWithShell, verifyToolchain } = await import("./toolchain-BIVGMRty.js").then((n) => n.i);
155
173
  const run = async (script) => await session.run({
156
174
  abortSignal,
157
175
  command: `sh -c ${shellQuote(script)}`,
@@ -0,0 +1,9 @@
1
+ //#region src/internal/runtime-type.ts
2
+ /** Returns a plain JSON-style object, or undefined for primitives, arrays, and functions. */
3
+ function runtimeRecord(value) {
4
+ if (value === null || Object(value) !== value || Array.isArray(value)) return;
5
+ if (Object.prototype.toString.call(value) !== "[object Object]") return;
6
+ return value;
7
+ }
8
+ //#endregion
9
+ export { runtimeRecord as t };
@@ -1,4 +1,4 @@
1
- import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
1
+ import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
2
2
  import { t as shellQuote } from "./shell-quote-Q3u3plif.js";
3
3
  import { posix } from "node:path";
4
4
  //#region src/internal/git-checkout.ts
@@ -276,6 +276,7 @@ function createSandboxSession(runtime, openOptions, cwd = runtime.defaultWorking
276
276
  abortSignal: operationSignal(options?.signal, options?.timeout),
277
277
  command: commandLine(command, args),
278
278
  env: options?.env ? { ...options.env } : void 0,
279
+ stdin: options?.stdin,
279
280
  timeout: options?.timeout,
280
281
  workingDirectory: options?.cwd ?? cwd
281
282
  }));
@@ -0,0 +1,118 @@
1
+ import { t as sandboxTaskErrorDiagnostics } from "./error-diagnostics-5QT_BjbQ.js";
2
+ //#region src/task/size.ts
3
+ const cloudflareInstanceTypes = [
4
+ {
5
+ name: "lite",
6
+ vcpu: 1 / 16,
7
+ memoryMib: 256
8
+ },
9
+ {
10
+ name: "basic",
11
+ vcpu: 1 / 4,
12
+ memoryMib: 1024
13
+ },
14
+ {
15
+ name: "standard-1",
16
+ vcpu: 1 / 2,
17
+ memoryMib: 4096
18
+ },
19
+ {
20
+ name: "standard-2",
21
+ vcpu: 1,
22
+ memoryMib: 6144
23
+ },
24
+ {
25
+ name: "standard-3",
26
+ vcpu: 2,
27
+ memoryMib: 8192
28
+ },
29
+ {
30
+ name: "standard-4",
31
+ vcpu: 4,
32
+ memoryMib: 12288
33
+ }
34
+ ];
35
+ const cloudflareInstanceTypeAliases = {
36
+ dev: "lite",
37
+ standard: "standard-1"
38
+ };
39
+ /** Same memory as the 2 vCPU default of Vercel. `lite` has too little memory for a package install. */
40
+ const defaultCloudflareInstanceType = "standard-1";
41
+ const vercelMemoryPerVcpu = 2048;
42
+ const vercelMaxVcpus = 32;
43
+ function readPositiveNumber(options, key, integer = false) {
44
+ const value = options[key];
45
+ if (value === void 0) return void 0;
46
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || integer && !Number.isInteger(value)) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_SIZE_INVALID({
47
+ key,
48
+ value: String(value)
49
+ });
50
+ return value;
51
+ }
52
+ /** Reads `cpu`, `memory`, and `maxInstances`, and rejects values that are not positive numbers. */
53
+ function readSandboxTaskSize(options) {
54
+ return {
55
+ cpu: readPositiveNumber(options, "cpu"),
56
+ memory: readPositiveNumber(options, "memory"),
57
+ maxInstances: readPositiveNumber(options, "maxInstances", true)
58
+ };
59
+ }
60
+ function formatVcpu(vcpu) {
61
+ return vcpu >= 1 ? String(vcpu) : `1/${Math.round(1 / vcpu)}`;
62
+ }
63
+ /** The vCPUs and memory of a Wrangler instance type. Undefined for a name that ViteHub does not know. */
64
+ function describeCloudflareInstanceType(instanceType) {
65
+ if (typeof instanceType === "object") return {
66
+ label: `custom (${formatVcpu(instanceType.vcpu)} vCPU, ${instanceType.memory_mib} MiB memory)`,
67
+ vcpu: instanceType.vcpu,
68
+ memoryMib: instanceType.memory_mib
69
+ };
70
+ const canonical = cloudflareInstanceTypeAliases[instanceType] ?? instanceType;
71
+ const named = cloudflareInstanceTypes.find((entry) => entry.name === canonical);
72
+ return named && {
73
+ label: `${instanceType} (${formatVcpu(named.vcpu)} vCPU, ${named.memoryMib} MiB memory)`,
74
+ vcpu: named.vcpu,
75
+ memoryMib: named.memoryMib
76
+ };
77
+ }
78
+ /** The smallest Cloudflare instance type that gives at least `cpu` vCPUs and `memory` MiB. */
79
+ function resolveCloudflareSandboxTaskInstanceType(options) {
80
+ const { cpu, memory } = readSandboxTaskSize(options);
81
+ if (cpu === void 0 && memory === void 0) return defaultCloudflareInstanceType;
82
+ const fit = cloudflareInstanceTypes.find((entry) => entry.vcpu >= (cpu ?? 0) && entry.memoryMib >= (memory ?? 0));
83
+ if (!fit) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_SIZE_TOO_LARGE({
84
+ provider: "Cloudflare",
85
+ size: formatRequest(cpu, memory),
86
+ max: "standard-4 (4 vCPU, 12288 MiB memory)"
87
+ });
88
+ return fit.name;
89
+ }
90
+ /** Throws when an app-owned Wrangler instance type gives less than the requested `cpu` or `memory`. */
91
+ function assertCloudflareInstanceTypeFits(instanceType, options, className) {
92
+ const { cpu, memory } = readSandboxTaskSize(options);
93
+ const size = describeCloudflareInstanceType(instanceType);
94
+ if (!size || size.vcpu >= (cpu ?? 0) && size.memoryMib >= (memory ?? 0)) return;
95
+ throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_CLOUDFLARE_INSTANCE_TYPE_TOO_SMALL({
96
+ className,
97
+ instanceType: size.label,
98
+ size: formatRequest(cpu, memory)
99
+ });
100
+ }
101
+ /** The Vercel vCPU count for `cpu` and `memory`: 1 or an even number up to 32. Undefined keeps the Vercel default. */
102
+ function resolveVercelSandboxTaskVcpus(options) {
103
+ const { cpu, memory } = readSandboxTaskSize(options);
104
+ if (cpu === void 0 && memory === void 0) return void 0;
105
+ const needed = Math.max(Math.ceil(cpu ?? 0), Math.ceil((memory ?? 0) / vercelMemoryPerVcpu), 1);
106
+ const vcpus = needed === 1 ? 1 : needed + needed % 2;
107
+ if (vcpus > vercelMaxVcpus) throw sandboxTaskErrorDiagnostics.SANDBOX_TASK_SIZE_TOO_LARGE({
108
+ provider: "Vercel",
109
+ size: formatRequest(cpu, memory),
110
+ max: `${vercelMaxVcpus} vCPU (${vercelMaxVcpus * vercelMemoryPerVcpu} MiB memory)`
111
+ });
112
+ return vcpus;
113
+ }
114
+ function formatRequest(cpu, memory) {
115
+ return [cpu === void 0 ? "" : `cpu: ${cpu}`, memory === void 0 ? "" : `memory: ${memory}`].filter(Boolean).join(", ");
116
+ }
117
+ //#endregion
118
+ export { resolveVercelSandboxTaskVcpus as a, resolveCloudflareSandboxTaskInstanceType as i, describeCloudflareInstanceType as n, readSandboxTaskSize as r, assertCloudflareInstanceTypeFits as t };
package/dist/ssh.d.ts CHANGED
@@ -10,6 +10,11 @@ export interface SshLaunchOptions {
10
10
  hostKeyFile?: string;
11
11
  /** Environment names only. Defaults to the launch context environment and required names. Values travel through SSH env requests. */
12
12
  forwardEnvironment?: readonly string[];
13
+ /**
14
+ * How long, in milliseconds, to connect again while the SSH port refuses connections, for example while a sidecar
15
+ * starts. Other SSH failures are not retried. Defaults to 30000. Set 0 to fail on the first refused connection.
16
+ */
17
+ connectRetryMs?: number;
13
18
  }
14
19
  export interface SshLaunchContext {
15
20
  command: string;
@@ -21,6 +26,9 @@ export interface SshLaunchContext {
21
26
  export declare function sshLaunch(options: SshLaunchOptions): (context: SshLaunchContext) => {
22
27
  command: string;
23
28
  args: string[];
29
+ prepare: (context: {
30
+ abortSignal?: AbortSignal;
31
+ }) => Promise<void>;
24
32
  };
25
33
  export interface SshServerOptions {
26
34
  hostKeyFile: string;