@neondatabase/env 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -0
- package/dist/cli.js +971 -6
- package/dist/cli.js.map +1 -1
- package/dist/{_shared/env-core/env.js → env.js} +62 -41
- package/dist/env.js.map +1 -0
- package/dist/index.d.ts +528 -3
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +197 -2
- package/dist/{lib/parse-env.js.map → index.js.map} +1 -1
- package/package.json +8 -6
- package/dist/_shared/auth_selection.d.ts +0 -95
- package/dist/_shared/auth_selection.d.ts.map +0 -1
- package/dist/_shared/auth_selection.js +0 -85
- package/dist/_shared/auth_selection.js.map +0 -1
- package/dist/_shared/credentials.d.ts +0 -186
- package/dist/_shared/credentials.d.ts.map +0 -1
- package/dist/_shared/credentials.js +0 -190
- package/dist/_shared/credentials.js.map +0 -1
- package/dist/_shared/env-core/env.d.ts +0 -424
- package/dist/_shared/env-core/env.d.ts.map +0 -1
- package/dist/_shared/env-core/env.js.map +0 -1
- package/dist/_shared/env-core/reuse-secrets.d.ts +0 -95
- package/dist/_shared/env-core/reuse-secrets.d.ts.map +0 -1
- package/dist/_shared/env-core/reuse-secrets.js +0 -181
- package/dist/_shared/env-core/reuse-secrets.js.map +0 -1
- package/dist/_shared/paths.d.ts +0 -116
- package/dist/_shared/paths.d.ts.map +0 -1
- package/dist/_shared/paths.js +0 -153
- package/dist/_shared/paths.js.map +0 -1
- package/dist/_shared/profiles.d.ts +0 -145
- package/dist/_shared/profiles.d.ts.map +0 -1
- package/dist/_shared/profiles.js +0 -228
- package/dist/_shared/profiles.js.map +0 -1
- package/dist/_shared/secure_file.d.ts +0 -25
- package/dist/_shared/secure_file.d.ts.map +0 -1
- package/dist/_shared/secure_file.js +0 -43
- package/dist/_shared/secure_file.js.map +0 -1
- package/dist/config/dist/lib/define-config.d.ts +0 -20
- package/dist/config/dist/lib/define-config.d.ts.map +0 -1
- package/dist/config/dist/lib/neon-api.d.ts +0 -375
- package/dist/config/dist/lib/neon-api.d.ts.map +0 -1
- package/dist/config/dist/lib/types.d.ts +0 -603
- package/dist/config/dist/lib/types.d.ts.map +0 -1
- package/dist/config/dist/v1.d.ts +0 -5
- package/dist/lib/cli/commands.d.ts +0 -68
- package/dist/lib/cli/commands.d.ts.map +0 -1
- package/dist/lib/cli/commands.js +0 -233
- package/dist/lib/cli/commands.js.map +0 -1
- package/dist/lib/cli/resolve-api-key.d.ts +0 -29
- package/dist/lib/cli/resolve-api-key.d.ts.map +0 -1
- package/dist/lib/cli/resolve-api-key.js +0 -74
- package/dist/lib/cli/resolve-api-key.js.map +0 -1
- package/dist/lib/cli/resolve-context.d.ts +0 -34
- package/dist/lib/cli/resolve-context.d.ts.map +0 -1
- package/dist/lib/cli/resolve-context.js +0 -88
- package/dist/lib/cli/resolve-context.js.map +0 -1
- package/dist/lib/parse-env.d.ts +0 -95
- package/dist/lib/parse-env.d.ts.map +0 -1
- package/dist/lib/parse-env.js +0 -198
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport {\n\ttype CommandResult,\n\trunEnvExport,\n\trunEnvRun,\n} from \"./lib/cli/commands.js\";\n\nconst pkgVersion = readPackageVersion();\n\nconst argv = yargs(hideBin(process.argv))\n\t.scriptName(\"neon-env\")\n\t.usage(\"$0 <command> [options]\")\n\t.parserConfiguration({ \"populate--\": true })\n\t.option(\"debug\", {\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t\tdescribe:\n\t\t\t\"Print stack traces and structured error details when something fails\",\n\t})\n\t.command(\n\t\t\"run\",\n\t\t\"Run a command with Neon env vars (from your neon.ts policy) injected into its environment. Use `--` to separate the command: `neon-env run -- npm run dev`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.command(\n\t\t\"export\",\n\t\t\"Print the branch's Neon env vars (from your neon.ts policy) to stdout, as dotenv lines or JSON. Useful for piping into other env tools, e.g. `neon-env export --format json`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"format\", {\n\t\t\t\t\tchoices: [\"dotenv\", \"json\"] as const,\n\t\t\t\t\tdefault: \"dotenv\",\n\t\t\t\t\tdescribe: \"Output format: dotenv (KEY=value lines) or json\",\n\t\t\t\t})\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.demandCommand(1, \"Run `neon-env --help` to see the available commands.\")\n\t.strict()\n\t.help()\n\t.version(pkgVersion)\n\t.parseSync();\n\nconst command = String(argv._[0]);\nconst cwd = process.cwd();\n\nlet result: CommandResult;\nswitch (command) {\n\tcase \"run\": {\n\t\tconst passthrough = Array.isArray(argv[\"--\"])\n\t\t\t? argv[\"--\"].map(String)\n\t\t\t: [];\n\t\tresult = await runEnvRun(\n\t\t\t{\n\t\t\t\tcommand: passthrough,\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tcase \"export\": {\n\t\tresult = await runEnvExport(\n\t\t\t{\n\t\t\t\tformat: argv.format === \"json\" ? \"json\" : \"dotenv\",\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tresult = {\n\t\t\texitCode: 1,\n\t\t\tstdout: \"\",\n\t\t\tstderr: `Unknown command: ${command}\\n`,\n\t\t};\n}\n\nif (result.stdout) process.stdout.write(result.stdout);\nif (result.stderr) process.stderr.write(result.stderr);\nif (argv.debug && result.exitCode !== 0 && result.debugInfo) {\n\tprocess.stderr.write(`\\n--- debug ---\\n${result.debugInfo}\\n`);\n}\nprocess.exit(result.exitCode);\n\nfunction readPackageVersion(): string {\n\t// The built CLI lives at `dist/cli.js`, so `package.json` is one directory up. When\n\t// running from source (tsx, vitest), the file lives at `src/cli.ts` and `package.json`\n\t// is again one directory up. Single resolution covers both layouts.\n\ttry {\n\t\tconst pkgUrl = new URL(\"../package.json\", import.meta.url);\n\t\tconst raw = readFileSync(fileURLToPath(pkgUrl), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as { version?: unknown };\n\t\treturn typeof parsed.version === \"string\" ? parsed.version : \"0.0.0\";\n\t} catch {\n\t\treturn \"0.0.0\";\n\t}\n}\n"],"mappings":";;;;;;;AAYA,MAAM,aAAa,mBAAmB;AAEtC,MAAM,OAAO,MAAM,QAAQ,QA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BAA6B;CAIrC,IAAI;EACH,MAAM,SAAS,IAAI,IAAI,mBAAmB,YAAY,GAAG;EACzD,MAAM,MAAM,aAAa,cAAc,MAAM,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,OAAO,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU;CAC9D,QAAQ;EACP,OAAO;CACR;AACD"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":["nonEmpty","nonEmpty","nonEmpty"],"sources":["../../../internals/env-core/dist/reuse-secrets.js","../../../internals/cli-core/dist/paths.js","../../../internals/cli-core/dist/profiles.js","../../../internals/cli-core/dist/auth_selection.js","../../../internals/cli-core/dist/credentials.js","../src/lib/cli/resolve-api-key.ts","../src/lib/cli/resolve-context.ts","../src/lib/cli/commands.ts","../src/cli.ts"],"sourcesContent":["import { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnvKeys, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries } from \"./env.js\";\nimport { credentialScopesSatisfied } from \"@neon/config/v1\";\n//#region src/reuse-secrets.ts\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 \"@neon-internals/env-core/reuse-secrets\";\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*/\nasync function fetchEnvReusingSecrets(config, options) {\n\tconst { env: source = process.env, keys: requestedKeys, revokeSuperseded = true, ...fetchOptions } = options;\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\tconst allPolicyKeys = policyEnvKeys(desired);\n\tconst requested = requestedKeys ? new Set(requestedKeys) : null;\n\tconst selectedPolicyKeys = requested === null ? allPolicyKeys : allPolicyKeys.filter((key) => requested.has(key));\n\tconst selected = new Set(selectedPolicyKeys);\n\tconst K = NEON_ENV_VAR_KEYS;\n\tconst storageCredentialSelected = (desired.preview?.buckets.length ?? 0) > 0 && (selected.has(K.storage.accessKeyId) || selected.has(K.storage.secretAccessKey));\n\tconst gatewayCredentialSelected = (desired.preview?.aiGatewayEnabled ?? false) && selected.has(K.aiGateway.apiKey);\n\tconst secretKeys = credentialEnvKeys({\n\t\tstorage: storageCredentialSelected,\n\t\taiGateway: gatewayCredentialSelected\n\t}).filter((key) => selected.has(key));\n\tif (secretKeys.length === 0) {\n\t\tconst fetched = await fetchEnvKeys(config, fetchOptions, requested === null ? null : selectedPolicyKeys);\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\tconst persisted = readPersistedSecrets(source);\n\tconst storageCredentialManaged = requested === null || storageCredentialSelected;\n\tconst gatewayCredentialManaged = requested === null || gatewayCredentialSelected;\n\tconst complete = (!storageCredentialSelected || Boolean(persisted.accessKeyId && persisted.secretAccessKey)) && (!gatewayCredentialSelected || Boolean(persisted.apiToken));\n\tconst named = storageCredentialManaged && persisted.accessKeyId !== \"\" || gatewayCredentialManaged && persisted.apiToken !== \"\" ? namedCredentials(await api.listCredentials(options.projectId, branch.id), persisted) : {\n\t\tstorage: null,\n\t\tgateway: null\n\t};\n\tconst reusable = complete ? reusableCredential(named, {\n\t\tstorageEnabled: storageCredentialSelected,\n\t\tgatewayEnabled: gatewayCredentialSelected\n\t}) : null;\n\tconst scopes = previewCredentialScopes(desired.preview, {\n\t\tstorage: storageCredentialSelected,\n\t\taiGateway: gatewayCredentialSelected\n\t});\n\tconst keep = reusable !== null && credentialScopesSatisfied(reusable.scopes, scopes);\n\tconst fetchKeys = keep ? selectedPolicyKeys.filter((key) => !secretKeys.includes(key)) : selectedPolicyKeys;\n\tconst fetched = await fetchEnvKeys(config, {\n\t\t...fetchOptions,\n\t\tbranchId: branch.id,\n\t\tapi\n\t}, fetchKeys);\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 !== void 0) 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\tconst ours = /* @__PURE__ */ new Set();\n\tfor (const meta of [storageCredentialManaged ? named.storage : null, gatewayCredentialManaged ? named.gateway : null]) if (meta !== null && meta.principalType === \"user\" && meta.name === credentialName(branch.name)) ours.add(meta.tokenId);\n\tif (revokeSuperseded) for (const tokenId of ours) await api.revokeCredential(options.projectId, branch.id, tokenId);\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/** Read the branch credential's secrets out of an env source. */\nfunction readPersistedSecrets(source) {\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* 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(vars, source) {\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 !== void 0 && persisted !== \"\") out[key] = persisted;\n\t}\n\treturn out;\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) {\n\treturn /^nt_live_([^_]+)_.+$/.exec(apiToken)?.[1] ?? null;\n}\n/** Whether an issued credential can still be used: not revoked, not past its expiry. */\nfunction isLiveCredential(meta, now) {\n\tif (meta.revokedAt !== void 0) return false;\n\tif (meta.expiresAt === void 0) return true;\n\tconst expiresAt = Date.parse(meta.expiresAt);\n\treturn Number.isNaN(expiresAt) || expiresAt > now;\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(live, persisted) {\n\tconst usable = live.filter((meta) => isLiveCredential(meta, Date.now()));\n\tconst shortId = persisted.apiToken ? gatewayTokenIdShort(persisted.apiToken) : null;\n\treturn {\n\t\tstorage: persisted.accessKeyId ? usable.find((meta) => meta.tokenId === persisted.accessKeyId) ?? null : null,\n\t\tgateway: shortId ? usable.find((meta) => meta.tokenIdShort === shortId) ?? null : null\n\t};\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(named, enabled) {\n\tif (enabled.storageEnabled && enabled.gatewayEnabled) return named.storage && named.gateway && named.storage.tokenId === named.gateway.tokenId ? named.storage : null;\n\tif (enabled.storageEnabled) return named.storage;\n\tif (enabled.gatewayEnabled) return named.gateway;\n\treturn null;\n}\n//#endregion\nexport { fetchEnvReusingSecrets };\n\n//# sourceMappingURL=reuse-secrets.js.map","import { existsSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n//#region src/paths.ts\n/**\n* # Where the Neon CLIs keep their files on disk\n*\n**Deliberately impure.** It reads environment variables and touches the filesystem, which\n* `@neon/config` — the package this used to be a subpath of — must never do from its root\n* export. It lives here instead of there precisely so that a policy-facing package does not\n* carry implementor-only code.\n*\n* It exists because three separate readers each grew their own answer to \"where is the\n* config directory\", and all three disagreed: `packages/cli` honoured `XDG_CONFIG_HOME` but\n* not `NEONCTL_CONFIG_DIR`, `packages/env` honoured the env var but not XDG, and the init\n* flow hardcoded `~/.config/neonctl`. With `XDG_CONFIG_HOME` set, the CLI wrote\n* credentials somewhere the other two never looked.\n*\n* ## The directory\n*\n* `neon` is the current name; `neonctl` is the legacy one, kept readable forever. Resolution,\n* each entry winning over the next:\n*\n* 1. An explicit directory (a `--config-dir` flag) — **exact**, no legacy fallback.\n* 2. `NEON_CONFIG_DIR` — exact.\n* 3. `NEONCTL_CONFIG_DIR` (legacy name) — exact.\n* 4. `$XDG_CONFIG_HOME/neon`, else `<home>/.config/neon`.\n*\n* An explicitly chosen directory is never paired with a fallback: `--config-dir /tmp/ci` that\n* quietly read `~/.config/neonctl` would defeat the point of passing it.\n*\n* ## The files\n*\n* {@link resolveConfigFile} answers \"which path should I use for this file\", and it is the\n* same answer for reading and writing:\n*\n* - Present in `neon/` → use it.\n* - Present only in `neonctl/` → **use it there, in place.** An existing credentials file is\n* never copied or moved, so nothing is left behind to go stale and no other tool starts\n* reading an abandoned token.\n* - Present in neither → the new location. New files only ever appear under `neon/`.\n*/\n/** Current directory name. New files are created here. */\nconst CONFIG_DIR_NAME = \"neon\";\n/** Legacy directory name, read forever so existing installs keep working untouched. */\nconst LEGACY_CONFIG_DIR_NAME = \"neonctl\";\n/** Where files are created. See the module docs for the precedence. */\nfunction configDir(options = {}) {\n\tconst explicit = explicitDir(options);\n\tif (explicit) return explicit;\n\treturn join(configHome(options.env ?? process.env), CONFIG_DIR_NAME);\n}\n/**\n* The legacy directory, or `undefined` when the location was chosen explicitly (in which\n* case there is no legacy counterpart to fall back to).\n*/\nfunction legacyConfigDir(options = {}) {\n\tif (explicitDir(options)) return void 0;\n\treturn join(configHome(options.env ?? process.env), LEGACY_CONFIG_DIR_NAME);\n}\n/**\n* Resolve one file inside the config directory. Prefers the current location, falls back to\n* an existing legacy file **in place**, and otherwise points at the current location so new\n* files are created there.\n*/\nfunction resolveConfigFile(fileName, options = {}) {\n\tconst dir = configDir(options);\n\tconst current = resolve(dir, fileName);\n\tif (existsSync(current)) return {\n\t\tpath: current,\n\t\tdir,\n\t\tisLegacy: false,\n\t\texists: true\n\t};\n\tconst legacyDir = legacyConfigDir(options);\n\tif (legacyDir) {\n\t\tconst legacy = resolve(legacyDir, fileName);\n\t\tif (existsSync(legacy)) return {\n\t\t\tpath: legacy,\n\t\t\tdir: legacyDir,\n\t\t\tisLegacy: true,\n\t\t\texists: true\n\t\t};\n\t}\n\treturn {\n\t\tpath: current,\n\t\tdir,\n\t\tisLegacy: false,\n\t\texists: false\n\t};\n}\n/** `$XDG_CONFIG_HOME`, else `<home>/.config`. Falls back to a relative `.config` with no home. */\nfunction configHome(env) {\n\tconst xdg = nonEmpty(env.XDG_CONFIG_HOME);\n\tif (xdg) return xdg;\n\tconst home = nonEmpty(env.HOME) ?? nonEmpty(env.USERPROFILE);\n\treturn home ? join(home, \".config\") : \".config\";\n}\nfunction explicitDir(options) {\n\tconst env = options.env ?? process.env;\n\treturn nonEmpty(options.dir) ?? nonEmpty(env.NEON_CONFIG_DIR) ?? nonEmpty(env.NEONCTL_CONFIG_DIR);\n}\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\nconst CREDENTIALS_FILE = \"credentials.json\";\n/**\n* Default for `--config-dir`: `$XDG_CONFIG_HOME/neon`, else `~/.config/neon`.\n*\n* The directory was called `neonctl` until the CLI was renamed. An existing one is still read —\n* see {@link credentialsPath} — but it is never written to, moved, or deleted.\n*/\nconst defaultDir = configDir();\n/**\n* Where this invocation's `credentials.json` lives.\n*\n* When `--config-dir` was left at its default, an existing file in the legacy `neonctl`\n* directory is used **in place**: an install that predates the rename keeps working, and its\n* credentials are never duplicated into a second location where one copy could go stale while\n* another tool still reads it.\n*\n* A `--config-dir` the user actually passed is used exactly as given. Falling back out of an\n* explicitly chosen directory would defeat the reason for choosing it — a CI run pointed at a\n* scratch directory must never pick up a developer's real credentials.\n*/\nconst credentialsPath = (dir) => resolveConfigFile(CREDENTIALS_FILE, dir === defaultDir ? {} : { dir }).path;\n/**\n* Whether a credentials file is one the CLI created, rather than a path a profile adopted.\n*\n* Anything that deletes a credential has to ask this first. A profile entry may point anywhere —\n* that is what makes adopting an existing directory a one-line edit — and a file we did not\n* create is not ours to remove.\n*/\nconst isInsideConfigDir = (configDirectory, file) => `${resolve(file)}/`.startsWith(`${resolve(configDirectory)}/`);\n/**\n* Whether a credentials file is one the CLI owns, counting the legacy `neonctl` directory.\n*\n* {@link credentialsPath} deliberately reads an existing legacy file in place rather than\n* migrating it, so for a default config directory that file is ours even though it sits outside\n* `neon/`. Judging ownership on the current directory alone would call an install that predates\n* the rename \"adopted\".\n*/\nconst isOwnedCredentialPath = (configDirectory, file) => {\n\tif (isInsideConfigDir(configDirectory, file)) return true;\n\tif (configDirectory !== defaultDir) return false;\n\tconst legacy = legacyConfigDir();\n\treturn legacy !== void 0 && isInsideConfigDir(legacy, file);\n};\n//#endregion\nexport { CONFIG_DIR_NAME, CREDENTIALS_FILE, LEGACY_CONFIG_DIR_NAME, configDir, credentialsPath, defaultDir, isInsideConfigDir, isOwnedCredentialPath, legacyConfigDir, resolveConfigFile };\n\n//# sourceMappingURL=paths.js.map","import { credentialsPath, defaultDir, resolveConfigFile } from \"./paths.js\";\nimport { writeSecretFile } from \"./secure_file.js\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\n//#region src/profiles.ts\n/**\n* # Profiles — several Neon accounts in one config directory\n*\n* A profile is **a pointer to a credentials file**. Nothing more. That constraint is what\n* keeps the feature small: there is no mirror, no per-profile directory tree, no persistent\n* \"active profile\" state to fall out of sync, and no migration.\n*\n* ```\n* ~/.config/neon/\n* ├── credentials.json # this IS the DEFAULT profile, not a copy of it\n* ├── credentials.work.json # created by `neon auth --profile work`\n* └── profiles.json # created only once a second profile exists\n* ```\n*\n* `profiles.json` maps a name to a path, and the path may point anywhere — which is what\n* makes adopting an existing directory a one-line edit rather than an import command:\n*\n* ```json\n* {\n* \"version\": 1,\n* \"profiles\": {\n* \"DEFAULT\": { \"credentials\": \"credentials.json\" },\n* \"work\": {\n* \"credentials\": \"../neonctl-databricks/credentials.json\",\n* \"label\": \"someone@example.com\"\n* }\n* }\n* }\n* ```\n*\n* ## Selection\n*\n* `--profile` → `NEON_PROFILE` → `DEFAULT`. Per invocation, like `AWS_PROFILE`; there is no\n* `profile use` command, so nothing persists that could disagree with what you typed.\n*\n* ## Compatibility\n*\n* An install with no `profiles.json` is already a valid `DEFAULT`-only state: `DEFAULT`\n* resolves to `credentials.json` in the config directory (including an existing one in the\n* legacy `neonctl` directory — see `./paths.ts`). Nothing is created until a second\n* profile is, and nothing is ever moved.\n*/\nconst PROFILES_FILE = \"profiles.json\";\n/** The implicit profile. Backed by plain `credentials.json`, with or without a profiles file. */\nconst DEFAULT_PROFILE = \"DEFAULT\";\n/** Profile names become part of a filename, so keep them boring. */\nconst NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n/** Which profile this invocation should use: `--profile` → `NEON_PROFILE` → `DEFAULT`. */\nconst selectProfileName = (flag, env = process.env) => nonEmpty(flag) ?? nonEmpty(env.NEON_PROFILE) ?? \"DEFAULT\";\nconst assertValidProfileName = (name) => {\n\tif (!NAME_PATTERN.test(name)) throw new Error(`Invalid profile name \"${name}\". Use letters, digits, dot, dash or underscore, starting with a letter or digit.`);\n};\n/** Where `profiles.json` lives for this config directory (whether or not it exists yet). */\nconst profilesFilePath = (dir) => resolveConfigFile(PROFILES_FILE, dir === defaultDir ? {} : { dir }).path;\n/**\n* Read and classify `profiles.json` without deciding what to do about it.\n*\n* Entry keys and shapes are validated here rather than at each use. A key is a profile name,\n* and a name that `assertValidProfileName` would reject cannot have been written by this CLI —\n* it would travel into error messages as a recovery command nobody can run, and into a\n* `credentials.<name>.json` filename.\n*/\nconst inspectProfiles = (dir) => {\n\tconst path = profilesFilePath(dir);\n\tif (!existsSync(path)) return { kind: \"absent\" };\n\tconst broken = (why) => ({\n\t\tkind: \"unusable\",\n\t\treason: `${path} could not be read as a profiles file: ${why}`\n\t});\n\tlet contents;\n\ttry {\n\t\tcontents = readFileSync(path, \"utf8\");\n\t} catch (err) {\n\t\tconst code = err.code;\n\t\treturn broken(code ? `reading it failed with ${code}` : \"reading it failed\");\n\t}\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(contents);\n\t} catch {\n\t\treturn broken(\"it is not valid JSON\");\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) return broken(\"it does not contain an object\");\n\tconst profiles = parsed.profiles;\n\tif (profiles === null || typeof profiles !== \"object\" || Array.isArray(profiles)) return broken(\"it has no `profiles` object\");\n\tfor (const [name, entry] of Object.entries(profiles)) {\n\t\tif (!NAME_PATTERN.test(name)) return broken(`\"${name}\" is not a valid profile name`);\n\t\tif (entry === null || typeof entry !== \"object\" || typeof entry.credentials !== \"string\" || entry.credentials.trim() === \"\") return broken(`profile \"${name}\" has no \\`credentials\\` path`);\n\t}\n\treturn {\n\t\tkind: \"ok\",\n\t\tfile: {\n\t\t\tversion: 1,\n\t\t\tprofiles\n\t\t}\n\t};\n};\n/**\n* Read `profiles.json`, or `null` when there is nothing usable there.\n*\n* A malformed file is reported through `onWarn` and treated as absent, because for a *read* the\n* worst case is a named profile turning up missing, which is recoverable — whereas throwing\n* would lock the user out of `neon auth` itself. Writing is the opposite: see\n* {@link upsertProfile}, which refuses rather than rebuilding a file it cannot read.\n*/\nconst readProfiles = (dir, onWarn = () => {}) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"ok\") return read.file;\n\tif (read.kind === \"unusable\") onWarn(read.reason);\n\treturn null;\n};\n/**\n* Refuse to act on a named profile when the file that defines it cannot be read.\n*\n* Call this **before** anything that writes a credential, opens a browser, or spends an API\n* call. {@link upsertProfile} refuses too, but it runs last: by then `create` has already\n* overwritten `credentials.<name>.json` and revoked the key it replaced, and `neon auth\n* --profile` has already signed in over it — a refusal that arrives after the destruction it\n* exists to prevent. The path resolution itself is the unsound part, since with the metadata\n* unreadable the conventional filename is a guess about which account that file belongs to.\n*\n* `DEFAULT` is exempt: it is defined by the absence of metadata rather than by an entry, so\n* signing in normally must keep working while a broken `profiles.json` is repaired.\n*/\nconst assertProfilesUsable = (dir, name) => {\n\tif (name === \"DEFAULT\") return;\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Fix or delete the file before working with profile \"${name}\" — it is the only record of where each account's credentials live.`);\n};\n/** Resolve a profile to an absolute credentials path. Throws when a named profile is unknown. */\nconst resolveProfile = (dir, name) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\" && name !== \"DEFAULT\") throw new Error(`${read.reason}. Fix or delete the file — every named profile is defined in it.`);\n\tconst file = read.kind === \"ok\" ? read.file : null;\n\tconst entry = file?.profiles[name];\n\tif (entry) return {\n\t\tname,\n\t\tcredentialsPath: resolveEntryPath(dir, entry.credentials),\n\t\t...entry.label ? { label: entry.label } : {},\n\t\t...entry.userId ? { userId: entry.userId } : {},\n\t\tdeclared: true\n\t};\n\tif (name === \"DEFAULT\") return {\n\t\tname,\n\t\tcredentialsPath: credentialsPath(dir),\n\t\tdeclared: false\n\t};\n\tconst known = file ? Object.keys(file.profiles).join(\", \") : DEFAULT_PROFILE;\n\tthrow new Error(`Unknown profile \"${name}\". Known profiles: ${known}. Create it with \\`neon profile create ${name}\\`.`);\n};\n/** Default location for a new named profile's credentials file. */\nconst newProfileCredentialsPath = (dir, name) => resolve(dir, `credentials.${name}.json`);\n/**\n* Record a profile, creating `profiles.json` if this is the first named one.\n*\n* When the file is created, `DEFAULT` is written explicitly and pointed at wherever\n* `credentials.json` actually is. That matters for an install predating the directory\n* rename: `profiles.json` is created in `neon/` while the credentials are still in\n* `neonctl/`, so `DEFAULT` is recorded as `../neonctl/credentials.json` rather than a\n* relative name that would resolve to a file that isn't there.\n*/\nconst upsertProfile = (dir, name, entry) => {\n\tassertValidProfileName(name);\n\tconst path = profilesFilePath(dir);\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Refusing to rewrite it, because doing so would discard the profiles it defines. Fix or delete the file, then re-run.`);\n\tconst file = read.kind === \"ok\" ? read.file : {\n\t\tversion: 1,\n\t\tprofiles: { [DEFAULT_PROFILE]: { credentials: relativeToProfiles(path, credentialsPath(dir)) } }\n\t};\n\tfile.profiles[name] = {\n\t\tcredentials: relativeToProfiles(path, entry.credentials),\n\t\t...entry.label ? { label: entry.label } : {},\n\t\t...entry.userId ? { userId: entry.userId } : {}\n\t};\n\twriteProfiles(path, file);\n};\n/** Remove an entry. Returns false when it wasn't there. */\nconst removeProfileEntry = (dir, name) => {\n\tconst path = profilesFilePath(dir);\n\tconst file = readProfiles(dir);\n\tif (!file?.profiles[name]) return false;\n\tdelete file.profiles[name];\n\twriteProfiles(path, file);\n\treturn true;\n};\n/**\n* True when only `DEFAULT` is left, so `profiles.json` no longer earns its place. Mirrors\n* lazy creation: a single-account install has no profiles file, before or after.\n*/\nconst onlyDefaultRemains = (file) => {\n\tconst names = Object.keys(file.profiles);\n\treturn names.length === 0 || names.length === 1 && names[0] === \"DEFAULT\";\n};\nconst listProfiles = (dir) => {\n\tconst read = inspectProfiles(dir);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. Fix or delete the file — every named profile is defined in it.`);\n\tconst file = read.kind === \"ok\" ? read.file : null;\n\tif (!file) return [resolveProfile(dir, DEFAULT_PROFILE)];\n\tconst names = Object.keys(file.profiles);\n\tif (!names.includes(\"DEFAULT\")) names.unshift(DEFAULT_PROFILE);\n\treturn names.map((name) => resolveProfile(dir, name));\n};\nconst writeProfiles = (path, file) => {\n\twriteSecretFile(path, `${JSON.stringify(file, null, 2)}\\n`);\n};\nconst resolveEntryPath = (dir, entry) => isAbsolute(entry) ? entry : resolve(profilesDir(dir), entry);\n/** `profiles.json` may sit in the legacy directory, so entries resolve against its own dir. */\nconst profilesDir = (dir) => resolve(profilesFilePath(dir), \"..\");\n/** Keep entries relative when they sit near `profiles.json`; absolute paths stay absolute. */\nconst relativeToProfiles = (profilesPath, target) => {\n\tconst rel = relative(resolve(profilesPath, \"..\"), target);\n\treturn rel && !isAbsolute(rel) ? rel : target;\n};\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\n//#endregion\nexport { DEFAULT_PROFILE, PROFILES_FILE, assertProfilesUsable, assertValidProfileName, inspectProfiles, listProfiles, newProfileCredentialsPath, onlyDefaultRemains, profilesFilePath, readProfiles, removeProfileEntry, resolveProfile, selectProfileName, upsertProfile };\n\n//# sourceMappingURL=profiles.js.map","import \"./profiles.js\";\n//#region src/auth_selection.ts\n/**\n* # Which credential an invocation authenticates with\n*\n* Four inputs can each answer \"who am I\": the `--api-key` flag, `NEON_API_KEY`, the\n* `--profile` flag, and `NEON_PROFILE`. This module decides between them, and it is pure so\n* the decision can be tested without a filesystem, a network, or a config directory.\n*\n* ## The rule\n*\n* **An explicit flag beats an ambient environment variable.** That single rule fixes the bug\n* this module exists for: before it, any API key — including one merely exported into the\n* shell — silently voided `--profile`, so `neon --profile work …` would quietly run as\n* whoever `NEON_API_KEY` belonged to and say nothing about it.\n*\n* | Given | What runs |\n* | --- | --- |\n* | `--api-key` and `--profile` | neither: contradictory explicit flags, so this throws |\n* | `--api-key` and `NEON_PROFILE` | the flag's key |\n* | `--profile` and `NEON_API_KEY` | the profile |\n* | `NEON_API_KEY` and `NEON_PROFILE` | the key, and the ignored profile is named in a warning |\n* | `--profile` or `NEON_PROFILE` alone | that profile |\n* | nothing | `DEFAULT` |\n*\n* Two explicit flags throw rather than picking a winner. They express different intents —\n* `--api-key` supplies a credential, `--profile` selects a stored one — so there is no\n* reading of the command that makes both true, and guessing is how the original bug behaved.\n*\n* When both are merely ambient, the key wins. That keeps CI exactly as it was: a pipeline\n* that injects `NEON_API_KEY` must not change behaviour because a `NEON_PROFILE` leaked into\n* the environment. It warns instead of staying silent, because a disregarded account\n* selection is precisely what nobody noticed last time.\n*\n* `auth` and the `profile` subcommands do not use any of this. They read the same flags with\n* different meanings — `neon auth --profile work` names where to *write* a credential, and\n* `neon profile create work --api-key …` names one to *store* — so their callers skip\n* selection entirely rather than passing exemptions down here.\n*/\nlet inputs = {\n\tapiKeyFlag: \"\",\n\tapiKeyEnv: \"\",\n\tprofileEnv: \"\"\n};\nconst recordCredentialInputs = (recorded) => {\n\tinputs = recorded;\n};\nconst credentialInputs = () => inputs;\nconst selectCredential = ({ apiKeyFlag, profileFlag, apiKeyEnv, profileEnv }) => {\n\tconst flagKey = nonEmpty(apiKeyFlag);\n\tconst flagProfile = nonEmpty(profileFlag);\n\tif (flagKey !== void 0 && flagProfile !== void 0) throw new Error(\"Pass either --api-key or --profile, not both. --api-key supplies a credential directly; --profile selects a stored one.\");\n\tif (flagKey !== void 0) return {\n\t\tsource: \"explicit-api-key\",\n\t\tapiKey: flagKey\n\t};\n\tif (flagProfile !== void 0) return {\n\t\tsource: \"profile\",\n\t\tprofile: flagProfile,\n\t\texplicit: true\n\t};\n\tconst envKey = nonEmpty(apiKeyEnv);\n\tconst envProfile = nonEmpty(profileEnv);\n\tif (envKey !== void 0) return {\n\t\tsource: \"ambient-api-key\",\n\t\tapiKey: envKey,\n\t\t...envProfile !== void 0 ? { ignoredProfile: envProfile } : {}\n\t};\n\treturn {\n\t\tsource: \"profile\",\n\t\tprofile: envProfile ?? \"DEFAULT\",\n\t\texplicit: envProfile !== void 0\n\t};\n};\n/** The warning for an ambient key that displaced an ambient profile, or `null`. */\nconst displacedProfileWarning = (selection) => selection.source === \"ambient-api-key\" && selection.ignoredProfile !== void 0 ? `NEON_API_KEY is set, so profile \"${selection.ignoredProfile}\" from NEON_PROFILE was ignored. Pass --profile ${selection.ignoredProfile} to use it instead.` : null;\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\n//#endregion\nexport { credentialInputs, displacedProfileWarning, recordCredentialInputs, selectCredential };\n\n//# sourceMappingURL=auth_selection.js.map","import { writeSecretFile } from \"./secure_file.js\";\nimport { readFileSync } from \"node:fs\";\n//#region src/credentials.ts\n/**\n* # Stored credentials — one file per account, two kinds\n*\n* A profile points at exactly one credentials file (see `./profiles.ts`), and that file says\n* what kind of credential it holds. Adding API-key support this way rather than adding a\n* second pointer to `profiles.json` keeps a profile what it already was — one name, one path\n* — and means `profiles.json` needs no schema change at all.\n*\n* ```json\n* // oauth: every file written before this existed. An absent `type` means this.\n* { \"access_token\": \"…\", \"refresh_token\": \"…\", \"expires_at\": 1786…, \"user_id\": \"…\" }\n*\n* // api_key, stored by `neon profile create --api-key`\n* { \"type\": \"api_key\", \"api_key\": \"napi_…\", \"user_id\": \"…\" }\n*\n* // api_key minted by `--mint --org-id`, which records the scope it was issued at\n* { \"type\": \"api_key\", \"api_key\": \"napi_…\", \"key_id\": 123, \"org_id\": \"org-…\" }\n* ```\n*\n* ## One profile, one kind\n*\n* A credentials file holds an API key or an OAuth session, never both, and `type` states\n* which. An earlier draft let the two coexist — the idea being that a key could keep the\n* session it was minted from and so rotate without a browser. It did not survive review, for\n* two reasons that are worth recording so nobody rebuilds it:\n*\n* 1. **It never worked.** The resolver returned the key without testing it, so a revoked key\n* failed to mint and never fell back to the session sitting beside it.\n* 2. **It could mix accounts.** Nothing compared the identity of the credential being written\n* with the one already there, so a profile could hold one account's session and another's\n* key, told apart only by a single string. Flip or lose `type` and the profile silently\n* becomes a different person.\n*\n* Recovery from a dead key is therefore one browser login — `neon profile create <name>\n* --mint --force` — which is what the retained session was supposed to save and never did.\n*\n* ## Older releases\n*\n* A CLI predating this reads the pointer, finds no `type` it understands, ignores it, and\n* looks for `access_token`. An `api_key` profile has none, so an older release falls through\n* to its browser login rather than crashing. That it does not crash is why `credentials`\n* stays a required pointer: an entry without one makes 2.41 and 2.42 throw\n* `ERR_INVALID_ARG_TYPE` from `resolveEntryPath`.\n*/\nconst OAUTH = \"oauth\";\nconst API_KEY = \"api_key\";\n/**\n* Which credential in this file authenticates, by declaration alone.\n*\n* An unrecognised `type` throws rather than falling back to `oauth`. A file we cannot\n* interpret is a misconfiguration the user has to see: treating it as OAuth would send them\n* to a browser login that silently replaces a credential they meant to keep, and treating it\n* as an API key would authenticate with whatever `api_key` happened to be there.\n*\n* This deliberately does not check that an `api_key` file has a key — `neon profile list`\n* needs the kind of a file it is not about to authenticate with, and must be able to report a\n* broken one rather than throwing halfway through a table.\n*/\nconst credentialKind = (credentials, at) => {\n\tconst declared = credentials.type;\n\tif (declared === void 0 || declared === \"oauth\") return OAUTH;\n\tif (declared === \"api_key\") return API_KEY;\n\tthrow new Error(`${at.path} declares a \"type\" this version does not understand. Expected \"${OAUTH}\" or \"${API_KEY}\". ${repair(at)}`);\n};\n/**\n* The way out of a credentials file that cannot be read.\n*\n* One sentence, shared by every such error, because they all have the same two answers: write\n* a new credential over it, or delete it and start again.\n*/\nconst repair = (at) => `Replace it deliberately with \\`neon profile create ${at.profile} --force\\`, or delete the file.`;\n/**\n* Resolve what to authenticate with, validating that the declared kind is actually usable.\n*\n* An `api_key` file with no key is a hard error rather than a fall-through to OAuth: the user\n* asked for a key, and quietly opening a browser instead would replace the credential they\n* were trying to fix.\n*/\nconst interpretCredentials = (credentials, at) => {\n\tif (credentialKind(credentials, at) === \"oauth\") return { kind: OAUTH };\n\tconst apiKey = nonEmpty(credentials.api_key);\n\tif (apiKey === void 0) throw new Error(`${at.path} declares \"type\": \"${API_KEY}\" but has no \"api_key\" value. ${repair(at)}`);\n\treturn {\n\t\tkind: API_KEY,\n\t\tapiKey\n\t};\n};\n/**\n* Read and classify a credentials file, without deciding what to do about it.\n*\n* A permission or I/O error still throws: there may be a perfectly good credential here that\n* we cannot see, and treating that as absent would send the user to a browser login that\n* overwrites it.\n*/\nconst inspectCredentials = (path) => {\n\tlet contents;\n\ttry {\n\t\tcontents = readFileSync(path, \"utf8\");\n\t} catch (err) {\n\t\tif (err.code === \"ENOENT\") return { kind: \"absent\" };\n\t\tthrow err;\n\t}\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(contents);\n\t} catch {\n\t\treturn {\n\t\t\tkind: \"unusable\",\n\t\t\treason: `${path} is not valid JSON, so the credential in it cannot be read`\n\t\t};\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) return {\n\t\tkind: \"unusable\",\n\t\treason: `${path} does not contain a credentials object`\n\t};\n\treturn {\n\t\tkind: \"ok\",\n\t\tcredentials: parsed\n\t};\n};\n/**\n* The credential at `path`, or `null` when the file is not there.\n*\n* A damaged file is an error, not an absence. Treating it as absent — which is what this used to\n* do — meant any read-only command could repair it by starting a browser sign-in and overwriting\n* it, **possibly as a different account**, with the user never having asked for a repair and no\n* way back to whatever was in the file. Failing here costs one deliberate command; the message\n* names it.\n*\n* `profile list` and telemetry use {@link inspectCredentials} instead, because describing a\n* broken credential is not the same as using one.\n*/\nconst readCredentials = (at) => {\n\tconst read = inspectCredentials(at.path);\n\tif (read.kind === \"unusable\") throw new Error(`${read.reason}. ${repair(at)}`);\n\treturn read.kind === \"ok\" ? read.credentials : null;\n};\nconst writeCredentials = (path, credentials) => {\n\twriteSecretFile(path, JSON.stringify(credentials));\n};\n/**\n* Build an `api_key` credentials object. Nothing from a previous credential is carried over.\n*\n* The scope is stored because it is not recoverable from the secret: `rotate-key` has to mint\n* the replacement on the same endpoint, and an org or project key minted as an account key\n* would silently widen what the profile reaches.\n*/\nconst apiKeyCredentials = ({ apiKey, keyId, userId, scope }) => ({\n\ttype: API_KEY,\n\tapi_key: apiKey,\n\t...keyId !== void 0 ? { key_id: keyId } : {},\n\t...userId !== void 0 ? { user_id: userId } : {},\n\t...scope?.orgId !== void 0 ? { org_id: scope.orgId } : {},\n\t...scope?.projectId !== void 0 ? { project_id: scope.projectId } : {}\n});\n/** The scope recorded on a stored credential. */\nconst scopeOf = (credentials) => ({\n\t...typeof credentials.org_id === \"string\" ? { orgId: credentials.org_id } : {},\n\t...typeof credentials.project_id === \"string\" ? { projectId: credentials.project_id } : {}\n});\n/** How to describe a scope in output. */\nconst describeScope = (scope) => {\n\tif (scope.projectId !== void 0) return `project ${scope.projectId}`;\n\tif (scope.orgId !== void 0) return `org ${scope.orgId}`;\n\treturn \"account\";\n};\nfunction nonEmpty(value) {\n\tif (typeof value !== \"string\") return void 0;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? void 0 : trimmed;\n}\n/**\n* Whether a stored credential is the same secret as the one about to replace it.\n*\n* Re-storing the key a profile already holds is a no-op, not a replacement — and retiring it\n* would revoke the credential the command has just committed to. Trimmed on both sides, because\n* a key read from a file or a pipe arrives with a trailing newline.\n*/\nconst isSameCredential = (existingKey, replacementKey) => {\n\tif (existingKey === void 0 || replacementKey === void 0) return false;\n\tconst trimmed = existingKey.trim();\n\treturn trimmed !== \"\" && trimmed === replacementKey.trim();\n};\n//#endregion\nexport { API_KEY, OAUTH, apiKeyCredentials, credentialKind, describeScope, inspectCredentials, interpretCredentials, isSameCredential, readCredentials, scopeOf, writeCredentials };\n\n//# sourceMappingURL=credentials.js.map","import {\n\tdisplacedProfileWarning,\n\tselectCredential,\n} from \"@neon-internals/cli-core/auth_selection\";\nimport {\n\tinspectCredentials,\n\tinterpretCredentials,\n} from \"@neon-internals/cli-core/credentials\";\nimport { configDir, resolveConfigFile } from \"@neon-internals/cli-core/paths\";\nimport {\n\tDEFAULT_PROFILE,\n\tresolveProfile,\n} from \"@neon-internals/cli-core/profiles\";\n\n/**\n * Resolve the Neon API key for a `neon-env` CLI invocation.\n *\n * Precedence is the `neon` CLI's, from the same module: **an explicit flag beats an ambient\n * environment variable.** `--api-key` and `--profile` together is an error; `--profile` beats\n * `NEON_API_KEY`; `--api-key` beats `NEON_PROFILE`; two ambient sources resolve to the key.\n *\n * Sharing that decision rather than restating it is the point. An earlier version of this file\n * checked `NEON_API_KEY` before the selected profile, so `NEON_API_KEY=… neon-env run --profile\n * work` silently used the wrong account — the very bug this feature fixes in `neon`.\n *\n * The CLI owns the resolution because `@neon/config` and `@neon/env`'s root export are\n * deliberately environment- and filesystem-agnostic: they accept an explicit `apiKey` and\n * nothing else, so the ambient sources a *user* expects have to be read out here.\n */\nexport function resolveApiKey(options: {\n\tapiKey?: string;\n\tprofile?: string;\n\tenv?: NodeJS.ProcessEnv;\n\t/** Where to say that an exported key displaced an exported profile. Defaults to stderr. */\n\twarn?: (message: string) => void;\n}): string | undefined {\n\tconst env = options.env ?? process.env;\n\tconst selection = selectCredential({\n\t\t...(options.apiKey !== undefined ? { apiKeyFlag: options.apiKey } : {}),\n\t\t...(options.profile !== undefined\n\t\t\t? { profileFlag: options.profile }\n\t\t\t: {}),\n\t\t...(env.NEON_API_KEY !== undefined\n\t\t\t? { apiKeyEnv: env.NEON_API_KEY }\n\t\t\t: {}),\n\t\t...(env.NEON_PROFILE !== undefined\n\t\t\t? { profileEnv: env.NEON_PROFILE }\n\t\t\t: {}),\n\t});\n\n\t// Sharing the decision is only half of it. The disclosure is the half that keeps a\n\t// displaced profile from being the original bug in a quieter form: `NEON_API_KEY=…\n\t// NEON_PROFILE=work neon-env run` legitimately uses the key, and saying nothing leaves the\n\t// user believing they ran as `work`. `neon` has warned here from the start; this did not.\n\tconst displaced = displacedProfileWarning(selection);\n\tif (displaced !== null) {\n\t\tconst warn =\n\t\t\toptions.warn ??\n\t\t\t((message: string) => process.stderr.write(`${message}\\n`));\n\t\twarn(displaced);\n\t}\n\n\tif (selection.source !== \"profile\") return selection.apiKey;\n\treturn readStoredCredential(selection, env);\n}\n\n/**\n * The credential stored for the selected profile.\n *\n * Two different situations, deliberately not merged. A **missing** credential under `DEFAULT` is\n * the ordinary not-signed-in state and resolves to no key; under a profile the user named it is\n * an error, because reporting a missing credential would hide that the real problem is the name\n * they typed. A **damaged** credential is always an error: the file is there, it is not an\n * absence, and no amount of signing in elsewhere explains it.\n */\nfunction readStoredCredential(\n\tselection: { profile: string; explicit: boolean },\n\tenv: NodeJS.ProcessEnv,\n): string | undefined {\n\tconst { profile, explicit } = selection;\n\t/**\n\t * An *absence* is only an error when the user named the profile. Not being signed in under\n\t * `DEFAULT` is the ordinary state, and the library's `PLATFORM_MISSING_API_KEY` says it\n\t * better than a stack trace.\n\t */\n\tconst absent = (reason: string): undefined => {\n\t\tif (explicit) throw new Error(reason);\n\t\treturn undefined;\n\t};\n\n\tlet path: string;\n\ttry {\n\t\tpath =\n\t\t\tprofile === DEFAULT_PROFILE\n\t\t\t\t? // Per *file*, so an install predating the rename still finds its\n\t\t\t\t\t// `credentials.json` in the legacy `neonctl` directory, in place.\n\t\t\t\t\tresolveConfigFile(\"credentials.json\", { env }).path\n\t\t\t\t: // From the config root, not from wherever `credentials.json` happens to live:\n\t\t\t\t\t// that file can still be in `neonctl/` while `profiles.json` is in `neon/`,\n\t\t\t\t\t// and deriving one from the other loses every named profile.\n\t\t\t\t\tresolveProfile(configDir({ env }), profile).credentialsPath;\n\t} catch (err) {\n\t\t// An unknown profile name is a naming error whoever typed it can fix, so it is fatal\n\t\t// either way — it cannot be reported as \"not signed in\".\n\t\tthrow err instanceof Error ? err : new Error(String(err));\n\t}\n\n\tconst read = inspectCredentials(path);\n\tif (read.kind === \"absent\") {\n\t\treturn absent(\n\t\t\t`Profile \"${profile}\" has no stored credential at ${path}. Sign in with \\`neon profile create ${profile}\\`.`,\n\t\t);\n\t}\n\n\t// A file that exists but cannot be read is never an absence, named or not. Returning\n\t// `undefined` here reported \"no API key\" for a credential that is present and broken,\n\t// which sends the reader looking for a missing login instead of at the damaged file — and\n\t// under `neon` the same file is a hard error, so the two CLIs disagreed about it.\n\tif (read.kind === \"unusable\") {\n\t\tthrow new Error(\n\t\t\t`${read.reason}. Replace it deliberately with \\`neon profile create ${profile} --force\\`, or delete the file.`,\n\t\t);\n\t}\n\n\tconst credential = interpretCredentials(read.credentials, {\n\t\tpath,\n\t\tprofile,\n\t});\n\tif (credential.kind === \"api_key\") return credential.apiKey;\n\tconst token = read.credentials.access_token;\n\tif (typeof token === \"string\" && token.trim() !== \"\") return token.trim();\n\tthrow new Error(\n\t\t`Profile \"${profile}\" holds a browser sign-in with no usable token at ${path}. Sign in again with \\`neon auth --profile ${profile}\\`.`,\n\t);\n}\n\nexport { DEFAULT_PROFILE };\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, resolve } from \"node:path\";\n\n/**\n * Resolved project + branch context for the `neon-env` CLI. The CLI owns this resolution\n * (flags → `NEON_*` env → `.neon[/project.json]` file) so the `@neon/env` library\n * functions can stay filesystem- and env-agnostic.\n */\nexport interface ResolvedContext {\n\tprojectId: string;\n\t/** Branch ref — a name (preferred for readability) or an id (`br-…`). */\n\tbranch: string;\n}\n\nexport interface ResolveContextOptions {\n\tprojectId?: string;\n\tbranch?: string;\n\tcwd: string;\n\tenv?: NodeJS.ProcessEnv;\n}\n\n/**\n * Resolve `projectId` and `branch` for a CLI invocation. Precedence (each wins over the\n * next): explicit flag → `NEON_*` env var → `.neon[/project.json]` walked up from `cwd`.\n *\n * Returns the resolved values plus a list of human-readable reasons for any field that\n * could not be resolved (so the caller can render one combined error).\n */\nexport function resolveContext(\n\toptions: ResolveContextOptions,\n): { ok: true; context: ResolvedContext } | { ok: false; missing: string[] } {\n\tconst env = options.env ?? process.env;\n\tconst file = findNeonFile(options.cwd);\n\n\tconst projectId =\n\t\tnonEmpty(options.projectId) ??\n\t\tnonEmpty(env.NEON_PROJECT_ID) ??\n\t\tfile?.projectId;\n\n\t// A branch ref — name (preferred) or id. `NEON_BRANCH` carries the name; `NEON_BRANCH_ID`\n\t// is the legacy id-only var. The `.neon` file pins `branch` (name) via `neonctl link`,\n\t// with legacy `branchId` still honored. fetchEnv resolves either form by name or id.\n\tconst branch =\n\t\tnonEmpty(options.branch) ??\n\t\tnonEmpty(env.NEON_BRANCH) ??\n\t\tnonEmpty(env.NEON_BRANCH_ID) ??\n\t\tfile?.branch;\n\n\tconst missing: string[] = [];\n\tif (!projectId) {\n\t\tmissing.push(\n\t\t\t\"project id — pass `--project-id`, set `NEON_PROJECT_ID`, or add `projectId` to `.neon` (run `npx neon link`).\",\n\t\t);\n\t}\n\tif (!branch) {\n\t\tmissing.push(\n\t\t\t\"branch — pass `--branch`, set `NEON_BRANCH`/`NEON_BRANCH_ID`, or add `branch` to `.neon` (run `npx neon link` / `neon checkout <branch>`).\",\n\t\t);\n\t}\n\tif (!projectId || !branch) return { ok: false, missing };\n\n\treturn {\n\t\tok: true,\n\t\tcontext: { projectId, branch },\n\t};\n}\n\ninterface NeonFile {\n\tprojectId?: string;\n\t/** Branch ref — name (preferred) or id. Reads `branch`, falling back to legacy `branchId`. */\n\tbranch?: string;\n}\n\n/**\n * Walk up from `cwd` looking for `.neon/project.json` (preferred) or `.neon` (neonctl\n * convention). Stops at the first `.git` directory or the home directory. Read-only.\n */\nfunction findNeonFile(cwd: string): NeonFile | null {\n\tlet current = resolve(cwd);\n\tconst stop = resolve(homedir());\n\tlet lastSeen: string | null = null;\n\n\twhile (true) {\n\t\tconst parsed =\n\t\t\treadNeonFileAt(resolve(current, \".neon\", \"project.json\")) ??\n\t\t\treadNeonFileAt(resolve(current, \".neon\"));\n\t\tif (parsed) return parsed;\n\n\t\tif (current === stop) return null;\n\t\tif (existsSync(resolve(current, \".git\"))) return null;\n\n\t\tconst parent = dirname(current);\n\t\tif (parent === current || parent === lastSeen) return null;\n\t\tlastSeen = current;\n\t\tcurrent = parent;\n\t}\n}\n\nfunction readNeonFileAt(path: string): NeonFile | null {\n\tif (!isFile(path)) return null;\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(path, \"utf-8\");\n\t} catch {\n\t\treturn null;\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed))\n\t\treturn null;\n\tconst obj = parsed as Record<string, unknown>;\n\tconst out: NeonFile = {};\n\tif (typeof obj.projectId === \"string\" && obj.projectId !== \"\")\n\t\tout.projectId = obj.projectId;\n\t// Prefer the `branch` field (name or id, written by `neonctl link`); fall back to the\n\t// legacy id-only `branchId`.\n\tconst branch =\n\t\ttypeof obj.branch === \"string\" && obj.branch !== \"\"\n\t\t\t? obj.branch\n\t\t\t: typeof obj.branchId === \"string\" && obj.branchId !== \"\"\n\t\t\t\t? obj.branchId\n\t\t\t\t: undefined;\n\tif (branch) out.branch = branch;\n\treturn out;\n}\n\nfunction isFile(path: string): boolean {\n\ttry {\n\t\treturn statSync(path).isFile();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = value.trim();\n\treturn trimmed === \"\" ? undefined : trimmed;\n}\n","import { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport {\n\tConfigLoadError,\n\tErrorCode,\n\tloadConfigFromFile,\n\tMissingContextError,\n\ttype NeonApi,\n\tPlatformError,\n} from \"@neon/config/v1\";\nimport { fetchEnvReusingSecrets } from \"@neon-internals/env-core/reuse-secrets\";\nimport { resolveApiKey } from \"./resolve-api-key.js\";\nimport { resolveContext } from \"./resolve-context.js\";\n\n/** File `env run` reads to layer one-time auth keys. Matches the Vercel/Next.js convention. */\nconst DEFAULT_ENV_FILE = \".env.local\";\n\n/**\n * Cross-cutting environment a CLI command is allowed to touch. Injected so tests can drive\n * the handler with a custom NeonApi and a controlled `cwd` without spawning child\n * processes.\n */\nexport interface CommandEnv {\n\tcwd: string;\n\t/**\n\t * When set, used directly as the NeonApi. When omitted, the real adapter is built from\n\t * the key {@link resolveApiKey} resolves (`--api-key` → `NEON_API_KEY` → the Neon CLI's\n\t * stored credentials).\n\t */\n\tapi?: NeonApi;\n}\n\nexport interface CommandResult {\n\t/** Process exit code. `0` for success, non-zero for failure. */\n\texitCode: number;\n\t/** Text intended for stdout. */\n\tstdout: string;\n\t/** Text intended for stderr (human-readable status / error messages). */\n\tstderr: string;\n\t/** Optional structured debug payload — printed only when `--debug` is passed. */\n\tdebugInfo?: string;\n}\n\n/**\n * Inputs needed to resolve a branch and fetch its env, shared by `run` and `export`: an\n * optional explicit `neon.ts` path, project/branch overrides, and an API key. Everything\n * ambient — `.neon`, `NEON_*` env, the Neon CLI's stored credentials — is resolved by the\n * CLI (see `resolveContext` and `resolveApiKey`), never by the library.\n */\nexport interface EnvResolveOptions {\n\tconfigPath?: string;\n\tprojectId?: string;\n\tbranch?: string;\n\tapiKey?: string;\n\t/** Neon CLI profile whose stored credential to use. `--profile`, else `NEON_PROFILE`. */\n\tprofile?: string;\n}\n\nexport interface EnvRunCommandOptions extends EnvResolveOptions {\n\t/** The user command to spawn (after `--`). The first element is the executable. */\n\tcommand: string[];\n}\n\n/**\n * Implementation of `neon-env run -- <cmd...>`. Loads `neon.ts`, fetches the env from\n * Neon, then spawns the user-supplied command with the env vars injected on top of the\n * inherited `process.env`. Stdio is inherited so interactive dev servers keep working.\n * The parent process exits with the child's exit code.\n */\nexport async function runEnvRun(\n\toptions: EnvRunCommandOptions,\n\tctx: CommandEnv,\n): Promise<CommandResult> {\n\tif (options.command.length === 0) {\n\t\treturn failure(\n\t\t\t[\n\t\t\t\t\"`env run` requires a command to spawn.\",\n\t\t\t\t\"Usage: neon-env run -- <command> [args...]\",\n\t\t\t\t\"Example: neon-env run -- npm run dev\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\t// The CLI owns project/branch resolution (flags → NEON_* env → .neon file) so the\n\t// library functions stay filesystem/env-agnostic.\n\tconst resolved = resolveContext({\n\t\tcwd: ctx.cwd,\n\t\t...(options.projectId ? { projectId: options.projectId } : {}),\n\t\t...(options.branch ? { branch: options.branch } : {}),\n\t});\n\tif (!resolved.ok) {\n\t\treturn failure(\n\t\t\t[\n\t\t\t\t\"`env run` could not resolve the Neon project and branch:\",\n\t\t\t\t...resolved.missing.map((m) => ` - ${m}`),\n\t\t\t].join(\"\\n\"),\n\t\t\t3,\n\t\t);\n\t}\n\n\tlet injected: Record<string, string>;\n\ttry {\n\t\tinjected = await loadConfigAndFetchEnv(options, ctx, resolved.context);\n\t} catch (err) {\n\t\treturn handleError(err);\n\t}\n\n\tconst [executable, ...args] = options.command;\n\tconst exitCode = await spawnAndWait(executable, args, {\n\t\tcwd: ctx.cwd,\n\t\tenv: { ...process.env, ...injected },\n\t});\n\treturn { exitCode, stdout: \"\", stderr: \"\" };\n}\n\nexport interface EnvExportCommandOptions extends EnvResolveOptions {\n\t/** Output format. `dotenv` (KEY=value lines) by default; `json` for tooling / bulk loaders. */\n\tformat?: \"dotenv\" | \"json\";\n}\n\n/**\n * Implementation of `neon-env export`. Resolves the branch's Neon env the same way `run`\n * does (neon.ts policy + linked branch), then writes it to stdout — as dotenv lines or JSON —\n * instead of spawning a process, so other env tools can consume it. For example, varlock can\n * bulk-load it with `@setValuesBulk(exec(\"neon-env export --format json\"), format=json)`.\n */\nexport async function runEnvExport(\n\toptions: EnvExportCommandOptions,\n\tctx: CommandEnv,\n): Promise<CommandResult> {\n\tconst resolved = resolveContext({\n\t\tcwd: ctx.cwd,\n\t\t...(options.projectId ? { projectId: options.projectId } : {}),\n\t\t...(options.branch ? { branch: options.branch } : {}),\n\t});\n\tif (!resolved.ok) {\n\t\treturn failure(\n\t\t\t[\n\t\t\t\t\"`env export` could not resolve the Neon project and branch:\",\n\t\t\t\t...resolved.missing.map((m) => ` - ${m}`),\n\t\t\t].join(\"\\n\"),\n\t\t\t3,\n\t\t);\n\t}\n\n\tlet entries: Record<string, string>;\n\ttry {\n\t\tentries = await loadConfigAndFetchEnv(options, ctx, resolved.context);\n\t} catch (err) {\n\t\treturn handleError(err);\n\t}\n\n\tconst stdout =\n\t\toptions.format === \"json\"\n\t\t\t? `${JSON.stringify(entries, null, 2)}\\n`\n\t\t\t: toDotenv(entries);\n\treturn { exitCode: 0, stdout, stderr: \"\" };\n}\n\n/** Render an env map as dotenv `KEY=value` lines, quoting values that need it. */\nfunction toDotenv(entries: Record<string, string>): string {\n\tconst lines = Object.entries(entries).map(([key, value]) =>\n\t\tformatDotenvLine(key, value),\n\t);\n\treturn lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\";\n}\n\n/**\n * Render a single `KEY=value` dotenv line, double-quoting (and escaping) values that contain\n * whitespace, `#`, quotes, or `=` so connection strings round-trip through dotenv parsers.\n */\nfunction formatDotenvLine(key: string, value: string): string {\n\tif (!/[\\s#\"'=]/.test(value)) return `${key}=${value}`;\n\tconst escaped = value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n\treturn `${key}=\"${escaped}\"`;\n}\n\n/**\n * Load `neon.ts`, then resolve the branch env for the explicitly-resolved project + branch.\n * Layers `.env.local` (next to the config file) into the env source so re-runs keep the\n * one-time secrets the Neon API only returns once — the branch credential's, and any Auth\n * values a pre-`base_url` integration can no longer report. Uses\n * {@link fetchEnvReusingSecrets} rather than a bare `fetchEnv` so a run that already has a\n * working credential verifies and keeps it instead of minting another one per invocation.\n */\nasync function loadConfigAndFetchEnv(\n\toptions: EnvResolveOptions,\n\tctx: CommandEnv,\n\tresolved: { projectId: string; branch: string },\n): Promise<Record<string, string>> {\n\tconst { config, resolvedPath } = await loadConfigFromFile({\n\t\t...(options.configPath ? { path: options.configPath } : {}),\n\t\tcwd: ctx.cwd,\n\t});\n\tconst envFileSource = join(dirname(resolvedPath), DEFAULT_ENV_FILE);\n\tconst fileEnv = existsSync(envFileSource)\n\t\t? parseEnvFile(readFileSync(envFileSource, \"utf-8\"))\n\t\t: {};\n\tconst apiKey = resolveApiKey({\n\t\t...(options.apiKey ? { apiKey: options.apiKey } : {}),\n\t\t...(options.profile ? { profile: options.profile } : {}),\n\t});\n\tconst { vars } = await fetchEnvReusingSecrets(config, {\n\t\tprojectId: resolved.projectId,\n\t\tbranch: resolved.branch,\n\t\tenv: { ...process.env, ...fileEnv },\n\t\t...(ctx.api ? { api: ctx.api } : {}),\n\t\t...(apiKey ? { apiKey } : {}),\n\t});\n\treturn vars;\n}\n\n/**\n * Spawn a child process with stdio inherited so dev servers stay interactive. Resolves\n * with the child's exit code (treating signal terminations as code 1 so the CLI surfaces\n * a non-zero exit consistently).\n */\nfunction spawnAndWait(\n\tcommand: string,\n\targs: string[],\n\toptions: { cwd: string; env: Record<string, string | undefined> },\n): Promise<number> {\n\treturn new Promise((resolve) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tenv: options.env,\n\t\t\tstdio: \"inherit\",\n\t\t});\n\t\tchild.on(\"error\", (err) => {\n\t\t\tprocess.stderr.write(\n\t\t\t\t`neon-env run: failed to spawn '${command}': ${err.message}\\n`,\n\t\t\t);\n\t\t\tresolve(1);\n\t\t});\n\t\tchild.on(\"exit\", (code, signal) => {\n\t\t\tif (typeof code === \"number\") {\n\t\t\t\tresolve(code);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (signal) {\n\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t`neon-env run: child terminated by signal ${signal}\\n`,\n\t\t\t\t);\n\t\t\t\tresolve(1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(1);\n\t\t});\n\t});\n}\n\nfunction parseEnvFile(body: string): NodeJS.ProcessEnv {\n\tconst out: NodeJS.ProcessEnv = {};\n\tfor (const line of body.split(\"\\n\")) {\n\t\tconst parsed = parseEnvLine(line);\n\t\tif (parsed) out[parsed.key] = parsed.value;\n\t}\n\treturn out;\n}\n\nfunction parseEnvLine(line: string): { key: string; value: string } | null {\n\tconst match = line.match(\n\t\t/^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/,\n\t);\n\tconst key = match?.[1];\n\tconst rawValue = match?.[2];\n\tif (key === undefined || rawValue === undefined) return null;\n\treturn { key, value: unescapeEnvValue(rawValue.trim()) };\n}\n\nfunction unescapeEnvValue(value: string): string {\n\tif (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) {\n\t\treturn value.slice(1, -1).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n\t}\n\tif (value.length >= 2 && value.startsWith(\"'\") && value.endsWith(\"'\")) {\n\t\treturn value.slice(1, -1);\n\t}\n\treturn value;\n}\n\n/**\n * Stable exit code per `PlatformError` code. Mirrors the table in the config package so\n * shell pipelines can branch on the specific failure mode without parsing free text.\n */\nconst EXIT_CODE_BY_PLATFORM_ERROR_CODE: Readonly<Record<string, number>> = {\n\t[ErrorCode.MissingApiKey]: 1,\n\t[ErrorCode.Unauthorized]: 6,\n\t[ErrorCode.Forbidden]: 7,\n\t[ErrorCode.NotFound]: 8,\n\t[ErrorCode.RateLimited]: 9,\n\t[ErrorCode.NetworkError]: 10,\n\t[ErrorCode.ServerError]: 11,\n\t[ErrorCode.Locked]: 11,\n\t[ErrorCode.InternalError]: 99,\n};\n\nfunction handleError(err: unknown): CommandResult {\n\tif (err instanceof MissingContextError)\n\t\treturn errorResult(err, `Missing context: ${err.message}`, 3);\n\tif (err instanceof ConfigLoadError)\n\t\treturn errorResult(err, `Failed to load config: ${err.message}`, 4);\n\t// The library's own wording is right for a library (\"this package never reads\n\t// NEON_API_KEY on your behalf\") and wrong here: `neon-env` does read it. Render the\n\t// chain this CLI actually implements, the same way an unresolved context is rendered.\n\tif (err instanceof PlatformError && err.code === ErrorCode.MissingApiKey) {\n\t\treturn errorResult(\n\t\t\terr,\n\t\t\t[\n\t\t\t\t\"No Neon API key. `neon-env` looks for one in this order:\",\n\t\t\t\t\" - the `--api-key` flag\",\n\t\t\t\t\" - the `NEON_API_KEY` environment variable\",\n\t\t\t\t\" - `credentials.json` in `NEONCTL_CONFIG_DIR` (else `~/.config/neonctl`) — run `neon auth` to create it\",\n\t\t\t].join(\"\\n\"),\n\t\t\tEXIT_CODE_BY_PLATFORM_ERROR_CODE[ErrorCode.MissingApiKey] ?? 1,\n\t\t);\n\t}\n\tif (err instanceof PlatformError) {\n\t\tconst exitCode = EXIT_CODE_BY_PLATFORM_ERROR_CODE[err.code];\n\t\tif (exitCode !== undefined)\n\t\t\treturn errorResult(err, err.message, exitCode);\n\t\treturn errorResult(err, `[${err.code}] ${err.message}`, 5);\n\t}\n\tif (err instanceof Error) return errorResult(err, err.message, 1);\n\treturn failure(String(err), 1);\n}\n\nfunction errorResult(\n\terr: unknown,\n\tmessage: string,\n\texitCode: number,\n): CommandResult {\n\tconst result: CommandResult = {\n\t\texitCode,\n\t\tstdout: \"\",\n\t\tstderr: `${message}\\n`,\n\t};\n\tconst debug = buildDebugInfo(err);\n\tif (debug) result.debugInfo = debug;\n\treturn result;\n}\n\nfunction buildDebugInfo(err: unknown): string | undefined {\n\tif (!(err instanceof Error)) return undefined;\n\tconst lines: string[] = [];\n\tif (err instanceof PlatformError) {\n\t\tlines.push(`code : ${err.code}`);\n\t\tif (Object.keys(err.details).length > 0) {\n\t\t\tlines.push(`details : ${JSON.stringify(err.details, null, 2)}`);\n\t\t}\n\t}\n\tif (err.cause instanceof Error) {\n\t\tlines.push(`cause : ${err.cause.name}: ${err.cause.message}`);\n\t}\n\tif (err.stack) {\n\t\tlines.push(err.stack);\n\t}\n\treturn lines.length > 0 ? lines.join(\"\\n\") : undefined;\n}\n\nfunction failure(message: string, exitCode = 1): CommandResult {\n\treturn { exitCode, stdout: \"\", stderr: `${message}\\n` };\n}\n","#!/usr/bin/env node\n\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\nimport {\n\ttype CommandResult,\n\trunEnvExport,\n\trunEnvRun,\n} from \"./lib/cli/commands.js\";\n\nconst pkgVersion = readPackageVersion();\n\nconst argv = yargs(hideBin(process.argv))\n\t.scriptName(\"neon-env\")\n\t.usage(\"$0 <command> [options]\")\n\t.parserConfiguration({ \"populate--\": true })\n\t.option(\"debug\", {\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t\tdescribe:\n\t\t\t\"Print stack traces and structured error details when something fails\",\n\t})\n\t.command(\n\t\t\"run\",\n\t\t\"Run a command with Neon env vars (from your neon.ts policy) injected into its environment. Use `--` to separate the command: `neon-env run -- npm run dev`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.command(\n\t\t\"export\",\n\t\t\"Print the branch's Neon env vars (from your neon.ts policy) to stdout, as dotenv lines or JSON. Useful for piping into other env tools, e.g. `neon-env export --format json`.\",\n\t\t(y) =>\n\t\t\ty\n\t\t\t\t.option(\"format\", {\n\t\t\t\t\tchoices: [\"dotenv\", \"json\"] as const,\n\t\t\t\t\tdefault: \"dotenv\",\n\t\t\t\t\tdescribe: \"Output format: dotenv (KEY=value lines) or json\",\n\t\t\t\t})\n\t\t\t\t.option(\"config\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Path to neon.ts (defaults to walking up from cwd)\",\n\t\t\t\t})\n\t\t\t\t.option(\"project-id\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Override the .neon/project.json projectId\",\n\t\t\t\t})\n\t\t\t\t.option(\"branch\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Branch name or id to target (overrides .neon / NEON_BRANCH / NEON_BRANCH_ID)\",\n\t\t\t\t})\n\t\t\t\t.option(\"api-key\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe: \"Neon API key (defaults to NEON_API_KEY)\",\n\t\t\t\t})\n\t\t\t\t.option(\"profile\", {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdescribe:\n\t\t\t\t\t\t\"Neon CLI profile whose stored credential to use (defaults to NEON_PROFILE, else DEFAULT)\",\n\t\t\t\t}),\n\t)\n\t.demandCommand(1, \"Run `neon-env --help` to see the available commands.\")\n\t.strict()\n\t.help()\n\t.version(pkgVersion)\n\t.parseSync();\n\nconst command = String(argv._[0]);\nconst cwd = process.cwd();\n\nlet result: CommandResult;\nswitch (command) {\n\tcase \"run\": {\n\t\tconst passthrough = Array.isArray(argv[\"--\"])\n\t\t\t? argv[\"--\"].map(String)\n\t\t\t: [];\n\t\tresult = await runEnvRun(\n\t\t\t{\n\t\t\t\tcommand: passthrough,\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tcase \"export\": {\n\t\tresult = await runEnvExport(\n\t\t\t{\n\t\t\t\tformat: argv.format === \"json\" ? \"json\" : \"dotenv\",\n\t\t\t\t...(typeof argv.config === \"string\"\n\t\t\t\t\t? { configPath: argv.config }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"project-id\"] === \"string\"\n\t\t\t\t\t? { projectId: argv[\"project-id\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.branch === \"string\"\n\t\t\t\t\t? { branch: argv.branch }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv[\"api-key\"] === \"string\"\n\t\t\t\t\t? { apiKey: argv[\"api-key\"] }\n\t\t\t\t\t: {}),\n\t\t\t\t...(typeof argv.profile === \"string\"\n\t\t\t\t\t? { profile: argv.profile }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t{ cwd },\n\t\t);\n\t\tbreak;\n\t}\n\tdefault:\n\t\tresult = {\n\t\t\texitCode: 1,\n\t\t\tstdout: \"\",\n\t\t\tstderr: `Unknown command: ${command}\\n`,\n\t\t};\n}\n\nif (result.stdout) process.stdout.write(result.stdout);\nif (result.stderr) process.stderr.write(result.stderr);\nif (argv.debug && result.exitCode !== 0 && result.debugInfo) {\n\tprocess.stderr.write(`\\n--- debug ---\\n${result.debugInfo}\\n`);\n}\nprocess.exit(result.exitCode);\n\nfunction readPackageVersion(): string {\n\t// The built CLI lives at `dist/cli.js`, so `package.json` is one directory up. When\n\t// running from source (tsx, vitest), the file lives at `src/cli.ts` and `package.json`\n\t// is again one directory up. Single resolution covers both layouts.\n\ttry {\n\t\tconst pkgUrl = new URL(\"../package.json\", import.meta.url);\n\t\tconst raw = readFileSync(fileURLToPath(pkgUrl), \"utf-8\");\n\t\tconst parsed = JSON.parse(raw) as { version?: unknown };\n\t\treturn typeof parsed.version === \"string\" ? parsed.version : \"0.0.0\";\n\t} catch {\n\t\treturn \"0.0.0\";\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,eAAe,uBAAuB,QAAQ,SAAS;CACtD,MAAM,EAAE,KA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AIrC,IAAI;EACH,MAAM,SAAS,IAAI,IAAI,mBAAmB,YAAY,GAAG;EACzD,MAAM,MAAM,aAAa,cAAc,MAAM,GAAG,OAAO;EACvD,MAAM,SAAS,KAAK,MAAM,GAAG;EAC7B,OAAO,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU;CAC9D,QAAQ;EACP,OAAO;CACR;AACD"}
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { ErrorCode, PlatformError, createNeonApiFromOptions, deriveCredentialScopes, resolveConfig } from "@neon/config/v1";
|
|
2
|
-
//#region
|
|
2
|
+
//#region ../../internals/env-core/dist/env.js
|
|
3
3
|
/**
|
|
4
4
|
* The Neon env core — resolving a branch's env from the Neon API, and projecting it into
|
|
5
5
|
* OS-level `{ KEY: value }` pairs.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* a copy rather than an import.
|
|
7
|
+
* Private, and bundled into both consumers: `@neon/env` publishes it as `fetchEnv` /
|
|
8
|
+
* `toEntries`, and the `neon` CLI needs the credential-reuse half in `reuse-secrets.ts`.
|
|
9
|
+
* See `README.md` for why it is not published.
|
|
11
10
|
*
|
|
12
11
|
* The counterpart that reads `process.env` — `parseEnv` and its zod schemas — is not here. It
|
|
13
12
|
* has no consumer outside `@neon/env`, so it stays in that package and imports this.
|
|
@@ -85,8 +84,18 @@ const NEON_ENV_VAR_KEYS = {
|
|
|
85
84
|
}
|
|
86
85
|
};
|
|
87
86
|
async function fetchEnv(config, options) {
|
|
87
|
+
if (options.keys) assertStorageCredentialKeyPair(options.keys);
|
|
88
88
|
return fetchEnvKeys(config, options, options.keys ?? null);
|
|
89
89
|
}
|
|
90
|
+
function assertStorageCredentialKeyPair(keys) {
|
|
91
|
+
if (keys.includes(NEON_ENV_VAR_KEYS.storage.accessKeyId) === keys.includes(NEON_ENV_VAR_KEYS.storage.secretAccessKey)) return;
|
|
92
|
+
throw new TypeError("fetchEnv: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be selected together. Pass both in `keys`, or omit both.");
|
|
93
|
+
}
|
|
94
|
+
/** Fail loudly when selected-key dependency planning and execution disagree. */
|
|
95
|
+
function requiredValue(value, description) {
|
|
96
|
+
if (value === null) throw new Error(`fetchEnv: missing ${description}.`);
|
|
97
|
+
return value;
|
|
98
|
+
}
|
|
90
99
|
/**
|
|
91
100
|
* The {@link fetchEnv} body, with the key selection as a plain argument and no generic
|
|
92
101
|
* narrowing. Exists for callers that compute the selection at runtime — notably
|
|
@@ -103,31 +112,38 @@ async function fetchEnvKeys(config, options, keys) {
|
|
|
103
112
|
const selection = keys ? new Set(keys) : null;
|
|
104
113
|
const wants = (key) => selection === null || selection.has(key);
|
|
105
114
|
const result = {};
|
|
106
|
-
const [roles, databases] = await Promise.all([api.listBranchRoles(projectId, branch.id), api.listBranchDatabases(projectId, branch.id)]);
|
|
107
|
-
const roleName = pickRoleName(roles, branch, options.roleName);
|
|
108
|
-
const databaseName = pickDatabaseName(databases, branch, options.databaseName);
|
|
109
115
|
const K = NEON_ENV_VAR_KEYS;
|
|
116
|
+
const wantsPooled = wants(K.postgres.databaseUrl);
|
|
117
|
+
const wantsUnpooled = wants(K.postgres.databaseUrlUnpooled);
|
|
110
118
|
const wantsAuth = desired.authEnabled && (wants(K.auth.baseUrl) || wants(K.auth.jwksUrl));
|
|
111
119
|
const wantsDataApi = desired.dataApiEnabled && wants(K.dataApi.url);
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
+
const gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;
|
|
121
|
+
const needsUnpooled = wantsUnpooled || gatewayEnabled && wants(K.aiGateway.baseUrl);
|
|
122
|
+
const needsConnectionTarget = wantsPooled || needsUnpooled;
|
|
123
|
+
const needsDatabase = needsConnectionTarget || wantsDataApi;
|
|
124
|
+
const [roles, databases] = await Promise.all([needsConnectionTarget ? api.listBranchRoles(projectId, branch.id) : Promise.resolve([]), needsDatabase ? api.listBranchDatabases(projectId, branch.id) : Promise.resolve([])]);
|
|
125
|
+
const databaseName = needsDatabase ? pickDatabaseName(databases, branch, options.databaseName) : null;
|
|
126
|
+
const connectionTarget = needsConnectionTarget ? {
|
|
127
|
+
roleName: pickRoleName(roles, branch, options.roleName),
|
|
128
|
+
databaseName: requiredValue(databaseName, "database for a selected connection URI")
|
|
129
|
+
} : null;
|
|
130
|
+
const getConnectionUri = (pooled) => {
|
|
131
|
+
const target = requiredValue(connectionTarget, "role and database for a selected connection URI");
|
|
132
|
+
return api.getConnectionUri(projectId, {
|
|
120
133
|
branchId: branch.id,
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
134
|
+
...target,
|
|
135
|
+
pooled
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
const [pooled, unpooled, authSnapshot, dataApiSnapshot] = await Promise.all([
|
|
139
|
+
wantsPooled ? getConnectionUri(true) : Promise.resolve(null),
|
|
140
|
+
needsUnpooled ? getConnectionUri(false) : Promise.resolve(null),
|
|
125
141
|
wantsAuth ? api.getNeonAuth(projectId, branch.id) : Promise.resolve(null),
|
|
126
|
-
wantsDataApi ? api.getNeonDataApi(projectId, branch.id, databaseName) : Promise.resolve(null)
|
|
142
|
+
wantsDataApi ? api.getNeonDataApi(projectId, branch.id, requiredValue(databaseName, "database for the selected Data API URL")) : Promise.resolve(null)
|
|
127
143
|
]);
|
|
128
144
|
const postgres = {};
|
|
129
|
-
if (
|
|
130
|
-
if (
|
|
145
|
+
if (wantsPooled) postgres.databaseUrl = requiredValue(pooled, "pooled connection URI response").uri;
|
|
146
|
+
if (wantsUnpooled) postgres.databaseUrlUnpooled = requiredValue(unpooled, "direct connection URI response").uri;
|
|
131
147
|
if (Object.keys(postgres).length > 0) result.postgres = postgres;
|
|
132
148
|
if (wants(K.branch.name)) result.branch = { name: branch.name };
|
|
133
149
|
if (wantsAuth) {
|
|
@@ -141,18 +157,22 @@ async function fetchEnvKeys(config, options, keys) {
|
|
|
141
157
|
result.auth = auth;
|
|
142
158
|
}
|
|
143
159
|
if (wantsDataApi) {
|
|
144
|
-
if (!dataApiSnapshot)
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
160
|
+
if (!dataApiSnapshot) {
|
|
161
|
+
const selectedDatabase = requiredValue(databaseName, "database for the selected Data API URL");
|
|
162
|
+
throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy enables dataApi but no Data API integration is enabled on branch ${branch.name} (${branch.id}) database ${selectedDatabase}.`, "Enable it via `apply(config, { projectId, branchId })` or in the Neon Console — then re-run fetchEnv. Or return dataApi.enabled=false."].join(" "), { details: {
|
|
163
|
+
projectId,
|
|
164
|
+
branchId: branch.id,
|
|
165
|
+
databaseName: selectedDatabase
|
|
166
|
+
} });
|
|
167
|
+
}
|
|
149
168
|
result.dataApi = { url: dataApiSnapshot.url };
|
|
150
169
|
}
|
|
151
170
|
const storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;
|
|
152
|
-
const gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;
|
|
153
171
|
const wantsStorage = storageEnabled && (wants(K.storage.accessKeyId) || wants(K.storage.secretAccessKey) || wants(K.storage.endpoint) || wants(K.storage.region));
|
|
154
172
|
const wantsGateway = gatewayEnabled && (wants(K.aiGateway.apiKey) || wants(K.aiGateway.baseUrl));
|
|
155
|
-
const
|
|
173
|
+
const wantsStorageCredential = storageEnabled && (wants(K.storage.accessKeyId) || wants(K.storage.secretAccessKey));
|
|
174
|
+
const wantsGatewayCredential = gatewayEnabled && wants(K.aiGateway.apiKey);
|
|
175
|
+
const wantsCredential = wantsStorageCredential || wantsGatewayCredential;
|
|
156
176
|
if (wantsStorage || wantsGateway) {
|
|
157
177
|
let storage = null;
|
|
158
178
|
if (wantsStorage) {
|
|
@@ -167,7 +187,10 @@ async function fetchEnvKeys(config, options, keys) {
|
|
|
167
187
|
projectId,
|
|
168
188
|
branchId: branch.id,
|
|
169
189
|
branchName: branch.name,
|
|
170
|
-
scopes: previewCredentialScopes(desired.preview
|
|
190
|
+
scopes: previewCredentialScopes(desired.preview, {
|
|
191
|
+
storage: wantsStorageCredential,
|
|
192
|
+
aiGateway: wantsGatewayCredential
|
|
193
|
+
})
|
|
171
194
|
}) : null;
|
|
172
195
|
if (storage) {
|
|
173
196
|
const storageEnv = {};
|
|
@@ -180,7 +203,7 @@ async function fetchEnvKeys(config, options, keys) {
|
|
|
180
203
|
if (wantsGateway) {
|
|
181
204
|
const gateway = {};
|
|
182
205
|
if (secrets && wants(K.aiGateway.apiKey)) gateway.apiKey = secrets.apiToken;
|
|
183
|
-
if (wants(K.aiGateway.baseUrl)) gateway.baseUrl = aiGatewayBaseUrl(branch.id, unpooled.uri);
|
|
206
|
+
if (wants(K.aiGateway.baseUrl)) gateway.baseUrl = aiGatewayBaseUrl(branch.id, requiredValue(unpooled, "direct connection URI for the selected AI Gateway base URL").uri);
|
|
184
207
|
result.aiGateway = gateway;
|
|
185
208
|
}
|
|
186
209
|
}
|
|
@@ -212,16 +235,14 @@ async function resolveBranchPolicy(config, options, api) {
|
|
|
212
235
|
};
|
|
213
236
|
}
|
|
214
237
|
/**
|
|
215
|
-
* Scopes the branch credential should carry for a resolved branch policy
|
|
216
|
-
* and the AI Gateway *require* a credential; functions never
|
|
217
|
-
*
|
|
218
|
-
* being minted for storage / the AI Gateway, so the one credential can invoke the branch's
|
|
219
|
-
* functions too. Returns `[]` only when nothing credential-bearing is enabled.
|
|
238
|
+
* Scopes the branch credential should carry for a resolved branch policy and optional key
|
|
239
|
+
* selection. Only object storage and the AI Gateway *require* a credential; functions never
|
|
240
|
+
* force one, but `functions:invoke` rides along when another selected feature mints one.
|
|
220
241
|
*/
|
|
221
|
-
function previewCredentialScopes(preview) {
|
|
242
|
+
function previewCredentialScopes(preview, selected) {
|
|
222
243
|
if (!preview) return [];
|
|
223
|
-
const storage = preview.buckets.length > 0;
|
|
224
|
-
const aiGateway = preview.aiGatewayEnabled;
|
|
244
|
+
const storage = preview.buckets.length > 0 && (selected?.storage ?? true);
|
|
245
|
+
const aiGateway = preview.aiGatewayEnabled && (selected?.aiGateway ?? true);
|
|
225
246
|
if (!storage && !aiGateway) return [];
|
|
226
247
|
return deriveCredentialScopes({
|
|
227
248
|
storage,
|
|
@@ -392,6 +413,6 @@ function toEntries(env) {
|
|
|
392
413
|
return out;
|
|
393
414
|
}
|
|
394
415
|
//#endregion
|
|
395
|
-
export {
|
|
416
|
+
export { fetchEnv as a, previewCredentialScopes as c, credentialName as i, resolveBranchPolicy as l, createApiFromOptions as n, fetchEnvKeys as o, credentialEnvKeys as r, policyEnvKeys as s, NEON_ENV_VAR_KEYS as t, toEntries as u };
|
|
396
417
|
|
|
397
418
|
//# sourceMappingURL=env.js.map
|
package/dist/env.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"env.js","names":[],"sources":["../../../internals/env-core/dist/env.js"],"sourcesContent":["import { ErrorCode, PlatformError, createNeonApiFromOptions, deriveCredentialScopes, resolveConfig } from \"@neon/config/v1\";\n//#region src/env.ts\n/**\n* The Neon env core — resolving a branch's env from the Neon API, and projecting it into\n* OS-level `{ KEY: value }` pairs.\n*\n* Private, and bundled into both consumers: `@neon/env` publishes it as `fetchEnv` /\n* `toEntries`, and the `neon` CLI needs the credential-reuse half in `reuse-secrets.ts`.\n* See `README.md` for why it is not published.\n*\n* The counterpart that reads `process.env` — `parseEnv` and its zod schemas — is not here. It\n* has no consumer outside `@neon/env`, so it stays in that package and imports this.\n*/\n/**\n* Mapping between the {@link NeonEnv} property paths and the OS-level env-var keys used\n* for cross-process transport (via `.env` files, `env run -- <cmd>`, or anything else\n* that talks to `process.env`).\n*\n* Each top-level key here is a {@link NeonEnv} namespace; the inner record maps the\n* camelCase property names exposed to TypeScript to the UPPER_SNAKE env-var names used\n* by the OS. Keep this in sync with {@link postgresEnvSchema} / {@link authEnvSchema} /\n* {@link dataApiEnvSchema}.\n*/\n/**\n* Neon's default branch owner role, created with every project. This is the role a\n* `DATABASE_URL` should connect as.\n*/\nconst NEON_DEFAULT_OWNER_ROLE = \"neondb_owner\";\n/**\n* Neon's default database, created with every project. When a branch has several databases\n* and none was requested, this is preferred for the `DATABASE_URL` so the common case (a\n* user added a second database next to `neondb`) auto-picks without asking.\n*/\nconst NEON_DEFAULT_DATABASE = \"neondb\";\n/**\n* Roles Neon provisions for the Auth / Data API (PostgREST) stack. They exist to back\n* RLS-scoped Data API requests authenticated by JWT — never to hold a `DATABASE_URL` —\n* so they're skipped when auto-picking the connection role. Enabling Neon Auth or the\n* Data API (`neon config apply`) adds these next to the owner role, which is why a plain\n* branch routinely reports more than one role.\n*/\nconst NEON_MANAGED_AUTH_ROLES = /* @__PURE__ */ new Set([\n\t\"authenticator\",\n\t\"anonymous\",\n\t\"authenticated\"\n]);\nconst NEON_ENV_VAR_KEYS = {\n\t/**\n\t* Branch identity. `NEON_BRANCH` carries the branch **name** and is injected into the\n\t* Neon Functions runtime on every branch (including the default) by default. `env pull` /\n\t* `neon dev` / `neon-env run` emit it too so local dev mirrors the deployed runtime.\n\t*/\n\tbranch: { name: \"NEON_BRANCH\" },\n\tpostgres: {\n\t\tdatabaseUrl: \"DATABASE_URL\",\n\t\tdatabaseUrlUnpooled: \"DATABASE_URL_UNPOOLED\"\n\t},\n\tauth: {\n\t\tbaseUrl: \"NEON_AUTH_BASE_URL\",\n\t\tjwksUrl: \"NEON_AUTH_JWKS_URL\"\n\t},\n\tdataApi: { url: \"NEON_DATA_API_URL\" },\n\t/**\n\t* Object storage (Preview). The S3 SDKs read `AWS_*` from their standard config chain, so\n\t* a branch credential + `neon dev` / `env pull` makes object storage work from env alone.\n\t* `region` is injected under the SDK-standard `AWS_REGION`.\n\t*/\n\tstorage: {\n\t\taccessKeyId: \"AWS_ACCESS_KEY_ID\",\n\t\tsecretAccessKey: \"AWS_SECRET_ACCESS_KEY\",\n\t\tendpoint: \"AWS_ENDPOINT_URL_S3\",\n\t\tregion: \"AWS_REGION\"\n\t},\n\t/**\n\t* AI Gateway (Preview). Exposed under the Neon-branded env vars the deployed Functions\n\t* runtime injects: `apiKey` is the minted credential's bearer (`NEON_AI_GATEWAY_TOKEN`)\n\t* and `baseUrl` is the bare branch gateway host (`NEON_AI_GATEWAY_BASE_URL`,\n\t* `scheme://host`, no path). Clients like `@neon/ai-sdk-provider` read these and append the\n\t* dialect route (`/v1`, `/openai/v1`, `/anthropic/v1`) themselves (https://github.com/vercel/ai/pull/15997).\n\t*/\n\taiGateway: {\n\t\tapiKey: \"NEON_AI_GATEWAY_TOKEN\",\n\t\tbaseUrl: \"NEON_AI_GATEWAY_BASE_URL\"\n\t}\n};\nasync function fetchEnv(config, options) {\n\tif (options.keys) assertStorageCredentialKeyPair(options.keys);\n\treturn fetchEnvKeys(config, options, options.keys ?? null);\n}\nfunction assertStorageCredentialKeyPair(keys) {\n\tif (keys.includes(NEON_ENV_VAR_KEYS.storage.accessKeyId) === keys.includes(NEON_ENV_VAR_KEYS.storage.secretAccessKey)) return;\n\tthrow new TypeError(\"fetchEnv: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be selected together. Pass both in `keys`, or omit both.\");\n}\n/** Fail loudly when selected-key dependency planning and execution disagree. */\nfunction requiredValue(value, description) {\n\tif (value === null) throw new Error(`fetchEnv: missing ${description}.`);\n\treturn value;\n}\n/**\n* The {@link fetchEnv} body, with the key selection as a plain argument and no generic\n* narrowing. Exists for callers that compute the selection at runtime — notably\n* {@link fetchEnvReusingSecrets}, which decides which keys it still needs by checking the\n* branch — since the public overload's `keys` is bound to a literal union those callers cannot\n* produce without asserting.\n*\n* `keys === null` selects everything the policy enables.\n*/\nasync function fetchEnvKeys(config, options, keys) {\n\tconst api = options.api ?? createApiFromOptions(options);\n\tconst projectId = options.projectId;\n\tconst { branch, desired } = await resolveBranchPolicy(config, options, api);\n\tconst selection = keys ? new Set(keys) : null;\n\tconst wants = (key) => selection === null || selection.has(key);\n\tconst result = {};\n\tconst K = NEON_ENV_VAR_KEYS;\n\tconst wantsPooled = wants(K.postgres.databaseUrl);\n\tconst wantsUnpooled = wants(K.postgres.databaseUrlUnpooled);\n\tconst wantsAuth = desired.authEnabled && (wants(K.auth.baseUrl) || wants(K.auth.jwksUrl));\n\tconst wantsDataApi = desired.dataApiEnabled && wants(K.dataApi.url);\n\tconst gatewayEnabled = desired.preview?.aiGatewayEnabled ?? false;\n\tconst needsUnpooled = wantsUnpooled || gatewayEnabled && wants(K.aiGateway.baseUrl);\n\tconst needsConnectionTarget = wantsPooled || needsUnpooled;\n\tconst needsDatabase = needsConnectionTarget || wantsDataApi;\n\tconst [roles, databases] = await Promise.all([needsConnectionTarget ? api.listBranchRoles(projectId, branch.id) : Promise.resolve([]), needsDatabase ? api.listBranchDatabases(projectId, branch.id) : Promise.resolve([])]);\n\tconst databaseName = needsDatabase ? pickDatabaseName(databases, branch, options.databaseName) : null;\n\tconst connectionTarget = needsConnectionTarget ? {\n\t\troleName: pickRoleName(roles, branch, options.roleName),\n\t\tdatabaseName: requiredValue(databaseName, \"database for a selected connection URI\")\n\t} : null;\n\tconst getConnectionUri = (pooled) => {\n\t\tconst target = requiredValue(connectionTarget, \"role and database for a selected connection URI\");\n\t\treturn api.getConnectionUri(projectId, {\n\t\t\tbranchId: branch.id,\n\t\t\t...target,\n\t\t\tpooled\n\t\t});\n\t};\n\tconst [pooled, unpooled, authSnapshot, dataApiSnapshot] = await Promise.all([\n\t\twantsPooled ? getConnectionUri(true) : Promise.resolve(null),\n\t\tneedsUnpooled ? getConnectionUri(false) : Promise.resolve(null),\n\t\twantsAuth ? api.getNeonAuth(projectId, branch.id) : Promise.resolve(null),\n\t\twantsDataApi ? api.getNeonDataApi(projectId, branch.id, requiredValue(databaseName, \"database for the selected Data API URL\")) : Promise.resolve(null)\n\t]);\n\tconst postgres = {};\n\tif (wantsPooled) postgres.databaseUrl = requiredValue(pooled, \"pooled connection URI response\").uri;\n\tif (wantsUnpooled) postgres.databaseUrlUnpooled = requiredValue(unpooled, \"direct connection URI response\").uri;\n\tif (Object.keys(postgres).length > 0) result.postgres = postgres;\n\tif (wants(K.branch.name)) result.branch = { name: branch.name };\n\tif (wantsAuth) {\n\t\tif (!authSnapshot) throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy enables auth but no Neon Auth integration is enabled on branch ${branch.name} (${branch.id}).`, \"Enable it via `apply(config, { projectId, branchId })` (or `npx neon …`), in the Neon Console — then re-run fetchEnv. Or return auth.enabled=false.\"].join(\" \"), { details: {\n\t\t\tprojectId,\n\t\t\tbranchId: branch.id\n\t\t} });\n\t\tconst auth = {};\n\t\tif (wants(K.auth.baseUrl)) auth.baseUrl = authSnapshot.baseUrl ?? \"\";\n\t\tif (wants(K.auth.jwksUrl)) auth.jwksUrl = authSnapshot.jwksUrl ?? \"\";\n\t\tresult.auth = auth;\n\t}\n\tif (wantsDataApi) {\n\t\tif (!dataApiSnapshot) {\n\t\t\tconst selectedDatabase = requiredValue(databaseName, \"database for the selected Data API URL\");\n\t\t\tthrow new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy enables dataApi but no Data API integration is enabled on branch ${branch.name} (${branch.id}) database ${selectedDatabase}.`, \"Enable it via `apply(config, { projectId, branchId })` or in the Neon Console — then re-run fetchEnv. Or return dataApi.enabled=false.\"].join(\" \"), { details: {\n\t\t\t\tprojectId,\n\t\t\t\tbranchId: branch.id,\n\t\t\t\tdatabaseName: selectedDatabase\n\t\t\t} });\n\t\t}\n\t\tresult.dataApi = { url: dataApiSnapshot.url };\n\t}\n\tconst storageEnabled = (desired.preview?.buckets.length ?? 0) > 0;\n\tconst wantsStorage = storageEnabled && (wants(K.storage.accessKeyId) || wants(K.storage.secretAccessKey) || wants(K.storage.endpoint) || wants(K.storage.region));\n\tconst wantsGateway = gatewayEnabled && (wants(K.aiGateway.apiKey) || wants(K.aiGateway.baseUrl));\n\tconst wantsStorageCredential = storageEnabled && (wants(K.storage.accessKeyId) || wants(K.storage.secretAccessKey));\n\tconst wantsGatewayCredential = gatewayEnabled && wants(K.aiGateway.apiKey);\n\tconst wantsCredential = wantsStorageCredential || wantsGatewayCredential;\n\tif (wantsStorage || wantsGateway) {\n\t\tlet storage = null;\n\t\tif (wantsStorage) {\n\t\t\tstorage = await api.getProjectBranchStorage(projectId, branch.id);\n\t\t\tif (!storage) throw new PlatformError(ErrorCode.NotFound, [`fetchEnv: branch policy declares object storage (preview.buckets) but storage is not enabled on branch ${branch.name} (${branch.id}).`, \"Enable it via `apply(config, { projectId, branchId })` (or in the Neon Console) — then re-run fetchEnv. Or remove preview.buckets.\"].join(\" \"), { details: {\n\t\t\t\tprojectId,\n\t\t\t\tbranchId: branch.id\n\t\t\t} });\n\t\t}\n\t\tconst secrets = wantsCredential ? await mintBranchCredential({\n\t\t\tapi,\n\t\t\tprojectId,\n\t\t\tbranchId: branch.id,\n\t\t\tbranchName: branch.name,\n\t\t\tscopes: previewCredentialScopes(desired.preview, {\n\t\t\t\tstorage: wantsStorageCredential,\n\t\t\t\taiGateway: wantsGatewayCredential\n\t\t\t})\n\t\t}) : null;\n\t\tif (storage) {\n\t\t\tconst storageEnv = {};\n\t\t\tif (secrets && wants(K.storage.accessKeyId)) storageEnv.accessKeyId = secrets.accessKeyId;\n\t\t\tif (secrets && wants(K.storage.secretAccessKey)) storageEnv.secretAccessKey = secrets.secretAccessKey;\n\t\t\tif (wants(K.storage.endpoint)) storageEnv.endpoint = storage.s3Endpoint;\n\t\t\tif (wants(K.storage.region)) storageEnv.region = storage.region;\n\t\t\tresult.storage = storageEnv;\n\t\t}\n\t\tif (wantsGateway) {\n\t\t\tconst gateway = {};\n\t\t\tif (secrets && wants(K.aiGateway.apiKey)) gateway.apiKey = secrets.apiToken;\n\t\t\tif (wants(K.aiGateway.baseUrl)) gateway.baseUrl = aiGatewayBaseUrl(branch.id, requiredValue(unpooled, \"direct connection URI for the selected AI Gateway base URL\").uri);\n\t\t\tresult.aiGateway = gateway;\n\t\t}\n\t}\n\treturn result;\n}\n/**\n* Resolve the target branch and evaluate the policy against it — the first thing any\n* branch-scoped operation needs. Shared by {@link fetchEnv} and {@link fetchEnvReusingSecrets}\n* so the two agree on which branch they're talking about and what it has enabled.\n*/\nasync function resolveBranchPolicy(config, options, api) {\n\tconst projectId = options.projectId;\n\tconst branches = await api.listBranches(projectId);\n\tif (branches.length === 0) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: project ${projectId} has no branches.`, \"Deploy your neon.ts policy (or create a branch) first, or pick a different project id.\"].join(\" \"), { details: { projectId } });\n\tconst branchRef = options.branch ?? options.branchId;\n\tif (!branchRef) throw new PlatformError(ErrorCode.BranchNotFound, [\"fetchEnv: no branch provided.\", \"Pass `branch` with a branch name (e.g. `main`) or id (`br-…`).\"].join(\" \"), { details: { projectId } });\n\tconst branch = resolveBranch(branchRef, branches);\n\treturn {\n\t\tbranch,\n\t\tdesired: resolveConfig(config, {\n\t\t\tname: branch.name,\n\t\t\tid: branch.id,\n\t\t\texists: true,\n\t\t\t...branch.parentId ? { parentId: branch.parentId } : {},\n\t\t\tisDefault: branch.isDefault,\n\t\t\tisProtected: branch.protected,\n\t\t\t...branch.expiresAt ? { expiresAt: branch.expiresAt } : {}\n\t\t})\n\t};\n}\n/**\n* Scopes the branch credential should carry for a resolved branch policy and optional key\n* selection. Only object storage and the AI Gateway *require* a credential; functions never\n* force one, but `functions:invoke` rides along when another selected feature mints one.\n*/\nfunction previewCredentialScopes(preview, selected) {\n\tif (!preview) return [];\n\tconst storage = preview.buckets.length > 0 && (selected?.storage ?? true);\n\tconst aiGateway = preview.aiGatewayEnabled && (selected?.aiGateway ?? true);\n\tif (!storage && !aiGateway) return [];\n\treturn deriveCredentialScopes({\n\t\tstorage,\n\t\taiGateway,\n\t\tfunctions: preview.functions.length > 0\n\t});\n}\n/** The `name` this tool stamps on every credential it mints, so it can recognize its own. */\nfunction credentialName(branchName) {\n\treturn `neon-env ${branchName}`;\n}\n/** The env-var keys a branch credential's secrets surface under, in emit order. */\nfunction credentialEnvKeys(flags) {\n\treturn [...flags.storage ? [NEON_ENV_VAR_KEYS.storage.accessKeyId, NEON_ENV_VAR_KEYS.storage.secretAccessKey] : [], ...flags.aiGateway ? [NEON_ENV_VAR_KEYS.aiGateway.apiKey] : []];\n}\n/**\n* Every OS-level env var a resolved branch policy produces, in emit order. Lets a caller\n* subtract the ones it already holds and pass the rest as {@link fetchEnv}'s `keys`, without\n* re-deriving which vars a policy implies.\n*/\nfunction policyEnvKeys(desired) {\n\tconst K = NEON_ENV_VAR_KEYS;\n\treturn [\n\t\tK.postgres.databaseUrl,\n\t\tK.postgres.databaseUrlUnpooled,\n\t\tK.branch.name,\n\t\t...desired.authEnabled ? [K.auth.baseUrl, K.auth.jwksUrl] : [],\n\t\t...desired.dataApiEnabled ? [K.dataApi.url] : [],\n\t\t...(desired.preview?.buckets.length ?? 0) > 0 ? [\n\t\t\tK.storage.accessKeyId,\n\t\t\tK.storage.secretAccessKey,\n\t\t\tK.storage.endpoint,\n\t\t\tK.storage.region\n\t\t] : [],\n\t\t...desired.preview?.aiGatewayEnabled ? [K.aiGateway.apiKey, K.aiGateway.baseUrl] : []\n\t];\n}\n/**\n* Mint the branch credential backing object storage / the AI Gateway.\n*\n* `api_token` and `s3_secret_access_key` come back **exactly once** — they are not stored\n* server-side and the list endpoint returns metadata only — so the caller's copy is the only\n* copy. That is why {@link fetchEnv} mints rather than fetches: there is nothing to fetch. A\n* caller that already holds a valid copy should leave the secret keys out of `keys` (see\n* {@link fetchEnvReusingSecrets}) instead of minting one it will discard.\n*/\nasync function mintBranchCredential(args) {\n\tconst minted = await args.api.createCredential(args.projectId, args.branchId, {\n\t\tscopes: args.scopes,\n\t\tprincipalType: \"user\",\n\t\tname: credentialName(args.branchName)\n\t});\n\treturn {\n\t\taccessKeyId: minted.tokenId,\n\t\tsecretAccessKey: minted.s3SecretAccessKey,\n\t\tapiToken: minted.apiToken\n\t};\n}\n/**\n* The AI Gateway is a **branch-scoped host** — `<branchId>-api.ai.<host-suffix>` — NOT the\n* control-plane API origin. Derive the suffix from the branch's own Postgres connection host\n* by dropping only the endpoint label (the first segment) and keeping everything after it,\n* including any infra cell prefix (`c-N.`): a connection host of\n* `ep-x.c-3.us-east-2.aws.neon.tech` yields the gateway host\n* `<branchId>-api.ai.c-3.us-east-2.aws.neon.tech`. The cell prefix is **load-bearing** —\n* the gateway is cell-routed, so dropping `c-N.` resolves to the wrong (or no) host.\n*/\nfunction aiGatewayHost(branchId, connectionUri) {\n\tlet connectionHost = \"\";\n\ttry {\n\t\tconnectionHost = new URL(connectionUri).hostname;\n\t} catch {\n\t\tconnectionHost = \"\";\n\t}\n\treturn `${branchId}-api.ai.${connectionHost.split(\".\").slice(1).join(\".\")}`;\n}\n/** The AI Gateway's bare base URL (`NEON_AI_GATEWAY_BASE_URL`) on the branch gateway host. */\nfunction aiGatewayBaseUrl(branchId, connectionUri) {\n\treturn `https://${aiGatewayHost(branchId, connectionUri)}`;\n}\nfunction createApiFromOptions(options) {\n\treturn createNeonApiFromOptions(\"fetchEnv\", {\n\t\t...options.apiKey ? { apiKey: options.apiKey } : {},\n\t\t...options.apiHost ? { apiHost: options.apiHost } : {}\n\t});\n}\n/**\n* Resolve a branch ref — a name or an id — to a concrete branch. Matches by id first\n* (exact `br-…`), then by name; both are unique within a project, so the lookup is\n* unambiguous. This lets `.neon` files written by `neonctl` (which pin the branch *name*)\n* and explicit `br-…` ids both work.\n*/\nfunction resolveBranch(branch, branches) {\n\tconst match = branches.find((b) => b.id === branch) ?? branches.find((b) => b.name === branch);\n\tif (match) return match;\n\tthrow new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: branch ${JSON.stringify(branch)} not found on project (matched by id or name).`, `Existing branches: ${branches.map((b) => `${b.name} (${b.id})`).join(\", \")}.`].join(\" \"), { details: {\n\t\tbranch,\n\t\tavailable: branches.map((b) => `${b.name} (${b.id})`)\n\t} });\n}\nfunction pickRoleName(roles, branch, requested) {\n\tif (requested) {\n\t\tif (!roles.some((r) => r.name === requested)) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: role \"${requested}\" not found on branch ${branch.name} (${branch.id}).`, `Existing roles: ${roles.map((r) => r.name).join(\", \") || \"(none)\"}.`].join(\" \"), { details: {\n\t\t\tbranchId: branch.id,\n\t\t\troleName: requested,\n\t\t\tavailableRoles: roles.map((r) => r.name)\n\t\t} });\n\t\treturn requested;\n\t}\n\tif (roles.length === 0) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: branch ${branch.name} (${branch.id}) has no roles.`, \"Create one via the Neon console or pass `roleName` explicitly.\"].join(\" \"), { details: { branchId: branch.id } });\n\tif (roles.length === 1) return roles[0].name;\n\tconst owner = roles.find((r) => r.name === NEON_DEFAULT_OWNER_ROLE);\n\tif (owner) return owner.name;\n\tconst appRoles = roles.filter((r) => !NEON_MANAGED_AUTH_ROLES.has(r.name));\n\tif (appRoles.length === 1) return appRoles[0].name;\n\tthrow new PlatformError(ErrorCode.AmbiguousBranchAuth, [`fetchEnv: branch ${branch.name} (${branch.id}) has ${roles.length} roles and none is \"${NEON_DEFAULT_OWNER_ROLE}\"; cannot auto-pick.`, `Pass \\`roleName\\` explicitly. Available: ${roles.map((r) => r.name).join(\", \")}.`].join(\" \"), { details: {\n\t\tbranchId: branch.id,\n\t\tavailableRoles: roles.map((r) => r.name)\n\t} });\n}\nfunction pickDatabaseName(databases, branch, requested) {\n\tif (requested) {\n\t\tif (!databases.some((d) => d.name === requested)) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: database \"${requested}\" not found on branch ${branch.name} (${branch.id}).`, `Existing databases: ${databases.map((d) => d.name).join(\", \") || \"(none)\"}.`].join(\" \"), { details: {\n\t\t\tbranchId: branch.id,\n\t\t\tdatabaseName: requested,\n\t\t\tavailableDatabases: databases.map((d) => d.name)\n\t\t} });\n\t\treturn requested;\n\t}\n\tif (databases.length === 0) throw new PlatformError(ErrorCode.BranchNotFound, [`fetchEnv: branch ${branch.name} (${branch.id}) has no databases.`, \"Create one via the Neon console or pass `databaseName` explicitly.\"].join(\" \"), { details: { branchId: branch.id } });\n\tconst neondb = databases.find((d) => d.name === NEON_DEFAULT_DATABASE);\n\tif (neondb) return neondb.name;\n\tif (databases.length === 1) return databases[0].name;\n\tthrow new PlatformError(ErrorCode.AmbiguousBranchAuth, [`fetchEnv: branch ${branch.name} (${branch.id}) has ${databases.length} databases and none is named \"${NEON_DEFAULT_DATABASE}\"; cannot auto-pick.`, `Rename one to \"${NEON_DEFAULT_DATABASE}\" or keep a single database on the branch (or, when calling fetchEnv directly, pass \\`databaseName\\`). Available: ${databases.map((d) => d.name).join(\", \")}.`].join(\" \"), { details: {\n\t\tbranchId: branch.id,\n\t\tavailableDatabases: databases.map((d) => d.name)\n\t} });\n}\n/**\n* Project a fully-resolved {@link NeonEnv} into the OS-level `{ KEY: value }` pairs used\n* for cross-process transport. Named after the web-platform `.entries()` convention\n* (`URLSearchParams` / `Headers` / `FormData`); returns a `Record` rather than an\n* iterator of tuples since that's the shape env injection needs (wrap with\n* `Object.entries(...)` if you want literal `[key, value]` pairs). Used by `neon-env run`\n* to inject the vars into a subprocess's `process.env`.\n*\n* Walks the value at runtime so it works for any `NeonEnv<C>` regardless of which\n* conditional namespaces are present.\n*/\nfunction toEntries(env) {\n\tconst out = {};\n\tconst put = (key, value) => {\n\t\tif (value !== void 0) out[key] = value;\n\t};\n\tconst K = NEON_ENV_VAR_KEYS;\n\tput(K.postgres.databaseUrl, env.postgres?.databaseUrl);\n\tput(K.postgres.databaseUrlUnpooled, env.postgres?.databaseUrlUnpooled);\n\tput(K.branch.name, env.branch?.name);\n\tput(K.auth.baseUrl, env.auth?.baseUrl);\n\tput(K.auth.jwksUrl, env.auth?.jwksUrl);\n\tput(K.dataApi.url, env.dataApi?.url);\n\tput(K.storage.accessKeyId, env.storage?.accessKeyId);\n\tput(K.storage.secretAccessKey, env.storage?.secretAccessKey);\n\tput(K.storage.endpoint, env.storage?.endpoint);\n\tput(K.storage.region, env.storage?.region);\n\tput(K.aiGateway.apiKey, env.aiGateway?.apiKey);\n\tput(K.aiGateway.baseUrl, env.aiGateway?.baseUrl);\n\treturn out;\n}\n//#endregion\nexport { NEON_ENV_VAR_KEYS, createApiFromOptions, credentialEnvKeys, credentialName, fetchEnv, fetchEnvKeys, policyEnvKeys, previewCredentialScopes, resolveBranchPolicy, toEntries };\n\n//# sourceMappingURL=env.js.map"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,0BAA0B;;;;;;AAMhC,MAAM,wBAAwB;;;;;;;;AAQ9B,MAAM,0CAA0C,IAAI,IAAI;CACvD;CACA;CACA;AACD,CAAC;AACD,MAAM,oBAAoB;;;;;;CAMzB,QAAQ,EAAE,MAAM,cAAc;CAC9B,UAAU;EACT,aAAa;EACb,qBAAqB;CACtB;CACA,MAAM;EACL,SAAS;EACT,SAAS;CACV;CACA,SAAS,EAAE,KAAK,oBAAoB;;;;;;CAMpC,SAAS;EACR,aAAa;EACb,iBAAiB;EACjB,UAAU;EACV,QAAQ;CACT;;;;;;;;CAQA,WAAW;EACV,QAAQ;EACR,SAAS;CACV;AACD;AACA,eAAe,SAAS,QAAQ,SAAS;CACxC,IAAI,QAAQ,MAAM,+BAA+B,QAAQ,IAAI;CAC7D,OAAO,aAAa,QAAQ,SAAS,QAAQ,QAAQ,IAAI;AAC1D;AACA,SAAS,+BAA+B,MAAM;CAC7C,IAAI,KAAK,SAAS,kBAAkB,QAAQ,WAAW,MAAM,KAAK,SAAS,kBAAkB,QAAQ,eAAe,GAAG;CACvH,MAAM,IAAI,UAAU,qHAAqH;AAC1I;;AAEA,SAAS,cAAc,OAAO,aAAa;CAC1C,IAAI,UAAU,MAAM,MAAM,IAAI,MAAM,qBAAqB,YAAY,EAAE;CACvE,OAAO;AACR;;;;;;;;;;AAUA,eAAe,aAAa,QAAQ,SAAS,MAAM;CAClD,MAAM,MAA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