@vercel/sandbox 2.0.0-beta.11 → 2.0.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/README.md +8 -0
  2. package/dist/_virtual/rolldown_runtime.cjs +29 -0
  3. package/dist/api-client/api-client.cjs +456 -0
  4. package/dist/api-client/api-client.cjs.map +1 -0
  5. package/dist/api-client/api-client.d.cts +790 -0
  6. package/dist/api-client/api-client.d.ts +784 -777
  7. package/dist/api-client/api-client.js +445 -471
  8. package/dist/api-client/api-client.js.map +1 -1
  9. package/dist/api-client/api-error.cjs +32 -0
  10. package/dist/api-client/api-error.cjs.map +1 -0
  11. package/dist/api-client/api-error.d.cts +29 -0
  12. package/dist/api-client/api-error.d.ts +21 -18
  13. package/dist/api-client/api-error.js +28 -33
  14. package/dist/api-client/api-error.js.map +1 -1
  15. package/dist/api-client/base-client.cjs +125 -0
  16. package/dist/api-client/base-client.cjs.map +1 -0
  17. package/dist/api-client/base-client.d.cts +38 -0
  18. package/dist/api-client/base-client.d.ts +31 -36
  19. package/dist/api-client/base-client.js +110 -130
  20. package/dist/api-client/base-client.js.map +1 -1
  21. package/dist/api-client/file-writer.cjs +62 -0
  22. package/dist/api-client/file-writer.cjs.map +1 -0
  23. package/dist/api-client/file-writer.d.cts +66 -0
  24. package/dist/api-client/file-writer.d.ts +56 -52
  25. package/dist/api-client/file-writer.js +57 -61
  26. package/dist/api-client/file-writer.js.map +1 -1
  27. package/dist/api-client/index.cjs +2 -0
  28. package/dist/api-client/index.d.ts +2 -2
  29. package/dist/api-client/index.js +4 -21
  30. package/dist/api-client/validators.cjs +182 -0
  31. package/dist/api-client/validators.cjs.map +1 -0
  32. package/dist/api-client/validators.d.cts +1469 -0
  33. package/dist/api-client/validators.d.ts +1282 -3699
  34. package/dist/api-client/validators.js +155 -170
  35. package/dist/api-client/validators.js.map +1 -1
  36. package/dist/api-client/with-retry.cjs +89 -0
  37. package/dist/api-client/with-retry.cjs.map +1 -0
  38. package/dist/api-client/with-retry.d.cts +10 -0
  39. package/dist/api-client/with-retry.d.ts +9 -13
  40. package/dist/api-client/with-retry.js +81 -102
  41. package/dist/api-client/with-retry.js.map +1 -1
  42. package/dist/auth/api.cjs +29 -0
  43. package/dist/auth/api.cjs.map +1 -0
  44. package/dist/auth/api.js +26 -25
  45. package/dist/auth/api.js.map +1 -1
  46. package/dist/auth/error.cjs +13 -0
  47. package/dist/auth/error.cjs.map +1 -0
  48. package/dist/auth/error.js +11 -11
  49. package/dist/auth/error.js.map +1 -1
  50. package/dist/auth/file.cjs +64 -0
  51. package/dist/auth/file.cjs.map +1 -0
  52. package/dist/auth/file.d.cts +26 -0
  53. package/dist/auth/file.d.ts +19 -15
  54. package/dist/auth/file.js +49 -64
  55. package/dist/auth/file.js.map +1 -1
  56. package/dist/auth/index.cjs +12 -0
  57. package/dist/auth/index.d.cts +5 -0
  58. package/dist/auth/index.d.ts +5 -6
  59. package/dist/auth/index.js +6 -27
  60. package/dist/auth/linked-project.cjs +38 -0
  61. package/dist/auth/linked-project.cjs.map +1 -0
  62. package/dist/auth/linked-project.js +30 -64
  63. package/dist/auth/linked-project.js.map +1 -1
  64. package/dist/auth/oauth.cjs +205 -0
  65. package/dist/auth/oauth.cjs.map +1 -0
  66. package/dist/auth/oauth.d.cts +135 -0
  67. package/dist/auth/oauth.d.ts +113 -109
  68. package/dist/auth/oauth.js +185 -252
  69. package/dist/auth/oauth.js.map +1 -1
  70. package/dist/auth/poll-for-token.cjs +82 -0
  71. package/dist/auth/poll-for-token.cjs.map +1 -0
  72. package/dist/auth/poll-for-token.d.cts +28 -0
  73. package/dist/auth/poll-for-token.d.ts +23 -15
  74. package/dist/auth/poll-for-token.js +79 -64
  75. package/dist/auth/poll-for-token.js.map +1 -1
  76. package/dist/auth/project.cjs +80 -0
  77. package/dist/auth/project.cjs.map +1 -0
  78. package/dist/auth/project.d.cts +44 -0
  79. package/dist/auth/project.d.ts +12 -8
  80. package/dist/auth/project.js +70 -72
  81. package/dist/auth/project.js.map +1 -1
  82. package/dist/auth/zod.cjs +22 -0
  83. package/dist/auth/zod.cjs.map +1 -0
  84. package/dist/auth/zod.js +18 -17
  85. package/dist/auth/zod.js.map +1 -1
  86. package/dist/command.cjs +328 -0
  87. package/dist/command.cjs.map +1 -0
  88. package/dist/command.d.cts +289 -0
  89. package/dist/command.d.ts +265 -171
  90. package/dist/command.js +323 -226
  91. package/dist/command.js.map +1 -1
  92. package/dist/constants.d.cts +5 -0
  93. package/dist/constants.d.ts +5 -1
  94. package/dist/index.cjs +13 -0
  95. package/dist/index.d.cts +7 -0
  96. package/dist/index.d.ts +7 -6
  97. package/dist/index.js +7 -17
  98. package/dist/network-policy.d.cts +100 -0
  99. package/dist/network-policy.d.ts +32 -28
  100. package/dist/sandbox.cjs +694 -0
  101. package/dist/sandbox.cjs.map +1 -0
  102. package/dist/sandbox.d.cts +796 -0
  103. package/dist/sandbox.d.ts +783 -711
  104. package/dist/sandbox.js +684 -615
  105. package/dist/sandbox.js.map +1 -1
  106. package/dist/session.cjs +520 -0
  107. package/dist/session.cjs.map +1 -0
  108. package/dist/session.d.cts +406 -0
  109. package/dist/session.d.ts +398 -367
  110. package/dist/session.js +517 -505
  111. package/dist/session.js.map +1 -1
  112. package/dist/snapshot.cjs +116 -0
  113. package/dist/snapshot.cjs.map +1 -0
  114. package/dist/snapshot.d.cts +107 -0
  115. package/dist/snapshot.d.ts +98 -91
  116. package/dist/snapshot.js +114 -115
  117. package/dist/snapshot.js.map +1 -1
  118. package/dist/utils/array.cjs +17 -0
  119. package/dist/utils/array.cjs.map +1 -0
  120. package/dist/utils/array.js +12 -15
  121. package/dist/utils/array.js.map +1 -1
  122. package/dist/utils/consume-readable.cjs +18 -0
  123. package/dist/utils/consume-readable.cjs.map +1 -0
  124. package/dist/utils/consume-readable.js +13 -12
  125. package/dist/utils/consume-readable.js.map +1 -1
  126. package/dist/utils/decode-base64-url.cjs +15 -0
  127. package/dist/utils/decode-base64-url.cjs.map +1 -0
  128. package/dist/utils/decode-base64-url.js +10 -9
  129. package/dist/utils/decode-base64-url.js.map +1 -1
  130. package/dist/utils/dev-credentials.cjs +142 -0
  131. package/dist/utils/dev-credentials.cjs.map +1 -0
  132. package/dist/utils/dev-credentials.js +126 -184
  133. package/dist/utils/dev-credentials.js.map +1 -1
  134. package/dist/utils/get-credentials.cjs +123 -0
  135. package/dist/utils/get-credentials.cjs.map +1 -0
  136. package/dist/utils/get-credentials.d.cts +21 -0
  137. package/dist/utils/get-credentials.d.ts +19 -61
  138. package/dist/utils/get-credentials.js +106 -140
  139. package/dist/utils/get-credentials.js.map +1 -1
  140. package/dist/utils/log.cjs +25 -0
  141. package/dist/utils/log.cjs.map +1 -0
  142. package/dist/utils/log.js +15 -17
  143. package/dist/utils/log.js.map +1 -1
  144. package/dist/utils/network-policy.cjs +65 -0
  145. package/dist/utils/network-policy.cjs.map +1 -0
  146. package/dist/utils/network-policy.js +58 -77
  147. package/dist/utils/network-policy.js.map +1 -1
  148. package/dist/utils/normalizePath.cjs +27 -0
  149. package/dist/utils/normalizePath.cjs.map +1 -0
  150. package/dist/utils/normalizePath.js +21 -28
  151. package/dist/utils/normalizePath.js.map +1 -1
  152. package/dist/utils/resolveSignal.cjs +20 -0
  153. package/dist/utils/resolveSignal.cjs.map +1 -0
  154. package/dist/utils/resolveSignal.d.cts +15 -0
  155. package/dist/utils/resolveSignal.d.ts +12 -10
  156. package/dist/utils/resolveSignal.js +14 -17
  157. package/dist/utils/resolveSignal.js.map +1 -1
  158. package/dist/utils/sandbox-snapshot.cjs +14 -0
  159. package/dist/utils/sandbox-snapshot.cjs.map +1 -0
  160. package/dist/utils/sandbox-snapshot.d.cts +10 -0
  161. package/dist/utils/sandbox-snapshot.d.ts +11 -0
  162. package/dist/utils/sandbox-snapshot.js +14 -0
  163. package/dist/utils/sandbox-snapshot.js.map +1 -0
  164. package/dist/utils/types.cjs +13 -0
  165. package/dist/utils/types.cjs.map +1 -0
  166. package/dist/utils/types.d.cts +11 -0
  167. package/dist/utils/types.d.ts +5 -7
  168. package/dist/utils/types.js +8 -8
  169. package/dist/utils/types.js.map +1 -1
  170. package/dist/version.cjs +7 -0
  171. package/dist/version.cjs.map +1 -0
  172. package/dist/version.js +5 -5
  173. package/dist/version.js.map +1 -1
  174. package/package.json +23 -3
  175. package/dist/api-client/index.js.map +0 -1
  176. package/dist/auth/api.d.ts +0 -6
  177. package/dist/auth/error.d.ts +0 -11
  178. package/dist/auth/index.js.map +0 -1
  179. package/dist/auth/linked-project.d.ts +0 -10
  180. package/dist/auth/zod.d.ts +0 -5
  181. package/dist/constants.js +0 -3
  182. package/dist/constants.js.map +0 -1
  183. package/dist/index.js.map +0 -1
  184. package/dist/network-policy.js +0 -3
  185. package/dist/network-policy.js.map +0 -1
  186. package/dist/utils/array.d.ts +0 -9
  187. package/dist/utils/consume-readable.d.ts +0 -5
  188. package/dist/utils/convert-sandbox.d.ts +0 -6
  189. package/dist/utils/convert-sandbox.js +0 -14
  190. package/dist/utils/convert-sandbox.js.map +0 -1
  191. package/dist/utils/decode-base64-url.d.ts +0 -7
  192. package/dist/utils/dev-credentials.d.ts +0 -37
  193. package/dist/utils/log.d.ts +0 -2
  194. package/dist/utils/network-policy.d.ts +0 -7
  195. package/dist/utils/normalizePath.d.ts +0 -17
  196. package/dist/version.d.ts +0 -1
@@ -1,196 +1,138 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.cachedGenerateCredentials = void 0;
40
- exports.shouldPromptForCredentials = shouldPromptForCredentials;
41
- exports.generateCredentials = generateCredentials;
42
- exports.signInAndGetToken = signInAndGetToken;
43
- const picocolors_1 = __importDefault(require("picocolors"));
44
- const ms_1 = __importDefault(require("ms"));
45
- const Log = __importStar(require("./log"));
1
+ import { code, write } from "./log.js";
2
+ import pico from "picocolors";
3
+ import ms from "ms";
4
+
5
+ //#region src/utils/dev-credentials.ts
46
6
  async function importAuth() {
47
- const auth = await Promise.resolve().then(() => __importStar(require("../auth/index")));
48
- return auth;
7
+ return await import("../auth/index.js");
49
8
  }
50
9
  function shouldPromptForCredentials() {
51
- return (process.env.NODE_ENV !== "production" &&
52
- !["1", "true"].includes(process.env.CI || "") &&
53
- process.stdout.isTTY &&
54
- process.stdin.isTTY);
10
+ return process.env.NODE_ENV !== "production" && !["1", "true"].includes(process.env.CI || "") && process.stdout.isTTY && process.stdin.isTTY;
55
11
  }
56
12
  /**
57
- * Returns cached credentials for the given team/project combination.
58
- *
59
- * @remarks
60
- * The cache is keyed by `teamId` and `projectId`. A new credential generation
61
- * is triggered only when these values change or when a previous attempt failed.
62
- *
63
- * **Important:** Successfully resolved credentials are cached indefinitely and
64
- * will not be refreshed even if the token expires. Cache invalidation only occurs
65
- * on rejection (error). This is intentional for development use cases where
66
- * short-lived sessions don't require proactive token refresh.
67
- */
68
- exports.cachedGenerateCredentials = (() => {
69
- let cache = null;
70
- return async (opts) => {
71
- if (!cache ||
72
- cache[0].teamId !== opts.teamId ||
73
- cache[0].projectId !== opts.projectId) {
74
- const promise = generateCredentials(opts).catch((err) => {
75
- cache = null;
76
- throw err;
77
- });
78
- cache = [opts, promise];
79
- }
80
- const v = await cache[1];
81
- Log.write("warn", `using inferred credentials team=${v.teamId} project=${v.projectId}`);
82
- return v;
83
- };
13
+ * Returns cached credentials for the given team/project combination.
14
+ *
15
+ * @remarks
16
+ * The cache is keyed by `teamId` and `projectId`. A new credential generation
17
+ * is triggered only when these values change or when a previous attempt failed.
18
+ *
19
+ * **Important:** Successfully resolved credentials are cached indefinitely and
20
+ * will not be refreshed even if the token expires. Cache invalidation only occurs
21
+ * on rejection (error). This is intentional for development use cases where
22
+ * short-lived sessions don't require proactive token refresh.
23
+ */
24
+ const cachedGenerateCredentials = (() => {
25
+ let cache = null;
26
+ return async (opts) => {
27
+ if (!cache || cache[0].teamId !== opts.teamId || cache[0].projectId !== opts.projectId) cache = [opts, generateCredentials(opts).catch((err) => {
28
+ cache = null;
29
+ throw err;
30
+ })];
31
+ const v = await cache[1];
32
+ write("warn", `using inferred credentials team=${v.teamId} project=${v.projectId}`);
33
+ return v;
34
+ };
84
35
  })();
85
36
  /**
86
- * Generates credentials by authenticating and inferring scope.
87
- *
88
- * @internal This is exported for testing purposes. Consider using
89
- * {@link cachedGenerateCredentials} instead, which caches the result
90
- * to avoid redundant authentication flows.
91
- */
37
+ * Generates credentials by authenticating and inferring scope.
38
+ *
39
+ * @internal This is exported for testing purposes. Consider using
40
+ * {@link cachedGenerateCredentials} instead, which caches the result
41
+ * to avoid redundant authentication flows.
42
+ */
92
43
  async function generateCredentials(opts) {
93
- const { OAuth, pollForToken, getAuth, updateAuthConfig, inferScope } = await importAuth();
94
- let auth = getAuth();
95
- if (!auth?.token) {
96
- const timeout = process.env.VERCEL_URL
97
- ? /* when deployed to vercel we don't want to have a long timeout */ "1 minute"
98
- : "5 minutes";
99
- auth = await signInAndGetToken({ OAuth, pollForToken, getAuth }, timeout);
100
- }
101
- if (auth?.refreshToken &&
102
- auth.expiresAt &&
103
- auth.expiresAt.getTime() <= Date.now()) {
104
- const oauth = await OAuth();
105
- const newToken = await oauth.refreshToken(auth.refreshToken);
106
- auth = {
107
- expiresAt: new Date(Date.now() + newToken.expires_in * 1000),
108
- token: newToken.access_token,
109
- refreshToken: newToken.refresh_token || auth.refreshToken,
110
- };
111
- updateAuthConfig(auth);
112
- }
113
- if (!auth?.token) {
114
- throw new Error([
115
- `Failed to retrieve authentication token.`,
116
- `${picocolors_1.default.bold("hint:")} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,
117
- "├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox",
118
- "╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token",
119
- ].join("\n"));
120
- }
121
- if (opts.teamId && opts.projectId) {
122
- return {
123
- token: auth.token,
124
- teamId: opts.teamId,
125
- projectId: opts.projectId,
126
- };
127
- }
128
- const scope = await inferScope({ teamId: opts.teamId, token: auth.token });
129
- if (scope.created) {
130
- Log.write("info", `Created default project "${scope.projectId}" in team "${scope.teamId}".`);
131
- }
132
- return {
133
- token: auth.token,
134
- teamId: opts.teamId || scope.teamId,
135
- projectId: opts.projectId || scope.projectId,
136
- };
44
+ const { OAuth, pollForToken, getAuth, updateAuthConfig, inferScope } = await importAuth();
45
+ let auth = getAuth();
46
+ if (!auth?.token) {
47
+ const timeout = process.env.VERCEL_URL ? "1 minute" : "5 minutes";
48
+ auth = await signInAndGetToken({
49
+ OAuth,
50
+ pollForToken,
51
+ getAuth
52
+ }, timeout);
53
+ }
54
+ if (auth?.refreshToken && auth.expiresAt && auth.expiresAt.getTime() <= Date.now()) {
55
+ const newToken = await (await OAuth()).refreshToken(auth.refreshToken);
56
+ auth = {
57
+ expiresAt: new Date(Date.now() + newToken.expires_in * 1e3),
58
+ token: newToken.access_token,
59
+ refreshToken: newToken.refresh_token || auth.refreshToken
60
+ };
61
+ updateAuthConfig(auth);
62
+ }
63
+ if (!auth?.token) throw new Error([
64
+ `Failed to retrieve authentication token.`,
65
+ `${pico.bold("hint:")} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,
66
+ "├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox",
67
+ "╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token"
68
+ ].join("\n"));
69
+ if (opts.teamId && opts.projectId) return {
70
+ token: auth.token,
71
+ teamId: opts.teamId,
72
+ projectId: opts.projectId
73
+ };
74
+ const scope = await inferScope({
75
+ teamId: opts.teamId,
76
+ token: auth.token
77
+ });
78
+ if (scope.created) write("info", `Created default project "${scope.projectId}" in team "${scope.teamId}".`);
79
+ return {
80
+ token: auth.token,
81
+ teamId: opts.teamId || scope.teamId,
82
+ projectId: opts.projectId || scope.projectId
83
+ };
137
84
  }
138
85
  async function signInAndGetToken(auth, timeout) {
139
- Log.write("warn", [
140
- `No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,
141
- `│ ${picocolors_1.default.bold("help:")} this flow only happens on development environment.`,
142
- `│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`,
143
- ]);
144
- const oauth = await auth.OAuth();
145
- const request = await oauth.deviceAuthorizationRequest();
146
- Log.write("info", [
147
- `╰▶ To authenticate, visit: ${request.verification_uri_complete}`,
148
- ` or visit ${picocolors_1.default.italic(request.verification_uri)} and type ${picocolors_1.default.bold(request.user_code)}`,
149
- ` Press ${picocolors_1.default.bold("<return>")} to open in your browser`,
150
- ]);
151
- let error;
152
- const generator = auth.pollForToken({ request, oauth });
153
- let done = false;
154
- let spawnedTimeout = setTimeout(() => {
155
- if (done)
156
- return;
157
- const message = [
158
- `Authentication flow timed out after ${timeout}.`,
159
- `│ Make sure to provide a token to avoid prompting an interactive flow.`,
160
- `╰▶ ${picocolors_1.default.bold("help:")} Link your project with ${Log.code("npx vercel link")} to refresh OIDC token automatically.`,
161
- ].join("\n");
162
- error = new Error(message);
163
- // Note: generator.return() initiates cooperative cancellation. The generator's
164
- // finally block will abort pending setTimeout calls, but any in-flight HTTP
165
- // request will complete before the generator terminates. This is acceptable
166
- // for this dev-only timeout scenario.
167
- generator.return();
168
- }, (0, ms_1.default)(timeout));
169
- try {
170
- for await (const event of generator) {
171
- switch (event._tag) {
172
- case "SlowDown":
173
- case "Timeout":
174
- case "Response":
175
- break;
176
- case "Error":
177
- error = event.error;
178
- break;
179
- default:
180
- throw new Error(`Unknown event type: ${JSON.stringify(event)}`);
181
- }
182
- }
183
- }
184
- finally {
185
- done = true;
186
- clearTimeout(spawnedTimeout);
187
- }
188
- if (error) {
189
- Log.write("error", `${picocolors_1.default.bold("error:")} Authentication failed: ${error.message}`);
190
- throw error;
191
- }
192
- Log.write("success", `${picocolors_1.default.bold("done!")} Authenticated successfully!`);
193
- const stored = auth.getAuth();
194
- return stored;
86
+ write("warn", [
87
+ `No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,
88
+ `│ ${pico.bold("help:")} this flow only happens on development environment.`,
89
+ `│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`
90
+ ]);
91
+ const oauth = await auth.OAuth();
92
+ const request = await oauth.deviceAuthorizationRequest();
93
+ write("info", [
94
+ `╰▶ To authenticate, visit: ${request.verification_uri_complete}`,
95
+ ` or visit ${pico.italic(request.verification_uri)} and type ${pico.bold(request.user_code)}`,
96
+ ` Press ${pico.bold("<return>")} to open in your browser`
97
+ ]);
98
+ let error;
99
+ const generator = auth.pollForToken({
100
+ request,
101
+ oauth
102
+ });
103
+ let done = false;
104
+ let spawnedTimeout = setTimeout(() => {
105
+ if (done) return;
106
+ const message = [
107
+ `Authentication flow timed out after ${timeout}.`,
108
+ `│ Make sure to provide a token to avoid prompting an interactive flow.`,
109
+ `╰▶ ${pico.bold("help:")} Link your project with ${code("npx vercel link")} to refresh OIDC token automatically.`
110
+ ].join("\n");
111
+ error = new Error(message);
112
+ generator.return();
113
+ }, ms(timeout));
114
+ try {
115
+ for await (const event of generator) switch (event._tag) {
116
+ case "SlowDown":
117
+ case "Timeout":
118
+ case "Response": break;
119
+ case "Error":
120
+ error = event.error;
121
+ break;
122
+ default: throw new Error(`Unknown event type: ${JSON.stringify(event)}`);
123
+ }
124
+ } finally {
125
+ done = true;
126
+ clearTimeout(spawnedTimeout);
127
+ }
128
+ if (error) {
129
+ write("error", `${pico.bold("error:")} Authentication failed: ${error.message}`);
130
+ throw error;
131
+ }
132
+ write("success", `${pico.bold("done!")} Authenticated successfully!`);
133
+ return auth.getAuth();
195
134
  }
135
+
136
+ //#endregion
137
+ export { cachedGenerateCredentials, shouldPromptForCredentials };
196
138
  //# sourceMappingURL=dev-credentials.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dev-credentials.js","sourceRoot":"","sources":["../../src/utils/dev-credentials.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,gEAOC;AA8CD,kDA6DC;AAED,8CAqEC;AAnMD,4DAA8B;AAE9B,4CAAoB;AACpB,2CAA6B;AAE7B,KAAK,UAAU,UAAU;IACvB,MAAM,IAAI,GAAG,wDAAa,eAAe,GAAC,CAAC;IAC3C,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAgB,0BAA0B;IACxC,OAAO,CACL,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC;QAC7C,OAAO,CAAC,MAA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G,IAAI,CAAC,OAAO,EAAE,CAAC;IAC9B,OAAO,MAAM,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"dev-credentials.js","names":["cache:\n | [{ teamId?: string; projectId?: string }, Promise<Credentials>]\n | null","timeout: ms.StringValue","error: Error | undefined","Log.code"],"sources":["../../src/utils/dev-credentials.ts"],"sourcesContent":["import pico from \"picocolors\";\nimport type { Credentials } from \"./get-credentials.js\";\nimport ms from \"ms\";\nimport * as Log from \"./log.js\";\n\nasync function importAuth() {\n const auth = await import(\"../auth/index.js\");\n return auth;\n}\n\nexport function shouldPromptForCredentials(): boolean {\n return (\n process.env.NODE_ENV !== \"production\" &&\n ![\"1\", \"true\"].includes(process.env.CI || \"\") &&\n process.stdout.isTTY &&\n process.stdin.isTTY\n );\n}\n\n/**\n * Returns cached credentials for the given team/project combination.\n *\n * @remarks\n * The cache is keyed by `teamId` and `projectId`. A new credential generation\n * is triggered only when these values change or when a previous attempt failed.\n *\n * **Important:** Successfully resolved credentials are cached indefinitely and\n * will not be refreshed even if the token expires. Cache invalidation only occurs\n * on rejection (error). This is intentional for development use cases where\n * short-lived sessions don't require proactive token refresh.\n */\nexport const cachedGenerateCredentials = (() => {\n let cache:\n | [{ teamId?: string; projectId?: string }, Promise<Credentials>]\n | null = null;\n return async (opts: { projectId?: string; teamId?: string }) => {\n if (\n !cache ||\n cache[0].teamId !== opts.teamId ||\n cache[0].projectId !== opts.projectId\n ) {\n const promise = generateCredentials(opts).catch((err) => {\n cache = null;\n throw err;\n });\n cache = [opts, promise];\n }\n const v = await cache[1];\n Log.write(\n \"warn\",\n `using inferred credentials team=${v.teamId} project=${v.projectId}`,\n );\n return v;\n };\n})();\n\n/**\n * Generates credentials by authenticating and inferring scope.\n *\n * @internal This is exported for testing purposes. Consider using\n * {@link cachedGenerateCredentials} instead, which caches the result\n * to avoid redundant authentication flows.\n */\nexport async function generateCredentials(opts: {\n teamId?: string;\n projectId?: string;\n}): Promise<Credentials> {\n const { OAuth, pollForToken, getAuth, updateAuthConfig, inferScope } =\n await importAuth();\n let auth = getAuth();\n if (!auth?.token) {\n const timeout: ms.StringValue = process.env.VERCEL_URL\n ? /* when deployed to vercel we don't want to have a long timeout */ \"1 minute\"\n : \"5 minutes\";\n auth = await signInAndGetToken({ OAuth, pollForToken, getAuth }, timeout);\n }\n if (\n auth?.refreshToken &&\n auth.expiresAt &&\n auth.expiresAt.getTime() <= Date.now()\n ) {\n const oauth = await OAuth();\n const newToken = await oauth.refreshToken(auth.refreshToken);\n auth = {\n expiresAt: new Date(Date.now() + newToken.expires_in * 1000),\n token: newToken.access_token,\n refreshToken: newToken.refresh_token || auth.refreshToken,\n };\n updateAuthConfig(auth);\n }\n\n if (!auth?.token) {\n throw new Error(\n [\n `Failed to retrieve authentication token.`,\n `${pico.bold(\"hint:\")} Set VERCEL_OIDC_TOKEN or provide a Vercel API token.`,\n \"├▶ Sandbox docs: https://vercel.com/docs/vercel-sandbox\",\n \"╰▶ Access tokens: https://vercel.com/kb/guide/how-do-i-use-a-vercel-api-access-token\",\n ].join(\"\\n\"),\n );\n }\n\n if (opts.teamId && opts.projectId) {\n return {\n token: auth.token,\n teamId: opts.teamId,\n projectId: opts.projectId,\n };\n }\n\n const scope = await inferScope({ teamId: opts.teamId, token: auth.token });\n\n if (scope.created) {\n Log.write(\n \"info\",\n `Created default project \"${scope.projectId}\" in team \"${scope.teamId}\".`,\n );\n }\n\n return {\n token: auth.token,\n teamId: opts.teamId || scope.teamId,\n projectId: opts.projectId || scope.projectId,\n };\n}\n\nexport async function signInAndGetToken(\n auth: Pick<\n Awaited<ReturnType<typeof importAuth>>,\n \"OAuth\" | \"getAuth\" | \"pollForToken\"\n >,\n timeout: ms.StringValue,\n) {\n Log.write(\"warn\", [\n `No VERCEL_OIDC_TOKEN environment variable found, initiating device authorization flow...`,\n `│ ${pico.bold(\"help:\")} this flow only happens on development environment.`,\n `│ In production, make sure to set up a proper token, or set up Vercel OIDC [https://vercel.com/docs/oidc].`,\n ]);\n const oauth = await auth.OAuth();\n const request = await oauth.deviceAuthorizationRequest();\n Log.write(\"info\", [\n `╰▶ To authenticate, visit: ${request.verification_uri_complete}`,\n ` or visit ${pico.italic(request.verification_uri)} and type ${pico.bold(request.user_code)}`,\n ` Press ${pico.bold(\"<return>\")} to open in your browser`,\n ]);\n\n let error: Error | undefined;\n const generator = auth.pollForToken({ request, oauth });\n let done = false;\n let spawnedTimeout = setTimeout(() => {\n if (done) return;\n const message = [\n `Authentication flow timed out after ${timeout}.`,\n `│ Make sure to provide a token to avoid prompting an interactive flow.`,\n `╰▶ ${pico.bold(\"help:\")} Link your project with ${Log.code(\"npx vercel link\")} to refresh OIDC token automatically.`,\n ].join(\"\\n\");\n error = new Error(message);\n // Note: generator.return() initiates cooperative cancellation. The generator's\n // finally block will abort pending setTimeout calls, but any in-flight HTTP\n // request will complete before the generator terminates. This is acceptable\n // for this dev-only timeout scenario.\n generator.return();\n }, ms(timeout));\n try {\n for await (const event of generator) {\n switch (event._tag) {\n case \"SlowDown\":\n case \"Timeout\":\n case \"Response\":\n break;\n case \"Error\":\n error = event.error;\n break;\n default:\n throw new Error(\n `Unknown event type: ${JSON.stringify(event satisfies never)}`,\n );\n }\n }\n } finally {\n done = true;\n clearTimeout(spawnedTimeout);\n }\n\n if (error) {\n Log.write(\n \"error\",\n `${pico.bold(\"error:\")} Authentication failed: ${error.message}`,\n );\n throw error;\n }\n\n Log.write(\"success\", `${pico.bold(\"done!\")} Authenticated successfully!`);\n const stored = auth.getAuth();\n return stored;\n}\n"],"mappings":";;;;;AAKA,eAAe,aAAa;AAE1B,QADa,MAAM,OAAO;;AAI5B,SAAgB,6BAAsC;AACpD,QACE,QAAQ,IAAI,aAAa,gBACzB,CAAC,CAAC,KAAK,OAAO,CAAC,SAAS,QAAQ,IAAI,MAAM,GAAG,IAC7C,QAAQ,OAAO,SACf,QAAQ,MAAM;;;;;;;;;;;;;;AAgBlB,MAAa,mCAAmC;CAC9C,IAAIA,QAEO;AACX,QAAO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_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_decode_base64_url = require('./decode-base64-url.cjs');
3
+ const require_dev_credentials = require('./dev-credentials.cjs');
4
+ let zod = require("zod");
5
+ let __vercel_oidc = require("@vercel/oidc");
6
+
7
+ //#region src/utils/get-credentials.ts
8
+ /**
9
+ * Error thrown when OIDC context is not available in local development,
10
+ * therefore we should guide how to ensure it is set up by linking a project
11
+ */
12
+ var LocalOidcContextError = class extends Error {
13
+ constructor(cause) {
14
+ const message = [
15
+ "Could not get credentials from OIDC context.",
16
+ "Please link your Vercel project using `npx vercel link`.",
17
+ "Then, pull an initial OIDC token with `npx vercel env pull`",
18
+ "and retry.",
19
+ "╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly."
20
+ ].join("\n");
21
+ super(message, { cause });
22
+ this.name = "LocalOidcContextError";
23
+ }
24
+ };
25
+ /**
26
+ * Error thrown when OIDC context is not available in Vercel environment,
27
+ * therefore we should guide how to set it up.
28
+ */
29
+ var VercelOidcContextError = class extends Error {
30
+ constructor(cause) {
31
+ const message = [
32
+ "Could not get credentials from OIDC context.",
33
+ "Please make sure OIDC is set up for your project",
34
+ "╰▶ Docs: https://vercel.com/docs/oidc"
35
+ ].join("\n");
36
+ super(message, { cause });
37
+ this.name = "VercelOidcContextError";
38
+ }
39
+ };
40
+ async function getVercelToken(opts) {
41
+ try {
42
+ return getCredentialsFromOIDCToken(await (0, __vercel_oidc.getVercelOidcToken)({
43
+ team: opts.teamId,
44
+ project: opts.projectId
45
+ }));
46
+ } catch (error) {
47
+ if (!require_dev_credentials.shouldPromptForCredentials()) if (process.env.VERCEL_URL) throw new VercelOidcContextError(error);
48
+ else throw new LocalOidcContextError(error);
49
+ return await require_dev_credentials.cachedGenerateCredentials(opts);
50
+ }
51
+ }
52
+ /**
53
+ * Allow to get credentials to access the Vercel API. Credentials can be
54
+ * provided in two different ways:
55
+ *
56
+ * 1. By passing an object with the `teamId`, `token`, and `projectId` properties.
57
+ * 2. By using an environment variable VERCEL_OIDC_TOKEN.
58
+ *
59
+ * If both methods are used, the object properties take precedence over the
60
+ * environment variable. If neither method is used, an error is thrown.
61
+ */
62
+ async function getCredentials(params) {
63
+ const credentials = getCredentialsFromParams(params ?? {});
64
+ if (credentials) return credentials;
65
+ return await getVercelToken({
66
+ teamId: params && typeof params === "object" && "teamId" in params && typeof params.teamId === "string" ? params.teamId : void 0,
67
+ projectId: params && typeof params === "object" && "projectId" in params && typeof params.projectId === "string" ? params.projectId : void 0
68
+ });
69
+ }
70
+ /**
71
+ * Attempt to extract credentials from the provided parameters. Either all
72
+ * required fields (`token`, `teamId`, and `projectId`) must be present
73
+ * or none of them, otherwise an error is thrown.
74
+ */
75
+ function getCredentialsFromParams(params) {
76
+ if (!params || typeof params !== "object") return null;
77
+ const missing = [
78
+ "token" in params && typeof params.token === "string" ? null : "token",
79
+ "teamId" in params && typeof params.teamId === "string" ? null : "teamId",
80
+ "projectId" in params && typeof params.projectId === "string" ? null : "projectId"
81
+ ].filter((value) => value !== null);
82
+ if (missing.length === 0) return {
83
+ token: params.token,
84
+ projectId: params.projectId,
85
+ teamId: params.teamId
86
+ };
87
+ if (missing.length < 3) throw new Error(`Missing credentials parameters to access the Vercel API: ${missing.filter((value) => value !== null).join(", ")}`);
88
+ return null;
89
+ }
90
+ /**
91
+ * Schema to validate the payload of the Vercel OIDC token where we expect
92
+ * to find the `teamId` and `projectId`.
93
+ */
94
+ const schema = zod.z.object({
95
+ exp: zod.z.number().optional().describe("Expiry timestamp (seconds since epoch)"),
96
+ iat: zod.z.number().optional().describe("Issued at timestamp"),
97
+ owner_id: zod.z.string(),
98
+ project_id: zod.z.string()
99
+ });
100
+ /**
101
+ * Extracts credentials from a Vercel OIDC token. The token is expected to be
102
+ * a JWT with a payload that contains `project_id` and `owner_id`.
103
+ *
104
+ * @param token - The Vercel OIDC token.
105
+ * @returns An object containing the token, projectId, and teamId.
106
+ * @throws If the token is invalid or does not contain the required fields.
107
+ */
108
+ function getCredentialsFromOIDCToken(token) {
109
+ try {
110
+ const payload = schema.parse(require_decode_base64_url.decodeBase64Url(token.split(".")[1]));
111
+ return {
112
+ token,
113
+ projectId: payload.project_id,
114
+ teamId: payload.owner_id
115
+ };
116
+ } catch (error) {
117
+ throw new Error(`Invalid Vercel OIDC token: ${error instanceof Error ? error.message : String(error)}`);
118
+ }
119
+ }
120
+
121
+ //#endregion
122
+ exports.getCredentials = getCredentials;
123
+ //# sourceMappingURL=get-credentials.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-credentials.cjs","names":["shouldPromptForCredentials","cachedGenerateCredentials","z","decodeBase64Url"],"sources":["../../src/utils/get-credentials.ts"],"sourcesContent":["import { getVercelOidcToken } from \"@vercel/oidc\";\nimport { decodeBase64Url } from \"./decode-base64-url.js\";\nimport { z } from \"zod\";\nimport {\n cachedGenerateCredentials,\n shouldPromptForCredentials,\n} from \"./dev-credentials.js\";\n\nexport interface Credentials {\n /**\n * Authentication token for the Vercel API. It could be an OIDC token\n * or a personal access token.\n */\n token: string;\n /**\n * The ID of the project to associate Sandbox operations.\n */\n projectId: string;\n /**\n * The ID of the team to associate Sandbox operations.\n */\n teamId: string;\n}\n\n/**\n * Error thrown when OIDC context is not available in local development,\n * therefore we should guide how to ensure it is set up by linking a project\n */\nexport class LocalOidcContextError extends Error {\n name = \"LocalOidcContextError\";\n constructor(cause: unknown) {\n const message = [\n \"Could not get credentials from OIDC context.\",\n \"Please link your Vercel project using `npx vercel link`.\",\n \"Then, pull an initial OIDC token with `npx vercel env pull`\",\n \"and retry.\",\n \"╰▶ Make sure you are loading `.env.local` correctly, or passing $VERCEL_OIDC_TOKEN directly.\",\n ].join(\"\\n\");\n super(message, { cause });\n }\n}\n\n/**\n * Error thrown when OIDC context is not available in Vercel environment,\n * therefore we should guide how to set it up.\n */\nexport class VercelOidcContextError extends Error {\n name = \"VercelOidcContextError\";\n constructor(cause: unknown) {\n const message = [\n \"Could not get credentials from OIDC context.\",\n \"Please make sure OIDC is set up for your project\",\n \"╰▶ Docs: https://vercel.com/docs/oidc\",\n ].join(\"\\n\");\n super(message, { cause });\n }\n}\n\nasync function getVercelToken(opts: {\n teamId?: string;\n projectId?: string;\n}): Promise<Credentials> {\n try {\n const token = await getVercelOidcToken({\n team: opts.teamId,\n project: opts.projectId,\n });\n return getCredentialsFromOIDCToken(token);\n } catch (error) {\n if (!shouldPromptForCredentials()) {\n if (process.env.VERCEL_URL) {\n throw new VercelOidcContextError(error);\n } else {\n throw new LocalOidcContextError(error);\n }\n }\n return await cachedGenerateCredentials(opts);\n }\n}\n\n/**\n * Allow to get credentials to access the Vercel API. Credentials can be\n * provided in two different ways:\n *\n * 1. By passing an object with the `teamId`, `token`, and `projectId` properties.\n * 2. By using an environment variable VERCEL_OIDC_TOKEN.\n *\n * If both methods are used, the object properties take precedence over the\n * environment variable. If neither method is used, an error is thrown.\n */\nexport async function getCredentials(params?: unknown): Promise<Credentials> {\n const credentials = getCredentialsFromParams(params ?? {});\n if (credentials) {\n return credentials;\n }\n\n const oidcToken = await getVercelToken({\n teamId:\n params &&\n typeof params === \"object\" &&\n \"teamId\" in params &&\n typeof params.teamId === \"string\"\n ? params.teamId\n : undefined,\n projectId:\n params &&\n typeof params === \"object\" &&\n \"projectId\" in params &&\n typeof params.projectId === \"string\"\n ? params.projectId\n : undefined,\n });\n\n return oidcToken;\n}\n\n/**\n * Attempt to extract credentials from the provided parameters. Either all\n * required fields (`token`, `teamId`, and `projectId`) must be present\n * or none of them, otherwise an error is thrown.\n */\nfunction getCredentialsFromParams(params: unknown): Credentials | null {\n // Type guard: params must be an object\n if (!params || typeof params !== \"object\") {\n return null;\n }\n\n const missing = [\n \"token\" in params && typeof params.token === \"string\" ? null : \"token\",\n \"teamId\" in params && typeof params.teamId === \"string\" ? null : \"teamId\",\n \"projectId\" in params && typeof params.projectId === \"string\"\n ? null\n : \"projectId\",\n ].filter((value) => value !== null);\n\n if (missing.length === 0) {\n return {\n token: (params as any).token,\n projectId: (params as any).projectId,\n teamId: (params as any).teamId,\n };\n }\n\n if (missing.length < 3) {\n throw new Error(\n `Missing credentials parameters to access the Vercel API: ${missing\n .filter((value) => value !== null)\n .join(\", \")}`,\n );\n }\n\n return null;\n}\n\n/**\n * Schema to validate the payload of the Vercel OIDC token where we expect\n * to find the `teamId` and `projectId`.\n */\nexport const schema = z.object({\n exp: z.number().optional().describe(\"Expiry timestamp (seconds since epoch)\"),\n iat: z.number().optional().describe(\"Issued at timestamp\"),\n owner_id: z.string(),\n project_id: z.string(),\n});\n\n/**\n * Extracts credentials from a Vercel OIDC token. The token is expected to be\n * a JWT with a payload that contains `project_id` and `owner_id`.\n *\n * @param token - The Vercel OIDC token.\n * @returns An object containing the token, projectId, and teamId.\n * @throws If the token is invalid or does not contain the required fields.\n */\nfunction getCredentialsFromOIDCToken(token: string): Credentials {\n try {\n const payload = schema.parse(decodeBase64Url(token.split(\".\")[1]));\n return {\n token,\n projectId: payload.project_id,\n teamId: payload.owner_id,\n };\n } catch (error) {\n throw new Error(\n `Invalid Vercel OIDC token: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AA4BA,IAAa,wBAAb,cAA2C,MAAM;CAE/C,YAAY,OAAgB;EAC1B,MAAM,UAAU;GACd;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,KAAK;AACZ,QAAM,SAAS,EAAE,OAAO,CAAC;OAT3B,OAAO;;;;;;;AAiBT,IAAa,yBAAb,cAA4C,MAAM;CAEhD,YAAY,OAAgB;EAC1B,MAAM,UAAU;GACd;GACA;GACA;GACD,CAAC,KAAK,KAAK;AACZ,QAAM,SAAS,EAAE,OAAO,CAAC;OAP3B,OAAO;;;AAWT,eAAe,eAAe,MAGL;AACvB,KAAI;AAKF,SAAO,4BAJO,4CAAyB;GACrC,MAAM,KAAK;GACX,SAAS,KAAK;GACf,CAAC,CACuC;UAClC,OAAO;AACd,MAAI,CAACA,oDAA4B,CAC/B,KAAI,QAA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B,MAAM,MAAM,IAAI,CAAC,GAAG,CAAC;AAClE,SAAO;GACL;GACA,WAAW,QAAQ;GACnB,QAAQ,QAAQ;GACjB;UACM,OAAO;AACd,QAAM,IAAI,MACR,8BAA8B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GACrF"}
@@ -0,0 +1,21 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/utils/get-credentials.d.ts
4
+ interface Credentials {
5
+ /**
6
+ * Authentication token for the Vercel API. It could be an OIDC token
7
+ * or a personal access token.
8
+ */
9
+ token: string;
10
+ /**
11
+ * The ID of the project to associate Sandbox operations.
12
+ */
13
+ projectId: string;
14
+ /**
15
+ * The ID of the team to associate Sandbox operations.
16
+ */
17
+ teamId: string;
18
+ }
19
+ //#endregion
20
+ export { Credentials };
21
+ //# sourceMappingURL=get-credentials.d.cts.map
@@ -1,63 +1,21 @@
1
1
  import { z } from "zod";
2
- export interface Credentials {
3
- /**
4
- * Authentication token for the Vercel API. It could be an OIDC token
5
- * or a personal access token.
6
- */
7
- token: string;
8
- /**
9
- * The ID of the project to associate Sandbox operations.
10
- */
11
- projectId: string;
12
- /**
13
- * The ID of the team to associate Sandbox operations.
14
- */
15
- teamId: string;
2
+
3
+ //#region src/utils/get-credentials.d.ts
4
+ interface Credentials {
5
+ /**
6
+ * Authentication token for the Vercel API. It could be an OIDC token
7
+ * or a personal access token.
8
+ */
9
+ token: string;
10
+ /**
11
+ * The ID of the project to associate Sandbox operations.
12
+ */
13
+ projectId: string;
14
+ /**
15
+ * The ID of the team to associate Sandbox operations.
16
+ */
17
+ teamId: string;
16
18
  }
17
- /**
18
- * Error thrown when OIDC context is not available in local development,
19
- * therefore we should guide how to ensure it is set up by linking a project
20
- */
21
- export declare class LocalOidcContextError extends Error {
22
- name: string;
23
- constructor(cause: unknown);
24
- }
25
- /**
26
- * Error thrown when OIDC context is not available in Vercel environment,
27
- * therefore we should guide how to set it up.
28
- */
29
- export declare class VercelOidcContextError extends Error {
30
- name: string;
31
- constructor(cause: unknown);
32
- }
33
- /**
34
- * Allow to get credentials to access the Vercel API. Credentials can be
35
- * provided in two different ways:
36
- *
37
- * 1. By passing an object with the `teamId`, `token`, and `projectId` properties.
38
- * 2. By using an environment variable VERCEL_OIDC_TOKEN.
39
- *
40
- * If both methods are used, the object properties take precedence over the
41
- * environment variable. If neither method is used, an error is thrown.
42
- */
43
- export declare function getCredentials(params?: unknown): Promise<Credentials>;
44
- /**
45
- * Schema to validate the payload of the Vercel OIDC token where we expect
46
- * to find the `teamId` and `projectId`.
47
- */
48
- export declare const schema: z.ZodObject<{
49
- exp: z.ZodOptional<z.ZodNumber>;
50
- iat: z.ZodOptional<z.ZodNumber>;
51
- owner_id: z.ZodString;
52
- project_id: z.ZodString;
53
- }, "strip", z.ZodTypeAny, {
54
- owner_id: string;
55
- project_id: string;
56
- exp?: number | undefined;
57
- iat?: number | undefined;
58
- }, {
59
- owner_id: string;
60
- project_id: string;
61
- exp?: number | undefined;
62
- iat?: number | undefined;
63
- }>;
19
+ //#endregion
20
+ export { Credentials };
21
+ //# sourceMappingURL=get-credentials.d.ts.map