@vite-hub/sandbox 0.0.4 → 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 (67) hide show
  1. package/README.md +395 -37
  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-sbV3Zjuo.js +1110 -0
  8. package/dist/error-diagnostics-5QT_BjbQ.js +354 -0
  9. package/dist/error-diagnostics-BJtLRL9w.js +536 -0
  10. package/dist/file-listing-CHtRrfo1.js +26 -0
  11. package/dist/file-lock-D0-XPogS.js +74 -0
  12. package/dist/index-DsoQAUb7.d.ts +594 -0
  13. package/dist/index.d.ts +2 -69
  14. package/dist/index.js +281 -1182
  15. package/dist/internal/cloudflare.d.ts +176 -0
  16. package/dist/internal/cloudflare.js +8 -0
  17. package/dist/internal/host-toolchain.d.ts +22 -0
  18. package/dist/internal/host-toolchain.js +96 -0
  19. package/dist/internal/vercel.d.ts +4 -0
  20. package/dist/internal/vercel.js +8 -0
  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-70ZVZZlq.js +265 -0
  27. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  28. package/dist/runtime-DHp6ImeP.js +32 -0
  29. package/dist/runtime-type-Deo4qzxN.js +9 -0
  30. package/dist/session-e0lyzjJ3.js +338 -0
  31. package/dist/shell-quote-Q3u3plif.js +6 -0
  32. package/dist/size-7AkVwGZb.js +118 -0
  33. package/dist/ssh.d.ts +63 -0
  34. package/dist/ssh.js +286 -0
  35. package/dist/task/index.d.ts +69 -0
  36. package/dist/task/index.js +1414 -0
  37. package/dist/task/runtime/empty-registry.d.ts +6 -0
  38. package/dist/{runtime → task/runtime}/empty-registry.js +2 -2
  39. package/dist/task/runtime/provider-loader.d.ts +18 -0
  40. package/dist/task/runtime/provider-loader.js +16 -0
  41. package/dist/task/runtime/providers/cloudflare.d.ts +14 -0
  42. package/dist/task/runtime/providers/cloudflare.js +27 -0
  43. package/dist/task/runtime/providers/vercel.d.ts +12 -0
  44. package/dist/task/runtime/providers/vercel.js +85 -0
  45. package/dist/task/runtime/state.d.ts +27 -0
  46. package/dist/task/runtime/state.js +82 -0
  47. package/dist/task/vite.d.ts +486 -0
  48. package/dist/task/vite.js +3966 -0
  49. package/dist/toolchain-BIVGMRty.js +528 -0
  50. package/dist/trusted-host-kxkpaQcs.js +714 -0
  51. package/dist/vercel-BGGrNpza.js +352 -0
  52. package/package.json +105 -51
  53. package/dist/cloudflare-env-QQV4uzCT.js +0 -14
  54. package/dist/module-types-DKYItiOu.d.ts +0 -93
  55. package/dist/module-types-Dj1MFmHT.js +0 -7
  56. package/dist/provider-loader-D0UihePq.d.ts +0 -21
  57. package/dist/runtime/empty-registry.d.ts +0 -6
  58. package/dist/runtime/provider-loader.d.ts +0 -2
  59. package/dist/runtime/provider-loader.js +0 -15
  60. package/dist/runtime/providers/cloudflare.d.ts +0 -29
  61. package/dist/runtime/providers/cloudflare.js +0 -25
  62. package/dist/runtime/providers/vercel.d.ts +0 -121
  63. package/dist/runtime/providers/vercel.js +0 -51
  64. package/dist/runtime/state.d.ts +0 -26
  65. package/dist/runtime/state.js +0 -72
  66. package/dist/vite.d.ts +0 -48
  67. package/dist/vite.js +0 -3324
@@ -0,0 +1,714 @@
1
+ import { r as markBuiltInSandboxRuntime } from "./runtime-DHp6ImeP.js";
2
+ import { t as sandboxErrorDiagnostics } from "./error-diagnostics-BJtLRL9w.js";
3
+ import { t as stopMarkedProcesses } from "./process-sweep-CMaujWE5.js";
4
+ import { a as sandboxRequirementSecrets, i as sandboxRequirementPlan, n as collectSandboxRequirementOutput, o as sandboxRequirementSignal, r as sandboxRequirementError, s as materializeGitCheckout, t as createSandboxSession } from "./session-e0lyzjJ3.js";
5
+ import { t as acquireFileLock } from "./file-lock-D0-XPogS.js";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { access, chmod, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
8
+ import { basename, delimiter, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
9
+ import { execFile, spawn } from "node:child_process";
10
+ import { promisify } from "node:util";
11
+ import { tmpdir } from "node:os";
12
+ import { constants } from "node:fs";
13
+ import { Readable, Writable } from "node:stream";
14
+ //#region src/internal/trusted-host.ts
15
+ const baseEnvironmentKeys = [
16
+ "ComSpec",
17
+ "LANG",
18
+ "LC_ALL",
19
+ "LOGNAME",
20
+ "Path",
21
+ "PATH",
22
+ "PATHEXT",
23
+ "SHELL",
24
+ "SystemRoot",
25
+ "TEMP",
26
+ "TERM",
27
+ "TMP",
28
+ "TMPDIR",
29
+ "USER"
30
+ ];
31
+ const runtimeEnvironmentKeys = /* @__PURE__ */ new Set([
32
+ "CODEX_HOME",
33
+ "HOME",
34
+ "INIT_CWD",
35
+ "OLDPWD",
36
+ "PWD",
37
+ "XDG_CACHE_HOME",
38
+ "XDG_CONFIG_HOME",
39
+ "XDG_STATE_HOME"
40
+ ]);
41
+ const trustedHostExecutionAuthority = {
42
+ credentials: "unknown",
43
+ environment: "selected",
44
+ filesystem: {
45
+ access: "read-write",
46
+ scope: "host"
47
+ },
48
+ isolation: "none",
49
+ network: "unrestricted",
50
+ processes: "arbitrary"
51
+ };
52
+ function createTrustedHostRuntime(options = {}) {
53
+ const preparedInputs = /* @__PURE__ */ new WeakMap();
54
+ return markBuiltInSandboxRuntime({
55
+ name: "trusted-host",
56
+ async prepare(input) {
57
+ const { cwd, stateRoot } = await resolveTrustedHostInput(input, options);
58
+ preparedInputs.set(input, {
59
+ cwd,
60
+ stateRoot
61
+ });
62
+ return {
63
+ cache: { state: "disposable" },
64
+ environment: { env: {} },
65
+ executionAuthority: trustedHostExecutionAuthority,
66
+ home: stateRoot ? { state: input.plan.state.map((state) => ({
67
+ identity: createHash("sha256").update(JSON.stringify([
68
+ stateRoot,
69
+ state.key,
70
+ state.path
71
+ ])).digest("hex"),
72
+ path: state.path
73
+ })) } : void 0,
74
+ identity: input.identity,
75
+ requirements: sandboxRequirementPlan(input.requirements),
76
+ runtime: "trusted-host",
77
+ workspace: cwd ? {
78
+ path: cwd,
79
+ state: "authoritative",
80
+ workDir: "workspace"
81
+ } : input.checkout ? {
82
+ state: "disposable",
83
+ workDir: "."
84
+ } : {
85
+ state: "disposable",
86
+ workDir: "."
87
+ }
88
+ };
89
+ },
90
+ async open(input, openOptions) {
91
+ const resolved = preparedInputs.get(input) ?? await resolveTrustedHostInput(input, options);
92
+ let initializedSession;
93
+ const runtimeSession = await createSession({
94
+ ...input,
95
+ ...resolved.cwd ? { cwd: resolved.cwd } : {}
96
+ }, { stateRoot: resolved.stateRoot }, {
97
+ abortSignal: openOptions?.signal,
98
+ ...openOptions?.initialize ? { async initialize(session) {
99
+ initializedSession = createSandboxSession(session, openOptions, resolved.cwd ? join(session.defaultWorkingDirectory, "workspace") : void 0);
100
+ await openOptions.initialize(initializedSession, { signal: openOptions.signal });
101
+ } } : {},
102
+ sessionId: openOptions?.id
103
+ });
104
+ return initializedSession ?? createSandboxSession(runtimeSession, openOptions, resolved.cwd ? join(runtimeSession.defaultWorkingDirectory, "workspace") : void 0);
105
+ }
106
+ });
107
+ }
108
+ async function resolveTrustedHostInput(input, options) {
109
+ const requestedCwd = input.cwd ? resolve(input.cwd) : void 0;
110
+ if (requestedCwd) await assertDirectory(requestedCwd, "workspace");
111
+ const cwd = requestedCwd ? await realpath(requestedCwd) : void 0;
112
+ const configuredStateRoot = options.stateRoot;
113
+ if (input.plan.state.length && (!configuredStateRoot || !isAbsolute(configuredStateRoot))) throw sandboxErrorDiagnostics.SANDBOX_R0130({ message: "[vitehub] The trusted-host runtime requires stateRoot to be an absolute path when sandbox.home.state is declared." });
114
+ const stateRoot = configuredStateRoot ? await canonicalFuturePath(configuredStateRoot) : void 0;
115
+ if (input.plan.state.length && stateRoot && dirname(stateRoot) === stateRoot) throw sandboxErrorDiagnostics.SANDBOX_R0131({ message: "[vitehub] Sandbox stateRoot must be a dedicated directory, not the filesystem root." });
116
+ if (cwd && input.plan.state.length && stateRoot) {
117
+ if (pathsOverlap(cwd, stateRoot)) throw sandboxErrorDiagnostics.SANDBOX_R0132({ message: "[vitehub] Sandbox stateRoot must be outside the authoritative workspace." });
118
+ }
119
+ return {
120
+ cwd,
121
+ stateRoot
122
+ };
123
+ }
124
+ async function createSession(input, options, createOptions) {
125
+ const releases = await acquireStateLeases(input.plan.state, options.stateRoot, createOptions.abortSignal);
126
+ let root;
127
+ let session;
128
+ const initializedState = [];
129
+ let initializationFailed = false;
130
+ try {
131
+ root = await realpath(await mkdtemp(join(tmpdir(), "vitehub-sandbox-")));
132
+ const home = join(root, "home");
133
+ await mkdir(home, { mode: 448 });
134
+ const states = await prepareState(input.plan.state, options.stateRoot);
135
+ const files = await resolveFiles(input.plan.files);
136
+ const env = await resolveEnvironment(home, input.plan.env);
137
+ await materializeState(home, states, initializedState);
138
+ await materializeFiles(home, files);
139
+ const checkout = input.checkout ? join(root, "workspace") : void 0;
140
+ if (input.checkout && checkout) await materializeGitCheckout(input.checkout, checkout, {
141
+ abortSignal: createOptions.abortSignal,
142
+ async run(args) {
143
+ return { stdout: (await promisify(execFile)("git", [...args], {
144
+ env,
145
+ signal: createOptions.abortSignal
146
+ })).stdout };
147
+ }
148
+ });
149
+ const toolchain = input.toolchain ? await provisionTrustedHostToolchain(input.toolchain, checkout ?? input.cwd ?? root, options.stateRoot, env, createOptions.abortSignal) : void 0;
150
+ session = await createTrustedHostSession({
151
+ env,
152
+ home,
153
+ async release() {
154
+ if (initializationFailed) await Promise.all(initializedState.map((path) => rm(path, {
155
+ force: true,
156
+ recursive: true
157
+ }).catch(() => void 0)));
158
+ await releases();
159
+ },
160
+ root,
161
+ sessionId: createOptions.sessionId,
162
+ workspace: input.cwd
163
+ });
164
+ session.toolchain = toolchain;
165
+ await validateRequirements(input.requirements, env, checkout ?? input.cwd ?? root, createOptions.abortSignal, sandboxRequirementSecrets([
166
+ ...Object.keys(input.plan.env).map((name) => env[name]),
167
+ ...files.map((file) => file.contents),
168
+ ...states.flatMap((state) => state.seed.map((file) => file.contents))
169
+ ]), input.plan.state.length === 0);
170
+ await createOptions.initialize?.(session);
171
+ return session;
172
+ } catch (error) {
173
+ if (session) {
174
+ initializationFailed = true;
175
+ try {
176
+ await session.destroy?.();
177
+ } catch {
178
+ retrySessionDestroy(session);
179
+ }
180
+ } else {
181
+ await Promise.all(initializedState.map((path) => rm(path, {
182
+ force: true,
183
+ recursive: true
184
+ }).catch(() => void 0)));
185
+ if (root) await rm(root, {
186
+ force: true,
187
+ recursive: true
188
+ }).catch(() => void 0);
189
+ await releases();
190
+ }
191
+ throw error;
192
+ }
193
+ }
194
+ async function retrySessionDestroy(session) {
195
+ while (true) {
196
+ await new Promise((resolvePromise) => {
197
+ setTimeout(resolvePromise, 250).unref?.();
198
+ });
199
+ try {
200
+ await session.destroy?.();
201
+ return;
202
+ } catch {}
203
+ }
204
+ }
205
+ async function provisionTrustedHostToolchain(toolchain, directory, stateRoot, env, abortSignal) {
206
+ const { hostToolchainCacheRoot, provisionHostToolchain, toolchainPath } = await import("./internal/host-toolchain.js");
207
+ const provisioned = await provisionHostToolchain(toolchain, directory, {
208
+ abortSignal,
209
+ cacheRoot: hostToolchainCacheRoot(stateRoot),
210
+ env
211
+ });
212
+ env.PATH = toolchainPath(provisioned, env.PATH);
213
+ return provisioned;
214
+ }
215
+ async function prepareState(states, stateRoot) {
216
+ if (!states.length) return [];
217
+ const prepared = [];
218
+ for (const state of states) {
219
+ const persistent = statePath(stateRoot, state.key);
220
+ const existing = await stat(persistent).catch((error) => {
221
+ if (error.code === "ENOENT") return void 0;
222
+ throw error;
223
+ });
224
+ if (existing && !existing.isDirectory()) throw sandboxErrorDiagnostics.SANDBOX_R0133({ message: `[vitehub] Sandbox state is not a directory: ${state.key}` });
225
+ prepared.push({
226
+ initialize: !existing,
227
+ path: state.path,
228
+ persistent,
229
+ projections: state.projections,
230
+ seed: existing ? [] : await resolveFiles(state.seed)
231
+ });
232
+ }
233
+ return prepared;
234
+ }
235
+ async function materializeState(home, states, initialized) {
236
+ for (const state of states) {
237
+ if (state.initialize) {
238
+ const staging = `${state.persistent}.init-${randomUUID()}`;
239
+ try {
240
+ await mkdir(staging, { mode: 448 });
241
+ await materializeFiles(staging, state.seed);
242
+ await rename(staging, state.persistent);
243
+ initialized.push(state.persistent);
244
+ } finally {
245
+ await rm(staging, {
246
+ force: true,
247
+ recursive: true
248
+ }).catch(() => void 0);
249
+ }
250
+ }
251
+ await reconcileProjections(state);
252
+ await chmod(state.persistent, 448);
253
+ const target = join(home, ...state.path.split("/"));
254
+ await mkdir(dirname(target), {
255
+ mode: 448,
256
+ recursive: true
257
+ });
258
+ await symlink(state.persistent, target, "dir");
259
+ }
260
+ }
261
+ async function reconcileProjections(state) {
262
+ const manifest = `${state.persistent}.projections`;
263
+ const previous = await readFile(manifest, "utf8").then((value) => {
264
+ const parsed = JSON.parse(value);
265
+ if (!Array.isArray(parsed) || parsed.some((path) => typeof path !== "string")) throw sandboxErrorDiagnostics.SANDBOX_R0134({ message: `[vitehub] Sandbox projection manifest is invalid: ${state.path}` });
266
+ return parsed;
267
+ }, (error) => {
268
+ if (error.code === "ENOENT") return [];
269
+ throw error;
270
+ });
271
+ const persistent = await realpath(state.persistent);
272
+ for (const path of state.projections) {
273
+ const parent = await canonicalFuturePath(dirname(join(state.persistent, ...path.split("/"))));
274
+ const relativeParent = relative(persistent, parent);
275
+ if (relativeParent === ".." || relativeParent.startsWith(`..${sep}`) || isAbsolute(relativeParent)) throw sandboxErrorDiagnostics.SANDBOX_R0135({ message: `[vitehub] Sandbox projected path escapes writable state: ${state.path}/${path}` });
276
+ }
277
+ const current = new Set(state.projections);
278
+ for (const path of previous) {
279
+ if (current.has(path)) continue;
280
+ const target = join(state.persistent, ...path.split("/"));
281
+ const parent = await realpath(dirname(target)).catch((error) => {
282
+ if (error.code === "ENOENT") return void 0;
283
+ throw error;
284
+ });
285
+ if (!parent) continue;
286
+ const relativeParent = relative(persistent, parent);
287
+ if (relativeParent === ".." || relativeParent.startsWith(`..${sep}`) || isAbsolute(relativeParent)) throw sandboxErrorDiagnostics.SANDBOX_R0136({ message: `[vitehub] Sandbox projected path escapes writable state: ${state.path}/${path}` });
288
+ await rm(target, {
289
+ force: true,
290
+ recursive: true
291
+ });
292
+ }
293
+ await writePrivateFile(manifest, new TextEncoder().encode(JSON.stringify(state.projections)));
294
+ }
295
+ async function resolveFiles(files) {
296
+ return await Promise.all(Object.entries(files).map(async ([path, input]) => ({
297
+ contents: await input.resolve(),
298
+ path
299
+ })));
300
+ }
301
+ async function materializeFiles(root, files) {
302
+ for (const file of files) await writePrivateFile(join(root, ...file.path.split("/")), file.contents);
303
+ }
304
+ async function writePrivateFile(path, contents) {
305
+ const directory = dirname(path);
306
+ await mkdir(directory, {
307
+ mode: 448,
308
+ recursive: true
309
+ });
310
+ const temporary = join(directory, `.vitehub-${randomUUID()}`);
311
+ try {
312
+ await writeFile(temporary, contents, { mode: 384 });
313
+ await rm(path, {
314
+ force: true,
315
+ recursive: true
316
+ });
317
+ await rename(temporary, path);
318
+ await chmod(path, 384);
319
+ } finally {
320
+ await rm(temporary, { force: true }).catch(() => void 0);
321
+ }
322
+ }
323
+ async function resolveEnvironment(home, values) {
324
+ const env = Object.fromEntries(baseEnvironmentKeys.map((name) => [name, process.env[name]]).filter((entry) => entry[1] !== void 0));
325
+ Object.assign(env, {
326
+ HOME: home,
327
+ XDG_CACHE_HOME: join(home, ".cache"),
328
+ XDG_CONFIG_HOME: join(home, ".config"),
329
+ XDG_STATE_HOME: join(home, ".local", "state")
330
+ });
331
+ for (const [name, resolveValue] of Object.entries(values)) env[name] = await resolveValue();
332
+ return env;
333
+ }
334
+ const sessionEnvironmentKey = "VITEHUB_SANDBOX_SESSION";
335
+ async function createTrustedHostSession(options) {
336
+ const workspace = join(options.root, "workspace");
337
+ if (options.workspace) await symlink(options.workspace, workspace, "dir");
338
+ else await mkdir(workspace, { recursive: true });
339
+ let destroyPromise;
340
+ let closing = false;
341
+ const processes = /* @__PURE__ */ new Set();
342
+ const processGroups = /* @__PURE__ */ new Set();
343
+ return {
344
+ defaultWorkingDirectory: options.workspace ? options.root : workspace,
345
+ env: options.env,
346
+ home: options.home,
347
+ id: options.sessionId || randomUUID(),
348
+ ports: [0],
349
+ processes,
350
+ root: options.root,
351
+ async destroy() {
352
+ closing = true;
353
+ const cleanup = async () => {
354
+ await this.stop();
355
+ try {
356
+ await rm(options.root, {
357
+ force: true,
358
+ recursive: true
359
+ });
360
+ } finally {
361
+ await options.release();
362
+ }
363
+ };
364
+ const attempt = destroyPromise ?? cleanup();
365
+ if (!destroyPromise) destroyPromise = attempt;
366
+ try {
367
+ await attempt;
368
+ } catch (error) {
369
+ if (destroyPromise === attempt) destroyPromise = void 0;
370
+ throw error;
371
+ }
372
+ },
373
+ async getPortUrl({ port, protocol = "http" }) {
374
+ return `${protocol}://127.0.0.1:${port}`;
375
+ },
376
+ async existsFile({ path }) {
377
+ return await lstat(resolveSessionPath(options.root, path)).then(() => true, (error) => {
378
+ if (error.code === "ENOENT") return false;
379
+ throw error;
380
+ });
381
+ },
382
+ async listFiles({ path, recursive = false }) {
383
+ const root = resolveSessionPath(options.root, path);
384
+ const entries = [];
385
+ await visit(root, path);
386
+ return entries.sort((left, right) => left.path.localeCompare(right.path));
387
+ async function visit(directory, logicalDirectory) {
388
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
389
+ const physicalPath = join(directory, entry.name);
390
+ const logicalPath = posix.join(logicalDirectory, entry.name);
391
+ const item = await lstat(physicalPath);
392
+ entries.push({
393
+ path: logicalPath,
394
+ size: entry.isFile() ? item.size : void 0,
395
+ type: entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "file"
396
+ });
397
+ if (recursive && entry.isDirectory()) await visit(physicalPath, logicalPath);
398
+ }
399
+ }
400
+ },
401
+ async makeDirectory({ path, recursive = false }) {
402
+ await mkdir(resolveSessionPath(options.root, path), { recursive });
403
+ },
404
+ async moveFile({ destination, source }) {
405
+ const target = resolveSessionPath(options.root, destination);
406
+ await mkdir(dirname(target), { recursive: true });
407
+ await rename(resolveSessionPath(options.root, source), target);
408
+ },
409
+ async readBinaryFile({ path }) {
410
+ return await readFile(resolveSessionPath(options.root, path)).catch((error) => {
411
+ if (error.code === "ENOENT") return null;
412
+ throw error;
413
+ });
414
+ },
415
+ async run(runOptions) {
416
+ const child = await this.spawn(runOptions);
417
+ const [stdout, stderr, { exitCode }] = await Promise.all([
418
+ collect(child.stdout),
419
+ collect(child.stderr),
420
+ child.wait()
421
+ ]);
422
+ return {
423
+ exitCode,
424
+ stderr,
425
+ stdout
426
+ };
427
+ },
428
+ async spawn(runOptions) {
429
+ runOptions.abortSignal?.throwIfAborted();
430
+ assertCommandEnvironment(runOptions.env);
431
+ const cwd = await physicalSessionPath(options.root, runOptions.workingDirectory ?? this.defaultWorkingDirectory);
432
+ runOptions.abortSignal?.throwIfAborted();
433
+ if (closing) throw sandboxErrorDiagnostics.SANDBOX_TRUSTED_HOST_CLOSING();
434
+ const child = spawn(runOptions.command, {
435
+ cwd,
436
+ detached: process.platform !== "win32",
437
+ env: {
438
+ ...options.env,
439
+ ...runOptions.env,
440
+ INIT_CWD: cwd,
441
+ OLDPWD: cwd,
442
+ PWD: cwd,
443
+ [sessionEnvironmentKey]: options.root
444
+ },
445
+ shell: true
446
+ });
447
+ processes.add(child);
448
+ if (child.pid && process.platform !== "win32") processGroups.add(child.pid);
449
+ child.once("close", () => {
450
+ processes.delete(child);
451
+ if (child.pid && process.platform !== "win32" && !processGroupExists(child.pid)) processGroups.delete(child.pid);
452
+ });
453
+ return processHandle(child, runOptions.abortSignal);
454
+ },
455
+ async stop() {
456
+ const active = [...processes];
457
+ for (const pid of processGroups) signalProcessGroup(pid, "SIGTERM");
458
+ if (process.platform === "win32") for (const child of active) signalProcessTree(child, "SIGTERM");
459
+ let graceTimeout;
460
+ try {
461
+ await Promise.race([Promise.all(active.map(waitForExit)), new Promise((resolvePromise) => {
462
+ graceTimeout = setTimeout(resolvePromise, 250);
463
+ })]);
464
+ } finally {
465
+ if (graceTimeout) clearTimeout(graceTimeout);
466
+ }
467
+ for (const pid of processGroups) signalProcessGroup(pid, "SIGKILL");
468
+ if (process.platform === "win32") for (const child of active) signalProcessTree(child, "SIGKILL");
469
+ let timedOut = false;
470
+ let timeout;
471
+ try {
472
+ await Promise.race([Promise.all(active.map(waitForExit)), new Promise((resolvePromise) => {
473
+ timeout = setTimeout(() => {
474
+ timedOut = true;
475
+ resolvePromise();
476
+ }, 1e4);
477
+ })]);
478
+ } finally {
479
+ if (timeout) clearTimeout(timeout);
480
+ }
481
+ if (timedOut) throw sandboxErrorDiagnostics.SANDBOX_TRUSTED_HOST_KILL_TIMED_OUT();
482
+ await stopMarkedProcesses(sessionEnvironmentKey, options.root);
483
+ processes.clear();
484
+ processGroups.clear();
485
+ },
486
+ async removeFile({ path, recursive = false }) {
487
+ const target = resolveSessionPath(options.root, path);
488
+ if (recursive) {
489
+ await rm(target, {
490
+ force: true,
491
+ recursive: true
492
+ });
493
+ return;
494
+ }
495
+ const item = await lstat(target).catch((error) => {
496
+ if (error.code === "ENOENT") return void 0;
497
+ throw error;
498
+ });
499
+ if (!item) return;
500
+ if (item.isDirectory() && !item.isSymbolicLink()) await rmdir(target);
501
+ else await rm(target, { force: true });
502
+ },
503
+ async writeBinaryFile({ content, path }) {
504
+ const target = resolveSessionPath(options.root, path);
505
+ await mkdir(dirname(target), { recursive: true });
506
+ await writeFile(target, content);
507
+ }
508
+ };
509
+ }
510
+ function assertCommandEnvironment(env) {
511
+ const name = Object.keys(env || {}).find((name) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name));
512
+ if (name) throw sandboxErrorDiagnostics.SANDBOX_R0112({ message: `[vitehub] Invalid Sandbox environment variable: ${name}` });
513
+ const reservedName = Object.keys(env || {}).find((name) => runtimeEnvironmentKeys.has(name));
514
+ if (reservedName) throw sandboxErrorDiagnostics.SANDBOX_R0137({ message: `[vitehub] Sandbox commands cannot override ${reservedName}.` });
515
+ }
516
+ async function validateRequirements(requirements, env, cwd, abortSignal, secrets, includeDiagnosticOutput) {
517
+ for (const requirement of requirements) {
518
+ const executable = await findExecutable(requirement.command, env.PATH || env.Path, env.PATHEXT, cwd);
519
+ if (!executable) throw sandboxRequirementError(requirement, { message: `${requirement.command} is not on PATH.` }, secrets, requirement.timeout, includeDiagnosticOutput);
520
+ if (!requirement.args.length) continue;
521
+ const timeout = requirement.timeout ?? 1e4;
522
+ let result;
523
+ try {
524
+ const handle = processHandle(spawn(executable, requirement.args, {
525
+ cwd,
526
+ detached: process.platform !== "win32",
527
+ env,
528
+ shell: isWindowsCommandShim(executable)
529
+ }), sandboxRequirementSignal({
530
+ ...requirement,
531
+ timeout
532
+ }, abortSignal));
533
+ const [stderr, stdout, { exitCode }] = await Promise.all([
534
+ collectSandboxRequirementOutput(handle.stderr, secrets),
535
+ collectSandboxRequirementOutput(handle.stdout, secrets),
536
+ handle.wait()
537
+ ]);
538
+ result = {
539
+ exitCode,
540
+ stderr,
541
+ stdout
542
+ };
543
+ } catch (cause) {
544
+ if (abortSignal?.aborted) throw abortSignal.reason;
545
+ throw sandboxRequirementError(requirement, cause, secrets, timeout, includeDiagnosticOutput);
546
+ }
547
+ if (result.exitCode !== 0) throw sandboxRequirementError(requirement, result, secrets, timeout, includeDiagnosticOutput);
548
+ }
549
+ }
550
+ async function acquireStateLeases(states, stateRoot, abortSignal) {
551
+ if (!states.length) return async () => {};
552
+ await ensureStateRoot(stateRoot);
553
+ const paths = [...new Set(states.map((state) => statePath(stateRoot, state.key)))].sort();
554
+ const releases = [];
555
+ try {
556
+ for (const path of paths) releases.push(await acquireFileLock(`${path}.lock`, abortSignal));
557
+ } catch (error) {
558
+ for (const release of releases.reverse()) await release();
559
+ throw error;
560
+ }
561
+ return async () => {
562
+ for (const release of releases.reverse()) await release();
563
+ };
564
+ }
565
+ function statePath(root, key) {
566
+ return join(resolve(root), createHash("sha256").update(key).digest("hex"));
567
+ }
568
+ async function assertDirectory(path, label) {
569
+ if (!(await stat(path).catch(() => void 0))?.isDirectory()) throw sandboxErrorDiagnostics.SANDBOX_R0138({ message: `[vitehub] Sandbox ${label} directory does not exist: ${path}` });
570
+ }
571
+ async function canonicalFuturePath(path) {
572
+ const missing = [];
573
+ let candidate = resolve(path);
574
+ while (true) try {
575
+ return join(await realpath(candidate), ...missing.toReversed());
576
+ } catch (error) {
577
+ if (error.code !== "ENOENT") throw error;
578
+ const parent = dirname(candidate);
579
+ if (parent === candidate) throw error;
580
+ missing.push(basename(candidate));
581
+ candidate = parent;
582
+ }
583
+ }
584
+ async function ensureStateRoot(path) {
585
+ await mkdir(path, {
586
+ mode: 448,
587
+ recursive: true
588
+ });
589
+ const canonical = await realpath(path);
590
+ if (resolve(canonical) !== resolve(path)) throw sandboxErrorDiagnostics.SANDBOX_R0139({ message: "[vitehub] Sandbox stateRoot changed while the Sandbox was materializing." });
591
+ await assertDirectory(canonical, "stateRoot");
592
+ }
593
+ async function findExecutable(command, path, pathExt, cwd) {
594
+ const names = [command, ...(pathExt || "").split(";").map((extension) => extension.trim()).filter(Boolean).flatMap((extension) => {
595
+ return command.toLowerCase().endsWith(extension.toLowerCase()) ? [] : [`${command}${extension}`];
596
+ })];
597
+ const candidates = command.includes("/") || command.includes("\\") || isAbsolute(command) ? names.map((name) => resolve(cwd ?? process.cwd(), name)) : (path || "").split(delimiter).filter(Boolean).flatMap((directory) => names.map((name) => isAbsolute(directory) ? join(directory, name) : resolve(cwd ?? process.cwd(), directory, name)));
598
+ for (const candidate of candidates) if (await access(candidate, constants.X_OK).then(() => true, () => false)) return candidate;
599
+ }
600
+ function isWindowsCommandShim(path) {
601
+ return process.platform === "win32" && /\.(?:bat|cmd)$/i.test(path);
602
+ }
603
+ function resolveSessionPath(root, path = "") {
604
+ const candidate = isRootedPath(path) ? isAbsolute(path) && isInside(root, resolve(path)) ? resolve(path) : resolve(root, rootRelativeFragment(path)) : resolve(root, path);
605
+ if (!isInside(root, candidate)) throw sandboxErrorDiagnostics.SANDBOX_R0140({ message: `[vitehub] Trusted host Sandbox path escapes the session root: ${path}` });
606
+ return candidate;
607
+ }
608
+ async function physicalSessionPath(root, path = "") {
609
+ return await realpath(resolveSessionPath(root, path));
610
+ }
611
+ function isInside(root, path) {
612
+ const next = relative(resolve(root), resolve(path));
613
+ return !next || !next.startsWith("..") && !isAbsolute(next);
614
+ }
615
+ function pathsOverlap(first, second) {
616
+ return isInside(first, second) || isInside(second, first);
617
+ }
618
+ function isRootedPath(path) {
619
+ return isAbsolute(path) || /^[A-Za-z]:/.test(path) || /^[\\/]{2}/.test(path);
620
+ }
621
+ function rootRelativeFragment(path) {
622
+ return path.replace(/^[A-Za-z]:[\\/]*/, "").replace(/^[\\/]+/, "").replace(/\\/g, "/");
623
+ }
624
+ async function collect(stream) {
625
+ return await new Response(stream).text();
626
+ }
627
+ function processHandle(child, abortSignal) {
628
+ let abortReason;
629
+ let forceKillTimer;
630
+ const abort = () => {
631
+ if (abortReason) return;
632
+ abortReason = abortSignal?.reason || sandboxErrorDiagnostics.SANDBOX_R0141({ message: "Sandbox command aborted." });
633
+ signalProcessTree(child, "SIGTERM");
634
+ forceKillTimer = setTimeout(() => signalProcessTree(child, "SIGKILL"), 250);
635
+ forceKillTimer.unref?.();
636
+ };
637
+ abortSignal?.addEventListener("abort", abort, { once: true });
638
+ const wait = new Promise((resolvePromise, reject) => {
639
+ child.once("error", reject);
640
+ child.once("close", (code) => {
641
+ abortSignal?.removeEventListener("abort", abort);
642
+ if (forceKillTimer) clearTimeout(forceKillTimer);
643
+ if (abortReason) reject(abortReason);
644
+ else resolvePromise({ exitCode: code ?? 1 });
645
+ });
646
+ });
647
+ wait.catch(() => void 0);
648
+ if (abortSignal?.aborted) abort();
649
+ let stdin;
650
+ return {
651
+ pid: child.pid,
652
+ stderr: Readable.toWeb(child.stderr),
653
+ get stdin() {
654
+ return stdin ??= Writable.toWeb(child.stdin);
655
+ },
656
+ stdout: Readable.toWeb(child.stdout),
657
+ wait: () => wait,
658
+ async kill(signal) {
659
+ signalProcessTree(child, normalizeSignal(signal));
660
+ const settled = wait.catch(() => void 0);
661
+ if (signal !== void 0) {
662
+ await settled;
663
+ return;
664
+ }
665
+ let timer;
666
+ try {
667
+ const gracePeriod = new Promise((resolvePromise) => {
668
+ timer = setTimeout(resolvePromise, 250);
669
+ });
670
+ await Promise.race([gracePeriod, settled.then(() => {
671
+ if (child.pid && process.platform !== "win32" && processGroupExists(child.pid)) return gracePeriod;
672
+ })]);
673
+ signalProcessTree(child, "SIGKILL");
674
+ await settled;
675
+ } finally {
676
+ clearTimeout(timer);
677
+ }
678
+ }
679
+ };
680
+ }
681
+ function normalizeSignal(signal = "TERM") {
682
+ const normalized = signal.toUpperCase();
683
+ return normalized.startsWith("SIG") ? normalized : `SIG${normalized}`;
684
+ }
685
+ function signalProcessTree(child, signal) {
686
+ if (child.pid && process.platform !== "win32") {
687
+ signalProcessGroup(child.pid, signal);
688
+ return;
689
+ }
690
+ if (child.exitCode !== null || child.signalCode !== null) return;
691
+ child.kill(signal);
692
+ }
693
+ function signalProcessGroup(pid, signal) {
694
+ try {
695
+ process.kill(-pid, signal);
696
+ } catch (error) {
697
+ if (error.code !== "ESRCH") throw error;
698
+ }
699
+ }
700
+ function processGroupExists(pid) {
701
+ try {
702
+ process.kill(-pid, 0);
703
+ return true;
704
+ } catch (error) {
705
+ if (error.code === "ESRCH") return false;
706
+ throw error;
707
+ }
708
+ }
709
+ function waitForExit(child) {
710
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
711
+ return new Promise((resolvePromise) => child.once("close", () => resolvePromise()));
712
+ }
713
+ //#endregion
714
+ export { createTrustedHostRuntime };