|
| 1 | +import { BuildExtension } from "@trigger.dev/core/v3/build"; |
| 2 | +import { syncEnvVars } from "../core.js"; |
| 3 | + |
| 4 | +export function syncVercelEnvVars( |
| 5 | + options?: { projectId?: string; vercelAccessToken?: string }, |
| 6 | +): BuildExtension { |
| 7 | + const sync = syncEnvVars(async (ctx) => { |
| 8 | + const projectId = options?.projectId ?? process.env.VERCEL_PROJECT_ID ?? |
| 9 | + ctx.env.VERCEL_PROJECT_ID; |
| 10 | + const vercelAccessToken = options?.vercelAccessToken ?? |
| 11 | + process.env.VERCEL_ACCESS_TOKEN ?? |
| 12 | + ctx.env.VERCEL_ACCESS_TOKEN; |
| 13 | + |
| 14 | + if (!projectId) { |
| 15 | + throw new Error( |
| 16 | + "vercelSyncEnvVars: you did not pass in a projectId or set the VERCEL_PROJECT_ID env var.", |
| 17 | + ); |
| 18 | + } |
| 19 | + |
| 20 | + if (!vercelAccessToken) { |
| 21 | + throw new Error( |
| 22 | + "vercelSyncEnvVars: you did not pass in a vercelAccessToken or set the VERCEL_ACCESS_TOKEN env var.", |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + const environmentMap = { |
| 27 | + prod: "production", |
| 28 | + staging: "preview", |
| 29 | + dev: "development", |
| 30 | + } as const; |
| 31 | + |
| 32 | + const vercelEnvironment = |
| 33 | + environmentMap[ctx.environment as keyof typeof environmentMap]; |
| 34 | + |
| 35 | + if (!vercelEnvironment) { |
| 36 | + throw new Error( |
| 37 | + `Invalid environment '${ctx.environment}'. Expected 'prod', 'staging', or 'dev'.`, |
| 38 | + ); |
| 39 | + } |
| 40 | + const vercelApiUrl = |
| 41 | + `https://api.vercel.com/v8/projects/${projectId}/env?decrypt=true`; |
| 42 | + |
| 43 | + try { |
| 44 | + const response = await fetch(vercelApiUrl, { |
| 45 | + headers: { |
| 46 | + Authorization: `Bearer ${vercelAccessToken}`, |
| 47 | + }, |
| 48 | + }); |
| 49 | + |
| 50 | + if (!response.ok) { |
| 51 | + throw new Error(`HTTP error! status: ${response.status}`); |
| 52 | + } |
| 53 | + |
| 54 | + const data = await response.json(); |
| 55 | + |
| 56 | + const filteredEnvs = data.envs |
| 57 | + .filter( |
| 58 | + (env: { type: string; value: string; target: string[] }) => |
| 59 | + env.value && |
| 60 | + env.target.includes(vercelEnvironment), |
| 61 | + ) |
| 62 | + .map((env: { key: string; value: string }) => ({ |
| 63 | + name: env.key, |
| 64 | + value: env.value, |
| 65 | + })); |
| 66 | + |
| 67 | + return filteredEnvs; |
| 68 | + } catch (error) { |
| 69 | + console.error( |
| 70 | + "Error fetching or processing Vercel environment variables:", |
| 71 | + error, |
| 72 | + ); |
| 73 | + throw error; // Re-throw the error to be handled by the caller |
| 74 | + } |
| 75 | + }); |
| 76 | + |
| 77 | + return { |
| 78 | + name: "SyncVercelEnvVarsExtension", |
| 79 | + async onBuildComplete(context, manifest) { |
| 80 | + await sync.onBuildComplete?.(context, manifest); |
| 81 | + }, |
| 82 | + }; |
| 83 | +} |
0 commit comments