neon 2.46.0 → 3.0.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.
package/README.md CHANGED
@@ -417,9 +417,15 @@ The human-readable summary line goes to stderr and the diff body to stdout, so `
417
417
 
418
418
  ### env pull
419
419
 
420
- `env pull` writes the linked branch's Neon environment variables into a local dotenv file: an existing `.env` if you have one, otherwise `.env.local` (override with `--file <path>`). Only Neon-managed keys (`DATABASE_URL`, `DATABASE_URL_UNPOOLED`, and the Neon Auth / Data API URLs when those services are enabled) are written; any other lines in the file are preserved. The branch comes from the closest `.neon` file, so no `--branch` is needed (pass `--branch <id|name>` to target another branch).
420
+ `env pull` writes the linked branch's Neon environment variables into a local dotenv file: an existing `.env` if you have one, otherwise `.env.local` (override with `--file <path>`). Only Neon-managed keys are written (see the table below); any other lines in the file are preserved. The branch comes from the closest `.neon` file, so no `--branch` is needed (pass `--branch <id|name>` to target another branch).
421
421
 
422
- `link` and `checkout` invoke `env pull` automatically (see above), so you usually only run it by hand to refresh vars or to pull a different branch into a specific file:
422
+ **What gets pulled**, in precedence order:
423
+
424
+ 1. **`--service`**, when you pass it — exactly those services, whatever else is on the branch and whatever a `neon.ts` says.
425
+ 2. **`neon.ts`**, when the working directory has one — the policy is the source of truth, same as `neon dev` and `neon deploy`.
426
+ 3. **Everything the branch has** otherwise — Postgres, Neon Auth, the Data API, and object storage read back from the branch, plus the AI Gateway. The gateway has no branch-level state to read back (it is credential-gated, not provisioned), so a bare `env pull` asks for it rather than detecting it, which mints a branch credential. To leave it out, name the services you do want with `--service`.
427
+
428
+ If the gateway can't be resolved, it is dropped with a warning and the rest of the pull still lands. Gateway variables already in your file for *this* branch are left alone — a pull that couldn't reach the gateway is no evidence the branch has stopped having one — while ones left over from a different branch are pruned like any other stale value.
423
429
 
424
430
  ```bash
425
431
  # Refresh the linked branch's vars in place
@@ -427,10 +433,45 @@ neon env pull
427
433
 
428
434
  # Pull a specific branch into a specific file
429
435
  neon env pull --branch preview --file .env.preview
436
+
437
+ # Only the AI Gateway
438
+ neon env pull --service ai-gateway
439
+
440
+ # Repeat the flag or comma-separate; -s, --service and --services are all accepted
441
+ neon env pull -s postgres -s data-api
442
+ neon env pull -s postgres,auth
443
+ ```
444
+
445
+ Every services flag in the CLI takes those three spellings, the same value syntax, and the same service names — see [`config init --services`](#getting-a-neonts-config-init).
446
+
447
+ | `--service` | Variables |
448
+ | --- | --- |
449
+ | `postgres` | `DATABASE_URL`, `DATABASE_URL_UNPOOLED` |
450
+ | `auth` | `NEON_AUTH_BASE_URL`, `NEON_AUTH_JWKS_URL` |
451
+ | `data-api` | `NEON_DATA_API_URL` |
452
+ | `object-storage` | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_ENDPOINT_URL_S3`, `AWS_REGION` |
453
+ | `ai-gateway` | `NEON_AI_GATEWAY_TOKEN`, `NEON_AI_GATEWAY_BASE_URL` |
454
+
455
+ `NEON_BRANCH` is written by every pull — it is branch identity, not a service.
456
+
457
+ **A scoped pull is scoped in both directions.** An unscoped `env pull` owns the Neon-named variables: pointing a directory at a branch without Neon Auth prunes the stale `NEON_AUTH_*` lines. `--service` narrows that to the services you named, so `env pull -s ai-gateway` never touches your `DATABASE_URL`. (`AWS_*` is never pruned by any pull: those names collide with credentials you may set yourself, so `env pull` only ever writes them.)
458
+
459
+ **A scoped pull also never revokes a credential.** Where an unscoped pull revokes the credential it replaces, a scoped one leaves the old one live — it can't tell which other services still use it. It says so when it happens; revoke it in the Neon Console if nothing does.
460
+
461
+ Naming a service the branch does not have is an error, not an empty pull:
462
+
463
+ ```
464
+ --service auth: branch br-snowy-frost-12345 has no Neon Auth integration, so there are no
465
+ auth env vars to pull. Provision it first (`neon deploy`, `neon config apply`, or the Neon
466
+ Console), or drop auth from --service.
430
467
  ```
431
468
 
469
+ `link`, `checkout`, and `config apply` invoke `env pull` automatically (see above). Those bundled pulls follow rules 2 and 3 above **without** the implied AI Gateway: minting a credential for a service you never named isn't something a side effect of another command should do. Run `neon env pull` to get it.
470
+
432
471
  If you'd rather not keep env vars on disk, inject them at runtime instead with `neon-env run -- <your dev command>` (from `@neon/env`) or `neon dev`, and pass `--no-env-pull` to `link` / `checkout`.
433
472
 
473
+ **`neon dev` resolves the same set, by the same rules** — including the AI Gateway on a branch with no `neon.ts`. A function running locally gets what the deployed runtime would inject into it, which is the whole point of `dev`; a handler that reads `NEON_AI_GATEWAY_BASE_URL` should not work in production and fail on your machine. `dev` writes nothing, but it does *read* your `.env` / `.env.local` to reuse the branch credential behind the AI Gateway and object storage. Without a file to read from it issues one on every start and leaves the last one live — it has nowhere to keep it, and so cannot name it to revoke it. It says so when it happens; run `env pull` (or just `link` / `checkout`) once and restarts reuse the credential instead.
474
+
434
475
  **Where `.neon` lives**: `link` writes `.neon` into the **current working directory** by default. If an existing `.neon` is found in any parent directory, that file is reused — so commands run from a sub-directory of a linked project still pick up the project's context. To pin the location explicitly, pass `--context-file <path>`.
435
476
 
436
477
  **`.gitignore` scaffolding**: when `.neon` is **created** for the first time, the CLI also makes sure a `.gitignore` sits alongside it listing `.neon`. If `.gitignore` doesn't exist it's created with a single `.neon` line; if it does exist, `.neon` is appended only when missing (no duplicates, your other entries are left alone). On subsequent updates to an existing `.neon`, `.gitignore` is left untouched — so if you deliberately un-ignore `.neon` (e.g. to commit shared context), the entry is not re-added on every command.
@@ -479,7 +520,10 @@ Selecting nothing is a valid answer: you get the starter policy, which is also w
479
520
  neon config init
480
521
 
481
522
  # Declare services with no prompt
482
- neon config init --services auth,functions,storage,ai-gateway
523
+ neon config init --services auth,functions,object-storage,ai-gateway
524
+
525
+ # Repeat the flag instead, and shorten it — every services flag takes all three spellings
526
+ neon config init -s auth -s functions
483
527
 
484
528
  # Explicitly ask for the bare starter policy
485
529
  neon config init --services none
@@ -488,6 +532,8 @@ neon config init --services none
488
532
  neon config init --no-install
489
533
  ```
490
534
 
535
+ Object storage is spelled `object-storage` here, matching [`env pull --service`](#env-pull) and the rest of the CLI. The old `storage` still works and warns; it will be removed.
536
+
491
537
  Choosing **Functions** also writes the handler the policy points at, since `source` is only resolved when `apply` bundles it — a declared function with no file on disk fails at deploy:
492
538
 
493
539
  ```ts
@@ -0,0 +1,558 @@
1
+ /**
2
+ * The Neon env core — resolving a branch's env from the Neon API, and projecting it into
3
+ * OS-level `{ KEY: value }` pairs.
4
+ *
5
+ * Shared source, not a package: `scripts/sync-shared.mjs` copies it into `@neon/env` (which
6
+ * publishes it as `fetchEnv` / `toEntries`) and into the `neon` CLI (which needs the
7
+ * credential-reuse half in `reuse-secrets.ts`). See `shared/env-core/README.md` for why it is
8
+ * a copy rather than an import.
9
+ *
10
+ * The counterpart that reads `process.env` — `parseEnv` and its zod schemas — is not here. It
11
+ * has no consumer outside `@neon/env`, so it stays in that package and imports this.
12
+ */
13
+ import { createNeonApiFromOptions, deriveCredentialScopes, ErrorCode, PlatformError, resolveConfig, } from "@neon/config/v1";
14
+ /**
15
+ * Mapping between the {@link NeonEnv} property paths and the OS-level env-var keys used
16
+ * for cross-process transport (via `.env` files, `env run -- <cmd>`, or anything else
17
+ * that talks to `process.env`).
18
+ *
19
+ * Each top-level key here is a {@link NeonEnv} namespace; the inner record maps the
20
+ * camelCase property names exposed to TypeScript to the UPPER_SNAKE env-var names used
21
+ * by the OS. Keep this in sync with {@link postgresEnvSchema} / {@link authEnvSchema} /
22
+ * {@link dataApiEnvSchema}.
23
+ */
24
+ /**
25
+ * Neon's default branch owner role, created with every project. This is the role a
26
+ * `DATABASE_URL` should connect as.
27
+ */
28
+ const NEON_DEFAULT_OWNER_ROLE = "neondb_owner";
29
+ /**
30
+ * Neon's default database, created with every project. When a branch has several databases
31
+ * and none was requested, this is preferred for the `DATABASE_URL` so the common case (a
32
+ * user added a second database next to `neondb`) auto-picks without asking.
33
+ */
34
+ const NEON_DEFAULT_DATABASE = "neondb";
35
+ /**
36
+ * Roles Neon provisions for the Auth / Data API (PostgREST) stack. They exist to back
37
+ * RLS-scoped Data API requests authenticated by JWT — never to hold a `DATABASE_URL` —
38
+ * so they're skipped when auto-picking the connection role. Enabling Neon Auth or the
39
+ * Data API (`neon config apply`) adds these next to the owner role, which is why a plain
40
+ * branch routinely reports more than one role.
41
+ */
42
+ const NEON_MANAGED_AUTH_ROLES = new Set([
43
+ "authenticator",
44
+ "anonymous",
45
+ "authenticated",
46
+ ]);
47
+ export const NEON_ENV_VAR_KEYS = {
48
+ /**
49
+ * Branch identity. `NEON_BRANCH` carries the branch **name** and is injected into the
50
+ * Neon Functions runtime on every branch (including the default) by default. `env pull` /
51
+ * `neon dev` / `neon-env run` emit it too so local dev mirrors the deployed runtime.
52
+ */
53
+ branch: {
54
+ name: "NEON_BRANCH",
55
+ },
56
+ postgres: {
57
+ databaseUrl: "DATABASE_URL",
58
+ databaseUrlUnpooled: "DATABASE_URL_UNPOOLED",
59
+ },
60
+ auth: {
61
+ baseUrl: "NEON_AUTH_BASE_URL",
62
+ jwksUrl: "NEON_AUTH_JWKS_URL",
63
+ },
64
+ dataApi: {
65
+ url: "NEON_DATA_API_URL",
66
+ },
67
+ /**
68
+ * Object storage (Preview). The S3 SDKs read `AWS_*` from their standard config chain, so
69
+ * a branch credential + `neon dev` / `env pull` makes object storage work from env alone.
70
+ * `region` is injected under the SDK-standard `AWS_REGION`.
71
+ */
72
+ storage: {
73
+ accessKeyId: "AWS_ACCESS_KEY_ID",
74
+ secretAccessKey: "AWS_SECRET_ACCESS_KEY",
75
+ endpoint: "AWS_ENDPOINT_URL_S3",
76
+ region: "AWS_REGION",
77
+ },
78
+ /**
79
+ * AI Gateway (Preview). Exposed under the Neon-branded env vars the deployed Functions
80
+ * runtime injects: `apiKey` is the minted credential's bearer (`NEON_AI_GATEWAY_TOKEN`)
81
+ * and `baseUrl` is the bare branch gateway host (`NEON_AI_GATEWAY_BASE_URL`,
82
+ * `scheme://host`, no path). Clients like `@neon/ai-sdk-provider` read these and append the
83
+ * dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves (https://github.com/vercel/ai/pull/15997).
84
+ */
85
+ aiGateway: {
86
+ apiKey: "NEON_AI_GATEWAY_TOKEN",
87
+ baseUrl: "NEON_AI_GATEWAY_BASE_URL",
88
+ },
89
+ };
90
+ export async function fetchEnv(config, options) {
91
+ return fetchEnvKeys(config, options, options.keys ?? null);
92
+ }
93
+ /**
94
+ * The {@link fetchEnv} body, with the key selection as a plain argument and no generic
95
+ * narrowing. Exists for callers that compute the selection at runtime — notably
96
+ * {@link fetchEnvReusingSecrets}, which decides which keys it still needs by checking the
97
+ * branch — since the public overload's `keys` is bound to a literal union those callers cannot
98
+ * produce without asserting.
99
+ *
100
+ * `keys === null` selects everything the policy enables.
101
+ */
102
+ export async function fetchEnvKeys(config, options, keys) {
103
+ const api = options.api ?? createApiFromOptions(options);
104
+ const projectId = options.projectId;
105
+ const { branch, desired } = await resolveBranchPolicy(config, options, api);
106
+ const selection = keys ? new Set(keys) : null;
107
+ const wants = (key) => selection === null || selection.has(key);
108
+ const result = {};
109
+ const [roles, databases] = await Promise.all([
110
+ api.listBranchRoles(projectId, branch.id),
111
+ api.listBranchDatabases(projectId, branch.id),
112
+ ]);
113
+ const roleName = pickRoleName(roles, branch, options.roleName);
114
+ const databaseName = pickDatabaseName(databases, branch, options.databaseName);
115
+ // Fan out: always fetch both Postgres URIs — the direct one also derives the AI Gateway
116
+ // host, so a selection that drops `DATABASE_URL_UNPOOLED` still needs it. Conditionally
117
+ // fetch auth + dataApi based on the branch policy and the selection. Auth key fields are
118
+ // only returned at integration creation time; for Better Auth they may legitimately be
119
+ // empty, so they can come back as empty strings.
120
+ const K = NEON_ENV_VAR_KEYS;
121
+ const wantsAuth = desired.authEnabled && (wants(K.auth.baseUrl) || wants(K.auth.jwksUrl));
122
+ const wantsDataApi = desired.dataApiEnabled && wants(K.dataApi.url);
123
+ const [pooled, unpooled, authSnapshot, dataApiSnapshot] = await Promise.all([
124
+ api.getConnectionUri(projectId, {
125
+ branchId: branch.id,
126
+ databaseName,
127
+ roleName,
128
+ pooled: true,
129
+ }),
130
+ api.getConnectionUri(projectId, {
131
+ branchId: branch.id,
132
+ databaseName,
133
+ roleName,
134
+ pooled: false,
135
+ }),
136
+ wantsAuth
137
+ ? api.getNeonAuth(projectId, branch.id)
138
+ : Promise.resolve(null),
139
+ wantsDataApi
140
+ ? api.getNeonDataApi(projectId, branch.id, databaseName)
141
+ : Promise.resolve(null),
142
+ ]);
143
+ const postgres = {};
144
+ if (wants(K.postgres.databaseUrl))
145
+ postgres.databaseUrl = pooled.uri;
146
+ if (wants(K.postgres.databaseUrlUnpooled)) {
147
+ postgres.databaseUrlUnpooled = unpooled.uri;
148
+ }
149
+ if (Object.keys(postgres).length > 0)
150
+ result.postgres = postgres;
151
+ // Branch identity, mirroring what the Functions runtime injects on every branch. Surfaced
152
+ // as `NEON_BRANCH` so local dev (`neon dev` / `neon-env run` / `env pull`) matches the
153
+ // deployed runtime. Uses the branch name.
154
+ if (wants(K.branch.name)) {
155
+ result.branch = { name: branch.name };
156
+ }
157
+ if (wantsAuth) {
158
+ if (!authSnapshot) {
159
+ throw new PlatformError(ErrorCode.NotFound, [
160
+ `fetchEnv: branch policy enables auth but no Neon Auth integration is enabled on branch ${branch.name} (${branch.id}).`,
161
+ "Enable it via `apply(config, { projectId, branchId })` (or `npx neon …`), in the Neon Console — then re-run fetchEnv. Or return auth.enabled=false.",
162
+ ].join(" "), {
163
+ details: { projectId, branchId: branch.id },
164
+ });
165
+ }
166
+ const auth = {};
167
+ if (wants(K.auth.baseUrl))
168
+ auth.baseUrl = authSnapshot.baseUrl ?? "";
169
+ if (wants(K.auth.jwksUrl))
170
+ auth.jwksUrl = authSnapshot.jwksUrl ?? "";
171
+ result.auth = auth;
172
+ }
173
+ if (wantsDataApi) {
174
+ if (!dataApiSnapshot) {
175
+ throw new PlatformError(ErrorCode.NotFound, [
176
+ `fetchEnv: branch policy enables dataApi but no Data API integration is enabled on branch ${branch.name} (${branch.id}) database ${databaseName}.`,
177
+ "Enable it via `apply(config, { projectId, branchId })` or in the Neon Console — then re-run fetchEnv. Or return dataApi.enabled=false.",
178
+ ].join(" "), {
179
+ details: {
180
+ projectId,
181
+ branchId: branch.id,
182
+ databaseName,
183
+ },
184
+ });
185
+ }
186
+ result.dataApi = { url: dataApiSnapshot.url };
187
+ }
188
+ // Object storage + AI Gateway (Preview). A single branch credential backs whichever of
189
+ // these the policy enables; functions never force one but ride along on its scopes. None
190
+ // of this runs when the policy enables neither, so the Postgres / Auth / Data API path
191
+ // never touches the credentials/storage endpoints (and keeps working on production, where
192
+ // they may not exist yet).
193
+ const storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;
194
+ const gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;
195
+ const wantsStorage = storageEnabled &&
196
+ (wants(K.storage.accessKeyId) ||
197
+ wants(K.storage.secretAccessKey) ||
198
+ wants(K.storage.endpoint) ||
199
+ wants(K.storage.region));
200
+ const wantsGateway = gatewayEnabled &&
201
+ (wants(K.aiGateway.apiKey) || wants(K.aiGateway.baseUrl));
202
+ // A credential is minted only for its *secrets*. The endpoint, region and gateway host
203
+ // are plain branch metadata, so selecting only those touches no credential at all — which
204
+ // is how a caller holding valid secrets refreshes the rest without issuing a new one.
205
+ const wantsCredential = (storageEnabled &&
206
+ (wants(K.storage.accessKeyId) ||
207
+ wants(K.storage.secretAccessKey))) ||
208
+ (gatewayEnabled && wants(K.aiGateway.apiKey));
209
+ if (wantsStorage || wantsGateway) {
210
+ // Read the branch's storage settings *before* minting: a policy that declares buckets
211
+ // on a branch without storage has to fail without having spent a credential on a
212
+ // resolve that cannot succeed.
213
+ let storage = null;
214
+ if (wantsStorage) {
215
+ storage = await api.getProjectBranchStorage(projectId, branch.id);
216
+ if (!storage) {
217
+ throw new PlatformError(ErrorCode.NotFound, [
218
+ `fetchEnv: branch policy declares object storage (preview.buckets) but storage is not enabled on branch ${branch.name} (${branch.id}).`,
219
+ "Enable it via `apply(config, { projectId, branchId })` (or in the Neon Console) — then re-run fetchEnv. Or remove preview.buckets.",
220
+ ].join(" "), { details: { projectId, branchId: branch.id } });
221
+ }
222
+ }
223
+ const secrets = wantsCredential
224
+ ? await mintBranchCredential({
225
+ api,
226
+ projectId,
227
+ branchId: branch.id,
228
+ branchName: branch.name,
229
+ scopes: previewCredentialScopes(desired.preview),
230
+ })
231
+ : null;
232
+ if (storage) {
233
+ const storageEnv = {};
234
+ if (secrets && wants(K.storage.accessKeyId)) {
235
+ storageEnv.accessKeyId = secrets.accessKeyId;
236
+ }
237
+ if (secrets && wants(K.storage.secretAccessKey)) {
238
+ storageEnv.secretAccessKey = secrets.secretAccessKey;
239
+ }
240
+ if (wants(K.storage.endpoint)) {
241
+ storageEnv.endpoint = storage.s3Endpoint;
242
+ }
243
+ if (wants(K.storage.region))
244
+ storageEnv.region = storage.region;
245
+ result.storage = storageEnv;
246
+ }
247
+ if (wantsGateway) {
248
+ const gateway = {};
249
+ if (secrets && wants(K.aiGateway.apiKey)) {
250
+ gateway.apiKey = secrets.apiToken;
251
+ }
252
+ if (wants(K.aiGateway.baseUrl)) {
253
+ // Bare branch-scoped gateway host derived from the branch's connection URI —
254
+ // not the control-plane API origin (which doesn't serve the gateway). Clients
255
+ // append the dialect route (/v1, /openai/v1, /anthropic/v1) themselves.
256
+ gateway.baseUrl = aiGatewayBaseUrl(branch.id, unpooled.uri);
257
+ }
258
+ result.aiGateway = gateway;
259
+ }
260
+ }
261
+ return result;
262
+ }
263
+ /**
264
+ * Resolve the target branch and evaluate the policy against it — the first thing any
265
+ * branch-scoped operation needs. Shared by {@link fetchEnv} and {@link fetchEnvReusingSecrets}
266
+ * so the two agree on which branch they're talking about and what it has enabled.
267
+ */
268
+ export async function resolveBranchPolicy(config, options, api) {
269
+ const projectId = options.projectId;
270
+ const branches = await api.listBranches(projectId);
271
+ if (branches.length === 0) {
272
+ throw new PlatformError(ErrorCode.BranchNotFound, [
273
+ `fetchEnv: project ${projectId} has no branches.`,
274
+ "Deploy your neon.ts policy (or create a branch) first, or pick a different project id.",
275
+ ].join(" "), { details: { projectId } });
276
+ }
277
+ const branchRef = options.branch ?? options.branchId;
278
+ if (!branchRef) {
279
+ throw new PlatformError(ErrorCode.BranchNotFound, [
280
+ "fetchEnv: no branch provided.",
281
+ "Pass `branch` with a branch name (e.g. `main`) or id (`br-…`).",
282
+ ].join(" "), { details: { projectId } });
283
+ }
284
+ const branch = resolveBranch(branchRef, branches);
285
+ const desired = resolveConfig(config, {
286
+ name: branch.name,
287
+ id: branch.id,
288
+ exists: true,
289
+ ...(branch.parentId ? { parentId: branch.parentId } : {}),
290
+ isDefault: branch.isDefault,
291
+ isProtected: branch.protected,
292
+ ...(branch.expiresAt ? { expiresAt: branch.expiresAt } : {}),
293
+ });
294
+ return { branch, desired };
295
+ }
296
+ /**
297
+ * Scopes the branch credential should carry for a resolved branch policy. Only object storage
298
+ * and the AI Gateway *require* a credential; functions never force one (they have no credential
299
+ * of their own), but `functions:invoke` is added to the scope set when a credential is already
300
+ * being minted for storage / the AI Gateway, so the one credential can invoke the branch's
301
+ * functions too. Returns `[]` only when nothing credential-bearing is enabled.
302
+ */
303
+ export function previewCredentialScopes(preview) {
304
+ if (!preview)
305
+ return [];
306
+ const storage = preview.buckets.length > 0;
307
+ const aiGateway = preview.aiGatewayEnabled;
308
+ if (!storage && !aiGateway)
309
+ return [];
310
+ return deriveCredentialScopes({
311
+ storage,
312
+ aiGateway,
313
+ functions: preview.functions.length > 0,
314
+ });
315
+ }
316
+ /** The `name` this tool stamps on every credential it mints, so it can recognize its own. */
317
+ export function credentialName(branchName) {
318
+ return `neon-env ${branchName}`;
319
+ }
320
+ /** The env-var keys a branch credential's secrets surface under, in emit order. */
321
+ export function credentialEnvKeys(flags) {
322
+ return [
323
+ ...(flags.storage
324
+ ? [
325
+ NEON_ENV_VAR_KEYS.storage.accessKeyId,
326
+ NEON_ENV_VAR_KEYS.storage.secretAccessKey,
327
+ ]
328
+ : []),
329
+ ...(flags.aiGateway ? [NEON_ENV_VAR_KEYS.aiGateway.apiKey] : []),
330
+ ];
331
+ }
332
+ /**
333
+ * Every OS-level env var a resolved branch policy produces, in emit order. Lets a caller
334
+ * subtract the ones it already holds and pass the rest as {@link fetchEnv}'s `keys`, without
335
+ * re-deriving which vars a policy implies.
336
+ */
337
+ export function policyEnvKeys(desired) {
338
+ const K = NEON_ENV_VAR_KEYS;
339
+ return [
340
+ K.postgres.databaseUrl,
341
+ K.postgres.databaseUrlUnpooled,
342
+ K.branch.name,
343
+ ...(desired.authEnabled ? [K.auth.baseUrl, K.auth.jwksUrl] : []),
344
+ ...(desired.dataApiEnabled ? [K.dataApi.url] : []),
345
+ ...((desired.preview?.buckets.length ?? 0) > 0
346
+ ? [
347
+ K.storage.accessKeyId,
348
+ K.storage.secretAccessKey,
349
+ K.storage.endpoint,
350
+ K.storage.region,
351
+ ]
352
+ : []),
353
+ ...(desired.preview?.aiGatewayEnabled
354
+ ? [K.aiGateway.apiKey, K.aiGateway.baseUrl]
355
+ : []),
356
+ ];
357
+ }
358
+ /**
359
+ * Mint the branch credential backing object storage / the AI Gateway.
360
+ *
361
+ * `api_token` and `s3_secret_access_key` come back **exactly once** — they are not stored
362
+ * server-side and the list endpoint returns metadata only — so the caller's copy is the only
363
+ * copy. That is why {@link fetchEnv} mints rather than fetches: there is nothing to fetch. A
364
+ * caller that already holds a valid copy should leave the secret keys out of `keys` (see
365
+ * {@link fetchEnvReusingSecrets}) instead of minting one it will discard.
366
+ */
367
+ async function mintBranchCredential(args) {
368
+ const minted = await args.api.createCredential(args.projectId, args.branchId, {
369
+ scopes: args.scopes,
370
+ principalType: "user",
371
+ name: credentialName(args.branchName),
372
+ });
373
+ return {
374
+ // The storage gateway authenticates against the full token id (e.g.
375
+ // `nak_live_…`), not the short token id — using the short id yields
376
+ // `InvalidAccessKeyId` on every S3 request.
377
+ accessKeyId: minted.tokenId,
378
+ secretAccessKey: minted.s3SecretAccessKey,
379
+ apiToken: minted.apiToken,
380
+ };
381
+ }
382
+ /**
383
+ * The AI Gateway is a **branch-scoped host** — `<branchId>-api.ai.<host-suffix>` — NOT the
384
+ * control-plane API origin. Derive the suffix from the branch's own Postgres connection host
385
+ * by dropping only the endpoint label (the first segment) and keeping everything after it,
386
+ * including any infra cell prefix (`c-N.`): a connection host of
387
+ * `ep-x.c-3.us-east-2.aws.neon.tech` yields the gateway host
388
+ * `<branchId>-api.ai.c-3.us-east-2.aws.neon.tech`. The cell prefix is **load-bearing** —
389
+ * the gateway is cell-routed, so dropping `c-N.` resolves to the wrong (or no) host.
390
+ */
391
+ function aiGatewayHost(branchId, connectionUri) {
392
+ let connectionHost = "";
393
+ try {
394
+ connectionHost = new URL(connectionUri).hostname;
395
+ }
396
+ catch {
397
+ connectionHost = "";
398
+ }
399
+ // Drop the endpoint label (first segment, e.g. `ep-x` / `ep-x-pooler`), keeping the rest
400
+ // of the host verbatim — including any infra cell prefix (`c-N.`) the gateway routes on:
401
+ // `[c-N.]<region>.<cloud>.neon.<tld>`.
402
+ const suffix = connectionHost.split(".").slice(1).join(".");
403
+ return `${branchId}-api.ai.${suffix}`;
404
+ }
405
+ /** The AI Gateway's bare base URL (`NEON_AI_GATEWAY_BASE_URL`) on the branch gateway host. */
406
+ function aiGatewayBaseUrl(branchId, connectionUri) {
407
+ return `https://${aiGatewayHost(branchId, connectionUri)}`;
408
+ }
409
+ export function createApiFromOptions(options) {
410
+ return createNeonApiFromOptions("fetchEnv", {
411
+ ...(options.apiKey ? { apiKey: options.apiKey } : {}),
412
+ ...(options.apiHost ? { apiHost: options.apiHost } : {}),
413
+ });
414
+ }
415
+ /**
416
+ * Resolve a branch ref — a name or an id — to a concrete branch. Matches by id first
417
+ * (exact `br-…`), then by name; both are unique within a project, so the lookup is
418
+ * unambiguous. This lets `.neon` files written by `neonctl` (which pin the branch *name*)
419
+ * and explicit `br-…` ids both work.
420
+ */
421
+ function resolveBranch(branch, branches) {
422
+ const match = branches.find((b) => b.id === branch) ??
423
+ branches.find((b) => b.name === branch);
424
+ if (match)
425
+ return match;
426
+ throw new PlatformError(ErrorCode.BranchNotFound, [
427
+ `fetchEnv: branch ${JSON.stringify(branch)} not found on project (matched by id or name).`,
428
+ `Existing branches: ${branches.map((b) => `${b.name} (${b.id})`).join(", ")}.`,
429
+ ].join(" "), {
430
+ details: {
431
+ branch,
432
+ available: branches.map((b) => `${b.name} (${b.id})`),
433
+ },
434
+ });
435
+ }
436
+ function pickRoleName(roles, branch, requested) {
437
+ if (requested) {
438
+ if (!roles.some((r) => r.name === requested)) {
439
+ throw new PlatformError(ErrorCode.BranchNotFound, [
440
+ `fetchEnv: role "${requested}" not found on branch ${branch.name} (${branch.id}).`,
441
+ `Existing roles: ${roles.map((r) => r.name).join(", ") || "(none)"}.`,
442
+ ].join(" "), {
443
+ details: {
444
+ branchId: branch.id,
445
+ roleName: requested,
446
+ availableRoles: roles.map((r) => r.name),
447
+ },
448
+ });
449
+ }
450
+ return requested;
451
+ }
452
+ if (roles.length === 0) {
453
+ throw new PlatformError(ErrorCode.BranchNotFound, [
454
+ `fetchEnv: branch ${branch.name} (${branch.id}) has no roles.`,
455
+ "Create one via the Neon console or pass `roleName` explicitly.",
456
+ ].join(" "), { details: { branchId: branch.id } });
457
+ }
458
+ if (roles.length === 1)
459
+ return roles[0].name;
460
+ // Multiple roles. Enabling Neon Auth / the Data API provisions the PostgREST roles
461
+ // (authenticator/anonymous/authenticated) alongside the project owner, so a normal
462
+ // branch ends up with >1 role even though only the owner backs a `DATABASE_URL`.
463
+ // Default to Neon's owner role; if the project was created with a custom owner name,
464
+ // fall back to the single role left after dropping the managed auth roles. Only a
465
+ // genuinely ambiguous set (more than one app role) still asks the caller to choose.
466
+ const owner = roles.find((r) => r.name === NEON_DEFAULT_OWNER_ROLE);
467
+ if (owner)
468
+ return owner.name;
469
+ const appRoles = roles.filter((r) => !NEON_MANAGED_AUTH_ROLES.has(r.name));
470
+ if (appRoles.length === 1)
471
+ return appRoles[0].name;
472
+ throw new PlatformError(ErrorCode.AmbiguousBranchAuth, [
473
+ `fetchEnv: branch ${branch.name} (${branch.id}) has ${roles.length} roles and none is "${NEON_DEFAULT_OWNER_ROLE}"; cannot auto-pick.`,
474
+ `Pass \`roleName\` explicitly. Available: ${roles.map((r) => r.name).join(", ")}.`,
475
+ ].join(" "), {
476
+ details: {
477
+ branchId: branch.id,
478
+ availableRoles: roles.map((r) => r.name),
479
+ },
480
+ });
481
+ }
482
+ function pickDatabaseName(databases, branch, requested) {
483
+ if (requested) {
484
+ if (!databases.some((d) => d.name === requested)) {
485
+ throw new PlatformError(ErrorCode.BranchNotFound, [
486
+ `fetchEnv: database "${requested}" not found on branch ${branch.name} (${branch.id}).`,
487
+ `Existing databases: ${databases.map((d) => d.name).join(", ") || "(none)"}.`,
488
+ ].join(" "), {
489
+ details: {
490
+ branchId: branch.id,
491
+ databaseName: requested,
492
+ availableDatabases: databases.map((d) => d.name),
493
+ },
494
+ });
495
+ }
496
+ return requested;
497
+ }
498
+ if (databases.length === 0) {
499
+ throw new PlatformError(ErrorCode.BranchNotFound, [
500
+ `fetchEnv: branch ${branch.name} (${branch.id}) has no databases.`,
501
+ "Create one via the Neon console or pass `databaseName` explicitly.",
502
+ ].join(" "), { details: { branchId: branch.id } });
503
+ }
504
+ // Prefer Neon's default `neondb`. On the common "added a second database" branch this
505
+ // auto-picks it, so a lone or `neondb`-including branch resolves without asking.
506
+ const neondb = databases.find((d) => d.name === NEON_DEFAULT_DATABASE);
507
+ if (neondb)
508
+ return neondb.name;
509
+ if (databases.length === 1)
510
+ return databases[0].name;
511
+ // Several databases and no `neondb` to fall back on. Auto-picking any of them would be
512
+ // perceived as random and is bad DX, so fail loudly and let the caller disambiguate.
513
+ throw new PlatformError(ErrorCode.AmbiguousBranchAuth, [
514
+ `fetchEnv: branch ${branch.name} (${branch.id}) has ${databases.length} databases and none is named "${NEON_DEFAULT_DATABASE}"; cannot auto-pick.`,
515
+ `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(", ")}.`,
516
+ ].join(" "), {
517
+ details: {
518
+ branchId: branch.id,
519
+ availableDatabases: databases.map((d) => d.name),
520
+ },
521
+ });
522
+ }
523
+ // ───────────────────────── env-var mapping helpers ─────────────────────────
524
+ /**
525
+ * Project a fully-resolved {@link NeonEnv} into the OS-level `{ KEY: value }` pairs used
526
+ * for cross-process transport. Named after the web-platform `.entries()` convention
527
+ * (`URLSearchParams` / `Headers` / `FormData`); returns a `Record` rather than an
528
+ * iterator of tuples since that's the shape env injection needs (wrap with
529
+ * `Object.entries(...)` if you want literal `[key, value]` pairs). Used by `neon-env run`
530
+ * to inject the vars into a subprocess's `process.env`.
531
+ *
532
+ * Walks the value at runtime so it works for any `NeonEnv<C>` regardless of which
533
+ * conditional namespaces are present.
534
+ */
535
+ export function toEntries(env) {
536
+ const out = {};
537
+ const put = (key, value) => {
538
+ if (value !== undefined)
539
+ out[key] = value;
540
+ };
541
+ const K = NEON_ENV_VAR_KEYS;
542
+ put(K.postgres.databaseUrl, env.postgres?.databaseUrl);
543
+ put(K.postgres.databaseUrlUnpooled, env.postgres?.databaseUrlUnpooled);
544
+ put(K.branch.name, env.branch?.name);
545
+ put(K.auth.baseUrl, env.auth?.baseUrl);
546
+ put(K.auth.jwksUrl, env.auth?.jwksUrl);
547
+ put(K.dataApi.url, env.dataApi?.url);
548
+ put(K.storage.accessKeyId, env.storage?.accessKeyId);
549
+ put(K.storage.secretAccessKey, env.storage?.secretAccessKey);
550
+ put(K.storage.endpoint, env.storage?.endpoint);
551
+ put(K.storage.region, env.storage?.region);
552
+ // Neon-branded gateway vars only: the bearer and the bare branch gateway host
553
+ // (scheme://host, no path) — the @neon/ai-sdk-provider appends the dialect route
554
+ // (/v1, /openai/v1, /anthropic/v1) itself (https://github.com/vercel/ai/pull/15997).
555
+ put(K.aiGateway.apiKey, env.aiGateway?.apiKey);
556
+ put(K.aiGateway.baseUrl, env.aiGateway?.baseUrl);
557
+ return out;
558
+ }