neon 2.1.1 → 2.29.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 (166) hide show
  1. package/LICENSE.md +178 -0
  2. package/README.md +601 -0
  3. package/dist/analytics.js +156 -0
  4. package/dist/api.js +665 -0
  5. package/dist/auth.js +127 -0
  6. package/dist/callback.html +51 -0
  7. package/dist/cli.js +9 -0
  8. package/dist/commands/auth.js +214 -0
  9. package/dist/commands/bootstrap.js +481 -0
  10. package/dist/commands/branches.js +481 -0
  11. package/dist/commands/bucket.js +543 -0
  12. package/dist/commands/checkout.js +289 -0
  13. package/dist/commands/config.js +544 -0
  14. package/dist/commands/connection_string.js +172 -0
  15. package/dist/commands/data_api.js +285 -0
  16. package/dist/commands/databases.js +82 -0
  17. package/dist/commands/deploy.js +26 -0
  18. package/dist/commands/dev.js +698 -0
  19. package/dist/commands/env.js +166 -0
  20. package/dist/commands/functions.js +373 -0
  21. package/dist/commands/index.js +54 -0
  22. package/dist/commands/init.js +73 -0
  23. package/dist/commands/ip_allow.js +137 -0
  24. package/dist/commands/link.js +1121 -0
  25. package/dist/commands/neon_auth.js +1028 -0
  26. package/dist/commands/operations.js +28 -0
  27. package/dist/commands/orgs.js +24 -0
  28. package/dist/commands/projects.js +372 -0
  29. package/dist/commands/psql.js +62 -0
  30. package/dist/commands/roles.js +65 -0
  31. package/dist/commands/schema_diff.js +151 -0
  32. package/dist/commands/set_context.js +29 -0
  33. package/dist/commands/status.js +40 -0
  34. package/dist/commands/user.js +15 -0
  35. package/dist/commands/vpc_endpoints.js +134 -0
  36. package/dist/config.js +11 -0
  37. package/dist/config_format.js +72 -0
  38. package/dist/context.js +177 -0
  39. package/dist/current_branch_fast_path.js +55 -0
  40. package/dist/dev/env.js +240 -0
  41. package/dist/dev/functions.js +70 -0
  42. package/dist/dev/inputs.js +63 -0
  43. package/dist/dev/runtime.js +146 -0
  44. package/dist/env.js +36 -0
  45. package/dist/env_file.js +159 -0
  46. package/dist/errors.js +80 -0
  47. package/dist/functions_api.js +44 -0
  48. package/dist/help.js +146 -0
  49. package/dist/index.js +234 -0
  50. package/dist/log.js +18 -0
  51. package/dist/parameters.gen.js +480 -0
  52. package/dist/pkg.js +25 -0
  53. package/dist/psql/cli.js +53 -0
  54. package/dist/psql/command/cmd_cond.js +437 -0
  55. package/dist/psql/command/cmd_connect.js +820 -0
  56. package/dist/psql/command/cmd_copy.js +1035 -0
  57. package/dist/psql/command/cmd_describe.js +1815 -0
  58. package/dist/psql/command/cmd_format.js +922 -0
  59. package/dist/psql/command/cmd_io.js +2193 -0
  60. package/dist/psql/command/cmd_lo.js +393 -0
  61. package/dist/psql/command/cmd_meta.js +970 -0
  62. package/dist/psql/command/cmd_misc.js +187 -0
  63. package/dist/psql/command/cmd_pipeline.js +1148 -0
  64. package/dist/psql/command/cmd_restrict.js +171 -0
  65. package/dist/psql/command/cmd_show.js +766 -0
  66. package/dist/psql/command/dispatch.js +343 -0
  67. package/dist/psql/command/inputQueue.js +42 -0
  68. package/dist/psql/command/shared.js +71 -0
  69. package/dist/psql/complete/filenames.js +139 -0
  70. package/dist/psql/complete/index.js +104 -0
  71. package/dist/psql/complete/matcher.js +315 -0
  72. package/dist/psql/complete/psqlVars.js +247 -0
  73. package/dist/psql/complete/queries.js +493 -0
  74. package/dist/psql/complete/rules.js +2424 -0
  75. package/dist/psql/core/common.js +1253 -0
  76. package/dist/psql/core/help.js +576 -0
  77. package/dist/psql/core/mainloop.js +1360 -0
  78. package/dist/psql/core/prompt.js +440 -0
  79. package/dist/psql/core/settings.js +684 -0
  80. package/dist/psql/core/sqlHelp.js +1066 -0
  81. package/dist/psql/core/startup.js +846 -0
  82. package/dist/psql/core/syncVars.js +116 -0
  83. package/dist/psql/core/variables.js +287 -0
  84. package/dist/psql/describe/formatters.js +1290 -0
  85. package/dist/psql/describe/processNamePattern.js +270 -0
  86. package/dist/psql/describe/queries.js +2378 -0
  87. package/dist/psql/describe/versionGate.js +43 -0
  88. package/dist/psql/index.js +2030 -0
  89. package/dist/psql/io/history.js +299 -0
  90. package/dist/psql/io/input.js +120 -0
  91. package/dist/psql/io/lineEditor/buffer.js +325 -0
  92. package/dist/psql/io/lineEditor/complete.js +227 -0
  93. package/dist/psql/io/lineEditor/filename.js +159 -0
  94. package/dist/psql/io/lineEditor/index.js +894 -0
  95. package/dist/psql/io/lineEditor/keymap.js +745 -0
  96. package/dist/psql/io/lineEditor/vt100.js +363 -0
  97. package/dist/psql/io/pgpass.js +202 -0
  98. package/dist/psql/io/pgservice.js +194 -0
  99. package/dist/psql/io/psqlrc.js +422 -0
  100. package/dist/psql/print/aligned.js +1765 -0
  101. package/dist/psql/print/asciidoc.js +248 -0
  102. package/dist/psql/print/crosstab.js +463 -0
  103. package/dist/psql/print/csv.js +95 -0
  104. package/dist/psql/print/html.js +258 -0
  105. package/dist/psql/print/json.js +96 -0
  106. package/dist/psql/print/latex.js +396 -0
  107. package/dist/psql/print/pager.js +267 -0
  108. package/dist/psql/print/troff.js +258 -0
  109. package/dist/psql/print/unaligned.js +119 -0
  110. package/dist/psql/print/units.js +135 -0
  111. package/dist/psql/scanner/slash.js +515 -0
  112. package/dist/psql/scanner/sql.js +914 -0
  113. package/dist/psql/scanner/stringutils.js +394 -0
  114. package/dist/psql/types/backslash.js +1 -0
  115. package/dist/psql/types/connection.js +1 -0
  116. package/dist/psql/types/index.js +7 -0
  117. package/dist/psql/types/printer.js +1 -0
  118. package/dist/psql/types/repl.js +1 -0
  119. package/dist/psql/types/scanner.js +24 -0
  120. package/dist/psql/types/settings.js +1 -0
  121. package/dist/psql/types/variables.js +1 -0
  122. package/dist/psql/wire/connection.js +2858 -0
  123. package/dist/psql/wire/copy.js +108 -0
  124. package/dist/psql/wire/notify.js +59 -0
  125. package/dist/psql/wire/pipeline.js +521 -0
  126. package/dist/psql/wire/protocol.js +466 -0
  127. package/dist/psql/wire/sasl.js +296 -0
  128. package/dist/psql/wire/tls.js +602 -0
  129. package/dist/storage_api.js +147 -0
  130. package/dist/test_utils/fixtures.js +122 -0
  131. package/dist/test_utils/oauth_server.js +9 -0
  132. package/dist/types.js +1 -0
  133. package/dist/utils/api_enums.js +33 -0
  134. package/dist/utils/auth.js +5 -0
  135. package/dist/utils/branch_notice.js +22 -0
  136. package/dist/utils/branch_picker.js +103 -0
  137. package/dist/utils/compute_units.js +28 -0
  138. package/dist/utils/enrichers.js +161 -0
  139. package/dist/utils/esbuild.js +158 -0
  140. package/dist/utils/formats.js +18 -0
  141. package/dist/utils/middlewares.js +20 -0
  142. package/dist/utils/package_manager.js +68 -0
  143. package/dist/utils/point_in_time.js +56 -0
  144. package/dist/utils/psql.js +120 -0
  145. package/dist/utils/string.js +5 -0
  146. package/dist/utils/ui.js +59 -0
  147. package/dist/utils/zip.js +4 -0
  148. package/dist/writer.js +97 -0
  149. package/package.json +117 -14
  150. package/.jshintrc +0 -3
  151. package/CHANGELOG.markdown +0 -22
  152. package/LICENSE +0 -21
  153. package/README.markdown +0 -76
  154. package/bower.json +0 -23
  155. package/license.txt +0 -9
  156. package/neon.js +0 -234
  157. package/stdlib/bubbling_support.js +0 -32
  158. package/stdlib/custom_event.js +0 -54
  159. package/stdlib/custom_event_support.js +0 -195
  160. package/stdlib/index.js +0 -7
  161. package/stdlib/node_support.js +0 -123
  162. package/stdlib/widget.js +0 -340
  163. package/test/neon_browser.html +0 -11
  164. package/test/neon_stdlib_browser.html +0 -15
  165. package/test/neon_stdlib_test.js +0 -84
  166. package/test/neon_test.js +0 -64
@@ -0,0 +1,481 @@
1
+ import { retryOnLock } from "../api.js";
2
+ import { contextBranch, readContextFile } from "../context.js";
3
+ import { log } from "../log.js";
4
+ import { branchCreateRequest } from "../parameters.gen.js";
5
+ import { EndpointType } from "../utils/api_enums.js";
6
+ import { getComputeUnits } from "../utils/compute_units.js";
7
+ import { branchIdFromProps, branchIdResolve, fillSingleProject, } from "../utils/enrichers.js";
8
+ import { looksLikeBranchId, looksLikeLSN, looksLikeTimestamp, } from "../utils/formats.js";
9
+ import { parsePointInTime } from "../utils/point_in_time.js";
10
+ import { psql } from "../utils/psql.js";
11
+ import { writer } from "../writer.js";
12
+ import { parseSchemaDiffParams, schemaDiff } from "./schema_diff.js";
13
+ export const BRANCH_FIELDS = [
14
+ "name",
15
+ "id",
16
+ "current_state",
17
+ "created_at",
18
+ "expires_at",
19
+ ];
20
+ const BRANCH_FIELDS_RESET = [
21
+ "name",
22
+ "id",
23
+ "default",
24
+ "current_state",
25
+ "created_at",
26
+ "last_reset_at",
27
+ ];
28
+ export const command = "branches";
29
+ export const describe = "Manage branches";
30
+ export const aliases = ["branch"];
31
+ export const builder = (argv) => argv
32
+ .usage("$0 branches <sub-command> [options]")
33
+ .options({
34
+ "project-id": {
35
+ describe: "Project ID",
36
+ type: "string",
37
+ },
38
+ })
39
+ .middleware(fillSingleProject)
40
+ .middleware((args) => {
41
+ // Provide alias for analytics
42
+ args.branchId ?? (args.branchId = args.id);
43
+ })
44
+ .command("list", "List branches", (yargs) => yargs, (args) => list(args))
45
+ .command("create", "Create a branch", (yargs) => yargs.options({
46
+ name: branchCreateRequest["branch.name"],
47
+ parent: {
48
+ describe: "Parent branch name or id or timestamp or LSN. Defaults to the default branch",
49
+ type: "string",
50
+ },
51
+ compute: {
52
+ describe: "Create a branch with or without a compute. By default branch is created with a read-write compute. To create a branch without compute use --no-compute",
53
+ type: "boolean",
54
+ default: true,
55
+ },
56
+ type: {
57
+ describe: "Type of compute to add",
58
+ type: "string",
59
+ implies: "compute",
60
+ default: EndpointType.ReadWrite,
61
+ choices: Object.values(EndpointType),
62
+ },
63
+ "suspend-timeout": {
64
+ describe: "Duration of inactivity in seconds after which the compute endpoint is\nautomatically suspended. The value `0` means use the global default.\nThe value `-1` means never suspend. The default value is `300` seconds (5 minutes).\nThe maximum value is `604800` seconds (1 week).",
65
+ type: "number",
66
+ implies: "compute",
67
+ default: 0,
68
+ },
69
+ cu: {
70
+ describe: 'The number of Compute Units. Could be a fixed size (e.g. "2") or a range delimited by a dash (e.g. "0.5-3").',
71
+ type: "string",
72
+ implies: "compute",
73
+ },
74
+ psql: {
75
+ type: "boolean",
76
+ describe: "Connect to a new branch via psql",
77
+ default: false,
78
+ },
79
+ fallback: {
80
+ type: "boolean",
81
+ describe: "Force the embedded TypeScript psql fallback (for testing)",
82
+ default: false,
83
+ hidden: true,
84
+ },
85
+ annotation: {
86
+ type: "string",
87
+ hidden: true,
88
+ default: "{}",
89
+ },
90
+ "schema-only": {
91
+ describe: "Create a schema-only branch. Requires exactly one read-write compute.",
92
+ type: "boolean",
93
+ default: false,
94
+ },
95
+ "expires-at": {
96
+ describe: "Set an expiration date for the branch. Accepts a date string (e.g., 2024-12-31T23:59:59Z).",
97
+ type: "string",
98
+ requiresArg: true,
99
+ },
100
+ }), (args) => create(args))
101
+ .command("reset <id|name>", "Reset a branch", (yargs) => yargs.options({
102
+ parent: {
103
+ describe: "Reset to a parent branch",
104
+ type: "boolean",
105
+ default: false,
106
+ },
107
+ "preserve-under-name": {
108
+ describe: "Name under which to preserve the old branch",
109
+ },
110
+ }), (args) => reset(args))
111
+ .command("restore <target-id|name> <source>[@(timestamp|lsn)]", "Restores a branch to a specific point in time\n<source> can be: ^self, ^parent, or <source-branch-id|name>", (yargs) => yargs
112
+ // we want to show meaningful help for the command
113
+ // but it makes yargs to fail on parsing the command
114
+ // so we need to fill in the missing args manually
115
+ .middleware((args) => {
116
+ args.id = args.targetId;
117
+ args.pointInTime = args["source@(timestamp"];
118
+ args.branchId = args.id; // for analytics
119
+ })
120
+ .usage("$0 branches restore <target-id|name> <source>[@(timestamp|lsn)]")
121
+ .options({
122
+ "preserve-under-name": {
123
+ describe: "Name under which to preserve the old branch",
124
+ },
125
+ })
126
+ .example([
127
+ [
128
+ "$0 branches restore main br-source-branch-123456",
129
+ "Restores main to the head of the branch with id br-source-branch-123456",
130
+ ],
131
+ [
132
+ "$0 branches restore main source@2021-01-01T00:00:00Z",
133
+ "Restores main to the timestamp 2021-01-01T00:00:00Z of the source branch",
134
+ ],
135
+ [
136
+ "$0 branches restore my-branch ^self@0/123456",
137
+ "Restores my-branch to the LSN 0/123456 from its own history",
138
+ ],
139
+ [
140
+ "$0 branches restore my-branch ^parent",
141
+ "Restore my-branch to the head of its parent branch",
142
+ ],
143
+ ]), (args) => restore(args))
144
+ .command("rename <id|name> <new-name>", "Rename a branch", (yargs) => yargs, (args) => rename(args))
145
+ .command("set-default <id|name>", "Set a branch as default", (yargs) => yargs, (args) => setDefault(args))
146
+ .command({
147
+ command: "set-expiration <id|name>",
148
+ describe: "Set an expiration date for the branch",
149
+ builder: (yargs) => yargs.options({
150
+ "expires-at": {
151
+ describe: "Set a expiration date for the branch. If omitted, expiration will be removed. Format [RFC3339]: 2024-12-31T23:59:59Z",
152
+ type: "string",
153
+ requiresArg: false,
154
+ },
155
+ }),
156
+ handler: (args) => setExpiration(args),
157
+ })
158
+ .command("add-compute <id|name>", "Add a compute to a branch", (yargs) => yargs.options({
159
+ type: {
160
+ type: "string",
161
+ choices: Object.values(EndpointType),
162
+ describe: "Type of compute to add",
163
+ default: EndpointType.ReadOnly,
164
+ },
165
+ cu: {
166
+ describe: 'The number of Compute Units. Could be a fixed size (e.g. "2") or a range delimited by a dash (e.g. "0.5-3").',
167
+ type: "string",
168
+ },
169
+ name: {
170
+ type: "string",
171
+ describe: "Optional name of the compute",
172
+ },
173
+ }), (args) => addCompute(args))
174
+ .command("delete <id|name>", "Delete a branch", (yargs) => yargs, (args) => deleteBranch(args))
175
+ .command("get <id|name>", "Get a branch", (yargs) => yargs, (args) => get(args))
176
+ .command({
177
+ command: "schema-diff [base-branch] [compare-source[@(timestamp|lsn)]]",
178
+ aliases: ["sd"],
179
+ describe: "Compare the latest schemas of any two branches, or compare a branch to its own or another branch's history.",
180
+ builder: (yargs) => {
181
+ return yargs
182
+ .middleware((args) => (args.compareSource =
183
+ args["compare-source@(timestamp"]))
184
+ .middleware(parseSchemaDiffParams)
185
+ .options({
186
+ database: {
187
+ alias: "db",
188
+ type: "string",
189
+ description: "Name of the database for which the schema comparison is performed",
190
+ },
191
+ })
192
+ .example([
193
+ [
194
+ "$0 branches schema-diff main br-compare-branch-123456",
195
+ "Compares the main branch to the head of the branch with ID br-compare-branch-123456",
196
+ ],
197
+ [
198
+ "$0 branches schema-diff main compare@2024-06-01T00:00:00Z",
199
+ "Compares the main branch to the state of the compare branch at timestamp 2024-06-01T00:00:00.000Z",
200
+ ],
201
+ [
202
+ "$0 branches schema-diff my-branch ^self@0/123456",
203
+ "Compares my-branch to LSN 0/123456 from its own history",
204
+ ],
205
+ [
206
+ "$0 branches schema-diff my-branch ^parent",
207
+ "Compares my-branch to the head of its parent branch",
208
+ ],
209
+ [
210
+ "$0 branches schema-diff",
211
+ "If a branch is specified in 'set-context', compares this branch to its parent. Otherwise, compares the default branch to its parent.",
212
+ ],
213
+ ]);
214
+ },
215
+ handler: (args) => schemaDiff(args),
216
+ });
217
+ export const handler = (args) => {
218
+ return args;
219
+ };
220
+ const list = async (props) => {
221
+ const { data: { branches, annotations }, } = await props.apiClient.listProjectBranches({
222
+ projectId: props.projectId,
223
+ });
224
+ // The branch pinned in the local context (.neon), so we can flag it as `[current]` — the
225
+ // one commands target by default and that `neonctl env pull` would read. The context
226
+ // stores the branch by name (preferred) or id, so match against either.
227
+ const currentBranch = contextBranch(readContextFile(props.contextFile));
228
+ writer(props).end(branches, {
229
+ fields: BRANCH_FIELDS,
230
+ renderColumns: {
231
+ expires_at: (br) => br.expires_at || "never",
232
+ // Word labels (not symbols) so they read clearly and match the existing `[anon]`.
233
+ name: (br) => {
234
+ const annotation = annotations[br.id];
235
+ const isAnon = annotation?.value.anonymized;
236
+ const labels = [];
237
+ if (br.default) {
238
+ labels.push("[default]");
239
+ }
240
+ if (br.protected) {
241
+ labels.push("[protected]");
242
+ }
243
+ if (isAnon) {
244
+ labels.push("[anon]");
245
+ }
246
+ if (currentBranch !== undefined &&
247
+ (br.id === currentBranch || br.name === currentBranch)) {
248
+ labels.push("[current]");
249
+ }
250
+ labels.push(br.name);
251
+ return labels.join(" ");
252
+ },
253
+ },
254
+ });
255
+ };
256
+ const create = async (props) => {
257
+ const branches = await props.apiClient
258
+ .listProjectBranches({ projectId: props.projectId })
259
+ .then(({ data }) => data.branches);
260
+ const parentProps = (() => {
261
+ if (!props.parent) {
262
+ const branch = branches.find((b) => b.default);
263
+ if (!branch) {
264
+ throw new Error("No default branch found");
265
+ }
266
+ return { parent_id: branch.id };
267
+ }
268
+ if (looksLikeLSN(props.parent)) {
269
+ return { parent_lsn: props.parent };
270
+ }
271
+ if (looksLikeTimestamp(props.parent)) {
272
+ return { parent_timestamp: props.parent };
273
+ }
274
+ if (looksLikeBranchId(props.parent)) {
275
+ return { parent_id: props.parent };
276
+ }
277
+ const branch = branches.find((b) => b.name === props.parent);
278
+ if (!branch) {
279
+ throw new Error(`Branch ${props.parent} not found`);
280
+ }
281
+ return { parent_id: branch.id };
282
+ })();
283
+ // Validate schema-only branch requirements
284
+ if (props.schemaOnly) {
285
+ if (!props.compute) {
286
+ throw new Error("Schema-only branches require a compute endpoint");
287
+ }
288
+ if (props.type !== EndpointType.ReadWrite) {
289
+ throw new Error("Schema-only branches require a read-write compute endpoint");
290
+ }
291
+ }
292
+ const { data } = await retryOnLock(() => props.apiClient.createProjectBranch(props.projectId, {
293
+ branch: {
294
+ name: props.name,
295
+ ...parentProps,
296
+ ...(props.schemaOnly ? { init_source: "schema-only" } : {}),
297
+ ...(props["expires-at"]
298
+ ? {
299
+ expires_at: new Date(props["expires-at"]).toISOString(),
300
+ }
301
+ : {}),
302
+ },
303
+ endpoints: props.compute
304
+ ? [
305
+ {
306
+ type: props.type,
307
+ suspend_timeout_seconds: props.suspendTimeout === 0
308
+ ? undefined
309
+ : props.suspendTimeout,
310
+ ...(props.cu
311
+ ? getComputeUnits(props.cu)
312
+ : undefined),
313
+ },
314
+ ]
315
+ : [],
316
+ annotation_value: props.annotation
317
+ ? JSON.parse(props.annotation)
318
+ : undefined,
319
+ }));
320
+ const parent = branches.find((b) => b.id === data.branch.parent_id);
321
+ if (parent?.protected) {
322
+ log.warning("The parent branch is protected; a unique role password has been generated for the new branch.");
323
+ }
324
+ const out = writer(props);
325
+ out.write(data.branch, {
326
+ fields: BRANCH_FIELDS,
327
+ title: "branch",
328
+ emptyMessage: "No branches have been found.",
329
+ });
330
+ if (data.endpoints?.length > 0) {
331
+ out.write(data.endpoints, {
332
+ fields: ["id", "created_at"],
333
+ title: "endpoints",
334
+ emptyMessage: "No endpoints have been found.",
335
+ });
336
+ }
337
+ if (data.connection_uris?.length) {
338
+ out.write(data.connection_uris, {
339
+ fields: ["connection_uri"],
340
+ title: "connection_uris",
341
+ emptyMessage: "No connection uris have been found",
342
+ });
343
+ }
344
+ out.end();
345
+ if (props.psql) {
346
+ if (!data.connection_uris?.length) {
347
+ throw new Error(`Branch ${data.branch.id} doesn't have a connection uri`);
348
+ }
349
+ const connection_uri = data.connection_uris[0].connection_uri;
350
+ const psqlArgs = props["--"];
351
+ await psql(connection_uri, psqlArgs, {
352
+ mode: props.fallback ? "ts" : "auto",
353
+ });
354
+ }
355
+ };
356
+ const rename = async (props) => {
357
+ const branchId = await branchIdFromProps(props);
358
+ const { data } = await retryOnLock(() => props.apiClient.updateProjectBranch(props.projectId, branchId, {
359
+ branch: {
360
+ name: props.newName,
361
+ },
362
+ }));
363
+ writer(props).end(data.branch, {
364
+ fields: BRANCH_FIELDS,
365
+ });
366
+ };
367
+ const setDefault = async (props) => {
368
+ const branchId = await branchIdFromProps(props);
369
+ const { data } = await retryOnLock(() => props.apiClient.setDefaultProjectBranch(props.projectId, branchId));
370
+ writer(props).end(data.branch, {
371
+ fields: BRANCH_FIELDS,
372
+ });
373
+ };
374
+ const deleteBranch = async (props) => {
375
+ const branchId = await branchIdFromProps(props);
376
+ const { data } = await retryOnLock(() => props.apiClient.deleteProjectBranch(props.projectId, branchId));
377
+ // A 204 (branch already gone) carries no body; only a 200 returns it.
378
+ if (data) {
379
+ writer(props).end(data.branch, {
380
+ fields: BRANCH_FIELDS,
381
+ });
382
+ }
383
+ };
384
+ const get = async (props) => {
385
+ const branchId = await branchIdFromProps(props);
386
+ const { data } = await props.apiClient.getProjectBranch(props.projectId, branchId);
387
+ writer(props).end(data.branch, {
388
+ fields: BRANCH_FIELDS,
389
+ });
390
+ };
391
+ const addCompute = async (props) => {
392
+ const branchId = await branchIdFromProps(props);
393
+ const computeName = props.name ? { name: props.name } : null;
394
+ const { data } = await retryOnLock(() => props.apiClient.createProjectEndpoint(props.projectId, {
395
+ endpoint: {
396
+ branch_id: branchId,
397
+ type: props.type,
398
+ ...(props.cu ? getComputeUnits(props.cu) : undefined),
399
+ ...computeName,
400
+ },
401
+ }));
402
+ writer(props).end(data.endpoint, {
403
+ fields: ["id", "host"],
404
+ });
405
+ };
406
+ const reset = async (props) => {
407
+ if (!props.parent) {
408
+ throw new Error("Only resetting to parent is supported for now");
409
+ }
410
+ const branchId = await branchIdFromProps(props);
411
+ const { data: { branch: { parent_id }, }, } = await props.apiClient.getProjectBranch(props.projectId, branchId);
412
+ if (!parent_id) {
413
+ throw new Error("Branch has no parent");
414
+ }
415
+ const { data } = await retryOnLock(() => props.apiClient.restoreProjectBranch(props.projectId, branchId, {
416
+ source_branch_id: parent_id,
417
+ preserve_under_name: props.preserveUnderName || undefined,
418
+ }));
419
+ writer(props).end(data.branch, {
420
+ // need to reset types until we expose reset api
421
+ fields: BRANCH_FIELDS_RESET,
422
+ });
423
+ };
424
+ const restore = async (props) => {
425
+ const targetBranchId = await branchIdResolve({
426
+ branch: props.id,
427
+ projectId: props.projectId,
428
+ apiClient: props.apiClient,
429
+ });
430
+ const pointInTime = await parsePointInTime({
431
+ pointInTime: props.pointInTime,
432
+ targetBranchId,
433
+ projectId: props.projectId,
434
+ api: props.apiClient,
435
+ });
436
+ log.info(`Restoring branch ${targetBranchId} to the branch ${pointInTime.branchId} ${(pointInTime.tag === "lsn" && "LSN " + pointInTime.lsn) ||
437
+ (pointInTime.tag === "timestamp" &&
438
+ "timestamp " + pointInTime.timestamp) ||
439
+ "head"}`);
440
+ const { data } = await retryOnLock(() => props.apiClient.restoreProjectBranch(props.projectId, targetBranchId, {
441
+ source_branch_id: pointInTime.branchId,
442
+ preserve_under_name: props.preserveUnderName || undefined,
443
+ ...(pointInTime.tag === "lsn" && { source_lsn: pointInTime.lsn }),
444
+ ...(pointInTime.tag === "timestamp" && {
445
+ source_timestamp: pointInTime.timestamp,
446
+ }),
447
+ }));
448
+ const writeInst = writer(props).write(data.branch, {
449
+ title: "Restored branch",
450
+ fields: ["id", "name", "last_reset_at"],
451
+ emptyMessage: "No branches have been restored.",
452
+ });
453
+ const parentId = data.branch.parent_id;
454
+ if (props.preserveUnderName && parentId) {
455
+ const { data } = await props.apiClient.getProjectBranch(props.projectId, parentId);
456
+ writeInst.write(data.branch, {
457
+ title: "Backup branch",
458
+ fields: ["id", "name"],
459
+ emptyMessage: "Backup branch has not been found.",
460
+ });
461
+ }
462
+ writeInst.end();
463
+ };
464
+ const setExpiration = async (props) => {
465
+ // Accept either branch name or id
466
+ const branchId = await branchIdFromProps({
467
+ ...props,
468
+ id: props.branchId,
469
+ });
470
+ const expiresAt = typeof props.expiresAt === "string"
471
+ ? new Date(props.expiresAt).toISOString()
472
+ : null;
473
+ const { data } = await retryOnLock(() => props.apiClient.updateProjectBranch(props.projectId, branchId, {
474
+ branch: {
475
+ expires_at: expiresAt,
476
+ },
477
+ }));
478
+ writer(props).end(data.branch, {
479
+ fields: BRANCH_FIELDS,
480
+ });
481
+ };