@vercel/sandbox 1.9.2 → 1.10.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 (49) hide show
  1. package/dist/api-client/api-client.cjs +23 -5
  2. package/dist/api-client/api-client.cjs.map +1 -1
  3. package/dist/api-client/api-client.d.cts +25 -25
  4. package/dist/api-client/api-client.d.ts +25 -25
  5. package/dist/api-client/api-client.js +23 -5
  6. package/dist/api-client/api-client.js.map +1 -1
  7. package/dist/api-client/base-client.cjs +2 -1
  8. package/dist/api-client/base-client.cjs.map +1 -1
  9. package/dist/api-client/base-client.js +2 -1
  10. package/dist/api-client/base-client.js.map +1 -1
  11. package/dist/api-client/validators.d.cts +102 -102
  12. package/dist/api-client/validators.d.ts +102 -102
  13. package/dist/auth/index.cjs +0 -1
  14. package/dist/auth/index.d.cts +2 -2
  15. package/dist/auth/index.d.ts +2 -2
  16. package/dist/auth/index.js +2 -2
  17. package/dist/auth/project.cjs +124 -26
  18. package/dist/auth/project.cjs.map +1 -1
  19. package/dist/auth/project.d.cts +9 -13
  20. package/dist/auth/project.d.ts +9 -13
  21. package/dist/auth/project.js +125 -26
  22. package/dist/auth/project.js.map +1 -1
  23. package/dist/filesystem.cjs +499 -0
  24. package/dist/filesystem.cjs.map +1 -0
  25. package/dist/filesystem.d.cts +258 -0
  26. package/dist/filesystem.d.ts +258 -0
  27. package/dist/filesystem.js +497 -0
  28. package/dist/filesystem.js.map +1 -0
  29. package/dist/index.cjs +2 -0
  30. package/dist/index.d.cts +3 -2
  31. package/dist/index.d.ts +3 -2
  32. package/dist/index.js +2 -1
  33. package/dist/sandbox.cjs +2 -0
  34. package/dist/sandbox.cjs.map +1 -1
  35. package/dist/sandbox.d.cts +20 -9
  36. package/dist/sandbox.d.ts +20 -9
  37. package/dist/sandbox.js +2 -0
  38. package/dist/sandbox.js.map +1 -1
  39. package/dist/snapshot.cjs +39 -5
  40. package/dist/snapshot.cjs.map +1 -1
  41. package/dist/snapshot.d.cts +36 -14
  42. package/dist/snapshot.d.ts +36 -14
  43. package/dist/snapshot.js +38 -5
  44. package/dist/snapshot.js.map +1 -1
  45. package/dist/version.cjs +1 -1
  46. package/dist/version.cjs.map +1 -1
  47. package/dist/version.js +1 -1
  48. package/dist/version.js.map +1 -1
  49. package/package.json +1 -1
@@ -5,24 +5,47 @@ const require_linked_project = require('./linked-project.cjs');
5
5
  let zod = require("zod");
6
6
 
7
7
  //#region src/auth/project.ts
8
- const TeamsSchema = zod.z.object({ teams: zod.z.array(zod.z.object({ slug: zod.z.string() })).min(1, `No teams found. Please create a team first.`) });
8
+ const UserSchema = zod.z.object({ user: zod.z.object({
9
+ defaultTeamId: zod.z.string().nullable(),
10
+ username: zod.z.string()
11
+ }) });
12
+ const TeamSchema = zod.z.object({
13
+ id: zod.z.string(),
14
+ slug: zod.z.string(),
15
+ updatedAt: zod.z.number(),
16
+ membership: zod.z.object({ role: zod.z.string() }),
17
+ billing: zod.z.object({ plan: zod.z.string() })
18
+ });
19
+ const TeamsSchema = zod.z.object({
20
+ teams: zod.z.array(TeamSchema),
21
+ pagination: zod.z.object({
22
+ count: zod.z.number(),
23
+ next: zod.z.number().nullable()
24
+ })
25
+ });
9
26
  const DEFAULT_PROJECT_NAME = "vercel-sandbox-default-project";
27
+ /** Status codes that mean "this team can't be used, try the next one". */
28
+ function isSkippableTeamError(e) {
29
+ return e instanceof require_error.NotOk && (e.response.statusCode === 402 || e.response.statusCode === 403);
30
+ }
10
31
  /**
11
32
  * Resolves the team and project scope for sandbox operations.
12
33
  *
13
34
  * First checks for a locally linked project in `.vercel/project.json`.
14
35
  * If found, uses the `projectId` and `orgId` from there.
15
36
  *
16
- * Otherwise, if `teamId` is not provided, selects the first available team for the account.
17
- * Ensures a default project exists within the team, creating it if necessary.
37
+ * Otherwise, if `teamId` is not provided, builds an ordered list of candidate
38
+ * teams to try: the user's `defaultTeamId` first (if set), then hobby-plan
39
+ * teams where the user has an OWNER role (preferring the personal team matching
40
+ * the username, then the most recently updated). Tries each candidate until one
41
+ * succeeds.
18
42
  *
19
43
  * @param opts.token - Vercel API authentication token.
20
- * @param opts.teamId - Optional team slug. If omitted, the first team is selected.
44
+ * @param opts.teamId - Optional team slug. If omitted, candidate teams are resolved automatically.
21
45
  * @param opts.cwd - Optional directory to search for `.vercel/project.json`. Defaults to `process.cwd()`.
22
46
  * @returns The resolved scope with `projectId`, `teamId`, and whether the project was `created`.
23
47
  *
24
48
  * @throws {NotOk} If the API returns an error other than 404 when checking the project.
25
- * @throws {ZodError} If no teams exist for the account.
26
49
  *
27
50
  * @example
28
51
  * ```ts
@@ -32,22 +55,89 @@ const DEFAULT_PROJECT_NAME = "vercel-sandbox-default-project";
32
55
  */
33
56
  async function inferScope(opts) {
34
57
  const linkedProject = await require_linked_project.readLinkedProject(opts.cwd ?? process.cwd());
35
- if (linkedProject) return {
36
- ...linkedProject,
37
- created: false
38
- };
39
- const teamId = opts.teamId ?? await selectTeam(opts.token);
58
+ if (linkedProject) {
59
+ const slugs = await resolveLinkedProjectSlugs(opts.token, linkedProject.teamId, linkedProject.projectId);
60
+ return {
61
+ ...linkedProject,
62
+ created: false,
63
+ ...slugs
64
+ };
65
+ }
66
+ if (opts.teamId) return tryTeam(opts.token, opts.teamId);
67
+ const { defaultTeamId, username } = (await require_api.fetchApi({
68
+ token: opts.token,
69
+ endpoint: "/v2/user"
70
+ }).then(UserSchema.parse)).user;
71
+ if (defaultTeamId) try {
72
+ const result = await tryTeam(opts.token, defaultTeamId);
73
+ try {
74
+ const team = await require_api.fetchApi({
75
+ token: opts.token,
76
+ endpoint: `/v2/teams/${encodeURIComponent(defaultTeamId)}`
77
+ }).then(zod.z.object({ slug: zod.z.string() }).parse);
78
+ return {
79
+ ...result,
80
+ teamSlug: team.slug
81
+ };
82
+ } catch {
83
+ return result;
84
+ }
85
+ } catch (e) {
86
+ if (!isSkippableTeamError(e)) throw e;
87
+ }
88
+ let next = null;
89
+ do {
90
+ const endpoint = next === null ? "/v2/teams?limit=20" : `/v2/teams?limit=20&until=${next}`;
91
+ const page = await require_api.fetchApi({
92
+ token: opts.token,
93
+ endpoint
94
+ }).then(TeamsSchema.parse);
95
+ next = page.pagination.next;
96
+ const hobbyOwnerTeams = page.teams.filter((t) => t.membership.role === "OWNER" && t.billing.plan === "hobby");
97
+ if (hobbyOwnerTeams.length === 0) continue;
98
+ const bestHobbyTeam = hobbyOwnerTeams.find((t) => t.slug === username) ?? hobbyOwnerTeams.sort((a, b) => b.updatedAt - a.updatedAt)[0];
99
+ if (bestHobbyTeam && bestHobbyTeam.id !== defaultTeamId) try {
100
+ return {
101
+ ...await tryTeam(opts.token, bestHobbyTeam.id),
102
+ teamSlug: bestHobbyTeam.slug
103
+ };
104
+ } catch (e) {
105
+ if (!isSkippableTeamError(e)) throw e;
106
+ }
107
+ } while (next !== null);
108
+ try {
109
+ return {
110
+ ...await tryTeam(opts.token, username),
111
+ teamSlug: username
112
+ };
113
+ } catch (e) {
114
+ if (!isSkippableTeamError(e)) throw e;
115
+ }
116
+ throw new require_error.NotOk({
117
+ statusCode: 403,
118
+ responseText: `Authenticated as "${username}" but none of the available teams allow sandbox creation. Specify a team explicitly with --scope <team-id-or-slug>.`
119
+ });
120
+ }
121
+ /**
122
+ * Attempts to use a specific team for sandbox operations by checking for
123
+ * (or creating) the default project within that team.
124
+ *
125
+ * @returns The resolved scope if the team is usable.
126
+ * @throws {NotOk} On authorization or other API errors.
127
+ */
128
+ async function tryTeam(token, teamId) {
129
+ const teamParam = teamId.startsWith("team_") ? `teamId=${encodeURIComponent(teamId)}` : `slug=${encodeURIComponent(teamId)}`;
40
130
  let created = false;
41
131
  try {
42
132
  await require_api.fetchApi({
43
- token: opts.token,
44
- endpoint: `/v2/projects/${encodeURIComponent(DEFAULT_PROJECT_NAME)}?slug=${encodeURIComponent(teamId)}`
133
+ token,
134
+ endpoint: `/v2/projects/${encodeURIComponent(DEFAULT_PROJECT_NAME)}?${teamParam}`
45
135
  });
46
136
  } catch (e) {
47
137
  if (!(e instanceof require_error.NotOk) || e.response.statusCode !== 404) throw e;
48
138
  await require_api.fetchApi({
49
- token: opts.token,
50
- endpoint: `/v11/projects?slug=${encodeURIComponent(teamId)}`,
139
+ token,
140
+ endpoint: `/v11/projects?${teamParam}`,
51
141
  method: "POST",
52
142
  body: JSON.stringify({ name: DEFAULT_PROJECT_NAME })
53
143
  });
@@ -60,21 +150,29 @@ async function inferScope(opts) {
60
150
  };
61
151
  }
62
152
  /**
63
- * Selects a team for the current token by querying the Teams API and
64
- * returning the slug of the first team in the result set.
65
- *
66
- * @param token - Authentication token used to call the Vercel API.
67
- * @returns A promise that resolves to the first team's slug.
153
+ * Best-effort resolution of team slug and project name for a linked project.
154
+ * Both IDs may be opaque (e.g. `team_xxx`, `prj_xxx`), so we fetch the
155
+ * human-readable names from the API in parallel.
68
156
  */
69
- async function selectTeam(token) {
70
- const { teams: [team] } = await require_api.fetchApi({
71
- token,
72
- endpoint: "/v2/teams?limit=1"
73
- }).then(TeamsSchema.parse);
74
- return team.slug;
157
+ async function resolveLinkedProjectSlugs(token, teamId, projectId) {
158
+ try {
159
+ const teamParam = teamId.startsWith("team_") ? `teamId=${encodeURIComponent(teamId)}` : `slug=${encodeURIComponent(teamId)}`;
160
+ const [teamData, projectData] = await Promise.all([require_api.fetchApi({
161
+ token,
162
+ endpoint: `/v2/teams/${encodeURIComponent(teamId)}`
163
+ }).then(zod.z.object({ slug: zod.z.string() }).parse), require_api.fetchApi({
164
+ token,
165
+ endpoint: `/v2/projects/${encodeURIComponent(projectId)}?${teamParam}`
166
+ }).then(zod.z.object({ name: zod.z.string() }).parse)]);
167
+ return {
168
+ teamSlug: teamData.slug,
169
+ projectSlug: projectData.name
170
+ };
171
+ } catch {
172
+ return {};
173
+ }
75
174
  }
76
175
 
77
176
  //#endregion
78
177
  exports.inferScope = inferScope;
79
- exports.selectTeam = selectTeam;
80
178
  //# sourceMappingURL=project.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"project.cjs","names":["z","readLinkedProject","fetchApi","NotOk"],"sources":["../../src/auth/project.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { fetchApi } from \"./api.js\";\nimport { NotOk } from \"./error.js\";\nimport { readLinkedProject } from \"./linked-project.js\";\n\nconst TeamsSchema = z.object({\n teams: z\n .array(\n z.object({\n slug: z.string(),\n }),\n )\n .min(1, `No teams found. Please create a team first.`),\n});\n\nconst DEFAULT_PROJECT_NAME = \"vercel-sandbox-default-project\";\n\n/**\n * Resolves the team and project scope for sandbox operations.\n *\n * First checks for a locally linked project in `.vercel/project.json`.\n * If found, uses the `projectId` and `orgId` from there.\n *\n * Otherwise, if `teamId` is not provided, selects the first available team for the account.\n * Ensures a default project exists within the team, creating it if necessary.\n *\n * @param opts.token - Vercel API authentication token.\n * @param opts.teamId - Optional team slug. If omitted, the first team is selected.\n * @param opts.cwd - Optional directory to search for `.vercel/project.json`. Defaults to `process.cwd()`.\n * @returns The resolved scope with `projectId`, `teamId`, and whether the project was `created`.\n *\n * @throws {NotOk} If the API returns an error other than 404 when checking the project.\n * @throws {ZodError} If no teams exist for the account.\n *\n * @example\n * ```ts\n * const scope = await inferScope({ token: \"vercel_...\" });\n * // => { projectId: \"vercel-sandbox-default-project\", teamId: \"my-team\", created: false }\n * ```\n */\nexport async function inferScope(opts: {\n token: string;\n teamId?: string;\n cwd?: string;\n}): Promise<{ projectId: string; teamId: string; created: boolean }> {\n const linkedProject = await readLinkedProject(opts.cwd ?? process.cwd());\n if (linkedProject) {\n return { ...linkedProject, created: false };\n }\n\n const teamId = opts.teamId ?? (await selectTeam(opts.token));\n\n let created = false;\n try {\n await fetchApi({\n token: opts.token,\n endpoint: `/v2/projects/${encodeURIComponent(DEFAULT_PROJECT_NAME)}?slug=${encodeURIComponent(teamId)}`,\n });\n } catch (e) {\n if (!(e instanceof NotOk) || e.response.statusCode !== 404) {\n throw e;\n }\n\n await fetchApi({\n token: opts.token,\n endpoint: `/v11/projects?slug=${encodeURIComponent(teamId)}`,\n method: \"POST\",\n body: JSON.stringify({\n name: DEFAULT_PROJECT_NAME,\n }),\n });\n created = true;\n }\n\n return { projectId: DEFAULT_PROJECT_NAME, teamId, created };\n}\n\n/**\n * Selects a team for the current token by querying the Teams API and\n * returning the slug of the first team in the result set.\n *\n * @param token - Authentication token used to call the Vercel API.\n * @returns A promise that resolves to the first team's slug.\n */\nexport async function selectTeam(token: string) {\n const {\n teams: [team],\n } = await fetchApi({ token, endpoint: \"/v2/teams?limit=1\" }).then(\n TeamsSchema.parse,\n );\n return team.slug;\n}\n"],"mappings":";;;;;;;AAKA,MAAM,cAAcA,MAAE,OAAO,EAC3B,OAAOA,MACJ,MACCA,MAAE,OAAO,EACP,MAAMA,MAAE,QAAQ,EACjB,CAAC,CACH,CACA,IAAI,GAAG,8CAA8C,EACzD,CAAC;AAEF,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;AAyB7B,eAAsB,WAAW,MAIoC;CACnE,MAAM,gBAAgB,MAAMC,yCAAkB,KAAK,OAAO,QAAQ,KAAK,CAAC;AACxE,KAAI,cACF,QAAO;EAAE,GAAG;EAAe,SAAS;EAAO;CAG7C,MAAM,SAAS,KAAK,UAAW,MAAM,WAAW,KAAK,MAAM;CAE3D,IAAI,UAAU;AACd,KAAI;AACF,QAAMC,qBAAS;GACb,OAAO,KAAK;GACZ,UAAU,gBAAgB,mBAAmB,qBAAqB,CAAC,QAAQ,mBAAmB,OAAO;GACtG,CAAC;UACK,GAAG;AACV,MAAI,EAAE,aAAaC,wBAAU,EAAE,SAAS,eAAe,IACrD,OAAM;AAGR,QAAMD,qBAAS;GACb,OAAO,KAAK;GACZ,UAAU,sBAAsB,mBAAmB,OAAO;GAC1D,QAAQ;GACR,MAAM,KAAK,UAAU,EACnB,MAAM,sBACP,CAAC;GACH,CAAC;AACF,YAAU;;AAGZ,QAAO;EAAE,WAAW;EAAsB;EAAQ;EAAS;;;;;;;;;AAU7D,eAAsB,WAAW,OAAe;CAC9C,MAAM,EACJ,OAAO,CAAC,UACN,MAAMA,qBAAS;EAAE;EAAO,UAAU;EAAqB,CAAC,CAAC,KAC3D,YAAY,MACb;AACD,QAAO,KAAK"}
1
+ {"version":3,"file":"project.cjs","names":["z","NotOk","readLinkedProject","fetchApi","next: number | null","endpoint: string"],"sources":["../../src/auth/project.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { fetchApi } from \"./api.js\";\nimport { NotOk } from \"./error.js\";\nimport { readLinkedProject } from \"./linked-project.js\";\n\nconst UserSchema = z.object({\n user: z.object({\n defaultTeamId: z.string().nullable(),\n username: z.string(),\n }),\n});\n\nconst TeamSchema = z.object({\n id: z.string(),\n slug: z.string(),\n updatedAt: z.number(),\n membership: z.object({\n role: z.string(),\n }),\n billing: z.object({\n plan: z.string(),\n }),\n});\n\nconst TeamsSchema = z.object({\n teams: z.array(TeamSchema),\n pagination: z.object({\n count: z.number(),\n next: z.number().nullable(),\n }),\n});\n\nconst DEFAULT_PROJECT_NAME = \"vercel-sandbox-default-project\";\n\n/** Status codes that mean \"this team can't be used, try the next one\". */\nfunction isSkippableTeamError(e: unknown): boolean {\n return e instanceof NotOk && (e.response.statusCode === 402 || e.response.statusCode === 403);\n}\n\n/**\n * Resolves the team and project scope for sandbox operations.\n *\n * First checks for a locally linked project in `.vercel/project.json`.\n * If found, uses the `projectId` and `orgId` from there.\n *\n * Otherwise, if `teamId` is not provided, builds an ordered list of candidate\n * teams to try: the user's `defaultTeamId` first (if set), then hobby-plan\n * teams where the user has an OWNER role (preferring the personal team matching\n * the username, then the most recently updated). Tries each candidate until one\n * succeeds.\n *\n * @param opts.token - Vercel API authentication token.\n * @param opts.teamId - Optional team slug. If omitted, candidate teams are resolved automatically.\n * @param opts.cwd - Optional directory to search for `.vercel/project.json`. Defaults to `process.cwd()`.\n * @returns The resolved scope with `projectId`, `teamId`, and whether the project was `created`.\n *\n * @throws {NotOk} If the API returns an error other than 404 when checking the project.\n *\n * @example\n * ```ts\n * const scope = await inferScope({ token: \"vercel_...\" });\n * // => { projectId: \"vercel-sandbox-default-project\", teamId: \"my-team\", created: false }\n * ```\n */\nexport async function inferScope(opts: {\n token: string;\n teamId?: string;\n cwd?: string;\n}): Promise<{\n projectId: string;\n teamId: string;\n created: boolean;\n teamSlug?: string;\n projectSlug?: string;\n}> {\n const linkedProject = await readLinkedProject(opts.cwd ?? process.cwd());\n if (linkedProject) {\n const slugs = await resolveLinkedProjectSlugs(\n opts.token,\n linkedProject.teamId,\n linkedProject.projectId,\n );\n return { ...linkedProject, created: false, ...slugs };\n }\n\n if (opts.teamId) {\n return tryTeam(opts.token, opts.teamId);\n }\n\n const userData = await fetchApi({\n token: opts.token,\n endpoint: \"/v2/user\",\n }).then(UserSchema.parse);\n const { defaultTeamId, username } = userData.user;\n\n // 1. Try defaultTeamId first\n if (defaultTeamId) {\n try {\n const result = await tryTeam(opts.token, defaultTeamId);\n // Resolve team slug (best-effort)\n try {\n const team = await fetchApi({\n token: opts.token,\n endpoint: `/v2/teams/${encodeURIComponent(defaultTeamId)}`,\n }).then(z.object({ slug: z.string() }).parse);\n return { ...result, teamSlug: team.slug };\n } catch {\n return result;\n }\n } catch (e) {\n if (!isSkippableTeamError(e)) throw e;\n }\n }\n\n // 2. Paginate teams in pages of 20, try best hobby team per page\n let next: number | null = null;\n do {\n const endpoint: string =\n next === null\n ? \"/v2/teams?limit=20\"\n : `/v2/teams?limit=20&until=${next}`;\n const page = await fetchApi({ token: opts.token, endpoint }).then(\n TeamsSchema.parse,\n );\n\n next = page.pagination.next;\n\n const hobbyOwnerTeams = page.teams.filter(\n (t) => t.membership.role === \"OWNER\" && t.billing.plan === \"hobby\",\n );\n if (hobbyOwnerTeams.length === 0) {\n continue;\n }\n\n const bestHobbyTeam =\n hobbyOwnerTeams.find((t) => t.slug === username) ??\n hobbyOwnerTeams.sort((a, b) => b.updatedAt - a.updatedAt)[0];\n\n if (bestHobbyTeam && bestHobbyTeam.id !== defaultTeamId) {\n try {\n const result = await tryTeam(opts.token, bestHobbyTeam.id);\n return { ...result, teamSlug: bestHobbyTeam.slug };\n } catch (e) {\n if (!isSkippableTeamError(e)) throw e;\n }\n }\n } while (next !== null);\n\n // 3. Fall back to username as personal team\n try {\n const result = await tryTeam(opts.token, username);\n return { ...result, teamSlug: username };\n } catch (e) {\n if (!isSkippableTeamError(e)) throw e;\n }\n\n throw new NotOk({\n statusCode: 403,\n responseText: `Authenticated as \"${username}\" but none of the available teams allow sandbox creation. Specify a team explicitly with --scope <team-id-or-slug>.`,\n });\n}\n\n/**\n * Attempts to use a specific team for sandbox operations by checking for\n * (or creating) the default project within that team.\n *\n * @returns The resolved scope if the team is usable.\n * @throws {NotOk} On authorization or other API errors.\n */\nasync function tryTeam(\n token: string,\n teamId: string,\n): Promise<{ projectId: string; teamId: string; created: boolean }> {\n const teamParam = teamId.startsWith(\"team_\")\n ? `teamId=${encodeURIComponent(teamId)}`\n : `slug=${encodeURIComponent(teamId)}`;\n\n let created = false;\n try {\n await fetchApi({\n token,\n endpoint: `/v2/projects/${encodeURIComponent(DEFAULT_PROJECT_NAME)}?${teamParam}`,\n });\n } catch (e) {\n if (!(e instanceof NotOk) || e.response.statusCode !== 404) {\n throw e;\n }\n\n await fetchApi({\n token,\n endpoint: `/v11/projects?${teamParam}`,\n method: \"POST\",\n body: JSON.stringify({\n name: DEFAULT_PROJECT_NAME,\n }),\n });\n created = true;\n }\n\n return { projectId: DEFAULT_PROJECT_NAME, teamId, created };\n}\n\n/**\n * Best-effort resolution of team slug and project name for a linked project.\n * Both IDs may be opaque (e.g. `team_xxx`, `prj_xxx`), so we fetch the\n * human-readable names from the API in parallel.\n */\nasync function resolveLinkedProjectSlugs(\n token: string,\n teamId: string,\n projectId: string,\n): Promise<{ teamSlug?: string; projectSlug?: string }> {\n try {\n const teamParam = teamId.startsWith(\"team_\")\n ? `teamId=${encodeURIComponent(teamId)}`\n : `slug=${encodeURIComponent(teamId)}`;\n const [teamData, projectData] = await Promise.all([\n fetchApi({\n token,\n endpoint: `/v2/teams/${encodeURIComponent(teamId)}`,\n }).then(z.object({ slug: z.string() }).parse),\n fetchApi({\n token,\n endpoint: `/v2/projects/${encodeURIComponent(projectId)}?${teamParam}`,\n }).then(z.object({ name: z.string() }).parse),\n ]);\n return { teamSlug: teamData.slug, projectSlug: projectData.name };\n } catch {\n return {};\n }\n}\n"],"mappings":";;;;;;;AAKA,MAAM,aAAaA,MAAE,OAAO,EAC1B,MAAMA,MAAE,OAAO;CACb,eAAeA,MAAE,QAAQ,CAAC,UAAU;CACpC,UAAUA,MAAE,QAAQ;CACrB,CAAC,EACH,CAAC;AAEF,MAAM,aAAaA,MAAE,OAAO;CAC1B,IAAIA,MAAE,QAAQ;CACd,MAAMA,MAAE,QAAQ;CAChB,WAAWA,MAAE,QAAQ;CACrB,YAAYA,MAAE,OAAO,EACnB,MAAMA,MAAE,QAAQ,EACjB,CAAC;CACF,SAASA,MAAE,OAAO,EAChB,MAAMA,MAAE,QAAQ,EACjB,CAAC;CACH,CAAC;AAEF,MAAM,cAAcA,MAAE,OAAO;CAC3B,OAAOA,MAAE,MAAM,WAAW;CAC1B,YAAYA,MAAE,OAAO;EACnB,OAAOA,MAAE,QAAQ;EACjB,MAAMA,MAAE,QAAQ,CAAC,UAAU;EAC5B,CAAC;CACH,CAAC;AAEF,MAAM,uBAAuB;;AAG7B,SAAS,qBAAqB,GAAqB;AACjD,QAAO,aAAaC,wBAAU,EAAE,SAAS,eAAe,OAAO,EAAE,SAAS,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B3F,eAAsB,WAAW,MAU9B;CACD,MAAM,gBAAgB,MAAMC,yCAAkB,KAAK,OAAO,QAAQ,KAAK,CAAC;AACxE,KAAI,eAAe;EACjB,MAAM,QAAQ,MAAM,0BAClB,KAAK,OACL,cAAc,QACd,cAAc,UACf;AACD,SAAO;GAAE,GAAG;GAAe,SAAS;GAAO,GAAG;GAAO;;AAGvD,KAAI,KAAK,OACP,QAAO,QAAQ,KAAK,OAAO,KAAK,O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First checks for a locally linked project in `.vercel/project.json`.
6
6
  * If found, uses the `projectId` and `orgId` from there.
7
7
  *
8
- * Otherwise, if `teamId` is not provided, selects the first available team for the account.
9
- * Ensures a default project exists within the team, creating it if necessary.
8
+ * Otherwise, if `teamId` is not provided, builds an ordered list of candidate
9
+ * teams to try: the user's `defaultTeamId` first (if set), then hobby-plan
10
+ * teams where the user has an OWNER role (preferring the personal team matching
11
+ * the username, then the most recently updated). Tries each candidate until one
12
+ * succeeds.
10
13
  *
11
14
  * @param opts.token - Vercel API authentication token.
12
- * @param opts.teamId - Optional team slug. If omitted, the first team is selected.
15
+ * @param opts.teamId - Optional team slug. If omitted, candidate teams are resolved automatically.
13
16
  * @param opts.cwd - Optional directory to search for `.vercel/project.json`. Defaults to `process.cwd()`.
14
17
  * @returns The resolved scope with `projectId`, `teamId`, and whether the project was `created`.
15
18
  *
16
19
  * @throws {NotOk} If the API returns an error other than 404 when checking the project.
17
- * @throws {ZodError} If no teams exist for the account.
18
20
  *
19
21
  * @example
20
22
  * ```ts
@@ -30,15 +32,9 @@ declare function inferScope(opts: {
30
32
  projectId: string;
31
33
  teamId: string;
32
34
  created: boolean;
35
+ teamSlug?: string;
36
+ projectSlug?: string;
33
37
  }>;
34
- /**
35
- * Selects a team for the current token by querying the Teams API and
36
- * returning the slug of the first team in the result set.
37
- *
38
- * @param token - Authentication token used to call the Vercel API.
39
- * @returns A promise that resolves to the first team's slug.
40
- */
41
- declare function selectTeam(token: string): Promise<string>;
42
38
  //#endregion
43
- export { inferScope, selectTeam };
39
+ export { inferScope };
44
40
  //# sourceMappingURL=project.d.cts.map
@@ -5,16 +5,18 @@
5
5
  * First checks for a locally linked project in `.vercel/project.json`.
6
6
  * If found, uses the `projectId` and `orgId` from there.
7
7
  *
8
- * Otherwise, if `teamId` is not provided, selects the first available team for the account.
9
- * Ensures a default project exists within the team, creating it if necessary.
8
+ * Otherwise, if `teamId` is not provided, builds an ordered list of candidate
9
+ * teams to try: the user's `defaultTeamId` first (if set), then hobby-plan
10
+ * teams where the user has an OWNER role (preferring the personal team matching
11
+ * the username, then the most recently updated). Tries each candidate until one
12
+ * succeeds.
10
13
  *
11
14
  * @param opts.token - Vercel API authentication token.
12
- * @param opts.teamId - Optional team slug. If omitted, the first team is selected.
15
+ * @param opts.teamId - Optional team slug. If omitted, candidate teams are resolved automatically.
13
16
  * @param opts.cwd - Optional directory to search for `.vercel/project.json`. Defaults to `process.cwd()`.
14
17
  * @returns The resolved scope with `projectId`, `teamId`, and whether the project was `created`.
15
18
  *
16
19
  * @throws {NotOk} If the API returns an error other than 404 when checking the project.
17
- * @throws {ZodError} If no teams exist for the account.
18
20
  *
19
21
  * @example
20
22
  * ```ts
@@ -30,15 +32,9 @@ declare function inferScope(opts: {
30
32
  projectId: string;
31
33
  teamId: string;
32
34
  created: boolean;
35
+ teamSlug?: string;
36
+ projectSlug?: string;
33
37
  }>;
34
- /**
35
- * Selects a team for the current token by querying the Teams API and
36
- * returning the slug of the first team in the result set.
37
- *
38
- * @param token - Authentication token used to call the Vercel API.
39
- * @returns A promise that resolves to the first team's slug.
40
- */
41
- declare function selectTeam(token: string): Promise<string>;
42
38
  //#endregion
43
- export { inferScope, selectTeam };
39
+ export { inferScope };
44
40
  //# sourceMappingURL=project.d.ts.map
@@ -4,24 +4,47 @@ import { readLinkedProject } from "./linked-project.js";
4
4
  import { z } from "zod";
5
5
 
6
6
  //#region src/auth/project.ts
7
- const TeamsSchema = z.object({ teams: z.array(z.object({ slug: z.string() })).min(1, `No teams found. Please create a team first.`) });
7
+ const UserSchema = z.object({ user: z.object({
8
+ defaultTeamId: z.string().nullable(),
9
+ username: z.string()
10
+ }) });
11
+ const TeamSchema = z.object({
12
+ id: z.string(),
13
+ slug: z.string(),
14
+ updatedAt: z.number(),
15
+ membership: z.object({ role: z.string() }),
16
+ billing: z.object({ plan: z.string() })
17
+ });
18
+ const TeamsSchema = z.object({
19
+ teams: z.array(TeamSchema),
20
+ pagination: z.object({
21
+ count: z.number(),
22
+ next: z.number().nullable()
23
+ })
24
+ });
8
25
  const DEFAULT_PROJECT_NAME = "vercel-sandbox-default-project";
26
+ /** Status codes that mean "this team can't be used, try the next one". */
27
+ function isSkippableTeamError(e) {
28
+ return e instanceof NotOk && (e.response.statusCode === 402 || e.response.statusCode === 403);
29
+ }
9
30
  /**
10
31
  * Resolves the team and project scope for sandbox operations.
11
32
  *
12
33
  * First checks for a locally linked project in `.vercel/project.json`.
13
34
  * If found, uses the `projectId` and `orgId` from there.
14
35
  *
15
- * Otherwise, if `teamId` is not provided, selects the first available team for the account.
16
- * Ensures a default project exists within the team, creating it if necessary.
36
+ * Otherwise, if `teamId` is not provided, builds an ordered list of candidate
37
+ * teams to try: the user's `defaultTeamId` first (if set), then hobby-plan
38
+ * teams where the user has an OWNER role (preferring the personal team matching
39
+ * the username, then the most recently updated). Tries each candidate until one
40
+ * succeeds.
17
41
  *
18
42
  * @param opts.token - Vercel API authentication token.
19
- * @param opts.teamId - Optional team slug. If omitted, the first team is selected.
43
+ * @param opts.teamId - Optional team slug. If omitted, candidate teams are resolved automatically.
20
44
  * @param opts.cwd - Optional directory to search for `.vercel/project.json`. Defaults to `process.cwd()`.
21
45
  * @returns The resolved scope with `projectId`, `teamId`, and whether the project was `created`.
22
46
  *
23
47
  * @throws {NotOk} If the API returns an error other than 404 when checking the project.
24
- * @throws {ZodError} If no teams exist for the account.
25
48
  *
26
49
  * @example
27
50
  * ```ts
@@ -31,22 +54,89 @@ const DEFAULT_PROJECT_NAME = "vercel-sandbox-default-project";
31
54
  */
32
55
  async function inferScope(opts) {
33
56
  const linkedProject = await readLinkedProject(opts.cwd ?? process.cwd());
34
- if (linkedProject) return {
35
- ...linkedProject,
36
- created: false
37
- };
38
- const teamId = opts.teamId ?? await selectTeam(opts.token);
57
+ if (linkedProject) {
58
+ const slugs = await resolveLinkedProjectSlugs(opts.token, linkedProject.teamId, linkedProject.projectId);
59
+ return {
60
+ ...linkedProject,
61
+ created: false,
62
+ ...slugs
63
+ };
64
+ }
65
+ if (opts.teamId) return tryTeam(opts.token, opts.teamId);
66
+ const { defaultTeamId, username } = (await fetchApi({
67
+ token: opts.token,
68
+ endpoint: "/v2/user"
69
+ }).then(UserSchema.parse)).user;
70
+ if (defaultTeamId) try {
71
+ const result = await tryTeam(opts.token, defaultTeamId);
72
+ try {
73
+ const team = await fetchApi({
74
+ token: opts.token,
75
+ endpoint: `/v2/teams/${encodeURIComponent(defaultTeamId)}`
76
+ }).then(z.object({ slug: z.string() }).parse);
77
+ return {
78
+ ...result,
79
+ teamSlug: team.slug
80
+ };
81
+ } catch {
82
+ return result;
83
+ }
84
+ } catch (e) {
85
+ if (!isSkippableTeamError(e)) throw e;
86
+ }
87
+ let next = null;
88
+ do {
89
+ const endpoint = next === null ? "/v2/teams?limit=20" : `/v2/teams?limit=20&until=${next}`;
90
+ const page = await fetchApi({
91
+ token: opts.token,
92
+ endpoint
93
+ }).then(TeamsSchema.parse);
94
+ next = page.pagination.next;
95
+ const hobbyOwnerTeams = page.teams.filter((t) => t.membership.role === "OWNER" && t.billing.plan === "hobby");
96
+ if (hobbyOwnerTeams.length === 0) continue;
97
+ const bestHobbyTeam = hobbyOwnerTeams.find((t) => t.slug === username) ?? hobbyOwnerTeams.sort((a, b) => b.updatedAt - a.updatedAt)[0];
98
+ if (bestHobbyTeam && bestHobbyTeam.id !== defaultTeamId) try {
99
+ return {
100
+ ...await tryTeam(opts.token, bestHobbyTeam.id),
101
+ teamSlug: bestHobbyTeam.slug
102
+ };
103
+ } catch (e) {
104
+ if (!isSkippableTeamError(e)) throw e;
105
+ }
106
+ } while (next !== null);
107
+ try {
108
+ return {
109
+ ...await tryTeam(opts.token, username),
110
+ teamSlug: username
111
+ };
112
+ } catch (e) {
113
+ if (!isSkippableTeamError(e)) throw e;
114
+ }
115
+ throw new NotOk({
116
+ statusCode: 403,
117
+ responseText: `Authenticated as "${username}" but none of the available teams allow sandbox creation. Specify a team explicitly with --scope <team-id-or-slug>.`
118
+ });
119
+ }
120
+ /**
121
+ * Attempts to use a specific team for sandbox operations by checking for
122
+ * (or creating) the default project within that team.
123
+ *
124
+ * @returns The resolved scope if the team is usable.
125
+ * @throws {NotOk} On authorization or other API errors.
126
+ */
127
+ async function tryTeam(token, teamId) {
128
+ const teamParam = teamId.startsWith("team_") ? `teamId=${encodeURIComponent(teamId)}` : `slug=${encodeURIComponent(teamId)}`;
39
129
  let created = false;
40
130
  try {
41
131
  await fetchApi({
42
- token: opts.token,
43
- endpoint: `/v2/projects/${encodeURIComponent(DEFAULT_PROJECT_NAME)}?slug=${encodeURIComponent(teamId)}`
132
+ token,
133
+ endpoint: `/v2/projects/${encodeURIComponent(DEFAULT_PROJECT_NAME)}?${teamParam}`
44
134
  });
45
135
  } catch (e) {
46
136
  if (!(e instanceof NotOk) || e.response.statusCode !== 404) throw e;
47
137
  await fetchApi({
48
- token: opts.token,
49
- endpoint: `/v11/projects?slug=${encodeURIComponent(teamId)}`,
138
+ token,
139
+ endpoint: `/v11/projects?${teamParam}`,
50
140
  method: "POST",
51
141
  body: JSON.stringify({ name: DEFAULT_PROJECT_NAME })
52
142
  });
@@ -59,20 +149,29 @@ async function inferScope(opts) {
59
149
  };
60
150
  }
61
151
  /**
62
- * Selects a team for the current token by querying the Teams API and
63
- * returning the slug of the first team in the result set.
64
- *
65
- * @param token - Authentication token used to call the Vercel API.
66
- * @returns A promise that resolves to the first team's slug.
152
+ * Best-effort resolution of team slug and project name for a linked project.
153
+ * Both IDs may be opaque (e.g. `team_xxx`, `prj_xxx`), so we fetch the
154
+ * human-readable names from the API in parallel.
67
155
  */
68
- async function selectTeam(token) {
69
- const { teams: [team] } = await fetchApi({
70
- token,
71
- endpoint: "/v2/teams?limit=1"
72
- }).then(TeamsSchema.parse);
73
- return team.slug;
156
+ async function resolveLinkedProjectSlugs(token, teamId, projectId) {
157
+ try {
158
+ const teamParam = teamId.startsWith("team_") ? `teamId=${encodeURIComponent(teamId)}` : `slug=${encodeURIComponent(teamId)}`;
159
+ const [teamData, projectData] = await Promise.all([fetchApi({
160
+ token,
161
+ endpoint: `/v2/teams/${encodeURIComponent(teamId)}`
162
+ }).then(z.object({ slug: z.string() }).parse), fetchApi({
163
+ token,
164
+ endpoint: `/v2/projects/${encodeURIComponent(projectId)}?${teamParam}`
165
+ }).then(z.object({ name: z.string() }).parse)]);
166
+ return {
167
+ teamSlug: teamData.slug,
168
+ projectSlug: projectData.name
169
+ };
170
+ } catch {
171
+ return {};
172
+ }
74
173
  }
75
174
 
76
175
  //#endregion
77
- export { inferScope, selectTeam };
176
+ export { inferScope };
78
177
  //# sourceMappingURL=project.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"project.js","names":[],"sources":["../../src/auth/project.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { fetchApi } from \"./api.js\";\nimport { NotOk } from \"./error.js\";\nimport { readLinkedProject } from \"./linked-project.js\";\n\nconst TeamsSchema = z.object({\n teams: z\n .array(\n z.object({\n slug: z.string(),\n }),\n )\n .min(1, `No teams found. Please create a team first.`),\n});\n\nconst DEFAULT_PROJECT_NAME = \"vercel-sandbox-default-project\";\n\n/**\n * Resolves the team and project scope for sandbox operations.\n *\n * First checks for a locally linked project in `.vercel/project.json`.\n * If found, uses the `projectId` and `orgId` from there.\n *\n * Otherwise, if `teamId` is not provided, selects the first available team for the account.\n * Ensures a default project exists within the team, creating it if necessary.\n *\n * @param opts.token - Vercel API authentication token.\n * @param opts.teamId - Optional team slug. If omitted, the first team is selected.\n * @param opts.cwd - Optional directory to search for `.vercel/project.json`. Defaults to `process.cwd()`.\n * @returns The resolved scope with `projectId`, `teamId`, and whether the project was `created`.\n *\n * @throws {NotOk} If the API returns an error other than 404 when checking the project.\n * @throws {ZodError} If no teams exist for the account.\n *\n * @example\n * ```ts\n * const scope = await inferScope({ token: \"vercel_...\" });\n * // => { projectId: \"vercel-sandbox-default-project\", teamId: \"my-team\", created: false }\n * ```\n */\nexport async function inferScope(opts: {\n token: string;\n teamId?: string;\n cwd?: string;\n}): Promise<{ projectId: string; teamId: string; created: boolean }> {\n const linkedProject = await readLinkedProject(opts.cwd ?? process.cwd());\n if (linkedProject) {\n return { ...linkedProject, created: false };\n }\n\n const teamId = opts.teamId ?? (await selectTeam(opts.token));\n\n let created = false;\n try {\n await fetchApi({\n token: opts.token,\n endpoint: `/v2/projects/${encodeURIComponent(DEFAULT_PROJECT_NAME)}?slug=${encodeURIComponent(teamId)}`,\n });\n } catch (e) {\n if (!(e instanceof NotOk) || e.response.statusCode !== 404) {\n throw e;\n }\n\n await fetchApi({\n token: opts.token,\n endpoint: `/v11/projects?slug=${encodeURIComponent(teamId)}`,\n method: \"POST\",\n body: JSON.stringify({\n name: DEFAULT_PROJECT_NAME,\n }),\n });\n created = true;\n }\n\n return { projectId: DEFAULT_PROJECT_NAME, teamId, created };\n}\n\n/**\n * Selects a team for the current token by querying the Teams API and\n * returning the slug of the first team in the result set.\n *\n * @param token - Authentication token used to call the Vercel API.\n * @returns A promise that resolves to the first team's slug.\n */\nexport async function selectTeam(token: string) {\n const {\n teams: [team],\n } = await fetchApi({ token, endpoint: \"/v2/teams?limit=1\" }).then(\n TeamsSchema.parse,\n );\n return team.slug;\n}\n"],"mappings":";;;;;;AAKA,MAAM,cAAc,EAAE,OAAO,EAC3B,OAAO,EACJ,MACC,EAAE,OAAO,EACP,MAAM,EAAE,QAAQ,EACjB,CAAC,CACH,CACA,IAAI,GAAG,8CAA8C,EACzD,CAAC;AAEF,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;AAyB7B,eAAsB,WAAW,MAIoC;CACnE,MAAM,gBAAgB,MAAM,kBAAkB,KAAK,OAAO,QAAQ,KAAK,CAAC;AACxE,KAAI,cACF,QAAO;EAAE,GAAG;EAAe,SAAS;EAAO;CAG7C,MAAM,SAAS,KAAK,UAAW,MAAM,WAAW,KAAK,MAAM;CAE3D,IAAI,UAAU;AACd,KAAI;AACF,QAAM,SAAS;GACb,OAAO,KAAK;GACZ,UAAU,gBAAgB,mBAAmB,qBAAqB,CAAC,QAAQ,mBAAmB,OAAO;GACtG,CAAC;UACK,GAAG;AACV,MAAI,EAAE,aAAa,UAAU,EAAE,SAAS,eAAe,IACrD,OAAM;AAGR,QAAM,SAAS;GACb,OAAO,KAAK;GACZ,UAAU,sBAAsB,mBAAmB,OAAO;GAC1D,QAAQ;GACR,MAAM,KAAK,UAAU,EACnB,MAAM,sBACP,CAAC;GACH,CAAC;AACF,YAAU;;AAGZ,QAAO;EAAE,WAAW;EAAsB;EAAQ;EAAS;;;;;;;;;AAU7D,eAAsB,WAAW,OAAe;CAC9C,MAAM,EACJ,OAAO,CAAC,UACN,MAAM,SAAS;EAAE;EAAO,UAAU;EAAqB,CAAC,CAAC,KAC3D,YAAY,MACb;AACD,QAAO,KAAK"}
1
+ {"version":3,"file":"project.js","names":["next: number | null","endpoint: string"],"sources":["../../src/auth/project.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { fetchApi } from \"./api.js\";\nimport { NotOk } from \"./error.js\";\nimport { readLinkedProject } from \"./linked-project.js\";\n\nconst UserSchema = z.object({\n user: z.object({\n defaultTeamId: z.string().nullable(),\n username: z.string(),\n }),\n});\n\nconst TeamSchema = z.object({\n id: z.string(),\n slug: z.string(),\n updatedAt: z.number(),\n membership: z.object({\n role: z.string(),\n }),\n billing: z.object({\n plan: z.string(),\n }),\n});\n\nconst TeamsSchema = z.object({\n teams: z.array(TeamSchema),\n pagination: z.object({\n count: z.number(),\n next: z.number().nullable(),\n }),\n});\n\nconst DEFAULT_PROJECT_NAME = \"vercel-sandbox-default-project\";\n\n/** Status codes that mean \"this team can't be used, try the next one\". */\nfunction isSkippableTeamError(e: unknown): boolean {\n return e instanceof NotOk && (e.response.statusCode === 402 || e.response.statusCode === 403);\n}\n\n/**\n * Resolves the team and project scope for sandbox operations.\n *\n * First checks for a locally linked project in `.vercel/project.json`.\n * If found, uses the `projectId` and `orgId` from there.\n *\n * Otherwise, if `teamId` is not provided, builds an ordered list of candidate\n * teams to try: the user's `defaultTeamId` first (if set), then hobby-plan\n * teams where the user has an OWNER role (preferring the personal team matching\n * the username, then the most recently updated). Tries each candidate until one\n * succeeds.\n *\n * @param opts.token - Vercel API authentication token.\n * @param opts.teamId - Optional team slug. If omitted, candidate teams are resolved automatically.\n * @param opts.cwd - Optional directory to search for `.vercel/project.json`. Defaults to `process.cwd()`.\n * @returns The resolved scope with `projectId`, `teamId`, and whether the project was `created`.\n *\n * @throws {NotOk} If the API returns an error other than 404 when checking the project.\n *\n * @example\n * ```ts\n * const scope = await inferScope({ token: \"vercel_...\" });\n * // => { projectId: \"vercel-sandbox-default-project\", teamId: \"my-team\", created: false }\n * ```\n */\nexport async function inferScope(opts: {\n token: string;\n teamId?: string;\n cwd?: string;\n}): Promise<{\n projectId: string;\n teamId: string;\n created: boolean;\n teamSlug?: string;\n projectSlug?: string;\n}> {\n const linkedProject = await readLinkedProject(opts.cwd ?? process.cwd());\n if (linkedProject) {\n const slugs = await resolveLinkedProjectSlugs(\n opts.token,\n linkedProject.teamId,\n linkedProject.projectId,\n );\n return { ...linkedProject, created: false, ...slugs };\n }\n\n if (opts.teamId) {\n return tryTeam(opts.token, opts.teamId);\n }\n\n const userData = await fetchApi({\n token: opts.token,\n endpoint: \"/v2/user\",\n }).then(UserSchema.parse);\n const { defaultTeamId, username } = userData.user;\n\n // 1. Try defaultTeamId first\n if (defaultTeamId) {\n try {\n const result = await tryTeam(opts.token, defaultTeamId);\n // Resolve team slug (best-effort)\n try {\n const team = await fetchApi({\n token: opts.token,\n endpoint: `/v2/teams/${encodeURIComponent(defaultTeamId)}`,\n }).then(z.object({ slug: z.string() }).parse);\n return { ...result, teamSlug: team.slug };\n } catch {\n return result;\n }\n } catch (e) {\n if (!isSkippableTeamError(e)) throw e;\n }\n }\n\n // 2. Paginate teams in pages of 20, try best hobby team per page\n let next: number | null = null;\n do {\n const endpoint: string =\n next === null\n ? \"/v2/teams?limit=20\"\n : `/v2/teams?limit=20&until=${next}`;\n const page = await fetchApi({ token: opts.token, endpoint }).then(\n TeamsSchema.parse,\n );\n\n next = page.pagination.next;\n\n const hobbyOwnerTeams = page.teams.filter(\n (t) => t.membership.role === \"OWNER\" && t.billing.plan === \"hobby\",\n );\n if (hobbyOwnerTeams.length === 0) {\n continue;\n }\n\n const bestHobbyTeam =\n hobbyOwnerTeams.find((t) => t.slug === username) ??\n hobbyOwnerTeams.sort((a, b) => b.updatedAt - a.updatedAt)[0];\n\n if (bestHobbyTeam && bestHobbyTeam.id !== defaultTeamId) {\n try {\n const result = await tryTeam(opts.token, bestHobbyTeam.id);\n return { ...result, teamSlug: bestHobbyTeam.slug };\n } catch (e) {\n if (!isSkippableTeamError(e)) throw e;\n }\n }\n } while (next !== null);\n\n // 3. Fall back to username as personal team\n try {\n const result = await tryTeam(opts.token, username);\n return { ...result, teamSlug: username };\n } catch (e) {\n if (!isSkippableTeamError(e)) throw e;\n }\n\n throw new NotOk({\n statusCode: 403,\n responseText: `Authenticated as \"${username}\" but none of the available teams allow sandbox creation. Specify a team explicitly with --scope <team-id-or-slug>.`,\n });\n}\n\n/**\n * Attempts to use a specific team for sandbox operations by checking for\n * (or creating) the default project within that team.\n *\n * @returns The resolved scope if the team is usable.\n * @throws {NotOk} On authorization or other API errors.\n */\nasync function tryTeam(\n token: string,\n teamId: string,\n): Promise<{ projectId: string; teamId: string; created: boolean }> {\n const teamParam = teamId.startsWith(\"team_\")\n ? `teamId=${encodeURIComponent(teamId)}`\n : `slug=${encodeURIComponent(teamId)}`;\n\n let created = false;\n try {\n await fetchApi({\n token,\n endpoint: `/v2/projects/${encodeURIComponent(DEFAULT_PROJECT_NAME)}?${teamParam}`,\n });\n } catch (e) {\n if (!(e instanceof NotOk) || e.response.statusCode !== 404) {\n throw e;\n }\n\n await fetchApi({\n token,\n endpoint: `/v11/projects?${teamParam}`,\n method: \"POST\",\n body: JSON.stringify({\n name: DEFAULT_PROJECT_NAME,\n }),\n });\n created = true;\n }\n\n return { projectId: DEFAULT_PROJECT_NAME, teamId, created };\n}\n\n/**\n * Best-effort resolution of team slug and project name for a linked project.\n * Both IDs may be opaque (e.g. `team_xxx`, `prj_xxx`), so we fetch the\n * human-readable names from the API in parallel.\n */\nasync function resolveLinkedProjectSlugs(\n token: string,\n teamId: string,\n projectId: string,\n): Promise<{ teamSlug?: string; projectSlug?: string }> {\n try {\n const teamParam = teamId.startsWith(\"team_\")\n ? `teamId=${encodeURIComponent(teamId)}`\n : `slug=${encodeURIComponent(teamId)}`;\n const [teamData, projectData] = await Promise.all([\n fetchApi({\n token,\n endpoint: `/v2/teams/${encodeURIComponent(teamId)}`,\n }).then(z.object({ slug: z.string() }).parse),\n fetchApi({\n token,\n endpoint: `/v2/projects/${encodeURIComponent(projectId)}?${teamParam}`,\n }).then(z.object({ name: z.string() }).parse),\n ]);\n return { teamSlug: teamData.slug, projectSlug: projectData.name };\n } catch {\n return {};\n }\n}\n"],"mappings":";;;;;;AAKA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EAAE,OAAO;CACb,eAAe,EAAE,QAAQ,CAAC,UAAU;CACpC,UAAU,EAAE,QAAQ;CACrB,CAAC,EACH,CAAC;AAEF,MAAM,aAAa,EAAE,OAAO;CAC1B,IAAI,EAAE,QAAQ;CACd,MAAM,EAAE,QAAQ;CAChB,WAAW,EAAE,QAAQ;CACrB,YAAY,EAAE,OAAO,EACnB,MAAM,EAAE,QAAQ,EACjB,CAAC;CACF,SAAS,EAAE,OAAO,EAChB,MAAM,EAAE,QAAQ,EACjB,CAAC;CACH,CAAC;AAEF,MAAM,cAAc,EAAE,OAAO;CAC3B,OAAO,EAAE,MAAM,WAAW;CAC1B,YAAY,EAAE,OAAO;EACnB,OAAO,EAAE,QAAQ;EACjB,MAAM,EAAE,QAAQ,CAAC,UAAU;EAC5B,CAAC;CACH,CAAC;AAEF,MAAM,uBAAuB;;AAG7B,SAAS,qBAAqB,GAAqB;AACjD,QAAO,aAAa,UAAU,EAAE,SAAS,eAAe,OAAO,EAAE,SAAS,eAAe;;;;;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