neonctl 2.37.1 → 2.38.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.
Files changed (159) hide show
  1. package/README.md +15 -700
  2. package/bin/cli.js +3 -0
  3. package/package.json +8 -75
  4. package/dist/analytics.js +0 -168
  5. package/dist/api.js +0 -720
  6. package/dist/auth.js +0 -125
  7. package/dist/callback.html +0 -60
  8. package/dist/cli.js +0 -9
  9. package/dist/commands/api.js +0 -278
  10. package/dist/commands/auth.js +0 -214
  11. package/dist/commands/bootstrap.js +0 -481
  12. package/dist/commands/branches.js +0 -488
  13. package/dist/commands/bucket.js +0 -549
  14. package/dist/commands/checkout.js +0 -321
  15. package/dist/commands/config.js +0 -626
  16. package/dist/commands/connection_string.js +0 -172
  17. package/dist/commands/data_api.js +0 -284
  18. package/dist/commands/databases.js +0 -82
  19. package/dist/commands/deploy.js +0 -26
  20. package/dist/commands/dev.js +0 -698
  21. package/dist/commands/diff.js +0 -222
  22. package/dist/commands/env.js +0 -189
  23. package/dist/commands/functions.js +0 -373
  24. package/dist/commands/index.js +0 -62
  25. package/dist/commands/init.js +0 -73
  26. package/dist/commands/inspect.js +0 -65
  27. package/dist/commands/ip_allow.js +0 -137
  28. package/dist/commands/link.js +0 -1121
  29. package/dist/commands/neon_auth.js +0 -1028
  30. package/dist/commands/operations.js +0 -28
  31. package/dist/commands/orgs.js +0 -24
  32. package/dist/commands/projects.js +0 -413
  33. package/dist/commands/psql.js +0 -62
  34. package/dist/commands/roles.js +0 -65
  35. package/dist/commands/schema_diff.js +0 -151
  36. package/dist/commands/set_context.js +0 -29
  37. package/dist/commands/snapshots.js +0 -455
  38. package/dist/commands/status.js +0 -40
  39. package/dist/commands/user.js +0 -15
  40. package/dist/commands/vpc_endpoints.js +0 -134
  41. package/dist/config.js +0 -11
  42. package/dist/config_format.js +0 -72
  43. package/dist/context.js +0 -231
  44. package/dist/current_branch_fast_path.js +0 -55
  45. package/dist/dev/env.js +0 -244
  46. package/dist/dev/functions.js +0 -70
  47. package/dist/dev/inputs.js +0 -63
  48. package/dist/dev/runtime.js +0 -146
  49. package/dist/env.js +0 -36
  50. package/dist/env_file.js +0 -159
  51. package/dist/errors.js +0 -80
  52. package/dist/functions_api.js +0 -48
  53. package/dist/help.js +0 -146
  54. package/dist/index.js +0 -240
  55. package/dist/log.js +0 -18
  56. package/dist/parameters.gen.js +0 -480
  57. package/dist/pkg.js +0 -25
  58. package/dist/psql/cli.js +0 -53
  59. package/dist/psql/command/cmd_cond.js +0 -437
  60. package/dist/psql/command/cmd_connect.js +0 -820
  61. package/dist/psql/command/cmd_copy.js +0 -1035
  62. package/dist/psql/command/cmd_describe.js +0 -1815
  63. package/dist/psql/command/cmd_format.js +0 -948
  64. package/dist/psql/command/cmd_io.js +0 -2193
  65. package/dist/psql/command/cmd_lo.js +0 -393
  66. package/dist/psql/command/cmd_meta.js +0 -969
  67. package/dist/psql/command/cmd_misc.js +0 -187
  68. package/dist/psql/command/cmd_pipeline.js +0 -1148
  69. package/dist/psql/command/cmd_restrict.js +0 -171
  70. package/dist/psql/command/cmd_show.js +0 -766
  71. package/dist/psql/command/dispatch.js +0 -343
  72. package/dist/psql/command/inputQueue.js +0 -42
  73. package/dist/psql/command/shared.js +0 -71
  74. package/dist/psql/complete/filenames.js +0 -139
  75. package/dist/psql/complete/index.js +0 -104
  76. package/dist/psql/complete/matcher.js +0 -315
  77. package/dist/psql/complete/psqlVars.js +0 -249
  78. package/dist/psql/complete/queries.js +0 -493
  79. package/dist/psql/complete/rules.js +0 -2424
  80. package/dist/psql/core/common.js +0 -1253
  81. package/dist/psql/core/help.js +0 -576
  82. package/dist/psql/core/mainloop.js +0 -1360
  83. package/dist/psql/core/prompt.js +0 -439
  84. package/dist/psql/core/settings.js +0 -686
  85. package/dist/psql/core/sqlHelp.js +0 -1066
  86. package/dist/psql/core/startup.js +0 -846
  87. package/dist/psql/core/syncVars.js +0 -116
  88. package/dist/psql/core/variables.js +0 -287
  89. package/dist/psql/describe/formatters.js +0 -1330
  90. package/dist/psql/describe/processNamePattern.js +0 -270
  91. package/dist/psql/describe/queries.js +0 -2452
  92. package/dist/psql/describe/versionGate.js +0 -44
  93. package/dist/psql/index.js +0 -2030
  94. package/dist/psql/io/history.js +0 -299
  95. package/dist/psql/io/input.js +0 -120
  96. package/dist/psql/io/lineEditor/buffer.js +0 -325
  97. package/dist/psql/io/lineEditor/complete.js +0 -227
  98. package/dist/psql/io/lineEditor/filename.js +0 -159
  99. package/dist/psql/io/lineEditor/index.js +0 -893
  100. package/dist/psql/io/lineEditor/keymap.js +0 -745
  101. package/dist/psql/io/lineEditor/vt100.js +0 -363
  102. package/dist/psql/io/pgpass.js +0 -202
  103. package/dist/psql/io/pgservice.js +0 -194
  104. package/dist/psql/io/psqlrc.js +0 -422
  105. package/dist/psql/print/aligned.js +0 -1748
  106. package/dist/psql/print/asciidoc.js +0 -230
  107. package/dist/psql/print/crosstab.js +0 -463
  108. package/dist/psql/print/csv.js +0 -76
  109. package/dist/psql/print/html.js +0 -240
  110. package/dist/psql/print/json.js +0 -96
  111. package/dist/psql/print/latex.js +0 -379
  112. package/dist/psql/print/pager.js +0 -267
  113. package/dist/psql/print/troff.js +0 -240
  114. package/dist/psql/print/unaligned.js +0 -99
  115. package/dist/psql/print/units.js +0 -188
  116. package/dist/psql/scanner/slash.js +0 -515
  117. package/dist/psql/scanner/sql.js +0 -914
  118. package/dist/psql/scanner/stringutils.js +0 -394
  119. package/dist/psql/types/backslash.js +0 -1
  120. package/dist/psql/types/connection.js +0 -1
  121. package/dist/psql/types/index.js +0 -7
  122. package/dist/psql/types/printer.js +0 -1
  123. package/dist/psql/types/repl.js +0 -1
  124. package/dist/psql/types/scanner.js +0 -24
  125. package/dist/psql/types/settings.js +0 -1
  126. package/dist/psql/types/variables.js +0 -1
  127. package/dist/psql/wire/connection.js +0 -2857
  128. package/dist/psql/wire/copy.js +0 -108
  129. package/dist/psql/wire/notify.js +0 -59
  130. package/dist/psql/wire/pipeline.js +0 -521
  131. package/dist/psql/wire/protocol.js +0 -466
  132. package/dist/psql/wire/sasl.js +0 -294
  133. package/dist/psql/wire/tls.js +0 -602
  134. package/dist/storage_api.js +0 -147
  135. package/dist/test_utils/fixtures.js +0 -121
  136. package/dist/test_utils/oauth_server.js +0 -9
  137. package/dist/types.js +0 -1
  138. package/dist/utils/ai_gateway_notice.js +0 -180
  139. package/dist/utils/api_enums.js +0 -33
  140. package/dist/utils/auth.js +0 -5
  141. package/dist/utils/branch_notice.js +0 -22
  142. package/dist/utils/branch_picker.js +0 -103
  143. package/dist/utils/compute_units.js +0 -28
  144. package/dist/utils/config_diff.js +0 -185
  145. package/dist/utils/enrichers.js +0 -161
  146. package/dist/utils/esbuild.js +0 -158
  147. package/dist/utils/formats.js +0 -18
  148. package/dist/utils/git_diff.js +0 -90
  149. package/dist/utils/inspect_db.js +0 -153
  150. package/dist/utils/inspect_queries.js +0 -372
  151. package/dist/utils/middlewares.js +0 -20
  152. package/dist/utils/openapi.js +0 -114
  153. package/dist/utils/package_manager.js +0 -68
  154. package/dist/utils/point_in_time.js +0 -56
  155. package/dist/utils/psql.js +0 -120
  156. package/dist/utils/string.js +0 -5
  157. package/dist/utils/ui.js +0 -59
  158. package/dist/utils/zip.js +0 -4
  159. package/dist/writer.js +0 -97
package/dist/env_file.js DELETED
@@ -1,159 +0,0 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- /**
4
- * Default dotenv file `env pull` writes to: `.env` when one already exists in the working
5
- * directory (update where secrets already live), otherwise `.env.local` — matching the
6
- * `vercel env pull` convention. An explicit `--file` always wins over this.
7
- */
8
- export const resolveEnvFilePath = (cwd, file) => {
9
- if (file)
10
- return join(cwd, file);
11
- if (existsSync(join(cwd, ".env")))
12
- return join(cwd, ".env");
13
- return join(cwd, ".env.local");
14
- };
15
- /**
16
- * Merge `updates` into the dotenv content at `path`, preserving every other line
17
- * (comments, blank lines, unrelated keys) and the file's existing order. Keys present in
18
- * both are updated in place; keys only in `updates` are appended. A non-existent file is
19
- * treated as empty. When `managedKeys` is given, any owned key on disk that is absent from
20
- * `updates` is removed. Returns the keys written and the (managed) keys removed.
21
- */
22
- export const mergeEnvFile = (path, updates, options = {}) => {
23
- const original = existsSync(path) ? readFileSync(path, "utf8") : "";
24
- const { content, written, removed } = mergeEnvContent(original, updates, options);
25
- writeFileSync(path, content);
26
- return { written, removed };
27
- };
28
- /**
29
- * Pure core of {@link mergeEnvFile}: takes the current file content and the updates, and
30
- * returns the new content plus which keys were written / removed. Kept side-effect-free so
31
- * it can be unit-tested without touching the filesystem.
32
- */
33
- export const mergeEnvContent = (original, updates, options = {}) => {
34
- const keys = Object.keys(updates);
35
- // Owned keys the current pull did not produce: stale Neon-managed vars to prune. Anything
36
- // not in `managedKeys` is always kept, so a user's own lines are never removed.
37
- const stale = new Set([...(options.managedKeys ?? [])].filter((key) => !(key in updates)));
38
- if (keys.length === 0 && stale.size === 0) {
39
- return { content: original, written: [], removed: [] };
40
- }
41
- const remaining = new Set(keys);
42
- const removed = [];
43
- const lines = original === "" ? [] : original.split("\n");
44
- // Walk the file: drop stale owned lines, update existing keys in place (so their position
45
- // and any surrounding comments are preserved), and pass everything else through untouched.
46
- const updatedLines = [];
47
- for (const line of lines) {
48
- const key = parseKey(line);
49
- if (key !== null && stale.has(key)) {
50
- removed.push(key);
51
- continue;
52
- }
53
- if (key !== null && remaining.has(key)) {
54
- remaining.delete(key);
55
- updatedLines.push(formatLine(key, updates[key]));
56
- continue;
57
- }
58
- updatedLines.push(line);
59
- }
60
- // Append keys that weren't already present, in the order they were given.
61
- const appended = keys
62
- .filter((key) => remaining.has(key))
63
- .map((key) => formatLine(key, updates[key]));
64
- const body = trimTrailingBlank(updatedLines);
65
- const content = [...body, ...appended].join("\n");
66
- return {
67
- // A dotenv file ends with a trailing newline.
68
- content: content === "" ? "" : `${content}\n`,
69
- written: keys,
70
- removed,
71
- };
72
- };
73
- /**
74
- * Read a dotenv file at `path` into a plain `{ KEY: value }` map. A non-existent file is an
75
- * error (callers pass an explicit `--env` path, so a typo should fail loudly rather than
76
- * silently load nothing). Quotes are stripped and `\"` / `\\` unescaped, matching the
77
- * quoting {@link mergeEnvFile} writes. Comments, blank lines, and non-assignment lines are
78
- * ignored.
79
- */
80
- export const readEnvFile = (path) => {
81
- if (!existsSync(path)) {
82
- throw new Error(`Env file not found: ${path}`);
83
- }
84
- const out = {};
85
- for (const line of readFileSync(path, "utf8").split("\n")) {
86
- const parsed = parseAssignment(line);
87
- if (parsed)
88
- out[parsed.key] = parsed.value;
89
- }
90
- return out;
91
- };
92
- /**
93
- * Load a dotenv file into `process.env` so values are available to anything read later
94
- * (e.g. a `neon.ts` whose function `env` values come from `process.env.X`). Existing
95
- * `process.env` entries are **not** overridden — an already-exported var wins over the
96
- * file, matching dotenv's default. Returns the keys that were applied.
97
- */
98
- export const loadEnvFileIntoProcess = (path) => {
99
- const parsed = readEnvFile(path);
100
- const applied = [];
101
- for (const [key, value] of Object.entries(parsed)) {
102
- if (process.env[key] === undefined) {
103
- process.env[key] = value;
104
- applied.push(key);
105
- }
106
- }
107
- return applied;
108
- };
109
- /**
110
- * Extract the variable name from a dotenv line, or `null` for comments / blank lines / any
111
- * line that isn't a `KEY=value` assignment. Tolerates a leading `export ` and surrounding
112
- * whitespace, matching common `.env` styles.
113
- */
114
- const parseKey = (line) => {
115
- const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
116
- return match ? match[1] : null;
117
- };
118
- /**
119
- * Parse a `KEY=value` dotenv line into its key and unquoted value, or `null` for
120
- * comments / blank lines / non-assignments. Mirrors {@link formatLine}'s quoting.
121
- */
122
- const parseAssignment = (line) => {
123
- const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
124
- const key = match?.[1];
125
- const raw = match?.[2];
126
- if (key === undefined || raw === undefined)
127
- return null;
128
- return { key, value: unquote(raw.trim()) };
129
- };
130
- /** Strip matching surrounding quotes and unescape `\"` / `\\` inside double quotes. */
131
- const unquote = (value) => {
132
- if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
133
- return value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\");
134
- }
135
- if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
136
- return value.slice(1, -1);
137
- }
138
- return value;
139
- };
140
- /**
141
- * Render a `KEY=value` line. The value is wrapped in double quotes when it contains
142
- * characters that would otherwise break parsing (spaces, `#`, quotes, `=`), with inner
143
- * quotes/backslashes escaped — Neon connection strings and URLs are safe either way, but
144
- * quoting defensively avoids surprises for tools that re-parse the file.
145
- */
146
- const formatLine = (key, value) => {
147
- const needsQuotes = /[\s#"'=]/.test(value);
148
- if (!needsQuotes)
149
- return `${key}=${value}`;
150
- const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
151
- return `${key}="${escaped}"`;
152
- };
153
- /** Drop trailing blank lines so we don't accumulate them across repeated merges. */
154
- const trimTrailingBlank = (lines) => {
155
- const out = [...lines];
156
- while (out.length > 0 && out[out.length - 1]?.trim() === "")
157
- out.pop();
158
- return out;
159
- };
package/dist/errors.js DELETED
@@ -1,80 +0,0 @@
1
- const ERROR_MATCHERS = [
2
- [/^Unknown command: (.*)$/, "UNKNOWN_COMMAND"],
3
- [/^Missing required argument: (.*)$/, "MISSING_ARGUMENT"],
4
- [/^Failed to open web browser. (.*)$/, "AUTH_BROWSER_FAILED"],
5
- ];
6
- export const matchErrorCode = (message) => {
7
- if (!message) {
8
- return "UNKNOWN_ERROR";
9
- }
10
- for (const [matcher, code] of ERROR_MATCHERS) {
11
- const match = message.match(matcher);
12
- if (match) {
13
- return code;
14
- }
15
- }
16
- return "UNKNOWN_ERROR";
17
- };
18
- /**
19
- * The single, human-readable line shown when the CLI couldn't reach the Neon API because
20
- * of a connection-level failure (DNS, refused/reset connection, offline). It replaces the
21
- * cryptic `fetch failed` / empty axios message a network blip otherwise surfaces (see
22
- * {@link isNetworkError}), pointing at the two things the user can actually check.
23
- */
24
- export const NETWORK_ERROR_MESSAGE = "Could not reach the Neon API. Please check your internet connection and try again. " +
25
- "If your connection is fine and this keeps happening, check https://neonstatus.com for ongoing incidents.";
26
- /**
27
- * Node-level socket/DNS error codes that mean the request never reached the server — a
28
- * genuine connectivity problem rather than an API response we should surface. Deliberately
29
- * excludes `ECONNABORTED` (axios' timeout), which the CLI already reports as a timeout.
30
- */
31
- const NETWORK_ERROR_CODES = new Set([
32
- "ECONNREFUSED",
33
- "ECONNRESET",
34
- "ETIMEDOUT",
35
- "ENOTFOUND",
36
- "EAI_AGAIN",
37
- "EPIPE",
38
- "EHOSTUNREACH",
39
- "ENETUNREACH",
40
- "EHOSTDOWN",
41
- "ENETDOWN",
42
- ]);
43
- /**
44
- * Message fragments that mark a connection-level failure across our two transports: the
45
- * `@neon/sdk` / global `fetch` path (used by `env pull` / `config` / `deploy`, and `link`'s
46
- * bundled env pull) throws a bare `TypeError: fetch failed` / "Failed to fetch", while the
47
- * axios `api-client` path throws an `AxiosError` whose message is "Network Error".
48
- */
49
- const NETWORK_ERROR_MESSAGE_PATTERN = /fetch failed|failed to fetch|network error/i;
50
- const readErrorCode = (value) => {
51
- if (value === null || typeof value !== "object")
52
- return undefined;
53
- const code = value.code;
54
- return typeof code === "string" ? code : undefined;
55
- };
56
- /**
57
- * Whether `err` is a connection-level failure (the network blip the user sees as a cryptic
58
- * `fetch failed`, or no message at all on the axios path) rather than an actual API response.
59
- *
60
- * A Node `fetch` failure is a bare `TypeError: fetch failed` whose underlying `cause` carries
61
- * the real socket `code` (e.g. `ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`), so we walk the
62
- * `cause` chain checking both the code and the message. This is what lets the CLI swap the
63
- * confusing default for {@link NETWORK_ERROR_MESSAGE}. It matches only failures where no
64
- * response was ever received, so it never masks a real 4xx/5xx the user needs to see.
65
- */
66
- export const isNetworkError = (err) => {
67
- let current = err;
68
- for (let depth = 0; depth < 6 && current !== null && current !== undefined; depth++) {
69
- const code = readErrorCode(current);
70
- if (code !== undefined && NETWORK_ERROR_CODES.has(code)) {
71
- return true;
72
- }
73
- if (current instanceof Error &&
74
- NETWORK_ERROR_MESSAGE_PATTERN.test(current.message)) {
75
- return true;
76
- }
77
- current = current.cause;
78
- }
79
- return false;
80
- };
@@ -1,48 +0,0 @@
1
- import { ContentType } from "./api.js";
2
- const functionsPath = (projectId, branchId) => `/projects/${encodeURIComponent(projectId)}/branches/${encodeURIComponent(branchId)}/functions`;
3
- export const listFunctions = async (apiClient, projectId, branchId, { cursor, limit } = {}) => {
4
- const { data } = await apiClient.request({
5
- path: functionsPath(projectId, branchId),
6
- method: "GET",
7
- query: { cursor, limit },
8
- secure: true,
9
- format: "json",
10
- });
11
- return { functions: data.functions ?? [], next: data.pagination?.next };
12
- };
13
- export const getFunction = async (apiClient, projectId, branchId, slug) => {
14
- const { data } = await apiClient.request({
15
- path: `${functionsPath(projectId, branchId)}/${encodeURIComponent(slug)}`,
16
- method: "GET",
17
- secure: true,
18
- format: "json",
19
- });
20
- return data.function;
21
- };
22
- export const deleteFunction = async (apiClient, projectId, branchId, slug) => {
23
- await apiClient.request({
24
- path: `${functionsPath(projectId, branchId)}/${encodeURIComponent(slug)}`,
25
- method: "DELETE",
26
- secure: true,
27
- });
28
- };
29
- export const createDeployment = async (apiClient, projectId, branchId, slug, params) => {
30
- const form = new FormData();
31
- // TS 5.9 types `Uint8Array` as `Uint8Array<ArrayBufferLike>`, which is not
32
- // assignable to `BlobPart` (it wants an `ArrayBuffer`-backed view, not a
33
- // possibly-`SharedArrayBuffer` one). The bundle is always a plain
34
- // `Uint8Array` over a regular `ArrayBuffer`, so the cast is safe.
35
- form.append("zip", new Blob([params.zip]), "bundle.zip");
36
- form.append("runtime", params.runtime);
37
- if (params.environment)
38
- form.append("environment", params.environment);
39
- // The deploy POST returns an operation the CLI cannot poll; the body is
40
- // ignored. We only need the request to succeed.
41
- await apiClient.request({
42
- path: `${functionsPath(projectId, branchId)}/${encodeURIComponent(slug)}/deployments`,
43
- method: "POST",
44
- type: ContentType.FormData,
45
- body: form,
46
- secure: true,
47
- });
48
- };
package/dist/help.js DELETED
@@ -1,146 +0,0 @@
1
- import chalk from "chalk";
2
- import cliui from "cliui";
3
- import { consumeBlockIfMatches, consumeNextMatching, drawPointer, splitColumns, } from "./utils/ui.js";
4
- // target width for the leftmost column
5
- const SPACE_WIDTH = 20;
6
- const formatHelp = (help) => {
7
- const lines = help.split("\n");
8
- const result = [];
9
- // full command, like `neonctl projects list`
10
- const topLevelCommand = consumeNextMatching(lines, /^.*/);
11
- if (topLevelCommand) {
12
- result.push(chalk.bold(topLevelCommand.replace("[options]", chalk.reset.green("[options]"))));
13
- result.push("");
14
- }
15
- // commands description block
16
- // example command to see: neonctl projects
17
- const commandsBlock = consumeBlockIfMatches(lines, /^Commands:/);
18
- if (commandsBlock.length > 0) {
19
- const header = commandsBlock.shift();
20
- result.push(header);
21
- const ui = cliui({
22
- width: 0,
23
- });
24
- commandsBlock.forEach((line) => {
25
- if (/^\s{3,}/.exec(line)) {
26
- ui.div({
27
- text: "",
28
- width: SPACE_WIDTH,
29
- padding: [0, 0, 0, 0],
30
- }, { text: line.trim(), padding: [0, 0, 0, 0] });
31
- return;
32
- }
33
- const [command, description] = splitColumns(line);
34
- // patch the previous command if it was multiline
35
- if (!description && ui.rows.length > 1) {
36
- ui.rows[ui.rows.length - 2][0].text += command;
37
- return;
38
- }
39
- ui.div(chalk.cyan(command));
40
- ui.div({
41
- text: chalk.gray(drawPointer(SPACE_WIDTH)),
42
- width: SPACE_WIDTH,
43
- padding: [0, 0, 0, 0],
44
- }, { text: description, padding: [0, 0, 0, 2] });
45
- });
46
- result.push(ui.toString());
47
- result.push("");
48
- }
49
- // positional args block
50
- // example command to see: neonctl branches rename
51
- const positionalsBlock = consumeBlockIfMatches(lines, /Positionals:/);
52
- if (positionalsBlock.length > 0) {
53
- const header = positionalsBlock.shift();
54
- result.push(header);
55
- const ui = cliui({
56
- width: 0,
57
- });
58
- positionalsBlock.forEach((line) => {
59
- const [positional, description] = splitColumns(line);
60
- ui.div({
61
- text: positional,
62
- width: SPACE_WIDTH,
63
- padding: [0, 2, 0, 0],
64
- }, {
65
- text: description,
66
- padding: [0, 0, 0, 0],
67
- });
68
- });
69
- result.push(ui.toString());
70
- result.push("");
71
- }
72
- // command description
73
- // example command to see: neonctl projects list
74
- const descriptionBlock = consumeBlockIfMatches(lines, /^(?!.*options:)/i);
75
- if (descriptionBlock.length > 0) {
76
- result.push(...descriptionBlock);
77
- result.push("");
78
- }
79
- while (true) {
80
- // there are two options blocks: global and specific
81
- // example to see both: neonctl projects create
82
- const optionsBlock = consumeBlockIfMatches(lines, /.*options:/i);
83
- if (optionsBlock.length === 0) {
84
- break;
85
- }
86
- result.push(optionsBlock.shift());
87
- optionsBlock.forEach((line) => {
88
- const [option, description] = splitColumns(line);
89
- const ui = cliui({
90
- width: 0,
91
- });
92
- if (option.startsWith("-")) {
93
- ui.div({
94
- text: chalk.green(option),
95
- padding: [0, 0, 0, 0],
96
- });
97
- ui.div({
98
- text: chalk.gray(drawPointer(SPACE_WIDTH)),
99
- width: SPACE_WIDTH,
100
- padding: [0, 2, 0, 0],
101
- }, {
102
- text: chalk.rgb(210, 210, 210)(description ?? ""),
103
- padding: [0, 0, 0, 0],
104
- });
105
- }
106
- else {
107
- ui.div({
108
- padding: [0, 0, 0, 0],
109
- text: "",
110
- width: SPACE_WIDTH,
111
- }, {
112
- text: chalk.rgb(210, 210, 210)(option),
113
- padding: [0, 0, 0, 0],
114
- });
115
- }
116
- result.push(ui.toString());
117
- });
118
- result.push("");
119
- }
120
- const exampleBlock = consumeBlockIfMatches(lines, /Examples:/);
121
- if (exampleBlock.length > 0) {
122
- result.push(exampleBlock.shift());
123
- const ui = cliui({
124
- width: 0,
125
- });
126
- for (const line of exampleBlock) {
127
- const [command, description] = splitColumns(line);
128
- ui.div({
129
- text: chalk.bold(command),
130
- padding: [0, 0, 0, 0],
131
- });
132
- ui.div({
133
- text: chalk.reset(description),
134
- padding: [0, 0, 0, 2],
135
- });
136
- }
137
- result.push(ui.toString());
138
- }
139
- return [...result, ...lines];
140
- };
141
- export const showHelp = async (argv) => {
142
- // add wrap to ensure that there are no line breaks
143
- const help = await argv.getHelp();
144
- process.stderr.write(formatHelp(help).join("\n") + "\n");
145
- process.exit(0);
146
- };
package/dist/index.js DELETED
@@ -1,240 +0,0 @@
1
- import { basename } from "node:path";
2
- import yargs from "yargs";
3
- import { hideBin } from "yargs/helpers";
4
- import { analyticsMiddleware, closeAnalytics, getAnalyticsEventProperties, initAnalyticsClientMiddleware, sendError, trackEvent, } from "./analytics.js";
5
- import { isNeonApiError, messageFromBody } from "./api.js";
6
- import { defaultClientID } from "./auth.js";
7
- import { deleteCredentials, ensureAuth } from "./commands/auth.js";
8
- import commands from "./commands/index.js";
9
- import { defaultDir, ensureConfigDir } from "./config.js";
10
- import { currentContextFile, enrichFromContext } from "./context.js";
11
- import { isNetworkError, matchErrorCode, NETWORK_ERROR_MESSAGE, } from "./errors.js";
12
- import { showHelp } from "./help.js";
13
- import { log } from "./log.js";
14
- import pkg from "./pkg.js";
15
- import { fillInArgs } from "./utils/middlewares.js";
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",
20
- // aliases
21
- "auth",
22
- "login",
23
- "me",
24
- // aliases
25
- "cs",
26
- "connection-string",
27
- "psql",
28
- "set-context",
29
- "checkout",
30
- "link",
31
- "init",
32
- "dev",
33
- "deploy",
34
- // `diff <compare-branch>` has a handler but no subcommands (like `status`),
35
- // so the help-fallback middleware must not intercept a bare `neon diff main`.
36
- "diff",
37
- "bootstrap",
38
- // alias of `config status`
39
- "status",
40
- ];
41
- let builder = yargs(hideBin(process.argv));
42
- builder = builder
43
- .scriptName(pkg.name)
44
- .locale("en")
45
- .usage("$0 <command> [options]")
46
- .parserConfiguration({
47
- "populate--": true,
48
- })
49
- .help()
50
- .option("output", {
51
- alias: "o",
52
- group: "Global options:",
53
- describe: "Set output format",
54
- type: "string",
55
- choices: ["json", "yaml", "table"],
56
- default: "table",
57
- })
58
- .option("api-host", {
59
- describe: "The API host",
60
- hidden: true,
61
- default: process.env.NEON_API_HOST ?? "https://console.neon.tech/api/v2",
62
- })
63
- // Setup config directory
64
- .option("config-dir", {
65
- describe: "Path to config directory",
66
- group: "Global options:",
67
- type: "string",
68
- default: defaultDir,
69
- })
70
- .option("force-auth", {
71
- describe: "Force authentication",
72
- type: "boolean",
73
- hidden: true,
74
- default: false,
75
- })
76
- .middleware(ensureConfigDir)
77
- .options({
78
- "oauth-host": {
79
- description: "URL to Neon OAuth host",
80
- hidden: true,
81
- default: process.env.NEON_OAUTH_HOST ?? "https://oauth2.neon.tech",
82
- },
83
- "client-id": {
84
- description: "OAuth client id",
85
- hidden: true,
86
- type: "string",
87
- default: defaultClientID,
88
- },
89
- "api-key": {
90
- describe: "API key",
91
- group: "Global options:",
92
- type: "string",
93
- default: process.env.NEON_API_KEY ?? "",
94
- },
95
- apiClient: {
96
- hidden: true,
97
- coerce: (v) => v,
98
- default: null,
99
- },
100
- "context-file": {
101
- describe: "Context file",
102
- type: "string",
103
- default: currentContextFile,
104
- },
105
- color: {
106
- group: "Global options:",
107
- describe: "Colorize the output. Example: --no-color, --color false",
108
- type: "boolean",
109
- default: true,
110
- },
111
- analytics: {
112
- describe: "Manage analytics. Example: --no-analytics, --analytics false",
113
- group: "Global options:",
114
- type: "boolean",
115
- default: true,
116
- },
117
- })
118
- .middleware((args) => {
119
- fillInArgs(args);
120
- }, true)
121
- .middleware(initAnalyticsClientMiddleware, true)
122
- .help(false)
123
- .group("help", "Global options:")
124
- .option("help", {
125
- describe: "Show help",
126
- type: "boolean",
127
- default: false,
128
- })
129
- .alias("help", "h")
130
- .middleware(async (args) => {
131
- if (args.help ||
132
- (args._.length === 1 &&
133
- !NO_SUBCOMMANDS_VERBS.includes(args._[0]))) {
134
- await showHelp(builder);
135
- }
136
- })
137
- .middleware(ensureAuth)
138
- .middleware(enrichFromContext)
139
- .middleware(analyticsMiddleware)
140
- .command(commands)
141
- .strictCommands()
142
- .version(pkg.version)
143
- .group("version", "Global options:")
144
- .alias("version", "v")
145
- .completion()
146
- .scriptName(basename(process.argv[1]) === "neon" ? "neon" : "neonctl")
147
- .epilog("For more information, visit https://neon.com/docs/reference/neon-cli")
148
- .wrap(null)
149
- .fail(false);
150
- async function handleError(msg, err) {
151
- if (process.argv.some((arg) => arg === "--help" || arg === "-h")) {
152
- await showHelp(builder);
153
- process.exit(0);
154
- }
155
- // Log stack trace if available
156
- if (err instanceof Error && err.stack) {
157
- log.debug("Stack: %s", err.stack);
158
- }
159
- // A connection-level failure (no response ever reached us) reads as a cryptic
160
- // `fetch failed` from the @neon/sdk / global `fetch` path. Detect it first and
161
- // swap in one clear "check your connection" hint. We deliberately do not retry
162
- // here: re-running the whole command could re-trigger a non-idempotent step
163
- // (e.g. project create), so retries belong at the request layer.
164
- if (isNetworkError(err)) {
165
- log.error(NETWORK_ERROR_MESSAGE);
166
- const error = err instanceof Error ? err : new Error(NETWORK_ERROR_MESSAGE);
167
- sendError(error, "NETWORK_ERROR");
168
- return false;
169
- }
170
- if (isNeonApiError(err)) {
171
- if (err.code === "ECONNABORTED") {
172
- log.error("Request timed out");
173
- sendError(err, "REQUEST_TIMEOUT");
174
- return false;
175
- }
176
- else if (err.status === 401) {
177
- sendError(err, "AUTH_FAILED");
178
- log.info("Authentication failed, deleting credentials...");
179
- try {
180
- deleteCredentials(defaultDir);
181
- return true; // Allow retry for auth failures
182
- }
183
- catch (deleteErr) {
184
- log.debug("Failed to delete credentials: %s", deleteErr instanceof Error
185
- ? deleteErr.message
186
- : "unknown error");
187
- return false;
188
- }
189
- }
190
- else {
191
- const serverMessage = messageFromBody(err.data);
192
- if (serverMessage) {
193
- log.error(serverMessage);
194
- }
195
- log.debug("status: %d %s | path: %s", err.status, err.statusText, err.requestPath);
196
- sendError(err, "API_ERROR");
197
- return false;
198
- }
199
- }
200
- else {
201
- const error = err instanceof Error ? err : new Error(msg || "Unknown error");
202
- sendError(error, matchErrorCode(error.message));
203
- log.error(error.message);
204
- return false;
205
- }
206
- }
207
- void (async () => {
208
- // Main loop with max 2 attempts (initial + 1 retry):
209
- let attempts = 0;
210
- const MAX_ATTEMPTS = 2;
211
- while (attempts < MAX_ATTEMPTS) {
212
- try {
213
- const args = await builder.argv;
214
- // Send analytics for a successful attempt
215
- trackEvent("cli_command_success", {
216
- ...getAnalyticsEventProperties(args),
217
- projectId: args.projectId,
218
- branchId: args.branchId,
219
- accountId: args.accountId,
220
- authMethod: args.authMethod,
221
- authData: args.authData,
222
- });
223
- if (args._.length === 0 || args.help) {
224
- await showHelp(builder);
225
- process.exit(0);
226
- }
227
- await closeAnalytics();
228
- break;
229
- }
230
- catch (err) {
231
- attempts++;
232
- const shouldRetry = await handleError("", err);
233
- if (!shouldRetry || attempts >= MAX_ATTEMPTS) {
234
- await closeAnalytics();
235
- process.exit(1);
236
- }
237
- // If shouldRetry is true and we haven't hit max attempts, loop continues
238
- }
239
- }
240
- })();
package/dist/log.js DELETED
@@ -1,18 +0,0 @@
1
- import { format } from "node:util";
2
- import { isDebug } from "./env.js";
3
- export const log = {
4
- debug: (...args) => {
5
- if (isDebug()) {
6
- process.stderr.write(`DEBUG: ${format(...args)}\n`);
7
- }
8
- },
9
- warning: (...args) => {
10
- process.stderr.write(`WARNING: ${format(...args)}\n`);
11
- },
12
- info: (...args) => {
13
- process.stderr.write(`INFO: ${format(...args)}\n`);
14
- },
15
- error: (...args) => {
16
- process.stderr.write(`ERROR: ${format(...args)}\n`);
17
- },
18
- };