@neondatabase/config 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env.example ADDED
@@ -0,0 +1,5 @@
1
+ # Copy to `.env` and fill in real values. `.env` itself is gitignored.
2
+ # Required to run `pnpm --filter @neondatabase/config test:e2e`.
3
+ NEON_API_KEY=
4
+ # Optional. When set, e2e tests scope project creation/listing to this org.
5
+ NEON_ORG_ID=
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # @neondatabase/config
2
+
3
+ Config-as-Code for the Neon Platform. A repo-local `neon.ts` exports a TypeScript policy function describing a branch's desired state. This package exposes **functions** to inspect, diff, and deploy that policy against the Neon API.
4
+
5
+ > No CLI commands ship here, and the package is **filesystem- and env-agnostic**: it never reads `.neon` files or `NEON_*` environment variables. You pass `projectId` and the target branch explicitly (resolve them in your CLI, e.g. neonctl). This package is functions only.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @neondatabase/config
11
+ ```
12
+
13
+ ## Define a policy
14
+
15
+ ```ts
16
+ // neon.ts
17
+ import { defineConfig } from "@neondatabase/config/v1";
18
+
19
+ export default defineConfig((branch) => {
20
+ if (branch.name === "main") {
21
+ return { protected: true, auth: {} };
22
+ }
23
+ return { parent: "main", ttl: "7d" };
24
+ });
25
+ ```
26
+
27
+ The `branch` argument is a **read-only descriptor** (`BranchTarget`) of the branch this policy is being evaluated for — `name`, `id`, `exists`, `isDefault`, `isProtected`, `parentId`, `expiresAt`. It is not a live branch handle: don't mutate it, just switch on its fields and **return** the desired config. The same callback runs both against existing branches and during pre-create evaluation (`exists: false`).
28
+
29
+ `parent` and `ttl` are branch lifecycle fields. Product-specific settings live under product namespaces such as `postgres`, `auth`, and `dataApi`.
30
+
31
+ ## Functions
32
+
33
+ The three operations mirror the Terraform mental model: **`inspect`** (read live state), **`plan`** (dry-run diff), **`apply`** (reconcile).
34
+
35
+ `projectId` and `branchId` are **required** — there is no `.neon`/env fallback. (`projectId` is required because the Neon management API addresses every branch through its project; deriving it from a branch id would need an extra discovery round-trip.)
36
+
37
+ ```ts
38
+ import config from "../neon";
39
+ import { inspect, plan, apply } from "@neondatabase/config/v1";
40
+
41
+ const target = { projectId: "patient-art-12345", branchId: "main" };
42
+
43
+ // Dry-run: what would apply do for this branch? No mutations.
44
+ const diff = await plan(config, target);
45
+
46
+ // Apply the policy to a branch. Never creates projects/branches.
47
+ await apply(config, { ...target, updateExisting: true });
48
+
49
+ // Read a branch's live Neon state as a plain object.
50
+ const live = await inspect(target);
51
+ ```
52
+
53
+ | Function | Description |
54
+ | --- | --- |
55
+ | `inspect(options)` | Returns the branch's live Neon state (project + branch metadata and a reverse-engineered `BranchConfig`). Read-only. |
56
+ | `plan(config, options)` | Returns the dry-run diff — what `apply` would do for the branch, with no mutations. Returns a `PushResult` whose `applied` holds the plan and `conflicts` holds blocking drift. |
57
+ | `apply(config, options)` | Reconciles your local `neon.ts` policy onto the branch. Pass `updateExisting` to auto-confirm overriding existing remote settings and `allowProtectedBranch` to auto-confirm applying to a protected branch. |
58
+
59
+ `options` requires both `projectId` and `branchId` (a Neon branch id, `br-…`). Resolve branch names to ids before calling. The Neon API key resolves via the `apiKey` option → `NEON_API_KEY` → `~/.config/neonctl/credentials.json`.
60
+
61
+ ## Lower-level engine
62
+
63
+ `inspect` / `plan` / `apply` are thin wrappers over `pullConfig(options)` / `pushConfig(config, options)` (both require `projectId` + `branchId`), which are also exported for advanced/programmatic use along with `defineConfig`, `loadConfigFromFile` (optional `neon.ts` loader), `createRealNeonApi`, the `PlatformError` base class + `ErrorCode` enum, the `errors` and `schemas` namespaces, and the supporting types.
64
+
65
+ ```ts
66
+ import {
67
+ defineConfig,
68
+ inspect,
69
+ plan,
70
+ apply,
71
+ pushConfig,
72
+ pullConfig,
73
+ loadConfigFromFile,
74
+ createRealNeonApi,
75
+ resolveApiKey,
76
+ PlatformError,
77
+ ErrorCode,
78
+ errors,
79
+ schemas,
80
+ } from "@neondatabase/config/v1";
81
+ ```
82
+
83
+ ## Safety Rules
84
+
85
+ - `apply` / `pushConfig` never creates projects or branches.
86
+ - `auth: {}` and `dataApi: {}` enable those integrations with Neon defaults. `auth.enabled: false`, `dataApi.enabled: false`, or absence leaves existing integrations alone. Disabling is destructive and remains explicit/manual.
87
+ - Mutable branch drift (`protected`, `ttl`, `postgres.computeSettings`) is reported as a conflict unless `updateExisting` is passed (or a `confirm` callback is supplied to `pushConfig`).
88
+ - Applying to a branch with the `protected` flag set on Neon requires `allowProtectedBranch` (or a `confirm` callback).
89
+
90
+ ## Env vars
91
+
92
+ Connection-string resolution/injection lives in the companion package [`@neondatabase/env`](../env), which depends on this package for the `Config` type and the Neon API client.
@@ -0,0 +1,52 @@
1
+ import { describe, expect } from "vitest";
2
+ import { createRealNeonApi, ErrorCode, type PlatformError } from "../src/v1.js";
3
+ import { detectApiKeyScope, e2eTest } from "./helpers.js";
4
+
5
+ describe("e2e — error wrapping against real Neon API", () => {
6
+ e2eTest(
7
+ "bad API key yields PLATFORM_UNAUTHORIZED with key-rotation guidance",
8
+ async () => {
9
+ const api = createRealNeonApi({
10
+ apiKey: "napi_definitely_not_a_real_key_xxxxxxxxxxxxxxxxxx",
11
+ });
12
+ await expect(api.listProjects({})).rejects.toMatchObject({
13
+ code: ErrorCode.Unauthorized,
14
+ });
15
+ try {
16
+ await api.listProjects({});
17
+ } catch (err) {
18
+ const p = err as PlatformError;
19
+ expect(p.message).toContain(
20
+ "Bearer token sent to the Neon API was rejected",
21
+ );
22
+ expect(p.message).toContain(
23
+ "https://console.neon.tech/app/settings/api-keys",
24
+ );
25
+ expect(p.message).toContain("neonctl auth");
26
+ }
27
+ },
28
+ );
29
+
30
+ e2eTest(
31
+ "getProject on a non-existent id yields PLATFORM_NOT_FOUND with the offending id in the message",
32
+ async () => {
33
+ const scope = await detectApiKeyScope();
34
+ if (scope.kind !== "org-or-user") return;
35
+ const api = createRealNeonApi({
36
+ apiKey: process.env.NEON_API_KEY ?? "",
37
+ });
38
+ await expect(
39
+ api.getProject("proj-definitely-not-real-12345"),
40
+ ).rejects.toMatchObject({
41
+ code: ErrorCode.NotFound,
42
+ });
43
+ try {
44
+ await api.getProject("proj-definitely-not-real-12345");
45
+ } catch (err) {
46
+ const p = err as PlatformError;
47
+ expect(p.message).toContain("proj-definitely-not-real-12345");
48
+ expect(p.details.status).toBe(404);
49
+ }
50
+ },
51
+ );
52
+ });
package/e2e/helpers.ts ADDED
@@ -0,0 +1,205 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createApiClient } from "@neondatabase/api-client";
3
+ import { test } from "vitest";
4
+ import type { NeonApi } from "../src/lib/neon-api.js";
5
+ import { createRealNeonApi } from "../src/lib/neon-api-real.js";
6
+
7
+ /**
8
+ * Every e2e-created project is named `neon-ts-e2e-<uuid>`. Tests can register
9
+ * `track(id)` to opt into the per-test cleanup hook. The suite-level
10
+ * {@link sweepOrphans} additionally deletes leftovers from a previous failed run.
11
+ */
12
+ const PROJECT_PREFIX = "neon-ts-e2e-";
13
+
14
+ /**
15
+ * Default Neon region used by every e2e test that creates a project. Override per-test
16
+ * by passing `region` to `defineConfig`.
17
+ */
18
+ export const DEFAULT_REGION = "aws-us-east-2";
19
+
20
+ /** Generate a project name guaranteed not to collide with anything else in the org. */
21
+ export function uniqueProjectName(suffix?: string): string {
22
+ const id = randomUUID().slice(0, 8);
23
+ return suffix
24
+ ? `${PROJECT_PREFIX}${id}-${suffix}`
25
+ : `${PROJECT_PREFIX}${id}`;
26
+ }
27
+
28
+ function requireApiKey(): string {
29
+ const key = process.env.NEON_API_KEY;
30
+ if (!key || key.trim() === "") {
31
+ throw new Error(
32
+ "NEON_API_KEY is not set. Create packages/config/.env (see .env.example) before running test:e2e.",
33
+ );
34
+ }
35
+ return key;
36
+ }
37
+
38
+ /** The same real NeonApi adapter the SDK uses internally — exercised end-to-end. */
39
+ export function makeRealApi(): NeonApi {
40
+ return createRealNeonApi({ apiKey: requireApiKey() });
41
+ }
42
+
43
+ /**
44
+ * Create a real Neon project via the NeonApi adapter directly. `pushConfig` no longer
45
+ * provisions projects (callers are expected to run `neonctl link` first), so every e2e
46
+ * test that needs a fresh project to push against goes through this helper instead.
47
+ */
48
+ export async function bootstrapProject(
49
+ api: NeonApi,
50
+ args: { name: string; region: string },
51
+ ): Promise<string> {
52
+ const created = await api.createProject({
53
+ name: args.name,
54
+ regionId: args.region,
55
+ });
56
+ return created.id;
57
+ }
58
+
59
+ /** Lower-level Neon client. Used by cleanup and a few setup helpers. */
60
+ function makeRawClient(): ReturnType<typeof createApiClient> {
61
+ return createApiClient({ apiKey: requireApiKey() });
62
+ }
63
+
64
+ /**
65
+ * Discriminates the key currently configured. Project-scoped keys can't list projects;
66
+ * org/user-scoped keys can.
67
+ */
68
+ export type ApiKeyScope =
69
+ | { kind: "org-or-user"; canCreate: true }
70
+ | { kind: "project"; projectId: string; canCreate: false };
71
+
72
+ /**
73
+ * Probe the configured API key to find out what it can do. Memoised because we only need
74
+ * to do this once per process.
75
+ */
76
+ let cachedScope: ApiKeyScope | undefined;
77
+ export async function detectApiKeyScope(): Promise<ApiKeyScope> {
78
+ if (cachedScope) return cachedScope;
79
+ const client = makeRawClient();
80
+ try {
81
+ await client.listProjects({ limit: 1 });
82
+ cachedScope = { kind: "org-or-user", canCreate: true };
83
+ return cachedScope;
84
+ } catch (err) {
85
+ const status = (err as { response?: { status?: number } } | undefined)
86
+ ?.response?.status;
87
+ if (status !== 401 && status !== 403) throw err;
88
+ }
89
+ const fixedProjectId = process.env.NEON_PROJECT_ID;
90
+ if (!fixedProjectId || fixedProjectId.trim() === "") {
91
+ throw new Error(
92
+ "API key cannot list projects (looks project-scoped) and NEON_PROJECT_ID is not set. " +
93
+ "Set NEON_PROJECT_ID in packages/config/.env to target a fixed project for the bounded e2e subset.",
94
+ );
95
+ }
96
+ cachedScope = {
97
+ kind: "project",
98
+ projectId: fixedProjectId,
99
+ canCreate: false,
100
+ };
101
+ return cachedScope;
102
+ }
103
+
104
+ /**
105
+ * Delete a project, ignoring "already gone" errors so cleanup is idempotent. Refuses to
106
+ * delete anything that isn't prefixed with {@link PROJECT_PREFIX} so a mis-typed id can
107
+ * never wipe an unrelated project.
108
+ */
109
+ async function deleteProject(projectId: string): Promise<void> {
110
+ const client = makeRawClient();
111
+ const project = await client.getProject(projectId).catch((err) => {
112
+ const status = (err as { response?: { status?: number } } | undefined)
113
+ ?.response?.status;
114
+ if (status === 404 || status === 410) return null;
115
+ throw err;
116
+ });
117
+ if (!project) return;
118
+ if (!project.data.project.name.startsWith(PROJECT_PREFIX)) {
119
+ throw new Error(
120
+ `Refusing to delete project ${projectId} ("${project.data.project.name}"): does not match the e2e prefix.`,
121
+ );
122
+ }
123
+ // Retry on 423 (locked while a previous mutation is in flight) so cleanup is robust.
124
+ const maxAttempts = 12;
125
+ let delay = 500;
126
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
127
+ try {
128
+ await client.deleteProject(projectId);
129
+ return;
130
+ } catch (err) {
131
+ const status = (
132
+ err as { response?: { status?: number } } | undefined
133
+ )?.response?.status;
134
+ if (status === 404 || status === 410) return;
135
+ if (status !== 423 || attempt === maxAttempts) throw err;
136
+ await sleep(delay);
137
+ delay = Math.min(delay * 2, 5_000);
138
+ }
139
+ }
140
+ }
141
+
142
+ /**
143
+ * List every project whose name starts with {@link PROJECT_PREFIX} and delete them.
144
+ * Called once at suite start to mop up orphans from a previous failed run.
145
+ */
146
+ export async function sweepOrphans(): Promise<{ swept: string[] }> {
147
+ const scope = await detectApiKeyScope();
148
+ if (scope.kind === "project") return { swept: [] };
149
+ const client = makeRawClient();
150
+ const swept: string[] = [];
151
+ let cursor: string | undefined;
152
+ while (true) {
153
+ const res = await client.listProjects({
154
+ limit: 100,
155
+ ...(cursor ? { cursor } : {}),
156
+ });
157
+ for (const project of res.data.projects) {
158
+ if (project.name.startsWith(PROJECT_PREFIX)) {
159
+ await deleteProject(project.id);
160
+ swept.push(project.id);
161
+ }
162
+ }
163
+ const next = (res.data as { pagination?: { next?: string } }).pagination
164
+ ?.next;
165
+ if (!next || next === cursor) break;
166
+ cursor = next;
167
+ }
168
+ return { swept };
169
+ }
170
+
171
+ /**
172
+ * A vitest `test.extend` fixture that tracks every project id a test creates and deletes
173
+ * each one in the cleanup phase, even if the test failed mid-way. Use `track(id)` to
174
+ * register ids — cleanup runs regardless of outcome.
175
+ */
176
+ export const e2eTest = test.extend<{
177
+ track: (projectId: string) => void;
178
+ }>({
179
+ // biome-ignore lint/correctness/noEmptyPattern: vitest's fixture API requires this exact shape.
180
+ track: async ({}, use) => {
181
+ const created: string[] = [];
182
+ await use((projectId: string) => {
183
+ created.push(projectId);
184
+ });
185
+ for (const projectId of created) {
186
+ try {
187
+ await deleteProject(projectId);
188
+ } catch (err) {
189
+ // Surface, but don't fail on cleanup errors — the orphan sweep on the next
190
+ // run will mop up anything we miss.
191
+ console.error(
192
+ `[e2e cleanup] failed to delete ${projectId}: ${(err as Error).message}`,
193
+ );
194
+ }
195
+ }
196
+ },
197
+ });
198
+
199
+ /**
200
+ * Some Neon operations are eventually consistent (notably branch creation finishing
201
+ * `init` → `ready`). A small wait avoids racing on subsequent reads.
202
+ */
203
+ function sleep(ms: number): Promise<void> {
204
+ return new Promise((resolve) => setTimeout(resolve, ms));
205
+ }
@@ -0,0 +1,29 @@
1
+ // Loaded by vitest.e2e.config.ts `setupFiles`; not imported statically.
2
+ // fallow-ignore-file unused-file
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { dirname, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ /**
8
+ * Vitest setup file — loads `packages/config/.env` into `process.env` so e2e tests can
9
+ * read `NEON_API_KEY` (and friends). Node 22 has `--env-file` but it's per-process; doing
10
+ * it here keeps the test command short (`pnpm test:e2e`).
11
+ *
12
+ * Lines starting with `#` are treated as comments; everything else is parsed as
13
+ * `KEY=value` (no quoting / interpolation — we keep this minimal on purpose).
14
+ */
15
+ const here = dirname(fileURLToPath(import.meta.url));
16
+ const envPath = resolve(here, "..", ".env");
17
+
18
+ if (existsSync(envPath)) {
19
+ const raw = readFileSync(envPath, "utf-8");
20
+ for (const rawLine of raw.split("\n")) {
21
+ const line = rawLine.trim();
22
+ if (line === "" || line.startsWith("#")) continue;
23
+ const eq = line.indexOf("=");
24
+ if (eq <= 0) continue;
25
+ const key = line.slice(0, eq).trim();
26
+ const value = line.slice(eq + 1).trim();
27
+ if (process.env[key] === undefined) process.env[key] = value;
28
+ }
29
+ }
package/e2e/setup.ts ADDED
@@ -0,0 +1,24 @@
1
+ // Loaded by vitest.e2e.config.ts `setupFiles`; not imported statically.
2
+ // fallow-ignore-file unused-file
3
+ import { beforeAll } from "vitest";
4
+ import { detectApiKeyScope, sweepOrphans } from "./helpers.js";
5
+
6
+ /**
7
+ * Suite-level setup. Runs once before any e2e test:
8
+ * 1. Probes the configured API key to detect its scope. We do this here so a misconfigured
9
+ * environment fails fast with a clear message rather than surfacing as cryptic 403s
10
+ * inside individual tests.
11
+ * 2. When the key is org/user-scoped, sweep any orphaned `neon-ts-e2e-*` projects
12
+ * left over from a previous run.
13
+ */
14
+ beforeAll(async () => {
15
+ const scope = await detectApiKeyScope();
16
+ if (scope.kind === "org-or-user") {
17
+ const { swept } = await sweepOrphans();
18
+ if (swept.length > 0) {
19
+ console.warn(
20
+ `[e2e setup] swept ${swept.length} orphaned project(s) from a previous run.`,
21
+ );
22
+ }
23
+ }
24
+ });
package/package.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "@neondatabase/config",
3
+ "version": "0.0.0",
4
+ "description": "Config-as-Code for the Neon Platform. Define a `neon.ts` policy and inspect/diff/deploy it against the Neon API as plain TypeScript functions.",
5
+ "keywords": [
6
+ "neon",
7
+ "database",
8
+ "postgres",
9
+ "iac",
10
+ "config-as-code",
11
+ "platform"
12
+ ],
13
+ "license": "Apache-2.0",
14
+ "author": {
15
+ "name": "Neon",
16
+ "url": "https://neon.com"
17
+ }
18
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The default entry point re-exports the latest stable version. New consumers should import
3
+ * directly from `@neondatabase/config/v1` to opt in to a specific major.
4
+ */
5
+ export * from "./v1.js";
@@ -0,0 +1,166 @@
1
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
2
+ import { readNeonctlCredentials, resolveApiKey } from "./auth.js";
3
+ import { makeTempRepo, stubCleanNeonEnv } from "./test-utils.js";
4
+
5
+ const cleanups: Array<() => void> = [];
6
+ afterEach(() => {
7
+ while (cleanups.length > 0) cleanups.shift()?.();
8
+ });
9
+
10
+ beforeEach(() => {
11
+ stubCleanNeonEnv();
12
+ });
13
+
14
+ function setupHome(files: Record<string, string | null>): string {
15
+ const repo = makeTempRepo(files);
16
+ cleanups.push(repo.cleanup);
17
+ return repo.root;
18
+ }
19
+
20
+ describe("readNeonctlCredentials", () => {
21
+ test("reads access_token from <home>/.config/neonctl/credentials.json by default", () => {
22
+ const home = setupHome({
23
+ ".config/neonctl/credentials.json": JSON.stringify({
24
+ access_token: "oauth-token-abc",
25
+ refresh_token: "rt-xyz",
26
+ }),
27
+ });
28
+ vi.stubEnv("HOME", home);
29
+ const creds = readNeonctlCredentials();
30
+ expect(creds?.access_token).toBe("oauth-token-abc");
31
+ expect(creds?.refresh_token).toBe("rt-xyz");
32
+ });
33
+
34
+ test("honours NEONCTL_CONFIG_DIR over the default location", () => {
35
+ const home = setupHome({
36
+ ".config/neonctl/credentials.json": JSON.stringify({
37
+ access_token: "default-loc",
38
+ }),
39
+ "custom/credentials.json": JSON.stringify({
40
+ access_token: "from-env-dir",
41
+ }),
42
+ });
43
+ vi.stubEnv("HOME", home);
44
+ vi.stubEnv("NEONCTL_CONFIG_DIR", `${home}/custom`);
45
+ const creds = readNeonctlCredentials();
46
+ expect(creds?.access_token).toBe("from-env-dir");
47
+ });
48
+
49
+ test("honours explicit configDir over the env var", () => {
50
+ const home = setupHome({
51
+ ".config/neonctl/credentials.json": JSON.stringify({
52
+ access_token: "default-loc",
53
+ }),
54
+ "env/credentials.json": JSON.stringify({
55
+ access_token: "from-env-dir",
56
+ }),
57
+ "opt/credentials.json": JSON.stringify({
58
+ access_token: "from-option",
59
+ }),
60
+ });
61
+ vi.stubEnv("HOME", home);
62
+ vi.stubEnv("NEONCTL_CONFIG_DIR", `${home}/env`);
63
+ const creds = readNeonctlCredentials({ configDir: `${home}/opt` });
64
+ expect(creds?.access_token).toBe("from-option");
65
+ });
66
+
67
+ test("returns null when the file is missing", () => {
68
+ const home = setupHome({ ".config/neonctl/.keep": "" });
69
+ vi.stubEnv("HOME", home);
70
+ expect(readNeonctlCredentials()).toBeNull();
71
+ });
72
+
73
+ test("returns null on malformed JSON instead of throwing", () => {
74
+ const home = setupHome({
75
+ ".config/neonctl/credentials.json": "not json",
76
+ });
77
+ vi.stubEnv("HOME", home);
78
+ expect(readNeonctlCredentials()).toBeNull();
79
+ });
80
+
81
+ test("returns null when access_token is missing or empty", () => {
82
+ const home = setupHome({
83
+ ".config/neonctl/credentials.json": JSON.stringify({
84
+ refresh_token: "rt-only",
85
+ }),
86
+ });
87
+ vi.stubEnv("HOME", home);
88
+ expect(readNeonctlCredentials()).toBeNull();
89
+ const home2 = setupHome({
90
+ ".config/neonctl/credentials.json": JSON.stringify({
91
+ access_token: "",
92
+ }),
93
+ });
94
+ vi.stubEnv("HOME", home2);
95
+ expect(readNeonctlCredentials()).toBeNull();
96
+ });
97
+
98
+ test("returns null when no home dir resolvable", () => {
99
+ // `stubCleanNeonEnv()` already cleared HOME and USERPROFILE.
100
+ expect(readNeonctlCredentials()).toBeNull();
101
+ });
102
+
103
+ test("falls back to USERPROFILE on Windows-style env", () => {
104
+ const winHome = setupHome({
105
+ ".config/neonctl/credentials.json": JSON.stringify({
106
+ access_token: "win-token",
107
+ }),
108
+ });
109
+ vi.stubEnv("USERPROFILE", winHome);
110
+ const creds = readNeonctlCredentials();
111
+ expect(creds?.access_token).toBe("win-token");
112
+ });
113
+ });
114
+
115
+ describe("resolveApiKey — priority chain", () => {
116
+ test("explicit option wins over env wins over credentials.json", () => {
117
+ const home = setupHome({
118
+ ".config/neonctl/credentials.json": JSON.stringify({
119
+ access_token: "from-file",
120
+ }),
121
+ });
122
+ vi.stubEnv("HOME", home);
123
+ vi.stubEnv("NEON_API_KEY", "from-env");
124
+ expect(resolveApiKey({ apiKey: "from-option" })).toEqual({
125
+ token: "from-option",
126
+ source: "option",
127
+ });
128
+
129
+ expect(resolveApiKey()).toEqual({ token: "from-env", source: "env" });
130
+
131
+ vi.stubEnv("NEON_API_KEY", undefined);
132
+ expect(resolveApiKey()).toEqual({
133
+ token: "from-file",
134
+ source: "neonctl",
135
+ });
136
+ });
137
+
138
+ test("returns null when no source provides a token", () => {
139
+ const home = setupHome({ ".config/neonctl/.keep": "" });
140
+ vi.stubEnv("HOME", home);
141
+ expect(resolveApiKey()).toBeNull();
142
+ });
143
+
144
+ test("treats whitespace-only option / env as missing", () => {
145
+ const home = setupHome({
146
+ ".config/neonctl/credentials.json": JSON.stringify({
147
+ access_token: "from-file",
148
+ }),
149
+ });
150
+ vi.stubEnv("HOME", home);
151
+ vi.stubEnv("NEON_API_KEY", " ");
152
+ expect(resolveApiKey({ apiKey: " " })).toEqual({
153
+ token: "from-file",
154
+ source: "neonctl",
155
+ });
156
+ });
157
+
158
+ test("trims whitespace around the resolved token", () => {
159
+ const home = setupHome({ ".config/neonctl/.keep": "" });
160
+ vi.stubEnv("HOME", home);
161
+ expect(resolveApiKey({ apiKey: " napi_x " })).toEqual({
162
+ token: "napi_x",
163
+ source: "option",
164
+ });
165
+ });
166
+ });