eve 0.46.1 → 0.47.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 (124) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/src/channel/schedule.d.ts +1 -0
  3. package/dist/src/channel/schedule.js +1 -1
  4. package/dist/src/compiled/.vendor-stamp.json +2 -1
  5. package/dist/src/compiled/@vercel/sandbox/index.js +9 -15
  6. package/dist/src/compiled/@vercel/sandbox-delete/LICENSE +201 -0
  7. package/dist/src/compiled/@vercel/sandbox-delete/_async-retry.d.ts +8 -0
  8. package/dist/src/compiled/@vercel/sandbox-delete/_workflow-serde.d.ts +5 -0
  9. package/dist/src/compiled/@vercel/sandbox-delete/api-client/api-client.d.ts +1730 -0
  10. package/dist/src/compiled/@vercel/sandbox-delete/api-client/api-error.d.ts +29 -0
  11. package/dist/src/compiled/@vercel/sandbox-delete/api-client/base-client.d.ts +39 -0
  12. package/dist/src/compiled/@vercel/sandbox-delete/api-client/file-writer.d.ts +66 -0
  13. package/dist/src/compiled/@vercel/sandbox-delete/api-client/index.d.ts +2 -0
  14. package/dist/src/compiled/@vercel/sandbox-delete/api-client/validators.d.ts +907 -0
  15. package/dist/src/compiled/@vercel/sandbox-delete/api-client/with-retry.d.ts +10 -0
  16. package/dist/src/compiled/@vercel/sandbox-delete/auth/error.d.ts +15 -0
  17. package/dist/src/compiled/@vercel/sandbox-delete/auth/file.d.ts +18 -0
  18. package/dist/src/compiled/@vercel/sandbox-delete/auth/index.d.ts +6 -0
  19. package/dist/src/compiled/@vercel/sandbox-delete/auth/oauth.d.ts +111 -0
  20. package/dist/src/compiled/@vercel/sandbox-delete/auth/poll-for-token.d.ts +28 -0
  21. package/dist/src/compiled/@vercel/sandbox-delete/auth/project.d.ts +40 -0
  22. package/dist/src/compiled/@vercel/sandbox-delete/command.d.ts +292 -0
  23. package/dist/src/compiled/@vercel/sandbox-delete/constants.d.ts +15 -0
  24. package/dist/src/compiled/@vercel/sandbox-delete/execution-context.d.ts +116 -0
  25. package/dist/src/compiled/@vercel/sandbox-delete/filesystem.d.ts +258 -0
  26. package/dist/src/compiled/@vercel/sandbox-delete/index.d.ts +13 -0
  27. package/dist/src/compiled/@vercel/sandbox-delete/index.js +9 -0
  28. package/dist/src/compiled/@vercel/sandbox-delete/network-policy.d.ts +169 -0
  29. package/dist/src/compiled/@vercel/sandbox-delete/proxy.d.ts +55 -0
  30. package/dist/src/compiled/@vercel/sandbox-delete/sandbox-user.d.ts +211 -0
  31. package/dist/src/compiled/@vercel/sandbox-delete/sandbox.d.ts +1258 -0
  32. package/dist/src/compiled/@vercel/sandbox-delete/session.d.ts +435 -0
  33. package/dist/src/compiled/@vercel/sandbox-delete/snapshot.d.ts +238 -0
  34. package/dist/src/compiled/@vercel/sandbox-delete/utils/get-credentials.d.ts +21 -0
  35. package/dist/src/compiled/@vercel/sandbox-delete/utils/paginator.d.ts +16 -0
  36. package/dist/src/compiled/@vercel/sandbox-delete/utils/resolveSignal.d.ts +15 -0
  37. package/dist/src/compiled/@vercel/sandbox-delete/utils/sandbox-snapshot.d.ts +11 -0
  38. package/dist/src/compiled/@vercel/sandbox-delete/utils/types.d.ts +11 -0
  39. package/dist/src/compiled/_chunks/node/auth-DpzFWvTn.js +2 -0
  40. package/dist/src/compiled/_chunks/node/auth-QgeX8nBM.js +2 -0
  41. package/dist/src/compiled/_chunks/node/decode_jwt-Col8JOnf.js +7 -0
  42. package/dist/src/compiled/_chunks/node/version-DH6yRy-M.js +1 -0
  43. package/dist/src/compiled/_chunks/node/xdg-app-paths-Bys8q02u.js +1 -0
  44. package/dist/src/compiler/extension-compatibility.d.ts +12 -12
  45. package/dist/src/compiler/extension-compatibility.js +1 -1
  46. package/dist/src/compiler/model-catalog.js +1 -1
  47. package/dist/src/context/build-callback-context.js +1 -1
  48. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  49. package/dist/src/context/keys.d.ts +2 -0
  50. package/dist/src/context/keys.js +1 -1
  51. package/dist/src/context/memory-tools.js +1 -1
  52. package/dist/src/context/providers/sandbox.js +1 -1
  53. package/dist/src/evals/context.js +1 -1
  54. package/dist/src/evals/session-content.d.ts +5 -0
  55. package/dist/src/evals/session-content.js +3 -0
  56. package/dist/src/evals/session.d.ts +1 -0
  57. package/dist/src/evals/session.js +1 -1
  58. package/dist/src/evals/types.d.ts +5 -0
  59. package/dist/src/execution/dispatch-runtime-actions-shared.js +1 -1
  60. package/dist/src/execution/eve-workflow-attributes.d.ts +3 -0
  61. package/dist/src/execution/eve-workflow-attributes.js +1 -1
  62. package/dist/src/execution/runtime-context.js +1 -1
  63. package/dist/src/execution/sandbox/bindings/docker-base-setup.d.ts +4 -4
  64. package/dist/src/execution/sandbox/bindings/docker-base-setup.js +1 -1
  65. package/dist/src/execution/sandbox/bindings/docker-session.d.ts +1 -1
  66. package/dist/src/execution/sandbox/bindings/docker-session.js +1 -1
  67. package/dist/src/execution/sandbox/bindings/docker.js +1 -1
  68. package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
  69. package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.js +1 -1
  70. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
  71. package/dist/src/execution/sandbox/bindings/vercel-base-runtime.d.ts +4 -0
  72. package/dist/src/execution/sandbox/bindings/vercel-base-runtime.js +2 -2
  73. package/dist/src/execution/sandbox/bindings/vercel-lifecycle.d.ts +8 -0
  74. package/dist/src/execution/sandbox/bindings/vercel-lifecycle.js +1 -0
  75. package/dist/src/execution/sandbox/bindings/vercel-sdk-types.d.ts +3 -0
  76. package/dist/src/execution/sandbox/bindings/vercel.d.ts +2 -1
  77. package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
  78. package/dist/src/execution/sandbox/ensure.d.ts +2 -0
  79. package/dist/src/execution/sandbox/ensure.js +1 -1
  80. package/dist/src/execution/sandbox/require-sandbox.js +1 -1
  81. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  82. package/dist/src/execution/tools/connection-search.js +2 -2
  83. package/dist/src/execution/tools/file-state.js +1 -1
  84. package/dist/src/execution/tools/load-skill.js +1 -1
  85. package/dist/src/execution/tools/subagent/local.js +1 -1
  86. package/dist/src/execution/workflow-steps.js +1 -1
  87. package/dist/src/harness/approval-delivery-coordinator.js +1 -1
  88. package/dist/src/harness/attachment-staging.js +1 -1
  89. package/dist/src/harness/authorization.js +1 -1
  90. package/dist/src/harness/current-messages.d.ts +15 -0
  91. package/dist/src/harness/current-messages.js +1 -0
  92. package/dist/src/harness/instrumentation/runtime-context.js +1 -1
  93. package/dist/src/harness/instrumentation/state.js +1 -1
  94. package/dist/src/harness/step-hooks.js +1 -1
  95. package/dist/src/harness/tool-loop.js +2 -2
  96. package/dist/src/harness/tools.js +1 -1
  97. package/dist/src/internal/application/package.js +1 -1
  98. package/dist/src/internal/model-catalog.js +1 -1
  99. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  100. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
  101. package/dist/src/public/definitions/sandbox-backend.d.ts +1 -1
  102. package/dist/src/public/sandbox/index.d.ts +1 -1
  103. package/dist/src/runtime/agent/resolve-model.js +1 -1
  104. package/dist/src/runtime/connections/principal.js +1 -1
  105. package/dist/src/sandbox/state.d.ts +2 -0
  106. package/dist/src/setup/scaffold/create/project.js +1 -1
  107. package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
  108. package/dist/src/setup/scaffold/create/web-template.js +4 -2
  109. package/dist/src/shared/sandbox-backend.d.ts +9 -0
  110. package/dist/src/shared/sandbox-definition.d.ts +5 -4
  111. package/dist/src/shared/sandbox-session.d.ts +4 -1
  112. package/dist/src/tasks/delivery-policy.d.ts +12 -0
  113. package/dist/src/tasks/delivery-policy.js +1 -0
  114. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  115. package/docs/evals/cases.mdx +11 -2
  116. package/docs/evals/judge.mdx +15 -0
  117. package/docs/evals/overview.mdx +2 -2
  118. package/docs/guides/instrumentation.md +1 -0
  119. package/docs/guides/session-context.md +2 -2
  120. package/docs/sandbox.mdx +25 -2
  121. package/docs/schedules.mdx +2 -0
  122. package/docs/tools/overview.mdx +2 -0
  123. package/package.json +2 -1
  124. package/dist/src/compiled/_chunks/node/auth-BaNbsImr.js +0 -2
@@ -0,0 +1,258 @@
1
+ import { Dirent, Stats } from "fs";
2
+
3
+ //#region src/filesystem.d.ts
4
+ type WriteFileData = string | Buffer | Uint8Array;
5
+ interface MkdirOptions {
6
+ recursive?: boolean;
7
+ signal?: AbortSignal;
8
+ }
9
+ interface RmOptions {
10
+ recursive?: boolean;
11
+ force?: boolean;
12
+ signal?: AbortSignal;
13
+ }
14
+ interface SandboxHandle {
15
+ readFileToBuffer(file: {
16
+ path: string;
17
+ }, opts?: {
18
+ signal?: AbortSignal;
19
+ }): Promise<Buffer | null>;
20
+ writeFiles(files: {
21
+ path: string;
22
+ content: Buffer;
23
+ }[], opts?: {
24
+ signal?: AbortSignal;
25
+ }): Promise<void>;
26
+ mkDir(path: string, opts?: {
27
+ signal?: AbortSignal;
28
+ }): Promise<void>;
29
+ runCommand(cmd: string, args?: string[], opts?: {
30
+ signal?: AbortSignal;
31
+ }): Promise<{
32
+ exitCode: number;
33
+ stdout(opts?: {
34
+ signal?: AbortSignal;
35
+ }): Promise<string>;
36
+ stderr(opts?: {
37
+ signal?: AbortSignal;
38
+ }): Promise<string>;
39
+ }>;
40
+ }
41
+ declare class FileSystem {
42
+ /** @internal */
43
+ private sandbox;
44
+ /** @internal */
45
+ constructor(sandbox: SandboxHandle);
46
+ /**
47
+ * Read the entire contents of a file.
48
+ *
49
+ * @param path - Path to the file
50
+ * @param options - Encoding or options object. If encoding is specified, returns a string; otherwise returns a Buffer.
51
+ */
52
+ readFile(path: string, options?: {
53
+ encoding?: null;
54
+ signal?: AbortSignal;
55
+ } | null): Promise<Buffer>;
56
+ readFile(path: string, options: {
57
+ encoding: BufferEncoding;
58
+ signal?: AbortSignal;
59
+ } | BufferEncoding): Promise<string>;
60
+ /**
61
+ * Write data to a file, replacing the file if it already exists.
62
+ *
63
+ * @param path - Path to the file
64
+ * @param data - The data to write
65
+ * @param options - Write options
66
+ */
67
+ writeFile(path: string, data: WriteFileData, options?: {
68
+ encoding?: BufferEncoding;
69
+ signal?: AbortSignal;
70
+ } | BufferEncoding): Promise<void>;
71
+ /**
72
+ * Append data to a file, creating the file if it does not yet exist.
73
+ *
74
+ * @param path - Path to the file
75
+ * @param data - The data to append
76
+ * @param options - Write options
77
+ */
78
+ appendFile(path: string, data: WriteFileData, options?: {
79
+ encoding?: BufferEncoding;
80
+ signal?: AbortSignal;
81
+ } | BufferEncoding): Promise<void>;
82
+ /**
83
+ * Create a directory.
84
+ *
85
+ * @param path - Path of the directory to create
86
+ * @param options - Options for directory creation
87
+ */
88
+ mkdir(path: string, options?: MkdirOptions | number): Promise<string | undefined>;
89
+ /**
90
+ * Read the contents of a directory.
91
+ *
92
+ * @param path - Path to the directory
93
+ * @param options - Options. When `withFileTypes` is true, returns `Dirent` objects.
94
+ */
95
+ readdir(path: string, options?: {
96
+ signal?: AbortSignal;
97
+ withFileTypes?: false;
98
+ }): Promise<string[]>;
99
+ readdir(path: string, options: {
100
+ signal?: AbortSignal;
101
+ withFileTypes: true;
102
+ }): Promise<Dirent[]>;
103
+ /**
104
+ * Get file status. Follows symbolic links.
105
+ *
106
+ * @param path - Path to the file
107
+ * @param options - Options
108
+ */
109
+ stat(path: string, options?: {
110
+ signal?: AbortSignal;
111
+ }): Promise<Stats>;
112
+ /**
113
+ * Get file status. Does not follow symbolic links.
114
+ *
115
+ * @param path - Path to the file
116
+ * @param options - Options
117
+ */
118
+ lstat(path: string, options?: {
119
+ signal?: AbortSignal;
120
+ }): Promise<Stats>;
121
+ /**
122
+ * Remove a file or symbolic link.
123
+ *
124
+ * @param path - Path to the file
125
+ * @param options - Options
126
+ */
127
+ unlink(path: string, options?: {
128
+ signal?: AbortSignal;
129
+ }): Promise<void>;
130
+ /**
131
+ * Remove files and directories.
132
+ *
133
+ * @param path - Path to remove
134
+ * @param options - Options
135
+ */
136
+ rm(path: string, options?: RmOptions): Promise<void>;
137
+ /**
138
+ * Remove a directory.
139
+ *
140
+ * @param path - Path to the directory
141
+ * @param options - Options
142
+ */
143
+ rmdir(path: string, options?: {
144
+ signal?: AbortSignal;
145
+ }): Promise<void>;
146
+ /**
147
+ * Rename a file or directory.
148
+ *
149
+ * @param oldPath - Current path
150
+ * @param newPath - New path
151
+ * @param options - Options
152
+ */
153
+ rename(oldPath: string, newPath: string, options?: {
154
+ signal?: AbortSignal;
155
+ }): Promise<void>;
156
+ /**
157
+ * Copy a file.
158
+ *
159
+ * @param src - Source path
160
+ * @param dest - Destination path
161
+ * @param options - Options
162
+ */
163
+ copyFile(src: string, dest: string, options?: {
164
+ signal?: AbortSignal;
165
+ }): Promise<void>;
166
+ /**
167
+ * Test whether a file exists and the user has the specified permissions.
168
+ *
169
+ * @param path - Path to the file
170
+ * @param options - Options
171
+ */
172
+ access(path: string, options?: {
173
+ signal?: AbortSignal;
174
+ }): Promise<void>;
175
+ /**
176
+ * Check if a path exists.
177
+ *
178
+ * This is a convenience method not in `node:fs/promises` but commonly needed.
179
+ *
180
+ * @param path - Path to check
181
+ * @param options - Options
182
+ */
183
+ exists(path: string, options?: {
184
+ signal?: AbortSignal;
185
+ }): Promise<boolean>;
186
+ /**
187
+ * Change file mode (permissions).
188
+ *
189
+ * @param path - Path to the file
190
+ * @param mode - File mode (e.g., 0o755 or "755")
191
+ * @param options - Options
192
+ */
193
+ chmod(path: string, mode: number | string, options?: {
194
+ signal?: AbortSignal;
195
+ }): Promise<void>;
196
+ /**
197
+ * Change file owner and group.
198
+ *
199
+ * @param path - Path to the file
200
+ * @param uid - User ID
201
+ * @param gid - Group ID
202
+ * @param options - Options
203
+ */
204
+ chown(path: string, uid: number, gid: number, options?: {
205
+ signal?: AbortSignal;
206
+ }): Promise<void>;
207
+ /**
208
+ * Create a symbolic link.
209
+ *
210
+ * @param target - The target of the symbolic link
211
+ * @param path - The path of the symbolic link to create
212
+ * @param options - Options
213
+ */
214
+ symlink(target: string, path: string, options?: {
215
+ signal?: AbortSignal;
216
+ }): Promise<void>;
217
+ /**
218
+ * Read the value of a symbolic link.
219
+ *
220
+ * @param path - Path to the symbolic link
221
+ * @param options - Options
222
+ */
223
+ readlink(path: string, options?: {
224
+ signal?: AbortSignal;
225
+ }): Promise<string>;
226
+ /**
227
+ * Resolve the real path of a file (resolving symlinks).
228
+ *
229
+ * @param path - Path to resolve
230
+ * @param options - Options
231
+ */
232
+ realpath(path: string, options?: {
233
+ signal?: AbortSignal;
234
+ }): Promise<string>;
235
+ /**
236
+ * Truncate a file to a specified length.
237
+ *
238
+ * @param path - Path to the file
239
+ * @param len - Length to truncate to (default: 0)
240
+ * @param options - Options
241
+ */
242
+ truncate(path: string, len?: number, options?: {
243
+ signal?: AbortSignal;
244
+ }): Promise<void>;
245
+ /**
246
+ * Create a unique temporary directory.
247
+ *
248
+ * @param prefix - The prefix for the temporary directory name
249
+ * @param options - Options
250
+ * @returns The path of the created temporary directory
251
+ */
252
+ mkdtemp(prefix: string, options?: {
253
+ signal?: AbortSignal;
254
+ }): Promise<string>;
255
+ }
256
+ //#endregion
257
+ export { FileSystem };
258
+ //# sourceMappingURL=filesystem.d.ts.map
@@ -0,0 +1,13 @@
1
+ import { APIError, StreamError } from "./api-client/api-error.js";
2
+ import { SnapshotTreeNodeData } from "./api-client/validators.js";
3
+ import { NetworkPolicy, NetworkPolicyKeyValueMatcher, NetworkPolicyMatch, NetworkPolicyMatcher, NetworkPolicyRule, NetworkTransformer } from "./network-policy.js";
4
+ import { DEFAULT_SANDBOX_REGION, SandboxRegion } from "./constants.js";
5
+ import { Command, CommandFinished, CommandOutput, SerializedCommand, SerializedCommandFinished } from "./command.js";
6
+ import { SerializedSnapshot, Snapshot } from "./snapshot.js";
7
+ import { ExecutionContext } from "./execution-context.js";
8
+ import { Session } from "./session.js";
9
+ import { FileSystem } from "./filesystem.js";
10
+ import { SandboxUser, SandboxUserAlreadyExistsError } from "./sandbox-user.js";
11
+ import { Sandbox, SerializedSandbox } from "./sandbox.js";
12
+ import { InvalidRequestProxyHandler, ProxyHandler, ProxyMeta, defineSandboxProxy } from "./proxy.js";
13
+ export { APIError, Command, CommandFinished, type CommandOutput, DEFAULT_SANDBOX_REGION, type ExecutionContext, FileSystem, type InvalidRequestProxyHandler, type NetworkPolicy, type NetworkPolicyKeyValueMatcher, type NetworkPolicyMatch, type NetworkPolicyMatcher, type NetworkPolicyRule, type NetworkTransformer, type ProxyHandler, type ProxyMeta, Sandbox, type SandboxRegion, SandboxUser, SandboxUserAlreadyExistsError, type SerializedCommand, type SerializedCommandFinished, type SerializedSandbox, type SerializedSnapshot, Session, Snapshot, type SnapshotTreeNodeData, StreamError, defineSandboxProxy };
@@ -0,0 +1,9 @@
1
+ import{o as e}from"../../_chunks/node/rolldown-runtime-DaDcL9Zw.js";import{n as t,t as n}from"../../_chunks/node/dist-DsNhwdzf.js";import{n as r}from"../../_chunks/node/retry-qwFNGj4P.js";import{At as i,Bt as a,Et as o,Nn as s,Rn as c,Tn as l,Tt as u,Xn as d,dn as f,wn as p,yt as m}from"../../_chunks/node/schemas-DtQwuPdM.js";import{t as h}from"../../_chunks/node/undici-CUIybhQ2.js";import{a as g,c as _,i as v,n as y,o as ee,r as te,s as ne,t as b}from"../../_chunks/node/decode_jwt-Col8JOnf.js";import{t as re}from"../../_chunks/node/version-DH6yRy-M.js";import{Readable as x}from"stream";import S,{dirname as ie,resolve as ae}from"path";import{createWriteStream as oe}from"fs";import se from"zlib";import ce from"os";import{pipeline as le}from"stream/promises";import{mkdir as ue}from"fs/promises";import*as de from"node:constants";import{setTimeout as fe}from"node:timers/promises";var C=class e extends Error{constructor(t,n){super(t.statusText),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.response=t,this.message=n?.message??``,this.json=n?.json,this.text=n?.text,this.sandboxName=n?.sandboxName,this.sessionId=n?.sessionId}},w=class e extends Error{constructor(t,n,r){super(n),this.name=`StreamError`,this.code=t,this.sessionId=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};const pe=`iad1`;function me(e){return e==null?[]:Array.isArray(e)?e:[e]}var he=e(_(),1);function ge(e){return async(t,n={})=>{let r=Object.assign({minTimeout:400,retries:2,factor:2},n.retry);n.onRetry&&(r.onRetry=(e,t)=>{n.onRetry(e,n),n.retry&&n.retry.onRetry&&n.retry.onRetry(e,t)});try{return await(0,he.default)(async(i,a)=>{try{if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));let o=await e(t,n);if(o.status===429){let e=Number(o.headers.get(`Retry-After`));if(e>20)return i(new C(o));let t=r.forever||a<=r.retries;throw e>0&&t&&await _e(e*1e3,n.signal),new C(o)}if(o.status>=500&&o.status<600)throw new C(o);return o}catch(e){if(ve(e))return i(e);if(n.signal?.aborted)return i(n.signal.reason||Error(`Request aborted`));throw e}},r)}catch(e){if(e instanceof C)return e.response;throw e}}}async function _e(e,t){if(t?.aborted)throw t.reason||Error(`Request aborted`);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason||Error(`Request aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n(null)},e);t?.addEventListener(`abort`,i,{once:!0})})}function ve(e){return e!=null&&e.name===`AbortError`}const ye=new(h()).Agent({bodyTimeout:0});var be=class{constructor(e){this.fetch=ge(e.fetch??globalThis.fetch),this.baseUrl=e.baseUrl,this.debug=e.debug??process.env.DEBUG_FETCH===`true`,this.token=e.token,this.agent=ye}async request(e,t){let n=new URL(`${this.baseUrl}${e}`);if(t?.query)for(let[e,r]of Object.entries(t.query))me(r).forEach(t=>{n.searchParams.append(e,t.toString())});let r=Date.now(),i=await this.fetch(n.toString(),{...t,body:t?.body,method:t?.method||`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`,...t?.headers}:t?.headers,dispatcher:this.agent,signal:t?.signal});if(this.debug){let e=Date.now()-r;if(console.log(`[API] ${n} (${i.status}) ${e}ms`),i.status===429){let e=parseInt(i.headers.get(`Retry-After`)??``,10),t=Math.floor(e/60/60),r=Math.floor(e/60)%60,a=e%60;console.warn(`[API] ${n} Rate Limited, Retry After ${t}h ${r}m ${a}s`)}}return i}};function xe(e){return e.match(/\/v2\/sandboxes\/sessions\/([^/?]+)/)?.[1]}function Se(e){return e.match(/\/v2\/sandboxes\/(?!sessions(?:\/|$|\?))(?!snapshots(?:\/|$|\?))([^/?]+)/)?.[1]}const Ce=l({error:l({message:c()})});function we(e){let t=Ce.safeParse(e);return t.success?t.data.error.message:void 0}async function Te(e,t){let n=xe(t.url),r;n||(r=Se(t.url));let i=await t.text().catch(e=>new C(t,{message:`Can't read response text: ${String(e)}`,sessionId:n,sandboxName:r}));if(typeof i!=`string`)return i;let a;try{a=JSON.parse(i||`{}`)}catch(e){return new C(t,{message:`Can't parse JSON: ${String(e)}`,text:i,sessionId:n,sandboxName:r})}if(!t.ok){let e=we(a);return new C(t,{message:e?`Status code ${t.status} is not ok: ${e}`:`Status code ${t.status} is not ok`,json:a,text:i,sessionId:n,sandboxName:r})}let o=e.safeParse(a);return o.success?{json:o.data,response:t,text:i}:new C(t,{message:`Response JSON is not valid: ${o.error}`,json:a,text:i,sessionId:n,sandboxName:r})}async function T(e,t){let n=await Te(e,t);if(n instanceof C)throw n;return n}const Ee=l({exact:c().optional(),startsWith:c().optional(),regex:c().optional()}),De=l({key:Ee.optional(),value:Ee.optional()}),Oe=l({path:Ee.optional(),method:o(c()).optional(),queryString:o(De).optional(),headers:o(De).optional()}),ke=l({domain:c(),headers:s(c(),c()).optional(),headerNames:o(c()).optional(),match:Oe.optional()}),Ae=l({domain:c(),forwardURL:c(),match:Oe.optional()}),je=l({headers:s(c(),c()).optional()}),Me=l({match:Oe.optional(),transform:o(je).optional(),forwardURL:c().optional()}).refine(({transform:e,forwardURL:t})=>e===void 0||t===void 0,{message:`transform and forwardURL cannot be used together`}).refine(({transform:e,forwardURL:t})=>e!==void 0||t!==void 0,{message:`transform or forwardURL must be provided`}),Ne=l({allow:d([o(c()),s(c(),o(Me))]).optional(),subnets:l({allow:o(c()).optional(),deny:o(c()).optional()}).optional()}),Pe=d([l({mode:f(`allow-all`)}).passthrough(),l({mode:f(`deny-all`)}).passthrough()]),Fe=l({mode:f(`custom`),allowedDomains:o(c()).optional(),allowedCIDRs:o(c()).optional(),deniedCIDRs:o(c()).optional(),injectionRules:o(ke).optional(),forwardRules:o(Ae).optional()}).passthrough(),Ie=d([Pe,Ne.passthrough()]),Le=d([Pe,Fe]),E=l({id:c(),memory:p(),vcpus:p(),region:c(),runtime:c().optional(),timeout:p(),status:m([`pending`,`running`,`stopping`,`stopped`,`failed`,`aborted`,`snapshotting`]),requestedAt:p(),startedAt:p().optional(),requestedStopAt:p().optional(),stoppedAt:p().optional(),abortedAt:p().optional(),duration:p().optional(),sourceSnapshotId:c().optional(),snapshottedAt:p().optional(),createdAt:p(),cwd:c(),updatedAt:p(),interactivePort:p().optional(),networkPolicy:Le.optional(),activeCpuDurationMs:p().optional(),networkTransfer:l({ingress:p(),egress:p()}).optional()}),Re=l({url:c(),subdomain:c(),port:p()}),D=l({id:c(),sourceSessionId:c(),region:c(),regions:o(c()).optional(),status:m([`created`,`deleted`,`failed`]),sizeBytes:p(),expiresAt:p().optional(),createdAt:p(),updatedAt:p(),lastUsedAt:p().optional(),creationMethod:c().optional(),parentId:c().optional()}),O=l({count:p(),next:c().nullable()}),ze=l({id:c(),name:c(),args:o(c()),cwd:c(),sessionId:c(),exitCode:p().nullable(),durationMs:p().optional(),startedAt:p()}),Be=ze.extend({exitCode:p()}),Ve=l({session:E.passthrough()}),He=Ve.extend({routes:o(Re)}),Ue=l({url:c(),token:c()}),We=l({sessions:o(E.passthrough()),pagination:O}),k=l({command:ze}),Ge=l({command:Be}),Ke=l({}),qe=l({data:c()}),Je=a(`stream`,[qe.extend({stream:f(`stdout`)}),qe.extend({stream:f(`stderr`)}),l({stream:f(`error`),data:l({code:c(),message:c()})})]),Ye=l({snapshots:o(D),pagination:O}),Xe=l({snapshot:D,siblings:o(D),count:c()}),Ze=l({snapshots:o(Xe),anchor:Xe.optional(),pagination:O}),Qe=l({snapshot:D,session:E.passthrough()}),$e=l({snapshot:D}),A=l({name:c(),persistent:i(),region:c().optional(),failoverRegions:o(c()).optional(),vcpus:p().optional(),memory:p().optional(),runtime:c().optional(),image:c().optional(),timeout:p().optional(),networkPolicy:Le.optional(),totalEgressBytes:p().optional(),totalIngressBytes:p().optional(),totalActiveCpuDurationMs:p().optional(),totalDurationMs:p().optional(),createdAt:p(),updatedAt:p(),expiresAt:p().optional(),currentSessionId:c(),currentSnapshotId:c().optional(),status:E.shape.status,statusUpdatedAt:p().optional(),cwd:c().optional(),tags:s(c(),c()).optional(),snapshotExpiration:p().optional(),keepLastSnapshots:l({count:p(),expiration:p().optional(),deleteEvicted:i().optional()}).optional()}),et=l({session:E.passthrough(),sandbox:A.optional(),snapshot:D.optional()}),tt=l({sandbox:A,session:E.passthrough(),routes:o(Re),resumed:i().optional()}),nt=l({sandboxes:o(A),pagination:O}),rt=l({sandbox:A,routes:o(Re).optional()});var it=e(ne(),1),at=class{constructor(){let e=se.createGzip();this.pack=it.pack(),this.readable=this.pack.pipe(e)}async addFile(e){return new Promise((t,n)=>{let r=this.pack.entry(`size`in e?{name:e.name,size:e.size,mode:e.mode}:{name:e.name,size:Buffer.byteLength(e.content),mode:e.mode},e=>{if(e)return n(e);t()});e.content instanceof x?e.content.pipe(r):r.end(e.content)})}async end(){return new Promise((e,t)=>{this.readable.on(`error`,t),this.readable.on(`end`,e),this.pack.finalize()})}};function ot(e){return new Promise((t,n)=>{let r=[];e.on(`error`,e=>n(e)),e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r)))})}function st(e){if(!S.posix.isAbsolute(e.cwd))throw Error(`cwd dir must be absolute`);if(!S.posix.isAbsolute(e.extractDir))throw Error(`extractDir must be absolute`);let t=S.posix.isAbsolute(e.filePath)?S.posix.normalize(e.filePath):S.posix.join(e.cwd,e.filePath);return S.posix.relative(e.extractDir,t)}function j(e){let t=e===`allow-all`||e===`deny-all`?{mode:e}:e;return Ie.parse(t),t}function ct(e){if(e.mode===`allow-all`||e.mode===`deny-all`)return e.mode;let t=e.allowedCIDRs||e.deniedCIDRs?{subnets:{...e.allowedCIDRs&&{allow:e.allowedCIDRs},...e.deniedCIDRs&&{deny:e.deniedCIDRs}}}:void 0;if(e.injectionRules&&e.injectionRules.length>0||e.forwardRules&&e.forwardRules.length>0){let n=new Map;for(let t of e.injectionRules??[]){let e=Object.fromEntries((t.headerNames??[]).map(e=>[e,`<redacted>`])),r=n.get(t.domain)??[];r.push({...t.match?{match:t.match}:{},transform:[{headers:e}]}),n.set(t.domain,r)}for(let t of e.forwardRules??[]){let e=n.get(t.domain)??[];e.push({...t.match?{match:t.match}:{},forwardURL:t.forwardURL}),n.set(t.domain,e)}let r={};for(let t of e.allowedDomains??[])r[t]=n.get(t)??[];for(let t of[...e.injectionRules??[],...e.forwardRules??[]])t.domain in r||(r[t.domain]=n.get(t.domain)??[]);return{allow:r,...t}}return{...e.allowedDomains&&{allow:e.allowedDomains},...t}}const M=e=>{let t=Object.entries(e??{}).filter(([e])=>e.startsWith(`__`));return Object.fromEntries(t)};var lt=e(ee(),1),ut=g();function dt(e){if(e.split(`.`).length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(`.`)[1],`base64url`).toString(`utf8`));return t.owner_id?{owner_id:t.owner_id,project_id:t.project_id}:null}catch{return null}}var N=class extends be{constructor(e){super({baseUrl:e.baseUrl??`https://vercel.com/api`,token:e.token,debug:!1,fetch:e.fetch}),this.teamId=e.teamId,this.isJwtToken=!1;let t=dt(e.token);t&&(this.isJwtToken=!0,this.projectId=t.project_id,this.teamId=t.owner_id)}async ensureValidToken(){if(this.isJwtToken)try{let e=await(0,ut.getVercelOidcToken)({expirationBufferMs:300*1e3,team:this.teamId,project:this.projectId});if(e!==this.token){this.token=e;let t=dt(e);t&&(this.teamId=t.owner_id)}}catch{}}async request(e,t){return await this.ensureValidToken(),super.request(e,{...t,query:{teamId:this.teamId,...t?.query},headers:{"content-type":`application/json`,"user-agent":`vercel/sandbox/${re} (Node.js/${process.version}; ${ce.platform()}/${ce.arch()})`,...t?.headers}})}async getSession(e){let t=M(e),n=new URLSearchParams(t).toString();return n=n?`?${n}`:``,T(He,await this.request(`/v2/sandboxes/sessions/${e.sessionId}${n}`,{signal:e.signal}))}async createSandbox(e){let t=M(e),n=e.runtime===void 0?`/v3/sandboxes`:`/v2/sandboxes`;return T(tt,await this.request(n,{method:`POST`,body:JSON.stringify({projectId:e.projectId,ports:e.ports,source:e.source,timeout:e.timeout,resources:e.resources,runtime:e.runtime,image:e.image,name:e.name,persistent:e.persistent,networkPolicy:e.networkPolicy?j(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async forkSandbox(e){let t=M(e);return T(tt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.sourceSandbox)}/fork`,{method:`POST`,query:{projectId:e.projectId},body:JSON.stringify({name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,persistent:e.persistent,networkPolicy:e.networkPolicy?j(e.networkPolicy):void 0,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,...t}),signal:e.signal}))}async runCommand(e){if(e.wait){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,wait:!0,logs:e.logs||void 0,timeout:e.timeout}),signal:e.signal});if(t.ok||await T(u(),t),t.headers.get(`content-type`)!==`application/x-ndjson`)throw new C(t,{message:`Expected a stream of command data`,sessionId:e.sessionId});if(t.body===null)throw new C(t,{message:`No response body`,sessionId:e.sessionId});let n=lt.parse();ft(t.body,n,{signal:e.signal}).catch(e=>{console.error(`Error piping command stream:`,e)});let r=n[Symbol.asyncIterator](),i=await r.next();if(i.done)throw new w(`stream_ended_early`,`Stream ended before command data was received`,e.sessionId);let{command:a}=k.parse(i.value);return{command:a,finished:(async()=>{for(;;){let t=await r.next();if(t.done)throw new w(`stream_ended_early`,`Stream ended before command finished`,e.sessionId);if(t.value?.command){let{command:e}=Ge.parse(t.value);return e}let n=Je.parse(t.value);if(n.stream===`error`)throw new w(n.data.code,n.data.message,e.sessionId);e.onLog?.(n)}})()}}return T(k,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd`,{method:`POST`,body:JSON.stringify({command:e.command,args:e.args,cwd:e.cwd,env:e.env,sudo:e.sudo,timeout:e.timeout}),signal:e.signal}))}async getCommand(e){return e.wait?T(Ge,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal,query:{wait:`true`}})):T(k,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}`,{signal:e.signal}))}async openInteractive(e){return T(Ue,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/interactive`,{method:`POST`,body:JSON.stringify({}),signal:e.signal}))}async mkDir(e){return T(Ke,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/mkdir`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal}))}getFileWriter(e){let t=new at;return{response:(async()=>this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/write`,{method:`POST`,headers:{"content-type":`application/gzip`,"x-cwd":e.extractDir},body:await ot(t.readable),signal:e.signal}))(),writer:t}}async listSessions(e){return T(We,await this.request(`/v2/sandboxes/sessions`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async listSnapshots(e){return T(Ye,await this.request(`/v2/sandboxes/snapshots`,{query:{project:e.projectId,name:e.name,limit:e.limit,cursor:e.cursor,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async getSnapshotTree(e){return T(Ze,await this.request(`/v2/sandboxes/snapshots/tree`,{query:{project:e.projectId,snapshotId:e.snapshotId,limit:e.limit,sortOrder:e.sortOrder},method:`GET`,signal:e.signal}))}async writeFiles(e){let{writer:t,response:n}=this.getFileWriter({sessionId:e.sessionId,extractDir:e.extractDir,signal:e.signal});for(let n of e.files)await t.addFile({name:st({filePath:n.path,extractDir:e.extractDir,cwd:e.cwd}),content:n.content,mode:n.mode});t.end(),await T(Ke,await n)}async readFile(e){let t=await this.request(`/v2/sandboxes/sessions/${e.sessionId}/fs/read`,{method:`POST`,body:JSON.stringify({path:e.path,cwd:e.cwd}),signal:e.signal});if(t.status===404)return null;let n=t.headers.get(`content-type`)??``;if(!t.ok||!n.includes(`application/octet-stream`)){let e=await t.text().catch(()=>``),r;try{r=JSON.parse(e||`{}`)}catch{r=void 0}throw new C(t,{message:`Unexpected response reading file: status ${t.status}, content-type ${n||`(none)`}`,json:r,text:e})}return t.body===null?null:x.fromWeb(t.body)}async killCommand(e){return T(k,await this.request(`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.commandId}/kill`,{method:`POST`,body:JSON.stringify({signal:e.signal}),signal:e.abortSignal}))}getLogs(e){let t=this,n=new AbortController,r=e.signal?pt(e.signal,n.signal):n.signal,i=(async function*(){let n=`/v2/sandboxes/sessions/${e.sessionId}/cmd/${e.cmdId}/logs`,i=await t.request(n,{method:`GET`,signal:r});if(i.ok||await T(u(),i),i.headers.get(`content-type`)!==`application/x-ndjson`)throw new C(i,{message:`Expected a stream of logs`,sessionId:e.sessionId});if(i.body===null)throw new C(i,{message:`No response body`,sessionId:e.sessionId});let a=lt.parse();ft(i.body,a,{signal:r}).catch(e=>{console.error(`Error piping logs:`,e)});for await(let t of a){let n=Je.parse(t);if(n.stream===`error`)throw new w(n.data.code,n.data.message,e.sessionId);yield n}})();return Object.assign(i,{[Symbol.dispose](){n.abort(`Disposed`)},close:()=>n.abort(`Disposed`)})}async stopSession(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/stop`;return T(et,await this.request(t,{method:`POST`,signal:e.signal}))}async updateNetworkPolicy(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/network-policy`;return T(Ve,await this.request(t,{method:`POST`,body:JSON.stringify(j(e.networkPolicy)),signal:e.signal}))}async extendTimeout(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/extend-timeout`;return T(Ve,await this.request(t,{method:`POST`,body:JSON.stringify({duration:e.duration}),signal:e.signal}))}async createSnapshot(e){let t=`/v2/sandboxes/sessions/${e.sessionId}/snapshot`,n=e.expiration===void 0?void 0:JSON.stringify({expiration:e.expiration});return T(Qe,await this.request(t,{method:`POST`,body:n,signal:e.signal}))}async deleteSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return T($e,await this.request(t,{method:`DELETE`,signal:e.signal}))}async getSnapshot(e){let t=`/v2/sandboxes/snapshots/${e.snapshotId}`;return T($e,await this.request(t,{signal:e.signal}))}async getSandbox(e){let t=M(e),n={projectId:e.projectId,...t};return e.resume!==void 0&&(n.resume=String(e.resume)),T(tt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{query:n,signal:e.signal}))}async listSandboxes(e){return T(nt,await this.request(`/v2/sandboxes`,{query:{project:e.projectId,limit:e.limit,sortBy:e.sortBy,sortOrder:e.sortOrder,namePrefix:e.namePrefix,cursor:e.cursor,tags:mt(e.tags)},method:`GET`,signal:e.signal}))}async updateSandbox(e){return T(rt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`PATCH`,query:{projectId:e.projectId},body:JSON.stringify({persistent:e.persistent,resources:e.resources,timeout:e.timeout,networkPolicy:e.networkPolicy?j(e.networkPolicy):void 0,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions}),signal:e.signal}))}async deleteSandbox(e){return T(rt,await this.request(`/v2/sandboxes/${encodeURIComponent(e.name)}`,{method:`DELETE`,query:{projectId:e.projectId,deleteOrphanSnapshots:e.deleteOrphanSnapshots?`true`:void 0},signal:e.signal}))}};async function ft(e,t,n){let r=e.getReader(),i=!1,a=n?.signal,o=()=>{i=!0;let e=a?.reason??new DOMException(`The operation was aborted.`,`AbortError`);if(r.cancel(e).catch(()=>{}),`destroy`in t&&typeof t.destroy==`function`){t.destroy(e);return}t.emit(`error`,e),t.end()};a&&(a.aborted?o():a.addEventListener(`abort`,o,{once:!0}));try{for(;;){let e=await r.read();if(e.value&&t.write(Buffer.from(e.value)),e.done)break}}catch(e){i||t.emit(`error`,e)}finally{a?.removeEventListener(`abort`,o),i||t.end()}}function pt(...e){let t=new AbortController,n=()=>{t.abort();for(let t of e)t.removeEventListener(`abort`,n)};for(let r of e){if(r.aborted){t.abort();break}r.addEventListener(`abort`,n)}return t.signal}function mt(e){if(e===void 0)return;let t=Object.entries(e);if(t.length!==0)return t.map(([e,t])=>`${e}:${t}`)}function ht(e){return JSON.parse(Buffer.from(e.replace(/-/g,`+`).replace(/_/g,`/`),`base64`).toString(`utf8`))}var P=e(v(),1);const gt={warn:P.default.yellow,error:P.default.red,success:P.default.green,info:P.default.blue},_t=P.default.dim(`[vercel/sandbox]`);function F(e,t){t=Array.isArray(t)?t.join(`
2
+ `):t;let n=t.replace(/^/gm,`${_t} `);console.error(gt[e](n))}function vt(e){return P.default.italic(P.default.dim("`")+e+P.default.dim("`"))}var yt=e(r(),1);async function bt(){return await import(`../../_chunks/node/auth-QgeX8nBM.js`)}function xt(){return process.env.NODE_ENV!==`production`&&![`1`,`true`].includes(process.env.CI||``)&&process.stdout.isTTY&&process.stdin.isTTY}const St=(()=>{let e=null;return async t=>{(!e||e[0].teamId!==t.teamId||e[0].projectId!==t.projectId)&&(e=[t,Ct(t).catch(t=>{throw e=null,t})]);let n=await e[1];return F(`warn`,`using inferred credentials team=${n.teamId} project=${n.projectId}`),n}})();async function Ct(e){let{OAuth:t,pollForToken:n,getAuth:r,updateAuthConfig:i,inferScope:a}=await bt(),o=r();if(!o?.token){let e=process.env.VERCEL_URL?`1 minute`:`5 minutes`;o=await wt({OAuth:t,pollForToken:n,getAuth:r},e)}if(o?.refreshToken&&o.expiresAt&&o.expiresAt.getTime()<=Date.now()){let e=await(await t()).refreshToken(o.refreshToken);o={expiresAt:new Date(Date.now()+e.expires_in*1e3),token:e.access_token,refreshToken:e.refresh_token||o.refreshToken},i(o)}if(!o?.token)throw Error([`Failed to retrieve authentication token.`,`${P.default.bold(`hint:`)} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,`├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox`,`╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token`].join(`
3
+ `));if(e.teamId&&e.projectId)return{token:o.token,teamId:e.teamId,projectId:e.projectId};let s=await a({teamId:e.teamId,token:o.token});return s.created&&F(`info`,`Created default project "${s.projectId}" in team "${s.teamId}".`),{token:o.token,teamId:e.teamId||s.teamId,projectId:e.projectId||s.projectId}}async function wt(e,t){F(`warn`,[`No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,`│ ${P.default.bold(`help:`)} this flow only happens on development environment.`,`│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`]);let n=await e.OAuth(),r=await n.deviceAuthorizationRequest();F(`info`,[`╰▶ To authenticate, visit: ${r.verification_uri_complete}`,` or visit ${P.default.italic(r.verification_uri)} and type ${P.default.bold(r.user_code)}`,` Press ${P.default.bold(`<return>`)} to open in your browser`]);let i,a=e.pollForToken({request:r,oauth:n}),o=!1,s=setTimeout(()=>{if(o)return;let e=[`Authentication flow timed out after ${t}.`,`│ Make sure to provide a token to avoid prompting an interactive flow.`,`╰▶ ${P.default.bold(`help:`)} Link your project with ${vt(`npx vercel link`)} to refresh OIDC token automatically.`].join(`
4
+ `);i=Error(e),a.return()},(0,yt.default)(t));try{for await(let e of a)switch(e._tag){case`SlowDown`:case`Timeout`:case`Response`:break;case`Error`:i=e.error;break;default:throw Error(`Unknown event type: ${JSON.stringify(e)}`)}}finally{o=!0,clearTimeout(s)}if(i)throw F(`error`,`${P.default.bold(`error:`)} Authentication failed: ${i.message}`),i;return F(`success`,`${P.default.bold(`done!`)} Authenticated successfully!`),e.getAuth()}var Tt=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,"Please link your Vercel project using `npx vercel link`.","Then, pull an initial OIDC token with `npx vercel env pull`",`and retry.`,"╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly."].join(`
5
+ `);super(t,{cause:e}),this.name=`LocalOidcContextError`}},Et=class extends Error{constructor(e){let t=[`Could not get credentials from OIDC context.`,`Please make sure OIDC is set up for your project`,`╰▶ Docs: https://vercel.com/docs/oidc`].join(`
6
+ `);super(t,{cause:e}),this.name=`VercelOidcContextError`}};async function Dt(e){try{return At(await(0,ut.getVercelOidcToken)({team:e.teamId,project:e.projectId}))}catch(t){if(!xt())throw process.env.VERCEL_URL?new Et(t):new Tt(t);return await St(e)}}async function I(e){return Ot(e??{})||await Dt({teamId:e&&typeof e==`object`&&`teamId`in e&&typeof e.teamId==`string`?e.teamId:void 0,projectId:e&&typeof e==`object`&&`projectId`in e&&typeof e.projectId==`string`?e.projectId:void 0})}function Ot(e){if(!e||typeof e!=`object`)return null;let t=[`token`in e&&typeof e.token==`string`?null:`token`,`teamId`in e&&typeof e.teamId==`string`?null:`teamId`,`projectId`in e&&typeof e.projectId==`string`?null:`projectId`].filter(e=>e!==null);if(t.length===0)return{token:e.token,projectId:e.projectId,teamId:e.teamId};if(t.length<3)throw Error(`Missing credentials parameters to access the Vercel API: ${t.filter(e=>e!==null).join(`, `)}`);return null}const kt=l({exp:p().optional().describe(`Expiry timestamp (seconds since epoch)`),iat:p().optional().describe(`Issued at timestamp`),owner_id:c(),project_id:c()});function At(e){try{let t=kt.parse(ht(e.split(`.`)[1]));return{token:e,projectId:t.project_id,teamId:t.owner_id}}catch(e){throw Error(`Invalid Vercel OIDC token: ${e instanceof Error?e.message:String(e)}`)}}const jt={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15,SIGCONT:18,SIGSTOP:19};function Mt(e){if(typeof e==`number`)return e;if(e in jt)return jt[e];throw Error(`Unknown signal name: ${String(e)}`)}var L=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get cmdId(){return this.cmd.id}get cwd(){return this.cmd.cwd}get startedAt(){return this.cmd.startedAt}constructor({client:e,sessionId:t,cmd:n,output:r}){this._client=null,this.outputCache=null,this._resolvedOutput=null,this._client=e??null,this.sessionId=t,this.cmd=n,this.exitCode=n.exitCode??null,this.durationMs=n.durationMs,r&&(this._resolvedOutput=r,this.outputCache=Promise.resolve({stdout:r.stdout,stderr:r.stderr,both:r.stdout+r.stderr}))}static[t](e){let t={sandboxId:e.sessionId,cmd:e.cmd};return e._resolvedOutput&&(t.output=e._resolvedOutput),t}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,output:t.output})}logs(e){if(!this._client)throw Error(`logs() requires an API client. Call an async method first to initialize the client.`);return this._client.getLogs({sessionId:this.sessionId,cmdId:this.cmd.id,signal:e?.signal})}async wait(e){"use step";let t=await this.ensureClient();e?.signal?.throwIfAborted();let n=await t.getCommand({sessionId:this.sessionId,cmdId:this.cmd.id,wait:!0,signal:e?.signal});return new R({client:t,sessionId:this.sessionId,cmd:n.json.command,exitCode:n.json.command.exitCode,durationMs:n.json.command.durationMs})}async getCachedOutput(e){return this.outputCache||=(async()=>{try{e?.signal?.throwIfAborted(),await this.ensureClient();let t=``,n=``,r=``;for await(let i of this.logs({signal:e?.signal}))r+=i.data,i.stream===`stdout`?t+=i.data:n+=i.data;return this._resolvedOutput={stdout:t,stderr:n},{stdout:t,stderr:n,both:r}}catch(e){throw this.outputCache=null,e}})(),this.outputCache}async output(e=`both`,t){"use step";return(await this.getCachedOutput(t))[e]}async stdout(e){"use step";return this.output(`stdout`,e)}async stderr(e){"use step";return this.output(`stderr`,e)}async kill(e,t){"use step";await(await this.ensureClient()).killCommand({sessionId:this.sessionId,commandId:this.cmd.id,signal:Mt(e??`SIGTERM`),abortSignal:t?.abortSignal})}},R=class e extends L{constructor(e){super({...e}),this.exitCode=e.exitCode,this.durationMs=e.durationMs??e.cmd.durationMs}static[t](e){return{...L[t](e),exitCode:e.exitCode,durationMs:e.durationMs}}static[n](t){return new e({sessionId:t.sandboxId,cmd:t.cmd,exitCode:t.exitCode,durationMs:t.durationMs,output:t.output})}async wait(){return this}};function z(e,t){let{itemsKey:n,fetchNext:r,signal:i}=t;async function*a(){Nt(i);let t=e;for(yield t;t.pagination.next!==null;)Nt(i),t=await r(t.pagination.next),yield t}async function*o(){for await(let e of a()){let t=e[n];for(let e of t)Nt(i),yield e}}return{...e,[Symbol.asyncIterator]:o,pages:a,toArray:async()=>{let e=[];for await(let t of o())e.push(t);return e}}}function Nt(e){if(e?.aborted)throw e.reason??new DOMException(`Aborted`,`AbortError`)}var Pt=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get snapshotId(){return this.snapshot.id}get sourceSessionId(){return this.snapshot.sourceSessionId}get regions(){return this.snapshot.regions??[this.snapshot.region]}get status(){return this.snapshot.status}get sizeBytes(){return this.snapshot.sizeBytes}get createdAt(){return new Date(this.snapshot.createdAt)}get updatedAt(){return new Date(this.snapshot.updatedAt)}get expiresAt(){if(this.snapshot.expiresAt!==void 0)return new Date(this.snapshot.expiresAt)}static[t](e){return{snapshot:e.snapshot}}static[n](t){return new e({snapshot:t.snapshot})}constructor({client:e,snapshot:t}){this._client=null,this._client=e??null,this.snapshot=t}static async list(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSnapshots({...t,...e,...r!==void 0&&{cursor:r}})).json;return z(await r(e?.cursor),{itemsKey:`snapshots`,fetchNext:r,signal:e?.signal})}static async tree(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=async r=>(await n.getSnapshotTree({...t,...e,snapshotId:r})).json;return z(await r(e.snapshotId),{itemsKey:`snapshots`,fetchNext:r,signal:e.signal})}static async get(t){"use step";let n=await I(t),r=new N({teamId:n.teamId,token:n.token,fetch:t.fetch});return new e({client:r,snapshot:(await r.getSnapshot({snapshotId:t.snapshotId,signal:t.signal})).json.snapshot})}async delete(e){"use step";this.snapshot=(await(await this.ensureClient()).deleteSnapshot({snapshotId:this.snapshot.id,signal:e?.signal})).json.snapshot}};function B(e){let{networkPolicy:t,...n}=e;return{...n,networkPolicy:t?ct(t):void 0}}var V=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get client(){if(!this._client)throw Error(`API client not initialized`);return this._client}get _sessionSnapshot(){return this.session}get sessionId(){return this.session.id}get interactivePort(){return this.session.interactivePort??void 0}get status(){return this.session.status}get createdAt(){return new Date(this.session.createdAt)}get timeout(){return this.session.timeout}get networkPolicy(){return this.session.networkPolicy}get sourceSnapshotId(){return this.session.sourceSnapshotId}get memory(){return this.session.memory}get vcpus(){return this.session.vcpus}get region(){return this.session.region}get runtime(){return this.session.runtime}get cwd(){return this.session.cwd}get requestedAt(){return new Date(this.session.requestedAt)}get startedAt(){return this.session.startedAt==null?void 0:new Date(this.session.startedAt)}get requestedStopAt(){return this.session.requestedStopAt==null?void 0:new Date(this.session.requestedStopAt)}get stoppedAt(){return this.session.stoppedAt==null?void 0:new Date(this.session.stoppedAt)}get abortedAt(){return this.session.abortedAt==null?void 0:new Date(this.session.abortedAt)}get duration(){return this.session.duration}get snapshottedAt(){return this.session.snapshottedAt==null?void 0:new Date(this.session.snapshottedAt)}get updatedAt(){return new Date(this.session.updatedAt)}get activeCpuUsageMs(){return this.session.activeCpuDurationMs}get networkTransfer(){return this.session.networkTransfer}static[t](e){return{session:e.session,routes:e.routes}}static[n](t){return new e({routes:t.routes,snapshot:t.session})}constructor(e){this._client=null,this.routes=e.routes,`snapshot`in e?this.session=e.snapshot:(this._client=e.client,this.session=B(e.session))}updateRoutes(e){this.routes=e}async getCommand(e,t){"use step";let n=await this.ensureClient(),r=await n.getCommand({sessionId:this.session.id,cmdId:e,signal:t?.signal});return new L({client:n,sessionId:this.session.id,cmd:r.json.command})}async runCommand(e,t,n){"use step";let r=await this.ensureClient(),i=typeof e==`string`?{cmd:e,args:t,signal:n?.signal,timeoutMs:n?.timeoutMs}:e,a=!i.detached,o=!!(i.stdout||i.stderr);if(a){let e=``,t=``,n=await(await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,wait:!0,logs:!0,onLog:n=>{n.stream===`stdout`?(e+=n.data,i.stdout?.write(n.data)):(t+=n.data,i.stderr?.write(n.data))},timeout:i.timeoutMs,signal:i.signal})).finished;return new R({client:r,sessionId:this.session.id,cmd:n,exitCode:n.exitCode??0,durationMs:n.durationMs,output:{stdout:e,stderr:t}})}let s=await r.runCommand({sessionId:this.session.id,command:i.cmd,args:i.args??[],cwd:i.cwd,env:i.env??{},sudo:i.sudo??!1,timeout:i.timeoutMs,signal:i.signal}),c=new L({client:r,sessionId:this.session.id,cmd:s.json.command});return o&&(async()=>{try{for await(let e of c.logs({signal:i.signal}))e.stream===`stdout`?i.stdout?.write(e.data):e.stream===`stderr`&&i.stderr?.write(e.data)}catch(e){if(i.signal?.aborted)return;(i.stderr??i.stdout)?.emit(`error`,e)}})(),c}async mkDir(e,t){"use step";await(await this.ensureClient()).mkDir({sessionId:this.session.id,path:e,signal:t?.signal})}async openInteractive(e){"use step";let{json:t}=await(await this.ensureClient()).openInteractive({sessionId:this.session.id,signal:e?.signal});return{url:t.url,token:t.token}}async readFile(e,t){"use step";return(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal})}async readFileToBuffer(e,t){"use step";let n=await(await this.ensureClient()).readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:t?.signal});return n===null?null:ot(n)}async downloadFile(e,t,n){"use step";let r=await this.ensureClient();if(!e?.path)throw Error(`downloadFile: source path is required`);if(!t?.path)throw Error(`downloadFile: destination path is required`);let i=await r.readFile({sessionId:this.session.id,path:e.path,cwd:e.cwd,signal:n?.signal});if(i===null)return null;try{let e=ae(t.cwd??``,t.path);return n?.mkdirRecursive&&await ue(ie(e),{recursive:!0}),await le(i,oe(e),{signal:n?.signal}),e}finally{i.destroy()}}async writeFiles(e,t){"use step";return(await this.ensureClient()).writeFiles({sessionId:this.session.id,cwd:this.session.cwd,extractDir:`/`,files:e,signal:t?.signal})}domain(e){let t=this.routes.find(({port:t})=>t==e);if(t)return`https://${t.subdomain}.vercel.run`;throw Error(`No route for port ${e}`)}async stop(e){"use step";let t=await(await this.ensureClient()).stopSession({sessionId:this.session.id,signal:e?.signal});return this.session=B(t.json.session),{session:this.session,sandbox:t.json.sandbox,snapshot:t.json.snapshot}}async update(e,t){"use step";e.networkPolicy!==void 0&&(this.session=B((await(await this.ensureClient()).updateNetworkPolicy({sessionId:this.session.id,networkPolicy:e.networkPolicy,signal:t?.signal})).json.session))}async extendTimeout(e,t){"use step";this.session=B((await(await this.ensureClient()).extendTimeout({sessionId:this.session.id,duration:e,signal:t?.signal})).json.session)}async snapshot(e){"use step";let t=await this.ensureClient(),n=await t.createSnapshot({sessionId:this.session.id,expiration:e?.expiration,signal:e?.signal});return this.session=B(n.json.session),new Pt({client:t,snapshot:n.json.snapshot})}};const{S_IFMT:H,S_IFREG:Ft,S_IFDIR:It,S_IFLNK:Lt,S_IFBLK:Rt,S_IFCHR:zt,S_IFIFO:Bt,S_IFSOCK:Vt}=de;function U(e,t,n,r){let i=Error(`${e}: ${t}, ${n} '${r}'`);return i.code=e,i.syscall=n,i.path=r,i}function Ht(e){return e==null?{encoding:null}:typeof e==`string`?{encoding:e}:{encoding:e.encoding??null,signal:e.signal}}var Ut=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){this.dev=e,this._mode=t,this.nlink=n,this.uid=r,this.gid=i,this.rdev=a,this.blksize=o,this.ino=s,this.size=c,this.blocks=l,this.atimeMs=u,this.mtimeMs=d,this.ctimeMs=f,this.birthtimeMs=p,this.atime=new Date(u),this.mtime=new Date(d),this.ctime=new Date(f),this.birthtime=new Date(p)}get mode(){return this._mode}isFile(){return(this.mode&H)===Ft}isDirectory(){return(this.mode&H)===It}isBlockDevice(){return(this.mode&H)===Rt}isCharacterDevice(){return(this.mode&H)===zt}isSymbolicLink(){return(this.mode&H)===Lt}isFIFO(){return(this.mode&H)===Bt}isSocket(){return(this.mode&H)===Vt}},Wt=class{constructor(e,t,n){this.name=e,this.type=t,this.parentPath=n,this.path=`${this.parentPath}/${this.name}`}isFile(){return this.type===1}isDirectory(){return this.type===2}isBlockDevice(){return this.type===7}isCharacterDevice(){return this.type===6}isSymbolicLink(){return this.type===3}isFIFO(){return this.type===4}isSocket(){return this.type===5}};function Gt(e){let t=e.trim().split(`|`);return new Ut(parseInt(t[10],10),parseInt(t[1],16),parseInt(t[8],10),parseInt(t[2],10),parseInt(t[3],10),0,parseInt(t[11],10),parseInt(t[9],10),parseInt(t[0],10),parseInt(t[12],10),parseFloat(t[4])*1e3,parseFloat(t[5])*1e3,parseFloat(t[6])*1e3,parseFloat(t[7])*1e3)}function Kt(e,t){let n=e.trim().split(`|`),r=n[0],i=n[1];if(!r)throw U(`ENOENT`,`no such file or directory`,`readdir`,t);if(!i)throw Error(`Invalid dirent type: ${i}`);return new Wt(r,Jt[i]??1,t)}const qt=`%s|%f|%u|%g|%X|%Y|%Z|%W|%h|%i|%d|%B|%b`,Jt={f:1,d:2,l:3,b:7,c:6,p:4,s:5};var Yt=class{constructor(e){this.sandbox=e}async readFile(e,t){"use step";let{encoding:n,signal:r}=Ht(t),i=await this.sandbox.readFileToBuffer({path:e},{signal:r});if(i===null)throw U(`ENOENT`,`no such file or directory`,`open`,e);return n?i.toString(n):i}async writeFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t),await this.sandbox.writeFiles([{path:e,content:a}],{signal:i})}async appendFile(e,t,n){"use step";let{encoding:r,signal:i}=typeof n==`string`?{encoding:n,signal:void 0}:{encoding:n?.encoding,signal:n?.signal},a;a=typeof t==`string`?Buffer.from(t,r??`utf8`):Buffer.isBuffer(t)?t:Buffer.from(t);let o=await this.sandbox.readFileToBuffer({path:e},{signal:i}),s=o===null?a:Buffer.concat([o,a]);await this.sandbox.writeFiles([{path:e,content:s}],{signal:i})}async mkdir(e,t){"use step";let n=typeof t==`number`?{recursive:!1}:t??{};if(n.recursive){let t=await this.sandbox.runCommand(`mkdir`,[`-p`,e],{signal:n.signal});if(t.exitCode!==0)throw U(`EACCES`,(await t.stderr()).trim()||`permission denied`,`mkdir`,e);return}await this.sandbox.mkDir(e,{signal:n.signal})}async readdir(e,t){"use step";if(t?.withFileTypes){let n=await this.sandbox.runCommand(`find`,[e,`-maxdepth`,`1`,`-mindepth`,`1`,`-printf`,`%f|%y\\n`],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`scandir`,e):U(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
7
+ `).filter(Boolean).map(t=>Kt(t,e))}let n=await this.sandbox.runCommand(`ls`,[`-1`,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`scandir`,e):U(`EACCES`,t.trim(),`scandir`,e)}return(await n.stdout()).trim().split(`
8
+ `).filter(Boolean)}async stat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-L`,`-c`,qt,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`stat`,e):U(`EACCES`,t.trim(),`stat`,e)}return Gt(await n.stdout())}async lstat(e,t){"use step";let n=await this.sandbox.runCommand(`stat`,[`-c`,qt,e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`lstat`,e):U(`EACCES`,t.trim(),`lstat`,e)}return Gt(await n.stdout())}async unlink(e,t){"use step";let n=await this.sandbox.runCommand(`rm`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`unlink`,e):U(`EACCES`,t.trim(),`unlink`,e)}}async rm(e,t){"use step";let n=[];t?.recursive&&n.push(`-r`),t?.force&&n.push(`-f`),n.push(e);let r=await this.sandbox.runCommand(`rm`,n,{signal:t?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`rm`,e):U(`EACCES`,t.trim(),`rm`,e)}}async rmdir(e,t){"use step";let n=await this.sandbox.runCommand(`rmdir`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`rmdir`,e):t.includes(`not empty`)?U(`ENOTEMPTY`,`directory not empty`,`rmdir`,e):U(`EACCES`,t.trim(),`rmdir`,e)}}async rename(e,t,n){"use step";let r=await this.sandbox.runCommand(`mv`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`rename`,e):U(`EACCES`,t.trim(),`rename`,e)}}async copyFile(e,t,n){"use step";let r=await this.sandbox.runCommand(`cp`,[e,t],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`copyfile`,e):U(`EACCES`,t.trim(),`copyfile`,e)}}async access(e,t){"use step";if((await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode!==0)throw U(`ENOENT`,`no such file or directory`,`access`,e)}async exists(e,t){return(await this.sandbox.runCommand(`test`,[`-e`,e],{signal:t?.signal})).exitCode===0}async chmod(e,t,n){"use step";let r=typeof t==`number`?t.toString(8):t,i=await this.sandbox.runCommand(`chmod`,[r,e],{signal:n?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`chmod`,e):U(`EACCES`,t.trim(),`chmod`,e)}}async chown(e,t,n,r){"use step";let i=await this.sandbox.runCommand(`chown`,[`${t}:${n}`,e],{signal:r?.signal});if(i.exitCode!==0){let t=await i.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`chown`,e):U(`EACCES`,t.trim(),`chown`,e)}}async symlink(e,t,n){"use step";let r=await this.sandbox.runCommand(`ln`,[`-s`,e,t],{signal:n?.signal});if(r.exitCode!==0){let e=await r.stderr();throw e.includes(`File exists`)?U(`EEXIST`,`file already exists`,`symlink`,t):U(`EACCES`,e.trim(),`symlink`,t)}}async readlink(e,t){"use step";let n=await this.sandbox.runCommand(`readlink`,[e],{signal:t?.signal});if(n.exitCode!==0)throw(await n.stderr()).includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`readlink`,e):U(`EINVAL`,`invalid argument`,`readlink`,e);return(await n.stdout()).trim()}async realpath(e,t){"use step";let n=await this.sandbox.runCommand(`realpath`,[e],{signal:t?.signal});if(n.exitCode!==0){let t=await n.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`realpath`,e):U(`EACCES`,t.trim(),`realpath`,e)}return(await n.stdout()).trim()}async truncate(e,t,n){"use step";let r=await this.sandbox.runCommand(`truncate`,[`-s`,String(t??0),e],{signal:n?.signal});if(r.exitCode!==0){let t=await r.stderr();throw t.includes(`No such file or directory`)?U(`ENOENT`,`no such file or directory`,`truncate`,e):U(`EACCES`,t.trim(),`truncate`,e)}}async mkdtemp(e,t){"use step";let n=await this.sandbox.runCommand(`mktemp`,[`-d`,`${e}XXXXXX`],{signal:t?.signal});if(n.exitCode!==0)throw U(`EACCES`,(await n.stderr()).trim(),`mkdtemp`,e);return(await n.stdout()).trim()}};const Xt=/^[a-z_][a-z0-9_-]*$/;function W(e,t){if(!e)throw Error(`Invalid ${t}: must not be empty`);if(e.length>32)throw Error(`Invalid ${t} "${e}": must be at most 32 characters`);if(!Xt.test(e))throw Error(`Invalid ${t} "${e}": must match ${Xt} (lowercase letters, digits, hyphens, underscores)`)}var Zt=class extends Error{constructor(e){super(`Failed to create user "${e}": user already exists`),this.name=`SandboxUserAlreadyExistsError`,this.username=e}},G=class{constructor({sandbox:e,username:t}){this.sandbox=e,this.username=t,this.homeDir=t===`root`?`/root`:`/home/${t}`}buildUserCommand(e){let t=Object.entries(e.env??{}),n=t.length>0?[`env`,...t.map(([e,t])=>`${e}=${t}`)]:[],r=e.cwd??this.homeDir;return{cmd:`sudo`,args:[`-u`,this.username,`--`,`bash`,`-c`,`cd "$1" || exit 1; shift; exec "$@"`,`bash`,r,...n,e.cmd,...e.args??[]]}}resolvePath(e){return e.startsWith(`/`)?e:`${this.homeDir}/${e}`}async runCommand(e,t,n){if(typeof e==`string`){let r=this.buildUserCommand({cmd:e,args:t});return this.sandbox.runCommand({...r,signal:n?.signal,timeoutMs:n?.timeoutMs})}let r=e;if(r.sudo)return this.sandbox.runCommand({...r});let i=this.buildUserCommand({cmd:r.cmd,args:r.args,env:r.env,cwd:r.cwd});return this.sandbox.runCommand({cmd:i.cmd,args:i.args,detached:r.detached,stdout:r.stdout,stderr:r.stderr,signal:r.signal,timeoutMs:r.timeoutMs})}async writeFiles(e,t){let n=e.map(e=>({...e,path:this.resolvePath(e.path)}));await this.sandbox.writeFiles(n,t);let r=n.map(e=>e.path);if(r.length===0)return;await this.chownOrThrow(r,`${this.username}:${await this.primaryGroup(t?.signal)}`,t?.signal);let i=this.ancestorDirsUnderHome(r);if(i.length>0){let{group:e}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(i,`${this.username}:${e}`,t?.signal),await this.chmodOrThrow(i,`770`,t?.signal)}}async readFile(e,t){"use step";let n=await this.catAsUser(e,t);return n===null?null:x.from([n])}async readFileToBuffer(e,t){return this.catAsUser(e,t)}async downloadFile(e,t,n){"use step";let r=await this.readFile(e,n);if(r===null)return null;let i=ae(t.cwd??``,t.path);return n?.mkdirRecursive&&await ue(ie(i),{recursive:!0}),await le(r,oe(i),{signal:n?.signal}),i}async catAsUser(e,t){let n=e.path.startsWith(`/`)?e.path:`${e.cwd??this.homeDir}/${e.path}`,r=await this.runCommand({cmd:`base64`,args:[n],signal:t?.signal});if(r.exitCode!==0){let e=await r.stderr();if(/No such file or directory/i.test(e))return null;throw Error(`Failed to read ${n}: ${e}`)}return Buffer.from(await r.stdout(),`base64`)}async mkDir(e,t){let n=this.resolvePath(e);await this.sandbox.mkDir(n,t);let r=[n,...this.ancestorDirsUnderHome([n])],{group:i}=await this.sandbox.getDefaultUser(t);await this.chownOrThrow(r,`${this.username}:${i}`,t?.signal),await this.chmodOrThrow(r,`770`,t?.signal)}primaryGroup(e){return this.primaryGroupPromise||=this.resolvePrimaryGroup(e).catch(e=>{throw this.primaryGroupPromise=void 0,e}),this.primaryGroupPromise}async resolvePrimaryGroup(e){let t=await this.sandbox.runCommand({cmd:`id`,args:[`-gn`,this.username],signal:e});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the primary group of "${this.username}": ${e}`)}let n=(await t.stdout()).trim();if(!n)throw Error(`Failed to resolve the primary group of "${this.username}"`);return n}async chownOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chown`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set ownership on ${e.join(`, `)}: ${t}`)}}async chmodOrThrow(e,t,n){let r=await this.sandbox.runCommand({cmd:`chmod`,args:[t,...e],sudo:!0,signal:n});if(r.exitCode!==0){let t=await r.stderr();throw Error(`Failed to set permissions on ${e.join(`, `)}: ${t}`)}}ancestorDirsUnderHome(e){let t=new Set,n=`${this.homeDir}/`;for(let r of e){let e=r.slice(0,r.lastIndexOf(`/`));for(;e.length>this.homeDir.length&&e.startsWith(n);)t.add(e),e=e.slice(0,e.lastIndexOf(`/`))}return[...t]}async addToGroup(e,t){W(e,`group name`),await this.sandbox.addUserToGroup(this.username,e,t)}async removeFromGroup(e,t){W(e,`group name`),await this.sandbox.removeUserFromGroup(this.username,e,t)}};function K(e){return e instanceof C&&e.response.status===410}function Qt(e){return e instanceof C&&e.response.status===404}function $t(e){return e instanceof C&&e.response.status===410&&e.json?.error?.code===`snapshot_not_found`}function q(e){return e instanceof C&&e.response.status===422&&e.json?.error?.code===`sandbox_stopping`}function en(e){return e instanceof C&&e.response.status===422&&e.json?.error?.code===`sandbox_snapshotting`}var tn=class e{async ensureClient(){"use step";if(this._client)return this._client;let e=await I();return this._client=new N({teamId:e.teamId,token:e.token}),this._client}get name(){return this.sandbox.name}get routes(){return this.currentSession().routes}get persistent(){return this.sandbox.persistent}get region(){return this.sandbox.region??`iad1`}get failoverRegions(){return this.sandbox.failoverRegions??[]}get vcpus(){return this.sandbox.vcpus}get memory(){return this.sandbox.memory}get runtime(){return this.sandbox.runtime}get image(){return this.sandbox.image}get totalEgressBytes(){return this.sandbox.totalEgressBytes}get totalIngressBytes(){return this.sandbox.totalIngressBytes}get totalActiveCpuDurationMs(){return this.sandbox.totalActiveCpuDurationMs}get totalDurationMs(){return this.sandbox.totalDurationMs}get updatedAt(){return new Date(this.sandbox.updatedAt)}get statusUpdatedAt(){return this.sandbox.statusUpdatedAt?new Date(this.sandbox.statusUpdatedAt):void 0}get createdAt(){return new Date(this.sandbox.createdAt)}get interactivePort(){return this.currentSession().interactivePort}get cwd(){return this.currentSession().cwd}get status(){return this.currentSession().status}get timeout(){return this.sandbox.timeout}get expiresAt(){if(this.session?.status===`running`){let e=this.session.startedAt??this.session.createdAt;return new Date(e.getTime()+this.session.timeout)}return this.sandbox.expiresAt===void 0?void 0:new Date(this.sandbox.expiresAt)}get tags(){return this.sandbox.tags}get networkPolicy(){return this.sandbox.networkPolicy?ct(this.sandbox.networkPolicy):void 0}get sourceSnapshotId(){return this.currentSession().sourceSnapshotId}get currentSnapshotId(){return this.sandbox.currentSnapshotId}get snapshotExpiration(){return this.sandbox.snapshotExpiration}get keepLastSnapshots(){return this.sandbox.keepLastSnapshots}get activeCpuUsageMs(){return this.currentSession().activeCpuUsageMs}get networkTransfer(){return this.currentSession().networkTransfer}static async list(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=async r=>(await n.listSandboxes({...t,...e,...r!==void 0&&{cursor:r}})).json;return z(await r(e?.cursor),{itemsKey:`sandboxes`,fetchNext:r,signal:e?.signal})}static[t](e){return{metadata:e.session?._sessionSnapshot,routes:e.session?.routes??[],sandboxMetadata:e.sandbox,projectId:e.projectId}}static[n](t){let n=new e({sandbox:t.sandboxMetadata,routes:t.routes,projectId:t.projectId});return t.metadata&&(n.session=new V({routes:t.routes,snapshot:t.metadata})),n}static async create(e){"use step";if(e?.runtime!==void 0&&e.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e?.fetch}),r=M(e),i=await n.createSandbox({source:e?.source,projectId:t.projectId,ports:e?.ports??[],timeout:e?.timeout,resources:e?.resources,runtime:e?.runtime,image:e?.image,networkPolicy:e?.networkPolicy,env:e?.env,tags:e?.tags,snapshotExpiration:e?.snapshotExpiration,keepLastSnapshots:e?.keepLastSnapshots,region:e?.region,failoverRegions:e?.failoverRegions,signal:e?.signal,name:e?.name,persistent:e?.persistent,...r});return new nn({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e?.onResume})}static async fork(e){"use step";let t=await I(e),n=new N({teamId:t.teamId,token:t.token,fetch:e.fetch}),r=M(e),i=await n.forkSandbox({sourceSandbox:e.sourceSandbox,projectId:t.projectId,name:e.name,ports:e.ports,timeout:e.timeout,resources:e.resources,image:e.image,networkPolicy:e.networkPolicy,env:e.env,tags:e.tags,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,region:e.region,failoverRegions:e.failoverRegions,persistent:e.persistent,signal:e.signal,...r});return new nn({client:n,session:i.json.session,sandbox:i.json.sandbox,routes:i.json.routes,projectId:t.projectId,onResume:e.onResume})}static async get(t){"use step";let n=await I(t),r=new N({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=M(t),a=await r.getSandbox({name:t.name,projectId:n.projectId,resume:t.resume,signal:t.signal,...i}),o=new e({client:r,session:a.json.session,sandbox:a.json.sandbox,routes:a.json.routes,projectId:n.projectId,onResume:t.onResume});return a.json.resumed&&t.onResume&&await t.onResume(o),o}static async getOrCreate(t){"use step";if(t?.runtime!==void 0&&t.image!==void 0)throw TypeError("`runtime` and `image` cannot be used together.");if(!t?.name){let n=await e.create(t);return t?.onCreate&&await t.onCreate(n),n}try{return await e.get(t)}catch(n){if(Qt(n)){let n=await e.create(t);return t.onCreate&&await t.onCreate(n),n}if($t(n)){let n=await I(t),r=new N({teamId:n.teamId,token:n.token,fetch:t.fetch}),i=M(t);try{await r.deleteSandbox({name:t.name,projectId:n.projectId,signal:t.signal,...i})}catch(e){if(!Qt(e))throw e}let a=await e.create(t);return t.onCreate&&await t.onCreate(a),a}throw n}}constructor({client:e,routes:t,session:n,sandbox:r,projectId:i,onResume:a}){this._client=null,this.resumePromise=null,this._client=e??null,n&&(this.session=new V({client:e,routes:t,session:n})),this.sandbox=r,this.projectId=i??``,this.onResume=a,this.fs=new Yt(this)}currentSession(){if(!this.session)throw Error(`No active session. Run a command or call resume first.`);return this.session}async resume(e){return this.resumePromise||=this.doResume(e).finally(()=>{this.resumePromise=null}),this.resumePromise}async doResume(e){let t=await this.ensureClient(),n=await t.getSandbox({name:this.sandbox.name,projectId:this.projectId,resume:!0,signal:e});this.session=new V({client:t,routes:n.json.routes,session:n.json.session}),this.onResume&&n.json.resumed&&await this.onResume(this)}async waitForStopAndResume(e){"use step";let t=await this.ensureClient(),n=this.session.status;for(;n===`stopping`||n===`snapshotting`;){await fe(500,void 0,{signal:e});let r=await t.getSession({sessionId:this.session.sessionId,signal:e});this.session=new V({client:t,routes:r.json.routes,session:r.json.session}),n=r.json.session.status}await this.resume(e)}async withResume(e,t){this.session||await this.resume(t);try{return await e()}catch(n){if(K(n))return await this.resume(t),e();if(q(n)||en(n))return await this.waitForStopAndResume(t),e();throw n}}async runCommand(e,t,n){"use step";let r=typeof e==`string`?n?.signal:e.signal;return this.withResume(()=>this.session.runCommand(e,t,n),r)}async getCommand(e,t){"use step";return this.withResume(()=>this.session.getCommand(e,t),t?.signal)}async mkDir(e,t){"use step";return this.withResume(()=>this.session.mkDir(e,t),t?.signal)}async openInteractive(e){"use step";return this.withResume(()=>this.session.openInteractive(e),e?.signal)}async readFile(e,t){"use step";return this.withResume(()=>this.session.readFile(e,t),t?.signal)}async readFileToBuffer(e,t){"use step";return this.withResume(()=>this.session.readFileToBuffer(e,t),t?.signal)}async downloadFile(e,t,n){"use step";return this.withResume(()=>this.session.downloadFile(e,t,n),n?.signal)}async writeFiles(e,t){"use step";return this.withResume(()=>this.session.writeFiles(e,t),t?.signal)}domain(e){return this.currentSession().domain(e)}async stop(e){"use step";if(!this.session)throw Error(`No active session to stop.`);let{session:t,sandbox:n,snapshot:r}=await this.session.stop(e);return n&&(this.sandbox=n),Object.assign(t,{snapshot:r})}async updateNetworkPolicy(e,t){"use step";return await this.withResume(()=>this.session.update({networkPolicy:e},t),t?.signal),this.session.networkPolicy}async extendTimeout(e,t){"use step";return this.withResume(()=>this.session.extendTimeout(e,t),t?.signal)}getDefaultUser(e){return this.defaultUserPromise||=this.resolveDefaultUser(e).catch(e=>{throw this.defaultUserPromise=void 0,e}),this.defaultUserPromise}async resolveDefaultUser(e){let t=await this.runCommand({cmd:`sh`,args:[`-c`,`id -un; id -gn`],signal:e?.signal});if(t.exitCode!==0){let e=await t.stderr();throw Error(`Failed to resolve the default sandbox user: ${e}`)}let[n,r]=(await t.stdout()).trim().split(`
9
+ `);if(!n||!r)throw Error(`Failed to resolve the default sandbox user (got "${n}:${r}")`);return{username:n,group:r}}async createUser(e,t){W(e,`username`);let{group:n}=await this.getDefaultUser(t),r=await this.runCommand({cmd:`useradd`,args:[`-m`,`-s`,`/bin/bash`,e],sudo:!0,signal:t?.signal});if(r.exitCode!==0){if(r.exitCode===9)throw new Zt(e);let t=await r.stderr();throw Error(`Failed to create user "${e}": ${t}`)}let i=await this.runCommand({cmd:`chown`,args:[`${e}:${n}`,`/home/${e}`],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to set ownership on /home/${e}: ${t}`)}let a=await this.runCommand({cmd:`chmod`,args:[`770`,`/home/${e}`],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let t=await a.stderr();throw Error(`Failed to set permissions on /home/${e}: ${t}`)}return new G({sandbox:this,username:e})}asUser(e){return W(e,`username`),new G({sandbox:this,username:e})}async createGroup(e,t){W(e,`group name`);let{username:n}=await this.getDefaultUser(t),r=`/shared/${e}`,i=await this.runCommand({cmd:`groupadd`,args:[e],sudo:!0,signal:t?.signal});if(i.exitCode!==0){let t=await i.stderr();throw Error(`Failed to create group "${e}": ${t}`)}let a=await this.runCommand({cmd:`mkdir`,args:[`-p`,r],sudo:!0,signal:t?.signal});if(a.exitCode!==0){let e=await a.stderr();throw Error(`Failed to create shared directory ${r}: ${e}`)}let o=await this.runCommand({cmd:`chown`,args:[`${n}:${e}`,r],sudo:!0,signal:t?.signal});if(o.exitCode!==0){let e=await o.stderr();throw Error(`Failed to set ownership on ${r}: ${e}`)}let s=await this.runCommand({cmd:`chmod`,args:[`2770`,r],sudo:!0,signal:t?.signal});if(s.exitCode!==0){let e=await s.stderr();throw Error(`Failed to set permissions on ${r}: ${e}`)}return{groupname:e,sharedDir:r}}async addUserToGroup(e,t,n){W(e,`username`),W(t,`group name`);let r=await this.runCommand({cmd:`usermod`,args:[`-aG`,t,e],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to add "${e}" to group "${t}": ${n}`)}}async removeUserFromGroup(e,t,n){W(e,`username`),W(t,`group name`);let r=await this.runCommand({cmd:`gpasswd`,args:[`-d`,e,t],sudo:!0,signal:n?.signal});if(r.exitCode!==0){let n=await r.stderr();throw Error(`Failed to remove "${e}" from group "${t}": ${n}`)}}async snapshot(e){"use step";return this.withResume(()=>this.session.snapshot(e),e?.signal)}async update(e,t){"use step";let n=await this.ensureClient(),r;e.resources?.vcpus&&(r={vcpus:e.resources.vcpus,memory:e.resources.vcpus*2048});let i=await n.updateSandbox({name:this.sandbox.name,projectId:this.projectId,persistent:e.persistent,resources:r,timeout:e.timeout,networkPolicy:e.networkPolicy,tags:e.tags,ports:e.ports,snapshotExpiration:e.snapshotExpiration,keepLastSnapshots:e.keepLastSnapshots,currentSnapshotId:e.currentSnapshotId,region:e.region,failoverRegions:e.failoverRegions,signal:t?.signal});if(this.sandbox=i.json.sandbox,e.ports!==void 0&&i.json.routes&&this.session?.updateRoutes(i.json.routes),e.timeout!==void 0&&this.session?.status===`running`){let n=e.timeout-this.session.timeout;if(n>0)try{await this.session.extendTimeout(n,t)}catch(e){if(!K(e)&&!q(e))throw e}}if(e.networkPolicy)try{return await this.session?.update({networkPolicy:e.networkPolicy},t)}catch(e){if(K(e)||q(e))return;throw e}}async delete(e){"use step";await(await this.ensureClient()).deleteSandbox({name:this.sandbox.name,projectId:this.projectId,deleteOrphanSnapshots:e?.deleteOrphanSnapshots,signal:e?.signal})}async listSessions(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSessions({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return z(await n(e?.cursor),{itemsKey:`sessions`,fetchNext:n,signal:e?.signal})}async listSnapshots(e){"use step";let t=await this.ensureClient(),n=async n=>(await t.listSnapshots({projectId:this.projectId,name:this.sandbox.name,limit:e?.limit,cursor:n,sortOrder:e?.sortOrder,signal:e?.signal})).json;return z(await n(e?.cursor),{itemsKey:`snapshots`,fetchNext:n,signal:e?.signal})}},nn=class extends tn{async[Symbol.asyncDispose](){await this.stop()}};const J=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,rn=new Set,an=typeof process==`object`&&process?process:{},on=(e,t,n,r)=>{typeof an.emitWarning==`function`?an.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let Y=globalThis.AbortController,sn=globalThis.AbortSignal;if(Y===void 0){sn=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},Y=class{constructor(){t()}signal=new sn;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=an.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,on("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.",`NO_ABORT_CONTROLLER`,`ENOTSUP`,t))}}const cn=e=>!rn.has(e),X=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),ln=e=>X(e)?e<=2**8?Uint8Array:e<=2**16?Uint16Array:e<=2**32?Uint32Array:e<=2**53-1?Z:null:null;var Z=class extends Array{constructor(e){super(e),this.fill(0)}},un=class e{heap;length;static#e=!1;static create(t){let n=ln(t);if(!n)return[];e.#e=!0;let r=new e(t,n);return e.#e=!1,r}constructor(t,n){if(!e.#e)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},dn=class e{#e;#t;#n;#r;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;static unsafeExposeInternals(e){return{starts:e.#v,ttls:e.#y,sizes:e.#_,keyMap:e.#c,keyList:e.#l,valList:e.#u,next:e.#d,prev:e.#f,get head(){return e.#p},get tail(){return e.#m},free:e.#h,isBackgroundFetch:t=>e.#L(t),backgroundFetch:(t,n,r,i)=>e.#I(t,n,r,i),moveToTail:t=>e.#z(t),indexes:t=>e.#M(t),rindexes:t=>e.#N(t),isStale:t=>e.#D(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#s}get size(){return this.#o}get fetchMethod(){return this.#i}get memoMethod(){return this.#a}get dispose(){return this.#n}get disposeAfter(){return this.#r}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:f,maxSize:p=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:_,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:ee,allowStaleOnFetchAbort:te,ignoreFetchAbort:ne}=t;if(n!==0&&!X(n))throw TypeError(`max option must be a nonnegative integer`);let b=n?ln(n):Array;if(!b)throw Error(`invalid max value: `+n);if(this.#e=n,this.#t=p,this.maxEntrySize=m||this.#t,this.sizeCalculation=h,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(_!==void 0&&typeof _!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#a=_,g!==void 0&&typeof g!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#i=g,this.#x=!!g,this.#c=new Map,this.#l=Array(n).fill(void 0),this.#u=Array(n).fill(void 0),this.#d=new b(n),this.#f=new b(n),this.#p=0,this.#m=0,this.#h=un.create(n),this.#o=0,this.#s=0,typeof l==`function`&&(this.#n=l),typeof u==`function`?(this.#r=u,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#b=!!this.#n,this.#S=!!this.#r,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!ee,this.allowStaleOnFetchAbort=!!te,this.ignoreFetchAbort=!!ne,this.maxEntrySize!==0){if(this.#t!==0&&!X(this.#t))throw TypeError(`maxSize must be a positive integer if specified`);if(!X(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#O()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=X(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!X(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#C()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#e&&!this.#t){let t=`LRU_CACHE_UNBOUNDED`;cn(t)&&(rn.add(t),on(`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`,`UnboundedCacheWarning`,t,e))}}getRemainingTTL(e){return this.#c.has(e)?1/0:0}#C(){let e=new Z(this.#e),t=new Z(this.#e);this.#y=e,this.#v=t,this.#E=(n,r,i=J.now())=>{if(t[n]=r===0?0:i,e[n]=r,r!==0&&this.ttlAutopurge){let e=setTimeout(()=>{this.#D(n)&&this.#B(this.#l[n],`expire`)},r+1);e.unref&&e.unref()}},this.#w=n=>{t[n]=e[n]===0?0:J.now()},this.#T=(i,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;i.ttl=o,i.start=s,i.now=n||r(),i.remainingTTL=o-(i.now-s)}};let n=0,r=()=>{let e=J.now();if(this.ttlResolution>0){n=e;let t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#c.get(i);if(a===void 0)return 0;let o=e[a],s=t[a];return!o||!s?1/0:o-((n||r())-s)},this.#D=i=>{let a=t[i],o=e[i];return!!o&&!!a&&(n||r())-a>o}}#w=()=>{};#T=()=>{};#E=()=>{};#D=()=>!1;#O(){let e=new Z(this.#e);this.#s=0,this.#_=e,this.#k=t=>{this.#s-=e[t],e[t]=0},this.#j=(e,t,n,r)=>{if(this.#L(t))return 0;if(!X(n))if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!X(n))throw TypeError(`sizeCalculation return invalid (expect positive integer)`)}else throw TypeError(`invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.`);return n},this.#A=(t,n,r)=>{if(e[t]=n,this.#t){let n=this.#t-e[t];for(;this.#s>n;)this.#F(!0)}this.#s+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#s)}}#k=e=>{};#A=(e,t,n)=>{};#j=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#M({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#m;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#p));)t=this.#f[t]}*#N({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#p;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#m));)t=this.#d[t]}#P(e){return e!==void 0&&this.#c.get(this.#l[e])===e}*entries(){for(let e of this.#M())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*rentries(){for(let e of this.#N())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*keys(){for(let e of this.#M()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*rkeys(){for(let e of this.#N()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*values(){for(let e of this.#M())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}*rvalues(){for(let e of this.#N())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;if(i!==void 0&&e(i,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#N()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#N({allowStale:!0}))this.#D(t)&&(this.#B(this.#l[t],`expire`),e=!0);return e}info(e){let t=this.#c.get(e);if(t===void 0)return;let n=this.#u[t],r=this.#L(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#y&&this.#v){let e=this.#y[t],n=this.#v[t];e&&n&&(i.ttl=e-(J.now()-n),i.start=Date.now())}return this.#_&&(i.size=this.#_[t]),i}dump(){let e=[];for(let t of this.#M({allowStale:!0})){let n=this.#l[t],r=this.#u[t],i=this.#L(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#y&&this.#v){a.ttl=this.#y[t];let e=J.now()-this.#v[t];a.start=Math.floor(Date.now()-e)}this.#_&&(a.size=this.#_[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=J.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#j(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#B(e,`set`),this;let u=this.#o===0?void 0:this.#c.get(e);if(u===void 0)u=this.#o===0?this.#m:this.#h.length===0?this.#o===this.#e?this.#F(!1):this.#o:this.#h.pop(),this.#l[u]=e,this.#u[u]=t,this.#c.set(e,u),this.#d[this.#m]=u,this.#f[u]=this.#m,this.#m=u,this.#o++,this.#A(u,l,s),s&&(s.set=`add`),c=!1;else{this.#z(u);let n=this.#u[u];if(t!==n){if(this.#x&&this.#L(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#b&&this.#n?.(t,e,`set`),this.#S&&this.#g?.push([t,e,`set`]))}else a||(this.#b&&this.#n?.(n,e,`set`),this.#S&&this.#g?.push([n,e,`set`]));if(this.#k(u),this.#A(u,l,s),this.#u[u]=t,s){s.set=`replace`;let e=n&&this.#L(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`)}if(r!==0&&!this.#y&&this.#C(),this.#y&&(c||this.#E(u,r,i),s&&this.#T(s,u)),!a&&this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return this}pop(){try{for(;this.#o;){let e=this.#u[this.#p];if(this.#F(!0),this.#L(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(e){let t=this.#p,n=this.#l[t],r=this.#u[t];return this.#x&&this.#L(r)?r.__abortController.abort(Error(`evicted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(r,n,`evict`),this.#S&&this.#g?.push([r,n,`evict`])),this.#k(t),e&&(this.#l[t]=void 0,this.#u[t]=void 0,this.#h.push(t)),this.#o===1?(this.#p=this.#m=0,this.#h.length=0):this.#p=this.#d[t],this.#c.delete(n),this.#o--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#c.get(e);if(i!==void 0){let e=this.#u[i];if(this.#L(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#D(i))r&&(r.has=`stale`,this.#T(r,i));else return n&&this.#w(i),r&&(r.has=`hit`,this.#T(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#c.get(e);if(r===void 0||!n&&this.#D(r))return;let i=this.#u[r];return this.#L(i)?i.__staleWhileFetching:i}#I(e,t,n,r){let i=t===void 0?void 0:this.#u[t];if(this.#L(i))return i;let a=new Y,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0;if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason);let l=f;return this.#u[t]===f&&(r===void 0?l.__staleWhileFetching?this.#u[t]=l.__staleWhileFetching:this.#B(e,`fetch`):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e)),u=r=>{let{aborted:i}=a.signal,o=i&&n.allowStaleOnFetchAbort,s=o||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,l=f;if(this.#u[t]===f&&(!c||l.__staleWhileFetching===void 0?this.#B(e,`fetch`):o||(this.#u[t]=l.__staleWhileFetching)),s)return n.status&&l.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw r},d=(t,r)=>{let o=this.#i?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#c.get(e)):this.#u[t]=p,p}#L(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof Y}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:_}=t;if(!this.#x)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let v={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:_},y=this.#c.get(e);if(y===void 0){g&&(g.fetch=`miss`);let t=this.#I(e,y,v,m);return t.__returned=t}else{let t=this.#u[y];if(this.#L(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#D(y);if(!h&&!i)return g&&(g.fetch=`hit`),this.#z(y),r&&this.#w(y),g&&this.#T(g,y),t;let a=this.#I(e,y,v,m),o=a.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=i?`stale`:`refresh`,o&&i&&(g.returnedStale=!0)),o?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#a;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#c.get(e);if(o!==void 0){let t=this.#u[o],s=this.#L(t);return a&&this.#T(a,o),this.#D(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#B(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#z(o),r&&this.#w(o),t))}else a&&(a.get=`miss`)}#R(e,t){this.#f[t]=e,this.#d[e]=t}#z(e){e!==this.#m&&(e===this.#p?this.#p=this.#d[e]:this.#R(this.#f[e],this.#d[e]),this.#R(this.#m,e),this.#m=e)}delete(e){return this.#B(e,`delete`)}#B(e,t){let n=!1;if(this.#o!==0){let r=this.#c.get(e);if(r!==void 0)if(n=!0,this.#o===1)this.#V(t);else{this.#k(r);let n=this.#u[r];if(this.#L(n)?n.__abortController.abort(Error(`deleted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(n,e,t),this.#S&&this.#g?.push([n,e,t])),this.#c.delete(e),this.#l[r]=void 0,this.#u[r]=void 0,r===this.#m)this.#m=this.#f[r];else if(r===this.#p)this.#p=this.#d[r];else{let e=this.#f[r];this.#d[e]=this.#d[r];let t=this.#d[r];this.#f[t]=this.#f[r]}this.#o--,this.#h.push(r)}}if(this.#S&&this.#g?.length){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return n}clear(){return this.#V(`delete`)}#V(e){for(let t of this.#N({allowStale:!0})){let n=this.#u[t];if(this.#L(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#l[t];this.#b&&this.#n?.(n,r,e),this.#S&&this.#g?.push([n,r,e])}}if(this.#c.clear(),this.#u.fill(void 0),this.#l.fill(void 0),this.#y&&this.#v&&(this.#y.fill(0),this.#v.fill(0)),this.#_&&this.#_.fill(0),this.#p=0,this.#m=0,this.#h.length=0,this.#s=0,this.#o=0,this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}};const fn=`vercel-forwarded-host`,pn=`vercel-forwarded-scheme`,mn=`vercel-forwarded-port`,hn=`vercel-forwarded-path`,gn=`vercel-sandbox-oidc-token`,_n=new dn({max:100});function vn(e,t=yn){return async function(n){let r=new Headers(n.headers),i=r.get(fn),a=r.get(pn),o=r.get(mn),s=r.get(hn),c=r.get(gn);if(r.delete(fn),r.delete(pn),r.delete(mn),r.delete(hn),r.delete(gn),!i||!a||!o||!s||!c)return t(n,Error(`Missing required proxy headers`));let l;try{l=new Request(bn(a,i,o,s),{method:n.method,body:n.body,headers:r,duplex:`half`})}catch{return t(new Request(n,{headers:r}),Error(`Invalid proxied request URL`))}l.headers.set(`host`,i);try{let t=xn(new URL(n.url),s),r=await Cn(c,t),i=Sn(t.host,r);return e(l,i)}catch(e){return t(l,e instanceof Error?e:Error(`Invalid OIDC token`))}}}function yn(){return new Response(`Forbidden`,{status:403})}function bn(e,t,n,r){let i=`${e}://${t}:${n}`;return r===`/`?i:`${i}${r}`}function xn(e,t){let n=Q(new URL(t,e.origin).pathname),r=new URL(e);return r.pathname=Q(r.pathname),n!==`/`&&r.pathname.endsWith(n)&&(r.pathname=Q(r.pathname.slice(0,-n.length))),r}function Q(e){return e.replace(/\/+$/,``)||`/`}function Sn(e,t){let n=$(t,`team_id`),r=$(t,`project_id`),i=$(t,`sandbox_id`),a=$(t,`sandbox_name`)??i;if(!n||!r||!i||!a)throw Error(`Missing required claims in OIDC token`);return{host:e,teamId:n,projectId:r,sandboxId:i,sandboxName:a}}async function Cn(e,t){let n=$(b(e),`iss`);if(!n)throw Error(`Missing OIDC issuer`);let r;try{r=new URL(n)}catch{throw Error(`Invalid OIDC issuer`)}if(r.protocol!==`https:`||r.hostname!==`oidc.vercel.com`)throw Error(`Invalid OIDC issuer`);let{payload:i}=await te(e,Tn(n),{audience:wn(t),algorithms:[`RS256`],clockTolerance:60,issuer:n});return i}function wn(e){let t=Q(e.pathname);return t===`/`?e.origin:e.origin+t}function Tn(e){let t=_n.get(e);if(t)return t;let n=y(new URL(`${e.replace(/\/$/,``)}/.well-known/jwks`));return _n.set(e,n),n}function $(e,t){let n=e[t];if(typeof n==`string`&&n)return n}export{C as APIError,L as Command,R as CommandFinished,pe as DEFAULT_SANDBOX_REGION,Yt as FileSystem,tn as Sandbox,G as SandboxUser,Zt as SandboxUserAlreadyExistsError,V as Session,Pt as Snapshot,w as StreamError,vn as defineSandboxProxy};
@@ -0,0 +1,169 @@
1
+ //#region src/network-policy.d.ts
2
+ /**
3
+ * A transform applied to network requests matching a domain rule.
4
+ *
5
+ * @example
6
+ * {
7
+ * headers: { authorization: "Bearer sk-..." }
8
+ * }
9
+ */
10
+ type NetworkTransformer = {
11
+ /** Headers to set on the outgoing request. */
12
+ headers?: Record<string, string>;
13
+ };
14
+ /**
15
+ * Defines how a request value is matched.
16
+ */
17
+ type NetworkPolicyMatcher = {
18
+ /** Match the value exactly. */
19
+ exact?: string;
20
+ } | {
21
+ /** Match values that start with the provided prefix. */
22
+ startsWith?: string;
23
+ } | {
24
+ /** Match values against an RE2 regular expression. */
25
+ regex?: string;
26
+ };
27
+ /**
28
+ * Matcher for key/value request entries such as headers and query parameters.
29
+ */
30
+ type NetworkPolicyKeyValueMatcher = {
31
+ /** Matcher for the entry key. */
32
+ key?: NetworkPolicyMatcher;
33
+ /** Matcher for the entry value. */
34
+ value?: NetworkPolicyMatcher;
35
+ };
36
+ /**
37
+ * Request matcher for a network policy rule.
38
+ *
39
+ * All specified dimensions must match. Multiple methods are ORed; multiple
40
+ * header and query-string matchers are ANDed.
41
+ */
42
+ type NetworkPolicyMatch = {
43
+ /** Match on the request path. */
44
+ path?: NetworkPolicyMatcher;
45
+ /** Match on the HTTP method. */
46
+ method?: string[];
47
+ /** Match on query-string entries. */
48
+ queryString?: NetworkPolicyKeyValueMatcher[];
49
+ /** Match on request headers. */
50
+ headers?: NetworkPolicyKeyValueMatcher[];
51
+ };
52
+ /**
53
+ * A rule applied to requests matching a domain in the network policy.
54
+ */
55
+ type NetworkPolicyRule = {
56
+ /**
57
+ * Optional request matcher. When provided, transforms and forwarding rules
58
+ * only apply to requests that match every specified dimension.
59
+ */
60
+ match?: NetworkPolicyMatch;
61
+ } & ({
62
+ /**
63
+ * Transforms to apply to matching requests.
64
+ *
65
+ * `transform` cannot be used together with `forwardURL`.
66
+ */
67
+ transform: NetworkTransformer[];
68
+ forwardURL?: never;
69
+ } | {
70
+ transform?: never;
71
+ /**
72
+ * HTTPS proxy URL to forward matching requests to. Must not include query string or fragment.
73
+ *
74
+ * You can use the `defineSandboxProxy` helper from `@vercel/sandbox/proxy` to implement the proxy handler
75
+ * automatically, which handles authorization and extracts metadata about the request and sandbox.
76
+ *
77
+ * `forwardURL` cannot be used together with `transform`.
78
+ *
79
+ * @see https://vercel.com/docs/vercel-sandbox/concepts/firewall#requests-proxying
80
+ */
81
+ forwardURL: string;
82
+ });
83
+ /**
84
+ * Network policy to define network restrictions for the sandbox.
85
+ *
86
+ * - `"allow-all"`: Full internet access (default). All traffic is allowed.
87
+ * - `"deny-all"`: No internet access. All traffic is denied.
88
+ * - Object: Custom access with explicit allow/deny lists.
89
+ *
90
+ * @example
91
+ * // Full internet access (default)
92
+ * "allow-all"
93
+ *
94
+ * @example
95
+ * // No external access
96
+ * "deny-all"
97
+ *
98
+ * @example
99
+ * // Custom access with specific domains (simple list)
100
+ * // All traffic not explicitly allowed is denied.
101
+ * {
102
+ * allow: ["*.npmjs.org", "github.com"],
103
+ * subnets: {
104
+ * allow: ["10.0.0.0/8"],
105
+ * deny: ["10.1.0.0/16"]
106
+ * }
107
+ * }
108
+ *
109
+ * @example
110
+ * // Custom access with specific domains (record form)
111
+ * {
112
+ * allow: {
113
+ * "*.npmjs.org": [],
114
+ * "github.com": [],
115
+ * }
116
+ * }
117
+ *
118
+ * @example
119
+ * // Custom access with request transformers
120
+ * {
121
+ * allow: {
122
+ * "ai-gateway.vercel.sh": [
123
+ * {
124
+ * match: {
125
+ * method: ["POST"],
126
+ * path: { startsWith: "/v1/" },
127
+ * headers: [
128
+ * { key: { exact: "x-api-key" }, value: { exact: "placeholder" } }
129
+ * ]
130
+ * },
131
+ * transform: [{
132
+ * headers: { authorization: "Bearer ..." }
133
+ * }]
134
+ * }
135
+ * ],
136
+ * "*": []
137
+ * }
138
+ * }
139
+ */
140
+ type NetworkPolicy = "allow-all" | "deny-all" | {
141
+ /**
142
+ * Domains to allow traffic to.
143
+ * Use "*" prefix for wildcard matching (e.g., "*.npmjs.org").
144
+ *
145
+ * Accepts either:
146
+ * - `string[]`: A simple list of domains to allow.
147
+ * - `Record<string, NetworkPolicyRule[]>`: A map of domains to rules.
148
+ * An empty array allows traffic with no additional rules.
149
+ */
150
+ allow?: string[] | Record<string, NetworkPolicyRule[]>;
151
+ /**
152
+ * Subnet-level access control using CIDR notation.
153
+ */
154
+ subnets?: {
155
+ /**
156
+ * List of CIDRs to allow traffic to.
157
+ * Traffic to these addresses will bypass the domain allowlist.
158
+ */
159
+ allow?: string[];
160
+ /**
161
+ * List of CIDRs to deny traffic to.
162
+ * These take precedence over allowed domains and CIDRs.
163
+ */
164
+ deny?: string[];
165
+ };
166
+ };
167
+ //#endregion
168
+ export { NetworkPolicy, NetworkPolicyKeyValueMatcher, NetworkPolicyMatch, NetworkPolicyMatcher, NetworkPolicyRule, NetworkTransformer };
169
+ //# sourceMappingURL=network-policy.d.ts.map