neonctl 2.33.1 → 2.34.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
@@ -505,6 +505,50 @@ $ neon bootstrap . --template hono
505
505
 
506
506
  The target directory must be empty unless you pass `--force` (a lone `.git` is ignored, so a freshly `git init`ed folder is fine). Symlinks and executable bits in the template are preserved.
507
507
 
508
+ ## Snapshots (`snapshots`)
509
+
510
+ `neon snapshots` (alias `neon snapshot`) manages **snapshots** — point-in-time backups of a branch that you can list, rename, expire, restore into a branch, or schedule automatically. Snapshots are a Beta Neon feature and were previously only available in the Console and REST API; this command group brings them to the CLI.
511
+
512
+ Every sub-command resolves the project through the standard chain (`--project-id`, then the `.neon` context file, then a single-project auto-detect). Branch-scoped sub-commands (`create`, `schedule`) default to the branch pinned in `.neon`, falling back to the project's default branch, and accept `--branch <id|name>`. The `get`, `update`, `delete`, and `restore` sub-commands take a snapshot **id or name** as their positional argument (an id wins; an ambiguous name errors and asks you to use the id).
513
+
514
+ ```bash
515
+ # Snapshot the head of the current/default branch
516
+ neon snapshots create --name pre-migration
517
+
518
+ # Snapshot a specific branch at a point in time (RFC 3339 timestamp OR LSN — mutually exclusive)
519
+ neon snapshots create --branch main --timestamp 2025-01-01T00:00:00Z
520
+ neon snapshots create --branch main --lsn 0/1F3C8A0 --expires-at 2025-12-31T23:59:59Z
521
+
522
+ # List / inspect
523
+ neon snapshots list
524
+ neon snapshots get pre-migration
525
+
526
+ # Rename or change expiration (omit both to error; --expires-at and --clear-expiration conflict)
527
+ neon snapshots update snap-1234 --name nightly
528
+ neon snapshots update snap-1234 --expires-at 2030-01-01T00:00:00Z
529
+ neon snapshots update snap-1234 --clear-expiration # keep indefinitely
530
+
531
+ # Restore a snapshot to a NEW branch
532
+ neon snapshots restore snap-1234 --name recovered
533
+
534
+ # Restore ONTO an existing branch. Without --finalize the restore is left un-finalized
535
+ # so you can inspect it first, then swap it in:
536
+ neon snapshots restore snap-1234 --target-branch main
537
+ neon snapshots finalize br-restored-1234 # commit the swap
538
+ # …or do it in one step:
539
+ neon snapshots restore snap-1234 --target-branch main --finalize
540
+
541
+ # Delete
542
+ neon snapshots delete snap-1234
543
+
544
+ # Automatic snapshot (backup) schedule of a branch
545
+ neon snapshots schedule get --branch main
546
+ neon snapshots schedule set --branch main --frequency daily --hour 3 --retention 604800
547
+ neon snapshots schedule set --branch main --schedule '[{"frequency":"hourly"},{"frequency":"daily","hour":3}]'
548
+ ```
549
+
550
+ All sub-commands honor the [global options](#global-options), including `--output json|yaml|table`.
551
+
508
552
  ## Commands
509
553
 
510
554
  | Command | Subcommands | Description |
@@ -518,6 +562,7 @@ The target directory must be empty unless you pass `--force` (a lone `.git` is i
518
562
  | function | `deploy`, `list`, `get`, `delete` | Manage Neon Functions |
519
563
  | [roles](https://neon.com/docs/reference/cli-roles) | `list`, `create`, `delete` | Manage roles |
520
564
  | [operations](https://neon.com/docs/reference/cli-operations) | `list` | Manage operations |
565
+ | snapshots | `list`, `get`, `create`, `update`, `delete`, `restore`, `finalize`, `schedule get`, `schedule set` | Manage snapshots |
521
566
  | [connection-string](https://neon.com/docs/reference/cli-connection-string) | | Get connection string |
522
567
  | [psql](https://neon.com/docs/reference/cli-psql) | | Connect to a database via psql |
523
568
  | set-context | | Deprecated; use `link` |
package/dist/analytics.js CHANGED
@@ -17,6 +17,7 @@ const hasCurrentBranchArgv = () => process.argv.includes("--current-branch");
17
17
  let client;
18
18
  let clientInitialized = false;
19
19
  let userId = "";
20
+ let errorEventContext;
20
21
  /**
21
22
  * Phase 1: Run before validation so the Segment client exists if any
22
23
  * middleware (e.g. auth) fails. Enables sendError() in the fail handler.
@@ -34,6 +35,7 @@ export const initAnalyticsClientMiddleware = (args) => {
34
35
  return;
35
36
  }
36
37
  clientInitialized = true;
38
+ errorEventContext = getErrorAnalyticsEventContext(args);
37
39
  client = new Analytics({
38
40
  writeKey: WRITE_KEY,
39
41
  host: "https://track.neon.tech",
@@ -112,6 +114,18 @@ export const closeAnalytics = async (opts) => {
112
114
  log.debug("Flushed CLI analytics");
113
115
  }
114
116
  };
117
+ export const getErrorAnalyticsEventProperties = (err, errCode, context) => {
118
+ const apiError = isNeonApiError(err) ? err : undefined;
119
+ const requestId = apiError?.headers?.["x-neon-ret-request-id"];
120
+ return {
121
+ ...context,
122
+ message: err.message,
123
+ stack: err.stack,
124
+ errCode,
125
+ statusCode: apiError?.status,
126
+ requestId,
127
+ };
128
+ };
115
129
  export const sendError = (err, errCode) => {
116
130
  if (!client) {
117
131
  return;
@@ -124,13 +138,7 @@ export const sendError = (err, errCode) => {
124
138
  client.track({
125
139
  event: "CLI Error",
126
140
  userId: userId || "anonymous",
127
- properties: {
128
- message: err.message,
129
- stack: err.stack,
130
- errCode,
131
- statusCode: apiError?.status,
132
- requestId: requestId,
133
- },
141
+ properties: getErrorAnalyticsEventProperties(err, errCode, errorEventContext),
134
142
  });
135
143
  log.debug("Sent CLI error event: %s", errCode);
136
144
  };
@@ -145,6 +153,10 @@ export const trackEvent = (event, properties) => {
145
153
  });
146
154
  log.debug("Sent CLI event: %s", event);
147
155
  };
156
+ const getErrorAnalyticsEventContext = (_args) => ({
157
+ version: pkg.version,
158
+ ci: isCi(),
159
+ });
148
160
  export const getAnalyticsEventProperties = (args) => ({
149
161
  version: pkg.version,
150
162
  command: args._.join(" "),
package/dist/api.js CHANGED
@@ -423,6 +423,44 @@ export const getApiClient = ({ apiKey, apiHost }) => {
423
423
  path: { project_id: projectId },
424
424
  body: data,
425
425
  })),
426
+ // ─── Snapshots ───────────────────────────────────────────────────────
427
+ listSnapshots: (projectId) => call(() => raw.listSnapshots({
428
+ client,
429
+ path: { project_id: projectId },
430
+ })),
431
+ createSnapshot: (projectId, branchId, query) => call(() => raw.createSnapshot({
432
+ client,
433
+ path: { project_id: projectId, branch_id: branchId },
434
+ ...(query !== undefined ? { query } : {}),
435
+ })),
436
+ updateSnapshot: (projectId, snapshotId, data) => call(() => raw.updateSnapshot({
437
+ client,
438
+ path: { project_id: projectId, snapshot_id: snapshotId },
439
+ body: data,
440
+ })),
441
+ deleteSnapshot: (projectId, snapshotId) => call(() => raw.deleteSnapshot({
442
+ client,
443
+ path: { project_id: projectId, snapshot_id: snapshotId },
444
+ })),
445
+ restoreSnapshot: (projectId, snapshotId, data) => call(() => raw.restoreSnapshot({
446
+ client,
447
+ path: { project_id: projectId, snapshot_id: snapshotId },
448
+ ...(data !== undefined ? { body: data } : {}),
449
+ })),
450
+ finalizeRestoreBranch: (projectId, branchId, data) => call(() => raw.finalizeRestoreBranch({
451
+ client,
452
+ path: { project_id: projectId, branch_id: branchId },
453
+ ...(data !== undefined ? { body: data } : {}),
454
+ })),
455
+ getSnapshotSchedule: (projectId, branchId) => call(() => raw.getSnapshotSchedule({
456
+ client,
457
+ path: { project_id: projectId, branch_id: branchId },
458
+ })),
459
+ setSnapshotSchedule: (projectId, branchId, data) => call(() => raw.setSnapshotSchedule({
460
+ client,
461
+ path: { project_id: projectId, branch_id: branchId },
462
+ body: data,
463
+ })),
426
464
  // ─── Databases ───────────────────────────────────────────────────────
427
465
  listProjectBranchDatabases: (projectId, branchId) => call(() => raw.listProjectBranchDatabases({
428
466
  client,
@@ -23,6 +23,7 @@ import * as projects from "./projects.js";
23
23
  import * as psql from "./psql.js";
24
24
  import * as roles from "./roles.js";
25
25
  import * as setContext from "./set_context.js";
26
+ import * as snapshots from "./snapshots.js";
26
27
  import * as status from "./status.js";
27
28
  import * as users from "./user.js";
28
29
  import * as vpcEndpoints from "./vpc_endpoints.js";
@@ -39,6 +40,7 @@ export default [
39
40
  databases,
40
41
  roles,
41
42
  operations,
43
+ snapshots,
42
44
  cs,
43
45
  psql,
44
46
  setContext,
@@ -0,0 +1,448 @@
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
+ const SNAPSHOT_FREQUENCIES = [
27
+ "hourly",
28
+ "daily",
29
+ "weekly",
30
+ "monthly",
31
+ "yearly",
32
+ ];
33
+ export const command = "snapshots";
34
+ export const describe = "Manage snapshots";
35
+ export const aliases = ["snapshot"];
36
+ export const builder = (argv) => argv
37
+ .usage("$0 snapshots <sub-command> [options]")
38
+ .options({
39
+ "project-id": {
40
+ describe: "Project ID",
41
+ type: "string",
42
+ },
43
+ })
44
+ .middleware(fillSingleProject)
45
+ .command("list", "List snapshots in the project", (yargs) => yargs, (args) => list(args))
46
+ .command("get <id>", "Get a snapshot by id or name", (yargs) => yargs, (args) => get(args))
47
+ .command("create", "Create a snapshot from a branch", (yargs) => yargs
48
+ .options({
49
+ branch: {
50
+ alias: "b",
51
+ describe: "Branch id or name to snapshot. Defaults to the branch in your context, or the project's default branch.",
52
+ type: "string",
53
+ },
54
+ name: {
55
+ describe: "A name for the snapshot",
56
+ type: "string",
57
+ },
58
+ timestamp: {
59
+ 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.",
60
+ type: "string",
61
+ },
62
+ lsn: {
63
+ describe: "Take the snapshot at this LSN (e.g. 0/1F3C8A0). Must fall within the branch's restore window. Mutually exclusive with --timestamp.",
64
+ type: "string",
65
+ },
66
+ "expires-at": {
67
+ describe: "When the snapshot is automatically deleted (RFC 3339, e.g. 2025-12-31T23:59:59Z). Omit to keep it indefinitely.",
68
+ type: "string",
69
+ },
70
+ })
71
+ .conflicts("timestamp", "lsn")
72
+ .example([
73
+ [
74
+ "$0 snapshots create",
75
+ "Snapshot the head of the context/default branch",
76
+ ],
77
+ [
78
+ "$0 snapshots create --branch main --name pre-migration",
79
+ "Snapshot the head of main with a name",
80
+ ],
81
+ [
82
+ "$0 snapshots create --branch main --timestamp 2025-01-01T00:00:00Z",
83
+ "Snapshot main at a point in time",
84
+ ],
85
+ [
86
+ "$0 snapshots create --branch main --lsn 0/1F3C8A0 --expires-at 2025-12-31T23:59:59Z",
87
+ "Snapshot main at an LSN, auto-deleting at the given time",
88
+ ],
89
+ ]), (args) => create(args))
90
+ .command("update <id>", "Update a snapshot's name or expiration", (yargs) => yargs
91
+ .options({
92
+ name: {
93
+ describe: "Rename the snapshot",
94
+ type: "string",
95
+ },
96
+ "expires-at": {
97
+ describe: "Set when the snapshot expires (RFC 3339). Mutually exclusive with --clear-expiration.",
98
+ type: "string",
99
+ },
100
+ "clear-expiration": {
101
+ describe: "Clear the expiration so the snapshot is kept indefinitely.",
102
+ type: "boolean",
103
+ },
104
+ })
105
+ .conflicts("expires-at", "clear-expiration"), (args) => update(args))
106
+ .command("delete <id>", "Delete a snapshot by id or name", (yargs) => yargs, (args) => deleteSnapshot(args))
107
+ .command("restore <id>", "Restore a snapshot into a branch", (yargs) => yargs
108
+ .options({
109
+ name: {
110
+ describe: "Name for the newly restored branch. Auto-generated when omitted.",
111
+ type: "string",
112
+ },
113
+ "target-branch": {
114
+ 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).",
115
+ type: "string",
116
+ },
117
+ finalize: {
118
+ 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>`.",
119
+ type: "boolean",
120
+ default: false,
121
+ },
122
+ })
123
+ .example([
124
+ [
125
+ "$0 snapshots restore snap-1234 --name recovered",
126
+ "Restore a snapshot to a new branch named 'recovered'",
127
+ ],
128
+ [
129
+ "$0 snapshots restore snap-1234 --target-branch main --finalize",
130
+ "Restore onto main and swap it in immediately",
131
+ ],
132
+ [
133
+ "$0 snapshots restore snap-1234 --target-branch main",
134
+ "Restore onto main un-finalized to preview, then run `snapshots finalize`",
135
+ ],
136
+ ]), (args) => restore(args))
137
+ .command("finalize <branch>", "Finalize a previewed snapshot restore (swap the restored branch in)", (yargs) => yargs.options({
138
+ name: {
139
+ describe: "Name to give the replaced (old) branch. Auto-generated when omitted.",
140
+ type: "string",
141
+ },
142
+ }), (args) => finalize(args))
143
+ .command("schedule", "Manage the automatic snapshot (backup) schedule of a branch", (yargs) => yargs
144
+ .usage("$0 snapshots schedule <sub-command> [options]")
145
+ .command("get", "Get a branch's automatic snapshot schedule", (yargs) => yargs.options({
146
+ branch: {
147
+ alias: "b",
148
+ describe: "Branch id or name. Defaults to the branch in your context, or the project's default branch.",
149
+ type: "string",
150
+ },
151
+ }), (args) => scheduleGet(args))
152
+ .command("set", "Set a branch's automatic snapshot schedule", (yargs) => yargs
153
+ .options({
154
+ branch: {
155
+ alias: "b",
156
+ describe: "Branch id or name. Defaults to the branch in your context, or the project's default branch.",
157
+ type: "string",
158
+ },
159
+ frequency: {
160
+ describe: "How often to take snapshots. Builds a single-entry schedule together with --hour/--day/--month/--retention.",
161
+ choices: SNAPSHOT_FREQUENCIES,
162
+ type: "string",
163
+ },
164
+ hour: {
165
+ describe: "Hour of the day (0-23) to take the snapshot (used with --frequency).",
166
+ type: "number",
167
+ },
168
+ day: {
169
+ describe: "Day of the week/month (1-31) to take the snapshot (used with --frequency).",
170
+ type: "number",
171
+ },
172
+ month: {
173
+ describe: "Month of the year (1-12) to take the snapshot (used with --frequency).",
174
+ type: "number",
175
+ },
176
+ retention: {
177
+ describe: "How long to keep each snapshot, in seconds (min 3600). Omit to keep indefinitely.",
178
+ type: "number",
179
+ },
180
+ schedule: {
181
+ describe: 'Full schedule as JSON, for multi-entry schedules, e.g. \'[{"frequency":"daily","hour":3,"retention_seconds":604800}]\'. Overrides the single-entry flags.',
182
+ type: "string",
183
+ },
184
+ })
185
+ .example([
186
+ [
187
+ "$0 snapshots schedule set --branch main --frequency daily --hour 3 --retention 604800",
188
+ "A daily 03:00 snapshot kept for 7 days",
189
+ ],
190
+ [
191
+ '$0 snapshots schedule set --branch main --schedule \'[{"frequency":"hourly"},{"frequency":"daily","hour":3}]\'',
192
+ "A multi-entry schedule via JSON",
193
+ ],
194
+ ]), (args) => scheduleSet(args))
195
+ .demandCommand(1, "Specify `get` or `set`."), () => { })
196
+ .demandCommand(1, "Specify a snapshots sub-command.");
197
+ export const handler = (args) => {
198
+ return args;
199
+ };
200
+ /** Narrow an unknown parsed JSON value to a plain object without type casting. */
201
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
202
+ /** Normalize a user-supplied date to an ISO 8601 string, or throw a friendly error. */
203
+ const toIso = (value, flag) => {
204
+ const ms = Date.parse(value);
205
+ if (Number.isNaN(ms)) {
206
+ throw new Error(`Invalid ${flag} value: "${value}". Use an RFC 3339 timestamp, e.g. 2025-12-31T23:59:59Z.`);
207
+ }
208
+ return new Date(ms).toISOString();
209
+ };
210
+ /**
211
+ * Resolve a snapshot from an id **or** a name. Snapshot names are not guaranteed
212
+ * unique, so an id match wins; a name that resolves to more than one snapshot is a
213
+ * hard error asking the user to disambiguate by id.
214
+ */
215
+ const resolveSnapshot = async (props) => {
216
+ const { data: { snapshots }, } = await props.apiClient.listSnapshots(props.projectId);
217
+ const byId = snapshots.find((s) => s.id === props.id);
218
+ if (byId) {
219
+ return byId;
220
+ }
221
+ const byName = snapshots.filter((s) => s.name === props.id);
222
+ if (byName.length === 1) {
223
+ return byName[0];
224
+ }
225
+ if (byName.length > 1) {
226
+ throw new Error(`Multiple snapshots are named "${props.id}". Re-run with the snapshot id:\n${byName
227
+ .map((s) => ` ${s.id}`)
228
+ .join("\n")}`);
229
+ }
230
+ throw new Error(`Snapshot "${props.id}" not found.\nAvailable snapshots: ${snapshots.map((s) => `${s.name} (${s.id})`).join(", ") ||
231
+ "none"}`);
232
+ };
233
+ const list = async (props) => {
234
+ const { data: { snapshots }, } = await props.apiClient.listSnapshots(props.projectId);
235
+ writer(props).end(snapshots, {
236
+ fields: SNAPSHOT_FIELDS,
237
+ title: "snapshots",
238
+ emptyMessage: "No snapshots found. Create one with:\n> neon snapshots create --help",
239
+ renderColumns: {
240
+ expires_at: (s) => s.expires_at || "never",
241
+ },
242
+ });
243
+ };
244
+ const get = async (props) => {
245
+ const snapshot = await resolveSnapshot(props);
246
+ writer(props).end(snapshot, {
247
+ fields: SNAPSHOT_FIELDS,
248
+ renderColumns: {
249
+ expires_at: (s) => s.expires_at || "never",
250
+ },
251
+ });
252
+ };
253
+ const create = async (props) => {
254
+ if (props.lsn !== undefined && !looksLikeLSN(props.lsn)) {
255
+ throw new Error(`Invalid --lsn value: "${props.lsn}". Expected an LSN like 0/1F3C8A0.`);
256
+ }
257
+ if (props.timestamp !== undefined && !looksLikeTimestamp(props.timestamp)) {
258
+ throw new Error(`Invalid --timestamp value: "${props.timestamp}". Use an RFC 3339 timestamp, e.g. 2025-01-01T00:00:00Z.`);
259
+ }
260
+ const { branchId } = await resolveBranchRef({
261
+ ...props,
262
+ branch: props.branch,
263
+ });
264
+ const { data } = await retryOnLock(() => props.apiClient.createSnapshot(props.projectId, branchId, {
265
+ name: props.name,
266
+ timestamp: props.timestamp,
267
+ lsn: props.lsn,
268
+ expires_at: props.expiresAt
269
+ ? toIso(props.expiresAt, "--expires-at")
270
+ : undefined,
271
+ }));
272
+ writer(props).end(data.snapshot, {
273
+ fields: SNAPSHOT_FIELDS,
274
+ title: "snapshot",
275
+ renderColumns: {
276
+ expires_at: (s) => s.expires_at || "never",
277
+ },
278
+ });
279
+ };
280
+ const update = async (props) => {
281
+ if (props.name === undefined &&
282
+ props.expiresAt === undefined &&
283
+ !props.clearExpiration) {
284
+ throw new Error("Nothing to update. Pass --name, --expires-at, or --clear-expiration.");
285
+ }
286
+ const snapshot = await resolveSnapshot(props);
287
+ // `undefined` fields are dropped by JSON serialization, so an omitted
288
+ // `expires_at` leaves the expiration unchanged while an explicit `null`
289
+ // clears it.
290
+ const expiresAt = props.clearExpiration
291
+ ? null
292
+ : props.expiresAt !== undefined
293
+ ? toIso(props.expiresAt, "--expires-at")
294
+ : undefined;
295
+ const { data } = await retryOnLock(() => props.apiClient.updateSnapshot(props.projectId, snapshot.id, {
296
+ snapshot: {
297
+ name: props.name,
298
+ expires_at: expiresAt,
299
+ },
300
+ }));
301
+ writer(props).end(data.snapshot, {
302
+ fields: SNAPSHOT_FIELDS,
303
+ renderColumns: {
304
+ expires_at: (s) => s.expires_at || "never",
305
+ },
306
+ });
307
+ };
308
+ const deleteSnapshot = async (props) => {
309
+ const snapshot = await resolveSnapshot(props);
310
+ await retryOnLock(() => props.apiClient.deleteSnapshot(props.projectId, snapshot.id));
311
+ // The delete endpoint returns the tracking operations (202), not the snapshot
312
+ // body, so echo the snapshot we just deleted for confirmation.
313
+ writer(props).end(snapshot, {
314
+ fields: SNAPSHOT_FIELDS,
315
+ renderColumns: {
316
+ expires_at: (s) => s.expires_at || "never",
317
+ },
318
+ });
319
+ };
320
+ const restore = async (props) => {
321
+ const snapshot = await resolveSnapshot(props);
322
+ const targetBranchId = props.targetBranch
323
+ ? await branchIdResolve({
324
+ branch: props.targetBranch,
325
+ projectId: props.projectId,
326
+ apiClient: props.apiClient,
327
+ })
328
+ : undefined;
329
+ const { data } = await retryOnLock(() => props.apiClient.restoreSnapshot(props.projectId, snapshot.id, {
330
+ name: props.name,
331
+ target_branch_id: targetBranchId,
332
+ finalize_restore: props.finalize,
333
+ }));
334
+ const out = writer(props).write(data.branch, {
335
+ fields: BRANCH_FIELDS,
336
+ title: "restored branch",
337
+ });
338
+ if (data.operations?.length) {
339
+ out.write(data.operations, {
340
+ fields: OPERATION_FIELDS,
341
+ title: "operations",
342
+ });
343
+ }
344
+ out.end();
345
+ if (!props.finalize) {
346
+ log.info(`Restore left un-finalized. Inspect branch ${data.branch.id}, then run:\n neon snapshots finalize ${data.branch.id} --project-id ${props.projectId}`);
347
+ }
348
+ };
349
+ const finalize = async (props) => {
350
+ const branchId = await branchIdResolve({
351
+ branch: props.branch,
352
+ projectId: props.projectId,
353
+ apiClient: props.apiClient,
354
+ });
355
+ const { data } = await retryOnLock(() => props.apiClient.finalizeRestoreBranch(props.projectId, branchId, props.name ? { name: props.name } : undefined));
356
+ writer(props).end(data.operations ?? [], {
357
+ fields: OPERATION_FIELDS,
358
+ title: "operations",
359
+ emptyMessage: `Finalized restore for branch ${branchId}.`,
360
+ });
361
+ };
362
+ const scheduleGet = async (props) => {
363
+ const { branchId } = await resolveBranchRef({
364
+ ...props,
365
+ branch: props.branch,
366
+ });
367
+ const { data } = await props.apiClient.getSnapshotSchedule(props.projectId, branchId);
368
+ writer(props).end(data.schedule, {
369
+ fields: SCHEDULE_FIELDS,
370
+ title: "schedule",
371
+ emptyMessage: "No automatic snapshot schedule is configured.",
372
+ });
373
+ };
374
+ /**
375
+ * Validate an untrusted parsed value as a {@link BackupScheduleItem}[] without any
376
+ * type casting, throwing a clear error for the first invalid field it finds.
377
+ */
378
+ const parseScheduleJson = (raw) => {
379
+ let parsed;
380
+ try {
381
+ parsed = JSON.parse(raw);
382
+ }
383
+ catch {
384
+ throw new Error("--schedule must be valid JSON.");
385
+ }
386
+ if (!Array.isArray(parsed)) {
387
+ throw new Error('--schedule must be a JSON array of schedule entries, e.g. \'[{"frequency":"daily","hour":3}]\'.');
388
+ }
389
+ return parsed.map((entry, index) => {
390
+ if (!isRecord(entry)) {
391
+ throw new Error(`--schedule entry ${index} must be an object.`);
392
+ }
393
+ const record = entry;
394
+ const frequency = record.frequency;
395
+ if (typeof frequency !== "string") {
396
+ throw new Error(`--schedule entry ${index} is missing a string "frequency".`);
397
+ }
398
+ const item = { frequency };
399
+ for (const key of [
400
+ "hour",
401
+ "day",
402
+ "month",
403
+ "retention_seconds",
404
+ ]) {
405
+ const value = record[key];
406
+ if (value === undefined) {
407
+ continue;
408
+ }
409
+ if (typeof value !== "number") {
410
+ throw new Error(`--schedule entry ${index} field "${key}" must be a number.`);
411
+ }
412
+ item[key] = value;
413
+ }
414
+ return item;
415
+ });
416
+ };
417
+ const scheduleSet = async (props) => {
418
+ const { branchId } = await resolveBranchRef({
419
+ ...props,
420
+ branch: props.branch,
421
+ });
422
+ let schedule;
423
+ if (props.schedule) {
424
+ schedule = parseScheduleJson(props.schedule);
425
+ }
426
+ else if (props.frequency) {
427
+ const item = { frequency: props.frequency };
428
+ if (props.hour !== undefined)
429
+ item.hour = props.hour;
430
+ if (props.day !== undefined)
431
+ item.day = props.day;
432
+ if (props.month !== undefined)
433
+ item.month = props.month;
434
+ if (props.retention !== undefined)
435
+ item.retention_seconds = props.retention;
436
+ schedule = [item];
437
+ }
438
+ else {
439
+ throw new Error("Provide --frequency (optionally with --hour/--day/--month/--retention) or --schedule <json>.");
440
+ }
441
+ await retryOnLock(() => props.apiClient.setSnapshotSchedule(props.projectId, branchId, {
442
+ schedule,
443
+ }));
444
+ writer(props).end(schedule, {
445
+ fields: SCHEDULE_FIELDS,
446
+ title: "schedule",
447
+ });
448
+ };
@@ -10,8 +10,8 @@ import { log } from "../log.js";
10
10
  * - **Free plan** — credentials provision, but the gateway does not *serve* model requests.
11
11
  * The account needs to upgrade to a paid plan.
12
12
  * - **Reduced model set** — on a paid plan, an account still ramping up on the beta gets a
13
- * trimmed model catalog (flagship models are missing from `/v1/models`). They can request
14
- * access to more models.
13
+ * trimmed model catalog (flagship models are listed but `enabled: false` on `/v1/models`).
14
+ * They can request access to more models.
15
15
  *
16
16
  * This is deliberately phrased for the user: it never mentions account "verification" or any
17
17
  * other internal gating mechanism.
@@ -39,11 +39,11 @@ export const aiGatewayModelsUrl = (projectId, branchId) => `https://console.neon
39
39
  export const isFreePlan = (subscriptionType) => subscriptionType !== undefined &&
40
40
  FREE_SUBSCRIPTION_TYPES.has(subscriptionType);
41
41
  /**
42
- * Whether a model catalog includes at least one flagship model. Flagship models (Anthropic
43
- * Opus, OpenAI Codex / `*-pro`) are the first to be held back for an account still ramping
44
- * up on the beta, so their total absence from a non-empty catalog is the signal that the
45
- * account has a reduced model set. Matched by id substring so it survives model version
46
- * bumps (e.g. `claude-opus-4-8`).
42
+ * Whether the model catalog includes at least one flagship model enabled. Flagship models
43
+ * (Anthropic Opus, OpenAI Codex / `*-pro`) are the first to be held back for an account still
44
+ * ramping up on the beta, so their total absence from a non-empty enabled set is the signal
45
+ * that the account has a reduced model set. Matched by id substring so it survives model
46
+ * version bumps (e.g. `claude-opus-4-8`).
47
47
  */
48
48
  export const hasFlagshipModels = (modelIds) => modelIds.some((id) => id.includes("opus") || id.includes("codex") || id.endsWith("-pro"));
49
49
  /**
@@ -86,20 +86,27 @@ export const buildAiGatewayNotice = ({ subscriptionType, modelIds, upgradeUrl, m
86
86
  return null;
87
87
  };
88
88
  const isRecord = (value) => typeof value === "object" && value !== null;
89
- /** Pull the string `id`s out of an OpenAI-compatible `{ object: "list", data: [...] }` body. */
90
- const extractModelIds = (body) => {
89
+ /**
90
+ * Pull the `id`s of enabled models out of an OpenAI-compatible
91
+ * `{ object: "list", data: [{ id, enabled, ... }] }` body. The gateway lists every model in
92
+ * the catalog but marks ones the account can't serve yet with `enabled: false`; only the
93
+ * enabled set is used to detect a reduced catalog.
94
+ */
95
+ export const extractEnabledModelIds = (body) => {
91
96
  if (!isRecord(body) || !Array.isArray(body.data))
92
97
  return null;
93
98
  const ids = [];
94
99
  for (const entry of body.data) {
95
- if (isRecord(entry) && typeof entry.id === "string") {
100
+ if (isRecord(entry) &&
101
+ typeof entry.id === "string" &&
102
+ entry.enabled === true) {
96
103
  ids.push(entry.id);
97
104
  }
98
105
  }
99
106
  return ids;
100
107
  };
101
108
  /**
102
- * `GET {baseUrl}/v1/models` → the served model ids, or `null` if the catalog can't be read
109
+ * `GET {baseUrl}/v1/models` → the enabled model ids, or `null` if the catalog can't be read
103
110
  * (network / HTTP / parse failure). Returning `null` keeps the notice silent rather than
104
111
  * risking a false "reduced models" warning. `/v1/models` is served only on the unified
105
112
  * dialect (the `/openai/v1` Responses dialect returns 404).
@@ -111,7 +118,7 @@ export const fetchGatewayModelIds = async (baseUrl, token) => {
111
118
  });
112
119
  if (!res.ok)
113
120
  return null;
114
- return extractModelIds(await res.json());
121
+ return extractEnabledModelIds(await res.json());
115
122
  }
116
123
  catch {
117
124
  return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neonctl",
3
- "version": "2.33.1",
3
+ "version": "2.34.0",
4
4
  "description": "CLI tool for Neon Serverless Postgres",
5
5
  "keywords": [
6
6
  "neon",
@@ -52,9 +52,9 @@
52
52
  "yaml": "^2.9.0",
53
53
  "yargs": "17.7.2",
54
54
  "@neon/sdk": "1.1.1",
55
+ "@neon/config": "0.9.4",
55
56
  "@neon/config-runtime": "0.9.4",
56
- "@neon/env": "0.11.3",
57
- "@neon/config": "0.9.4"
57
+ "@neon/env": "0.11.3"
58
58
  },
59
59
  "optionalDependencies": {
60
60
  "esbuild": "0.28.1"