neon 2.29.2 → 2.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,7 +8,7 @@ The Neon CLI is a command-line interface that lets you manage [Neon Serverless P
8
8
  npm i -g neon
9
9
  ```
10
10
 
11
- Requires Node.js 18.0 or higher.
11
+ Requires Node.js 20.19 or higher.
12
12
 
13
13
  **Howebrew**
14
14
 
@@ -28,7 +28,7 @@ Download a binary file [here](https://github.com/neondatabase/neonctl/releases).
28
28
  npm update -g neon
29
29
  ```
30
30
 
31
- Requires Node.js 18.0 or higher.
31
+ Requires Node.js 20.19 or higher.
32
32
 
33
33
  **Howebrew**
34
34
 
package/dist/api.js CHANGED
@@ -287,6 +287,12 @@ export const getApiClient = ({ apiKey, apiHost }) => {
287
287
  headers["Content-Type"] = ContentType.Json;
288
288
  payload = JSON.stringify(params.body);
289
289
  }
290
+ // Caller-supplied headers win over the defaults set above.
291
+ if (params.headers) {
292
+ for (const [key, value] of Object.entries(params.headers)) {
293
+ headers[key] = value;
294
+ }
295
+ }
290
296
  let response;
291
297
  try {
292
298
  response = await timedFetch(url, {
@@ -0,0 +1,278 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import YAML from "yaml";
4
+ import { DEFAULT_SPEC_URL, getEndpoints, loadSpec } from "../utils/openapi.js";
5
+ import { writer } from "../writer.js";
6
+ const HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
7
+ // ── Pure helpers (unit-tested) ───────────────────────────────────────────────
8
+ /**
9
+ * Coerce a raw string into a typed JSON value: booleans, `null`, integers,
10
+ * floats, and JSON arrays/objects are parsed; everything else stays a string.
11
+ */
12
+ export function parseTypedValue(raw) {
13
+ if (raw === "true")
14
+ return true;
15
+ if (raw === "false")
16
+ return false;
17
+ if (raw === "null")
18
+ return null;
19
+ if (/^-?\d+$/.test(raw))
20
+ return Number.parseInt(raw, 10);
21
+ if (/^-?\d*\.\d+$/.test(raw))
22
+ return Number.parseFloat(raw);
23
+ if (raw.startsWith("[") || raw.startsWith("{")) {
24
+ try {
25
+ return JSON.parse(raw);
26
+ }
27
+ catch {
28
+ return raw;
29
+ }
30
+ }
31
+ return raw;
32
+ }
33
+ /** Split a `key=value` pair on the first `=`. */
34
+ export function parseKeyValue(input) {
35
+ const eq = input.indexOf("=");
36
+ if (eq === -1) {
37
+ throw new Error(`Invalid "key=value" pair: "${input}".`);
38
+ }
39
+ return { key: input.slice(0, eq), value: input.slice(eq + 1) };
40
+ }
41
+ /**
42
+ * Assign `value` into `target` at a dot-delimited path, creating intermediate
43
+ * objects as needed. Enables `-F branch.name=dev` → `{ branch: { name: "dev" } }`,
44
+ * matching the nested shape of Neon request bodies.
45
+ */
46
+ export function setDeep(target, dottedKey, value) {
47
+ const parts = dottedKey.split(".");
48
+ let node = target;
49
+ for (let i = 0; i < parts.length - 1; i++) {
50
+ const part = parts[i];
51
+ const next = node[part];
52
+ if (typeof next !== "object" || next === null || Array.isArray(next)) {
53
+ node[part] = {};
54
+ }
55
+ node = node[part];
56
+ }
57
+ node[parts[parts.length - 1]] = value;
58
+ }
59
+ /** Build a JSON body object from typed `-F` and string `-f` field pairs. */
60
+ export function buildBody(fields, rawFields) {
61
+ const body = {};
62
+ for (const field of fields) {
63
+ const { key, value } = parseKeyValue(field);
64
+ setDeep(body, key, parseTypedValue(value));
65
+ }
66
+ for (const field of rawFields) {
67
+ const { key, value } = parseKeyValue(field);
68
+ setDeep(body, key, value);
69
+ }
70
+ return body;
71
+ }
72
+ /** Build a query-string map from `-Q key=value` pairs. */
73
+ export function buildQuery(pairs) {
74
+ const query = {};
75
+ for (const pair of pairs) {
76
+ const { key, value } = parseKeyValue(pair);
77
+ query[key] = value;
78
+ }
79
+ return query;
80
+ }
81
+ /** Build a header map from `-H key:value` pairs. */
82
+ export function parseHeaders(pairs) {
83
+ const headers = {};
84
+ for (const pair of pairs) {
85
+ const idx = pair.indexOf(":");
86
+ if (idx === -1) {
87
+ throw new Error(`Invalid header "${pair}". Expected "key:value".`);
88
+ }
89
+ headers[pair.slice(0, idx).trim()] = pair.slice(idx + 1).trim();
90
+ }
91
+ return headers;
92
+ }
93
+ function assertMethod(method) {
94
+ if (!HTTP_METHODS.includes(method)) {
95
+ throw new Error(`Unsupported method "${method}". Use one of: ${HTTP_METHODS.join(", ")}.`);
96
+ }
97
+ }
98
+ // ── I/O helpers ──────────────────────────────────────────────────────────────
99
+ async function readStdin() {
100
+ const chunks = [];
101
+ for await (const chunk of process.stdin) {
102
+ chunks.push(Buffer.from(chunk));
103
+ }
104
+ return Buffer.concat(chunks).toString("utf8");
105
+ }
106
+ /** Resolve `--data`: `-` reads stdin, `@file` reads a file, else the literal string. Parsed as JSON when possible. */
107
+ async function readData(data) {
108
+ let raw;
109
+ if (data === "-") {
110
+ raw = await readStdin();
111
+ }
112
+ else if (data.startsWith("@")) {
113
+ raw = readFileSync(resolve(data.slice(1)), "utf8");
114
+ }
115
+ else {
116
+ raw = data;
117
+ }
118
+ try {
119
+ return JSON.parse(raw);
120
+ }
121
+ catch {
122
+ return raw;
123
+ }
124
+ }
125
+ const toStrings = (values) => (values ?? []).map(String);
126
+ async function listEndpoints(args) {
127
+ const spec = await loadSpec({
128
+ configDir: args.configDir,
129
+ specUrl: args.specUrl,
130
+ refresh: args.refresh,
131
+ });
132
+ if (!spec) {
133
+ throw new Error(`Could not load the Neon OpenAPI spec from ${args.specUrl}. ` +
134
+ "Check your network connection or pass --spec-url.");
135
+ }
136
+ const endpoints = getEndpoints(spec).map((endpoint) => ({
137
+ method: endpoint.method,
138
+ path: endpoint.path,
139
+ summary: endpoint.summary ?? "",
140
+ }));
141
+ writer(args).end(endpoints, {
142
+ fields: ["method", "path", "summary"],
143
+ title: `Neon API endpoints (${endpoints.length})`,
144
+ emptyMessage: "No endpoints found in the spec.",
145
+ });
146
+ }
147
+ async function runRequest(args) {
148
+ const path = args.path;
149
+ if (!path) {
150
+ throw new Error("Missing API path. Usage: neon api <path> (e.g. neon api /projects). " +
151
+ "Run `neon api --list` to see available routes.");
152
+ }
153
+ if (!path.startsWith("/")) {
154
+ throw new Error(`Invalid path "${path}". API paths must start with "/". ` +
155
+ "Run `neon api --list` to see available routes.");
156
+ }
157
+ const fields = toStrings(args.field);
158
+ const rawFields = toStrings(args.rawField);
159
+ let body;
160
+ if (args.data !== undefined) {
161
+ body = await readData(args.data);
162
+ }
163
+ else if (fields.length > 0 || rawFields.length > 0) {
164
+ body = buildBody(fields, rawFields);
165
+ }
166
+ const hasBody = body !== undefined;
167
+ const method = String(args.method ?? (hasBody ? "POST" : "GET")).toUpperCase();
168
+ assertMethod(method);
169
+ const query = buildQuery(toStrings(args.query));
170
+ const headers = parseHeaders(toStrings(args.header));
171
+ const params = {
172
+ path,
173
+ method,
174
+ ...(Object.keys(query).length > 0 ? { query } : {}),
175
+ ...(hasBody ? { body } : {}),
176
+ ...(Object.keys(headers).length > 0 ? { headers } : {}),
177
+ };
178
+ const response = await args.apiClient.request(params);
179
+ const out = process.stdout;
180
+ if (args.include) {
181
+ out.write(`HTTP ${response.status} ${response.statusText}\n`);
182
+ for (const [key, value] of Object.entries(response.headers)) {
183
+ out.write(`${key}: ${value}\n`);
184
+ }
185
+ out.write("\n");
186
+ }
187
+ if (response.data === undefined) {
188
+ return;
189
+ }
190
+ if (args.output === "yaml") {
191
+ out.write(YAML.stringify(response.data));
192
+ }
193
+ else {
194
+ out.write(`${JSON.stringify(response.data, null, 2)}\n`);
195
+ }
196
+ }
197
+ export const command = "api [path]";
198
+ export const describe = "Call any Neon API route directly (authenticated passthrough)";
199
+ export const builder = (argv) => argv
200
+ .usage("$0 api <path> [options]")
201
+ .positional("path", {
202
+ type: "string",
203
+ describe: 'API path beginning with "/" (e.g. /projects or ' +
204
+ "/projects/{project_id}/branches). Use `list` to list endpoints.",
205
+ })
206
+ .options({
207
+ method: {
208
+ alias: "X",
209
+ type: "string",
210
+ describe: "HTTP method (GET, POST, PUT, PATCH, DELETE). " +
211
+ "Defaults to GET, or POST when a body is provided.",
212
+ },
213
+ field: {
214
+ alias: "F",
215
+ type: "array",
216
+ string: true,
217
+ describe: "Body field key=value (repeatable). Dot-notation nests " +
218
+ "objects (e.g. -F branch.name=dev); values are typed " +
219
+ "(numbers, booleans, null, JSON).",
220
+ },
221
+ "raw-field": {
222
+ alias: "f",
223
+ type: "array",
224
+ string: true,
225
+ describe: "Body field key=value with the value kept as a raw string.",
226
+ },
227
+ data: {
228
+ alias: "d",
229
+ type: "string",
230
+ describe: "Raw request body: a JSON string, @file, or - for stdin. " +
231
+ "Overrides --field.",
232
+ },
233
+ query: {
234
+ alias: "Q",
235
+ type: "array",
236
+ string: true,
237
+ describe: "Query parameter key=value (repeatable).",
238
+ },
239
+ header: {
240
+ alias: "H",
241
+ type: "array",
242
+ string: true,
243
+ describe: "Extra request header key:value (repeatable).",
244
+ },
245
+ include: {
246
+ alias: "i",
247
+ type: "boolean",
248
+ default: false,
249
+ describe: "Print the response status and headers before the body.",
250
+ },
251
+ list: {
252
+ type: "boolean",
253
+ default: false,
254
+ describe: "List available API endpoints from the OpenAPI spec.",
255
+ },
256
+ refresh: {
257
+ type: "boolean",
258
+ default: false,
259
+ describe: "Refresh the cached OpenAPI spec (used with --list).",
260
+ },
261
+ "spec-url": {
262
+ type: "string",
263
+ default: process.env.NEON_API_SPEC_URL ?? DEFAULT_SPEC_URL,
264
+ hidden: true,
265
+ describe: "OpenAPI spec URL used by --list.",
266
+ },
267
+ })
268
+ .example("$0 api /projects", "List your projects")
269
+ .example("$0 api /projects/{id}/branches -X POST -F branch.name=dev", "Create a branch")
270
+ .example("$0 api --list", "List every available API route");
271
+ export const handler = async (args) => {
272
+ const apiArgs = args;
273
+ if (apiArgs.list || apiArgs.path === "list" || apiArgs.path === "ls") {
274
+ await listEndpoints(apiArgs);
275
+ return;
276
+ }
277
+ await runRequest(apiArgs);
278
+ };
@@ -1,3 +1,4 @@
1
+ import * as api from "./api.js";
1
2
  import * as auth from "./auth.js";
2
3
  import * as bootstrap from "./bootstrap.js";
3
4
  import * as branches from "./branches.js";
@@ -26,6 +27,7 @@ import * as users from "./user.js";
26
27
  import * as vpcEndpoints from "./vpc_endpoints.js";
27
28
  export default [
28
29
  auth,
30
+ api,
29
31
  users,
30
32
  orgs,
31
33
  projects,
package/dist/index.js CHANGED
@@ -14,6 +14,9 @@ import { log } from "./log.js";
14
14
  import pkg from "./pkg.js";
15
15
  import { fillInArgs } from "./utils/middlewares.js";
16
16
  const NO_SUBCOMMANDS_VERBS = [
17
+ // `api <path>` has a handler but no subcommands (like `status`), so the
18
+ // help-fallback middleware must not intercept a bare `neon api /projects`.
19
+ "api",
17
20
  // aliases
18
21
  "auth",
19
22
  "login",
@@ -0,0 +1,114 @@
1
+ // Lightweight loader for the Neon OpenAPI spec, used by `neon api --list` to
2
+ // enumerate the available routes. The `neon api <path>` request path does NOT
3
+ // depend on this module — it is a pure passthrough — so a stale or unreachable
4
+ // spec never blocks a real API call. Listing degrades gracefully: fresh cache →
5
+ // live fetch → stale cache → clear error.
6
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import { log } from "../log.js";
9
+ /** Public URL of the released Neon OpenAPI v2 spec. */
10
+ export const DEFAULT_SPEC_URL = "https://neon.com/api_spec/release/v2.json";
11
+ const CACHE_FILE = "openapi-spec.json";
12
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
13
+ const FETCH_TIMEOUT_MS = 10000;
14
+ const HTTP_METHODS = new Set([
15
+ "get",
16
+ "post",
17
+ "put",
18
+ "patch",
19
+ "delete",
20
+ "head",
21
+ "options",
22
+ ]);
23
+ async function fetchSpec(url) {
24
+ const controller = new AbortController();
25
+ const timer = setTimeout(() => {
26
+ controller.abort();
27
+ }, FETCH_TIMEOUT_MS);
28
+ try {
29
+ const res = await fetch(url, {
30
+ signal: controller.signal,
31
+ headers: { Accept: "application/json" },
32
+ });
33
+ if (!res.ok) {
34
+ throw new Error(`Failed to fetch OpenAPI spec (${res.status} ${res.statusText})`);
35
+ }
36
+ return (await res.json());
37
+ }
38
+ finally {
39
+ clearTimeout(timer);
40
+ }
41
+ }
42
+ function readCache(cachePath) {
43
+ try {
44
+ return JSON.parse(readFileSync(cachePath, "utf8"));
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ function writeCache(cachePath, data) {
51
+ try {
52
+ mkdirSync(dirname(cachePath), { recursive: true });
53
+ writeFileSync(cachePath, JSON.stringify(data));
54
+ }
55
+ catch (err) {
56
+ log.debug("Failed to cache OpenAPI spec: %s", err);
57
+ }
58
+ }
59
+ /**
60
+ * Load the Neon OpenAPI spec, preferring a fresh on-disk cache, then a live
61
+ * fetch (which refreshes the cache), then a stale cache as a last resort.
62
+ * Returns `null` when no spec can be obtained.
63
+ */
64
+ export async function loadSpec(opts) {
65
+ const { configDir, specUrl, refresh } = opts;
66
+ const cachePath = join(configDir, CACHE_FILE);
67
+ if (!refresh) {
68
+ const cached = readCache(cachePath);
69
+ if (cached &&
70
+ cached.specUrl === specUrl &&
71
+ Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
72
+ log.debug("Using cached OpenAPI spec from %s", cachePath);
73
+ return cached.spec;
74
+ }
75
+ }
76
+ try {
77
+ log.debug("Fetching OpenAPI spec from %s", specUrl);
78
+ const spec = await fetchSpec(specUrl);
79
+ writeCache(cachePath, { fetchedAt: Date.now(), specUrl, spec });
80
+ return spec;
81
+ }
82
+ catch (err) {
83
+ log.debug("Failed to fetch OpenAPI spec: %s", err);
84
+ const stale = readCache(cachePath);
85
+ if (stale && stale.specUrl === specUrl) {
86
+ log.debug("Falling back to stale cached OpenAPI spec");
87
+ return stale.spec;
88
+ }
89
+ return null;
90
+ }
91
+ }
92
+ /** Flatten a spec into a sorted list of routes (by path, then method). */
93
+ export function getEndpoints(spec) {
94
+ const endpoints = [];
95
+ for (const [path, item] of Object.entries(spec.paths ?? {})) {
96
+ for (const [method, op] of Object.entries(item)) {
97
+ if (!HTTP_METHODS.has(method.toLowerCase())) {
98
+ continue;
99
+ }
100
+ const operation = (op ?? {});
101
+ endpoints.push({
102
+ method: method.toUpperCase(),
103
+ path,
104
+ summary: operation.summary,
105
+ operationId: operation.operationId,
106
+ tags: operation.tags ?? [],
107
+ });
108
+ }
109
+ }
110
+ endpoints.sort((a, b) => a.path === b.path
111
+ ? a.method.localeCompare(b.method)
112
+ : a.path.localeCompare(b.path));
113
+ return endpoints;
114
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neon",
3
- "version": "2.29.2",
3
+ "version": "2.30.0",
4
4
  "description": "CLI tool for Neon Serverless Postgres",
5
5
  "keywords": [
6
6
  "neon",
@@ -31,7 +31,7 @@
31
31
  "package.json"
32
32
  ],
33
33
  "engines": {
34
- "node": ">=20.18.1"
34
+ "node": ">=20.19.0"
35
35
  },
36
36
  "dependencies": {
37
37
  "@hono/node-server": "2.0.4",
@@ -42,7 +42,7 @@
42
42
  "cliui": "8.0.1",
43
43
  "diff": "5.2.0",
44
44
  "fflate": "^0.8.3",
45
- "neon-init": "0.19.0",
45
+ "neon-init": "0.20.0",
46
46
  "open": "10.1.0",
47
47
  "openid-client": "6.8.1",
48
48
  "pg-protocol": "^1.14.0",
@@ -51,10 +51,10 @@
51
51
  "which": "3.0.1",
52
52
  "yaml": "2.4.5",
53
53
  "yargs": "17.7.2",
54
- "@neon/sdk": "0.1.0",
55
- "@neon/config": "0.8.1",
56
- "@neon/config-runtime": "0.8.1",
57
- "@neon/env": "0.9.0"
54
+ "@neon/config": "0.9.0",
55
+ "@neon/sdk": "0.2.0",
56
+ "@neon/config-runtime": "0.9.0",
57
+ "@neon/env": "0.10.0"
58
58
  },
59
59
  "optionalDependencies": {
60
60
  "esbuild": "0.28.0"