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,515 @@
1
+ /**
2
+ * psql backslash-command argument scanner.
3
+ *
4
+ * Hand-port of PostgreSQL's `src/bin/psql/psqlscanslash.l`. The upstream is a
5
+ * flex-generated state machine with these exclusive states:
6
+ *
7
+ * - `xslashcmd` — reading the command name (the letters after `\`)
8
+ * - `xslashargstart` — skipping whitespace before the next arg; `|` at
9
+ * this position is special in `filepipe` mode
10
+ * - `xslasharg` — reading an unquoted arg (handles `:var`,
11
+ * `:'var'`, `:"var"` substitutions and the start of
12
+ * `'`, `"`, `` ` `` quoted runs)
13
+ * - `xslashquote` — inside `'…'` (C-string-style escapes processed)
14
+ * - `xslashbackquote` — inside `` `…` `` (variable expansion only; the
15
+ * body is shipped to the shell by upstream)
16
+ * - `xslashdquote` — inside `"…"` (literal copy, double quotes kept)
17
+ * - `xslashwholeline` — slurp rest of line, suppressing leading whitespace
18
+ * - `xslashend` — terminator (we don't model it here; the caller
19
+ * knows where the slash command ended)
20
+ *
21
+ * The TS port collapses these into a single {@link scanSlashArgs} function
22
+ * that takes the post-command-name remainder of the input line plus a
23
+ * {@link SlashArgMode} and returns the list of parsed arguments. We hand-roll
24
+ * the state machine instead of attempting to mechanically translate flex
25
+ * rules; the resulting code is easier to read and trivially testable.
26
+ *
27
+ * Behavioural notes vs upstream:
28
+ *
29
+ * - **Whole-line mode** returns a single-element array containing the entire
30
+ * rest-of-line, with leading whitespace suppressed. Empty input still
31
+ * yields `[]` so callers can treat the result uniformly.
32
+ * - **filepipe mode** treats a leading `|` as the start of a shell command
33
+ * and slurps the rest of the line as one argument. Anything else is
34
+ * handled as a normal arg.
35
+ * - **Variable substitution** matches upstream's three forms:
36
+ * `:varname` — plain expansion
37
+ * `:'varname'` — SQL-literal-quoted expansion
38
+ * `:"varname"` — SQL-identifier-quoted expansion
39
+ * `varname` is `[A-Za-z0-9_\x80-\xff]+` (upstream's `variable_char`). When
40
+ * the variable is unset, the colon form is emitted literally — matching
41
+ * the upstream `ECHO` fallback.
42
+ * - **no-vars mode** disables all `:var` substitution; the lexer emits the
43
+ * raw text. Useful for commands that should never expand variables
44
+ * (e.g. `\setenv`'s value argument).
45
+ * - **sql-id / sql-id-keep-case modes** post-process each arg through
46
+ * `dequoteDowncaseIdentifier`, which mirrors upstream's
47
+ * `dequote_downcase_identifier()`: collapse `"…"` quoting, double `""`
48
+ * into a single `"`, and (for `sql-id`) lowercase unquoted letters.
49
+ * - **Backticks** ARE executed here, synchronously via `child_process.execSync`
50
+ * on `sh -c <body>`. Variable references inside the backticked body are
51
+ * expanded first (matching upstream's `xslashbackquote` rules), then the
52
+ * resulting command is run with the inherited environment but NO shell
53
+ * state; the child's stdout (trimmed of one trailing newline) is the
54
+ * arg's value. Non-zero exits / spawn failures are reported on stderr
55
+ * in the upstream `psql:...: error: \!:` shape and substitute the empty
56
+ * string. This is the scanner-level analogue of upstream's `evaluate_backtick`.
57
+ * - **Inside-quote escapes** match upstream `xslashquote`: `\n \t \b \r \f`,
58
+ * octal `\ooo`, hex `\xhh`, and `\<other>` as a literal character. We
59
+ * apply them in-line so the returned arg contains the decoded value.
60
+ */
61
+ import { execSync } from "node:child_process";
62
+ import { dequote } from "./stringutils.js";
63
+ const WHITESPACE = " \t\n\r\f\v";
64
+ const VARIABLE_CHAR_RE = /[A-Za-z0-9_\x80-\xff]/;
65
+ const isVarChar = (c) => c !== undefined && VARIABLE_CHAR_RE.test(c);
66
+ const isWhitespace = (c) => c !== undefined && WHITESPACE.includes(c);
67
+ /**
68
+ * SQL-literal-quote a value for the `:'varname'` substitution form.
69
+ * Mirrors libpq's `PQescapeLiteral` for the common case: wrap in `'…'`,
70
+ * double any embedded `'`, and backslash-escape any embedded `\`. Upstream
71
+ * additionally emits an `E` prefix when the value contains backslashes; we
72
+ * preserve that behaviour for compatibility with code that round-trips
73
+ * through the SQL parser.
74
+ */
75
+ const quoteSqlLiteral = (value) => {
76
+ let needsEscape = false;
77
+ let inner = "";
78
+ for (const c of value) {
79
+ if (c === "'")
80
+ inner += "''";
81
+ else if (c === "\\") {
82
+ inner += "\\\\";
83
+ needsEscape = true;
84
+ }
85
+ else {
86
+ inner += c;
87
+ }
88
+ }
89
+ return needsEscape ? `E'${inner}'` : `'${inner}'`;
90
+ };
91
+ /**
92
+ * SQL-identifier-quote a value for the `:"varname"` substitution form.
93
+ * Wraps the value in `"…"` and doubles any embedded `"`.
94
+ */
95
+ const quoteSqlIdent = (value) => {
96
+ let inner = "";
97
+ for (const c of value) {
98
+ inner += c === '"' ? '""' : c;
99
+ }
100
+ return `"${inner}"`;
101
+ };
102
+ /**
103
+ * Match upstream's `dequote_downcase_identifier()`. Strips out `"…"` quoting
104
+ * (collapsing `""` to `"` inside quotes) and optionally downcases unquoted
105
+ * letters. The transformation is in-place semantically: a string like
106
+ * `FOO"BAR"BAZ` becomes `fooBARbaz` (when `downcase`) or `FOOBARBAZ`
107
+ * (otherwise).
108
+ */
109
+ const dequoteDowncaseIdentifier = (str, downcase) => {
110
+ let out = "";
111
+ let inquotes = false;
112
+ let i = 0;
113
+ while (i < str.length) {
114
+ const c = str[i];
115
+ if (c === '"') {
116
+ if (inquotes && str[i + 1] === '"') {
117
+ // Keep one quote, drop the other.
118
+ out += '"';
119
+ i += 2;
120
+ continue;
121
+ }
122
+ inquotes = !inquotes;
123
+ i++;
124
+ continue;
125
+ }
126
+ out += downcase && !inquotes ? c.toLowerCase() : c;
127
+ i++;
128
+ }
129
+ return out;
130
+ };
131
+ /**
132
+ * Attempt to consume one of the `:var`, `:'var'`, `:"var"` variable
133
+ * substitution forms at position `i` in `s`. Returns the new index plus the
134
+ * substituted text, or `null` if no recognised form is present.
135
+ *
136
+ * Caller controls whether the colon forms are honoured at all via
137
+ * `varLookup`: pass `undefined` to disable substitution entirely (`no-vars`
138
+ * mode).
139
+ */
140
+ const tryConsumeVarSubstitution = (s, i, varLookup) => {
141
+ if (varLookup === undefined)
142
+ return null;
143
+ if (s[i] !== ":")
144
+ return null;
145
+ // :{?varname} — defined-variable test, emits literal TRUE / FALSE.
146
+ // Mirrors upstream `psqlscanslash.l`'s `:\{\?{variable_char}+\}` rule
147
+ // (calls `psqlscan_test_variable`). A malformed expression (missing
148
+ // closing `}` or empty name) falls through to `null` so the caller emits
149
+ // the literal `:` and continues.
150
+ if (s[i + 1] === "{" && s[i + 2] === "?") {
151
+ let j = i + 3;
152
+ while (j < s.length && isVarChar(s[j]))
153
+ j++;
154
+ if (j > i + 3 && s[j] === "}") {
155
+ const name = s.slice(i + 3, j);
156
+ const value = varLookup(name);
157
+ return { end: j + 1, text: value !== undefined ? "TRUE" : "FALSE" };
158
+ }
159
+ return null;
160
+ }
161
+ // :"varname" — SQL identifier quote
162
+ if (s[i + 1] === '"') {
163
+ let j = i + 2;
164
+ while (j < s.length && isVarChar(s[j]))
165
+ j++;
166
+ if (j > i + 2 && s[j] === '"') {
167
+ const name = s.slice(i + 2, j);
168
+ const value = varLookup(name);
169
+ if (value === undefined) {
170
+ // Upstream still substitutes — passing an empty string would quietly
171
+ // misparse downstream. We instead pass through the literal so the
172
+ // caller can see (and report) the unset reference. This matches the
173
+ // ECHO fallback used by upstream's plain `:varname` form.
174
+ return { end: j + 1, text: s.slice(i, j + 1) };
175
+ }
176
+ return { end: j + 1, text: quoteSqlIdent(value) };
177
+ }
178
+ return null;
179
+ }
180
+ // :'varname' — SQL literal quote
181
+ if (s[i + 1] === "'") {
182
+ let j = i + 2;
183
+ while (j < s.length && isVarChar(s[j]))
184
+ j++;
185
+ if (j > i + 2 && s[j] === "'") {
186
+ const name = s.slice(i + 2, j);
187
+ const value = varLookup(name);
188
+ if (value === undefined) {
189
+ return { end: j + 1, text: s.slice(i, j + 1) };
190
+ }
191
+ return { end: j + 1, text: quoteSqlLiteral(value) };
192
+ }
193
+ return null;
194
+ }
195
+ // :varname — plain substitution
196
+ if (isVarChar(s[i + 1])) {
197
+ let j = i + 1;
198
+ while (j < s.length && isVarChar(s[j]))
199
+ j++;
200
+ const name = s.slice(i + 1, j);
201
+ const value = varLookup(name);
202
+ if (value === undefined) {
203
+ // Unset → emit literally so it stays visible. Upstream ECHOes the
204
+ // entire `:name` text in this case.
205
+ return { end: j, text: s.slice(i, j) };
206
+ }
207
+ return { end: j, text: value };
208
+ }
209
+ return null;
210
+ };
211
+ /**
212
+ * Process the contents of a `'…'` slash-quoted token: handle psql's C-style
213
+ * escapes (\n, \t, \b, \r, \f, octal, hex, and \<other>) and undouble `''`.
214
+ * The opening quote has already been consumed; we read until the matching
215
+ * closing quote and return the decoded payload plus the new index (pointing
216
+ * just past the closing quote).
217
+ */
218
+ const consumeSingleQuoted = (s, start) => {
219
+ let out = "";
220
+ let i = start;
221
+ while (i < s.length) {
222
+ const c = s[i];
223
+ if (c === "'") {
224
+ if (s[i + 1] === "'") {
225
+ out += "'";
226
+ i += 2;
227
+ continue;
228
+ }
229
+ return { end: i + 1, text: out };
230
+ }
231
+ if (c === "\\" && i + 1 < s.length) {
232
+ const next = s[i + 1];
233
+ if (next === "n") {
234
+ out += "\n";
235
+ i += 2;
236
+ continue;
237
+ }
238
+ if (next === "t") {
239
+ out += "\t";
240
+ i += 2;
241
+ continue;
242
+ }
243
+ if (next === "b") {
244
+ out += "\b";
245
+ i += 2;
246
+ continue;
247
+ }
248
+ if (next === "r") {
249
+ out += "\r";
250
+ i += 2;
251
+ continue;
252
+ }
253
+ if (next === "f") {
254
+ out += "\f";
255
+ i += 2;
256
+ continue;
257
+ }
258
+ // Octal: \ooo (1–3 digits)
259
+ if (next >= "0" && next <= "7") {
260
+ const j = i + 1;
261
+ let octEnd = j;
262
+ while (octEnd < s.length &&
263
+ octEnd - j < 3 &&
264
+ s[octEnd] >= "0" &&
265
+ s[octEnd] <= "7") {
266
+ octEnd++;
267
+ }
268
+ const code = parseInt(s.slice(j, octEnd), 8);
269
+ out += String.fromCharCode(code);
270
+ i = octEnd;
271
+ continue;
272
+ }
273
+ // Hex: \xhh (1–2 digits)
274
+ if (next === "x") {
275
+ const j = i + 2;
276
+ const hexRe = /[0-9a-fA-F]/;
277
+ let hexEnd = j;
278
+ while (hexEnd < s.length &&
279
+ hexEnd - j < 2 &&
280
+ hexRe.test(s[hexEnd])) {
281
+ hexEnd++;
282
+ }
283
+ if (hexEnd > j) {
284
+ const code = parseInt(s.slice(j, hexEnd), 16);
285
+ out += String.fromCharCode(code);
286
+ i = hexEnd;
287
+ continue;
288
+ }
289
+ }
290
+ // \<other> → literal next char
291
+ out += next;
292
+ i += 2;
293
+ continue;
294
+ }
295
+ out += c;
296
+ i++;
297
+ }
298
+ // Unterminated — return what we have. Upstream reports an error; for the
299
+ // scanner-as-library shape we'd rather surface the partial text and let
300
+ // the caller decide. Tests cover both well-formed and unterminated cases.
301
+ return { end: i, text: out };
302
+ };
303
+ /**
304
+ * Process the contents of a `"…"` slash-quoted token. Upstream copies the
305
+ * body verbatim *including the double quotes themselves* (see `xslashdquote`
306
+ * rule, which ECHOes the opening dquote on entry). That preserves
307
+ * SQL-identifier semantics — the caller's `dequoteDowncaseIdentifier()` is
308
+ * what eventually unwraps the quotes for `sql-id` modes.
309
+ */
310
+ const consumeDoubleQuoted = (s, start) => {
311
+ let i = start;
312
+ while (i < s.length) {
313
+ if (s[i] === '"') {
314
+ return { end: i + 1, text: s.slice(start - 1, i + 1) };
315
+ }
316
+ i++;
317
+ }
318
+ // Unterminated — return what we have, including the opening quote.
319
+ return { end: i, text: s.slice(start - 1, i) };
320
+ };
321
+ /**
322
+ * Test seam for swapping the shell executor. Vitest sets `current` to its
323
+ * own mock; production uses `execSync(cmd, { shell: '/bin/sh' })`. Kept as
324
+ * an exported object so tests can flip it in `beforeEach` without monkey-
325
+ * patching `child_process`.
326
+ */
327
+ export const BACKTICK_EXECUTOR = {
328
+ current: (cmd) => execSync(cmd, {
329
+ shell: "/bin/sh",
330
+ encoding: "utf8",
331
+ // Children inherit the parent env but get no stdin pipe — matches
332
+ // upstream's `popen(cmd, "r")` semantics. stderr passes through so
333
+ // shell error output is visible to the user.
334
+ stdio: ["ignore", "pipe", "inherit"],
335
+ // Defensive cap: backtick output goes into a slash arg, so a runaway
336
+ // command shouldn't be able to fill arbitrary memory.
337
+ maxBuffer: 1 << 20,
338
+ }),
339
+ };
340
+ /**
341
+ * Execute the lexed body of a `` `…` `` token via `sh -c` and return its
342
+ * stdout with one trailing newline stripped (matching shell command-
343
+ * substitution convention). Errors are reported on stderr in the upstream
344
+ * `psql: error: \!: <command>: <message>` shape and substitute the empty
345
+ * string — so a failed backtick never aborts the surrounding slash command.
346
+ *
347
+ * Called only by {@link consumeBackQuoted}; lives at module scope so the
348
+ * scanner stays free of inline I/O and tests can spy on the executor via
349
+ * {@link BACKTICK_EXECUTOR}.
350
+ */
351
+ const runBacktickCommand = (cmd) => {
352
+ if (cmd.length === 0)
353
+ return "";
354
+ try {
355
+ const out = BACKTICK_EXECUTOR.current(cmd);
356
+ // Trim a single trailing newline; preserve interior newlines so multi-line
357
+ // output (e.g. `\set FOO `cat file``) lands as-is.
358
+ return out.endsWith("\n") ? out.slice(0, -1) : out;
359
+ }
360
+ catch (err) {
361
+ const msg = err instanceof Error ? err.message : String(err);
362
+ // Upstream prints `psql:file:line: error: \!: <cmd>: <msg>`. We don't
363
+ // have file/line context in the scanner; emit the prefix verbatim and
364
+ // include the command for diagnosis.
365
+ process.stderr.write(`psql: error: \\!: ${cmd}: ${msg}\n`);
366
+ return "";
367
+ }
368
+ };
369
+ /**
370
+ * Process the contents of a `` `…` `` slash-backquoted token.
371
+ *
372
+ * Phase 1 (this function): consume the body, expanding `:var` references
373
+ * along the way (matching upstream's `xslashbackquote` rules).
374
+ *
375
+ * Phase 2 (delegated to {@link runBacktickCommand}): run the assembled
376
+ * command via `sh -c` and return its stdout.
377
+ *
378
+ * Returns the command's stdout (one trailing `\n` stripped). Unterminated
379
+ * backticks still execute the body so partial input doesn't silently
380
+ * succeed; tests cover both well-formed and unterminated cases.
381
+ */
382
+ const consumeBackQuoted = (s, start, varLookup) => {
383
+ let inner = "";
384
+ let i = start;
385
+ while (i < s.length) {
386
+ const c = s[i];
387
+ if (c === "`") {
388
+ return { end: i + 1, text: runBacktickCommand(inner) };
389
+ }
390
+ const sub = tryConsumeVarSubstitution(s, i, varLookup);
391
+ if (sub !== null) {
392
+ inner += sub.text;
393
+ i = sub.end;
394
+ continue;
395
+ }
396
+ inner += c;
397
+ i++;
398
+ }
399
+ // Unterminated — still run what we accumulated so the user can see the
400
+ // error from `sh` itself rather than silently dropping the command.
401
+ return { end: i, text: runBacktickCommand(inner) };
402
+ };
403
+ /**
404
+ * Lex a single slash-command argument starting at `s[i]`. Returns the parsed
405
+ * argument text and the index just past it, or `null` if no argument is
406
+ * available before end of input.
407
+ */
408
+ const scanOneArg = (s, i, mode, varLookup) => {
409
+ // Skip leading whitespace (xslashargstart).
410
+ while (i < s.length && isWhitespace(s[i]))
411
+ i++;
412
+ if (i >= s.length)
413
+ return null;
414
+ // filepipe special: a leading `|` flips into whole-line mode for this arg.
415
+ if (mode === "filepipe" && s[i] === "|") {
416
+ const rest = s.slice(i);
417
+ return { end: s.length, arg: rest };
418
+ }
419
+ // Accumulate the argument piece by piece. Each iteration consumes either:
420
+ // - a single-quoted run
421
+ // - a double-quoted run
422
+ // - a backticked run
423
+ // - a :var / :'var' / :"var" substitution
424
+ // - a literal character (the catch-all)
425
+ // We stop on whitespace or `\` (which begins the next slash command).
426
+ let out = "";
427
+ while (i < s.length) {
428
+ const c = s[i];
429
+ if (isWhitespace(c))
430
+ break;
431
+ if (c === "\\")
432
+ break;
433
+ if (c === "'") {
434
+ const r = consumeSingleQuoted(s, i + 1);
435
+ out += r.text;
436
+ i = r.end;
437
+ continue;
438
+ }
439
+ if (c === '"') {
440
+ const r = consumeDoubleQuoted(s, i + 1);
441
+ out += r.text;
442
+ i = r.end;
443
+ continue;
444
+ }
445
+ if (c === "`") {
446
+ const r = consumeBackQuoted(s, i + 1, varLookup);
447
+ out += r.text;
448
+ i = r.end;
449
+ continue;
450
+ }
451
+ const sub = tryConsumeVarSubstitution(s, i, varLookup);
452
+ if (sub !== null) {
453
+ out += sub.text;
454
+ i = sub.end;
455
+ continue;
456
+ }
457
+ out += c;
458
+ i++;
459
+ }
460
+ return { end: i, arg: out };
461
+ };
462
+ /**
463
+ * Scan the argument portion of a backslash command.
464
+ *
465
+ * @param input the rest of the input line *after* the command name (e.g.
466
+ * `" foo 'bar baz'"` for `\echo foo 'bar baz'`)
467
+ * @param mode argument processing mode — see {@link SlashArgMode}
468
+ * @param varLookup callback that resolves `:varname` references. Omit (or
469
+ * pass `undefined`) for `no-vars` mode behaviour even when
470
+ * `mode !== 'no-vars'`.
471
+ *
472
+ * @returns array of parsed argument strings; empty input yields `[]`.
473
+ */
474
+ export const scanSlashArgs = (input, mode, varLookup) => {
475
+ // Whole-line: return everything, with leading whitespace suppressed and a
476
+ // single trailing newline (if any) preserved verbatim. Empty (or
477
+ // whitespace-only) input yields no args.
478
+ if (mode === "whole-line") {
479
+ let start = 0;
480
+ while (start < input.length && isWhitespace(input[start]))
481
+ start++;
482
+ if (start >= input.length)
483
+ return [];
484
+ return [input.slice(start)];
485
+ }
486
+ const effectiveLookup = mode === "no-vars" ? undefined : varLookup;
487
+ const args = [];
488
+ let i = 0;
489
+ while (i < input.length) {
490
+ const result = scanOneArg(input, i, mode, effectiveLookup);
491
+ if (result === null)
492
+ break;
493
+ let arg = result.arg;
494
+ // sql-id / sql-id-keep-case post-process: collapse SQL-identifier
495
+ // quoting, optionally downcasing unquoted letters.
496
+ if (mode === "sql-id") {
497
+ arg = dequoteDowncaseIdentifier(arg, true);
498
+ }
499
+ else if (mode === "sql-id-keep-case") {
500
+ arg = dequoteDowncaseIdentifier(arg, false);
501
+ }
502
+ args.push(arg);
503
+ i = result.end;
504
+ // Consume the inter-arg whitespace so the next iteration starts cleanly.
505
+ while (i < input.length && isWhitespace(input[i]))
506
+ i++;
507
+ // Stop on a `\` — start of the next backslash command.
508
+ if (input[i] === "\\")
509
+ break;
510
+ }
511
+ return args;
512
+ };
513
+ // Re-export `dequote` for callers that want to undo `quoteIfNeeded` on
514
+ // scanned args without reaching across modules.
515
+ export { dequote };