@neondatabase/env 0.14.1 → 1.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.
Files changed (47) hide show
  1. package/README.md +8 -26
  2. package/dist/_shared/auth_selection.d.ts +95 -0
  3. package/dist/_shared/auth_selection.d.ts.map +1 -0
  4. package/dist/_shared/auth_selection.js +10 -1
  5. package/dist/_shared/auth_selection.js.map +1 -1
  6. package/dist/_shared/credentials.d.ts +186 -0
  7. package/dist/_shared/credentials.d.ts.map +1 -0
  8. package/dist/_shared/credentials.js +60 -1
  9. package/dist/_shared/credentials.js.map +1 -1
  10. package/dist/{lib → _shared/env-core}/env.d.ts +7 -92
  11. package/dist/_shared/env-core/env.d.ts.map +1 -0
  12. package/dist/{lib → _shared/env-core}/env.js +14 -184
  13. package/dist/_shared/env-core/env.js.map +1 -0
  14. package/dist/{lib → _shared/env-core}/reuse-secrets.d.ts +23 -4
  15. package/dist/_shared/env-core/reuse-secrets.d.ts.map +1 -0
  16. package/dist/{lib → _shared/env-core}/reuse-secrets.js +10 -7
  17. package/dist/_shared/env-core/reuse-secrets.js.map +1 -0
  18. package/dist/_shared/paths.d.ts +116 -0
  19. package/dist/_shared/paths.d.ts.map +1 -0
  20. package/dist/_shared/paths.js +23 -1
  21. package/dist/_shared/paths.js.map +1 -1
  22. package/dist/_shared/profiles.d.ts +140 -2
  23. package/dist/_shared/profiles.d.ts.map +1 -1
  24. package/dist/_shared/profiles.js +106 -2
  25. package/dist/_shared/profiles.js.map +1 -1
  26. package/dist/_shared/secure_file.d.ts +25 -0
  27. package/dist/_shared/secure_file.d.ts.map +1 -0
  28. package/dist/_shared/secure_file.js +43 -0
  29. package/dist/_shared/secure_file.js.map +1 -0
  30. package/dist/config/dist/lib/types.d.ts +92 -33
  31. package/dist/config/dist/lib/types.d.ts.map +1 -1
  32. package/dist/config/dist/v1.d.ts +1 -1
  33. package/dist/index.d.ts +2 -1
  34. package/dist/index.js +2 -1
  35. package/dist/lib/cli/commands.js +1 -1
  36. package/dist/lib/cli/commands.js.map +1 -1
  37. package/dist/lib/parse-env.d.ts +95 -0
  38. package/dist/lib/parse-env.d.ts.map +1 -0
  39. package/dist/lib/parse-env.js +198 -0
  40. package/dist/lib/parse-env.js.map +1 -0
  41. package/package.json +4 -9
  42. package/dist/lib/env.d.ts.map +0 -1
  43. package/dist/lib/env.js.map +0 -1
  44. package/dist/lib/reuse-secrets.d.ts.map +0 -1
  45. package/dist/lib/reuse-secrets.js.map +0 -1
  46. package/dist/runtime.d.ts +0 -2
  47. package/dist/runtime.js +0 -2
@@ -1,9 +1,10 @@
1
- import { Config, CredentialScope, ResolvedPreviewConfig } from "../config/dist/lib/types.js";
2
- import { NeonApi, NeonBranchSnapshot } from "../config/dist/lib/neon-api.js";
3
- import { resolveConfig } from "../config/dist/lib/define-config.js";
4
- import "../config/dist/v1.js";
1
+ import { Config, CredentialScope, ResolvedPreviewConfig } from "../../config/dist/lib/types.js";
2
+ import { NeonApi, NeonBranchSnapshot } from "../../config/dist/lib/neon-api.js";
3
+ import { resolveConfig } from "../../config/dist/lib/define-config.js";
4
+ import "../../config/dist/v1.js";
5
+
6
+ //#region src/_shared/env-core/env.d.ts
5
7
 
6
- //#region src/lib/env.d.ts
7
8
  declare const NEON_ENV_VAR_KEYS: {
8
9
  /**
9
10
  * Branch identity. `NEON_BRANCH` carries the branch **name** and is injected into the
@@ -197,40 +198,6 @@ type NeonEnv<C extends Config = Config> = {
197
198
  } : NoNamespace) & (AiGatewayOn<C> extends true ? {
198
199
  aiGateway: NeonAiGatewayEnv;
199
200
  } : NoNamespace);
200
- /** The static `preview.functions` record of a config, or an empty record when absent. */
201
- type PreviewFunctionsOf<C extends Config> = NonNullable<C["preview"]> extends {
202
- functions: infer F;
203
- } ? F : Record<never, never>;
204
- /** The declared function slugs of a config (record keys), as a string union. */
205
- type FunctionSlugOf<C extends Config> = Extract<keyof PreviewFunctionsOf<C>, string>;
206
- /**
207
- * Human-readable hint surfaced as the **expected type** of `parseEnv`'s `scope` argument when
208
- * the policy declares no functions at all. Without it the argument's expected type is the bare
209
- * `never` {@link FunctionSlugOf} yields, and TypeScript reports the opaque `Type '"x"' is not
210
- * assignable to type 'never'`; the literal turns that into a sentence naming the fix (and the
211
- * editor offers it as the single completion, so the empty completion list is explained rather
212
- * than just empty). Mirrors `NeonAuthRequiredHint` in `@neon/config`.
213
- */
214
- 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";
215
- /**
216
- * The expected type of `parseEnv`'s function-slug `scope` argument: the caller's inferred slug
217
- * `S` normally, and the {@link NoFunctionScopeHint} message when the policy declares no
218
- * functions. Keeping `S` (rather than `FunctionSlugOf<C>`) in the enabled branch is what makes
219
- * the returned `function` namespace exact — it stays the one function's env keys instead of
220
- * widening to every declared function's.
221
- */
222
- type FunctionScopeField<C extends Config, S extends string> = [FunctionSlugOf<C>] extends [never] ? NoFunctionScopeHint : S;
223
- /** The declared env-var keys of one function `S`, as a string union. */
224
- type FunctionEnvKeysOf<C extends Config, S extends string> = S extends keyof PreviewFunctionsOf<C> ? NonNullable<PreviewFunctionsOf<C>[S]> extends {
225
- env: infer E;
226
- } ? Extract<keyof E, string> : never : never;
227
- /**
228
- * The extra `function` namespace added to `parseEnv`'s result when called with a function
229
- * slug scope: the declared env-var keys for that function, each resolved to a `string`.
230
- */
231
- type NeonFunctionEnv<C extends Config, S extends string> = {
232
- function: Record<FunctionEnvKeysOf<C, S>, string>;
233
- };
234
201
  /**
235
202
  * OS-level env-var keys grouped by the {@link NeonEnv} namespace they populate. Only the
236
203
  * **input** vars `parseEnv` validates are listed — the output-only aliases in
@@ -433,58 +400,6 @@ declare function credentialEnvKeys(flags: {
433
400
  */
434
401
  declare function policyEnvKeys(desired: ReturnType<typeof resolveConfig>): string[];
435
402
  declare function createApiFromOptions(options: FetchEnvOptions): NeonApi;
436
- /**
437
- * Synchronous, network-free counterpart to {@link fetchEnv}. Reads `process.env`, validates
438
- * the required Neon env vars with zod, and returns the same {@link NeonEnv} shape — so the
439
- * rest of your app touches `env.postgres.databaseUrl` instead of stringly-typed
440
- * `process.env.DATABASE_URL` lookups.
441
- *
442
- * Designed for the **"env-vars-already-injected"** path:
443
- * - You wrapped your dev command with `neon-env run -- <cmd>` or `neon dev`.
444
- * - Your platform (Vercel, Fly, Railway, …) injected the vars via its own integration.
445
- * - You are **inside a deployed Neon Function**, whose env was uploaded at `config apply`.
446
- *
447
- * Unlike the old API, `parseEnv` does **not** take a branch name: the secret set is now
448
- * static (top-level `config.auth` / `config.dataApi`), so it reads those directly without
449
- * evaluating the per-branch closure.
450
- *
451
- * The second argument is a **scope** or a **key filter**:
452
- * - omitted — *external* scope (app bootstrap, build scripts, your dev machine). Returns the
453
- * full `{ postgres, auth?, dataApi?, … }` the policy enables.
454
- * - a **function slug** (a key of `config.preview.functions`) — *function* scope: you are
455
- * running inside that function. Returns the same branch secrets **plus** a typed
456
- * `function` namespace with the function's declared env-var keys. The slug autocompletes
457
- * from the policy ({@link FunctionSlugOf}) and an undeclared one is a type error.
458
- * - an **array of OS-level env-var keys** (e.g. `["DATABASE_URL", "NEON_AUTH_BASE_URL"]`) —
459
- * *filtered* mode: only those vars are required and returned, as a narrowed namespaced
460
- * shape. The keys autocomplete from the policy ({@link SelectableEnvKey}), so you can only
461
- * pick vars the policy actually enables. Use this when a process needs just a subset (a
462
- * Next.js app that reads `DATABASE_URL` but not `DATABASE_URL_UNPOOLED`, say) and you don't
463
- * want `parseEnv` to throw over vars you never use.
464
- *
465
- * Throws `PlatformError(EnvNotInjected)` listing every missing/invalid var when the env
466
- * isn't fully populated, with a fix hint pointing back at `neon dev` / `neon-env run`.
467
- *
468
- * ```ts
469
- * import config from "../neon";
470
- * import { parseEnv } from "@neon/env";
471
- *
472
- * // External (app / build):
473
- * const env = parseEnv(config);
474
- * const db = drizzle(neon(env.postgres.databaseUrl), { schema });
475
- *
476
- * // Inside the "hello" function:
477
- * const env = parseEnv(config, "hello");
478
- * env.function.resendApiKey; // typed from hello's declared env keys
479
- *
480
- * // Filtered: only enforce + return the pooled URL.
481
- * const { postgres } = parseEnv(config, ["DATABASE_URL"]);
482
- * postgres.databaseUrl; // string — `databaseUrlUnpooled` is absent
483
- * ```
484
- */
485
- declare function parseEnv<const C extends Config>(config: C): NeonEnv<C>;
486
- declare function parseEnv<const C extends Config, const S extends FunctionSlugOf<C>>(config: C, scope: FunctionScopeField<C, S>): NeonEnv<C> & NeonFunctionEnv<C, S>;
487
- declare function parseEnv<const C extends Config, const K extends SelectableEnvKey<C>>(config: C, keys: readonly K[]): FilteredNeonEnv<K>;
488
403
  /**
489
404
  * Project a fully-resolved {@link NeonEnv} into the OS-level `{ KEY: value }` pairs used
490
405
  * for cross-process transport. Named after the web-platform `.entries()` convention
@@ -505,5 +420,5 @@ declare function toEntries(env: ResolvedNeonEnv): Record<string, string>;
505
420
  */
506
421
  type ResolvedNeonEnv = { [N in keyof NamespaceEnv]?: Partial<NamespaceEnv[N]> };
507
422
  //#endregion
508
- export { FetchEnvOptions, FilteredNeonEnv, FunctionSlugOf, NEON_ENV_VAR_KEYS, NeonAiGatewayEnv, NeonAuthEnv, NeonBranchEnv, NeonDataApiEnv, NeonEnv, NeonFunctionEnv, NeonPostgresEnv, NeonStorageEnv, NoFunctionScopeHint, ResolvedNeonEnv, SelectableEnvKey, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnv, fetchEnvKeys, parseEnv, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries };
423
+ export { FetchEnvOptions, FilteredNeonEnv, NEON_ENV_VAR_KEYS, NeonAiGatewayEnv, NeonAuthEnv, NeonBranchEnv, NeonDataApiEnv, NeonEnv, NeonPostgresEnv, NeonStorageEnv, ResolvedNeonEnv, SelectableEnvKey, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnv, fetchEnvKeys, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries };
509
424
  //# source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BAAgB,aAAa,GAAG,aAAa,UAC7C,sBACA,aAAa;UAIL,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAiCV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgDe,yBACL,wBACA,iBAAiB,YAEzB,YACC;;;;;;;;;;;;;;;;iBAgBO;IAEd,QAAQ,gBAAgB;iBACL,yBAAyB,gBACtC,YACC,kBACP,QAAQ,QAAQ;;;;;;;;;;iBAiBG,YAAA,SACb,iBACC,kDAEP,QAAQ;;;;;;iBAuMW,mBAAA,SACb,iBACC,KAAK,4DACT,UACH;UACM;WACC,kBAAkB;;;;;;;;;iBA8CZ,uBAAA,UACN,oCACP;;iBAaa,cAAA;;iBAKA,iBAAA;;;;;;;;;iBAoBA,aAAA,UACN,kBAAkB;iBA0FZ,oBAAA,UAA8B,kBAAkB;;;;;;;;;;;;iBA2KhD,SAAA,MAAe,kBAAkB;;;;;;;KA8BrC,eAAA,iBACC,gBAAgB,QAAQ,aAAa"}
@@ -1,6 +1,17 @@
1
1
  import { ErrorCode, PlatformError, createNeonApiFromOptions, deriveCredentialScopes, resolveConfig } from "@neon/config/v1";
2
- import { z } from "zod";
3
- //#region src/lib/env.ts
2
+ //#region src/_shared/env-core/env.ts
3
+ /**
4
+ * The Neon env core — resolving a branch's env from the Neon API, and projecting it into
5
+ * OS-level `{ KEY: value }` pairs.
6
+ *
7
+ * Shared source, not a package: `scripts/sync-shared.mjs` copies it into `@neon/env` (which
8
+ * publishes it as `fetchEnv` / `toEntries`) and into the `neon` CLI (which needs the
9
+ * credential-reuse half in `reuse-secrets.ts`). See `shared/env-core/README.md` for why it is
10
+ * a copy rather than an import.
11
+ *
12
+ * The counterpart that reads `process.env` — `parseEnv` and its zod schemas — is not here. It
13
+ * has no consumer outside `@neon/env`, so it stays in that package and imports this.
14
+ */
4
15
  /**
5
16
  * Mapping between the {@link NeonEnv} property paths and the OS-level env-var keys used
6
17
  * for cross-process transport (via `.env` files, `env run -- <cmd>`, or anything else
@@ -350,187 +361,6 @@ function pickDatabaseName(databases, branch, requested) {
350
361
  } });
351
362
  }
352
363
  /**
353
- * Per-namespace zod schemas. Each defines exactly the OS-level keys parsed from
354
- * `process.env` for its namespace. Keep in sync with {@link NEON_ENV_VAR_KEYS}.
355
- *
356
- * `z.string().url()` would be tighter than `min(1)` but Postgres URIs that include
357
- * URL-illegal characters in the password (rare but legal in Neon's connection-string
358
- * format) fail the WHATWG `URL` parse, so we settle for "non-empty string".
359
- */
360
- const postgresEnvSchema = z.object({
361
- DATABASE_URL: z.string({ message: "DATABASE_URL is missing" }).min(1, "DATABASE_URL must not be empty"),
362
- DATABASE_URL_UNPOOLED: z.string({ message: "DATABASE_URL_UNPOOLED is missing" }).min(1, "DATABASE_URL_UNPOOLED must not be empty")
363
- });
364
- const authEnvSchema = z.object({
365
- NEON_AUTH_BASE_URL: z.string({ message: "NEON_AUTH_BASE_URL is missing" }).min(1, "NEON_AUTH_BASE_URL must not be empty"),
366
- NEON_AUTH_JWKS_URL: z.string({ message: "NEON_AUTH_JWKS_URL is missing" }).min(1, "NEON_AUTH_JWKS_URL must not be empty")
367
- });
368
- const dataApiEnvSchema = z.object({ NEON_DATA_API_URL: z.string({ message: "NEON_DATA_API_URL is missing" }).min(1, "NEON_DATA_API_URL must not be empty") });
369
- const storageEnvSchema = z.object({
370
- AWS_ACCESS_KEY_ID: z.string({ message: "AWS_ACCESS_KEY_ID is missing" }).min(1, "AWS_ACCESS_KEY_ID must not be empty"),
371
- AWS_SECRET_ACCESS_KEY: z.string({ message: "AWS_SECRET_ACCESS_KEY is missing" }).min(1, "AWS_SECRET_ACCESS_KEY must not be empty"),
372
- AWS_ENDPOINT_URL_S3: z.string({ message: "AWS_ENDPOINT_URL_S3 is missing" }).min(1, "AWS_ENDPOINT_URL_S3 must not be empty"),
373
- AWS_REGION: z.string({ message: "AWS_REGION is missing" }).min(1, "AWS_REGION must not be empty")
374
- });
375
- const aiGatewayEnvSchema = z.object({
376
- NEON_AI_GATEWAY_TOKEN: z.string({ message: "NEON_AI_GATEWAY_TOKEN is missing" }).min(1, "NEON_AI_GATEWAY_TOKEN must not be empty"),
377
- NEON_AI_GATEWAY_BASE_URL: z.string({ message: "NEON_AI_GATEWAY_BASE_URL is missing" }).min(1, "NEON_AI_GATEWAY_BASE_URL must not be empty")
378
- });
379
- /** Whether a **static** policy declares object storage (`preview.buckets`). No network. */
380
- function configWantsStorage(config) {
381
- return Object.keys(config.preview?.buckets ?? {}).length > 0;
382
- }
383
- /** Whether a **static** policy enables the AI Gateway (`preview.aiGateway`). No network. */
384
- function configWantsAiGateway(config) {
385
- return isServiceEnabledInput(config.preview?.aiGateway);
386
- }
387
- /** Static-toggle helper mirroring `config`'s `isServiceEnabled` for the env reader. */
388
- function isServiceEnabledInput(toggle) {
389
- if (toggle === void 0) return false;
390
- if (typeof toggle === "boolean") return toggle;
391
- return toggle.enabled !== false;
392
- }
393
- function parseEnv(config, scopeOrKeys) {
394
- const source = process.env;
395
- if (Array.isArray(scopeOrKeys)) return parseFilteredEnv(source, scopeOrKeys);
396
- const scope = typeof scopeOrKeys === "string" ? scopeOrKeys : void 0;
397
- const issues = [];
398
- const result = {};
399
- const pg = postgresEnvSchema.safeParse({
400
- DATABASE_URL: source.DATABASE_URL,
401
- DATABASE_URL_UNPOOLED: source.DATABASE_URL_UNPOOLED
402
- });
403
- if (pg.success) result.postgres = {
404
- databaseUrl: pg.data.DATABASE_URL,
405
- databaseUrlUnpooled: pg.data.DATABASE_URL_UNPOOLED
406
- };
407
- else for (const issue of pg.error.issues) issues.push(issue.message);
408
- const branchName = source[NEON_ENV_VAR_KEYS.branch.name];
409
- if (branchName !== void 0 && branchName !== "") result.branch = { name: branchName };
410
- if (isServiceEnabledInput(config.auth)) {
411
- const auth = authEnvSchema.safeParse({
412
- NEON_AUTH_BASE_URL: source.NEON_AUTH_BASE_URL,
413
- NEON_AUTH_JWKS_URL: source.NEON_AUTH_JWKS_URL
414
- });
415
- if (auth.success) result.auth = {
416
- baseUrl: auth.data.NEON_AUTH_BASE_URL,
417
- jwksUrl: auth.data.NEON_AUTH_JWKS_URL
418
- };
419
- else for (const issue of auth.error.issues) issues.push(issue.message);
420
- }
421
- if (isServiceEnabledInput(config.dataApi)) {
422
- const dataApi = dataApiEnvSchema.safeParse({ NEON_DATA_API_URL: source.NEON_DATA_API_URL });
423
- if (dataApi.success) result.dataApi = { url: dataApi.data.NEON_DATA_API_URL };
424
- else for (const issue of dataApi.error.issues) issues.push(issue.message);
425
- }
426
- if (configWantsStorage(config)) {
427
- const storage = storageEnvSchema.safeParse({
428
- AWS_ACCESS_KEY_ID: source.AWS_ACCESS_KEY_ID,
429
- AWS_SECRET_ACCESS_KEY: source.AWS_SECRET_ACCESS_KEY,
430
- AWS_ENDPOINT_URL_S3: source.AWS_ENDPOINT_URL_S3,
431
- AWS_REGION: source.AWS_REGION
432
- });
433
- if (storage.success) result.storage = {
434
- accessKeyId: storage.data.AWS_ACCESS_KEY_ID,
435
- secretAccessKey: storage.data.AWS_SECRET_ACCESS_KEY,
436
- endpoint: storage.data.AWS_ENDPOINT_URL_S3,
437
- region: storage.data.AWS_REGION
438
- };
439
- else for (const issue of storage.error.issues) issues.push(issue.message);
440
- }
441
- if (configWantsAiGateway(config)) {
442
- const aiGateway = aiGatewayEnvSchema.safeParse({
443
- NEON_AI_GATEWAY_TOKEN: source.NEON_AI_GATEWAY_TOKEN,
444
- NEON_AI_GATEWAY_BASE_URL: source.NEON_AI_GATEWAY_BASE_URL
445
- });
446
- if (aiGateway.success) result.aiGateway = {
447
- apiKey: aiGateway.data.NEON_AI_GATEWAY_TOKEN,
448
- baseUrl: aiGateway.data.NEON_AI_GATEWAY_BASE_URL
449
- };
450
- else for (const issue of aiGateway.error.issues) issues.push(issue.message);
451
- }
452
- if (scope !== void 0) {
453
- const fn = config.preview?.functions?.[scope];
454
- if (!fn) throw new PlatformError(ErrorCode.EnvNotInjected, [`parseEnv: no function "${scope}" is declared in this policy's preview.functions.`, "Pass a declared function slug (or omit the scope to read external env)."].join("\n"), { details: { scope } });
455
- const envOut = {};
456
- for (const key of Object.keys(fn.env ?? {})) {
457
- const value = source[key];
458
- if (value === void 0) issues.push(`${key} is missing (function "${scope}")`);
459
- else envOut[key] = value;
460
- }
461
- result.function = envOut;
462
- }
463
- if (issues.length > 0) throw new PlatformError(ErrorCode.EnvNotInjected, [
464
- "parseEnv: the required Neon env variables are not present in process.env.",
465
- ...issues.map((i) => ` - ${i}`),
466
- "Inject them via one of:",
467
- " - `neon dev` / `neon-env run -- <your dev command>` (wraps the command with the vars injected)",
468
- " - your hosting platform's Neon integration (Vercel, Fly, Railway, …)",
469
- " - for the `function` namespace: deploy the function (`neon deploy` / `config apply`) so its env is uploaded.",
470
- "Or switch the call to `await fetchEnv(config, …)` if you're in a context that can do async I/O."
471
- ].join("\n"), { details: { missing: issues } });
472
- return result;
473
- }
474
- /**
475
- * Runtime reverse map for filtered `parseEnv`: OS-level env-var key → `[namespace, property]`
476
- * in the {@link NeonEnv} shape. The compile-time mirror is {@link EnvKeysByNamespace} /
477
- * {@link EnvKeyToProp}; keep all three in sync. Only input vars appear (no output-only
478
- * aliases).
479
- */
480
- const FILTERABLE_ENV_KEYS = {
481
- DATABASE_URL: ["postgres", "databaseUrl"],
482
- DATABASE_URL_UNPOOLED: ["postgres", "databaseUrlUnpooled"],
483
- NEON_BRANCH: ["branch", "name"],
484
- NEON_AUTH_BASE_URL: ["auth", "baseUrl"],
485
- NEON_AUTH_JWKS_URL: ["auth", "jwksUrl"],
486
- NEON_DATA_API_URL: ["dataApi", "url"],
487
- AWS_ACCESS_KEY_ID: ["storage", "accessKeyId"],
488
- AWS_SECRET_ACCESS_KEY: ["storage", "secretAccessKey"],
489
- AWS_ENDPOINT_URL_S3: ["storage", "endpoint"],
490
- AWS_REGION: ["storage", "region"],
491
- NEON_AI_GATEWAY_TOKEN: ["aiGateway", "apiKey"],
492
- NEON_AI_GATEWAY_BASE_URL: ["aiGateway", "baseUrl"]
493
- };
494
- /**
495
- * Filtered counterpart to the {@link parseEnv} body: validate and return only the explicitly
496
- * selected OS-level env-var keys, projected back into the narrowed namespaced shape. Unlike
497
- * the full reader it never consults the policy — the selection alone decides what's required —
498
- * so vars the caller didn't ask for (e.g. `DATABASE_URL_UNPOOLED`) can be absent without
499
- * throwing. Mirrors the same non-empty constraint and {@link PlatformError} aggregation.
500
- */
501
- function parseFilteredEnv(source, keys) {
502
- const issues = [];
503
- const result = {};
504
- for (const key of keys) {
505
- if (!Object.hasOwn(FILTERABLE_ENV_KEYS, key)) {
506
- issues.push(`${key} is not a selectable Neon env variable`);
507
- continue;
508
- }
509
- const value = source[key];
510
- if (value === void 0) {
511
- issues.push(`${key} is missing`);
512
- continue;
513
- }
514
- if (value === "") {
515
- issues.push(`${key} must not be empty`);
516
- continue;
517
- }
518
- const [namespace, property] = FILTERABLE_ENV_KEYS[key];
519
- const bucket = result[namespace] ?? {};
520
- bucket[property] = value;
521
- result[namespace] = bucket;
522
- }
523
- if (issues.length > 0) throw new PlatformError(ErrorCode.EnvNotInjected, [
524
- "parseEnv: the required Neon env variables are not present in process.env.",
525
- ...issues.map((i) => ` - ${i}`),
526
- "Inject them via one of:",
527
- " - `neon dev` / `neon-env run -- <your dev command>` (wraps the command with the vars injected)",
528
- " - your hosting platform's Neon integration (Vercel, Fly, Railway, …)",
529
- "Or switch the call to `await fetchEnv(config, …)` if you're in a context that can do async I/O."
530
- ].join("\n"), { details: { missing: issues } });
531
- return result;
532
- }
533
- /**
534
364
  * Project a fully-resolved {@link NeonEnv} into the OS-level `{ KEY: value }` pairs used
535
365
  * for cross-process transport. Named after the web-platform `.entries()` convention
536
366
  * (`URLSearchParams` / `Headers` / `FormData`); returns a `Record` rather than an
@@ -562,6 +392,6 @@ function toEntries(env) {
562
392
  return out;
563
393
  }
564
394
  //#endregion
565
- export { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnv, fetchEnvKeys, parseEnv, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries };
395
+ export { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnv, fetchEnvKeys, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries };
566
396
 
567
397
  //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","names":[],"sources":["../../../src/_shared/env-core/env.ts"],"sourcesContent":["/**\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 * Shared source, not a package: `scripts/sync-shared.mjs` copies it into `@neon/env` (which\n * publishes it as `fetchEnv` / `toEntries`) and into the `neon` CLI (which needs the\n * credential-reuse half in `reuse-secrets.ts`). See `shared/env-core/README.md` for why it is\n * a copy rather than an import.\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\nimport {\n\ttype Config,\n\ttype CredentialScope,\n\tcreateNeonApiFromOptions,\n\tderiveCredentialScopes,\n\tErrorCode,\n\ttype NeonApi,\n\ttype NeonBranchSnapshot,\n\ttype NeonBranchStorageSnapshot,\n\ttype NeonDatabaseSnapshot,\n\ttype NeonRoleSnapshot,\n\tPlatformError,\n\ttype ResolvedPreviewConfig,\n\tresolveConfig,\n} from \"@neon/config/v1\";\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/**\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/**\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: ReadonlySet<string> = new Set([\n\t\"authenticator\",\n\t\"anonymous\",\n\t\"authenticated\",\n]);\n\nexport const 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: {\n\t\tname: \"NEON_BRANCH\",\n\t},\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: {\n\t\turl: \"NEON_DATA_API_URL\",\n\t},\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} as const;\n\n/**\n * Branch identity for the resolved branch. Always present on a `fetchEnv` result (the branch\n * name is always known); on a `parseEnv` result it's present only when `NEON_BRANCH` was\n * injected into `process.env` (the Functions runtime injects it by default, as do `neon dev` /\n * `neon-env run` / `env pull`). `name` is the branch **name** (e.g. `main`, `preview/foo`).\n */\nexport interface NeonBranchEnv {\n\tname: string;\n}\n\n/** Per-namespace inner shapes. Exposed so consumers can name the parts independently. */\nexport interface NeonPostgresEnv {\n\t/**\n\t * Pooled connection string (via Neon's PgBouncer pooler). The right default for\n\t * serverless drivers (`@neondatabase/serverless`, edge runtimes, Postgres.js, …).\n\t */\n\tdatabaseUrl: string;\n\t/**\n\t * Direct (unpooled) connection string. Use this when you need session-level\n\t * features (`LISTEN`/`NOTIFY`, prepared statements across calls, transactions\n\t * spanning round-trips) that PgBouncer's transaction-mode pooling drops.\n\t */\n\tdatabaseUrlUnpooled: string;\n}\n\n/**\n * Bits of a Neon Auth integration for the resolved branch. Only present on `NeonEnv`\n * when the branch policy enables `auth`.\n *\n * Neon Auth exposes the `baseUrl` (which doubles as the publishable client identifier) and\n * the `jwksUrl` used to verify tokens it issues. `fetchEnv` reads both from the live\n * integration; `parseEnv` reads them from `process.env` (`NEON_AUTH_BASE_URL` /\n * `NEON_AUTH_JWKS_URL`).\n */\nexport interface NeonAuthEnv {\n\tbaseUrl: string;\n\t/** JWKS URL for verifying tokens issued by Neon Auth (`NEON_AUTH_JWKS_URL`). */\n\tjwksUrl: string;\n}\n\n/** Bits of a Neon Data API integration. Only present when the branch policy enables it. */\nexport interface NeonDataApiEnv {\n\turl: string;\n}\n\n/**\n * S3-compatible object-storage access for the branch (Preview). Present on `NeonEnv` only\n * when the policy declares `preview.buckets`. Combines a minted branch credential's access\n * keys (`accessKeyId` = the credential's full token id, e.g. `nak_live_…`, which is what the\n * storage gateway authenticates against; `secretAccessKey` = its\n * `s3_secret_access_key`) with the branch's non-secret connection details\n * (`endpoint`/`region`, from `GET .../storage`). Projects to the AWS SDK's\n * standard config env (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_ENDPOINT_URL_S3`,\n * `AWS_REGION`) so the S3 client works from env alone. Neon's storage gateway always\n * requires path-style addressing, so set `forcePathStyle: true` on your S3 client.\n */\nexport interface NeonStorageEnv {\n\taccessKeyId: string;\n\tsecretAccessKey: string;\n\t/** S3-compatible endpoint URL for the branch. */\n\tendpoint: string;\n\t/** AWS region string (e.g. `us-east-2`). Injected as `AWS_REGION`. */\n\tregion: string;\n}\n\n/**\n * AI Gateway access for the branch (Preview). Present on `NeonEnv` only when the policy\n * enables `preview.aiGateway`. `apiKey` is the minted credential's bearer (`api_token`);\n * `baseUrl` is the bare branch-scoped gateway host\n * (`https://<branchId>-api.ai.<region>.…`, no path). Projects to the Neon-branded env\n * (`NEON_AI_GATEWAY_TOKEN`, `NEON_AI_GATEWAY_BASE_URL`); clients like `@neon/ai-sdk-provider`\n * append the dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves.\n */\nexport interface NeonAiGatewayEnv {\n\tapiKey: string;\n\tbaseUrl: string;\n}\n\n/**\n * Empty record alias used as the \"false\" branch of the conditional namespace adds below.\n * `Record<never, never>` is the no-op for intersection — the cleaner alternative to `{}`,\n * which biome rejects (it means \"any non-null\", not \"empty object\").\n */\ntype NoNamespace = Record<never, never>;\n\n/**\n * Resolve a **static** service toggle (the value of `config.auth` / `config.dataApi`) to a\n * type-level boolean. The whole-thing wrapping (`[T] extends […]`) turns off distribution\n * so a union/`undefined` is checked as one unit:\n *\n * - `false` / `{ enabled: false }` / `undefined` → `false`\n * - `true` / `{ enabled: true }` / any other object (`{}`, `{ enabled?: boolean }`) → `true`\n * (a present toggle defaults to enabled)\n * - the bare `boolean | ServiceToggle | undefined` (the default `Config` param, no literal\n * info) → `false`, so an untyped policy yields just `{ postgres }`.\n */\ntype ServiceOn<T> = [T] extends [false]\n\t? false\n\t: [T] extends [{ enabled: false }]\n\t\t? false\n\t\t: [T] extends [undefined]\n\t\t\t? false\n\t\t\t: [T] extends [true]\n\t\t\t\t? true\n\t\t\t\t: [T] extends [{ enabled: true }]\n\t\t\t\t\t? true\n\t\t\t\t\t: [T] extends [object]\n\t\t\t\t\t\t? true\n\t\t\t\t\t\t: false;\n\n/** True when `T` has at least one known key; `false` for `{}` / `never`. */\ntype HasKeys<T> = [keyof T] extends [never] ? false : true;\n\n/**\n * Whether the policy's **static** `preview` block declares at least one object-storage bucket\n * (`preview.buckets`). Drives whether {@link NeonEnv} carries the `storage` namespace.\n *\n * The leading `[never]` guard is load-bearing: when a policy has no `preview` at all,\n * `NonNullable<C[\"preview\"]>` is `never`, and without the guard the `extends { … }` probe\n * below would vacuously match (everything extends `never`-derived shapes) and `HasKeys<never>`\n * would resolve `true`, wrongly adding the namespace. The guard short-circuits to `false`.\n */\ntype HasBuckets<C extends Config> = [NonNullable<C[\"preview\"]>] extends [never]\n\t? false\n\t: NonNullable<C[\"preview\"]> extends { buckets: infer B }\n\t\t? HasKeys<NonNullable<B>>\n\t\t: false;\n\n/**\n * Whether the policy's **static** `preview` block enables the AI Gateway\n * (`preview.aiGateway`). Drives whether {@link NeonEnv} carries the `aiGateway` namespace.\n *\n * The leading `[never]` guard is load-bearing for the same reason as {@link HasBuckets}: when\n * a policy has no `preview`, `NonNullable<C[\"preview\"]>` is `never`, and a naked `never` in the\n * `extends` below would *distribute* (collapsing the result — and the whole `NeonEnv`\n * intersection — to `never`). The tuple-wrapped guard short-circuits that to `false`.\n */\ntype AiGatewayOn<C extends Config> = [NonNullable<C[\"preview\"]>] extends [never]\n\t? false\n\t: NonNullable<C[\"preview\"]> extends { aiGateway: infer A }\n\t\t? ServiceOn<NonNullable<A>>\n\t\t: false;\n\n/**\n * Static, namespaced shape of `fetchEnv` / `parseEnv`'s return value. Generic over the\n * {@link Config} so the type system knows which optional namespaces are present.\n *\n * Because the secret-bearing toggles now live in the **static** top-level `config.auth` /\n * `config.dataApi` (not inside a per-branch closure), the namespace presence is a direct\n * read of those fields — no union-across-branches, no default-config escape hatch:\n *\n * - `postgres` is always present.\n * - `auth` is added iff `config.auth` is statically enabled.\n * - `dataApi` is added iff `config.dataApi` is statically enabled.\n * - `storage` is added iff `config.preview.buckets` declares at least one bucket.\n * - `aiGateway` is added iff `config.preview.aiGateway` is statically enabled.\n */\nexport type NeonEnv<C extends Config = Config> = {\n\tpostgres: NeonPostgresEnv;\n\t/**\n\t * Branch identity (`NEON_BRANCH`). Optional because `parseEnv` only surfaces it when the\n\t * var was injected; `fetchEnv` always populates it.\n\t */\n\tbranch?: NeonBranchEnv;\n} & (ServiceOn<NonNullable<C[\"auth\"]>> extends true\n\t? { auth: NeonAuthEnv }\n\t: NoNamespace) &\n\t(ServiceOn<NonNullable<C[\"dataApi\"]>> extends true\n\t\t? { dataApi: NeonDataApiEnv }\n\t\t: NoNamespace) &\n\t(HasBuckets<C> extends true ? { storage: NeonStorageEnv } : NoNamespace) &\n\t(AiGatewayOn<C> extends true\n\t\t? { aiGateway: NeonAiGatewayEnv }\n\t\t: NoNamespace);\n\n// ───────────────────────── env-var key filtering ─────────────────────────\n\n/**\n * OS-level env-var keys grouped by the {@link NeonEnv} namespace they populate. Only the\n * **input** vars `parseEnv` validates are listed — the output-only aliases in\n * {@link NEON_ENV_VAR_KEYS} (`NEON_AI_GATEWAY_TOKEN`, …) are intentionally absent, so they\n * are not selectable in a `parseEnv(config, keys)` filter. Keep in sync with\n * {@link EnvKeyToProp}.\n */\ninterface EnvKeysByNamespace {\n\tpostgres: \"DATABASE_URL\" | \"DATABASE_URL_UNPOOLED\";\n\tbranch: \"NEON_BRANCH\";\n\tauth: \"NEON_AUTH_BASE_URL\" | \"NEON_AUTH_JWKS_URL\";\n\tdataApi: \"NEON_DATA_API_URL\";\n\tstorage:\n\t\t| \"AWS_ACCESS_KEY_ID\"\n\t\t| \"AWS_SECRET_ACCESS_KEY\"\n\t\t| \"AWS_ENDPOINT_URL_S3\"\n\t\t| \"AWS_REGION\";\n\taiGateway: \"NEON_AI_GATEWAY_TOKEN\" | \"NEON_AI_GATEWAY_BASE_URL\";\n}\n\n/** The {@link NeonEnv} namespace interface backing each namespace key. */\ninterface NamespaceEnv {\n\tpostgres: NeonPostgresEnv;\n\tbranch: NeonBranchEnv;\n\tauth: NeonAuthEnv;\n\tdataApi: NeonDataApiEnv;\n\tstorage: NeonStorageEnv;\n\taiGateway: NeonAiGatewayEnv;\n}\n\n/** OS-level env-var key → the camelCase property it sets on its namespace object. */\ninterface EnvKeyToProp {\n\tDATABASE_URL: \"databaseUrl\";\n\tDATABASE_URL_UNPOOLED: \"databaseUrlUnpooled\";\n\tNEON_BRANCH: \"name\";\n\tNEON_AUTH_BASE_URL: \"baseUrl\";\n\tNEON_AUTH_JWKS_URL: \"jwksUrl\";\n\tNEON_DATA_API_URL: \"url\";\n\tAWS_ACCESS_KEY_ID: \"accessKeyId\";\n\tAWS_SECRET_ACCESS_KEY: \"secretAccessKey\";\n\tAWS_ENDPOINT_URL_S3: \"endpoint\";\n\tAWS_REGION: \"region\";\n\tNEON_AI_GATEWAY_TOKEN: \"apiKey\";\n\tNEON_AI_GATEWAY_BASE_URL: \"baseUrl\";\n}\n\n/**\n * The OS-level env-var keys selectable for a given policy: the union of input vars across\n * exactly the namespaces {@link NeonEnv}<C> carries. Drives the typesafe autocomplete of the\n * `keys` filter — selecting a var from a namespace the policy does not enable is a type error\n * (e.g. `NEON_AUTH_BASE_URL` is only offered once the policy turns on `auth`).\n */\nexport type SelectableEnvKey<C extends Config> =\n\tEnvKeysByNamespace[keyof NeonEnv<C> & keyof EnvKeysByNamespace];\n\n/**\n * The result shape of a **filtered** `parseEnv(config, keys)` call: the namespaced\n * {@link NeonEnv} restricted to exactly the selected OS-level keys `K`. Namespaces with no\n * selected key are dropped, and within a kept namespace only the selected properties survive\n * — selecting just `[\"DATABASE_URL\"]` yields `{ postgres: { databaseUrl: string } }`, with no\n * `databaseUrlUnpooled`.\n *\n * The policy gating lives on the `parseEnv` overload (which binds `K` to\n * {@link SelectableEnvKey}); this type only needs the selection, so it takes a bare\n * `K extends string` and filters with `Extract`. The outer mapped type's `as` clause drops\n * any namespace whose intersection with the selection is empty (`[…] extends [never]`,\n * tuple-wrapped to switch off distribution); the inner one re-keys each selected OS var to its\n * camelCase property and looks the value type up on the canonical namespace interface, so it\n * stays correct if a field ever stops being a plain `string`.\n */\nexport type FilteredNeonEnv<K extends string> = {\n\t[N in keyof EnvKeysByNamespace as [\n\t\tExtract<K, EnvKeysByNamespace[N]>,\n\t] extends [never]\n\t\t? never\n\t\t: N]: {\n\t\t[P in Extract<K, EnvKeysByNamespace[N]> as EnvKeyToProp[P &\n\t\t\tkeyof EnvKeyToProp]]: NamespaceEnv[N][EnvKeyToProp[P &\n\t\t\tkeyof EnvKeyToProp] &\n\t\t\tkeyof NamespaceEnv[N]];\n\t};\n};\n\nexport interface FetchEnvOptions {\n\t/**\n\t * Neon project id. **Required** — the management API addresses branches through their\n\t * project. Resolve it in your CLI (e.g. neonctl) and pass it in.\n\t */\n\tprojectId: string;\n\t/**\n\t * Neon branch — its **name** (e.g. `main`) or its id (`br-…`). **Required** (or pass the\n\t * legacy {@link FetchEnvOptions.branchId}). Resolved against the project's branches by\n\t * id first, then by name, so either form works.\n\t */\n\tbranch?: string;\n\t/**\n\t * @deprecated Legacy id-only field. Prefer {@link FetchEnvOptions.branch}, which accepts\n\t * a branch name or id. Still honored for backward compatibility; ignored when `branch`\n\t * is set.\n\t */\n\tbranchId?: string;\n\t/**\n\t * Neon API key. Resolved via the standard chain (option → `NEON_API_KEY` →\n\t * `~/.config/neonctl/credentials.json`) when omitted. Ignored when a custom `api`\n\t * is supplied.\n\t */\n\tapiKey?: string;\n\t/**\n\t * Neon **management** API base URL (not the Auth base URL). Falls back to\n\t * `NEON_API_HOST`, then production. Ignored when a custom `api` is supplied.\n\t */\n\tapiHost?: string;\n\t/**\n\t * Inject a custom NeonApi adapter. Primarily used by tests; production callers can rely\n\t * on the default real adapter built from `apiKey`.\n\t */\n\tapi?: NeonApi;\n\t/**\n\t * Role name to fetch credentials for. When omitted, the connection role is auto-picked:\n\t * the only role on the branch, else Neon's default owner (`neondb_owner`), else the\n\t * single role left after dropping the managed Auth/Data API roles\n\t * (`authenticator`/`anonymous`/`authenticated`). Throws {@link PlatformError} with\n\t * `PLATFORM_AMBIGUOUS_BRANCH_AUTH` only when more than one app role remains.\n\t */\n\troleName?: string;\n\t/**\n\t * Database name. When omitted, it is auto-picked: Neon's default `neondb` if present,\n\t * else the only database on the branch. Throws {@link PlatformError} with\n\t * `PLATFORM_AMBIGUOUS_BRANCH_AUTH` when the branch has several databases and none is\n\t * `neondb` (pass `databaseName` to disambiguate), and `PLATFORM_BRANCH_NOT_FOUND` when\n\t * the branch has no databases or the requested `databaseName` does not exist.\n\t */\n\tdatabaseName?: string;\n}\n\n/**\n * Resolve the project + branch this process should target, then fetch live Neon\n * connection strings for that branch over the network. Async — calls the Neon API.\n *\n * Use this from build scripts and the `neon-env run` command, where top-level await is\n * fine. For application code that needs a synchronous bootstrap (most frameworks: Drizzle\n * config, Next.js, Vite, etc.), inject env vars via `neon-env run -- <cmd>` and use\n * {@link parseEnv} instead — same {@link NeonEnv} shape, but a sync call against\n * `process.env`.\n *\n * Filesystem- and env-agnostic: pass `projectId` and the target `branch` (name or id)\n * explicitly (resolve them in your CLI, e.g. neonctl).\n *\n * ```ts\n * import config from \"../neon\";\n * import { fetchEnv } from \"@neon/env\";\n *\n * const env = await fetchEnv(config, { projectId: \"patient-art-12345\", branch: \"main\" });\n * const db = drizzle(neon(env.postgres.databaseUrl), { schema });\n * ```\n *\n * Pass `keys` to fetch only some of them — see the overload below.\n *\n * The package does **not** read `process.env`, mutate it, or touch the filesystem. Everything\n * it returns comes from the Neon API, so a value the API cannot produce (a one-time secret\n * issued to a previous call) is minted afresh rather than recovered. Callers that hold\n * persisted secrets and want to keep them use {@link fetchEnvReusingSecrets}, which decides\n * what is still valid and narrows this call's `keys` accordingly.\n */\nexport async function fetchEnv<\n\tconst C extends Config,\n\tconst K extends SelectableEnvKey<C>,\n>(\n\tconfig: C,\n\toptions: FetchEnvOptions & {\n\t\t/**\n\t\t * Fetch only these OS-level env vars, instead of everything the policy enables. The\n\t\t * keys autocomplete from the policy ({@link SelectableEnvKey}), and the result is\n\t\t * narrowed to match ({@link FilteredNeonEnv}).\n\t\t *\n\t\t * The point is not just a smaller result: **work is skipped too.** Leave out\n\t\t * `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / `NEON_AI_GATEWAY_TOKEN` and no branch\n\t\t * credential is minted at all, so a caller that already holds valid secrets can refresh\n\t\t * everything else without issuing a new one. The non-secret vars of the same features\n\t\t * (`AWS_ENDPOINT_URL_S3`, `AWS_REGION`, `NEON_AI_GATEWAY_BASE_URL`) are not\n\t\t * credential-backed and stay available on their own.\n\t\t *\n\t\t * The selection **intersects** with the policy rather than overriding it: naming a var\n\t\t * the branch policy does not enable is not an error, it simply yields nothing.\n\t\t */\n\t\tkeys: readonly K[];\n\t},\n): Promise<FilteredNeonEnv<K>>;\nexport async function fetchEnv<const C extends Config>(\n\tconfig: C,\n\toptions: FetchEnvOptions,\n): Promise<NeonEnv<C>>;\nexport async function fetchEnv(\n\tconfig: Config,\n\toptions: FetchEnvOptions & { keys?: readonly string[] },\n): Promise<unknown> {\n\treturn fetchEnvKeys(config, options, options.keys ?? null);\n}\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 */\nexport async function fetchEnvKeys(\n\tconfig: Config,\n\toptions: FetchEnvOptions,\n\tkeys: readonly string[] | null,\n): Promise<ResolvedNeonEnv> {\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst projectId = options.projectId;\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\n\tconst selection = keys ? new Set<string>(keys) : null;\n\tconst wants = (key: string): boolean =>\n\t\tselection === null || selection.has(key);\n\n\tconst result: ResolvedNeonEnv = {};\n\tconst [roles, databases] = await Promise.all([\n\t\tapi.listBranchRoles(projectId, branch.id),\n\t\tapi.listBranchDatabases(projectId, branch.id),\n\t]);\n\n\tconst roleName = pickRoleName(roles, branch, options.roleName);\n\tconst databaseName = pickDatabaseName(\n\t\tdatabases,\n\t\tbranch,\n\t\toptions.databaseName,\n\t);\n\n\t// Fan out: always fetch both Postgres URIs — the direct one also derives the AI Gateway\n\t// host, so a selection that drops `DATABASE_URL_UNPOOLED` still needs it. Conditionally\n\t// fetch auth + dataApi based on the branch policy and the selection. Auth key fields are\n\t// only returned at integration creation time; for Better Auth they may legitimately be\n\t// empty, so they can come back as empty strings.\n\tconst K = NEON_ENV_VAR_KEYS;\n\tconst wantsAuth =\n\t\tdesired.authEnabled && (wants(K.auth.baseUrl) || wants(K.auth.jwksUrl));\n\tconst wantsDataApi = desired.dataApiEnabled && wants(K.dataApi.url);\n\n\tconst [pooled, unpooled, authSnapshot, dataApiSnapshot] = await Promise.all(\n\t\t[\n\t\t\tapi.getConnectionUri(projectId, {\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tdatabaseName,\n\t\t\t\troleName,\n\t\t\t\tpooled: true,\n\t\t\t}),\n\t\t\tapi.getConnectionUri(projectId, {\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tdatabaseName,\n\t\t\t\troleName,\n\t\t\t\tpooled: false,\n\t\t\t}),\n\t\t\twantsAuth\n\t\t\t\t? api.getNeonAuth(projectId, branch.id)\n\t\t\t\t: Promise.resolve(null),\n\t\t\twantsDataApi\n\t\t\t\t? api.getNeonDataApi(projectId, branch.id, databaseName)\n\t\t\t\t: Promise.resolve(null),\n\t\t],\n\t);\n\n\tconst postgres: Partial<NeonPostgresEnv> = {};\n\tif (wants(K.postgres.databaseUrl)) postgres.databaseUrl = pooled.uri;\n\tif (wants(K.postgres.databaseUrlUnpooled)) {\n\t\tpostgres.databaseUrlUnpooled = unpooled.uri;\n\t}\n\tif (Object.keys(postgres).length > 0) result.postgres = postgres;\n\n\t// Branch identity, mirroring what the Functions runtime injects on every branch. Surfaced\n\t// as `NEON_BRANCH` so local dev (`neon dev` / `neon-env run` / `env pull`) matches the\n\t// deployed runtime. Uses the branch name.\n\tif (wants(K.branch.name)) {\n\t\tresult.branch = { name: branch.name } satisfies NeonBranchEnv;\n\t}\n\n\tif (wantsAuth) {\n\t\tif (!authSnapshot) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.NotFound,\n\t\t\t\t[\n\t\t\t\t\t`fetchEnv: branch policy enables auth but no Neon Auth integration is enabled on branch ${branch.name} (${branch.id}).`,\n\t\t\t\t\t\"Enable it via `apply(config, { projectId, branchId })` (or `npx neon …`), in the Neon Console — then re-run fetchEnv. Or return auth.enabled=false.\",\n\t\t\t\t].join(\" \"),\n\t\t\t\t{\n\t\t\t\t\tdetails: { projectId, branchId: branch.id },\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tconst auth: Partial<NeonAuthEnv> = {};\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\n\tif (wantsDataApi) {\n\t\tif (!dataApiSnapshot) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.NotFound,\n\t\t\t\t[\n\t\t\t\t\t`fetchEnv: branch policy enables dataApi but no Data API integration is enabled on branch ${branch.name} (${branch.id}) database ${databaseName}.`,\n\t\t\t\t\t\"Enable it via `apply(config, { projectId, branchId })` or in the Neon Console — then re-run fetchEnv. Or return dataApi.enabled=false.\",\n\t\t\t\t].join(\" \"),\n\t\t\t\t{\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tprojectId,\n\t\t\t\t\t\tbranchId: branch.id,\n\t\t\t\t\t\tdatabaseName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tresult.dataApi = { url: dataApiSnapshot.url } satisfies NeonDataApiEnv;\n\t}\n\n\t// Object storage + AI Gateway (Preview). A single branch credential backs whichever of\n\t// these the policy enables; functions never force one but ride along on its scopes. None\n\t// of this runs when the policy enables neither, so the Postgres / Auth / Data API path\n\t// never touches the credentials/storage endpoints (and keeps working on production, where\n\t// they may not exist yet).\n\tconst storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;\n\tconst gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;\n\tconst wantsStorage =\n\t\tstorageEnabled &&\n\t\t(wants(K.storage.accessKeyId) ||\n\t\t\twants(K.storage.secretAccessKey) ||\n\t\t\twants(K.storage.endpoint) ||\n\t\t\twants(K.storage.region));\n\tconst wantsGateway =\n\t\tgatewayEnabled &&\n\t\t(wants(K.aiGateway.apiKey) || wants(K.aiGateway.baseUrl));\n\t// A credential is minted only for its *secrets*. The endpoint, region and gateway host\n\t// are plain branch metadata, so selecting only those touches no credential at all — which\n\t// is how a caller holding valid secrets refreshes the rest without issuing a new one.\n\tconst wantsCredential =\n\t\t(storageEnabled &&\n\t\t\t(wants(K.storage.accessKeyId) ||\n\t\t\t\twants(K.storage.secretAccessKey))) ||\n\t\t(gatewayEnabled && wants(K.aiGateway.apiKey));\n\n\tif (wantsStorage || wantsGateway) {\n\t\t// Read the branch's storage settings *before* minting: a policy that declares buckets\n\t\t// on a branch without storage has to fail without having spent a credential on a\n\t\t// resolve that cannot succeed.\n\t\tlet storage: NeonBranchStorageSnapshot | null = null;\n\t\tif (wantsStorage) {\n\t\t\tstorage = await api.getProjectBranchStorage(projectId, branch.id);\n\t\t\tif (!storage) {\n\t\t\t\tthrow new PlatformError(\n\t\t\t\t\tErrorCode.NotFound,\n\t\t\t\t\t[\n\t\t\t\t\t\t`fetchEnv: branch policy declares object storage (preview.buckets) but storage is not enabled on branch ${branch.name} (${branch.id}).`,\n\t\t\t\t\t\t\"Enable it via `apply(config, { projectId, branchId })` (or in the Neon Console) — then re-run fetchEnv. Or remove preview.buckets.\",\n\t\t\t\t\t].join(\" \"),\n\t\t\t\t\t{ details: { projectId, branchId: branch.id } },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst secrets = wantsCredential\n\t\t\t? await mintBranchCredential({\n\t\t\t\t\tapi,\n\t\t\t\t\tprojectId,\n\t\t\t\t\tbranchId: branch.id,\n\t\t\t\t\tbranchName: branch.name,\n\t\t\t\t\tscopes: previewCredentialScopes(desired.preview),\n\t\t\t\t})\n\t\t\t: null;\n\n\t\tif (storage) {\n\t\t\tconst storageEnv: Partial<NeonStorageEnv> = {};\n\t\t\tif (secrets && wants(K.storage.accessKeyId)) {\n\t\t\t\tstorageEnv.accessKeyId = secrets.accessKeyId;\n\t\t\t}\n\t\t\tif (secrets && wants(K.storage.secretAccessKey)) {\n\t\t\t\tstorageEnv.secretAccessKey = secrets.secretAccessKey;\n\t\t\t}\n\t\t\tif (wants(K.storage.endpoint)) {\n\t\t\t\tstorageEnv.endpoint = storage.s3Endpoint;\n\t\t\t}\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: Partial<NeonAiGatewayEnv> = {};\n\t\t\tif (secrets && wants(K.aiGateway.apiKey)) {\n\t\t\t\tgateway.apiKey = secrets.apiToken;\n\t\t\t}\n\t\t\tif (wants(K.aiGateway.baseUrl)) {\n\t\t\t\t// Bare branch-scoped gateway host derived from the branch's connection URI —\n\t\t\t\t// not the control-plane API origin (which doesn't serve the gateway). Clients\n\t\t\t\t// append the dialect route (/v1, /openai/v1, /anthropic/v1) themselves.\n\t\t\t\tgateway.baseUrl = aiGatewayBaseUrl(branch.id, unpooled.uri);\n\t\t\t}\n\t\t\tresult.aiGateway = gateway;\n\t\t}\n\t}\n\n\treturn result;\n}\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 */\nexport async function resolveBranchPolicy(\n\tconfig: Config,\n\toptions: Pick<FetchEnvOptions, \"projectId\" | \"branch\" | \"branchId\">,\n\tapi: NeonApi,\n): Promise<{\n\tbranch: NeonBranchSnapshot;\n\tdesired: ReturnType<typeof resolveConfig>;\n}> {\n\tconst projectId = options.projectId;\n\tconst branches = await api.listBranches(projectId);\n\tif (branches.length === 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.BranchNotFound,\n\t\t\t[\n\t\t\t\t`fetchEnv: project ${projectId} has no branches.`,\n\t\t\t\t\"Deploy your neon.ts policy (or create a branch) first, or pick a different project id.\",\n\t\t\t].join(\" \"),\n\t\t\t{ details: { projectId } },\n\t\t);\n\t}\n\n\tconst branchRef = options.branch ?? options.branchId;\n\tif (!branchRef) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.BranchNotFound,\n\t\t\t[\n\t\t\t\t\"fetchEnv: no branch provided.\",\n\t\t\t\t\"Pass `branch` with a branch name (e.g. `main`) or id (`br-…`).\",\n\t\t\t].join(\" \"),\n\t\t\t{ details: { projectId } },\n\t\t);\n\t}\n\tconst branch = resolveBranch(branchRef, branches);\n\tconst desired = resolveConfig(config, {\n\t\tname: branch.name,\n\t\tid: branch.id,\n\t\texists: true,\n\t\t...(branch.parentId ? { parentId: branch.parentId } : {}),\n\t\tisDefault: branch.isDefault,\n\t\tisProtected: branch.protected,\n\t\t...(branch.expiresAt ? { expiresAt: branch.expiresAt } : {}),\n\t});\n\treturn { branch, desired };\n}\n\n/**\n * Scopes the branch credential should carry for a resolved branch policy. Only object storage\n * and the AI Gateway *require* a credential; functions never force one (they have no credential\n * of their own), but `functions:invoke` is added to the scope set when a credential is already\n * being minted for storage / the AI Gateway, so the one credential can invoke the branch's\n * functions too. Returns `[]` only when nothing credential-bearing is enabled.\n */\nexport function previewCredentialScopes(\n\tpreview: ResolvedPreviewConfig | undefined,\n): CredentialScope[] {\n\tif (!preview) return [];\n\tconst storage = preview.buckets.length > 0;\n\tconst aiGateway = preview.aiGatewayEnabled;\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\n/** The `name` this tool stamps on every credential it mints, so it can recognize its own. */\nexport function credentialName(branchName: string): string {\n\treturn `neon-env ${branchName}`;\n}\n\n/** The env-var keys a branch credential's secrets surface under, in emit order. */\nexport function credentialEnvKeys(flags: {\n\tstorage: boolean;\n\taiGateway: boolean;\n}): string[] {\n\treturn [\n\t\t...(flags.storage\n\t\t\t? [\n\t\t\t\t\tNEON_ENV_VAR_KEYS.storage.accessKeyId,\n\t\t\t\t\tNEON_ENV_VAR_KEYS.storage.secretAccessKey,\n\t\t\t\t]\n\t\t\t: []),\n\t\t...(flags.aiGateway ? [NEON_ENV_VAR_KEYS.aiGateway.apiKey] : []),\n\t];\n}\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 */\nexport function policyEnvKeys(\n\tdesired: ReturnType<typeof resolveConfig>,\n): string[] {\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\t? [\n\t\t\t\t\tK.storage.accessKeyId,\n\t\t\t\t\tK.storage.secretAccessKey,\n\t\t\t\t\tK.storage.endpoint,\n\t\t\t\t\tK.storage.region,\n\t\t\t\t]\n\t\t\t: []),\n\t\t...(desired.preview?.aiGatewayEnabled\n\t\t\t? [K.aiGateway.apiKey, K.aiGateway.baseUrl]\n\t\t\t: []),\n\t];\n}\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\tapi: NeonApi;\n\tprojectId: string;\n\tbranchId: string;\n\tbranchName: string;\n\tscopes: CredentialScope[];\n}): Promise<{\n\taccessKeyId: string;\n\tsecretAccessKey: string;\n\tapiToken: string;\n}> {\n\tconst minted = await args.api.createCredential(\n\t\targs.projectId,\n\t\targs.branchId,\n\t\t{\n\t\t\tscopes: args.scopes,\n\t\t\tprincipalType: \"user\",\n\t\t\tname: credentialName(args.branchName),\n\t\t},\n\t);\n\treturn {\n\t\t// The storage gateway authenticates against the full token id (e.g.\n\t\t// `nak_live_…`), not the short token id — using the short id yields\n\t\t// `InvalidAccessKeyId` on every S3 request.\n\t\taccessKeyId: minted.tokenId,\n\t\tsecretAccessKey: minted.s3SecretAccessKey,\n\t\tapiToken: minted.apiToken,\n\t};\n}\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: string, connectionUri: string): string {\n\tlet connectionHost = \"\";\n\ttry {\n\t\tconnectionHost = new URL(connectionUri).hostname;\n\t} catch {\n\t\tconnectionHost = \"\";\n\t}\n\t// Drop the endpoint label (first segment, e.g. `ep-x` / `ep-x-pooler`), keeping the rest\n\t// of the host verbatim — including any infra cell prefix (`c-N.`) the gateway routes on:\n\t// `[c-N.]<region>.<cloud>.neon.<tld>`.\n\tconst suffix = connectionHost.split(\".\").slice(1).join(\".\");\n\treturn `${branchId}-api.ai.${suffix}`;\n}\n\n/** The AI Gateway's bare base URL (`NEON_AI_GATEWAY_BASE_URL`) on the branch gateway host. */\nfunction aiGatewayBaseUrl(branchId: string, connectionUri: string): string {\n\treturn `https://${aiGatewayHost(branchId, connectionUri)}`;\n}\n\nexport function createApiFromOptions(options: FetchEnvOptions): NeonApi {\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/**\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(\n\tbranch: string,\n\tbranches: NeonBranchSnapshot[],\n): NeonBranchSnapshot {\n\tconst match =\n\t\tbranches.find((b) => b.id === branch) ??\n\t\tbranches.find((b) => b.name === branch);\n\tif (match) return match;\n\tthrow new PlatformError(\n\t\tErrorCode.BranchNotFound,\n\t\t[\n\t\t\t`fetchEnv: branch ${JSON.stringify(branch)} not found on project (matched by id or name).`,\n\t\t\t`Existing branches: ${branches.map((b) => `${b.name} (${b.id})`).join(\", \")}.`,\n\t\t].join(\" \"),\n\t\t{\n\t\t\tdetails: {\n\t\t\t\tbranch,\n\t\t\t\tavailable: branches.map((b) => `${b.name} (${b.id})`),\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction pickRoleName(\n\troles: NeonRoleSnapshot[],\n\tbranch: NeonBranchSnapshot,\n\trequested: string | undefined,\n): string {\n\tif (requested) {\n\t\tif (!roles.some((r) => r.name === requested)) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.BranchNotFound,\n\t\t\t\t[\n\t\t\t\t\t`fetchEnv: role \"${requested}\" not found on branch ${branch.name} (${branch.id}).`,\n\t\t\t\t\t`Existing roles: ${roles.map((r) => r.name).join(\", \") || \"(none)\"}.`,\n\t\t\t\t].join(\" \"),\n\t\t\t\t{\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tbranchId: branch.id,\n\t\t\t\t\t\troleName: requested,\n\t\t\t\t\t\tavailableRoles: roles.map((r) => r.name),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\treturn requested;\n\t}\n\tif (roles.length === 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.BranchNotFound,\n\t\t\t[\n\t\t\t\t`fetchEnv: branch ${branch.name} (${branch.id}) has no roles.`,\n\t\t\t\t\"Create one via the Neon console or pass `roleName` explicitly.\",\n\t\t\t].join(\" \"),\n\t\t\t{ details: { branchId: branch.id } },\n\t\t);\n\t}\n\tif (roles.length === 1) return roles[0].name;\n\n\t// Multiple roles. Enabling Neon Auth / the Data API provisions the PostgREST roles\n\t// (authenticator/anonymous/authenticated) alongside the project owner, so a normal\n\t// branch ends up with >1 role even though only the owner backs a `DATABASE_URL`.\n\t// Default to Neon's owner role; if the project was created with a custom owner name,\n\t// fall back to the single role left after dropping the managed auth roles. Only a\n\t// genuinely ambiguous set (more than one app role) still asks the caller to choose.\n\tconst owner = roles.find((r) => r.name === NEON_DEFAULT_OWNER_ROLE);\n\tif (owner) return owner.name;\n\n\tconst appRoles = roles.filter((r) => !NEON_MANAGED_AUTH_ROLES.has(r.name));\n\tif (appRoles.length === 1) return appRoles[0].name;\n\n\tthrow new PlatformError(\n\t\tErrorCode.AmbiguousBranchAuth,\n\t\t[\n\t\t\t`fetchEnv: branch ${branch.name} (${branch.id}) has ${roles.length} roles and none is \"${NEON_DEFAULT_OWNER_ROLE}\"; cannot auto-pick.`,\n\t\t\t`Pass \\`roleName\\` explicitly. Available: ${roles.map((r) => r.name).join(\", \")}.`,\n\t\t].join(\" \"),\n\t\t{\n\t\t\tdetails: {\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tavailableRoles: roles.map((r) => r.name),\n\t\t\t},\n\t\t},\n\t);\n}\n\nfunction pickDatabaseName(\n\tdatabases: NeonDatabaseSnapshot[],\n\tbranch: NeonBranchSnapshot,\n\trequested: string | undefined,\n): string {\n\tif (requested) {\n\t\tif (!databases.some((d) => d.name === requested)) {\n\t\t\tthrow new PlatformError(\n\t\t\t\tErrorCode.BranchNotFound,\n\t\t\t\t[\n\t\t\t\t\t`fetchEnv: database \"${requested}\" not found on branch ${branch.name} (${branch.id}).`,\n\t\t\t\t\t`Existing databases: ${databases.map((d) => d.name).join(\", \") || \"(none)\"}.`,\n\t\t\t\t].join(\" \"),\n\t\t\t\t{\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tbranchId: branch.id,\n\t\t\t\t\t\tdatabaseName: requested,\n\t\t\t\t\t\tavailableDatabases: databases.map((d) => d.name),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\treturn requested;\n\t}\n\tif (databases.length === 0) {\n\t\tthrow new PlatformError(\n\t\t\tErrorCode.BranchNotFound,\n\t\t\t[\n\t\t\t\t`fetchEnv: branch ${branch.name} (${branch.id}) has no databases.`,\n\t\t\t\t\"Create one via the Neon console or pass `databaseName` explicitly.\",\n\t\t\t].join(\" \"),\n\t\t\t{ details: { branchId: branch.id } },\n\t\t);\n\t}\n\n\t// Prefer Neon's default `neondb`. On the common \"added a second database\" branch this\n\t// auto-picks it, so a lone or `neondb`-including branch resolves without asking.\n\tconst neondb = databases.find((d) => d.name === NEON_DEFAULT_DATABASE);\n\tif (neondb) return neondb.name;\n\n\tif (databases.length === 1) return databases[0].name;\n\n\t// Several databases and no `neondb` to fall back on. Auto-picking any of them would be\n\t// perceived as random and is bad DX, so fail loudly and let the caller disambiguate.\n\tthrow new PlatformError(\n\t\tErrorCode.AmbiguousBranchAuth,\n\t\t[\n\t\t\t`fetchEnv: branch ${branch.name} (${branch.id}) has ${databases.length} databases and none is named \"${NEON_DEFAULT_DATABASE}\"; cannot auto-pick.`,\n\t\t\t`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(\", \")}.`,\n\t\t].join(\" \"),\n\t\t{\n\t\t\tdetails: {\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tavailableDatabases: databases.map((d) => d.name),\n\t\t\t},\n\t\t},\n\t);\n}\n\n// ───────────────────────── env-var mapping helpers ─────────────────────────\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 */\nexport function toEntries(env: ResolvedNeonEnv): Record<string, string> {\n\tconst out: Record<string, string> = {};\n\tconst put = (key: string, value: string | undefined): void => {\n\t\tif (value !== undefined) 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\t// Neon-branded gateway vars only: the bearer and the bare branch gateway host\n\t// (scheme://host, no path) — the @neon/ai-sdk-provider appends the dialect route\n\t// (/v1, /openai/v1, /anthropic/v1) itself (https://github.com/vercel/ai/pull/15997).\n\tput(K.aiGateway.apiKey, env.aiGateway?.apiKey);\n\tput(K.aiGateway.baseUrl, env.aiGateway?.baseUrl);\n\treturn out;\n}\n\n/**\n * Any resolved env {@link toEntries} can project: a full {@link NeonEnv}, or the narrowed\n * result of a `keys`-filtered {@link fetchEnv} / {@link parseEnv} call. Every namespace and\n * property is optional so a filtered result — which legitimately carries only what was asked\n * for — projects to exactly the vars it holds instead of failing to type-check.\n */\nexport type ResolvedNeonEnv = {\n\t[N in keyof NamespaceEnv]?: Partial<NamespaceEnv[N]>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,0BAA0B;;;;;;AAOhC,MAAM,wBAAwB;;;;;;;;AAS9B,MAAM,0CAA+C,IAAI,IAAI;CAC5D;CACA;CACA;AACD,CAAC;AAED,MAAa,oBAAoB;;;;;;CAMhC,QAAQ,EACP,MAAM,cACP;CACA,UAAU;EACT,aAAa;EACb,qBAAqB;CACtB;CACA,MAAM;EACL,SAAS;EACT,SAAS;CACV;CACA,SAAS,EACR,KAAK,oBACN;;;;;;CAMA,SAAS;EAC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from "../config/dist/lib/types.js";
2
- import "../config/dist/v1.js";
1
+ import { Config } from "../../config/dist/lib/types.js";
2
+ import "../../config/dist/v1.js";
3
3
  import { FetchEnvOptions } from "./env.js";
4
4
 
5
- //#region src/lib/reuse-secrets.d.ts
5
+ //#region src/_shared/env-core/reuse-secrets.d.ts
6
6
  /**
7
7
  * What happened to the branch credential during a {@link fetchEnvReusingSecrets} call.
8
8
  */
@@ -23,6 +23,13 @@ interface CredentialOutcome {
23
23
  * secrets named *and* that this tool issued; empty otherwise.
24
24
  */
25
25
  revoked: string[];
26
+ /**
27
+ * `tokenId`s this call superseded but left live, because `revokeSuperseded` was `false`.
28
+ * The counterpart to {@link CredentialOutcome.revoked}: exactly the ids that would be
29
+ * there instead. Lets a caller name what it orphaned rather than saying that it might
30
+ * have orphaned something — always empty on the default path.
31
+ */
32
+ superseded: string[];
26
33
  }
27
34
  /** A resolved branch env, ready to write to a dotenv file or inject into a process. */
28
35
  interface ReusedBranchEnv {
@@ -54,7 +61,7 @@ interface ReusedBranchEnv {
54
61
  * the record of what the last call issued.
55
62
  *
56
63
  * ```ts
57
- * import { fetchEnvReusingSecrets } from "@neon/env/runtime";
64
+ * import { fetchEnvReusingSecrets } from "../_shared/env-core/reuse-secrets.js";
58
65
  *
59
66
  * const { vars, credential } = await fetchEnvReusingSecrets(config, {
60
67
  * projectId,
@@ -70,6 +77,18 @@ declare function fetchEnvReusingSecrets<const C extends Config>(config: C, optio
70
77
  * `.env` file, typically. Defaults to `process.env`.
71
78
  */
72
79
  env?: NodeJS.ProcessEnv;
80
+ /**
81
+ * Revoke the credential a freshly-minted one supersedes. Defaults to `true`.
82
+ *
83
+ * Pass `false` when this resolve covers only *part* of what the branch has. Object
84
+ * storage and the AI Gateway share one credential, so a partial resolve cannot tell
85
+ * whether the credential its persisted secrets name also backs a service it is not
86
+ * resolving — and revoking it would kill that service while its vars, which this call
87
+ * is not rewriting, stay on disk and stop working. The cost is an orphaned credential,
88
+ * which is the safer of the two failures. `neon env pull --service` is the caller that
89
+ * needs this.
90
+ */
91
+ revokeSuperseded?: boolean;
73
92
  }): Promise<ReusedBranchEnv>;
74
93
  //#endregion
75
94
  export { CredentialOutcome, ReusedBranchEnv, fetchEnvReusingSecrets };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reuse-secrets.d.ts","names":[],"sources":["../../../src/_shared/env-core/reuse-secrets.ts"],"mappings":";;;;;;;;AAsBiB,UAAA,iBAAA,CAAiB;EA2BjB;AAAe;AAEzB;AAEM;AAAiB;EA2CR,MAAA,EAAA,OAAA;EAAsB;AAAiB;AACpD;AACC;EAKF,IAAA,EAAA,MAAO,EAAA;EAcJ;AAAR;AAAO;;;;;;;;;;;;UApEO,eAAA;;QAEV;;cAEM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA2CS,uCAAuC,gBACpD,YACC;;;;;QAKF,MAAA,CAAO;;;;;;;;;;;;;IAcZ,QAAQ"}
@@ -1,6 +1,6 @@
1
1
  import { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnvKeys, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries } from "./env.js";
2
2
  import { credentialScopesSatisfied } from "@neon/config/v1";
3
- //#region src/lib/reuse-secrets.ts
3
+ //#region src/_shared/env-core/reuse-secrets.ts
4
4
  /**
5
5
  * Resolve a branch's env while keeping one-time secrets the caller already holds.
6
6
  *
@@ -24,7 +24,7 @@ import { credentialScopesSatisfied } from "@neon/config/v1";
24
24
  * the record of what the last call issued.
25
25
  *
26
26
  * ```ts
27
- * import { fetchEnvReusingSecrets } from "@neon/env/runtime";
27
+ * import { fetchEnvReusingSecrets } from "../_shared/env-core/reuse-secrets.js";
28
28
  *
29
29
  * const { vars, credential } = await fetchEnvReusingSecrets(config, {
30
30
  * projectId,
@@ -35,7 +35,7 @@ import { credentialScopesSatisfied } from "@neon/config/v1";
35
35
  * ```
36
36
  */
37
37
  async function fetchEnvReusingSecrets(config, options) {
38
- const { env: source = process.env, ...fetchOptions } = options;
38
+ const { env: source = process.env, revokeSuperseded = true, ...fetchOptions } = options;
39
39
  const api = options.api ?? createApiFromOptions(options);
40
40
  const { branch, desired } = await resolveBranchPolicy(config, options, api);
41
41
  const storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;
@@ -51,7 +51,8 @@ async function fetchEnvReusingSecrets(config, options) {
51
51
  credential: {
52
52
  issued: false,
53
53
  keys: [],
54
- revoked: []
54
+ revoked: [],
55
+ superseded: []
55
56
  }
56
57
  };
57
58
  }
@@ -85,19 +86,21 @@ async function fetchEnvReusingSecrets(config, options) {
85
86
  credential: {
86
87
  issued: false,
87
88
  keys: secretKeys,
88
- revoked: []
89
+ revoked: [],
90
+ superseded: []
89
91
  }
90
92
  };
91
93
  }
92
94
  const ours = /* @__PURE__ */ new Set();
93
95
  for (const meta of [named.storage, named.gateway]) if (meta !== null && meta.principalType === "user" && meta.name === credentialName(branch.name)) ours.add(meta.tokenId);
94
- for (const tokenId of ours) await api.revokeCredential(options.projectId, branch.id, tokenId);
96
+ if (revokeSuperseded) for (const tokenId of ours) await api.revokeCredential(options.projectId, branch.id, tokenId);
95
97
  return {
96
98
  vars,
97
99
  credential: {
98
100
  issued: true,
99
101
  keys: secretKeys,
100
- revoked: [...ours]
102
+ revoked: revokeSuperseded ? [...ours] : [],
103
+ superseded: revokeSuperseded ? [] : [...ours]
101
104
  }
102
105
  };
103
106
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reuse-secrets.js","names":[],"sources":["../../../src/_shared/env-core/reuse-secrets.ts"],"sourcesContent":["import {\n\ttype Config,\n\tcredentialScopesSatisfied,\n\ttype NeonCredentialMeta,\n} from \"@neon/config/v1\";\n\nimport {\n\tcreateApiFromOptions,\n\tcredentialEnvKeys,\n\tcredentialName,\n\ttype FetchEnvOptions,\n\tfetchEnvKeys,\n\tNEON_ENV_VAR_KEYS,\n\tpolicyEnvKeys,\n\tpreviewCredentialScopes,\n\tresolveBranchPolicy,\n\ttoEntries,\n} from \"./env.js\";\n\n/**\n * What happened to the branch credential during a {@link fetchEnvReusingSecrets} call.\n */\nexport interface CredentialOutcome {\n\t/**\n\t * `true` when a new credential was minted — because none was persisted, or because the\n\t * persisted secrets could not be verified against this branch. `false` when the persisted\n\t * secrets were verified and kept, and when the policy enables nothing credential-backed.\n\t */\n\tissued: boolean;\n\t/**\n\t * The env-var keys the branch credential's secrets surface under, given what the policy\n\t * enables. Empty when the policy enables neither object storage nor the AI Gateway.\n\t */\n\tkeys: string[];\n\t/**\n\t * `tokenId`s revoked because this call superseded them. Only ever credentials the persisted\n\t * secrets named *and* that this tool issued; empty otherwise.\n\t */\n\trevoked: string[];\n\t/**\n\t * `tokenId`s this call superseded but left live, because `revokeSuperseded` was `false`.\n\t * The counterpart to {@link CredentialOutcome.revoked}: exactly the ids that would be\n\t * there instead. Lets a caller name what it orphaned rather than saying that it might\n\t * have orphaned something — always empty on the default path.\n\t */\n\tsuperseded: string[];\n}\n\n/** A resolved branch env, ready to write to a dotenv file or inject into a process. */\nexport interface ReusedBranchEnv {\n\t/** Every Neon env var for the branch, as `{ KEY: value }`. */\n\tvars: Record<string, string>;\n\t/** What happened to the branch credential. */\n\tcredential: CredentialOutcome;\n}\n\n/** The branch credential's secrets as persisted in an env source. Empty string means absent. */\ninterface PersistedSecrets {\n\taccessKeyId: string;\n\tsecretAccessKey: string;\n\tapiToken: string;\n}\n\n/**\n * Resolve a branch's env while keeping one-time secrets the caller already holds.\n *\n * {@link fetchEnvKeys} — and the public `fetchEnv` — only ever *fetch*. The Neon API returns a\n * credential's `api_token` / `s3_secret_access_key` exactly once, at mint time, so \"fetching\"\n * them means minting a new credential; a plain `fetchEnv` on every `neon dev` start or `env\n * pull` would leave a live credential behind each time. This is the wrapper that avoids that:\n * it looks at what the caller already has, decides what is still usable, and asks `fetchEnv`\n * for only the rest.\n *\n * The check is a real verification, not a presence test. A persisted secret is kept only when\n * it names a credential that still exists on this branch, is not revoked or expired, and\n * carries every scope the policy needs. A `.env.example` placeholder, a credential revoked in\n * the console, one copied in from another branch, or one predating a newly-enabled feature all\n * fail that check and get replaced.\n *\n * None of this needs local bookkeeping, because the secrets carry their own credential id:\n * `AWS_ACCESS_KEY_ID` **is** the credential's `tokenId` (the storage gateway authenticates\n * against the full id), and the AI Gateway token is minted as `nt_live_<tokenIdShort>_<secret>`,\n * where `tokenIdShort` is what the credentials list reports. The env source being replaced is\n * the record of what the last call issued.\n *\n * ```ts\n * import { fetchEnvReusingSecrets } from \"../_shared/env-core/reuse-secrets.js\";\n *\n * const { vars, credential } = await fetchEnvReusingSecrets(config, {\n * projectId,\n * branch: \"main\",\n * env: { ...process.env, ...readEnvFile(\".env\") },\n * });\n * if (credential.issued) console.log(`new values for ${credential.keys.join(\", \")}`);\n * ```\n */\nexport async function fetchEnvReusingSecrets<const C extends Config>(\n\tconfig: C,\n\toptions: FetchEnvOptions & {\n\t\t/**\n\t\t * Env source holding secrets a previous call persisted — `process.env` layered with a\n\t\t * `.env` file, typically. Defaults to `process.env`.\n\t\t */\n\t\tenv?: NodeJS.ProcessEnv;\n\t\t/**\n\t\t * Revoke the credential a freshly-minted one supersedes. Defaults to `true`.\n\t\t *\n\t\t * Pass `false` when this resolve covers only *part* of what the branch has. Object\n\t\t * storage and the AI Gateway share one credential, so a partial resolve cannot tell\n\t\t * whether the credential its persisted secrets name also backs a service it is not\n\t\t * resolving — and revoking it would kill that service while its vars, which this call\n\t\t * is not rewriting, stay on disk and stop working. The cost is an orphaned credential,\n\t\t * which is the safer of the two failures. `neon env pull --service` is the caller that\n\t\t * needs this.\n\t\t */\n\t\trevokeSuperseded?: boolean;\n\t},\n): Promise<ReusedBranchEnv> {\n\tconst {\n\t\tenv: source = process.env,\n\t\trevokeSuperseded = true,\n\t\t...fetchOptions\n\t} = options;\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\n\tconst storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;\n\tconst gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;\n\tconst secretKeys = credentialEnvKeys({\n\t\tstorage: storageEnabled,\n\t\taiGateway: gatewayEnabled,\n\t});\n\n\t// Nothing credential-backed on this branch, so there is nothing to preserve and no\n\t// credential to spend: fetch everything and skip the credentials endpoint entirely.\n\tif (secretKeys.length === 0) {\n\t\tconst fetched = await fetchEnvKeys(config, fetchOptions, null);\n\t\treturn {\n\t\t\tvars: preferPersisted(toEntries(fetched), source),\n\t\t\tcredential: {\n\t\t\t\tissued: false,\n\t\t\t\tkeys: [],\n\t\t\t\trevoked: [],\n\t\t\t\tsuperseded: [],\n\t\t\t},\n\t\t};\n\t}\n\n\tconst persisted = readPersistedSecrets(source);\n\tconst complete =\n\t\t(!storageEnabled ||\n\t\t\tBoolean(persisted.accessKeyId && persisted.secretAccessKey)) &&\n\t\t(!gatewayEnabled || Boolean(persisted.apiToken));\n\n\t// Look the persisted secrets up whenever there are any — not only when they're complete.\n\t// An incomplete set still names the credential a newly-enabled feature is about to\n\t// supersede (a storage-only credential on a branch that just gained the AI Gateway), and\n\t// that one should be revoked rather than left live.\n\tconst named =\n\t\tpersisted.accessKeyId !== \"\" || persisted.apiToken !== \"\"\n\t\t\t? namedCredentials(\n\t\t\t\t\tawait api.listCredentials(options.projectId, branch.id),\n\t\t\t\t\tpersisted,\n\t\t\t\t)\n\t\t\t: { storage: null, gateway: null };\n\n\tconst reusable = complete\n\t\t? reusableCredential(named, { storageEnabled, gatewayEnabled })\n\t\t: null;\n\tconst scopes = previewCredentialScopes(desired.preview);\n\tconst keep =\n\t\treusable !== null && credentialScopesSatisfied(reusable.scopes, scopes);\n\n\t// Ask for everything the policy produces, minus the secrets we're keeping — which is what\n\t// stops `fetchEnv` from minting a credential it doesn't need.\n\tconst allKeys = policyEnvKeys(desired);\n\tconst fetchKeys = keep\n\t\t? allKeys.filter((key) => !secretKeys.includes(key))\n\t\t: allKeys;\n\tconst fetched = await fetchEnvKeys(\n\t\tconfig,\n\t\t// Pass the resolved id so `fetchEnv` targets the same branch this call verified against,\n\t\t// even if `options.branch` was a name that has since been reused.\n\t\t{ ...fetchOptions, branchId: branch.id, api },\n\t\tfetchKeys,\n\t);\n\n\tconst vars = preferPersisted(toEntries(fetched), source);\n\tif (keep) {\n\t\tfor (const key of secretKeys) {\n\t\t\tconst value = source[key];\n\t\t\tif (value !== undefined) vars[key] = value;\n\t\t}\n\t\treturn {\n\t\t\tvars,\n\t\t\tcredential: {\n\t\t\t\tissued: false,\n\t\t\t\tkeys: secretKeys,\n\t\t\t\trevoked: [],\n\t\t\t\tsuperseded: [],\n\t\t\t},\n\t\t};\n\t}\n\n\t// A replacement was minted, so revoke what it supersedes: the credentials the old secrets\n\t// named, minus any this tool did not issue. Their secrets lived nowhere but the env source\n\t// this call replaces, so revoking them strands nothing — and it keeps a branch from\n\t// accumulating a live credential per call. Everything else on the branch is left alone: it\n\t// may belong to a teammate, another checkout, or a deployed function, and nothing\n\t// observable distinguishes those from an orphan of our own.\n\t//\n\t// Revoked *after* the fetch, so a failed fetch leaves the caller's existing secrets working.\n\tconst ours = new Set<string>();\n\tfor (const meta of [named.storage, named.gateway]) {\n\t\tif (\n\t\t\tmeta !== null &&\n\t\t\tmeta.principalType === \"user\" &&\n\t\t\tmeta.name === credentialName(branch.name)\n\t\t) {\n\t\t\tours.add(meta.tokenId);\n\t\t}\n\t}\n\tif (revokeSuperseded) {\n\t\tfor (const tokenId of ours) {\n\t\t\tawait api.revokeCredential(options.projectId, branch.id, tokenId);\n\t\t}\n\t}\n\n\treturn {\n\t\tvars,\n\t\tcredential: {\n\t\t\tissued: true,\n\t\t\tkeys: secretKeys,\n\t\t\trevoked: revokeSuperseded ? [...ours] : [],\n\t\t\tsuperseded: revokeSuperseded ? [] : [...ours],\n\t\t},\n\t};\n}\n\n/** Read the branch credential's secrets out of an env source. */\nfunction readPersistedSecrets(source: NodeJS.ProcessEnv): PersistedSecrets {\n\tconst storage = NEON_ENV_VAR_KEYS.storage;\n\tconst gateway = NEON_ENV_VAR_KEYS.aiGateway;\n\treturn {\n\t\taccessKeyId: source[storage.accessKeyId] ?? \"\",\n\t\tsecretAccessKey: source[storage.secretAccessKey] ?? \"\",\n\t\tapiToken: source[gateway.apiKey] ?? \"\",\n\t};\n}\n\n/**\n * Keep a persisted value rather than overwriting it with an empty fetched one.\n *\n * Neon Auth's `base_url` is the case that needs this: integrations created before the API\n * returned it answer with an empty string, and the persisted copy is the only one left. An\n * empty fetched value never carries more information than a non-empty persisted one, so\n * preferring the latter is safe for every var — and it keeps a pull from blanking a working\n * line in someone's `.env`.\n */\nfunction preferPersisted(\n\tvars: Record<string, string>,\n\tsource: NodeJS.ProcessEnv,\n): Record<string, string> {\n\tconst out = { ...vars };\n\tfor (const [key, value] of Object.entries(out)) {\n\t\tif (value !== \"\") continue;\n\t\tconst persisted = source[key];\n\t\tif (persisted !== undefined && persisted !== \"\") out[key] = persisted;\n\t}\n\treturn out;\n}\n\n/**\n * The credential id embedded in an AI Gateway token. The API mints them as\n * `nt_live_<tokenIdShort>_<secret>`, and `tokenIdShort` is the public identifier the credentials\n * list reports — so a persisted token names the credential that issued it. Returns `null` for\n * anything not in that shape (a `.env.example` placeholder, a hand-typed value), which callers\n * treat as unverifiable.\n */\nfunction gatewayTokenIdShort(apiToken: string): string | null {\n\treturn /^nt_live_([^_]+)_.+$/.exec(apiToken)?.[1] ?? null;\n}\n\n/** Whether an issued credential can still be used: not revoked, not past its expiry. */\nfunction isLiveCredential(meta: NeonCredentialMeta, now: number): boolean {\n\tif (meta.revokedAt !== undefined) return false;\n\tif (meta.expiresAt === undefined) return true;\n\tconst expiresAt = Date.parse(meta.expiresAt);\n\treturn Number.isNaN(expiresAt) || expiresAt > now;\n}\n\n/**\n * The live credentials the persisted secrets name — at most one per half. A half that names\n * nothing contributes nothing, which is what a placeholder, a credential revoked in the\n * console, and one copied in from another branch all look like from here.\n */\nfunction namedCredentials(\n\tlive: NeonCredentialMeta[],\n\tpersisted: PersistedSecrets,\n): { storage: NeonCredentialMeta | null; gateway: NeonCredentialMeta | null } {\n\tconst usable = live.filter((meta) => isLiveCredential(meta, Date.now()));\n\tconst shortId = persisted.apiToken\n\t\t? gatewayTokenIdShort(persisted.apiToken)\n\t\t: null;\n\treturn {\n\t\tstorage: persisted.accessKeyId\n\t\t\t? (usable.find((meta) => meta.tokenId === persisted.accessKeyId) ??\n\t\t\t\tnull)\n\t\t\t: null,\n\t\tgateway: shortId\n\t\t\t? (usable.find((meta) => meta.tokenIdShort === shortId) ?? null)\n\t\t\t: null,\n\t};\n}\n\n/**\n * The credential the persisted secrets can be *reused* as, or `null`.\n *\n * Strict on purpose: every half the policy enables has to name a live credential, and when both\n * features are enabled they must name the *same* one — they share a single credential, so\n * halves that disagree came from two different calls and neither can be trusted.\n */\nfunction reusableCredential(\n\tnamed: ReturnType<typeof namedCredentials>,\n\tenabled: { storageEnabled: boolean; gatewayEnabled: boolean },\n): NeonCredentialMeta | null {\n\tif (enabled.storageEnabled && enabled.gatewayEnabled) {\n\t\treturn named.storage &&\n\t\t\tnamed.gateway &&\n\t\t\tnamed.storage.tokenId === named.gateway.tokenId\n\t\t\t? named.storage\n\t\t\t: null;\n\t}\n\tif (enabled.storageEnabled) return named.storage;\n\tif (enabled.gatewayEnabled) return named.gateway;\n\treturn null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,eAAsB,uBACrB,QACA,SAmB2B;CAC3B,MAAM,EACL,KAAK,SAAS,QAAQ,KACtB,mBAAmB,MACnB,GAAG,iBACA;CACJ,MAAM,MAAM,QAAQ,OAAO,qBAAqB,OAAO;CACvD,MAAM,EAAE,QAAQ,YAAY,MAAM,oBAAoB,QAAQ,SAAS,GAAG;CAE1E,MAAM,kBAAkB,QAAQ,SAAS,QAAQ,UAAU,KAAK;CAChE,MAAM,iBAAiB,QAAQ,SAAS,oBAAoB;CAC5D,MAAM,aAAa,kBAAkB;EACpC,SAAS;EACT,WAAW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