@vercel/sandbox 2.0.0-beta.10 → 2.0.0-beta.12

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 (196) hide show
  1. package/README.md +8 -0
  2. package/dist/_virtual/rolldown_runtime.cjs +29 -0
  3. package/dist/api-client/api-client.cjs +456 -0
  4. package/dist/api-client/api-client.cjs.map +1 -0
  5. package/dist/api-client/api-client.d.cts +788 -0
  6. package/dist/api-client/api-client.d.ts +782 -777
  7. package/dist/api-client/api-client.js +445 -471
  8. package/dist/api-client/api-client.js.map +1 -1
  9. package/dist/api-client/api-error.cjs +32 -0
  10. package/dist/api-client/api-error.cjs.map +1 -0
  11. package/dist/api-client/api-error.d.cts +29 -0
  12. package/dist/api-client/api-error.d.ts +21 -18
  13. package/dist/api-client/api-error.js +28 -33
  14. package/dist/api-client/api-error.js.map +1 -1
  15. package/dist/api-client/base-client.cjs +125 -0
  16. package/dist/api-client/base-client.cjs.map +1 -0
  17. package/dist/api-client/base-client.d.cts +38 -0
  18. package/dist/api-client/base-client.d.ts +31 -36
  19. package/dist/api-client/base-client.js +110 -130
  20. package/dist/api-client/base-client.js.map +1 -1
  21. package/dist/api-client/file-writer.cjs +62 -0
  22. package/dist/api-client/file-writer.cjs.map +1 -0
  23. package/dist/api-client/file-writer.d.cts +66 -0
  24. package/dist/api-client/file-writer.d.ts +56 -52
  25. package/dist/api-client/file-writer.js +57 -61
  26. package/dist/api-client/file-writer.js.map +1 -1
  27. package/dist/api-client/index.cjs +2 -0
  28. package/dist/api-client/index.d.ts +2 -2
  29. package/dist/api-client/index.js +4 -21
  30. package/dist/api-client/validators.cjs +181 -0
  31. package/dist/api-client/validators.cjs.map +1 -0
  32. package/dist/api-client/validators.d.cts +1469 -0
  33. package/dist/api-client/validators.d.ts +1282 -3699
  34. package/dist/api-client/validators.js +154 -170
  35. package/dist/api-client/validators.js.map +1 -1
  36. package/dist/api-client/with-retry.cjs +89 -0
  37. package/dist/api-client/with-retry.cjs.map +1 -0
  38. package/dist/api-client/with-retry.d.cts +10 -0
  39. package/dist/api-client/with-retry.d.ts +9 -13
  40. package/dist/api-client/with-retry.js +81 -102
  41. package/dist/api-client/with-retry.js.map +1 -1
  42. package/dist/auth/api.cjs +29 -0
  43. package/dist/auth/api.cjs.map +1 -0
  44. package/dist/auth/api.js +26 -25
  45. package/dist/auth/api.js.map +1 -1
  46. package/dist/auth/error.cjs +13 -0
  47. package/dist/auth/error.cjs.map +1 -0
  48. package/dist/auth/error.js +11 -11
  49. package/dist/auth/error.js.map +1 -1
  50. package/dist/auth/file.cjs +64 -0
  51. package/dist/auth/file.cjs.map +1 -0
  52. package/dist/auth/file.d.cts +26 -0
  53. package/dist/auth/file.d.ts +19 -15
  54. package/dist/auth/file.js +49 -64
  55. package/dist/auth/file.js.map +1 -1
  56. package/dist/auth/index.cjs +12 -0
  57. package/dist/auth/index.d.cts +5 -0
  58. package/dist/auth/index.d.ts +5 -6
  59. package/dist/auth/index.js +6 -27
  60. package/dist/auth/linked-project.cjs +38 -0
  61. package/dist/auth/linked-project.cjs.map +1 -0
  62. package/dist/auth/linked-project.js +30 -64
  63. package/dist/auth/linked-project.js.map +1 -1
  64. package/dist/auth/oauth.cjs +205 -0
  65. package/dist/auth/oauth.cjs.map +1 -0
  66. package/dist/auth/oauth.d.cts +135 -0
  67. package/dist/auth/oauth.d.ts +113 -109
  68. package/dist/auth/oauth.js +185 -252
  69. package/dist/auth/oauth.js.map +1 -1
  70. package/dist/auth/poll-for-token.cjs +82 -0
  71. package/dist/auth/poll-for-token.cjs.map +1 -0
  72. package/dist/auth/poll-for-token.d.cts +28 -0
  73. package/dist/auth/poll-for-token.d.ts +23 -15
  74. package/dist/auth/poll-for-token.js +79 -64
  75. package/dist/auth/poll-for-token.js.map +1 -1
  76. package/dist/auth/project.cjs +80 -0
  77. package/dist/auth/project.cjs.map +1 -0
  78. package/dist/auth/project.d.cts +44 -0
  79. package/dist/auth/project.d.ts +12 -8
  80. package/dist/auth/project.js +70 -72
  81. package/dist/auth/project.js.map +1 -1
  82. package/dist/auth/zod.cjs +22 -0
  83. package/dist/auth/zod.cjs.map +1 -0
  84. package/dist/auth/zod.js +18 -17
  85. package/dist/auth/zod.js.map +1 -1
  86. package/dist/command.cjs +328 -0
  87. package/dist/command.cjs.map +1 -0
  88. package/dist/command.d.cts +289 -0
  89. package/dist/command.d.ts +265 -171
  90. package/dist/command.js +323 -226
  91. package/dist/command.js.map +1 -1
  92. package/dist/constants.d.cts +5 -0
  93. package/dist/constants.d.ts +5 -1
  94. package/dist/index.cjs +13 -0
  95. package/dist/index.d.cts +7 -0
  96. package/dist/index.d.ts +7 -6
  97. package/dist/index.js +7 -17
  98. package/dist/network-policy.d.cts +100 -0
  99. package/dist/network-policy.d.ts +32 -28
  100. package/dist/sandbox.cjs +688 -0
  101. package/dist/sandbox.cjs.map +1 -0
  102. package/dist/sandbox.d.cts +780 -0
  103. package/dist/sandbox.d.ts +767 -711
  104. package/dist/sandbox.js +680 -612
  105. package/dist/sandbox.js.map +1 -1
  106. package/dist/session.cjs +520 -0
  107. package/dist/session.cjs.map +1 -0
  108. package/dist/session.d.cts +406 -0
  109. package/dist/session.d.ts +398 -367
  110. package/dist/session.js +517 -505
  111. package/dist/session.js.map +1 -1
  112. package/dist/snapshot.cjs +116 -0
  113. package/dist/snapshot.cjs.map +1 -0
  114. package/dist/snapshot.d.cts +107 -0
  115. package/dist/snapshot.d.ts +98 -91
  116. package/dist/snapshot.js +114 -115
  117. package/dist/snapshot.js.map +1 -1
  118. package/dist/utils/array.cjs +17 -0
  119. package/dist/utils/array.cjs.map +1 -0
  120. package/dist/utils/array.js +12 -15
  121. package/dist/utils/array.js.map +1 -1
  122. package/dist/utils/consume-readable.cjs +18 -0
  123. package/dist/utils/consume-readable.cjs.map +1 -0
  124. package/dist/utils/consume-readable.js +13 -12
  125. package/dist/utils/consume-readable.js.map +1 -1
  126. package/dist/utils/decode-base64-url.cjs +15 -0
  127. package/dist/utils/decode-base64-url.cjs.map +1 -0
  128. package/dist/utils/decode-base64-url.js +10 -9
  129. package/dist/utils/decode-base64-url.js.map +1 -1
  130. package/dist/utils/dev-credentials.cjs +142 -0
  131. package/dist/utils/dev-credentials.cjs.map +1 -0
  132. package/dist/utils/dev-credentials.js +126 -184
  133. package/dist/utils/dev-credentials.js.map +1 -1
  134. package/dist/utils/get-credentials.cjs +123 -0
  135. package/dist/utils/get-credentials.cjs.map +1 -0
  136. package/dist/utils/get-credentials.d.cts +21 -0
  137. package/dist/utils/get-credentials.d.ts +19 -61
  138. package/dist/utils/get-credentials.js +106 -140
  139. package/dist/utils/get-credentials.js.map +1 -1
  140. package/dist/utils/log.cjs +25 -0
  141. package/dist/utils/log.cjs.map +1 -0
  142. package/dist/utils/log.js +15 -17
  143. package/dist/utils/log.js.map +1 -1
  144. package/dist/utils/network-policy.cjs +65 -0
  145. package/dist/utils/network-policy.cjs.map +1 -0
  146. package/dist/utils/network-policy.js +58 -77
  147. package/dist/utils/network-policy.js.map +1 -1
  148. package/dist/utils/normalizePath.cjs +27 -0
  149. package/dist/utils/normalizePath.cjs.map +1 -0
  150. package/dist/utils/normalizePath.js +21 -28
  151. package/dist/utils/normalizePath.js.map +1 -1
  152. package/dist/utils/resolveSignal.cjs +20 -0
  153. package/dist/utils/resolveSignal.cjs.map +1 -0
  154. package/dist/utils/resolveSignal.d.cts +15 -0
  155. package/dist/utils/resolveSignal.d.ts +12 -10
  156. package/dist/utils/resolveSignal.js +14 -17
  157. package/dist/utils/resolveSignal.js.map +1 -1
  158. package/dist/utils/sandbox-snapshot.cjs +14 -0
  159. package/dist/utils/sandbox-snapshot.cjs.map +1 -0
  160. package/dist/utils/sandbox-snapshot.d.cts +10 -0
  161. package/dist/utils/sandbox-snapshot.d.ts +11 -0
  162. package/dist/utils/sandbox-snapshot.js +14 -0
  163. package/dist/utils/sandbox-snapshot.js.map +1 -0
  164. package/dist/utils/types.cjs +13 -0
  165. package/dist/utils/types.cjs.map +1 -0
  166. package/dist/utils/types.d.cts +11 -0
  167. package/dist/utils/types.d.ts +5 -7
  168. package/dist/utils/types.js +8 -8
  169. package/dist/utils/types.js.map +1 -1
  170. package/dist/version.cjs +7 -0
  171. package/dist/version.cjs.map +1 -0
  172. package/dist/version.js +5 -5
  173. package/dist/version.js.map +1 -1
  174. package/package.json +23 -3
  175. package/dist/api-client/index.js.map +0 -1
  176. package/dist/auth/api.d.ts +0 -6
  177. package/dist/auth/error.d.ts +0 -11
  178. package/dist/auth/index.js.map +0 -1
  179. package/dist/auth/linked-project.d.ts +0 -10
  180. package/dist/auth/zod.d.ts +0 -5
  181. package/dist/constants.js +0 -3
  182. package/dist/constants.js.map +0 -1
  183. package/dist/index.js.map +0 -1
  184. package/dist/network-policy.js +0 -3
  185. package/dist/network-policy.js.map +0 -1
  186. package/dist/utils/array.d.ts +0 -9
  187. package/dist/utils/consume-readable.d.ts +0 -5
  188. package/dist/utils/convert-sandbox.d.ts +0 -6
  189. package/dist/utils/convert-sandbox.js +0 -14
  190. package/dist/utils/convert-sandbox.js.map +0 -1
  191. package/dist/utils/decode-base64-url.d.ts +0 -7
  192. package/dist/utils/dev-credentials.d.ts +0 -37
  193. package/dist/utils/log.d.ts +0 -2
  194. package/dist/utils/network-policy.d.ts +0 -7
  195. package/dist/utils/normalizePath.d.ts +0 -17
  196. package/dist/version.d.ts +0 -1
package/dist/sandbox.js CHANGED
@@ -1,619 +1,687 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Sandbox = void 0;
4
- const api_client_1 = require("./api-client");
5
- const api_error_1 = require("./api-client/api-error");
6
- const get_credentials_1 = require("./utils/get-credentials");
7
- const types_1 = require("./utils/types");
8
- const session_1 = require("./session");
9
- const network_policy_1 = require("./utils/network-policy");
10
- const promises_1 = require("node:timers/promises");
1
+ import { APIError } from "./api-client/api-error.js";
2
+ import { fromAPINetworkPolicy } from "./utils/network-policy.js";
3
+ import { getPrivateParams } from "./utils/types.js";
4
+ import { APIClient } from "./api-client/api-client.js";
5
+ import "./api-client/index.js";
6
+ import { getCredentials } from "./utils/get-credentials.js";
7
+ import { Session } from "./session.js";
8
+ import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from "@workflow/serde";
9
+ import { setTimeout } from "node:timers/promises";
10
+
11
+ //#region src/sandbox.ts
11
12
  function isSandboxStoppedError(err) {
12
- return err instanceof api_error_1.APIError && err.response.status === 410;
13
+ return err instanceof APIError && err.response.status === 410;
13
14
  }
14
15
  function isSandboxStoppingError(err) {
15
- return (err instanceof api_error_1.APIError &&
16
- err.response.status === 422 &&
17
- err.json?.error?.code === "sandbox_stopping");
16
+ return err instanceof APIError && err.response.status === 422 && err.json?.error?.code === "sandbox_stopping";
18
17
  }
19
- /**
20
- * A Sandbox is a persistent, isolated Linux MicroVMs to run commands in.
21
- * Use {@link Sandbox.create} or {@link Sandbox.get} to construct.
22
- * @hideconstructor
23
- */
24
- class Sandbox {
25
- /**
26
- * The name of this sandbox.
27
- */
28
- get name() {
29
- return this.sandbox.name;
30
- }
31
- /**
32
- * Routes from ports to subdomains.
33
- * @hidden
34
- */
35
- get routes() {
36
- return this.session.routes;
37
- }
38
- /**
39
- * Whether the sandbox persists the state.
40
- */
41
- get persistent() {
42
- return this.sandbox.persistent;
43
- }
44
- /**
45
- * The region this sandbox runs in.
46
- */
47
- get region() {
48
- return this.sandbox.region;
49
- }
50
- /**
51
- * Number of virtual CPUs allocated.
52
- */
53
- get vcpus() {
54
- return this.sandbox.vcpus;
55
- }
56
- /**
57
- * Memory allocated in MB.
58
- */
59
- get memory() {
60
- return this.sandbox.memory;
61
- }
62
- /** Runtime identifier (e.g. "node24", "python3.13"). */
63
- get runtime() {
64
- return this.sandbox.runtime;
65
- }
66
- /**
67
- * Cumulative egress bytes across all sessions.
68
- */
69
- get totalEgressBytes() {
70
- return this.sandbox.totalEgressBytes;
71
- }
72
- /**
73
- * Cumulative ingress bytes across all sessions.
74
- */
75
- get totalIngressBytes() {
76
- return this.sandbox.totalIngressBytes;
77
- }
78
- /**
79
- * Cumulative active CPU duration in milliseconds across all sessions.
80
- */
81
- get totalActiveCpuDurationMs() {
82
- return this.sandbox.totalActiveCpuDurationMs;
83
- }
84
- /**
85
- * Cumulative wall-clock duration in milliseconds across all sessions.
86
- */
87
- get totalDurationMs() {
88
- return this.sandbox.totalDurationMs;
89
- }
90
- /**
91
- * When this sandbox was last updated.
92
- */
93
- get updatedAt() {
94
- return new Date(this.sandbox.updatedAt);
95
- }
96
- /**
97
- * When the sandbox status was last updated.
98
- */
99
- get statusUpdatedAt() {
100
- return this.sandbox.statusUpdatedAt
101
- ? new Date(this.sandbox.statusUpdatedAt)
102
- : undefined;
103
- }
104
- /**
105
- * When this sandbox was created.
106
- */
107
- get createdAt() {
108
- return new Date(this.sandbox.createdAt);
109
- }
110
- /**
111
- * Interactive port.
112
- */
113
- get interactivePort() {
114
- return this.session.interactivePort;
115
- }
116
- /**
117
- * The status of the current session.
118
- */
119
- get status() {
120
- return this.session.status;
121
- }
122
- /**
123
- * The default timeout of this sandbox in milliseconds.
124
- */
125
- get timeout() {
126
- return this.sandbox.timeout;
127
- }
128
- /**
129
- * Key-value tags attached to the sandbox.
130
- */
131
- get tags() {
132
- return this.sandbox.tags;
133
- }
134
- /**
135
- * The default network policy of this sandbox.
136
- */
137
- get networkPolicy() {
138
- return this.sandbox.networkPolicy
139
- ? (0, network_policy_1.fromAPINetworkPolicy)(this.sandbox.networkPolicy)
140
- : undefined;
141
- }
142
- /**
143
- * If the session was created from a snapshot, the ID of that snapshot.
144
- */
145
- get sourceSnapshotId() {
146
- return this.session.sourceSnapshotId;
147
- }
148
- /**
149
- * The current snapshot ID of this sandbox, if any.
150
- */
151
- get currentSnapshotId() {
152
- return this.sandbox.currentSnapshotId;
153
- }
154
- /**
155
- * The default snapshot expiration in milliseconds, if set.
156
- */
157
- get snapshotExpiration() {
158
- return this.sandbox.snapshotExpiration;
159
- }
160
- /**
161
- * The amount of CPU used by the session. Only reported once the VM is stopped.
162
- */
163
- get activeCpuUsageMs() {
164
- return this.session.activeCpuUsageMs;
165
- }
166
- /**
167
- * The amount of network data used by the session. Only reported once the VM is stopped.
168
- */
169
- get networkTransfer() {
170
- return this.session.networkTransfer;
171
- }
172
- /**
173
- * Allow to get a list of sandboxes for a team narrowed to the given params.
174
- * It returns both the sandboxes and the pagination metadata to allow getting
175
- * the next page of results.
176
- */
177
- static async list(params) {
178
- const credentials = await (0, get_credentials_1.getCredentials)(params);
179
- const client = new api_client_1.APIClient({
180
- teamId: credentials.teamId,
181
- token: credentials.token,
182
- fetch: params?.fetch,
183
- });
184
- const response = await client.listSandboxes({
185
- ...credentials,
186
- ...params,
187
- });
188
- return response.json;
189
- }
190
- /**
191
- * Create a new sandbox.
192
- *
193
- * @param params - Creation parameters and optional credentials.
194
- * @returns A promise resolving to the created {@link Sandbox}.
195
- * @example
196
- * <caption>Create a sandbox and drop it in the end of the block</caption>
197
- * async function fn() {
198
- * await using const sandbox = await Sandbox.create();
199
- * // Sandbox automatically stopped at the end of the lexical scope
200
- * }
201
- */
202
- static async create(params) {
203
- const credentials = await (0, get_credentials_1.getCredentials)(params);
204
- const client = new api_client_1.APIClient({
205
- teamId: credentials.teamId,
206
- token: credentials.token,
207
- fetch: params?.fetch,
208
- });
209
- const privateParams = (0, types_1.getPrivateParams)(params);
210
- const response = await client.createSandbox({
211
- source: params?.source,
212
- projectId: credentials.projectId,
213
- ports: params?.ports ?? [],
214
- timeout: params?.timeout,
215
- resources: params?.resources,
216
- runtime: params && "runtime" in params ? params?.runtime : undefined,
217
- networkPolicy: params?.networkPolicy,
218
- env: params?.env,
219
- tags: params?.tags,
220
- snapshotExpiration: params?.snapshotExpiration,
221
- signal: params?.signal,
222
- name: params?.name,
223
- persistent: params?.persistent,
224
- ...privateParams,
225
- });
226
- return new DisposableSandbox({
227
- client,
228
- session: response.json.session,
229
- sandbox: response.json.sandbox,
230
- routes: response.json.routes,
231
- projectId: credentials.projectId,
232
- });
233
- }
234
- /**
235
- * Retrieve an existing sandbox and resume its session.
236
- *
237
- * @param params - Get parameters and optional credentials.
238
- * @returns A promise resolving to the {@link Sandbox}.
239
- */
240
- static async get(params) {
241
- const credentials = await (0, get_credentials_1.getCredentials)(params);
242
- const client = new api_client_1.APIClient({
243
- teamId: credentials.teamId,
244
- token: credentials.token,
245
- fetch: params.fetch,
246
- });
247
- const privateParams = (0, types_1.getPrivateParams)(params);
248
- const response = await client.getSandbox({
249
- name: params.name,
250
- projectId: credentials.projectId,
251
- resume: params.resume,
252
- signal: params.signal,
253
- ...privateParams,
254
- });
255
- return new Sandbox({
256
- client,
257
- session: response.json.session,
258
- sandbox: response.json.sandbox,
259
- routes: response.json.routes,
260
- projectId: credentials.projectId,
261
- });
262
- }
263
- constructor({ client, routes, session, sandbox, projectId, }) {
264
- /**
265
- * In-flight resume promise, used to deduplicate concurrent resume calls.
266
- */
267
- this.resumePromise = null;
268
- this.client = client;
269
- this.session = new session_1.Session({ client, routes, session });
270
- this.sandbox = sandbox;
271
- this.projectId = projectId;
272
- }
273
- /**
274
- * Get the current session (the running VM) for this sandbox.
275
- *
276
- * @returns The {@link Session} instance.
277
- */
278
- currentSession() {
279
- return this.session;
280
- }
281
- /**
282
- * Resume this sandbox by creating a new session via `getSandbox`.
283
- */
284
- async resume(signal) {
285
- if (!this.resumePromise) {
286
- this.resumePromise = this.doResume(signal).finally(() => {
287
- this.resumePromise = null;
288
- });
289
- }
290
- return this.resumePromise;
291
- }
292
- async doResume(signal) {
293
- const response = await this.client.getSandbox({
294
- name: this.sandbox.name,
295
- projectId: this.projectId,
296
- resume: true,
297
- signal,
298
- });
299
- this.session = new session_1.Session({
300
- client: this.client,
301
- routes: response.json.routes,
302
- session: response.json.session,
303
- });
304
- }
305
- /**
306
- * Poll until the current session reaches a terminal state, then resume.
307
- */
308
- async waitForStopAndResume(signal) {
309
- const pollingInterval = 500;
310
- let status = this.session.status;
311
- while (status === "stopping" || status === "snapshotting") {
312
- await (0, promises_1.setTimeout)(pollingInterval, undefined, { signal });
313
- const poll = await this.client.getSession({
314
- sessionId: this.session.sessionId,
315
- signal,
316
- });
317
- this.session = new session_1.Session({
318
- client: this.client,
319
- routes: poll.json.routes,
320
- session: poll.json.session,
321
- });
322
- status = poll.json.session.status;
323
- }
324
- await this.resume(signal);
325
- }
326
- /**
327
- * Execute `fn`, and if the session is stopped/stopping, resume and retry.
328
- */
329
- async withResume(fn, signal) {
330
- try {
331
- return await fn();
332
- }
333
- catch (err) {
334
- if (isSandboxStoppedError(err)) {
335
- await this.resume(signal);
336
- return fn();
337
- }
338
- if (isSandboxStoppingError(err)) {
339
- await this.waitForStopAndResume(signal);
340
- return fn();
341
- }
342
- throw err;
343
- }
344
- }
345
- async runCommand(commandOrParams, args, opts) {
346
- const signal = typeof commandOrParams === "string"
347
- ? opts?.signal
348
- : commandOrParams.signal;
349
- return this.withResume(() => this.session.runCommand(commandOrParams, args, opts), signal);
350
- }
351
- /**
352
- * Internal helper to start a command in the sandbox.
353
- *
354
- * @param params - Command execution parameters.
355
- * @returns A {@link Command} or {@link CommandFinished}, depending on `detached`.
356
- * @internal
357
- */
358
- async getCommand(cmdId, opts) {
359
- return this.withResume(() => this.session.getCommand(cmdId, opts), opts?.signal);
360
- }
361
- /**
362
- * Create a directory in the filesystem of this sandbox.
363
- *
364
- * @param path - Path of the directory to create
365
- * @param opts - Optional parameters.
366
- * @param opts.signal - An AbortSignal to cancel the operation.
367
- */
368
- async mkDir(path, opts) {
369
- return this.withResume(() => this.session.mkDir(path, opts), opts?.signal);
370
- }
371
- /**
372
- * Read a file from the filesystem of this sandbox as a stream.
373
- *
374
- * @param file - File to read, with path and optional cwd
375
- * @param opts - Optional parameters.
376
- * @param opts.signal - An AbortSignal to cancel the operation.
377
- * @returns A promise that resolves to a ReadableStream containing the file contents, or null if file not found
378
- */
379
- async readFile(file, opts) {
380
- return this.withResume(() => this.session.readFile(file, opts), opts?.signal);
381
- }
382
- /**
383
- * Read a file from the filesystem of this sandbox as a Buffer.
384
- *
385
- * @param file - File to read, with path and optional cwd
386
- * @param opts - Optional parameters.
387
- * @param opts.signal - An AbortSignal to cancel the operation.
388
- * @returns A promise that resolves to the file contents as a Buffer, or null if file not found
389
- */
390
- async readFileToBuffer(file, opts) {
391
- return this.withResume(() => this.session.readFileToBuffer(file, opts), opts?.signal);
392
- }
393
- /**
394
- * Download a file from the sandbox to the local filesystem.
395
- *
396
- * @param src - Source file on the sandbox, with path and optional cwd
397
- * @param dst - Destination file on the local machine, with path and optional cwd
398
- * @param opts - Optional parameters.
399
- * @param opts.mkdirRecursive - If true, create parent directories for the destination if they don't exist.
400
- * @param opts.signal - An AbortSignal to cancel the operation.
401
- * @returns The absolute path to the written file, or null if the source file was not found
402
- */
403
- async downloadFile(src, dst, opts) {
404
- return this.withResume(() => this.session.downloadFile(src, dst, opts), opts?.signal);
405
- }
406
- /**
407
- * Write files to the filesystem of this sandbox.
408
- * Defaults to writing to /vercel/sandbox unless an absolute path is specified.
409
- * Writes files using the `vercel-sandbox` user.
410
- *
411
- * @param files - Array of files with path, content, and optional mode (permissions)
412
- * @param opts - Optional parameters.
413
- * @param opts.signal - An AbortSignal to cancel the operation.
414
- * @returns A promise that resolves when the files are written
415
- *
416
- * @example
417
- * // Write an executable script
418
- * await sandbox.writeFiles([
419
- * { path: "/usr/local/bin/myscript", content: Buffer.from("#!/bin/bash\necho hello"), mode: 0o755 }
420
- * ]);
421
- */
422
- async writeFiles(files, opts) {
423
- return this.withResume(() => this.session.writeFiles(files, opts), opts?.signal);
424
- }
425
- /**
426
- * Get the public domain of a port of this sandbox.
427
- *
428
- * @param p - Port number to resolve
429
- * @returns A full domain (e.g. `https://subdomain.vercel.run`)
430
- * @throws If the port has no associated route
431
- */
432
- domain(p) {
433
- return this.session.domain(p);
434
- }
435
- /**
436
- * Stop the sandbox.
437
- *
438
- * @param opts - Optional parameters.
439
- * @param opts.signal - An AbortSignal to cancel the operation.
440
- * @param opts.blocking - If true, poll until the sandbox has fully stopped and return the final state.
441
- * @returns The sandbox at the time the stop was acknowledged, or after fully stopped if `blocking` is true.
442
- */
443
- async stop(opts) {
444
- return this.session.stop(opts);
445
- }
446
- /**
447
- * Update the network policy for this sandbox.
448
- *
449
- * @deprecated Use {@link Sandbox.update} instead.
450
- *
451
- * @param networkPolicy - The new network policy to apply.
452
- * @param opts - Optional parameters.
453
- * @param opts.signal - An AbortSignal to cancel the operation.
454
- * @returns A promise that resolves when the network policy is updated.
455
- *
456
- * @example
457
- * // Restrict to specific domains
458
- * await sandbox.updateNetworkPolicy({
459
- * allow: ["*.npmjs.org", "github.com"],
460
- * });
461
- *
462
- * @example
463
- * // Inject credentials with per-domain transformers
464
- * await sandbox.updateNetworkPolicy({
465
- * allow: {
466
- * "ai-gateway.vercel.sh": [{
467
- * transform: [{
468
- * headers: { authorization: "Bearer ..." }
469
- * }]
470
- * }],
471
- * "*": []
472
- * }
473
- * });
474
- *
475
- * @example
476
- * // Deny all network access
477
- * await sandbox.updateNetworkPolicy("deny-all");
478
- */
479
- async updateNetworkPolicy(networkPolicy, opts) {
480
- await this.withResume(() => this.session.update({ networkPolicy: networkPolicy }, opts), opts?.signal);
481
- return this.session.networkPolicy;
482
- }
483
- /**
484
- * Extend the timeout of the sandbox by the specified duration.
485
- *
486
- * This allows you to extend the lifetime of a sandbox up until the maximum
487
- * execution timeout for your plan.
488
- *
489
- * @param duration - The duration in milliseconds to extend the timeout by
490
- * @param opts - Optional parameters.
491
- * @param opts.signal - An AbortSignal to cancel the operation.
492
- * @returns A promise that resolves when the timeout is extended
493
- *
494
- * @example
495
- * const sandbox = await Sandbox.create({ timeout: ms('10m') });
496
- * // Extends timeout by 5 minutes, to a total of 15 minutes.
497
- * await sandbox.extendTimeout(ms('5m'));
498
- */
499
- async extendTimeout(duration, opts) {
500
- return this.withResume(() => this.session.extendTimeout(duration, opts), opts?.signal);
501
- }
502
- /**
503
- * Create a snapshot from this currently running sandbox. New sandboxes can
504
- * then be created from this snapshot using {@link Sandbox.createFromSnapshot}.
505
- *
506
- * Note: this sandbox will be stopped as part of the snapshot creation process.
507
- *
508
- * @param opts - Optional parameters.
509
- * @param opts.expiration - Optional expiration time in milliseconds. Use 0 for no expiration at all.
510
- * @param opts.signal - An AbortSignal to cancel the operation.
511
- * @returns A promise that resolves to the Snapshot instance
512
- */
513
- async snapshot(opts) {
514
- return this.withResume(() => this.session.snapshot(opts), opts?.signal);
515
- }
516
- /**
517
- * Update the sandbox configuration.
518
- *
519
- * @param params - Fields to update.
520
- * @param opts - Optional abort signal.
521
- */
522
- async update(params, opts) {
523
- let resources;
524
- if (params.resources?.vcpus) {
525
- resources = {
526
- vcpus: params.resources.vcpus,
527
- memory: params.resources.vcpus * 2048,
528
- };
529
- }
530
- // Update the sandbox config. This config will be used on the next session.
531
- const response = await this.client.updateSandbox({
532
- name: this.sandbox.name,
533
- projectId: this.projectId,
534
- persistent: params.persistent,
535
- resources,
536
- timeout: params.timeout,
537
- networkPolicy: params.networkPolicy,
538
- tags: params.tags,
539
- snapshotExpiration: params.snapshotExpiration,
540
- signal: opts?.signal,
541
- });
542
- this.sandbox = response.json.sandbox;
543
- // Update the current session config. This only applies to network policy.
544
- if (params.networkPolicy) {
545
- try {
546
- return await this.session.update({ networkPolicy: params.networkPolicy }, opts);
547
- }
548
- catch (err) {
549
- if (isSandboxStoppedError(err) || isSandboxStoppingError(err)) {
550
- return;
551
- }
552
- throw err;
553
- }
554
- }
555
- }
556
- /**
557
- * Delete this sandbox.
558
- *
559
- * After deletion the instance becomes inert — all further API calls will
560
- * throw immediately.
561
- */
562
- async delete(opts) {
563
- await this.client.deleteSandbox({
564
- name: this.sandbox.name,
565
- projectId: this.projectId,
566
- signal: opts?.signal,
567
- });
568
- }
569
- /**
570
- * List sessions (VMs) that have been created for this sandbox.
571
- *
572
- * @param params - Optional pagination parameters.
573
- * @returns The list of sessions and pagination metadata.
574
- */
575
- async listSessions(params) {
576
- const response = await this.client.listSessions({
577
- projectId: this.projectId,
578
- name: this.sandbox.name,
579
- limit: params?.limit,
580
- cursor: params?.cursor,
581
- sortOrder: params?.sortOrder,
582
- signal: params?.signal,
583
- });
584
- return response.json;
585
- }
586
- /**
587
- * List snapshots that belong to this sandbox.
588
- *
589
- * @param params - Optional pagination parameters.
590
- * @returns The list of snapshots and pagination metadata.
591
- */
592
- async listSnapshots(params) {
593
- const response = await this.client.listSnapshots({
594
- projectId: this.projectId,
595
- name: this.sandbox.name,
596
- limit: params?.limit,
597
- cursor: params?.cursor,
598
- sortOrder: params?.sortOrder,
599
- signal: params?.signal,
600
- });
601
- return response.json;
602
- }
18
+ function isSandboxSnapshottingError(err) {
19
+ return err instanceof APIError && err.response.status === 422 && err.json?.error?.code === "sandbox_snapshotting";
603
20
  }
604
- exports.Sandbox = Sandbox;
605
21
  /**
606
- * A {@link Sandbox} that can automatically be disposed using a `await using` statement.
607
- *
608
- * @example
609
- * {
610
- * await using const sandbox = await Sandbox.create();
611
- * }
612
- * // Sandbox is automatically stopped here
613
- */
614
- class DisposableSandbox extends Sandbox {
615
- async [Symbol.asyncDispose]() {
616
- await this.stop();
617
- }
618
- }
22
+ * A Sandbox is a persistent, isolated Linux MicroVMs to run commands in.
23
+ * Use {@link Sandbox.create} or {@link Sandbox.get} to construct.
24
+ * @hideconstructor
25
+ */
26
+ var Sandbox = class Sandbox {
27
+ /**
28
+ * Lazily resolve credentials and construct an API client.
29
+ * @internal
30
+ */
31
+ async ensureClient() {
32
+ "use step";
33
+ if (this._client) return this._client;
34
+ const credentials = await getCredentials();
35
+ this._client = new APIClient({
36
+ teamId: credentials.teamId,
37
+ token: credentials.token
38
+ });
39
+ return this._client;
40
+ }
41
+ /**
42
+ * The name of this sandbox.
43
+ */
44
+ get name() {
45
+ return this.sandbox.name;
46
+ }
47
+ /**
48
+ * Routes from ports to subdomains.
49
+ * @hidden
50
+ */
51
+ get routes() {
52
+ return this.currentSession().routes;
53
+ }
54
+ /**
55
+ * Whether the sandbox persists the state.
56
+ */
57
+ get persistent() {
58
+ return this.sandbox.persistent;
59
+ }
60
+ /**
61
+ * The region this sandbox runs in.
62
+ */
63
+ get region() {
64
+ return this.sandbox.region;
65
+ }
66
+ /**
67
+ * Number of virtual CPUs allocated.
68
+ */
69
+ get vcpus() {
70
+ return this.sandbox.vcpus;
71
+ }
72
+ /**
73
+ * Memory allocated in MB.
74
+ */
75
+ get memory() {
76
+ return this.sandbox.memory;
77
+ }
78
+ /** Runtime identifier (e.g. "node24", "python3.13"). */
79
+ get runtime() {
80
+ return this.sandbox.runtime;
81
+ }
82
+ /**
83
+ * Cumulative egress bytes across all sessions.
84
+ */
85
+ get totalEgressBytes() {
86
+ return this.sandbox.totalEgressBytes;
87
+ }
88
+ /**
89
+ * Cumulative ingress bytes across all sessions.
90
+ */
91
+ get totalIngressBytes() {
92
+ return this.sandbox.totalIngressBytes;
93
+ }
94
+ /**
95
+ * Cumulative active CPU duration in milliseconds across all sessions.
96
+ */
97
+ get totalActiveCpuDurationMs() {
98
+ return this.sandbox.totalActiveCpuDurationMs;
99
+ }
100
+ /**
101
+ * Cumulative wall-clock duration in milliseconds across all sessions.
102
+ */
103
+ get totalDurationMs() {
104
+ return this.sandbox.totalDurationMs;
105
+ }
106
+ /**
107
+ * When this sandbox was last updated.
108
+ */
109
+ get updatedAt() {
110
+ return new Date(this.sandbox.updatedAt);
111
+ }
112
+ /**
113
+ * When the sandbox status was last updated.
114
+ */
115
+ get statusUpdatedAt() {
116
+ return this.sandbox.statusUpdatedAt ? new Date(this.sandbox.statusUpdatedAt) : void 0;
117
+ }
118
+ /**
119
+ * When this sandbox was created.
120
+ */
121
+ get createdAt() {
122
+ return new Date(this.sandbox.createdAt);
123
+ }
124
+ /**
125
+ * Interactive port.
126
+ */
127
+ get interactivePort() {
128
+ return this.currentSession().interactivePort;
129
+ }
130
+ /**
131
+ * The status of the current session.
132
+ */
133
+ get status() {
134
+ return this.currentSession().status;
135
+ }
136
+ /**
137
+ * The default timeout of this sandbox in milliseconds.
138
+ */
139
+ get timeout() {
140
+ return this.sandbox.timeout;
141
+ }
142
+ /**
143
+ * Key-value tags attached to the sandbox.
144
+ */
145
+ get tags() {
146
+ return this.sandbox.tags;
147
+ }
148
+ /**
149
+ * The default network policy of this sandbox.
150
+ */
151
+ get networkPolicy() {
152
+ return this.sandbox.networkPolicy ? fromAPINetworkPolicy(this.sandbox.networkPolicy) : void 0;
153
+ }
154
+ /**
155
+ * If the session was created from a snapshot, the ID of that snapshot.
156
+ */
157
+ get sourceSnapshotId() {
158
+ return this.currentSession().sourceSnapshotId;
159
+ }
160
+ /**
161
+ * The current snapshot ID of this sandbox, if any.
162
+ */
163
+ get currentSnapshotId() {
164
+ return this.sandbox.currentSnapshotId;
165
+ }
166
+ /**
167
+ * The default snapshot expiration in milliseconds, if set.
168
+ */
169
+ get snapshotExpiration() {
170
+ return this.sandbox.snapshotExpiration;
171
+ }
172
+ /**
173
+ * The amount of CPU used by the session. Only reported once the VM is stopped.
174
+ */
175
+ get activeCpuUsageMs() {
176
+ return this.currentSession().activeCpuUsageMs;
177
+ }
178
+ /**
179
+ * The amount of network data used by the session. Only reported once the VM is stopped.
180
+ */
181
+ get networkTransfer() {
182
+ return this.currentSession().networkTransfer;
183
+ }
184
+ /**
185
+ * Allow to get a list of sandboxes for a team narrowed to the given params.
186
+ * It returns both the sandboxes and the pagination metadata to allow getting
187
+ * the next page of results.
188
+ */
189
+ static async list(params) {
190
+ "use step";
191
+ const credentials = await getCredentials(params);
192
+ return (await new APIClient({
193
+ teamId: credentials.teamId,
194
+ token: credentials.token,
195
+ fetch: params?.fetch
196
+ }).listSandboxes({
197
+ ...credentials,
198
+ ...params
199
+ })).json;
200
+ }
201
+ /**
202
+ * Serialize a Sandbox instance to plain data for @workflow/serde.
203
+ *
204
+ * @param instance - The Sandbox instance to serialize
205
+ * @returns A plain object containing sandbox metadata and routes
206
+ */
207
+ static [WORKFLOW_SERIALIZE](instance) {
208
+ return {
209
+ metadata: instance.session?._sessionSnapshot,
210
+ routes: instance.session?.routes ?? [],
211
+ sandboxMetadata: instance.sandbox,
212
+ projectId: instance.projectId
213
+ };
214
+ }
215
+ /**
216
+ * Deserialize a Sandbox from serialized snapshot data.
217
+ *
218
+ * The deserialized instance uses the serialized metadata synchronously and
219
+ * lazily creates an API client only when methods perform API requests.
220
+ *
221
+ * @param data - The serialized sandbox data
222
+ * @returns The reconstructed Sandbox instance
223
+ */
224
+ static [WORKFLOW_DESERIALIZE](data) {
225
+ const sandbox = new Sandbox({
226
+ sandbox: data.sandboxMetadata,
227
+ routes: data.routes,
228
+ projectId: data.projectId
229
+ });
230
+ if (data.metadata) sandbox.session = new Session({
231
+ routes: data.routes,
232
+ snapshot: data.metadata
233
+ });
234
+ return sandbox;
235
+ }
236
+ /**
237
+ * Create a new sandbox.
238
+ *
239
+ * @param params - Creation parameters and optional credentials.
240
+ * @returns A promise resolving to the created {@link Sandbox}.
241
+ * @example
242
+ * <caption>Create a sandbox with default options</caption>
243
+ * const sandbox = await Sandbox.create();
244
+ *
245
+ * @example
246
+ * <caption>Create a sandbox and drop it in the end of the block</caption>
247
+ * async function fn() {
248
+ * await using const sandbox = await Sandbox.create();
249
+ * // Sandbox automatically stopped at the end of the lexical scope
250
+ * }
251
+ */
252
+ static async create(params) {
253
+ "use step";
254
+ const credentials = await getCredentials(params);
255
+ const client = new APIClient({
256
+ teamId: credentials.teamId,
257
+ token: credentials.token,
258
+ fetch: params?.fetch
259
+ });
260
+ const privateParams = getPrivateParams(params);
261
+ const response = await client.createSandbox({
262
+ source: params?.source,
263
+ projectId: credentials.projectId,
264
+ ports: params?.ports ?? [],
265
+ timeout: params?.timeout,
266
+ resources: params?.resources,
267
+ runtime: params && "runtime" in params ? params?.runtime : void 0,
268
+ networkPolicy: params?.networkPolicy,
269
+ env: params?.env,
270
+ tags: params?.tags,
271
+ snapshotExpiration: params?.snapshotExpiration,
272
+ signal: params?.signal,
273
+ name: params?.name,
274
+ persistent: params?.persistent,
275
+ ...privateParams
276
+ });
277
+ return new DisposableSandbox({
278
+ client,
279
+ session: response.json.session,
280
+ sandbox: response.json.sandbox,
281
+ routes: response.json.routes,
282
+ projectId: credentials.projectId
283
+ });
284
+ }
285
+ /**
286
+ * Retrieve an existing sandbox and resume its session.
287
+ *
288
+ * @param params - Get parameters and optional credentials.
289
+ * @returns A promise resolving to the {@link Sandbox}.
290
+ */
291
+ static async get(params) {
292
+ "use step";
293
+ const credentials = await getCredentials(params);
294
+ const client = new APIClient({
295
+ teamId: credentials.teamId,
296
+ token: credentials.token,
297
+ fetch: params.fetch
298
+ });
299
+ const privateParams = getPrivateParams(params);
300
+ const response = await client.getSandbox({
301
+ name: params.name,
302
+ projectId: credentials.projectId,
303
+ resume: params.resume,
304
+ signal: params.signal,
305
+ ...privateParams
306
+ });
307
+ return new Sandbox({
308
+ client,
309
+ session: response.json.session,
310
+ sandbox: response.json.sandbox,
311
+ routes: response.json.routes,
312
+ projectId: credentials.projectId
313
+ });
314
+ }
315
+ /**
316
+ * Create a new Sandbox instance.
317
+ *
318
+ * @param params.client - Optional API client. If not provided, will be lazily created using global credentials.
319
+ * @param params.routes - Port-to-subdomain mappings for exposed ports
320
+ * @param params.sandbox - Sandbox snapshot metadata
321
+ */
322
+ constructor({ client, routes, session, sandbox, projectId }) {
323
+ this._client = null;
324
+ this.resumePromise = null;
325
+ this._client = client ?? null;
326
+ if (session) this.session = new Session({
327
+ client,
328
+ routes,
329
+ session
330
+ });
331
+ this.sandbox = sandbox;
332
+ this.projectId = projectId ?? "";
333
+ }
334
+ /**
335
+ * Get the current session (the running VM) for this sandbox.
336
+ *
337
+ * @returns The {@link Session} instance.
338
+ */
339
+ currentSession() {
340
+ if (!this.session) throw new Error("No active session. Run a command or call resume first.");
341
+ return this.session;
342
+ }
343
+ /**
344
+ * Resume this sandbox by creating a new session via `getSandbox`.
345
+ */
346
+ async resume(signal) {
347
+ if (!this.resumePromise) this.resumePromise = this.doResume(signal).finally(() => {
348
+ this.resumePromise = null;
349
+ });
350
+ return this.resumePromise;
351
+ }
352
+ async doResume(signal) {
353
+ const client = await this.ensureClient();
354
+ const response = await client.getSandbox({
355
+ name: this.sandbox.name,
356
+ projectId: this.projectId,
357
+ resume: true,
358
+ signal
359
+ });
360
+ this.session = new Session({
361
+ client,
362
+ routes: response.json.routes,
363
+ session: response.json.session
364
+ });
365
+ }
366
+ /**
367
+ * Poll until the current session reaches a terminal state, then resume.
368
+ */
369
+ async waitForStopAndResume(signal) {
370
+ "use step";
371
+ const client = await this.ensureClient();
372
+ const pollingInterval = 500;
373
+ let status = this.session.status;
374
+ while (status === "stopping" || status === "snapshotting") {
375
+ await setTimeout(pollingInterval, void 0, { signal });
376
+ const poll = await client.getSession({
377
+ sessionId: this.session.sessionId,
378
+ signal
379
+ });
380
+ this.session = new Session({
381
+ client,
382
+ routes: poll.json.routes,
383
+ session: poll.json.session
384
+ });
385
+ status = poll.json.session.status;
386
+ }
387
+ await this.resume(signal);
388
+ }
389
+ /**
390
+ * Execute `fn`, and if the session is stopped/stopping/snapshotting, resume and retry.
391
+ */
392
+ async withResume(fn, signal) {
393
+ if (!this.session) await this.resume(signal);
394
+ try {
395
+ return await fn();
396
+ } catch (err) {
397
+ if (isSandboxStoppedError(err)) {
398
+ await this.resume(signal);
399
+ return fn();
400
+ }
401
+ if (isSandboxStoppingError(err) || isSandboxSnapshottingError(err)) {
402
+ await this.waitForStopAndResume(signal);
403
+ return fn();
404
+ }
405
+ throw err;
406
+ }
407
+ }
408
+ async runCommand(commandOrParams, args, opts) {
409
+ "use step";
410
+ const signal = typeof commandOrParams === "string" ? opts?.signal : commandOrParams.signal;
411
+ return this.withResume(() => this.session.runCommand(commandOrParams, args, opts), signal);
412
+ }
413
+ /**
414
+ * Internal helper to start a command in the sandbox.
415
+ *
416
+ * @param params - Command execution parameters.
417
+ * @returns A {@link Command} or {@link CommandFinished}, depending on `detached`.
418
+ * @internal
419
+ */
420
+ async getCommand(cmdId, opts) {
421
+ "use step";
422
+ return this.withResume(() => this.session.getCommand(cmdId, opts), opts?.signal);
423
+ }
424
+ /**
425
+ * Create a directory in the filesystem of this sandbox.
426
+ *
427
+ * @param path - Path of the directory to create
428
+ * @param opts - Optional parameters.
429
+ * @param opts.signal - An AbortSignal to cancel the operation.
430
+ */
431
+ async mkDir(path, opts) {
432
+ "use step";
433
+ return this.withResume(() => this.session.mkDir(path, opts), opts?.signal);
434
+ }
435
+ /**
436
+ * Read a file from the filesystem of this sandbox as a stream.
437
+ *
438
+ * @param file - File to read, with path and optional cwd
439
+ * @param opts - Optional parameters.
440
+ * @param opts.signal - An AbortSignal to cancel the operation.
441
+ * @returns A promise that resolves to a ReadableStream containing the file contents, or null if file not found
442
+ */
443
+ async readFile(file, opts) {
444
+ "use step";
445
+ return this.withResume(() => this.session.readFile(file, opts), opts?.signal);
446
+ }
447
+ /**
448
+ * Read a file from the filesystem of this sandbox as a Buffer.
449
+ *
450
+ * @param file - File to read, with path and optional cwd
451
+ * @param opts - Optional parameters.
452
+ * @param opts.signal - An AbortSignal to cancel the operation.
453
+ * @returns A promise that resolves to the file contents as a Buffer, or null if file not found
454
+ */
455
+ async readFileToBuffer(file, opts) {
456
+ "use step";
457
+ return this.withResume(() => this.session.readFileToBuffer(file, opts), opts?.signal);
458
+ }
459
+ /**
460
+ * Download a file from the sandbox to the local filesystem.
461
+ *
462
+ * @param src - Source file on the sandbox, with path and optional cwd
463
+ * @param dst - Destination file on the local machine, with path and optional cwd
464
+ * @param opts - Optional parameters.
465
+ * @param opts.mkdirRecursive - If true, create parent directories for the destination if they don't exist.
466
+ * @param opts.signal - An AbortSignal to cancel the operation.
467
+ * @returns The absolute path to the written file, or null if the source file was not found
468
+ */
469
+ async downloadFile(src, dst, opts) {
470
+ "use step";
471
+ return this.withResume(() => this.session.downloadFile(src, dst, opts), opts?.signal);
472
+ }
473
+ /**
474
+ * Write files to the filesystem of this sandbox.
475
+ * Defaults to writing to /vercel/sandbox unless an absolute path is specified.
476
+ * Writes files using the `vercel-sandbox` user.
477
+ *
478
+ * @param files - Array of files with path, content, and optional mode (permissions)
479
+ * @param opts - Optional parameters.
480
+ * @param opts.signal - An AbortSignal to cancel the operation.
481
+ * @returns A promise that resolves when the files are written
482
+ *
483
+ * @example
484
+ * // Write an executable script
485
+ * await sandbox.writeFiles([
486
+ * { path: "/usr/local/bin/myscript", content: "#!/bin/bash\necho hello", mode: 0o755 }
487
+ * ]);
488
+ */
489
+ async writeFiles(files, opts) {
490
+ "use step";
491
+ return this.withResume(() => this.session.writeFiles(files, opts), opts?.signal);
492
+ }
493
+ /**
494
+ * Get the public domain of a port of this sandbox.
495
+ *
496
+ * @param p - Port number to resolve
497
+ * @returns A full domain (e.g. `https://subdomain.vercel.run`)
498
+ * @throws If the port has no associated route
499
+ */
500
+ domain(p) {
501
+ return this.currentSession().domain(p);
502
+ }
503
+ /**
504
+ * Stop the sandbox.
505
+ *
506
+ * @param opts - Optional parameters.
507
+ * @param opts.signal - An AbortSignal to cancel the operation.
508
+ * @param opts.blocking - If true, poll until the sandbox has fully stopped and return the final state.
509
+ * @returns The sandbox at the time the stop was acknowledged, or after fully stopped if `blocking` is true.
510
+ */
511
+ async stop(opts) {
512
+ "use step";
513
+ if (!this.session) throw new Error("No active session to stop.");
514
+ return this.session.stop(opts);
515
+ }
516
+ /**
517
+ * Update the network policy for this sandbox.
518
+ *
519
+ * @deprecated Use {@link Sandbox.update} instead.
520
+ *
521
+ * @param networkPolicy - The new network policy to apply.
522
+ * @param opts - Optional parameters.
523
+ * @param opts.signal - An AbortSignal to cancel the operation.
524
+ * @returns A promise that resolves when the network policy is updated.
525
+ *
526
+ * @example
527
+ * // Restrict to specific domains
528
+ * await sandbox.updateNetworkPolicy({
529
+ * allow: ["*.npmjs.org", "github.com"],
530
+ * });
531
+ *
532
+ * @example
533
+ * // Inject credentials with per-domain transformers
534
+ * await sandbox.updateNetworkPolicy({
535
+ * allow: {
536
+ * "ai-gateway.vercel.sh": [{
537
+ * transform: [{
538
+ * headers: { authorization: "Bearer ..." }
539
+ * }]
540
+ * }],
541
+ * "*": []
542
+ * }
543
+ * });
544
+ *
545
+ * @example
546
+ * // Deny all network access
547
+ * await sandbox.updateNetworkPolicy("deny-all");
548
+ */
549
+ async updateNetworkPolicy(networkPolicy, opts) {
550
+ "use step";
551
+ await this.withResume(() => this.session.update({ networkPolicy }, opts), opts?.signal);
552
+ return this.session.networkPolicy;
553
+ }
554
+ /**
555
+ * Extend the timeout of the sandbox by the specified duration.
556
+ *
557
+ * This allows you to extend the lifetime of a sandbox up until the maximum
558
+ * execution timeout for your plan.
559
+ *
560
+ * @param duration - The duration in milliseconds to extend the timeout by
561
+ * @param opts - Optional parameters.
562
+ * @param opts.signal - An AbortSignal to cancel the operation.
563
+ * @returns A promise that resolves when the timeout is extended
564
+ *
565
+ * @example
566
+ * const sandbox = await Sandbox.create({ timeout: ms('10m') });
567
+ * // Extends timeout by 5 minutes, to a total of 15 minutes.
568
+ * await sandbox.extendTimeout(ms('5m'));
569
+ */
570
+ async extendTimeout(duration, opts) {
571
+ "use step";
572
+ return this.withResume(() => this.session.extendTimeout(duration, opts), opts?.signal);
573
+ }
574
+ /**
575
+ * Create a snapshot from this currently running sandbox. New sandboxes can
576
+ * then be created from this snapshot using {@link Sandbox.createFromSnapshot}.
577
+ *
578
+ * Note: this sandbox will be stopped as part of the snapshot creation process.
579
+ *
580
+ * @param opts - Optional parameters.
581
+ * @param opts.expiration - Optional expiration time in milliseconds. Use 0 for no expiration at all.
582
+ * @param opts.signal - An AbortSignal to cancel the operation.
583
+ * @returns A promise that resolves to the Snapshot instance
584
+ */
585
+ async snapshot(opts) {
586
+ "use step";
587
+ return this.withResume(() => this.session.snapshot(opts), opts?.signal);
588
+ }
589
+ /**
590
+ * Update the sandbox configuration.
591
+ *
592
+ * @param params - Fields to update.
593
+ * @param opts - Optional abort signal.
594
+ */
595
+ async update(params, opts) {
596
+ "use step";
597
+ const client = await this.ensureClient();
598
+ let resources;
599
+ if (params.resources?.vcpus) resources = {
600
+ vcpus: params.resources.vcpus,
601
+ memory: params.resources.vcpus * 2048
602
+ };
603
+ this.sandbox = (await client.updateSandbox({
604
+ name: this.sandbox.name,
605
+ projectId: this.projectId,
606
+ persistent: params.persistent,
607
+ resources,
608
+ timeout: params.timeout,
609
+ networkPolicy: params.networkPolicy,
610
+ tags: params.tags,
611
+ snapshotExpiration: params.snapshotExpiration,
612
+ signal: opts?.signal
613
+ })).json.sandbox;
614
+ if (params.networkPolicy) try {
615
+ return await this.session?.update({ networkPolicy: params.networkPolicy }, opts);
616
+ } catch (err) {
617
+ if (isSandboxStoppedError(err) || isSandboxStoppingError(err)) return;
618
+ throw err;
619
+ }
620
+ }
621
+ /**
622
+ * Delete this sandbox.
623
+ *
624
+ * After deletion the instance becomes inert — all further API calls will
625
+ * throw immediately.
626
+ */
627
+ async delete(opts) {
628
+ "use step";
629
+ await (await this.ensureClient()).deleteSandbox({
630
+ name: this.sandbox.name,
631
+ projectId: this.projectId,
632
+ signal: opts?.signal
633
+ });
634
+ }
635
+ /**
636
+ * List sessions (VMs) that have been created for this sandbox.
637
+ *
638
+ * @param params - Optional pagination parameters.
639
+ * @returns The list of sessions and pagination metadata.
640
+ */
641
+ async listSessions(params) {
642
+ "use step";
643
+ return (await (await this.ensureClient()).listSessions({
644
+ projectId: this.projectId,
645
+ name: this.sandbox.name,
646
+ limit: params?.limit,
647
+ cursor: params?.cursor,
648
+ sortOrder: params?.sortOrder,
649
+ signal: params?.signal
650
+ })).json;
651
+ }
652
+ /**
653
+ * List snapshots that belong to this sandbox.
654
+ *
655
+ * @param params - Optional pagination parameters.
656
+ * @returns The list of snapshots and pagination metadata.
657
+ */
658
+ async listSnapshots(params) {
659
+ "use step";
660
+ return (await (await this.ensureClient()).listSnapshots({
661
+ projectId: this.projectId,
662
+ name: this.sandbox.name,
663
+ limit: params?.limit,
664
+ cursor: params?.cursor,
665
+ sortOrder: params?.sortOrder,
666
+ signal: params?.signal
667
+ })).json;
668
+ }
669
+ };
670
+ /**
671
+ * A {@link Sandbox} that can automatically be disposed using a `await using` statement.
672
+ *
673
+ * @example
674
+ * {
675
+ * await using const sandbox = await Sandbox.create();
676
+ * }
677
+ * // Sandbox is automatically stopped here
678
+ */
679
+ var DisposableSandbox = class extends Sandbox {
680
+ async [Symbol.asyncDispose]() {
681
+ await this.stop();
682
+ }
683
+ };
684
+
685
+ //#endregion
686
+ export { Sandbox };
619
687
  //# sourceMappingURL=sandbox.js.map