neonctl 2.37.0 → 2.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/{LICENSE.md → LICENSE} +27 -3
  2. package/README.md +15 -700
  3. package/bin/cli.js +3 -0
  4. package/package.json +8 -75
  5. package/dist/analytics.js +0 -168
  6. package/dist/api.js +0 -720
  7. package/dist/auth.js +0 -125
  8. package/dist/callback.html +0 -51
  9. package/dist/cli.js +0 -9
  10. package/dist/commands/api.js +0 -278
  11. package/dist/commands/auth.js +0 -214
  12. package/dist/commands/bootstrap.js +0 -481
  13. package/dist/commands/branches.js +0 -488
  14. package/dist/commands/bucket.js +0 -549
  15. package/dist/commands/checkout.js +0 -321
  16. package/dist/commands/config.js +0 -626
  17. package/dist/commands/connection_string.js +0 -172
  18. package/dist/commands/data_api.js +0 -284
  19. package/dist/commands/databases.js +0 -82
  20. package/dist/commands/deploy.js +0 -26
  21. package/dist/commands/dev.js +0 -698
  22. package/dist/commands/diff.js +0 -222
  23. package/dist/commands/env.js +0 -189
  24. package/dist/commands/functions.js +0 -373
  25. package/dist/commands/index.js +0 -62
  26. package/dist/commands/init.js +0 -73
  27. package/dist/commands/inspect.js +0 -65
  28. package/dist/commands/ip_allow.js +0 -137
  29. package/dist/commands/link.js +0 -1121
  30. package/dist/commands/neon_auth.js +0 -1028
  31. package/dist/commands/operations.js +0 -28
  32. package/dist/commands/orgs.js +0 -24
  33. package/dist/commands/projects.js +0 -413
  34. package/dist/commands/psql.js +0 -62
  35. package/dist/commands/roles.js +0 -65
  36. package/dist/commands/schema_diff.js +0 -151
  37. package/dist/commands/set_context.js +0 -29
  38. package/dist/commands/snapshots.js +0 -455
  39. package/dist/commands/status.js +0 -40
  40. package/dist/commands/user.js +0 -15
  41. package/dist/commands/vpc_endpoints.js +0 -134
  42. package/dist/config.js +0 -11
  43. package/dist/config_format.js +0 -72
  44. package/dist/context.js +0 -231
  45. package/dist/current_branch_fast_path.js +0 -55
  46. package/dist/dev/env.js +0 -244
  47. package/dist/dev/functions.js +0 -70
  48. package/dist/dev/inputs.js +0 -63
  49. package/dist/dev/runtime.js +0 -146
  50. package/dist/env.js +0 -36
  51. package/dist/env_file.js +0 -159
  52. package/dist/errors.js +0 -80
  53. package/dist/functions_api.js +0 -48
  54. package/dist/help.js +0 -146
  55. package/dist/index.js +0 -240
  56. package/dist/log.js +0 -18
  57. package/dist/parameters.gen.js +0 -480
  58. package/dist/pkg.js +0 -25
  59. package/dist/psql/cli.js +0 -53
  60. package/dist/psql/command/cmd_cond.js +0 -437
  61. package/dist/psql/command/cmd_connect.js +0 -820
  62. package/dist/psql/command/cmd_copy.js +0 -1035
  63. package/dist/psql/command/cmd_describe.js +0 -1815
  64. package/dist/psql/command/cmd_format.js +0 -948
  65. package/dist/psql/command/cmd_io.js +0 -2193
  66. package/dist/psql/command/cmd_lo.js +0 -393
  67. package/dist/psql/command/cmd_meta.js +0 -969
  68. package/dist/psql/command/cmd_misc.js +0 -187
  69. package/dist/psql/command/cmd_pipeline.js +0 -1148
  70. package/dist/psql/command/cmd_restrict.js +0 -171
  71. package/dist/psql/command/cmd_show.js +0 -766
  72. package/dist/psql/command/dispatch.js +0 -343
  73. package/dist/psql/command/inputQueue.js +0 -42
  74. package/dist/psql/command/shared.js +0 -71
  75. package/dist/psql/complete/filenames.js +0 -139
  76. package/dist/psql/complete/index.js +0 -104
  77. package/dist/psql/complete/matcher.js +0 -315
  78. package/dist/psql/complete/psqlVars.js +0 -249
  79. package/dist/psql/complete/queries.js +0 -493
  80. package/dist/psql/complete/rules.js +0 -2424
  81. package/dist/psql/core/common.js +0 -1253
  82. package/dist/psql/core/help.js +0 -576
  83. package/dist/psql/core/mainloop.js +0 -1360
  84. package/dist/psql/core/prompt.js +0 -439
  85. package/dist/psql/core/settings.js +0 -686
  86. package/dist/psql/core/sqlHelp.js +0 -1066
  87. package/dist/psql/core/startup.js +0 -846
  88. package/dist/psql/core/syncVars.js +0 -116
  89. package/dist/psql/core/variables.js +0 -287
  90. package/dist/psql/describe/formatters.js +0 -1330
  91. package/dist/psql/describe/processNamePattern.js +0 -270
  92. package/dist/psql/describe/queries.js +0 -2452
  93. package/dist/psql/describe/versionGate.js +0 -44
  94. package/dist/psql/index.js +0 -2030
  95. package/dist/psql/io/history.js +0 -299
  96. package/dist/psql/io/input.js +0 -120
  97. package/dist/psql/io/lineEditor/buffer.js +0 -325
  98. package/dist/psql/io/lineEditor/complete.js +0 -227
  99. package/dist/psql/io/lineEditor/filename.js +0 -159
  100. package/dist/psql/io/lineEditor/index.js +0 -893
  101. package/dist/psql/io/lineEditor/keymap.js +0 -745
  102. package/dist/psql/io/lineEditor/vt100.js +0 -363
  103. package/dist/psql/io/pgpass.js +0 -202
  104. package/dist/psql/io/pgservice.js +0 -194
  105. package/dist/psql/io/psqlrc.js +0 -422
  106. package/dist/psql/print/aligned.js +0 -1748
  107. package/dist/psql/print/asciidoc.js +0 -230
  108. package/dist/psql/print/crosstab.js +0 -463
  109. package/dist/psql/print/csv.js +0 -76
  110. package/dist/psql/print/html.js +0 -240
  111. package/dist/psql/print/json.js +0 -96
  112. package/dist/psql/print/latex.js +0 -379
  113. package/dist/psql/print/pager.js +0 -267
  114. package/dist/psql/print/troff.js +0 -240
  115. package/dist/psql/print/unaligned.js +0 -99
  116. package/dist/psql/print/units.js +0 -188
  117. package/dist/psql/scanner/slash.js +0 -515
  118. package/dist/psql/scanner/sql.js +0 -914
  119. package/dist/psql/scanner/stringutils.js +0 -394
  120. package/dist/psql/types/backslash.js +0 -1
  121. package/dist/psql/types/connection.js +0 -1
  122. package/dist/psql/types/index.js +0 -7
  123. package/dist/psql/types/printer.js +0 -1
  124. package/dist/psql/types/repl.js +0 -1
  125. package/dist/psql/types/scanner.js +0 -24
  126. package/dist/psql/types/settings.js +0 -1
  127. package/dist/psql/types/variables.js +0 -1
  128. package/dist/psql/wire/connection.js +0 -2857
  129. package/dist/psql/wire/copy.js +0 -108
  130. package/dist/psql/wire/notify.js +0 -59
  131. package/dist/psql/wire/pipeline.js +0 -521
  132. package/dist/psql/wire/protocol.js +0 -466
  133. package/dist/psql/wire/sasl.js +0 -294
  134. package/dist/psql/wire/tls.js +0 -602
  135. package/dist/storage_api.js +0 -147
  136. package/dist/test_utils/fixtures.js +0 -121
  137. package/dist/test_utils/oauth_server.js +0 -9
  138. package/dist/types.js +0 -1
  139. package/dist/utils/ai_gateway_notice.js +0 -180
  140. package/dist/utils/api_enums.js +0 -33
  141. package/dist/utils/auth.js +0 -5
  142. package/dist/utils/branch_notice.js +0 -22
  143. package/dist/utils/branch_picker.js +0 -103
  144. package/dist/utils/compute_units.js +0 -28
  145. package/dist/utils/config_diff.js +0 -185
  146. package/dist/utils/enrichers.js +0 -161
  147. package/dist/utils/esbuild.js +0 -158
  148. package/dist/utils/formats.js +0 -18
  149. package/dist/utils/git_diff.js +0 -90
  150. package/dist/utils/inspect_db.js +0 -153
  151. package/dist/utils/inspect_queries.js +0 -372
  152. package/dist/utils/middlewares.js +0 -20
  153. package/dist/utils/openapi.js +0 -114
  154. package/dist/utils/package_manager.js +0 -68
  155. package/dist/utils/point_in_time.js +0 -56
  156. package/dist/utils/psql.js +0 -120
  157. package/dist/utils/string.js +0 -5
  158. package/dist/utils/ui.js +0 -59
  159. package/dist/utils/zip.js +0 -4
  160. package/dist/writer.js +0 -97
@@ -1,151 +0,0 @@
1
- import chalk from "chalk";
2
- import { createPatch } from "diff";
3
- import { sendError } from "../analytics.js";
4
- import { isNeonApiError, messageFromBody } from "../api.js";
5
- import { log } from "../log.js";
6
- import { branchIdFromProps } from "../utils/enrichers.js";
7
- import { parsePointInTime, } from "../utils/point_in_time.js";
8
- import { writer } from "../writer.js";
9
- const COLORS = {
10
- added: chalk.green,
11
- removed: chalk.red,
12
- header: chalk.yellow,
13
- section: chalk.magenta,
14
- };
15
- export const schemaDiff = async (props) => {
16
- props.branch = props.baseBranch || props.branch;
17
- const baseBranch = await branchIdFromProps(props);
18
- let pointInTime = await parsePointInTime({
19
- pointInTime: props.compareSource,
20
- targetBranchId: baseBranch,
21
- projectId: props.projectId,
22
- api: props.apiClient,
23
- });
24
- // Swap base and compare points if comparing with parent branch
25
- const comparingWithParent = props.compareSource.startsWith("^parent");
26
- let baseBranchPoint = {
27
- branchId: baseBranch,
28
- tag: "head",
29
- };
30
- [baseBranchPoint, pointInTime] = comparingWithParent
31
- ? [pointInTime, baseBranchPoint]
32
- : [baseBranchPoint, pointInTime];
33
- const baseDatabases = await fetchDatabases(baseBranch, props);
34
- if (props.database) {
35
- const database = baseDatabases.find((db) => db.name === props.database);
36
- if (!database) {
37
- throw new Error(`Database ${props.database} does not exist in base branch ${baseBranch}`);
38
- }
39
- const patch = await createSchemaDiff(baseBranchPoint, pointInTime, database, props);
40
- writer(props).text(colorize(patch));
41
- return;
42
- }
43
- await Promise.all(baseDatabases.map(async (database) => {
44
- const patch = await createSchemaDiff(baseBranchPoint, pointInTime, database, props);
45
- writer(props).text(colorize(patch));
46
- }));
47
- };
48
- const fetchDatabases = async (branch, props) => {
49
- return props.apiClient
50
- .listProjectBranchDatabases(props.projectId, branch)
51
- .then((response) => response.data.databases);
52
- };
53
- const createSchemaDiff = async (baseBranch, pointInTime, database, props) => {
54
- const [baseSchema, compareSchema] = await Promise.all([
55
- fetchSchema(baseBranch, database, props),
56
- fetchSchema(pointInTime, database, props),
57
- ]);
58
- return createPatch(`Database: ${database.name}`, baseSchema, compareSchema, generateHeader(baseBranch), generateHeader(pointInTime));
59
- };
60
- const fetchSchema = async (pointInTime, database, props) => {
61
- try {
62
- const response = await props.apiClient.getProjectBranchSchema({
63
- projectId: props.projectId,
64
- branchId: pointInTime.branchId,
65
- db_name: database.name,
66
- ...pointInTimeParams(pointInTime),
67
- });
68
- return response.data.sql ?? "";
69
- }
70
- catch (error) {
71
- if (isNeonApiError(error)) {
72
- sendError(error, "API_ERROR");
73
- throw new Error(messageFromBody(error.data) ??
74
- `Error while fetching schema for branch ${pointInTime.branchId}`);
75
- }
76
- throw error;
77
- }
78
- };
79
- const colorize = (patch) => {
80
- return patch
81
- .replace(/^([^\n]+)\n([^\n]+)\n/m, "") // Remove first two lines
82
- .replace(/^-.*/gm, colorizer("removed"))
83
- .replace(/^\+.*/gm, colorizer("added"))
84
- .replace(/^@@.+@@.*/gm, colorizer("section"));
85
- };
86
- const colorizer = (colorId) => {
87
- const color = COLORS[colorId];
88
- return (line) => color(line);
89
- };
90
- const pointInTimeParams = (pointInTime) => {
91
- switch (pointInTime.tag) {
92
- case "timestamp":
93
- return {
94
- timestamp: pointInTime.timestamp,
95
- };
96
- case "lsn":
97
- return {
98
- lsn: pointInTime.lsn ?? undefined,
99
- };
100
- default:
101
- return {};
102
- }
103
- };
104
- const generateHeader = (pointInTime) => {
105
- const header = `(Branch: ${pointInTime.branchId}`;
106
- switch (pointInTime.tag) {
107
- case "timestamp":
108
- return `${header} at ${pointInTime.timestamp})`;
109
- case "lsn":
110
- return `${header} at ${pointInTime.lsn})`;
111
- default:
112
- return `${header})`;
113
- }
114
- };
115
- /*
116
- The command has two positional optional arguments - [base-branch] and [compare-source]
117
- If only one argument is specified, we should consider it as `compare-source`
118
- and `base-branch` will be either read from context or the default branch of project.
119
- If no branches are specified, compare the context branch with its parent
120
- */
121
- export const parseSchemaDiffParams = async (props) => {
122
- if (!props.compareSource) {
123
- if (props.baseBranch) {
124
- props.compareSource = props.baseBranch;
125
- props.baseBranch = props.branch;
126
- }
127
- else if (props.branch) {
128
- const { data } = await props.apiClient.listProjectBranches({
129
- projectId: props.projectId,
130
- });
131
- const contextBranch = data.branches.find((b) => b.id === props.branch || b.name === props.branch);
132
- if (contextBranch?.parent_id == undefined) {
133
- throw new Error(`No branch specified. Your context branch (${props.branch}) has no parent, so no comparison is possible.`);
134
- }
135
- log.info(`No branches specified. Comparing your context branch '${props.branch}' with its parent`);
136
- props.compareSource = "^parent";
137
- }
138
- else {
139
- const { data } = await props.apiClient.listProjectBranches({
140
- projectId: props.projectId,
141
- });
142
- const defaultBranch = data.branches.find((b) => b.default);
143
- if (defaultBranch?.parent_id == undefined) {
144
- throw new Error("No branch specified. Include a base branch or add a set-context branch to continue. Your default branch has no parent, so no comparison is possible.");
145
- }
146
- log.info(`No branches specified. Comparing default branch with its parent`);
147
- props.compareSource = "^parent";
148
- }
149
- }
150
- return props;
151
- };
@@ -1,29 +0,0 @@
1
- import { applyContext } from "../context.js";
2
- import { log } from "../log.js";
3
- export const command = "set-context";
4
- export const describe = "Deprecated: use `neonctl link`. Set the .neon context (raw write).";
5
- export const builder = (argv) => argv.usage("$0 set-context [options]").options({
6
- "project-id": {
7
- describe: "Project ID",
8
- type: "string",
9
- },
10
- "org-id": {
11
- describe: "Organization ID",
12
- type: "string",
13
- },
14
- "branch-id": {
15
- describe: "Branch ID",
16
- type: "string",
17
- },
18
- });
19
- export const handler = (props) => {
20
- log.warning("`neonctl set-context` is deprecated and will be removed in a future release. " +
21
- "Use `neonctl link` instead — it verifies inputs and infers the org for you " +
22
- "(or `neonctl link --no-checks` for the same write-without-checks behavior).");
23
- const context = {
24
- projectId: props.projectId,
25
- orgId: props.orgId,
26
- branchId: props.branchId,
27
- };
28
- applyContext(props.contextFile, context);
29
- };
@@ -1,455 +0,0 @@
1
- import { retryOnLock } from "../api.js";
2
- import { log } from "../log.js";
3
- import { branchIdResolve, fillSingleProject, resolveBranchRef, } from "../utils/enrichers.js";
4
- import { looksLikeLSN, looksLikeTimestamp } from "../utils/formats.js";
5
- import { writer } from "../writer.js";
6
- import { BRANCH_FIELDS } from "./branches.js";
7
- export const SNAPSHOT_FIELDS = [
8
- "id",
9
- "name",
10
- "source_branch_id",
11
- "created_at",
12
- "expires_at",
13
- ];
14
- const SCHEDULE_FIELDS = [
15
- "frequency",
16
- "hour",
17
- "day",
18
- "month",
19
- "retention_seconds",
20
- ];
21
- const OPERATION_FIELDS = [
22
- "id",
23
- "action",
24
- "status",
25
- ];
26
- // The values the Neon API accepts for a backup-schedule entry's `frequency`
27
- // (per the OpenAPI `BackupScheduleItem` description). `satisfies` fails the
28
- // build if a value listed here leaves the SDK's `SnapshotFrequency` union, so
29
- // the CLI can never offer a frequency the API rejects.
30
- const SNAPSHOT_FREQUENCIES = [
31
- "daily",
32
- "weekly",
33
- "monthly",
34
- ];
35
- /** Narrow an arbitrary string to a supported {@link SnapshotFrequency}. */
36
- const isSnapshotFrequency = (value) => SNAPSHOT_FREQUENCIES.some((frequency) => frequency === value);
37
- export const command = "snapshots";
38
- export const describe = "Manage snapshots";
39
- export const aliases = ["snapshot"];
40
- export const builder = (argv) => argv
41
- .usage("$0 snapshots <sub-command> [options]")
42
- .options({
43
- "project-id": {
44
- describe: "Project ID",
45
- type: "string",
46
- },
47
- })
48
- .middleware(fillSingleProject)
49
- .command("list", "List snapshots in the project", (yargs) => yargs, (args) => list(args))
50
- .command("get <id>", "Get a snapshot by id or name", (yargs) => yargs, (args) => get(args))
51
- .command("create", "Create a snapshot from a branch", (yargs) => yargs
52
- .options({
53
- branch: {
54
- alias: "b",
55
- describe: "Branch id or name to snapshot. Defaults to the branch in your context, or the project's default branch.",
56
- type: "string",
57
- },
58
- name: {
59
- describe: "A name for the snapshot",
60
- type: "string",
61
- },
62
- timestamp: {
63
- describe: "Take the snapshot at this point in time (RFC 3339, e.g. 2025-01-01T00:00:00Z). Must fall within the branch's restore window. Mutually exclusive with --lsn.",
64
- type: "string",
65
- },
66
- lsn: {
67
- describe: "Take the snapshot at this LSN (e.g. 0/1F3C8A0). Must fall within the branch's restore window. Mutually exclusive with --timestamp.",
68
- type: "string",
69
- },
70
- "expires-at": {
71
- describe: "When the snapshot is automatically deleted (RFC 3339, e.g. 2025-12-31T23:59:59Z). Omit to keep it indefinitely.",
72
- type: "string",
73
- },
74
- })
75
- .conflicts("timestamp", "lsn")
76
- .example([
77
- [
78
- "$0 snapshots create",
79
- "Snapshot the head of the context/default branch",
80
- ],
81
- [
82
- "$0 snapshots create --branch main --name pre-migration",
83
- "Snapshot the head of main with a name",
84
- ],
85
- [
86
- "$0 snapshots create --branch main --timestamp 2025-01-01T00:00:00Z",
87
- "Snapshot main at a point in time",
88
- ],
89
- [
90
- "$0 snapshots create --branch main --lsn 0/1F3C8A0 --expires-at 2025-12-31T23:59:59Z",
91
- "Snapshot main at an LSN, auto-deleting at the given time",
92
- ],
93
- ]), (args) => create(args))
94
- .command("update <id>", "Update a snapshot's name or expiration", (yargs) => yargs
95
- .options({
96
- name: {
97
- describe: "Rename the snapshot",
98
- type: "string",
99
- },
100
- "expires-at": {
101
- describe: "Set when the snapshot expires (RFC 3339). Mutually exclusive with --clear-expiration.",
102
- type: "string",
103
- },
104
- "clear-expiration": {
105
- describe: "Clear the expiration so the snapshot is kept indefinitely.",
106
- type: "boolean",
107
- },
108
- })
109
- .conflicts("expires-at", "clear-expiration"), (args) => update(args))
110
- .command("delete <id>", "Delete a snapshot by id or name", (yargs) => yargs, (args) => deleteSnapshot(args))
111
- .command("restore <id>", "Restore a snapshot into a branch", (yargs) => yargs
112
- .options({
113
- name: {
114
- describe: "Name for the newly restored branch. Auto-generated when omitted.",
115
- type: "string",
116
- },
117
- "target-branch": {
118
- describe: "Branch id or name to restore the snapshot onto. Defaults to the snapshot's source branch. Recommended when you intend to finalize (replace an existing branch).",
119
- type: "string",
120
- },
121
- finalize: {
122
- describe: "Finalize the restore immediately: move computes onto the restored branch and swap it in for the target. Without this, the restore is left un-finalized so you can inspect it first, then run `snapshots finalize <branch>`.",
123
- type: "boolean",
124
- default: false,
125
- },
126
- })
127
- .example([
128
- [
129
- "$0 snapshots restore snap-1234 --name recovered",
130
- "Restore a snapshot to a new branch named 'recovered'",
131
- ],
132
- [
133
- "$0 snapshots restore snap-1234 --target-branch main --finalize",
134
- "Restore onto main and swap it in immediately",
135
- ],
136
- [
137
- "$0 snapshots restore snap-1234 --target-branch main",
138
- "Restore onto main un-finalized to preview, then run `snapshots finalize`",
139
- ],
140
- ]), (args) => restore(args))
141
- .command("finalize <branch>", "Finalize a previewed snapshot restore (swap the restored branch in)", (yargs) => yargs.options({
142
- name: {
143
- describe: "Name to give the replaced (old) branch. Auto-generated when omitted.",
144
- type: "string",
145
- },
146
- }), (args) => finalize(args))
147
- .command("schedule", "Manage the automatic snapshot (backup) schedule of a branch", (yargs) => yargs
148
- .usage("$0 snapshots schedule <sub-command> [options]")
149
- .command("get", "Get a branch's automatic snapshot schedule", (yargs) => yargs.options({
150
- branch: {
151
- alias: "b",
152
- describe: "Branch id or name. Defaults to the branch in your context, or the project's default branch.",
153
- type: "string",
154
- },
155
- }), (args) => scheduleGet(args))
156
- .command("set", "Set a branch's automatic snapshot schedule", (yargs) => yargs
157
- .options({
158
- branch: {
159
- alias: "b",
160
- describe: "Branch id or name. Defaults to the branch in your context, or the project's default branch.",
161
- type: "string",
162
- },
163
- frequency: {
164
- describe: "How often to take snapshots. Builds a single-entry schedule together with --hour/--day/--month/--retention.",
165
- choices: SNAPSHOT_FREQUENCIES,
166
- type: "string",
167
- },
168
- hour: {
169
- describe: "Hour of the day (0-23) to take the snapshot (used with --frequency).",
170
- type: "number",
171
- },
172
- day: {
173
- describe: "Day of the week/month (1-31) to take the snapshot (used with --frequency).",
174
- type: "number",
175
- },
176
- month: {
177
- describe: "Month of the year (1-12) to take the snapshot (used with --frequency).",
178
- type: "number",
179
- },
180
- retention: {
181
- describe: "How long to keep each snapshot, in seconds (min 3600). Omit to keep indefinitely.",
182
- type: "number",
183
- },
184
- schedule: {
185
- describe: 'Full schedule as JSON, for multi-entry schedules, e.g. \'[{"frequency":"daily","hour":3,"retention_seconds":604800}]\'. Overrides the single-entry flags.',
186
- type: "string",
187
- },
188
- })
189
- .example([
190
- [
191
- "$0 snapshots schedule set --branch main --frequency daily --hour 3 --retention 604800",
192
- "A daily 03:00 snapshot kept for 7 days",
193
- ],
194
- [
195
- '$0 snapshots schedule set --branch main --schedule \'[{"frequency":"weekly","day":1,"hour":2},{"frequency":"daily","hour":3}]\'',
196
- "A multi-entry schedule via JSON",
197
- ],
198
- ]), (args) => scheduleSet(args))
199
- .demandCommand(1, "Specify `get` or `set`."), () => { })
200
- .demandCommand(1, "Specify a snapshots sub-command.");
201
- export const handler = (args) => {
202
- return args;
203
- };
204
- /** Narrow an unknown parsed JSON value to a plain object without type casting. */
205
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
206
- /** Normalize a user-supplied date to an ISO 8601 string, or throw a friendly error. */
207
- const toIso = (value, flag) => {
208
- const ms = Date.parse(value);
209
- if (Number.isNaN(ms)) {
210
- throw new Error(`Invalid ${flag} value: "${value}". Use an RFC 3339 timestamp, e.g. 2025-12-31T23:59:59Z.`);
211
- }
212
- return new Date(ms).toISOString();
213
- };
214
- /**
215
- * Resolve a snapshot from an id **or** a name. Snapshot names are not guaranteed
216
- * unique, so an id match wins; a name that resolves to more than one snapshot is a
217
- * hard error asking the user to disambiguate by id.
218
- */
219
- const resolveSnapshot = async (props) => {
220
- const { data: { snapshots }, } = await props.apiClient.listSnapshots(props.projectId);
221
- const byId = snapshots.find((s) => s.id === props.id);
222
- if (byId) {
223
- return byId;
224
- }
225
- const byName = snapshots.filter((s) => s.name === props.id);
226
- if (byName.length === 1) {
227
- return byName[0];
228
- }
229
- if (byName.length > 1) {
230
- throw new Error(`Multiple snapshots are named "${props.id}". Re-run with the snapshot id:\n${byName
231
- .map((s) => ` ${s.id}`)
232
- .join("\n")}`);
233
- }
234
- throw new Error(`Snapshot "${props.id}" not found.\nAvailable snapshots: ${snapshots.map((s) => `${s.name} (${s.id})`).join(", ") ||
235
- "none"}`);
236
- };
237
- const list = async (props) => {
238
- const { data: { snapshots }, } = await props.apiClient.listSnapshots(props.projectId);
239
- writer(props).end(snapshots, {
240
- fields: SNAPSHOT_FIELDS,
241
- title: "snapshots",
242
- emptyMessage: "No snapshots found. Create one with:\n> neon snapshots create --help",
243
- renderColumns: {
244
- expires_at: (s) => s.expires_at || "never",
245
- },
246
- });
247
- };
248
- const get = async (props) => {
249
- const snapshot = await resolveSnapshot(props);
250
- writer(props).end(snapshot, {
251
- fields: SNAPSHOT_FIELDS,
252
- renderColumns: {
253
- expires_at: (s) => s.expires_at || "never",
254
- },
255
- });
256
- };
257
- const create = async (props) => {
258
- if (props.lsn !== undefined && !looksLikeLSN(props.lsn)) {
259
- throw new Error(`Invalid --lsn value: "${props.lsn}". Expected an LSN like 0/1F3C8A0.`);
260
- }
261
- if (props.timestamp !== undefined && !looksLikeTimestamp(props.timestamp)) {
262
- throw new Error(`Invalid --timestamp value: "${props.timestamp}". Use an RFC 3339 timestamp, e.g. 2025-01-01T00:00:00Z.`);
263
- }
264
- const { branchId } = await resolveBranchRef({
265
- ...props,
266
- branch: props.branch,
267
- });
268
- const { data } = await retryOnLock(() => props.apiClient.createSnapshot(props.projectId, branchId, {
269
- name: props.name,
270
- timestamp: props.timestamp,
271
- lsn: props.lsn,
272
- expires_at: props.expiresAt
273
- ? toIso(props.expiresAt, "--expires-at")
274
- : undefined,
275
- }));
276
- writer(props).end(data.snapshot, {
277
- fields: SNAPSHOT_FIELDS,
278
- title: "snapshot",
279
- renderColumns: {
280
- expires_at: (s) => s.expires_at || "never",
281
- },
282
- });
283
- };
284
- const update = async (props) => {
285
- if (props.name === undefined &&
286
- props.expiresAt === undefined &&
287
- !props.clearExpiration) {
288
- throw new Error("Nothing to update. Pass --name, --expires-at, or --clear-expiration.");
289
- }
290
- const snapshot = await resolveSnapshot(props);
291
- // `undefined` fields are dropped by JSON serialization, so an omitted
292
- // `expires_at` leaves the expiration unchanged while an explicit `null`
293
- // clears it.
294
- const expiresAt = props.clearExpiration
295
- ? null
296
- : props.expiresAt !== undefined
297
- ? toIso(props.expiresAt, "--expires-at")
298
- : undefined;
299
- const { data } = await retryOnLock(() => props.apiClient.updateSnapshot(props.projectId, snapshot.id, {
300
- snapshot: {
301
- name: props.name,
302
- expires_at: expiresAt,
303
- },
304
- }));
305
- writer(props).end(data.snapshot, {
306
- fields: SNAPSHOT_FIELDS,
307
- renderColumns: {
308
- expires_at: (s) => s.expires_at || "never",
309
- },
310
- });
311
- };
312
- const deleteSnapshot = async (props) => {
313
- const snapshot = await resolveSnapshot(props);
314
- await retryOnLock(() => props.apiClient.deleteSnapshot(props.projectId, snapshot.id));
315
- // The delete endpoint returns the tracking operations (202), not the snapshot
316
- // body, so echo the snapshot we just deleted for confirmation.
317
- writer(props).end(snapshot, {
318
- fields: SNAPSHOT_FIELDS,
319
- renderColumns: {
320
- expires_at: (s) => s.expires_at || "never",
321
- },
322
- });
323
- };
324
- const restore = async (props) => {
325
- const snapshot = await resolveSnapshot(props);
326
- const targetBranchId = props.targetBranch
327
- ? await branchIdResolve({
328
- branch: props.targetBranch,
329
- projectId: props.projectId,
330
- apiClient: props.apiClient,
331
- })
332
- : undefined;
333
- const { data } = await retryOnLock(() => props.apiClient.restoreSnapshot(props.projectId, snapshot.id, {
334
- name: props.name,
335
- target_branch_id: targetBranchId,
336
- finalize_restore: props.finalize,
337
- }));
338
- const out = writer(props).write(data.branch, {
339
- fields: BRANCH_FIELDS,
340
- title: "restored branch",
341
- });
342
- if (data.operations?.length) {
343
- out.write(data.operations, {
344
- fields: OPERATION_FIELDS,
345
- title: "operations",
346
- });
347
- }
348
- out.end();
349
- if (!props.finalize) {
350
- log.info(`Restore left un-finalized. Inspect branch ${data.branch.id}, then run:\n neon snapshots finalize ${data.branch.id} --project-id ${props.projectId}`);
351
- }
352
- };
353
- const finalize = async (props) => {
354
- const branchId = await branchIdResolve({
355
- branch: props.branch,
356
- projectId: props.projectId,
357
- apiClient: props.apiClient,
358
- });
359
- const { data } = await retryOnLock(() => props.apiClient.finalizeRestoreBranch(props.projectId, branchId, props.name ? { name: props.name } : undefined));
360
- writer(props).end(data.operations ?? [], {
361
- fields: OPERATION_FIELDS,
362
- title: "operations",
363
- emptyMessage: `Finalized restore for branch ${branchId}.`,
364
- });
365
- };
366
- const scheduleGet = async (props) => {
367
- const { branchId } = await resolveBranchRef({
368
- ...props,
369
- branch: props.branch,
370
- });
371
- const { data } = await props.apiClient.getSnapshotSchedule(props.projectId, branchId);
372
- writer(props).end(data.schedule, {
373
- fields: SCHEDULE_FIELDS,
374
- title: "schedule",
375
- emptyMessage: "No automatic snapshot schedule is configured.",
376
- });
377
- };
378
- /**
379
- * Validate an untrusted parsed value as a {@link BackupScheduleItem}[] without any
380
- * type casting, throwing a clear error for the first invalid field it finds.
381
- */
382
- const parseScheduleJson = (raw) => {
383
- let parsed;
384
- try {
385
- parsed = JSON.parse(raw);
386
- }
387
- catch {
388
- throw new Error("--schedule must be valid JSON.");
389
- }
390
- if (!Array.isArray(parsed)) {
391
- throw new Error('--schedule must be a JSON array of schedule entries, e.g. \'[{"frequency":"daily","hour":3}]\'.');
392
- }
393
- return parsed.map((entry, index) => {
394
- if (!isRecord(entry)) {
395
- throw new Error(`--schedule entry ${index} must be an object.`);
396
- }
397
- const record = entry;
398
- const frequency = record.frequency;
399
- if (typeof frequency !== "string") {
400
- throw new Error(`--schedule entry ${index} is missing a string "frequency".`);
401
- }
402
- if (!isSnapshotFrequency(frequency)) {
403
- throw new Error(`--schedule entry ${index} has an unsupported "frequency": "${frequency}". Use one of: ${SNAPSHOT_FREQUENCIES.join(", ")}.`);
404
- }
405
- const item = { frequency };
406
- for (const key of [
407
- "hour",
408
- "day",
409
- "month",
410
- "retention_seconds",
411
- ]) {
412
- const value = record[key];
413
- if (value === undefined) {
414
- continue;
415
- }
416
- if (typeof value !== "number") {
417
- throw new Error(`--schedule entry ${index} field "${key}" must be a number.`);
418
- }
419
- item[key] = value;
420
- }
421
- return item;
422
- });
423
- };
424
- const scheduleSet = async (props) => {
425
- const { branchId } = await resolveBranchRef({
426
- ...props,
427
- branch: props.branch,
428
- });
429
- let schedule;
430
- if (props.schedule) {
431
- schedule = parseScheduleJson(props.schedule);
432
- }
433
- else if (props.frequency) {
434
- const item = { frequency: props.frequency };
435
- if (props.hour !== undefined)
436
- item.hour = props.hour;
437
- if (props.day !== undefined)
438
- item.day = props.day;
439
- if (props.month !== undefined)
440
- item.month = props.month;
441
- if (props.retention !== undefined)
442
- item.retention_seconds = props.retention;
443
- schedule = [item];
444
- }
445
- else {
446
- throw new Error("Provide --frequency (optionally with --hour/--day/--month/--retention) or --schedule <json>.");
447
- }
448
- await retryOnLock(() => props.apiClient.setSnapshotSchedule(props.projectId, branchId, {
449
- schedule,
450
- }));
451
- writer(props).end(schedule, {
452
- fields: SCHEDULE_FIELDS,
453
- title: "schedule",
454
- });
455
- };
@@ -1,40 +0,0 @@
1
- import { fillSingleProject } from "../utils/enrichers.js";
2
- import { status } from "./config.js";
3
- /**
4
- * `neon status` is a top-level alias for `neon config status` — the most-reached-for
5
- * config subcommand. It mirrors that command's options (including `--current-branch`,
6
- * the offline branch probe) and delegates to the same `status` handler.
7
- *
8
- * Because it has a handler but no subcommands, `status` must also be listed in
9
- * `NO_SUBCOMMANDS_VERBS` (see index.ts) so the help-fallback middleware doesn't
10
- * intercept a bare `neon status`.
11
- */
12
- export const command = "status";
13
- export const describe = "Show the branch's live Neon state (alias of `config status`)";
14
- export const builder = (argv) => argv
15
- .usage("$0 status [options]")
16
- .options({
17
- "project-id": {
18
- describe: "Project ID",
19
- type: "string",
20
- },
21
- branch: {
22
- describe: "Branch ID or name",
23
- type: "string",
24
- },
25
- "config-json": {
26
- describe: "Print only the branch's live config as neon.ts-shaped JSON " +
27
- "(services + branch tuning + preview), to stdout. Useful for " +
28
- "scripting or copying into a neon.ts.",
29
- type: "boolean",
30
- default: false,
31
- },
32
- "current-branch": {
33
- describe: "Print only the linked branch name from the local .neon file " +
34
- "(no network). Exits non-zero when no branch is pinned.",
35
- type: "boolean",
36
- default: false,
37
- },
38
- })
39
- .middleware(fillSingleProject);
40
- export const handler = (args) => status(args);
@@ -1,15 +0,0 @@
1
- import { writer } from "../writer.js";
2
- export const command = "me";
3
- export const describe = "Show current user";
4
- export const builder = (yargs) => yargs.option("context-file", {
5
- hidden: true,
6
- });
7
- export const handler = async (args) => {
8
- await me(args);
9
- };
10
- const me = async (props) => {
11
- const { data } = await props.apiClient.getCurrentUserInfo();
12
- writer(props).end(data, {
13
- fields: ["login", "email", "name", "projects_limit"],
14
- });
15
- };