@vercel/sandbox 2.0.0-beta.2 → 2.0.0-beta.20

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