@vite-hub/sandbox 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +388 -22
  3. package/dist/cloudflare-DO0h3Ncf.js +281 -0
  4. package/dist/cloudflare-env-BBJaBbuQ.js +39 -0
  5. package/dist/crabbox-BFCdf41h.js +1106 -0
  6. package/dist/error-diagnostics-BSysPv-D.js +166 -0
  7. package/dist/error-diagnostics-dGQqfgLt.js +99 -0
  8. package/dist/file-listing-DECFTdSl.js +26 -0
  9. package/dist/file-lock-CxyVl4Cv.js +73 -0
  10. package/dist/index-CXej1Bt0.d.ts +519 -0
  11. package/dist/index.d.ts +2 -65
  12. package/dist/index.js +277 -1172
  13. package/dist/internal/cloudflare.d.ts +4 -0
  14. package/dist/internal/cloudflare.js +16 -0
  15. package/dist/internal/host-toolchain.d.ts +22 -0
  16. package/dist/internal/host-toolchain.js +97 -0
  17. package/dist/internal/vercel.d.ts +4 -0
  18. package/dist/internal/vercel.js +16 -0
  19. package/dist/module-types-BfyRBaiP.js +7 -0
  20. package/dist/module-types-Cis4hrF1.d.ts +95 -0
  21. package/dist/remote-1Jz2oUMK.js +247 -0
  22. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  23. package/dist/runtime-DHp6ImeP.js +32 -0
  24. package/dist/runtime-type-DrmrW5m5.js +42 -0
  25. package/dist/session-DD0S1PDC.js +337 -0
  26. package/dist/shell-quote-Q3u3plif.js +6 -0
  27. package/dist/ssh.d.ts +55 -0
  28. package/dist/ssh.js +219 -0
  29. package/dist/task/index.d.ts +67 -0
  30. package/dist/task/index.js +1523 -0
  31. package/dist/task/runtime/empty-registry.d.ts +6 -0
  32. package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
  33. package/dist/task/runtime/provider-loader.d.ts +20 -0
  34. package/dist/task/runtime/provider-loader.js +19 -0
  35. package/dist/task/runtime/providers/cloudflare.d.ts +28 -0
  36. package/dist/task/runtime/providers/cloudflare.js +26 -0
  37. package/dist/task/runtime/providers/vercel.d.ts +12 -0
  38. package/dist/{runtime → task/runtime}/providers/vercel.js +17 -14
  39. package/dist/task/runtime/state.d.ts +24 -0
  40. package/dist/task/runtime/state.js +73 -0
  41. package/dist/task/vite.d.ts +360 -0
  42. package/dist/task/vite.js +3643 -0
  43. package/dist/toolchain-BUVXtQ2m.js +527 -0
  44. package/dist/trusted-host-DNMJ-Oig.js +872 -0
  45. package/dist/vercel-Jtxa9TJx.js +279 -0
  46. package/package.json +103 -39
  47. package/dist/cloudflare-env-2NctU8i7.js +0 -12
  48. package/dist/module-types-DfXe133f.d.ts +0 -91
  49. package/dist/module-types-Dj1MFmHT.js +0 -7
  50. package/dist/provider-loader-hL7uHVWp.d.ts +0 -21
  51. package/dist/runtime/empty-registry.d.ts +0 -6
  52. package/dist/runtime/provider-loader.d.ts +0 -2
  53. package/dist/runtime/provider-loader.js +0 -15
  54. package/dist/runtime/providers/cloudflare.d.ts +0 -29
  55. package/dist/runtime/providers/cloudflare.js +0 -25
  56. package/dist/runtime/providers/vercel.d.ts +0 -112
  57. package/dist/runtime/state.d.ts +0 -17
  58. package/dist/runtime/state.js +0 -21
  59. package/dist/vite.d.ts +0 -24
  60. package/dist/vite.js +0 -2367
@@ -0,0 +1,4 @@
1
+ import { l as Sandbox, tt as CloudflareSandboxOptions } from "../index-CXej1Bt0.js";
2
+ //#region src/internal/cloudflare.d.ts
3
+ export declare function resolveCloudflareSandbox(options: CloudflareSandboxOptions, requirements: readonly string[]): Promise<Sandbox>;
4
+ //#endregion
@@ -0,0 +1,16 @@
1
+ import { a as resolveRemoteSandboxRuntime } from "../remote-1Jz2oUMK.js";
2
+ import { n as createCloudflareRuntime } from "../cloudflare-DO0h3Ncf.js";
3
+ //#region src/internal/cloudflare.ts
4
+ async function resolveCloudflareSandbox(options, requirements) {
5
+ const getSandbox = options.getSandbox ?? await loadCloudflareSandbox();
6
+ return await resolveRemoteSandboxRuntime(createCloudflareRuntime({
7
+ ...options,
8
+ getSandbox
9
+ }), requirements);
10
+ }
11
+ async function loadCloudflareSandbox() {
12
+ const { getSandbox } = await import("@cloudflare/sandbox");
13
+ return getSandbox;
14
+ }
15
+ //#endregion
16
+ export { resolveCloudflareSandbox };
@@ -0,0 +1,22 @@
1
+ import { I as SandboxToolchain, L as SandboxToolchainInput, k as SandboxResolvedToolchain } from "../index-CXej1Bt0.js";
2
+ //#region src/internal/host-toolchain.d.ts
3
+ export interface HostToolchainOptions {
4
+ abortSignal?: AbortSignal;
5
+ /** Shared cache directory. Defaults to `$XDG_CACHE_HOME/vitehub/toolchains`. */
6
+ cacheRoot?: string;
7
+ /** Environment of the install and verification shell. Its PATH follows the toolchain entries. */
8
+ env?: Readonly<Record<string, string | undefined>>;
9
+ }
10
+ /** Default host cache. A configured Sandbox stateRoot keeps toolchains beside durable state. */
11
+ export declare function hostToolchainCacheRoot(stateRoot?: string): string;
12
+ export declare function readHostProjectFiles(directory: string, paths?: readonly string[]): Promise<Record<string, string | undefined>>;
13
+ /**
14
+ * Provision a project-pinned toolchain for a directory on this host.
15
+ * Concurrent processes that share the cache download each version once.
16
+ */
17
+ export declare function provisionHostToolchain(toolchain: SandboxToolchainInput, directory: string, options?: HostToolchainOptions): Promise<SandboxResolvedToolchain>;
18
+ /** PATH with the toolchain entries before the base PATH. */
19
+ export declare function toolchainPath(toolchain: SandboxResolvedToolchain, base: string | undefined): string;
20
+ /** Validate a toolchain declaration and provision it for a host directory. */
21
+ export declare function prepareHostToolchain(declaration: SandboxToolchain, directory: string, options?: HostToolchainOptions): Promise<SandboxResolvedToolchain>;
22
+ //#endregion
@@ -0,0 +1,97 @@
1
+ import { t as sandboxErrorDiagnostics } from "../error-diagnostics-BSysPv-D.js";
2
+ import { n as isRuntimeString, t as isRuntimeNumber } from "../runtime-type-DrmrW5m5.js";
3
+ import { t as acquireFileLock } from "../file-lock-CxyVl4Cv.js";
4
+ import { a as verifyToolchain, n as provisionToolchain, r as toolchainProjectFiles, t as normalizeToolchain } from "../toolchain-BUVXtQ2m.js";
5
+ import { lstat, mkdir, readFile, writeFile } from "node:fs/promises";
6
+ import { delimiter, dirname, join, resolve } from "node:path";
7
+ import { execFile } from "node:child_process";
8
+ import { homedir } from "node:os";
9
+ import { promisify } from "node:util";
10
+ //#region src/internal/host-toolchain.ts
11
+ /** Default host cache. A configured Sandbox stateRoot keeps toolchains beside durable state. */
12
+ function hostToolchainCacheRoot(stateRoot) {
13
+ return stateRoot ? join(stateRoot, "toolchains") : join(process.env.XDG_CACHE_HOME || join(homedir(), ".cache"), "vitehub", "toolchains");
14
+ }
15
+ async function readHostProjectFiles(directory, paths = toolchainProjectFiles) {
16
+ const files = {};
17
+ for (const path of paths) files[path] = await readFile(join(directory, path), "utf8").catch((error) => {
18
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return void 0;
19
+ throw error;
20
+ });
21
+ return files;
22
+ }
23
+ /**
24
+ * Provision a project-pinned toolchain for a directory on this host.
25
+ * Concurrent processes that share the cache download each version once.
26
+ */
27
+ async function provisionHostToolchain(toolchain, directory, options = {}) {
28
+ if (process.platform === "win32") throw sandboxErrorDiagnostics.SANDBOX_R0150({ message: "[vitehub] Sandbox toolchain provisioning requires a Linux or macOS host." });
29
+ const cacheRoot = resolve(options.cacheRoot ?? hostToolchainCacheRoot());
30
+ await mkdir(cacheRoot, {
31
+ mode: 448,
32
+ recursive: true
33
+ });
34
+ const cache = await lstat(cacheRoot);
35
+ const uid = process.getuid?.();
36
+ if (!cache.isDirectory() || uid !== void 0 && cache.uid !== uid || (cache.mode & 18) !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0154({ message: `[vitehub] Sandbox toolchain cache must be a directory owned by the current user and not writable by others: ${cacheRoot}` });
37
+ const env = Object.fromEntries(Object.entries(options.env ?? process.env).filter((entry) => entry[1] !== void 0));
38
+ const run = async (script, environment = env) => {
39
+ try {
40
+ const result = await promisify(execFile)("sh", ["-c", script], {
41
+ cwd: cacheRoot,
42
+ encoding: "utf8",
43
+ env: environment,
44
+ maxBuffer: 16777216,
45
+ signal: options.abortSignal
46
+ });
47
+ return {
48
+ exitCode: 0,
49
+ stderr: result.stderr,
50
+ stdout: result.stdout
51
+ };
52
+ } catch (error) {
53
+ options.abortSignal?.throwIfAborted();
54
+ const code = error instanceof Error && "code" in error ? error.code : void 0;
55
+ if (!isRuntimeNumber(code)) throw error;
56
+ const output = (name) => {
57
+ const value = error instanceof Error && name in error ? Reflect.get(error, name) : void 0;
58
+ return isRuntimeString(value) ? value : "";
59
+ };
60
+ return {
61
+ exitCode: code,
62
+ stderr: output("stderr"),
63
+ stdout: output("stdout")
64
+ };
65
+ }
66
+ };
67
+ const toolchainResult = await provisionToolchain(toolchain, {
68
+ abortSignal: options.abortSignal,
69
+ cacheRoot,
70
+ lock: async (key) => await acquireFileLock(join(cacheRoot, `.${key}.lock`), options.abortSignal),
71
+ readProjectFiles: async (paths) => await readHostProjectFiles(directory, paths),
72
+ run,
73
+ scratch: cacheRoot,
74
+ async write(path, contents) {
75
+ await mkdir(dirname(path), {
76
+ mode: 448,
77
+ recursive: true
78
+ });
79
+ await writeFile(path, contents, { mode: 384 });
80
+ }
81
+ });
82
+ await verifyToolchain(toolchainResult, cacheRoot, async (script) => await run(script, {
83
+ ...env,
84
+ PATH: toolchainPath(toolchainResult, env.PATH)
85
+ }));
86
+ return toolchainResult;
87
+ }
88
+ /** PATH with the toolchain entries before the base PATH. */
89
+ function toolchainPath(toolchain, base) {
90
+ return [...toolchain.bin, base].filter(Boolean).join(delimiter);
91
+ }
92
+ /** Validate a toolchain declaration and provision it for a host directory. */
93
+ async function prepareHostToolchain(declaration, directory, options = {}) {
94
+ return await provisionHostToolchain(normalizeToolchain(declaration), directory, options);
95
+ }
96
+ //#endregion
97
+ export { hostToolchainCacheRoot, prepareHostToolchain, provisionHostToolchain, readHostProjectFiles, toolchainPath };
@@ -0,0 +1,4 @@
1
+ import { X as VercelSandboxOptions, l as Sandbox } from "../index-CXej1Bt0.js";
2
+ //#region src/internal/vercel.d.ts
3
+ export declare function resolveVercelSandbox(options: VercelSandboxOptions, requirements: readonly string[]): Promise<Sandbox>;
4
+ //#endregion
@@ -0,0 +1,16 @@
1
+ import { a as resolveRemoteSandboxRuntime } from "../remote-1Jz2oUMK.js";
2
+ import { t as createVercelRuntime } from "../vercel-Jtxa9TJx.js";
3
+ //#region src/internal/vercel.ts
4
+ async function resolveVercelSandbox(options, requirements) {
5
+ const create = options.create ?? await loadVercelSandbox();
6
+ return await resolveRemoteSandboxRuntime(createVercelRuntime({
7
+ ...options,
8
+ create
9
+ }), requirements);
10
+ }
11
+ async function loadVercelSandbox() {
12
+ const { Sandbox } = await import("@vercel/sandbox");
13
+ return async (createOptions) => await Sandbox.create(createOptions);
14
+ }
15
+ //#endregion
16
+ export { resolveVercelSandbox };
@@ -0,0 +1,7 @@
1
+ //#region src/task/module-types.ts
2
+ function getSandboxTaskFeatureProvider(config) {
3
+ if (!config || typeof config !== "object" || typeof config.provider !== "string") return void 0;
4
+ return config;
5
+ }
6
+ //#endregion
7
+ export { getSandboxTaskFeatureProvider as t };
@@ -0,0 +1,95 @@
1
+ import { Y as VercelSandboxNetworkPolicy, Z as VercelSandboxSource } from "./index-CXej1Bt0.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/module-types.d.ts
22
+ type SandboxTaskProvider = 'cloudflare' | 'vercel';
23
+ interface CloudflareSandboxTaskOptions {
24
+ sleepAfter?: string | number;
25
+ keepAlive?: boolean;
26
+ normalizeId?: boolean;
27
+ }
28
+ interface VercelSandboxTaskProviderOptions {
29
+ provider: 'vercel';
30
+ runtime?: string;
31
+ timeout?: number;
32
+ cpu?: number;
33
+ ports?: number[];
34
+ source?: VercelSandboxSource;
35
+ networkPolicy?: VercelSandboxNetworkPolicy;
36
+ token?: string;
37
+ teamId?: string;
38
+ projectId?: string;
39
+ }
40
+ interface CloudflareSandboxTaskDefinitionProviderOptions {
41
+ provider: 'cloudflare';
42
+ binding?: string;
43
+ className?: string;
44
+ migrationTag?: string;
45
+ name?: string;
46
+ sandboxId?: string;
47
+ sleepAfter?: CloudflareSandboxTaskOptions['sleepAfter'];
48
+ keepAlive?: CloudflareSandboxTaskOptions['keepAlive'];
49
+ normalizeId?: CloudflareSandboxTaskOptions['normalizeId'];
50
+ }
51
+ type SandboxTaskDefinitionProviderOptions = VercelSandboxTaskProviderOptions | CloudflareSandboxTaskDefinitionProviderOptions;
52
+ type AgentSandboxTaskConfig = SandboxTaskDefinitionProviderOptions | {
53
+ provider?: undefined;
54
+ name?: string;
55
+ };
56
+ interface SandboxTaskDefinitionBundle {
57
+ entry: string;
58
+ execution?: 'definition' | 'module';
59
+ modules: Record<string, string>;
60
+ project?: SandboxTaskProject;
61
+ }
62
+ interface SandboxTaskExecutionOptions {
63
+ context?: Record<string, unknown>;
64
+ /** Abort this invocation and propagate the caller's abort reason. */
65
+ signal?: AbortSignal;
66
+ sandboxId?: string;
67
+ }
68
+ type SandboxTaskDefinitionHandler<TPayload = unknown, TResult = unknown> = (payload?: TPayload, context?: Record<string, unknown>) => TResult | Promise<TResult>;
69
+ type SandboxTaskDefinitionPayload<THandler extends (...args: any[]) => any> = Parameters<THandler> extends [infer TPayload, ...unknown[]] ? TPayload : unknown;
70
+ type SandboxTaskDefinitionResult<THandler extends (...args: any[]) => any> = Awaited<ReturnType<THandler>>;
71
+ interface SandboxTaskDefinitionOptions {
72
+ timeout?: number;
73
+ env?: Record<string, string>;
74
+ }
75
+ interface SandboxTaskProjectOptions {
76
+ timeout?: number;
77
+ }
78
+ interface SandboxTaskDefinitionInput<TPayload = unknown, TResult = unknown> extends SandboxTaskDefinitionOptions {
79
+ /** Force project packaging on or off. Omit to detect project use automatically. */
80
+ project?: boolean;
81
+ run: SandboxTaskDefinitionHandler<TPayload, TResult>;
82
+ }
83
+ interface SandboxTaskDefinition<TPayload = unknown, TResult = unknown> {
84
+ run: SandboxTaskDefinitionHandler<TPayload, TResult>;
85
+ options?: SandboxTaskDefinitionOptions;
86
+ }
87
+ type SandboxTaskDefinitionFromHandler<THandler extends (...args: any[]) => any> = SandboxTaskDefinition<SandboxTaskDefinitionPayload<THandler>, SandboxTaskDefinitionResult<THandler>> & {
88
+ run: THandler;
89
+ };
90
+ /** The result of a sandbox invocation. HTTP semantics are used for both
91
+ * successful values and failures. */
92
+ type SandboxTaskRunResult = Response;
93
+ declare function getSandboxTaskFeatureProvider(config?: AgentSandboxTaskConfig | false): SandboxTaskDefinitionProviderOptions | undefined;
94
+ //#endregion
95
+ export { SandboxTaskDefinitionBundle as a, SandboxTaskDefinitionInput as c, SandboxTaskExecutionOptions as d, SandboxTaskProjectOptions as f, getSandboxTaskFeatureProvider as g, VercelSandboxTaskProviderOptions as h, SandboxTaskDefinition as i, SandboxTaskDefinitionOptions as l, SandboxTaskRunResult as m, CloudflareSandboxTaskDefinitionProviderOptions as n, SandboxTaskDefinitionFromHandler as o, SandboxTaskProvider as p, CloudflareSandboxTaskOptions as r, SandboxTaskDefinitionHandler as s, AgentSandboxTaskConfig as t, SandboxTaskDefinitionProviderOptions as u };
@@ -0,0 +1,247 @@
1
+ import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BSysPv-D.js";
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";
4
+ import { normalizeExecutionAuthority } from "@vite-hub/runtime";
5
+ //#region src/internal/remote.ts
6
+ async function resolveRemoteSandboxRuntime(runtime, requirements) {
7
+ const resolvedRequirements = requirements.map((command) => ({
8
+ args: [],
9
+ command,
10
+ name: command
11
+ }));
12
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(resolvedRequirements)));
13
+ const input = {
14
+ identity: Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""),
15
+ plan: {
16
+ env: {},
17
+ files: {},
18
+ state: []
19
+ },
20
+ requirements: resolvedRequirements
21
+ };
22
+ const prepared = await runtime.prepare(input);
23
+ const plan = Object.freeze({
24
+ ...prepared,
25
+ executionAuthority: normalizeExecutionAuthority(prepared.executionAuthority),
26
+ home: Object.freeze({ state: Object.freeze(prepared.home?.state || []) })
27
+ });
28
+ return Object.freeze({
29
+ async open(options) {
30
+ options?.signal?.throwIfAborted();
31
+ return await runtime.open(input, {
32
+ ...options,
33
+ executionAuthority: plan.executionAuthority
34
+ });
35
+ },
36
+ plan
37
+ });
38
+ }
39
+ function remoteSandboxPlan(input, options) {
40
+ assertRemoteInput(input, options.runtime);
41
+ return {
42
+ cache: { state: "disposable" },
43
+ environment: { env: {} },
44
+ executionAuthority: options.executionAuthority,
45
+ identity: input.identity,
46
+ requirements: sandboxRequirementPlan(input.requirements),
47
+ runtime: options.runtime,
48
+ workspace: {
49
+ state: "disposable",
50
+ workDir: "."
51
+ }
52
+ };
53
+ }
54
+ async function openRemoteSandbox(input, runtimeSession, options, environment) {
55
+ assertRemoteInput(input, options.runtime);
56
+ const session = createSandboxSession(runtimeSession, {
57
+ executionAuthority: options.executionAuthority,
58
+ initialize: options.initialize,
59
+ signal: options.signal
60
+ });
61
+ try {
62
+ await materializeRemotePlan(input, runtimeSession, options, environment);
63
+ await options.initialize?.(session, { signal: options.signal });
64
+ return session;
65
+ } catch (error) {
66
+ try {
67
+ await session.close();
68
+ } catch (cleanupError) {
69
+ throw new AggregateError([error, cleanupError], `[vitehub] ${options.runtime} Sandbox initialization failed: ${remoteFailureMessage(error)} Cleanup failed: ${remoteFailureMessage(cleanupError)}`);
70
+ }
71
+ throw error;
72
+ }
73
+ }
74
+ function remoteFailureMessage(error) {
75
+ return error instanceof Error ? error.message || error.name : String(error);
76
+ }
77
+ async function resolveRemoteEnvironment(input, options) {
78
+ const home = options.home ?? "/home/vitehub";
79
+ const workspace = options.workspace ?? "/workspace";
80
+ const env = {
81
+ HOME: home,
82
+ INIT_CWD: workspace,
83
+ OLDPWD: workspace,
84
+ PWD: workspace,
85
+ XDG_CACHE_HOME: joinRemotePath(home, ".cache"),
86
+ XDG_CONFIG_HOME: joinRemotePath(home, ".config"),
87
+ XDG_STATE_HOME: joinRemotePath(home, ".local/state")
88
+ };
89
+ for (const [name, resolveValue] of Object.entries(input.plan.env)) env[name] = await resolveValue();
90
+ return env;
91
+ }
92
+ async function materializeRemotePlan(input, session, options, environment) {
93
+ const home = options.home ?? "/home/vitehub";
94
+ const workspace = options.workspace ?? "/workspace";
95
+ const abortSignal = options.signal;
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({
98
+ abortSignal,
99
+ path
100
+ })) await session.removeFile({
101
+ abortSignal,
102
+ path,
103
+ recursive: true
104
+ });
105
+ await session.makeDirectory({
106
+ abortSignal,
107
+ path: home,
108
+ recursive: true
109
+ });
110
+ await session.makeDirectory({
111
+ abortSignal,
112
+ path: workspace,
113
+ recursive: true
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({
119
+ abortSignal,
120
+ path: dirnameRemotePath(joinRemotePath(home, path)),
121
+ recursive: true
122
+ });
123
+ await session.writeBinaryFile({
124
+ abortSignal,
125
+ content,
126
+ path: joinRemotePath(home, path)
127
+ });
128
+ }
129
+ if (input.checkout) await materializeGitCheckout(input.checkout, workspace, {
130
+ abortSignal,
131
+ async run(args) {
132
+ const result = await session.run({
133
+ abortSignal,
134
+ command: ["git", ...args.map(shellQuote)].join(" "),
135
+ workingDirectory: workspace
136
+ });
137
+ if (result.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0121({ message: result.stderr });
138
+ return { stdout: result.stdout };
139
+ }
140
+ });
141
+ if (input.toolchain) await provisionRemoteToolchain(input, session, {
142
+ abortSignal,
143
+ home,
144
+ workspace
145
+ }, environment);
146
+ await validateRequirements(session, input.requirements, workspace, abortSignal, diagnosticSecrets);
147
+ }
148
+ /**
149
+ * Remote Sandboxes do not share a cache. Reuse an exact image node, otherwise upload
150
+ * the verified toolchain into the Sandbox Home cache for this session.
151
+ */
152
+ async function provisionRemoteToolchain(input, session, options, environment) {
153
+ const { abortSignal, home, workspace } = options;
154
+ const { provisionToolchain, readProjectFilesWithShell, verifyToolchain } = await import("./toolchain-BUVXtQ2m.js").then((n) => n.i);
155
+ const run = async (script) => await session.run({
156
+ abortSignal,
157
+ command: `sh -c ${shellQuote(script)}`,
158
+ workingDirectory: workspace
159
+ });
160
+ const basePath = await run(`printf '%s' "$PATH"`);
161
+ if (basePath.exitCode !== 0) throw sandboxErrorDiagnostics.SANDBOX_R0154({ message: `[vitehub] Sandbox toolchain could not read the Sandbox PATH: ${basePath.stderr.trim()}` });
162
+ const cacheRoot = joinRemotePath(home, ".cache/vitehub/toolchains");
163
+ const toolchain = await provisionToolchain(input.toolchain, {
164
+ abortSignal,
165
+ cacheRoot,
166
+ readProjectFiles: async (paths) => await readProjectFilesWithShell(run, workspace, paths),
167
+ reuseExactNode: true,
168
+ run,
169
+ scratch: cacheRoot,
170
+ async write(path, content) {
171
+ await session.makeDirectory({
172
+ abortSignal,
173
+ path: dirnameRemotePath(path),
174
+ recursive: true
175
+ });
176
+ await session.writeBinaryFile({
177
+ abortSignal,
178
+ content,
179
+ path
180
+ });
181
+ }
182
+ });
183
+ environment.PATH = [...toolchain.bin, basePath.stdout].filter(Boolean).join(":");
184
+ await verifyToolchain(toolchain, cacheRoot, async (script) => await session.run({
185
+ abortSignal,
186
+ command: script,
187
+ workingDirectory: workspace
188
+ }));
189
+ session.toolchain = toolchain;
190
+ }
191
+ function joinRemotePath(...parts) {
192
+ return parts.join("/").replace(/\/{2,}/g, "/");
193
+ }
194
+ function dirnameRemotePath(path) {
195
+ const index = path.lastIndexOf("/");
196
+ return index <= 0 ? "/" : path.slice(0, index);
197
+ }
198
+ async function validateRequirements(session, requirements, workspace, abortSignal, secrets) {
199
+ for (const requirement of requirements) {
200
+ const command = [
201
+ "command -v",
202
+ shellQuote(requirement.command),
203
+ ">/dev/null"
204
+ ];
205
+ if (requirement.args.length) command.push("&&", shellQuote(requirement.command), ...requirement.args.map(shellQuote));
206
+ let result;
207
+ try {
208
+ result = await session.run({
209
+ abortSignal: sandboxRequirementSignal(requirement, abortSignal),
210
+ command: command.join(" "),
211
+ workingDirectory: workspace
212
+ });
213
+ } catch (cause) {
214
+ if (abortSignal?.aborted) throw abortSignal.reason;
215
+ throw sandboxRequirementError(requirement, cause, secrets);
216
+ }
217
+ if (result.exitCode !== 0) throw sandboxRequirementError(requirement, result, secrets);
218
+ }
219
+ }
220
+ function assertRemoteInput(input, runtime) {
221
+ if (input.cwd) throw sandboxErrorDiagnostics.SANDBOX_R0122({ message: `[vitehub] ${runtime} cannot mount a host Sandbox cwd; use Workspace instead.` });
222
+ if (input.plan.state.length) throw sandboxErrorDiagnostics.SANDBOX_R0123({ message: `[vitehub] ${runtime} does not provide durable Sandbox Home state.` });
223
+ }
224
+ async function collectProcessOutput(process) {
225
+ const [{ exitCode }, stdout, stderr] = await Promise.all([
226
+ process.wait(),
227
+ process.stdout(),
228
+ process.stderr()
229
+ ]);
230
+ return {
231
+ exitCode,
232
+ stderr,
233
+ stdout
234
+ };
235
+ }
236
+ function snapshotStream(read) {
237
+ return new ReadableStream({ async start(controller) {
238
+ try {
239
+ controller.enqueue(new TextEncoder().encode(await read()));
240
+ controller.close();
241
+ } catch (error) {
242
+ controller.error(error);
243
+ }
244
+ } });
245
+ }
246
+ //#endregion
247
+ export { resolveRemoteSandboxRuntime as a, resolveRemoteEnvironment as i, openRemoteSandbox as n, snapshotStream as o, remoteSandboxPlan as r, collectProcessOutput as t };
@@ -0,0 +1,14 @@
1
+ import "node:module";
2
+ //#region \0rolldown/runtime.js
3
+ var __defProp = Object.defineProperty;
4
+ var __exportAll = (all, no_symbols) => {
5
+ let target = {};
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
11
+ return target;
12
+ };
13
+ //#endregion
14
+ export { __exportAll as t };
@@ -0,0 +1,32 @@
1
+ //#region src/internal/runtime.ts
2
+ const builtInSandboxRuntime = Symbol.for("vitehub.sandbox.internal-runtime");
3
+ function isFunction(value) {
4
+ return typeof value === "function";
5
+ }
6
+ function isOrdinaryObjectPrototype(value) {
7
+ if (Object.getPrototypeOf(value) !== null || !Object.hasOwn(value, "constructor")) return false;
8
+ const constructor = Object.getOwnPropertyDescriptor(value, "constructor")?.value;
9
+ return isFunction(constructor) && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(Object);
10
+ }
11
+ function isBuiltInSandboxRuntime(runtime) {
12
+ return Object.getOwnPropertyDescriptor(runtime, builtInSandboxRuntime)?.value === true;
13
+ }
14
+ function hasDeclaredSandboxRuntimeMember(value, key) {
15
+ if (Object.hasOwn(value, key)) return true;
16
+ let prototype = Object.getPrototypeOf(value);
17
+ while (prototype && prototype !== Object.prototype) {
18
+ if (isOrdinaryObjectPrototype(prototype)) return false;
19
+ if (Object.hasOwn(prototype, key)) {
20
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
21
+ return isFunction(constructor) && constructor.prototype === prototype && /^class\b/.test(Function.prototype.toString.call(constructor));
22
+ }
23
+ prototype = Object.getPrototypeOf(prototype);
24
+ }
25
+ return false;
26
+ }
27
+ function markBuiltInSandboxRuntime(runtime) {
28
+ Object.defineProperty(runtime, builtInSandboxRuntime, { value: true });
29
+ return runtime;
30
+ }
31
+ //#endregion
32
+ export { isBuiltInSandboxRuntime as n, markBuiltInSandboxRuntime as r, hasDeclaredSandboxRuntimeMember as t };
@@ -0,0 +1,42 @@
1
+ //#region src/internal/abortable.ts
2
+ /**
3
+ * Wait for a promise until the caller's signal aborts.
4
+ *
5
+ * The underlying operation is intentionally not cancelled. This helper only
6
+ * stops waiting for it and rejects with the signal reason.
7
+ */
8
+ function abortable(promise, signal) {
9
+ if (!signal) return promise;
10
+ signal.throwIfAborted();
11
+ return new Promise((resolve, reject) => {
12
+ const onAbort = () => {
13
+ signal.removeEventListener("abort", onAbort);
14
+ reject(signal.reason);
15
+ };
16
+ signal.addEventListener("abort", onAbort, { once: true });
17
+ promise.then((value) => {
18
+ signal.removeEventListener("abort", onAbort);
19
+ resolve(value);
20
+ }, (error) => {
21
+ signal.removeEventListener("abort", onAbort);
22
+ reject(error);
23
+ });
24
+ });
25
+ }
26
+ //#endregion
27
+ //#region src/internal/runtime-type.ts
28
+ /** Parses JavaScript runtime representations at Sandbox boundaries. */
29
+ function isRuntimeString(value) {
30
+ return Object(value) !== value && Object.prototype.toString.call(value) === "[object String]";
31
+ }
32
+ function isRuntimeNumber(value) {
33
+ return Object(value) !== value && Object.prototype.toString.call(value) === "[object Number]";
34
+ }
35
+ /** Returns a plain JSON-style object, or undefined for primitives, arrays, and functions. */
36
+ function runtimeRecord(value) {
37
+ if (value === null || Object(value) !== value || Array.isArray(value)) return;
38
+ if (Object.prototype.toString.call(value) !== "[object Object]") return;
39
+ return value;
40
+ }
41
+ //#endregion
42
+ export { abortable as i, isRuntimeString as n, runtimeRecord as r, isRuntimeNumber as t };