@neondatabase/env 0.15.0 → 1.0.1

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 (48) hide show
  1. package/README.md +21 -29
  2. package/dist/cli.js +971 -6
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{lib/env.js → env.js} +70 -219
  5. package/dist/env.js.map +1 -0
  6. package/dist/index.d.ts +528 -2
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +197 -1
  9. package/dist/index.js.map +1 -0
  10. package/package.json +11 -14
  11. package/dist/_shared/auth_selection.js +0 -76
  12. package/dist/_shared/auth_selection.js.map +0 -1
  13. package/dist/_shared/credentials.js +0 -131
  14. package/dist/_shared/credentials.js.map +0 -1
  15. package/dist/_shared/paths.js +0 -131
  16. package/dist/_shared/paths.js.map +0 -1
  17. package/dist/_shared/profiles.d.ts +0 -7
  18. package/dist/_shared/profiles.d.ts.map +0 -1
  19. package/dist/_shared/profiles.js +0 -124
  20. package/dist/_shared/profiles.js.map +0 -1
  21. package/dist/config/dist/lib/define-config.d.ts +0 -20
  22. package/dist/config/dist/lib/define-config.d.ts.map +0 -1
  23. package/dist/config/dist/lib/neon-api.d.ts +0 -375
  24. package/dist/config/dist/lib/neon-api.d.ts.map +0 -1
  25. package/dist/config/dist/lib/types.d.ts +0 -544
  26. package/dist/config/dist/lib/types.d.ts.map +0 -1
  27. package/dist/config/dist/v1.d.ts +0 -5
  28. package/dist/lib/cli/commands.d.ts +0 -68
  29. package/dist/lib/cli/commands.d.ts.map +0 -1
  30. package/dist/lib/cli/commands.js +0 -233
  31. package/dist/lib/cli/commands.js.map +0 -1
  32. package/dist/lib/cli/resolve-api-key.d.ts +0 -29
  33. package/dist/lib/cli/resolve-api-key.d.ts.map +0 -1
  34. package/dist/lib/cli/resolve-api-key.js +0 -74
  35. package/dist/lib/cli/resolve-api-key.js.map +0 -1
  36. package/dist/lib/cli/resolve-context.d.ts +0 -34
  37. package/dist/lib/cli/resolve-context.d.ts.map +0 -1
  38. package/dist/lib/cli/resolve-context.js +0 -88
  39. package/dist/lib/cli/resolve-context.js.map +0 -1
  40. package/dist/lib/env.d.ts +0 -509
  41. package/dist/lib/env.d.ts.map +0 -1
  42. package/dist/lib/env.js.map +0 -1
  43. package/dist/lib/reuse-secrets.d.ts +0 -95
  44. package/dist/lib/reuse-secrets.d.ts.map +0 -1
  45. package/dist/lib/reuse-secrets.js +0 -181
  46. package/dist/lib/reuse-secrets.js.map +0 -1
  47. package/dist/runtime.d.ts +0 -2
  48. package/dist/runtime.js +0 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","names":[],"sources":["../../../internals/env-core/dist/env.js"],"sourcesContent":["import { ErrorCode, PlatformError, createNeonApiFromOptions, deriveCredentialScopes, resolveConfig } from \"@neon/config/v1\";\n//#region src/env.ts\n/**\n* The Neon env core — resolving a branch's env from the Neon API, and projecting it into\n* OS-level `{ KEY: value }` pairs.\n*\n* Private, and bundled into both consumers: `@neon/env` publishes it as `fetchEnv` /\n* `toEntries`, and the `neon` CLI needs the credential-reuse half in `reuse-secrets.ts`.\n* See `README.md` for why it is not published.\n*\n* The counterpart that reads `process.env` — `parseEnv` and its zod schemas — is not here. It\n* has no consumer outside `@neon/env`, so it stays in that package and imports this.\n*/\n/**\n* Mapping between the {@link NeonEnv} property paths and the OS-level env-var keys used\n* for cross-process transport (via `.env` files, `env run -- <cmd>`, or anything else\n* that talks to `process.env`).\n*\n* Each top-level key here is a {@link NeonEnv} namespace; the inner record maps the\n* camelCase property names exposed to TypeScript to the UPPER_SNAKE env-var names used\n* by the OS. Keep this in sync with {@link postgresEnvSchema} / {@link authEnvSchema} /\n* {@link dataApiEnvSchema}.\n*/\n/**\n* Neon's default branch owner role, created with every project. This is the role a\n* `DATABASE_URL` should connect as.\n*/\nconst NEON_DEFAULT_OWNER_ROLE = \"neondb_owner\";\n/**\n* Neon's default database, created with every project. When a branch has several databases\n* and none was requested, this is preferred for the `DATABASE_URL` so the common case (a\n* user added a second database next to `neondb`) auto-picks without asking.\n*/\nconst NEON_DEFAULT_DATABASE = \"neondb\";\n/**\n* Roles Neon provisions for the Auth / Data API (PostgREST) stack. They exist to back\n* RLS-scoped Data API requests authenticated by JWT — never to hold a `DATABASE_URL` —\n* so they're skipped when auto-picking the connection role. Enabling Neon Auth or the\n* Data API (`neon config apply`) adds these next to the owner role, which is why a plain\n* branch routinely reports more than one role.\n*/\nconst NEON_MANAGED_AUTH_ROLES = /* @__PURE__ */ new Set([\n\t\"authenticator\",\n\t\"anonymous\",\n\t\"authenticated\"\n]);\nconst NEON_ENV_VAR_KEYS = {\n\t/**\n\t* Branch identity. `NEON_BRANCH` carries the branch **name** and is injected into the\n\t* Neon Functions runtime on every branch (including the default) by default. `env pull` /\n\t* `neon dev` / `neon-env run` emit it too so local dev mirrors the deployed runtime.\n\t*/\n\tbranch: { name: \"NEON_BRANCH\" },\n\tpostgres: {\n\t\tdatabaseUrl: \"DATABASE_URL\",\n\t\tdatabaseUrlUnpooled: \"DATABASE_URL_UNPOOLED\"\n\t},\n\tauth: {\n\t\tbaseUrl: \"NEON_AUTH_BASE_URL\",\n\t\tjwksUrl: \"NEON_AUTH_JWKS_URL\"\n\t},\n\tdataApi: { url: \"NEON_DATA_API_URL\" },\n\t/**\n\t* Object storage (Preview). The S3 SDKs read `AWS_*` from their standard config chain, so\n\t* a branch credential + `neon dev` / `env pull` makes object storage work from env alone.\n\t* `region` is injected under the SDK-standard `AWS_REGION`.\n\t*/\n\tstorage: {\n\t\taccessKeyId: \"AWS_ACCESS_KEY_ID\",\n\t\tsecretAccessKey: \"AWS_SECRET_ACCESS_KEY\",\n\t\tendpoint: \"AWS_ENDPOINT_URL_S3\",\n\t\tregion: \"AWS_REGION\"\n\t},\n\t/**\n\t* AI Gateway (Preview). Exposed under the Neon-branded env vars the deployed Functions\n\t* runtime injects: `apiKey` is the minted credential's bearer (`NEON_AI_GATEWAY_TOKEN`)\n\t* and `baseUrl` is the bare branch gateway host (`NEON_AI_GATEWAY_BASE_URL`,\n\t* `scheme://host`, no path). Clients like `@neon/ai-sdk-provider` read these and append the\n\t* dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves (https://github.com/vercel/ai/pull/15997).\n\t*/\n\taiGateway: {\n\t\tapiKey: \"NEON_AI_GATEWAY_TOKEN\",\n\t\tbaseUrl: \"NEON_AI_GATEWAY_BASE_URL\"\n\t}\n};\nasync function fetchEnv(config, options) {\n\tif (options.keys) assertStorageCredentialKeyPair(options.keys);\n\treturn fetchEnvKeys(config, options, options.keys ?? null);\n}\nfunction assertStorageCredentialKeyPair(keys) {\n\tif (keys.includes(NEON_ENV_VAR_KEYS.storage.accessKeyId) === keys.includes(NEON_ENV_VAR_KEYS.storage.secretAccessKey)) return;\n\tthrow new TypeError(\"fetchEnv: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be selected together. Pass both in `keys`, or omit both.\");\n}\n/** Fail loudly when selected-key dependency planning and execution disagree. */\nfunction requiredValue(value, description) {\n\tif (value === null) throw new Error(`fetchEnv: missing ${description}.`);\n\treturn value;\n}\n/**\n* The {@link fetchEnv} body, with the key selection as a plain argument and no generic\n* narrowing. Exists for callers that compute the selection at runtime — notably\n* {@link fetchEnvReusingSecrets}, which decides which keys it still needs by checking the\n* branch — since the public overload's `keys` is bound to a literal union those callers cannot\n* produce without asserting.\n*\n* `keys === null` selects everything the policy enables.\n*/\nasync function fetchEnvKeys(config, options, keys) {\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst projectId = options.projectId;\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\tconst selection = keys ? new Set(keys) : null;\n\tconst wants = (key) => selection === null || selection.has(key);\n\tconst result = {};\n\tconst K = NEON_ENV_VAR_KEYS;\n\tconst wantsPooled = wants(K.postgres.databaseUrl);\n\tconst wantsUnpooled = wants(K.postgres.databaseUrlUnpooled);\n\tconst wantsAuth = desired.authEnabled && (wants(K.auth.baseUrl) || wants(K.auth.jwksUrl));\n\tconst wantsDataApi = desired.dataApiEnabled && wants(K.dataApi.url);\n\tconst gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;\n\tconst needsUnpooled = wantsUnpooled || gatewayEnabled && wants(K.aiGateway.baseUrl);\n\tconst needsConnectionTarget = wantsPooled || needsUnpooled;\n\tconst needsDatabase = needsConnectionTarget || wantsDataApi;\n\tconst [roles, databases] = await Promise.all([needsConnectionTarget ? api.listBranchRoles(projectId, branch.id) : Promise.resolve([]), needsDatabase ? api.listBranchDatabases(projectId, branch.id) : Promise.resolve([])]);\n\tconst databaseName = needsDatabase ? pickDatabaseName(databases, branch, options.databaseName) : null;\n\tconst connectionTarget = needsConnectionTarget ? {\n\t\troleName: pickRoleName(roles, branch, options.roleName),\n\t\tdatabaseName: requiredValue(databaseName, \"database for a selected connection URI\")\n\t} : null;\n\tconst getConnectionUri = (pooled) => {\n\t\tconst target = requiredValue(connectionTarget, \"role and database for a selected connection URI\");\n\t\treturn api.getConnectionUri(projectId, {\n\t\t\tbranchId: branch.id,\n\t\t\t...target,\n\t\t\tpooled\n\t\t});\n\t};\n\tconst [pooled, unpooled, authSnapshot, dataApiSnapshot] = await Promise.all([\n\t\twantsPooled ? getConnectionUri(true) : Promise.resolve(null),\n\t\tneedsUnpooled ? getConnectionUri(false) : Promise.resolve(null),\n\t\twantsAuth ? api.getNeonAuth(projectId, branch.id) : Promise.resolve(null),\n\t\twantsDataApi ? api.getNeonDataApi(projectId, branch.id, requiredValue(databaseName, \"database for the selected Data API URL\")) : Promise.resolve(null)\n\t]);\n\tconst postgres = {};\n\tif (wantsPooled) postgres.databaseUrl = requiredValue(pooled, \"pooled connection URI response\").uri;\n\tif (wantsUnpooled) postgres.databaseUrlUnpooled = requiredValue(unpooled, \"direct connection URI response\").uri;\n\tif (Object.keys(postgres).length > 0) result.postgres = postgres;\n\tif (wants(K.branch.name)) result.branch = { name: branch.name };\n\tif (wantsAuth) {\n\t\tif (!authSnapshot) throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy enables auth but no Neon Auth integration is enabled on branch ${branch.name} (${branch.id}).`, \"Enable it via `apply(config, { projectId, branchId })` (or `npx neon …`), in the Neon Console — then re-run fetchEnv. Or return auth.enabled=false.\"].join(\" \"), { details: {\n\t\t\tprojectId,\n\t\t\tbranchId: branch.id\n\t\t} });\n\t\tconst auth = {};\n\t\tif (wants(K.auth.baseUrl)) auth.baseUrl = authSnapshot.baseUrl ?? \"\";\n\t\tif (wants(K.auth.jwksUrl)) auth.jwksUrl = authSnapshot.jwksUrl ?? \"\";\n\t\tresult.auth = auth;\n\t}\n\tif (wantsDataApi) {\n\t\tif (!dataApiSnapshot) {\n\t\t\tconst selectedDatabase = requiredValue(databaseName, \"database for the selected Data API URL\");\n\t\t\tthrow new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy enables dataApi but no Data API integration is enabled on branch ${branch.name} (${branch.id}) database ${selectedDatabase}.`, \"Enable it via `apply(config, { projectId, branchId })` or in the Neon Console — then re-run fetchEnv. Or return dataApi.enabled=false.\"].join(\" \"), { details: {\n\t\t\t\tprojectId,\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tdatabaseName: selectedDatabase\n\t\t\t} });\n\t\t}\n\t\tresult.dataApi = { url: dataApiSnapshot.url };\n\t}\n\tconst storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;\n\tconst wantsStorage = storageEnabled && (wants(K.storage.accessKeyId) || wants(K.storage.secretAccessKey) || wants(K.storage.endpoint) || wants(K.storage.region));\n\tconst wantsGateway = gatewayEnabled && (wants(K.aiGateway.apiKey) || wants(K.aiGateway.baseUrl));\n\tconst wantsStorageCredential = storageEnabled && (wants(K.storage.accessKeyId) || wants(K.storage.secretAccessKey));\n\tconst wantsGatewayCredential = gatewayEnabled && wants(K.aiGateway.apiKey);\n\tconst wantsCredential = wantsStorageCredential || wantsGatewayCredential;\n\tif (wantsStorage || wantsGateway) {\n\t\tlet storage = null;\n\t\tif (wantsStorage) {\n\t\t\tstorage = await api.getProjectBranchStorage(projectId, branch.id);\n\t\t\tif (!storage) throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy declares object storage (preview.buckets) but storage is not enabled on branch ${branch.name} (${branch.id}).`, \"Enable it via `apply(config, { projectId, branchId })` (or in the Neon Console) — then re-run fetchEnv. Or remove preview.buckets.\"].join(\" \"), { details: {\n\t\t\t\tprojectId,\n\t\t\t\tbranchId: branch.id\n\t\t\t} });\n\t\t}\n\t\tconst secrets = wantsCredential ? await mintBranchCredential({\n\t\t\tapi,\n\t\t\tprojectId,\n\t\t\tbranchId: branch.id,\n\t\t\tbranchName: branch.name,\n\t\t\tscopes: previewCredentialScopes(desired.preview, {\n\t\t\t\tstorage: wantsStorageCredential,\n\t\t\t\taiGateway: wantsGatewayCredential\n\t\t\t})\n\t\t}) : null;\n\t\tif (storage) {\n\t\t\tconst storageEnv = {};\n\t\t\tif (secrets && wants(K.storage.accessKeyId)) storageEnv.accessKeyId = secrets.accessKeyId;\n\t\t\tif (secrets && wants(K.storage.secretAccessKey)) storageEnv.secretAccessKey = secrets.secretAccessKey;\n\t\t\tif (wants(K.storage.endpoint)) storageEnv.endpoint = storage.s3Endpoint;\n\t\t\tif (wants(K.storage.region)) storageEnv.region = storage.region;\n\t\t\tresult.storage = storageEnv;\n\t\t}\n\t\tif (wantsGateway) {\n\t\t\tconst gateway = {};\n\t\t\tif (secrets && wants(K.aiGateway.apiKey)) gateway.apiKey = secrets.apiToken;\n\t\t\tif (wants(K.aiGateway.baseUrl)) gateway.baseUrl = aiGatewayBaseUrl(branch.id, requiredValue(unpooled, \"direct connection URI for the selected AI Gateway base URL\").uri);\n\t\t\tresult.aiGateway = gateway;\n\t\t}\n\t}\n\treturn result;\n}\n/**\n* Resolve the target branch and evaluate the policy against it — the first thing any\n* branch-scoped operation needs. Shared by {@link fetchEnv} and {@link fetchEnvReusingSecrets}\n* so the two agree on which branch they're talking about and what it has enabled.\n*/\nasync function resolveBranchPolicy(config, options, api) {\n\tconst projectId = options.projectId;\n\tconst branches = await api.listBranches(projectId);\n\tif (branches.length === 0) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: project ${projectId} has no branches.`, \"Deploy your neon.ts policy (or create a branch) first, or pick a different project id.\"].join(\" \"), { details: { projectId } });\n\tconst branchRef = options.branch ?? options.branchId;\n\tif (!branchRef) throw new PlatformError(ErrorCode.BranchNotFound, [\"fetchEnv: no branch provided.\", \"Pass `branch` with a branch name (e.g. `main`) or id (`br-…`).\"].join(\" \"), { details: { projectId } });\n\tconst branch = resolveBranch(branchRef, branches);\n\treturn {\n\t\tbranch,\n\t\tdesired: resolveConfig(config, {\n\t\t\tname: branch.name,\n\t\t\tid: branch.id,\n\t\t\texists: true,\n\t\t\t...branch.parentId ? { parentId: branch.parentId } : {},\n\t\t\tisDefault: branch.isDefault,\n\t\t\tisProtected: branch.protected,\n\t\t\t...branch.expiresAt ? { expiresAt: branch.expiresAt } : {}\n\t\t})\n\t};\n}\n/**\n* Scopes the branch credential should carry for a resolved branch policy and optional key\n* selection. Only object storage and the AI Gateway *require* a credential; functions never\n* force one, but `functions:invoke` rides along when another selected feature mints one.\n*/\nfunction previewCredentialScopes(preview, selected) {\n\tif (!preview) return [];\n\tconst storage = preview.buckets.length > 0 && (selected?.storage ?? true);\n\tconst aiGateway = preview.aiGatewayEnabled && (selected?.aiGateway ?? true);\n\tif (!storage && !aiGateway) return [];\n\treturn deriveCredentialScopes({\n\t\tstorage,\n\t\taiGateway,\n\t\tfunctions: preview.functions.length > 0\n\t});\n}\n/** The `name` this tool stamps on every credential it mints, so it can recognize its own. */\nfunction credentialName(branchName) {\n\treturn `neon-env ${branchName}`;\n}\n/** The env-var keys a branch credential's secrets surface under, in emit order. */\nfunction credentialEnvKeys(flags) {\n\treturn [...flags.storage ? [NEON_ENV_VAR_KEYS.storage.accessKeyId, NEON_ENV_VAR_KEYS.storage.secretAccessKey] : [], ...flags.aiGateway ? [NEON_ENV_VAR_KEYS.aiGateway.apiKey] : []];\n}\n/**\n* Every OS-level env var a resolved branch policy produces, in emit order. Lets a caller\n* subtract the ones it already holds and pass the rest as {@link fetchEnv}'s `keys`, without\n* re-deriving which vars a policy implies.\n*/\nfunction policyEnvKeys(desired) {\n\tconst K = NEON_ENV_VAR_KEYS;\n\treturn [\n\t\tK.postgres.databaseUrl,\n\t\tK.postgres.databaseUrlUnpooled,\n\t\tK.branch.name,\n\t\t...desired.authEnabled ? [K.auth.baseUrl, K.auth.jwksUrl] : [],\n\t\t...desired.dataApiEnabled ? [K.dataApi.url] : [],\n\t\t...(desired.preview?.buckets.length ?? 0) > 0 ? [\n\t\t\tK.storage.accessKeyId,\n\t\t\tK.storage.secretAccessKey,\n\t\t\tK.storage.endpoint,\n\t\t\tK.storage.region\n\t\t] : [],\n\t\t...desired.preview?.aiGatewayEnabled ? [K.aiGateway.apiKey, K.aiGateway.baseUrl] : []\n\t];\n}\n/**\n* Mint the branch credential backing object storage / the AI Gateway.\n*\n* `api_token` and `s3_secret_access_key` come back **exactly once** — they are not stored\n* server-side and the list endpoint returns metadata only — so the caller's copy is the only\n* copy. That is why {@link fetchEnv} mints rather than fetches: there is nothing to fetch. A\n* caller that already holds a valid copy should leave the secret keys out of `keys` (see\n* {@link fetchEnvReusingSecrets}) instead of minting one it will discard.\n*/\nasync function mintBranchCredential(args) {\n\tconst minted = await args.api.createCredential(args.projectId, args.branchId, {\n\t\tscopes: args.scopes,\n\t\tprincipalType: \"user\",\n\t\tname: credentialName(args.branchName)\n\t});\n\treturn {\n\t\taccessKeyId: minted.tokenId,\n\t\tsecretAccessKey: minted.s3SecretAccessKey,\n\t\tapiToken: minted.apiToken\n\t};\n}\n/**\n* The AI Gateway is a **branch-scoped host** — `<branchId>-api.ai.<host-suffix>` — NOT the\n* control-plane API origin. Derive the suffix from the branch's own Postgres connection host\n* by dropping only the endpoint label (the first segment) and keeping everything after it,\n* including any infra cell prefix (`c-N.`): a connection host of\n* `ep-x.c-3.us-east-2.aws.neon.tech` yields the gateway host\n* `<branchId>-api.ai.c-3.us-east-2.aws.neon.tech`. The cell prefix is **load-bearing** —\n* the gateway is cell-routed, so dropping `c-N.` resolves to the wrong (or no) host.\n*/\nfunction aiGatewayHost(branchId, connectionUri) {\n\tlet connectionHost = \"\";\n\ttry {\n\t\tconnectionHost = new URL(connectionUri).hostname;\n\t} catch {\n\t\tconnectionHost = \"\";\n\t}\n\treturn `${branchId}-api.ai.${connectionHost.split(\".\").slice(1).join(\".\")}`;\n}\n/** The AI Gateway's bare base URL (`NEON_AI_GATEWAY_BASE_URL`) on the branch gateway host. */\nfunction aiGatewayBaseUrl(branchId, connectionUri) {\n\treturn `https://${aiGatewayHost(branchId, connectionUri)}`;\n}\nfunction createApiFromOptions(options) {\n\treturn createNeonApiFromOptions(\"fetchEnv\", {\n\t\t...options.apiKey ? { apiKey: options.apiKey } : {},\n\t\t...options.apiHost ? { apiHost: options.apiHost } : {}\n\t});\n}\n/**\n* Resolve a branch ref — a name or an id — to a concrete branch. Matches by id first\n* (exact `br-…`), then by name; both are unique within a project, so the lookup is\n* unambiguous. This lets `.neon` files written by `neonctl` (which pin the branch *name*)\n* and explicit `br-…` ids both work.\n*/\nfunction resolveBranch(branch, branches) {\n\tconst match = branches.find((b) => b.id === branch) ?? branches.find((b) => b.name === branch);\n\tif (match) return match;\n\tthrow new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: branch ${JSON.stringify(branch)} not found on project (matched by id or name).`, `Existing branches: ${branches.map((b) => `${b.name} (${b.id})`).join(\", \")}.`].join(\" \"), { details: {\n\t\tbranch,\n\t\tavailable: branches.map((b) => `${b.name} (${b.id})`)\n\t} });\n}\nfunction pickRoleName(roles, branch, requested) {\n\tif (requested) {\n\t\tif (!roles.some((r) => r.name === requested)) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: role \"${requested}\" not found on branch ${branch.name} (${branch.id}).`, `Existing roles: ${roles.map((r) => r.name).join(\", \") || \"(none)\"}.`].join(\" \"), { details: {\n\t\t\tbranchId: branch.id,\n\t\t\troleName: requested,\n\t\t\tavailableRoles: roles.map((r) => r.name)\n\t\t} });\n\t\treturn requested;\n\t}\n\tif (roles.length === 0) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: branch ${branch.name} (${branch.id}) has no roles.`, \"Create one via the Neon console or pass `roleName` explicitly.\"].join(\" \"), { details: { branchId: branch.id } });\n\tif (roles.length === 1) return roles[0].name;\n\tconst owner = roles.find((r) => r.name === NEON_DEFAULT_OWNER_ROLE);\n\tif (owner) return owner.name;\n\tconst appRoles = roles.filter((r) => !NEON_MANAGED_AUTH_ROLES.has(r.name));\n\tif (appRoles.length === 1) return appRoles[0].name;\n\tthrow new PlatformError(ErrorCode.AmbiguousBranchAuth, [`fetchEnv: branch ${branch.name} (${branch.id}) has ${roles.length} roles and none is \"${NEON_DEFAULT_OWNER_ROLE}\"; cannot auto-pick.`, `Pass \\`roleName\\` explicitly. Available: ${roles.map((r) => r.name).join(\", \")}.`].join(\" \"), { details: {\n\t\tbranchId: branch.id,\n\t\tavailableRoles: roles.map((r) => r.name)\n\t} });\n}\nfunction pickDatabaseName(databases, branch, requested) {\n\tif (requested) {\n\t\tif (!databases.some((d) => d.name === requested)) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: database \"${requested}\" not found on branch ${branch.name} (${branch.id}).`, `Existing databases: ${databases.map((d) => d.name).join(\", \") || \"(none)\"}.`].join(\" \"), { details: {\n\t\t\tbranchId: branch.id,\n\t\t\tdatabaseName: requested,\n\t\t\tavailableDatabases: databases.map((d) => d.name)\n\t\t} });\n\t\treturn requested;\n\t}\n\tif (databases.length === 0) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: branch ${branch.name} (${branch.id}) has no databases.`, \"Create one via the Neon console or pass `databaseName` explicitly.\"].join(\" \"), { details: { branchId: branch.id } });\n\tconst neondb = databases.find((d) => d.name === NEON_DEFAULT_DATABASE);\n\tif (neondb) return neondb.name;\n\tif (databases.length === 1) return databases[0].name;\n\tthrow new PlatformError(ErrorCode.AmbiguousBranchAuth, [`fetchEnv: branch ${branch.name} (${branch.id}) has ${databases.length} databases and none is named \"${NEON_DEFAULT_DATABASE}\"; cannot auto-pick.`, `Rename one to \"${NEON_DEFAULT_DATABASE}\" or keep a single database on the branch (or, when calling fetchEnv directly, pass \\`databaseName\\`). Available: ${databases.map((d) => d.name).join(\", \")}.`].join(\" \"), { details: {\n\t\tbranchId: branch.id,\n\t\tavailableDatabases: databases.map((d) => d.name)\n\t} });\n}\n/**\n* Project a fully-resolved {@link NeonEnv} into the OS-level `{ KEY: value }` pairs used\n* for cross-process transport. Named after the web-platform `.entries()` convention\n* (`URLSearchParams` / `Headers` / `FormData`); returns a `Record` rather than an\n* iterator of tuples since that's the shape env injection needs (wrap with\n* `Object.entries(...)` if you want literal `[key, value]` pairs). Used by `neon-env run`\n* to inject the vars into a subprocess's `process.env`.\n*\n* Walks the value at runtime so it works for any `NeonEnv<C>` regardless of which\n* conditional namespaces are present.\n*/\nfunction toEntries(env) {\n\tconst out = {};\n\tconst put = (key, value) => {\n\t\tif (value !== void 0) out[key] = value;\n\t};\n\tconst K = NEON_ENV_VAR_KEYS;\n\tput(K.postgres.databaseUrl, env.postgres?.databaseUrl);\n\tput(K.postgres.databaseUrlUnpooled, env.postgres?.databaseUrlUnpooled);\n\tput(K.branch.name, env.branch?.name);\n\tput(K.auth.baseUrl, env.auth?.baseUrl);\n\tput(K.auth.jwksUrl, env.auth?.jwksUrl);\n\tput(K.dataApi.url, env.dataApi?.url);\n\tput(K.storage.accessKeyId, env.storage?.accessKeyId);\n\tput(K.storage.secretAccessKey, env.storage?.secretAccessKey);\n\tput(K.storage.endpoint, env.storage?.endpoint);\n\tput(K.storage.region, env.storage?.region);\n\tput(K.aiGateway.apiKey, env.aiGateway?.apiKey);\n\tput(K.aiGateway.baseUrl, env.aiGateway?.baseUrl);\n\treturn out;\n}\n//#endregion\nexport { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys,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I,SAAS,GAAG;CACnC,IAAI,EAAE,QAAQ,aAAa,IAAI,SAAS,WAAW;CACnD,IAAI,EAAE,QAAQ,iBAAiB,IAAI,SAAS,eAAe;CAC3D,IAAI,EAAE,QAAQ,UAAU,IAAI,SAAS,QAAQ;CAC7C,IAAI,EAAE,QAAQ,QAAQ,IAAI,SAAS,MAAM;CACzC,IAAI,EAAE,UAAU,QAAQ,IAAI,WAAW,MAAM;CAC7C,IAAI,EAAE,UAAU,SAAS,IAAI,WAAW,OAAO;CAC/C,OAAO;AACR"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,528 @@
1
- import { FetchEnvOptions, FilteredNeonEnv, FunctionSlugOf, NEON_ENV_VAR_KEYS, NeonAiGatewayEnv, NeonAuthEnv, NeonBranchEnv, NeonDataApiEnv, NeonEnv, NeonFunctionEnv, NeonPostgresEnv, NeonStorageEnv, ResolvedNeonEnv, SelectableEnvKey, fetchEnv, parseEnv, toEntries } from "./lib/env.js";
2
- export { type FetchEnvOptions, type FilteredNeonEnv, type FunctionSlugOf, NEON_ENV_VAR_KEYS, type NeonAiGatewayEnv, type NeonAuthEnv, type NeonBranchEnv, type NeonDataApiEnv, type NeonEnv, type NeonFunctionEnv, type NeonPostgresEnv, type NeonStorageEnv, type ResolvedNeonEnv, type SelectableEnvKey, fetchEnv, parseEnv, toEntries };
1
+ import { Config, NeonApi, resolveConfig } from "@neon/config/v1";
2
+
3
+ //#region ../../internals/env-core/dist/env.d.ts
4
+
5
+ //#region src/env.d.ts
6
+ declare const NEON_ENV_VAR_KEYS: {
7
+ /**
8
+ * Branch identity. `NEON_BRANCH` carries the branch **name** and is injected into the
9
+ * Neon Functions runtime on every branch (including the default) by default. `env pull` /
10
+ * `neon dev` / `neon-env run` emit it too so local dev mirrors the deployed runtime.
11
+ */
12
+ readonly branch: {
13
+ readonly name: "NEON_BRANCH";
14
+ };
15
+ readonly postgres: {
16
+ readonly databaseUrl: "DATABASE_URL";
17
+ readonly databaseUrlUnpooled: "DATABASE_URL_UNPOOLED";
18
+ };
19
+ readonly auth: {
20
+ readonly baseUrl: "NEON_AUTH_BASE_URL";
21
+ readonly jwksUrl: "NEON_AUTH_JWKS_URL";
22
+ };
23
+ readonly dataApi: {
24
+ readonly url: "NEON_DATA_API_URL";
25
+ };
26
+ /**
27
+ * Object storage (Preview). The S3 SDKs read `AWS_*` from their standard config chain, so
28
+ * a branch credential + `neon dev` / `env pull` makes object storage work from env alone.
29
+ * `region` is injected under the SDK-standard `AWS_REGION`.
30
+ */
31
+ readonly storage: {
32
+ readonly accessKeyId: "AWS_ACCESS_KEY_ID";
33
+ readonly secretAccessKey: "AWS_SECRET_ACCESS_KEY";
34
+ readonly endpoint: "AWS_ENDPOINT_URL_S3";
35
+ readonly region: "AWS_REGION";
36
+ };
37
+ /**
38
+ * AI Gateway (Preview). Exposed under the Neon-branded env vars the deployed Functions
39
+ * runtime injects: `apiKey` is the minted credential's bearer (`NEON_AI_GATEWAY_TOKEN`)
40
+ * and `baseUrl` is the bare branch gateway host (`NEON_AI_GATEWAY_BASE_URL`,
41
+ * `scheme://host`, no path). Clients like `@neon/ai-sdk-provider` read these and append the
42
+ * dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves (https://github.com/vercel/ai/pull/15997).
43
+ */
44
+ readonly aiGateway: {
45
+ readonly apiKey: "NEON_AI_GATEWAY_TOKEN";
46
+ readonly baseUrl: "NEON_AI_GATEWAY_BASE_URL";
47
+ };
48
+ };
49
+ /**
50
+ * Branch identity for the resolved branch. Always present on a `fetchEnv` result (the branch
51
+ * name is always known); on a `parseEnv` result it's present only when `NEON_BRANCH` was
52
+ * injected into `process.env` (the Functions runtime injects it by default, as do `neon dev` /
53
+ * `neon-env run` / `env pull`). `name` is the branch **name** (e.g. `main`, `preview/foo`).
54
+ */
55
+ interface NeonBranchEnv {
56
+ name: string;
57
+ }
58
+ /** Per-namespace inner shapes. Exposed so consumers can name the parts independently. */
59
+ interface NeonPostgresEnv {
60
+ /**
61
+ * Pooled connection string (via Neon's PgBouncer pooler). The right default for
62
+ * serverless drivers (`@neondatabase/serverless`, edge runtimes, Postgres.js, …).
63
+ */
64
+ databaseUrl: string;
65
+ /**
66
+ * Direct (unpooled) connection string. Use this when you need session-level
67
+ * features (`LISTEN`/`NOTIFY`, prepared statements across calls, transactions
68
+ * spanning round-trips) that PgBouncer's transaction-mode pooling drops.
69
+ */
70
+ databaseUrlUnpooled: string;
71
+ }
72
+ /**
73
+ * Bits of a Neon Auth integration for the resolved branch. Only present on `NeonEnv`
74
+ * when the branch policy enables `auth`.
75
+ *
76
+ * Neon Auth exposes the `baseUrl` (which doubles as the publishable client identifier) and
77
+ * the `jwksUrl` used to verify tokens it issues. `fetchEnv` reads both from the live
78
+ * integration; `parseEnv` reads them from `process.env` (`NEON_AUTH_BASE_URL` /
79
+ * `NEON_AUTH_JWKS_URL`).
80
+ */
81
+ interface NeonAuthEnv {
82
+ baseUrl: string;
83
+ /** JWKS URL for verifying tokens issued by Neon Auth (`NEON_AUTH_JWKS_URL`). */
84
+ jwksUrl: string;
85
+ }
86
+ /** Bits of a Neon Data API integration. Only present when the branch policy enables it. */
87
+ interface NeonDataApiEnv {
88
+ url: string;
89
+ }
90
+ /**
91
+ * S3-compatible object-storage access for the branch (Preview). Present on `NeonEnv` only
92
+ * when the policy declares `preview.buckets`. Combines a minted branch credential's access
93
+ * keys (`accessKeyId` = the credential's full token id, e.g. `nak_live_…`, which is what the
94
+ * storage gateway authenticates against; `secretAccessKey` = its
95
+ * `s3_secret_access_key`) with the branch's non-secret connection details
96
+ * (`endpoint`/`region`, from `GET .../storage`). Projects to the AWS SDK's
97
+ * standard config env (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_ENDPOINT_URL_S3`,
98
+ * `AWS_REGION`) so the S3 client works from env alone. Neon's storage gateway always
99
+ * requires path-style addressing, so set `forcePathStyle: true` on your S3 client.
100
+ */
101
+ interface NeonStorageEnv {
102
+ accessKeyId: string;
103
+ secretAccessKey: string;
104
+ /** S3-compatible endpoint URL for the branch. */
105
+ endpoint: string;
106
+ /** AWS region string (e.g. `us-east-2`). Injected as `AWS_REGION`. */
107
+ region: string;
108
+ }
109
+ /**
110
+ * AI Gateway access for the branch (Preview). Present on `NeonEnv` only when the policy
111
+ * enables `preview.aiGateway`. `apiKey` is the minted credential's bearer (`api_token`);
112
+ * `baseUrl` is the bare branch-scoped gateway host
113
+ * (`https://<branchId>-api.ai.<region>.…`, no path). Projects to the Neon-branded env
114
+ * (`NEON_AI_GATEWAY_TOKEN`, `NEON_AI_GATEWAY_BASE_URL`); clients like `@neon/ai-sdk-provider`
115
+ * append the dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves.
116
+ */
117
+ interface NeonAiGatewayEnv {
118
+ apiKey: string;
119
+ baseUrl: string;
120
+ }
121
+ /**
122
+ * Empty record alias used as the "false" branch of the conditional namespace adds below.
123
+ * `Record<never, never>` is the no-op for intersection — the cleaner alternative to `{}`,
124
+ * which biome rejects (it means "any non-null", not "empty object").
125
+ */
126
+ type NoNamespace = Record<never, never>;
127
+ /**
128
+ * Resolve a **static** service toggle (the value of `config.auth` / `config.dataApi`) to a
129
+ * type-level boolean. The whole-thing wrapping (`[T] extends […]`) turns off distribution
130
+ * so a union/`undefined` is checked as one unit:
131
+ *
132
+ * - `false` / `{ enabled: false }` / `undefined` → `false`
133
+ * - `true` / `{ enabled: true }` / any other object (`{}`, `{ enabled?: boolean }`) → `true`
134
+ * (a present toggle defaults to enabled)
135
+ * - the bare `boolean | ServiceToggle | undefined` (the default `Config` param, no literal
136
+ * info) → `false`, so an untyped policy yields just `{ postgres }`.
137
+ */
138
+ type ServiceOn<T> = [T] extends [false] ? false : [T] extends [{
139
+ enabled: false;
140
+ }] ? false : [T] extends [undefined] ? false : [T] extends [true] ? true : [T] extends [{
141
+ enabled: true;
142
+ }] ? true : [T] extends [object] ? true : false;
143
+ /** True when `T` has at least one known key; `false` for `{}` / `never`. */
144
+ type HasKeys<T> = [keyof T] extends [never] ? false : true;
145
+ /**
146
+ * Whether the policy's **static** `preview` block declares at least one object-storage bucket
147
+ * (`preview.buckets`). Drives whether {@link NeonEnv} carries the `storage` namespace.
148
+ *
149
+ * The leading `[never]` guard is load-bearing: when a policy has no `preview` at all,
150
+ * `NonNullable<C["preview"]>` is `never`, and without the guard the `extends { … }` probe
151
+ * below would vacuously match (everything extends `never`-derived shapes) and `HasKeys<never>`
152
+ * would resolve `true`, wrongly adding the namespace. The guard short-circuits to `false`.
153
+ */
154
+ type HasBuckets<C extends Config> = [NonNullable<C["preview"]>] extends [never] ? false : NonNullable<C["preview"]> extends {
155
+ buckets: infer B;
156
+ } ? HasKeys<NonNullable<B>> : false;
157
+ /**
158
+ * Whether the policy's **static** `preview` block enables the AI Gateway
159
+ * (`preview.aiGateway`). Drives whether {@link NeonEnv} carries the `aiGateway` namespace.
160
+ *
161
+ * The leading `[never]` guard is load-bearing for the same reason as {@link HasBuckets}: when
162
+ * a policy has no `preview`, `NonNullable<C["preview"]>` is `never`, and a naked `never` in the
163
+ * `extends` below would *distribute* (collapsing the result — and the whole `NeonEnv`
164
+ * intersection — to `never`). The tuple-wrapped guard short-circuits that to `false`.
165
+ */
166
+ type AiGatewayOn<C extends Config> = [NonNullable<C["preview"]>] extends [never] ? false : NonNullable<C["preview"]> extends {
167
+ aiGateway: infer A;
168
+ } ? ServiceOn<NonNullable<A>> : false;
169
+ /**
170
+ * Static, namespaced shape of `fetchEnv` / `parseEnv`'s return value. Generic over the
171
+ * {@link Config} so the type system knows which optional namespaces are present.
172
+ *
173
+ * Because the secret-bearing toggles now live in the **static** top-level `config.auth` /
174
+ * `config.dataApi` (not inside a per-branch closure), the namespace presence is a direct
175
+ * read of those fields — no union-across-branches, no default-config escape hatch:
176
+ *
177
+ * - `postgres` is always present.
178
+ * - `auth` is added iff `config.auth` is statically enabled.
179
+ * - `dataApi` is added iff `config.dataApi` is statically enabled.
180
+ * - `storage` is added iff `config.preview.buckets` declares at least one bucket.
181
+ * - `aiGateway` is added iff `config.preview.aiGateway` is statically enabled.
182
+ */
183
+ type NeonEnv<C extends Config = Config> = {
184
+ postgres: NeonPostgresEnv;
185
+ /**
186
+ * Branch identity (`NEON_BRANCH`). Optional because `parseEnv` only surfaces it when the
187
+ * var was injected; `fetchEnv` always populates it.
188
+ */
189
+ branch?: NeonBranchEnv;
190
+ } & (ServiceOn<NonNullable<C["auth"]>> extends true ? {
191
+ auth: NeonAuthEnv;
192
+ } : NoNamespace) & (ServiceOn<NonNullable<C["dataApi"]>> extends true ? {
193
+ dataApi: NeonDataApiEnv;
194
+ } : NoNamespace) & (HasBuckets<C> extends true ? {
195
+ storage: NeonStorageEnv;
196
+ } : NoNamespace) & (AiGatewayOn<C> extends true ? {
197
+ aiGateway: NeonAiGatewayEnv;
198
+ } : NoNamespace);
199
+ /**
200
+ * OS-level env-var keys grouped by the {@link NeonEnv} namespace they populate. Only the
201
+ * **input** vars `parseEnv` validates are listed — the output-only aliases in
202
+ * {@link NEON_ENV_VAR_KEYS} (`NEON_AI_GATEWAY_TOKEN`, …) are intentionally absent, so they
203
+ * are not selectable in a `parseEnv(config, keys)` filter. Keep in sync with
204
+ * {@link EnvKeyToProp}.
205
+ */
206
+ interface EnvKeysByNamespace {
207
+ postgres: "DATABASE_URL" | "DATABASE_URL_UNPOOLED";
208
+ branch: "NEON_BRANCH";
209
+ auth: "NEON_AUTH_BASE_URL" | "NEON_AUTH_JWKS_URL";
210
+ dataApi: "NEON_DATA_API_URL";
211
+ storage: "AWS_ACCESS_KEY_ID" | "AWS_SECRET_ACCESS_KEY" | "AWS_ENDPOINT_URL_S3" | "AWS_REGION";
212
+ aiGateway: "NEON_AI_GATEWAY_TOKEN" | "NEON_AI_GATEWAY_BASE_URL";
213
+ }
214
+ /** The {@link NeonEnv} namespace interface backing each namespace key. */
215
+ interface NamespaceEnv {
216
+ postgres: NeonPostgresEnv;
217
+ branch: NeonBranchEnv;
218
+ auth: NeonAuthEnv;
219
+ dataApi: NeonDataApiEnv;
220
+ storage: NeonStorageEnv;
221
+ aiGateway: NeonAiGatewayEnv;
222
+ }
223
+ /** OS-level env-var key → the camelCase property it sets on its namespace object. */
224
+ interface EnvKeyToProp {
225
+ DATABASE_URL: "databaseUrl";
226
+ DATABASE_URL_UNPOOLED: "databaseUrlUnpooled";
227
+ NEON_BRANCH: "name";
228
+ NEON_AUTH_BASE_URL: "baseUrl";
229
+ NEON_AUTH_JWKS_URL: "jwksUrl";
230
+ NEON_DATA_API_URL: "url";
231
+ AWS_ACCESS_KEY_ID: "accessKeyId";
232
+ AWS_SECRET_ACCESS_KEY: "secretAccessKey";
233
+ AWS_ENDPOINT_URL_S3: "endpoint";
234
+ AWS_REGION: "region";
235
+ NEON_AI_GATEWAY_TOKEN: "apiKey";
236
+ NEON_AI_GATEWAY_BASE_URL: "baseUrl";
237
+ }
238
+ /**
239
+ * The OS-level env-var keys selectable for a given policy: the union of input vars across
240
+ * exactly the namespaces {@link NeonEnv}<C> carries. Drives the typesafe autocomplete of the
241
+ * `keys` filter — selecting a var from a namespace the policy does not enable is a type error
242
+ * (e.g. `NEON_AUTH_BASE_URL` is only offered once the policy turns on `auth`).
243
+ */
244
+ type SelectableEnvKey<C extends Config> = EnvKeysByNamespace[keyof NeonEnv<C> & keyof EnvKeysByNamespace];
245
+ /**
246
+ * The result shape of a **filtered** `parseEnv(config, keys)` call: the namespaced
247
+ * {@link NeonEnv} restricted to exactly the selected OS-level keys `K`. Namespaces with no
248
+ * selected key are dropped, and within a kept namespace only the selected properties survive
249
+ * — selecting just `["DATABASE_URL"]` yields `{ postgres: { databaseUrl: string } }`, with no
250
+ * `databaseUrlUnpooled`.
251
+ *
252
+ * The policy gating lives on the `parseEnv` overload (which binds `K` to
253
+ * {@link SelectableEnvKey}); this type only needs the selection, so it takes a bare
254
+ * `K extends string` and filters with `Extract`. The outer mapped type's `as` clause drops
255
+ * any namespace whose intersection with the selection is empty (`[…] extends [never]`,
256
+ * tuple-wrapped to switch off distribution); the inner one re-keys each selected OS var to its
257
+ * camelCase property and looks the value type up on the canonical namespace interface, so it
258
+ * stays correct if a field ever stops being a plain `string`.
259
+ */
260
+ type FilteredNeonEnv<K extends string> = { [N in keyof EnvKeysByNamespace as [Extract<K, EnvKeysByNamespace[N]>] extends [never] ? never : N]: { [P in Extract<K, EnvKeysByNamespace[N]> as EnvKeyToProp[P & keyof EnvKeyToProp]]: NamespaceEnv[N][EnvKeyToProp[P & keyof EnvKeyToProp] & keyof NamespaceEnv[N]] } };
261
+ /**
262
+ * A filtered result when the exact runtime contents of a key array are unknown. Both the
263
+ * namespace and its selected properties are optional because the array may omit any member of
264
+ * its element union, or be empty.
265
+ */
266
+ type OptionalFilteredNeonEnv<K extends string> = { [N in keyof EnvKeysByNamespace as [Extract<K, EnvKeysByNamespace[N]>] extends [never] ? never : N]?: { [P in Extract<K, EnvKeysByNamespace[N]> as EnvKeyToProp[P & keyof EnvKeyToProp]]?: NamespaceEnv[N][EnvKeyToProp[P & keyof EnvKeyToProp] & keyof NamespaceEnv[N]] } };
267
+ /** Whether `T` is a union rather than one concrete type. */
268
+ type IsUnion<T, Whole = T> = T extends Whole ? [Whole] extends [T] ? false : true : never;
269
+ /** Whether any fixed tuple position can hold more than one key at runtime. */
270
+ type TupleHasUnion<T extends readonly unknown[]> = T extends readonly [] ? false : T extends readonly [infer Head, ...infer Tail extends readonly unknown[]] ? true extends IsUnion<Head> ? true : TupleHasUnion<Tail> : true;
271
+ /**
272
+ * The sound result of selecting an array of OS-level env-var keys.
273
+ *
274
+ * Inline literal tuples remain exact. Widened arrays, rest tuples, and tuple positions whose
275
+ * value is a union are conservative because their runtime contents may be any subset of the
276
+ * element type. The leading conditional distributes unions of whole literal tuples, preserving
277
+ * each exact alternative.
278
+ */
279
+ type SelectedNeonEnv<Keys extends readonly string[]> = Keys extends readonly string[] ? number extends Keys["length"] ? OptionalFilteredNeonEnv<Keys[number]> : TupleHasUnion<Keys> extends true ? OptionalFilteredNeonEnv<Keys[number]> : FilteredNeonEnv<Keys[number]> : never;
280
+ type StorageCredentialEnvKey = "AWS_ACCESS_KEY_ID" | "AWS_SECRET_ACCESS_KEY";
281
+ type StorageKeyPairError = {
282
+ readonly "fetchEnv keys must include AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY together": never;
283
+ };
284
+ type TupleDefinitelyContains<Keys extends readonly string[], Key extends string> = Keys extends readonly [infer Head extends string, ...infer Tail extends readonly string[]] ? [Head] extends [Key] ? true : TupleDefinitelyContains<Tail, Key> : false;
285
+ type TupleDefinitelyContainsStoragePair<Keys extends readonly string[]> = TupleDefinitelyContains<Keys, "AWS_ACCESS_KEY_ID"> extends true ? TupleDefinitelyContains<Keys, "AWS_SECRET_ACCESS_KEY"> extends true ? true : false : false;
286
+ /**
287
+ * Reject a fixed key tuple that contains only one half of the storage credential. Dynamic
288
+ * arrays are checked at runtime because their contents are not known to TypeScript.
289
+ */
290
+ type InvalidStorageKeyTuple<Keys extends readonly string[]> = Keys extends unknown ? number extends Keys["length"] ? never : [Extract<Keys[number], StorageCredentialEnvKey>] extends [never] ? never : TupleDefinitelyContainsStoragePair<Keys> extends true ? never : Keys : never;
291
+ type StorageKeyPairConstraint<Keys extends readonly string[]> = [InvalidStorageKeyTuple<Keys>] extends [never] ? unknown : StorageKeyPairError;
292
+ type FetchEnvKeysFromArgs<Args extends readonly unknown[]> = Args[0] extends {
293
+ keys: infer Keys extends readonly string[];
294
+ } ? Keys : never;
295
+ type StorageKeyPairArgsConstraint<Args extends readonly unknown[]> = StorageKeyPairConstraint<FetchEnvKeysFromArgs<Args>>;
296
+ /** Preserve the same pair rule for callers that explicitly provide the legacy `K` generic. */
297
+ type StorageKeyUnionConstraint<K extends string> = [Extract<K, StorageCredentialEnvKey>] extends [never] ? unknown : StorageCredentialEnvKey extends K ? unknown : StorageKeyPairError;
298
+ interface FetchEnvOptions {
299
+ /**
300
+ * Neon project id. **Required** — the management API addresses branches through their
301
+ * project. Resolve it in your CLI (e.g. neonctl) and pass it in.
302
+ */
303
+ projectId: string;
304
+ /**
305
+ * Neon branch — its **name** (e.g. `main`) or its id (`br-…`). **Required** (or pass the
306
+ * legacy {@link FetchEnvOptions.branchId}). Resolved against the project's branches by
307
+ * id first, then by name, so either form works.
308
+ */
309
+ branch?: string;
310
+ /**
311
+ * @deprecated Legacy id-only field. Prefer {@link FetchEnvOptions.branch}, which accepts
312
+ * a branch name or id. Still honored for backward compatibility; ignored when `branch`
313
+ * is set.
314
+ */
315
+ branchId?: string;
316
+ /**
317
+ * Neon API key. Resolved via the standard chain (option → `NEON_API_KEY` →
318
+ * `~/.config/neonctl/credentials.json`) when omitted. Ignored when a custom `api`
319
+ * is supplied.
320
+ */
321
+ apiKey?: string;
322
+ /**
323
+ * Neon **management** API base URL (not the Auth base URL). Falls back to
324
+ * `NEON_API_HOST`, then production. Ignored when a custom `api` is supplied.
325
+ */
326
+ apiHost?: string;
327
+ /**
328
+ * Inject a custom NeonApi adapter. Primarily used by tests; production callers can rely
329
+ * on the default real adapter built from `apiKey`.
330
+ */
331
+ api?: NeonApi;
332
+ /**
333
+ * Role name to fetch credentials for. When omitted, the connection role is auto-picked:
334
+ * the only role on the branch, else Neon's default owner (`neondb_owner`), else the
335
+ * single role left after dropping the managed Auth/Data API roles
336
+ * (`authenticator`/`anonymous`/`authenticated`). Throws {@link PlatformError} with
337
+ * `PLATFORM_AMBIGUOUS_BRANCH_AUTH` only when more than one app role remains.
338
+ */
339
+ roleName?: string;
340
+ /**
341
+ * Database name. When omitted, it is auto-picked: Neon's default `neondb` if present,
342
+ * else the only database on the branch. Throws {@link PlatformError} with
343
+ * `PLATFORM_AMBIGUOUS_BRANCH_AUTH` when the branch has several databases and none is
344
+ * `neondb` (pass `databaseName` to disambiguate), and `PLATFORM_BRANCH_NOT_FOUND` when
345
+ * the branch has no databases or the requested `databaseName` does not exist.
346
+ */
347
+ databaseName?: string;
348
+ }
349
+ /**
350
+ * Resolve the project + branch this process should target, then fetch live Neon
351
+ * connection strings for that branch over the network. Async — calls the Neon API.
352
+ *
353
+ * Use this from build scripts and the `neon-env run` command, where top-level await is
354
+ * fine. For application code that needs a synchronous bootstrap (most frameworks: Drizzle
355
+ * config, Next.js, Vite, etc.), inject env vars via `neon-env run -- <cmd>` and use
356
+ * {@link parseEnv} instead — same {@link NeonEnv} shape, but a sync call against
357
+ * `process.env`.
358
+ *
359
+ * Filesystem- and env-agnostic: pass `projectId` and the target `branch` (name or id)
360
+ * explicitly (resolve them in your CLI, e.g. neonctl).
361
+ *
362
+ * ```ts
363
+ * import config from "../neon";
364
+ * import { fetchEnv } from "@neon/env";
365
+ *
366
+ * const env = await fetchEnv(config, { projectId: "patient-art-12345", branch: "main" });
367
+ * const db = drizzle(neon(env.postgres.databaseUrl), { schema });
368
+ * ```
369
+ *
370
+ * Pass `keys` to fetch only some of them — see the overload below.
371
+ *
372
+ * The package does **not** read `process.env`, mutate it, or touch the filesystem. Everything
373
+ * it returns comes from the Neon API, so a value the API cannot produce (a one-time secret
374
+ * issued to a previous call) is minted afresh rather than recovered. Callers that hold
375
+ * persisted secrets and want to keep them use {@link fetchEnvReusingSecrets}, which decides
376
+ * what is still valid and narrows this call's `keys` accordingly.
377
+ */
378
+ declare function fetchEnv<const C extends Config, const Args extends readonly [options: FetchEnvOptions & {
379
+ /**
380
+ * Fetch only these OS-level env vars, instead of everything the policy enables. The
381
+ * keys autocomplete from the policy ({@link SelectableEnvKey}), and the result is
382
+ * narrowed to match ({@link SelectedNeonEnv}). Inline literal arrays produce an exact
383
+ * result; runtime-built arrays make their possible namespaces and properties optional.
384
+ * `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` must be selected together.
385
+ *
386
+ * The point is not just a smaller result: **work is skipped too.** Leave out
387
+ * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `NEON_AI_GATEWAY_TOKEN` and no branch
388
+ * credential is minted at all, so a caller that already holds valid secrets can refresh
389
+ * everything else without issuing a new one. The non-secret vars of the same features
390
+ * (`AWS_ENDPOINT_URL_S3`, `AWS_REGION`, `NEON_AI_GATEWAY_BASE_URL`) are not
391
+ * credential-backed and stay available on their own.
392
+ *
393
+ * The selection **intersects** with the policy rather than overriding it: naming a var
394
+ * the branch policy does not enable is not an error, it simply yields nothing.
395
+ */
396
+ keys: readonly SelectableEnvKey<C>[];
397
+ }]>(config: C, ...args: Args & StorageKeyPairArgsConstraint<NoInfer<Args>>): Promise<SelectedNeonEnv<FetchEnvKeysFromArgs<NoInfer<Args>>>>;
398
+ declare function fetchEnv<const C extends Config, const K extends SelectableEnvKey<C> = never>(config: C, options: [NoInfer<K>] extends [never] ? never : FetchEnvOptions & {
399
+ keys: readonly NoInfer<K>[];
400
+ } & StorageKeyUnionConstraint<NoInfer<K>>): Promise<FilteredNeonEnv<NoInfer<K>>>;
401
+ declare function fetchEnv<const C extends Config>(config: C, options: FetchEnvOptions & {
402
+ keys?: never;
403
+ }): Promise<NeonEnv<C>>;
404
+ /** Diagnostic-only fallback: valid keyed calls resolve through the exact overload above. */
405
+ declare function fetchEnv<const C extends Config, const Keys extends readonly SelectableEnvKey<C>[]>(config: C, options: FetchEnvOptions & {
406
+ keys: Keys;
407
+ } & StorageKeyPairError): Promise<never>;
408
+ /**
409
+ * The {@link fetchEnv} body, with the key selection as a plain argument and no generic
410
+ * narrowing. Exists for callers that compute the selection at runtime — notably
411
+ * {@link fetchEnvReusingSecrets}, which decides which keys it still needs by checking the
412
+ * branch — since the public overload's `keys` is bound to a literal union those callers cannot
413
+ * produce without asserting.
414
+ *
415
+ * `keys === null` selects everything the policy enables.
416
+ */
417
+
418
+ /**
419
+ * Project a fully-resolved {@link NeonEnv} into the OS-level `{ KEY: value }` pairs used
420
+ * for cross-process transport. Named after the web-platform `.entries()` convention
421
+ * (`URLSearchParams` / `Headers` / `FormData`); returns a `Record` rather than an
422
+ * iterator of tuples since that's the shape env injection needs (wrap with
423
+ * `Object.entries(...)` if you want literal `[key, value]` pairs). Used by `neon-env run`
424
+ * to inject the vars into a subprocess's `process.env`.
425
+ *
426
+ * Walks the value at runtime so it works for any `NeonEnv<C>` regardless of which
427
+ * conditional namespaces are present.
428
+ */
429
+ declare function toEntries(env: ResolvedNeonEnv): Record<string, string>;
430
+ /**
431
+ * Any resolved env {@link toEntries} can project: a full {@link NeonEnv}, or the narrowed
432
+ * result of a `keys`-filtered {@link fetchEnv} / {@link parseEnv} call. Every namespace and
433
+ * property is optional so a filtered result — which legitimately carries only what was asked
434
+ * for — projects to exactly the vars it holds instead of failing to type-check.
435
+ */
436
+ type ResolvedNeonEnv = { [N in keyof NamespaceEnv]?: Partial<NamespaceEnv[N]> };
437
+ //#endregion
438
+ //#endregion
439
+ //#region src/lib/parse-env.d.ts
440
+ /** The static `preview.functions` record of a config, or an empty record when absent. */
441
+ type PreviewFunctionsOf<C extends Config> = NonNullable<C["preview"]> extends {
442
+ functions: infer F;
443
+ } ? F : Record<never, never>;
444
+ /** The declared function slugs of a config (record keys), as a string union. */
445
+ type FunctionSlugOf<C extends Config> = Extract<keyof PreviewFunctionsOf<C>, string>;
446
+ /**
447
+ * Human-readable hint surfaced as the **expected type** of `parseEnv`'s `scope` argument when
448
+ * the policy declares no functions at all. Without it the argument's expected type is the bare
449
+ * `never` {@link FunctionSlugOf} yields, and TypeScript reports the opaque `Type '"x"' is not
450
+ * assignable to type 'never'`; the literal turns that into a sentence naming the fix (and the
451
+ * editor offers it as the single completion, so the empty completion list is explained rather
452
+ * than just empty). Mirrors `NeonAuthRequiredHint` in `@neon/config`.
453
+ */
454
+ type NoFunctionScopeHint = "this policy declares no `preview.functions`, so there is no function scope to read. Declare the function in `neon.ts` first, or omit the scope to read the branch env";
455
+ /**
456
+ * The expected type of `parseEnv`'s function-slug `scope` argument: the caller's inferred slug
457
+ * `S` normally, and the {@link NoFunctionScopeHint} message when the policy declares no
458
+ * functions. Keeping `S` (rather than `FunctionSlugOf<C>`) in the enabled branch is what makes
459
+ * the returned `function` namespace exact — it stays the one function's env keys instead of
460
+ * widening to every declared function's.
461
+ */
462
+ type FunctionScopeField<C extends Config, S extends string> = [FunctionSlugOf<C>] extends [never] ? NoFunctionScopeHint : S;
463
+ /** The declared env-var keys of one function `S`, as a string union. */
464
+ type FunctionEnvKeysOf<C extends Config, S extends string> = S extends keyof PreviewFunctionsOf<C> ? NonNullable<PreviewFunctionsOf<C>[S]> extends {
465
+ env: infer E;
466
+ } ? Extract<keyof E, string> : never : never;
467
+ /**
468
+ * The extra `function` namespace added to `parseEnv`'s result when called with a function
469
+ * slug scope: the declared env-var keys for that function, each resolved to a `string`.
470
+ */
471
+ type NeonFunctionEnv<C extends Config, S extends string> = {
472
+ function: Record<FunctionEnvKeysOf<C, S>, string>;
473
+ };
474
+ /**
475
+ * Synchronous, network-free counterpart to {@link fetchEnv}. Reads `process.env`, validates
476
+ * the required Neon env vars with zod, and returns the same {@link NeonEnv} shape — so the
477
+ * rest of your app touches `env.postgres.databaseUrl` instead of stringly-typed
478
+ * `process.env.DATABASE_URL` lookups.
479
+ *
480
+ * Designed for the **"env-vars-already-injected"** path:
481
+ * - You wrapped your dev command with `neon-env run -- <cmd>` or `neon dev`.
482
+ * - Your platform (Vercel, Fly, Railway, …) injected the vars via its own integration.
483
+ * - You are **inside a deployed Neon Function**, whose env was uploaded at `config apply`.
484
+ *
485
+ * Unlike the old API, `parseEnv` does **not** take a branch name: the secret set is now
486
+ * static (top-level `config.auth` / `config.dataApi`), so it reads those directly without
487
+ * evaluating the per-branch closure.
488
+ *
489
+ * The second argument is a **scope** or a **key filter**:
490
+ * - omitted — *external* scope (app bootstrap, build scripts, your dev machine). Returns the
491
+ * full `{ postgres, auth?, dataApi?, … }` the policy enables.
492
+ * - a **function slug** (a key of `config.preview.functions`) — *function* scope: you are
493
+ * running inside that function. Returns the same branch secrets **plus** a typed
494
+ * `function` namespace with the function's declared env-var keys. The slug autocompletes
495
+ * from the policy ({@link FunctionSlugOf}) and an undeclared one is a type error.
496
+ * - an **array of OS-level env-var keys** (e.g. `["DATABASE_URL", "NEON_AUTH_BASE_URL"]`) —
497
+ * *filtered* mode: only those vars are required and returned, as a narrowed namespaced
498
+ * shape. The keys autocomplete from the policy ({@link SelectableEnvKey}), so you can only
499
+ * pick vars the policy actually enables. Use this when a process needs just a subset (a
500
+ * Next.js app that reads `DATABASE_URL` but not `DATABASE_URL_UNPOOLED`, say) and you don't
501
+ * want `parseEnv` to throw over vars you never use.
502
+ *
503
+ * Throws `PlatformError(EnvNotInjected)` listing every missing/invalid var when the env
504
+ * isn't fully populated, with a fix hint pointing back at `neon dev` / `neon-env run`.
505
+ *
506
+ * ```ts
507
+ * import config from "../neon";
508
+ * import { parseEnv } from "@neon/env";
509
+ *
510
+ * // External (app / build):
511
+ * const env = parseEnv(config);
512
+ * const db = drizzle(neon(env.postgres.databaseUrl), { schema });
513
+ *
514
+ * // Inside the "hello" function:
515
+ * const env = parseEnv(config, "hello");
516
+ * env.function.resendApiKey; // typed from hello's declared env keys
517
+ *
518
+ * // Filtered: only enforce + return the pooled URL.
519
+ * const { postgres } = parseEnv(config, ["DATABASE_URL"]);
520
+ * postgres.databaseUrl; // string — `databaseUrlUnpooled` is absent
521
+ * ```
522
+ */
523
+ declare function parseEnv<const C extends Config>(config: C): NeonEnv<C>;
524
+ declare function parseEnv<const C extends Config, const S extends FunctionSlugOf<C>>(config: C, scope: FunctionScopeField<C, S>): NeonEnv<C> & NeonFunctionEnv<C, S>;
525
+ declare function parseEnv<const C extends Config, const K extends SelectableEnvKey<C>>(config: C, keys: readonly K[]): FilteredNeonEnv<K>;
526
+ //#endregion
527
+ export { type FetchEnvOptions, type FilteredNeonEnv, type FunctionSlugOf, NEON_ENV_VAR_KEYS, type NeonAiGatewayEnv, type NeonAuthEnv, type NeonBranchEnv, type NeonDataApiEnv, type NeonEnv, type NeonFunctionEnv, type NeonPostgresEnv, type NeonStorageEnv, type ResolvedNeonEnv, type SelectableEnvKey, type SelectedNeonEnv, fetchEnv, parseEnv, toEntries };
528
+ //# sourceMappingURL=index.d.ts.map