burnless 0.1.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.
@@ -0,0 +1,2133 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'node:module';
3
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
4
+ import { dirname as __pathDirname } from 'node:path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __pathDirname(__filename);
8
+
9
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/index.js
10
+ import os from "os";
11
+ import fs from "fs";
12
+
13
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/query.js
14
+ var originCache = /* @__PURE__ */ new Map();
15
+ var originStackCache = /* @__PURE__ */ new Map();
16
+ var originError = /* @__PURE__ */ Symbol("OriginError");
17
+ var CLOSE = {};
18
+ var Query = class extends Promise {
19
+ constructor(strings, args, handler, canceller, options = {}) {
20
+ let resolve, reject;
21
+ super((a, b2) => {
22
+ resolve = a;
23
+ reject = b2;
24
+ });
25
+ this.tagged = Array.isArray(strings.raw);
26
+ this.strings = strings;
27
+ this.args = args;
28
+ this.handler = handler;
29
+ this.canceller = canceller;
30
+ this.options = options;
31
+ this.state = null;
32
+ this.statement = null;
33
+ this.resolve = (x) => (this.active = false, resolve(x));
34
+ this.reject = (x) => (this.active = false, reject(x));
35
+ this.active = false;
36
+ this.cancelled = null;
37
+ this.executed = false;
38
+ this.signature = "";
39
+ this[originError] = this.handler.debug ? new Error() : this.tagged && cachedError(this.strings);
40
+ }
41
+ get origin() {
42
+ return (this.handler.debug ? this[originError].stack : this.tagged && originStackCache.has(this.strings) ? originStackCache.get(this.strings) : originStackCache.set(this.strings, this[originError].stack).get(this.strings)) || "";
43
+ }
44
+ static get [Symbol.species]() {
45
+ return Promise;
46
+ }
47
+ cancel() {
48
+ return this.canceller && (this.canceller(this), this.canceller = null);
49
+ }
50
+ simple() {
51
+ this.options.simple = true;
52
+ this.options.prepare = false;
53
+ return this;
54
+ }
55
+ async readable() {
56
+ this.simple();
57
+ this.streaming = true;
58
+ return this;
59
+ }
60
+ async writable() {
61
+ this.simple();
62
+ this.streaming = true;
63
+ return this;
64
+ }
65
+ cursor(rows = 1, fn) {
66
+ this.options.simple = false;
67
+ if (typeof rows === "function") {
68
+ fn = rows;
69
+ rows = 1;
70
+ }
71
+ this.cursorRows = rows;
72
+ if (typeof fn === "function")
73
+ return this.cursorFn = fn, this;
74
+ let prev;
75
+ return {
76
+ [Symbol.asyncIterator]: () => ({
77
+ next: () => {
78
+ if (this.executed && !this.active)
79
+ return { done: true };
80
+ prev && prev();
81
+ const promise = new Promise((resolve, reject) => {
82
+ this.cursorFn = (value) => {
83
+ resolve({ value, done: false });
84
+ return new Promise((r) => prev = r);
85
+ };
86
+ this.resolve = () => (this.active = false, resolve({ done: true }));
87
+ this.reject = (x) => (this.active = false, reject(x));
88
+ });
89
+ this.execute();
90
+ return promise;
91
+ },
92
+ return() {
93
+ prev && prev(CLOSE);
94
+ return { done: true };
95
+ }
96
+ })
97
+ };
98
+ }
99
+ describe() {
100
+ this.options.simple = false;
101
+ this.onlyDescribe = this.options.prepare = true;
102
+ return this;
103
+ }
104
+ stream() {
105
+ throw new Error(".stream has been renamed to .forEach");
106
+ }
107
+ forEach(fn) {
108
+ this.forEachFn = fn;
109
+ this.handle();
110
+ return this;
111
+ }
112
+ raw() {
113
+ this.isRaw = true;
114
+ return this;
115
+ }
116
+ values() {
117
+ this.isRaw = "values";
118
+ return this;
119
+ }
120
+ async handle() {
121
+ !this.executed && (this.executed = true) && await 1 && this.handler(this);
122
+ }
123
+ execute() {
124
+ this.handle();
125
+ return this;
126
+ }
127
+ then() {
128
+ this.handle();
129
+ return super.then.apply(this, arguments);
130
+ }
131
+ catch() {
132
+ this.handle();
133
+ return super.catch.apply(this, arguments);
134
+ }
135
+ finally() {
136
+ this.handle();
137
+ return super.finally.apply(this, arguments);
138
+ }
139
+ };
140
+ function cachedError(xs) {
141
+ if (originCache.has(xs))
142
+ return originCache.get(xs);
143
+ const x = Error.stackTraceLimit;
144
+ Error.stackTraceLimit = 4;
145
+ originCache.set(xs, new Error());
146
+ Error.stackTraceLimit = x;
147
+ return originCache.get(xs);
148
+ }
149
+
150
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/errors.js
151
+ var PostgresError = class extends Error {
152
+ constructor(x) {
153
+ super(x.message);
154
+ this.name = this.constructor.name;
155
+ Object.assign(this, x);
156
+ }
157
+ };
158
+ var Errors = {
159
+ connection,
160
+ postgres,
161
+ generic,
162
+ notSupported
163
+ };
164
+ function connection(x, options, socket) {
165
+ const { host, port } = socket || options;
166
+ const error = Object.assign(
167
+ new Error("write " + x + " " + (options.path || host + ":" + port)),
168
+ {
169
+ code: x,
170
+ errno: x,
171
+ address: options.path || host
172
+ },
173
+ options.path ? {} : { port }
174
+ );
175
+ Error.captureStackTrace(error, connection);
176
+ return error;
177
+ }
178
+ function postgres(x) {
179
+ const error = new PostgresError(x);
180
+ Error.captureStackTrace(error, postgres);
181
+ return error;
182
+ }
183
+ function generic(code, message) {
184
+ const error = Object.assign(new Error(code + ": " + message), { code });
185
+ Error.captureStackTrace(error, generic);
186
+ return error;
187
+ }
188
+ function notSupported(x) {
189
+ const error = Object.assign(
190
+ new Error(x + " (B) is not supported"),
191
+ {
192
+ code: "MESSAGE_NOT_SUPPORTED",
193
+ name: x
194
+ }
195
+ );
196
+ Error.captureStackTrace(error, notSupported);
197
+ return error;
198
+ }
199
+
200
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/types.js
201
+ var types = {
202
+ string: {
203
+ to: 25,
204
+ from: null,
205
+ // defaults to string
206
+ serialize: (x) => "" + x
207
+ },
208
+ number: {
209
+ to: 0,
210
+ from: [21, 23, 26, 700, 701],
211
+ serialize: (x) => "" + x,
212
+ parse: (x) => +x
213
+ },
214
+ json: {
215
+ to: 114,
216
+ from: [114, 3802],
217
+ serialize: (x) => JSON.stringify(x),
218
+ parse: (x) => JSON.parse(x)
219
+ },
220
+ boolean: {
221
+ to: 16,
222
+ from: 16,
223
+ serialize: (x) => x === true ? "t" : "f",
224
+ parse: (x) => x === "t"
225
+ },
226
+ date: {
227
+ to: 1184,
228
+ from: [1082, 1114, 1184],
229
+ serialize: (x) => (x instanceof Date ? x : new Date(x)).toISOString(),
230
+ parse: (x) => new Date(x)
231
+ },
232
+ bytea: {
233
+ to: 17,
234
+ from: 17,
235
+ serialize: (x) => "\\x" + Buffer.from(x).toString("hex"),
236
+ parse: (x) => Buffer.from(x.slice(2), "hex")
237
+ }
238
+ };
239
+ var NotTagged = class {
240
+ then() {
241
+ notTagged();
242
+ }
243
+ catch() {
244
+ notTagged();
245
+ }
246
+ finally() {
247
+ notTagged();
248
+ }
249
+ };
250
+ var Identifier = class extends NotTagged {
251
+ constructor(value) {
252
+ super();
253
+ this.value = escapeIdentifier(value);
254
+ }
255
+ };
256
+ var Parameter = class extends NotTagged {
257
+ constructor(value, type, array) {
258
+ super();
259
+ this.value = value;
260
+ this.type = type;
261
+ this.array = array;
262
+ }
263
+ };
264
+ var Builder = class extends NotTagged {
265
+ constructor(first, rest) {
266
+ super();
267
+ this.first = first;
268
+ this.rest = rest;
269
+ }
270
+ build(before, parameters, types2, options) {
271
+ const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b2) => a.i - b2.i).pop();
272
+ return keyword.i === -1 ? escapeIdentifiers(this.first, options) : keyword.fn(this.first, this.rest, parameters, types2, options);
273
+ }
274
+ };
275
+ function handleValue(x, parameters, types2, options) {
276
+ let value = x instanceof Parameter ? x.value : x;
277
+ if (value === void 0) {
278
+ x instanceof Parameter ? x.value = options.transform.undefined : value = x = options.transform.undefined;
279
+ if (value === void 0)
280
+ throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
281
+ }
282
+ return "$" + types2.push(
283
+ x instanceof Parameter ? (parameters.push(x.value), x.array ? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value) : x.type) : (parameters.push(x), inferType(x))
284
+ );
285
+ }
286
+ var defaultHandlers = typeHandlers(types);
287
+ function stringify(q, string, value, parameters, types2, options) {
288
+ for (let i = 1; i < q.strings.length; i++) {
289
+ string += stringifyValue(string, value, parameters, types2, options) + q.strings[i];
290
+ value = q.args[i];
291
+ }
292
+ return string;
293
+ }
294
+ function stringifyValue(string, value, parameters, types2, o) {
295
+ return value instanceof Builder ? value.build(string, parameters, types2, o) : value instanceof Query ? fragment(value, parameters, types2, o) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x) => acc + " " + fragment(x, parameters, types2, o), "") : handleValue(value, parameters, types2, o);
296
+ }
297
+ function fragment(q, parameters, types2, options) {
298
+ q.fragment = true;
299
+ return stringify(q, q.strings[0], q.args[0], parameters, types2, options);
300
+ }
301
+ function valuesBuilder(first, parameters, types2, columns, options) {
302
+ return first.map(
303
+ (row) => "(" + columns.map(
304
+ (column) => stringifyValue("values", row[column], parameters, types2, options)
305
+ ).join(",") + ")"
306
+ ).join(",");
307
+ }
308
+ function values(first, rest, parameters, types2, options) {
309
+ const multi = Array.isArray(first[0]);
310
+ const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first);
311
+ return valuesBuilder(multi ? first : [first], parameters, types2, columns, options);
312
+ }
313
+ function select(first, rest, parameters, types2, options) {
314
+ typeof first === "string" && (first = [first].concat(rest));
315
+ if (Array.isArray(first))
316
+ return escapeIdentifiers(first, options);
317
+ let value;
318
+ const columns = rest.length ? rest.flat() : Object.keys(first);
319
+ return columns.map((x) => {
320
+ value = first[x];
321
+ return (value instanceof Query ? fragment(value, parameters, types2, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types2, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x);
322
+ }).join(",");
323
+ }
324
+ var builders = Object.entries({
325
+ values,
326
+ in: (...xs) => {
327
+ const x = values(...xs);
328
+ return x === "()" ? "(null)" : x;
329
+ },
330
+ select,
331
+ as: select,
332
+ returning: select,
333
+ "\\(": select,
334
+ update(first, rest, parameters, types2, options) {
335
+ return (rest.length ? rest.flat() : Object.keys(first)).map(
336
+ (x) => escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) + "=" + stringifyValue("values", first[x], parameters, types2, options)
337
+ );
338
+ },
339
+ insert(first, rest, parameters, types2, options) {
340
+ const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first);
341
+ return "(" + escapeIdentifiers(columns, options) + ")values" + valuesBuilder(Array.isArray(first) ? first : [first], parameters, types2, columns, options);
342
+ }
343
+ }).map(([x, fn]) => [new RegExp("((?:^|[\\s(])" + x + "(?:$|[\\s(]))(?![\\s\\S]*\\1)", "i"), fn]);
344
+ function notTagged() {
345
+ throw Errors.generic("NOT_TAGGED_CALL", "Query not called as a tagged template literal");
346
+ }
347
+ var serializers = defaultHandlers.serializers;
348
+ var parsers = defaultHandlers.parsers;
349
+ function firstIsString(x) {
350
+ if (Array.isArray(x))
351
+ return firstIsString(x[0]);
352
+ return typeof x === "string" ? 1009 : 0;
353
+ }
354
+ var mergeUserTypes = function(types2) {
355
+ const user = typeHandlers(types2 || {});
356
+ return {
357
+ serializers: Object.assign({}, serializers, user.serializers),
358
+ parsers: Object.assign({}, parsers, user.parsers)
359
+ };
360
+ };
361
+ function typeHandlers(types2) {
362
+ return Object.keys(types2).reduce((acc, k) => {
363
+ types2[k].from && [].concat(types2[k].from).forEach((x) => acc.parsers[x] = types2[k].parse);
364
+ if (types2[k].serialize) {
365
+ acc.serializers[types2[k].to] = types2[k].serialize;
366
+ types2[k].from && [].concat(types2[k].from).forEach((x) => acc.serializers[x] = types2[k].serialize);
367
+ }
368
+ return acc;
369
+ }, { parsers: {}, serializers: {} });
370
+ }
371
+ function escapeIdentifiers(xs, { transform: { column } }) {
372
+ return xs.map((x) => escapeIdentifier(column.to ? column.to(x) : x)).join(",");
373
+ }
374
+ var escapeIdentifier = function escape(str) {
375
+ return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"';
376
+ };
377
+ var inferType = function inferType2(x) {
378
+ return x instanceof Parameter ? x.type : x instanceof Date ? 1184 : x instanceof Uint8Array ? 17 : x === true || x === false ? 16 : typeof x === "bigint" ? 20 : Array.isArray(x) ? inferType2(x[0]) : 0;
379
+ };
380
+ var escapeBackslash = /\\/g;
381
+ var escapeQuote = /"/g;
382
+ function arrayEscape(x) {
383
+ return x.replace(escapeBackslash, "\\\\").replace(escapeQuote, '\\"');
384
+ }
385
+ var arraySerializer = function arraySerializer2(xs, serializer, options, typarray) {
386
+ if (Array.isArray(xs) === false)
387
+ return xs;
388
+ if (!xs.length)
389
+ return "{}";
390
+ const first = xs[0];
391
+ const delimiter = typarray === 1020 ? ";" : ",";
392
+ if (Array.isArray(first) && !first.type)
393
+ return "{" + xs.map((x) => arraySerializer2(x, serializer, options, typarray)).join(delimiter) + "}";
394
+ return "{" + xs.map((x) => {
395
+ if (x === void 0) {
396
+ x = options.transform.undefined;
397
+ if (x === void 0)
398
+ throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
399
+ }
400
+ return x === null ? "null" : '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : "" + x) + '"';
401
+ }).join(delimiter) + "}";
402
+ };
403
+ var arrayParserState = {
404
+ i: 0,
405
+ char: null,
406
+ str: "",
407
+ quoted: false,
408
+ last: 0
409
+ };
410
+ var arrayParser = function arrayParser2(x, parser, typarray) {
411
+ arrayParserState.i = arrayParserState.last = 0;
412
+ return arrayParserLoop(arrayParserState, x, parser, typarray);
413
+ };
414
+ function arrayParserLoop(s, x, parser, typarray) {
415
+ const xs = [];
416
+ const delimiter = typarray === 1020 ? ";" : ",";
417
+ for (; s.i < x.length; s.i++) {
418
+ s.char = x[s.i];
419
+ if (s.quoted) {
420
+ if (s.char === "\\") {
421
+ s.str += x[++s.i];
422
+ } else if (s.char === '"') {
423
+ xs.push(parser ? parser(s.str) : s.str);
424
+ s.str = "";
425
+ s.quoted = x[s.i + 1] === '"';
426
+ s.last = s.i + 2;
427
+ } else {
428
+ s.str += s.char;
429
+ }
430
+ } else if (s.char === '"') {
431
+ s.quoted = true;
432
+ } else if (s.char === "{") {
433
+ s.last = ++s.i;
434
+ xs.push(arrayParserLoop(s, x, parser, typarray));
435
+ } else if (s.char === "}") {
436
+ s.quoted = false;
437
+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
438
+ s.last = s.i + 1;
439
+ break;
440
+ } else if (s.char === delimiter && s.p !== "}" && s.p !== '"') {
441
+ xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
442
+ s.last = s.i + 1;
443
+ }
444
+ s.p = s.char;
445
+ }
446
+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1));
447
+ return xs;
448
+ }
449
+ var toCamel = (x) => {
450
+ let str = x[0];
451
+ for (let i = 1; i < x.length; i++)
452
+ str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
453
+ return str;
454
+ };
455
+ var toPascal = (x) => {
456
+ let str = x[0].toUpperCase();
457
+ for (let i = 1; i < x.length; i++)
458
+ str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
459
+ return str;
460
+ };
461
+ var toKebab = (x) => x.replace(/_/g, "-");
462
+ var fromCamel = (x) => x.replace(/([A-Z])/g, "_$1").toLowerCase();
463
+ var fromPascal = (x) => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase();
464
+ var fromKebab = (x) => x.replace(/-/g, "_");
465
+ function createJsonTransform(fn) {
466
+ return function jsonTransform(x, column) {
467
+ return typeof x === "object" && x !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x) ? x.map((x2) => jsonTransform(x2, column)) : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {}) : x;
468
+ };
469
+ }
470
+ toCamel.column = { from: toCamel };
471
+ toCamel.value = { from: createJsonTransform(toCamel) };
472
+ fromCamel.column = { to: fromCamel };
473
+ var camel = { ...toCamel };
474
+ camel.column.to = fromCamel;
475
+ toPascal.column = { from: toPascal };
476
+ toPascal.value = { from: createJsonTransform(toPascal) };
477
+ fromPascal.column = { to: fromPascal };
478
+ var pascal = { ...toPascal };
479
+ pascal.column.to = fromPascal;
480
+ toKebab.column = { from: toKebab };
481
+ toKebab.value = { from: createJsonTransform(toKebab) };
482
+ fromKebab.column = { to: fromKebab };
483
+ var kebab = { ...toKebab };
484
+ kebab.column.to = fromKebab;
485
+
486
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/connection.js
487
+ import net from "net";
488
+ import tls from "tls";
489
+ import crypto from "crypto";
490
+ import Stream from "stream";
491
+ import { performance } from "perf_hooks";
492
+
493
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/result.js
494
+ var Result = class extends Array {
495
+ constructor() {
496
+ super();
497
+ Object.defineProperties(this, {
498
+ count: { value: null, writable: true },
499
+ state: { value: null, writable: true },
500
+ command: { value: null, writable: true },
501
+ columns: { value: null, writable: true },
502
+ statement: { value: null, writable: true }
503
+ });
504
+ }
505
+ static get [Symbol.species]() {
506
+ return Array;
507
+ }
508
+ };
509
+
510
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/queue.js
511
+ var queue_default = Queue;
512
+ function Queue(initial = []) {
513
+ let xs = initial.slice();
514
+ let index = 0;
515
+ return {
516
+ get length() {
517
+ return xs.length - index;
518
+ },
519
+ remove: (x) => {
520
+ const index2 = xs.indexOf(x);
521
+ return index2 === -1 ? null : (xs.splice(index2, 1), x);
522
+ },
523
+ push: (x) => (xs.push(x), x),
524
+ shift: () => {
525
+ const out = xs[index++];
526
+ if (index === xs.length) {
527
+ index = 0;
528
+ xs = [];
529
+ } else {
530
+ xs[index - 1] = void 0;
531
+ }
532
+ return out;
533
+ }
534
+ };
535
+ }
536
+
537
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/bytes.js
538
+ var size = 256;
539
+ var buffer = Buffer.allocUnsafe(size);
540
+ var messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x) => {
541
+ const v = x.charCodeAt(0);
542
+ acc[x] = () => {
543
+ buffer[0] = v;
544
+ b.i = 5;
545
+ return b;
546
+ };
547
+ return acc;
548
+ }, {});
549
+ var b = Object.assign(reset, messages, {
550
+ N: String.fromCharCode(0),
551
+ i: 0,
552
+ inc(x) {
553
+ b.i += x;
554
+ return b;
555
+ },
556
+ str(x) {
557
+ const length = Buffer.byteLength(x);
558
+ fit(length);
559
+ b.i += buffer.write(x, b.i, length, "utf8");
560
+ return b;
561
+ },
562
+ i16(x) {
563
+ fit(2);
564
+ buffer.writeUInt16BE(x, b.i);
565
+ b.i += 2;
566
+ return b;
567
+ },
568
+ i32(x, i) {
569
+ if (i || i === 0) {
570
+ buffer.writeUInt32BE(x, i);
571
+ return b;
572
+ }
573
+ fit(4);
574
+ buffer.writeUInt32BE(x, b.i);
575
+ b.i += 4;
576
+ return b;
577
+ },
578
+ z(x) {
579
+ fit(x);
580
+ buffer.fill(0, b.i, b.i + x);
581
+ b.i += x;
582
+ return b;
583
+ },
584
+ raw(x) {
585
+ buffer = Buffer.concat([buffer.subarray(0, b.i), x]);
586
+ b.i = buffer.length;
587
+ return b;
588
+ },
589
+ end(at = 1) {
590
+ buffer.writeUInt32BE(b.i - at, at);
591
+ const out = buffer.subarray(0, b.i);
592
+ b.i = 0;
593
+ buffer = Buffer.allocUnsafe(size);
594
+ return out;
595
+ }
596
+ });
597
+ var bytes_default = b;
598
+ function fit(x) {
599
+ if (buffer.length - b.i < x) {
600
+ const prev = buffer, length = prev.length;
601
+ buffer = Buffer.allocUnsafe(length + (length >> 1) + x);
602
+ prev.copy(buffer);
603
+ }
604
+ }
605
+ function reset() {
606
+ b.i = 0;
607
+ return b;
608
+ }
609
+
610
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/connection.js
611
+ var connection_default = Connection;
612
+ var uid = 1;
613
+ var Sync = bytes_default().S().end();
614
+ var Flush = bytes_default().H().end();
615
+ var SSLRequest = bytes_default().i32(8).i32(80877103).end(8);
616
+ var ExecuteUnnamed = Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(), Sync]);
617
+ var DescribeUnnamed = bytes_default().D().str("S").str(bytes_default.N).end();
618
+ var noop = () => {
619
+ };
620
+ var retryRoutines = /* @__PURE__ */ new Set([
621
+ "FetchPreparedStatement",
622
+ "RevalidateCachedQuery",
623
+ "transformAssignedExpr"
624
+ ]);
625
+ var errorFields = {
626
+ 83: "severity_local",
627
+ // S
628
+ 86: "severity",
629
+ // V
630
+ 67: "code",
631
+ // C
632
+ 77: "message",
633
+ // M
634
+ 68: "detail",
635
+ // D
636
+ 72: "hint",
637
+ // H
638
+ 80: "position",
639
+ // P
640
+ 112: "internal_position",
641
+ // p
642
+ 113: "internal_query",
643
+ // q
644
+ 87: "where",
645
+ // W
646
+ 115: "schema_name",
647
+ // s
648
+ 116: "table_name",
649
+ // t
650
+ 99: "column_name",
651
+ // c
652
+ 100: "data type_name",
653
+ // d
654
+ 110: "constraint_name",
655
+ // n
656
+ 70: "file",
657
+ // F
658
+ 76: "line",
659
+ // L
660
+ 82: "routine"
661
+ // R
662
+ };
663
+ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
664
+ const {
665
+ sslnegotiation,
666
+ ssl,
667
+ max,
668
+ user,
669
+ host,
670
+ port,
671
+ database,
672
+ parsers: parsers2,
673
+ transform,
674
+ onnotice,
675
+ onnotify,
676
+ onparameter,
677
+ max_pipeline,
678
+ keep_alive,
679
+ backoff: backoff2,
680
+ target_session_attrs
681
+ } = options;
682
+ const sent = queue_default(), id = uid++, backend = { pid: null, secret: null }, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout);
683
+ let socket = null, cancelMessage, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedTime = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null;
684
+ const connection2 = {
685
+ queue: queues.closed,
686
+ idleTimer,
687
+ connect(query2) {
688
+ initial = query2;
689
+ reconnect();
690
+ },
691
+ terminate,
692
+ execute,
693
+ cancel,
694
+ end,
695
+ count: 0,
696
+ id
697
+ };
698
+ queues.closed && queues.closed.push(connection2);
699
+ return connection2;
700
+ async function createSocket() {
701
+ let x;
702
+ try {
703
+ x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket();
704
+ } catch (e) {
705
+ error(e);
706
+ return;
707
+ }
708
+ x.on("error", error);
709
+ x.on("close", closed);
710
+ x.on("drain", drain);
711
+ return x;
712
+ }
713
+ async function cancel({ pid, secret }, resolve, reject) {
714
+ try {
715
+ cancelMessage = bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16);
716
+ await connect();
717
+ socket.once("error", reject);
718
+ socket.once("close", resolve);
719
+ } catch (error2) {
720
+ reject(error2);
721
+ }
722
+ }
723
+ function execute(q) {
724
+ if (terminated)
725
+ return queryError(q, Errors.connection("CONNECTION_DESTROYED", options));
726
+ if (stream)
727
+ return queryError(q, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy"));
728
+ if (q.cancelled)
729
+ return;
730
+ try {
731
+ q.state = backend;
732
+ query ? sent.push(q) : (query = q, query.active = true);
733
+ build(q);
734
+ return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2));
735
+ } catch (error2) {
736
+ sent.length === 0 && write(Sync);
737
+ errored(error2);
738
+ return true;
739
+ }
740
+ }
741
+ function toBuffer(q) {
742
+ if (q.parameters.length >= 65534)
743
+ throw Errors.generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded");
744
+ return q.options.simple ? bytes_default().Q().str(q.statement.string + bytes_default.N).end() : q.describeFirst ? Buffer.concat([describe(q), Flush]) : q.prepare ? q.prepared ? prepared(q) : Buffer.concat([describe(q), prepared(q)]) : unnamed(q);
745
+ }
746
+ function describe(q) {
747
+ return Buffer.concat([
748
+ Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name),
749
+ Describe("S", q.statement.name)
750
+ ]);
751
+ }
752
+ function prepared(q) {
753
+ return Buffer.concat([
754
+ Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName),
755
+ q.cursorFn ? Execute("", q.cursorRows) : ExecuteUnnamed
756
+ ]);
757
+ }
758
+ function unnamed(q) {
759
+ return Buffer.concat([
760
+ Parse(q.statement.string, q.parameters, q.statement.types),
761
+ DescribeUnnamed,
762
+ prepared(q)
763
+ ]);
764
+ }
765
+ function build(q) {
766
+ const parameters = [], types2 = [];
767
+ const string = stringify(q, q.strings[0], q.args[0], parameters, types2, options);
768
+ !q.tagged && q.args.forEach((x) => handleValue(x, parameters, types2, options));
769
+ q.prepare = options.prepare && ("prepare" in q.options ? q.options.prepare : true);
770
+ q.string = string;
771
+ q.signature = q.prepare && types2 + string;
772
+ q.onlyDescribe && delete statements[q.signature];
773
+ q.parameters = q.parameters || parameters;
774
+ q.prepared = q.prepare && q.signature in statements;
775
+ q.describeFirst = q.onlyDescribe || parameters.length && !q.prepared;
776
+ q.statement = q.prepared ? statements[q.signature] : { string, types: types2, name: q.prepare ? statementId + statementCount++ : "" };
777
+ typeof options.debug === "function" && options.debug(id, string, parameters, types2);
778
+ }
779
+ function write(x, fn) {
780
+ chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x);
781
+ if (fn || chunk.length >= 1024)
782
+ return nextWrite(fn);
783
+ nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite));
784
+ return true;
785
+ }
786
+ function nextWrite(fn) {
787
+ const x = socket.write(chunk, fn);
788
+ nextWriteTimer !== null && clearImmediate(nextWriteTimer);
789
+ chunk = nextWriteTimer = null;
790
+ return x;
791
+ }
792
+ function connectTimedOut() {
793
+ errored(Errors.connection("CONNECT_TIMEOUT", options, socket));
794
+ socket.destroy();
795
+ }
796
+ async function secure() {
797
+ if (sslnegotiation !== "direct") {
798
+ write(SSLRequest);
799
+ const canSSL = await new Promise((r) => socket.once("data", (x) => r(x[0] === 83)));
800
+ if (!canSSL && ssl === "prefer")
801
+ return connected();
802
+ }
803
+ const options2 = {
804
+ socket,
805
+ servername: net.isIP(socket.host) ? void 0 : socket.host
806
+ };
807
+ if (sslnegotiation === "direct")
808
+ options2.ALPNProtocols = ["postgresql"];
809
+ if (ssl === "require" || ssl === "allow" || ssl === "prefer")
810
+ options2.rejectUnauthorized = false;
811
+ else if (typeof ssl === "object")
812
+ Object.assign(options2, ssl);
813
+ socket.removeAllListeners();
814
+ socket = tls.connect(options2);
815
+ socket.on("secureConnect", connected);
816
+ socket.on("error", error);
817
+ socket.on("close", closed);
818
+ socket.on("drain", drain);
819
+ }
820
+ function drain() {
821
+ !query && onopen(connection2);
822
+ }
823
+ function data(x) {
824
+ if (incomings) {
825
+ incomings.push(x);
826
+ remaining -= x.length;
827
+ if (remaining > 0)
828
+ return;
829
+ }
830
+ incoming = incomings ? Buffer.concat(incomings, length - remaining) : incoming.length === 0 ? x : Buffer.concat([incoming, x], incoming.length + x.length);
831
+ while (incoming.length > 4) {
832
+ length = incoming.readUInt32BE(1);
833
+ if (length >= incoming.length) {
834
+ remaining = length - incoming.length;
835
+ incomings = [incoming];
836
+ break;
837
+ }
838
+ try {
839
+ handle(incoming.subarray(0, length + 1));
840
+ } catch (e) {
841
+ query && (query.cursorFn || query.describeFirst) && write(Sync);
842
+ errored(e);
843
+ }
844
+ incoming = incoming.subarray(length + 1);
845
+ remaining = 0;
846
+ incomings = null;
847
+ }
848
+ }
849
+ async function connect() {
850
+ terminated = false;
851
+ backendParameters = {};
852
+ socket || (socket = await createSocket());
853
+ if (!socket)
854
+ return;
855
+ connectTimer.start();
856
+ if (options.socket)
857
+ return ssl ? secure() : connected();
858
+ socket.on("connect", ssl ? secure : connected);
859
+ if (options.path)
860
+ return socket.connect(options.path);
861
+ socket.ssl = ssl;
862
+ socket.connect(port[hostIndex], host[hostIndex]);
863
+ socket.host = host[hostIndex];
864
+ socket.port = port[hostIndex];
865
+ hostIndex = (hostIndex + 1) % port.length;
866
+ }
867
+ function reconnect() {
868
+ setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0);
869
+ }
870
+ function connected() {
871
+ try {
872
+ statements = {};
873
+ needsTypes = options.fetch_types;
874
+ statementId = Math.random().toString(36).slice(2);
875
+ statementCount = 1;
876
+ lifeTimer.start();
877
+ socket.on("data", data);
878
+ keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1e3 * keep_alive);
879
+ const s = StartupMessage();
880
+ write(s);
881
+ } catch (err) {
882
+ error(err);
883
+ }
884
+ }
885
+ function error(err) {
886
+ if (connection2.queue === queues.connecting && options.host[retries + 1])
887
+ return;
888
+ errored(err);
889
+ while (sent.length)
890
+ queryError(sent.shift(), err);
891
+ }
892
+ function errored(err) {
893
+ stream && (stream.destroy(err), stream = null);
894
+ query && queryError(query, err);
895
+ initial && (queryError(initial, err), initial = null);
896
+ }
897
+ function queryError(query2, err) {
898
+ if (query2.reserve)
899
+ return query2.reject(err);
900
+ if (!err || typeof err !== "object")
901
+ err = new Error(err);
902
+ "query" in err || "parameters" in err || Object.defineProperties(err, {
903
+ stack: { value: err.stack + query2.origin.replace(/.*\n/, "\n"), enumerable: options.debug },
904
+ query: { value: query2.string, enumerable: options.debug },
905
+ parameters: { value: query2.parameters, enumerable: options.debug },
906
+ args: { value: query2.args, enumerable: options.debug },
907
+ types: { value: query2.statement && query2.statement.types, enumerable: options.debug }
908
+ });
909
+ query2.reject(err);
910
+ }
911
+ function end() {
912
+ return ending || (!connection2.reserved && onend(connection2), !connection2.reserved && !initial && !query && sent.length === 0 ? (terminate(), new Promise((r) => socket && socket.readyState !== "closed" ? socket.once("close", r) : r())) : ending = new Promise((r) => ended = r));
913
+ }
914
+ function terminate() {
915
+ terminated = true;
916
+ if (stream || query || initial || sent.length)
917
+ error(Errors.connection("CONNECTION_DESTROYED", options));
918
+ clearImmediate(nextWriteTimer);
919
+ if (socket) {
920
+ socket.removeListener("data", data);
921
+ socket.removeListener("connect", connected);
922
+ socket.readyState === "open" && socket.end(bytes_default().X().end());
923
+ }
924
+ ended && (ended(), ending = ended = null);
925
+ }
926
+ async function closed(hadError) {
927
+ incoming = Buffer.alloc(0);
928
+ remaining = 0;
929
+ incomings = null;
930
+ clearImmediate(nextWriteTimer);
931
+ socket.removeListener("data", data);
932
+ socket.removeListener("connect", connected);
933
+ idleTimer.cancel();
934
+ lifeTimer.cancel();
935
+ connectTimer.cancel();
936
+ socket.removeAllListeners();
937
+ socket = null;
938
+ if (initial)
939
+ return reconnect();
940
+ !hadError && (query || sent.length) && error(Errors.connection("CONNECTION_CLOSED", options, socket));
941
+ closedTime = performance.now();
942
+ hadError && options.shared.retries++;
943
+ delay = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3;
944
+ onclose(connection2, Errors.connection("CONNECTION_CLOSED", options, socket));
945
+ }
946
+ function handle(xs, x = xs[0]) {
947
+ (x === 68 ? DataRow : (
948
+ // D
949
+ x === 100 ? CopyData : (
950
+ // d
951
+ x === 65 ? NotificationResponse : (
952
+ // A
953
+ x === 83 ? ParameterStatus : (
954
+ // S
955
+ x === 90 ? ReadyForQuery : (
956
+ // Z
957
+ x === 67 ? CommandComplete : (
958
+ // C
959
+ x === 50 ? BindComplete : (
960
+ // 2
961
+ x === 49 ? ParseComplete : (
962
+ // 1
963
+ x === 116 ? ParameterDescription : (
964
+ // t
965
+ x === 84 ? RowDescription : (
966
+ // T
967
+ x === 82 ? Authentication : (
968
+ // R
969
+ x === 110 ? NoData : (
970
+ // n
971
+ x === 75 ? BackendKeyData : (
972
+ // K
973
+ x === 69 ? ErrorResponse : (
974
+ // E
975
+ x === 115 ? PortalSuspended : (
976
+ // s
977
+ x === 51 ? CloseComplete : (
978
+ // 3
979
+ x === 71 ? CopyInResponse : (
980
+ // G
981
+ x === 78 ? NoticeResponse : (
982
+ // N
983
+ x === 72 ? CopyOutResponse : (
984
+ // H
985
+ x === 99 ? CopyDone : (
986
+ // c
987
+ x === 73 ? EmptyQueryResponse : (
988
+ // I
989
+ x === 86 ? FunctionCallResponse : (
990
+ // V
991
+ x === 118 ? NegotiateProtocolVersion : (
992
+ // v
993
+ x === 87 ? CopyBothResponse : (
994
+ // W
995
+ /* c8 ignore next */
996
+ UnknownMessage
997
+ )
998
+ )
999
+ )
1000
+ )
1001
+ )
1002
+ )
1003
+ )
1004
+ )
1005
+ )
1006
+ )
1007
+ )
1008
+ )
1009
+ )
1010
+ )
1011
+ )
1012
+ )
1013
+ )
1014
+ )
1015
+ )
1016
+ )
1017
+ )
1018
+ )
1019
+ )
1020
+ ))(xs);
1021
+ }
1022
+ function DataRow(x) {
1023
+ let index = 7;
1024
+ let length2;
1025
+ let column;
1026
+ let value;
1027
+ const row = query.isRaw ? new Array(query.statement.columns.length) : {};
1028
+ for (let i = 0; i < query.statement.columns.length; i++) {
1029
+ column = query.statement.columns[i];
1030
+ length2 = x.readInt32BE(index);
1031
+ index += 4;
1032
+ value = length2 === -1 ? null : query.isRaw === true ? x.subarray(index, index += length2) : column.parser === void 0 ? x.toString("utf8", index, index += length2) : column.parser.array === true ? column.parser(x.toString("utf8", index + 1, index += length2)) : column.parser(x.toString("utf8", index, index += length2));
1033
+ query.isRaw ? row[i] = query.isRaw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
1034
+ }
1035
+ query.forEachFn ? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result) : result[rows++] = transform.row.from ? transform.row.from(row) : row;
1036
+ }
1037
+ function ParameterStatus(x) {
1038
+ const [k, v] = x.toString("utf8", 5, x.length - 1).split(bytes_default.N);
1039
+ backendParameters[k] = v;
1040
+ if (options.parameters[k] !== v) {
1041
+ options.parameters[k] = v;
1042
+ onparameter && onparameter(k, v);
1043
+ }
1044
+ }
1045
+ function ReadyForQuery(x) {
1046
+ if (query) {
1047
+ if (errorResponse) {
1048
+ query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse);
1049
+ } else {
1050
+ query.resolve(results || result);
1051
+ }
1052
+ } else if (errorResponse) {
1053
+ errored(errorResponse);
1054
+ }
1055
+ query = results = errorResponse = null;
1056
+ result = new Result();
1057
+ connectTimer.cancel();
1058
+ if (initial) {
1059
+ if (target_session_attrs) {
1060
+ if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only)
1061
+ return fetchState();
1062
+ else if (tryNext(target_session_attrs, backendParameters))
1063
+ return terminate();
1064
+ }
1065
+ if (needsTypes) {
1066
+ initial.reserve && (initial = null);
1067
+ return fetchArrayTypes();
1068
+ }
1069
+ initial && !initial.reserve && execute(initial);
1070
+ options.shared.retries = retries = 0;
1071
+ initial = null;
1072
+ return;
1073
+ }
1074
+ while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
1075
+ Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject);
1076
+ if (query)
1077
+ return;
1078
+ connection2.reserved ? !connection2.reserved.release && x[5] === 73 ? ending ? terminate() : (connection2.reserved = null, onopen(connection2)) : connection2.reserved() : ending ? terminate() : onopen(connection2);
1079
+ }
1080
+ function CommandComplete(x) {
1081
+ rows = 0;
1082
+ for (let i = x.length - 1; i > 0; i--) {
1083
+ if (x[i] === 32 && x[i + 1] < 58 && result.count === null)
1084
+ result.count = +x.toString("utf8", i + 1, x.length - 1);
1085
+ if (x[i - 1] >= 65) {
1086
+ result.command = x.toString("utf8", 5, i);
1087
+ result.state = backend;
1088
+ break;
1089
+ }
1090
+ }
1091
+ final && (final(), final = null);
1092
+ if (result.command === "BEGIN" && max !== 1 && !connection2.reserved)
1093
+ return errored(Errors.generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1"));
1094
+ if (query.options.simple)
1095
+ return BindComplete();
1096
+ if (query.cursorFn) {
1097
+ result.count && query.cursorFn(result);
1098
+ write(Sync);
1099
+ }
1100
+ }
1101
+ function ParseComplete() {
1102
+ query.parsing = false;
1103
+ }
1104
+ function BindComplete() {
1105
+ !result.statement && (result.statement = query.statement);
1106
+ result.columns = query.statement.columns;
1107
+ }
1108
+ function ParameterDescription(x) {
1109
+ const length2 = x.readUInt16BE(5);
1110
+ for (let i = 0; i < length2; ++i)
1111
+ !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4));
1112
+ query.prepare && (statements[query.signature] = query.statement);
1113
+ query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false);
1114
+ }
1115
+ function RowDescription(x) {
1116
+ if (result.command) {
1117
+ results = results || [result];
1118
+ results.push(result = new Result());
1119
+ result.count = null;
1120
+ query.statement.columns = null;
1121
+ }
1122
+ const length2 = x.readUInt16BE(5);
1123
+ let index = 7;
1124
+ let start;
1125
+ query.statement.columns = Array(length2);
1126
+ for (let i = 0; i < length2; ++i) {
1127
+ start = index;
1128
+ while (x[index++] !== 0) ;
1129
+ const table = x.readUInt32BE(index);
1130
+ const number = x.readUInt16BE(index + 4);
1131
+ const type = x.readUInt32BE(index + 6);
1132
+ query.statement.columns[i] = {
1133
+ name: transform.column.from ? transform.column.from(x.toString("utf8", start, index - 1)) : x.toString("utf8", start, index - 1),
1134
+ parser: parsers2[type],
1135
+ table,
1136
+ number,
1137
+ type
1138
+ };
1139
+ index += 18;
1140
+ }
1141
+ result.statement = query.statement;
1142
+ if (query.onlyDescribe)
1143
+ return query.resolve(query.statement), write(Sync);
1144
+ }
1145
+ async function Authentication(x, type = x.readUInt32BE(5)) {
1146
+ (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop)(x, type);
1147
+ }
1148
+ async function AuthenticationCleartextPassword() {
1149
+ const payload = await Pass();
1150
+ write(
1151
+ bytes_default().p().str(payload).z(1).end()
1152
+ );
1153
+ }
1154
+ async function AuthenticationMD5Password(x) {
1155
+ const payload = "md5" + await md5(
1156
+ Buffer.concat([
1157
+ Buffer.from(await md5(await Pass() + user)),
1158
+ x.subarray(9)
1159
+ ])
1160
+ );
1161
+ write(
1162
+ bytes_default().p().str(payload).z(1).end()
1163
+ );
1164
+ }
1165
+ async function SASL() {
1166
+ nonce = (await crypto.randomBytes(18)).toString("base64");
1167
+ bytes_default().p().str("SCRAM-SHA-256" + bytes_default.N);
1168
+ const i = bytes_default.i;
1169
+ write(bytes_default.inc(4).str("n,,n=*,r=" + nonce).i32(bytes_default.i - i - 4, i).end());
1170
+ }
1171
+ async function SASLContinue(x) {
1172
+ const res = x.toString("utf8", 9).split(",").reduce((acc, x2) => (acc[x2[0]] = x2.slice(2), acc), {});
1173
+ const saltedPassword = await crypto.pbkdf2Sync(
1174
+ await Pass(),
1175
+ Buffer.from(res.s, "base64"),
1176
+ parseInt(res.i),
1177
+ 32,
1178
+ "sha256"
1179
+ );
1180
+ const clientKey = await hmac(saltedPassword, "Client Key");
1181
+ const auth = "n=*,r=" + nonce + ",r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r;
1182
+ serverSignature = (await hmac(await hmac(saltedPassword, "Server Key"), auth)).toString("base64");
1183
+ const payload = "c=biws,r=" + res.r + ",p=" + xor(
1184
+ clientKey,
1185
+ Buffer.from(await hmac(await sha256(clientKey), auth))
1186
+ ).toString("base64");
1187
+ write(
1188
+ bytes_default().p().str(payload).end()
1189
+ );
1190
+ }
1191
+ function SASLFinal(x) {
1192
+ if (x.toString("utf8", 9).split(bytes_default.N, 1)[0].slice(2) === serverSignature)
1193
+ return;
1194
+ errored(Errors.generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature"));
1195
+ socket.destroy();
1196
+ }
1197
+ function Pass() {
1198
+ return Promise.resolve(
1199
+ typeof options.pass === "function" ? options.pass() : options.pass
1200
+ );
1201
+ }
1202
+ function NoData() {
1203
+ result.statement = query.statement;
1204
+ result.statement.columns = [];
1205
+ if (query.onlyDescribe)
1206
+ return query.resolve(query.statement), write(Sync);
1207
+ }
1208
+ function BackendKeyData(x) {
1209
+ backend.pid = x.readUInt32BE(5);
1210
+ backend.secret = x.readUInt32BE(9);
1211
+ }
1212
+ async function fetchArrayTypes() {
1213
+ needsTypes = false;
1214
+ const types2 = await new Query([`
1215
+ select b.oid, b.typarray
1216
+ from pg_catalog.pg_type a
1217
+ left join pg_catalog.pg_type b on b.oid = a.typelem
1218
+ where a.typcategory = 'A'
1219
+ group by b.oid, b.typarray
1220
+ order by b.oid
1221
+ `], [], execute);
1222
+ types2.forEach(({ oid, typarray }) => addArrayType(oid, typarray));
1223
+ }
1224
+ function addArrayType(oid, typarray) {
1225
+ if (!!options.parsers[typarray] && !!options.serializers[typarray]) return;
1226
+ const parser = options.parsers[oid];
1227
+ options.shared.typeArrayMap[oid] = typarray;
1228
+ options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray);
1229
+ options.parsers[typarray].array = true;
1230
+ options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray);
1231
+ }
1232
+ function tryNext(x, xs) {
1233
+ return x === "read-write" && xs.default_transaction_read_only === "on" || x === "read-only" && xs.default_transaction_read_only === "off" || x === "primary" && xs.in_hot_standby === "on" || x === "standby" && xs.in_hot_standby === "off" || x === "prefer-standby" && xs.in_hot_standby === "off" && options.host[retries];
1234
+ }
1235
+ function fetchState() {
1236
+ const query2 = new Query([`
1237
+ show transaction_read_only;
1238
+ select pg_catalog.pg_is_in_recovery()
1239
+ `], [], execute, null, { simple: true });
1240
+ query2.resolve = ([[a], [b2]]) => {
1241
+ backendParameters.default_transaction_read_only = a.transaction_read_only;
1242
+ backendParameters.in_hot_standby = b2.pg_is_in_recovery ? "on" : "off";
1243
+ };
1244
+ query2.execute();
1245
+ }
1246
+ function ErrorResponse(x) {
1247
+ if (query) {
1248
+ (query.cursorFn || query.describeFirst) && write(Sync);
1249
+ errorResponse = Errors.postgres(parseError(x));
1250
+ } else {
1251
+ errored(Errors.postgres(parseError(x)));
1252
+ }
1253
+ }
1254
+ function retry(q, error2) {
1255
+ delete statements[q.signature];
1256
+ q.retried = error2;
1257
+ execute(q);
1258
+ }
1259
+ function NotificationResponse(x) {
1260
+ if (!onnotify)
1261
+ return;
1262
+ let index = 9;
1263
+ while (x[index++] !== 0) ;
1264
+ onnotify(
1265
+ x.toString("utf8", 9, index - 1),
1266
+ x.toString("utf8", index, x.length - 1)
1267
+ );
1268
+ }
1269
+ async function PortalSuspended() {
1270
+ try {
1271
+ const x = await Promise.resolve(query.cursorFn(result));
1272
+ rows = 0;
1273
+ x === CLOSE ? write(Close(query.portal)) : (result = new Result(), write(Execute("", query.cursorRows)));
1274
+ } catch (err) {
1275
+ write(Sync);
1276
+ query.reject(err);
1277
+ }
1278
+ }
1279
+ function CloseComplete() {
1280
+ result.count && query.cursorFn(result);
1281
+ query.resolve(result);
1282
+ }
1283
+ function CopyInResponse() {
1284
+ stream = new Stream.Writable({
1285
+ autoDestroy: true,
1286
+ write(chunk2, encoding, callback) {
1287
+ socket.write(bytes_default().d().raw(chunk2).end(), callback);
1288
+ },
1289
+ destroy(error2, callback) {
1290
+ callback(error2);
1291
+ socket.write(bytes_default().f().str(error2 + bytes_default.N).end());
1292
+ stream = null;
1293
+ },
1294
+ final(callback) {
1295
+ socket.write(bytes_default().c().end());
1296
+ final = callback;
1297
+ stream = null;
1298
+ }
1299
+ });
1300
+ query.resolve(stream);
1301
+ }
1302
+ function CopyOutResponse() {
1303
+ stream = new Stream.Readable({
1304
+ read() {
1305
+ socket.resume();
1306
+ }
1307
+ });
1308
+ query.resolve(stream);
1309
+ }
1310
+ function CopyBothResponse() {
1311
+ stream = new Stream.Duplex({
1312
+ autoDestroy: true,
1313
+ read() {
1314
+ socket.resume();
1315
+ },
1316
+ /* c8 ignore next 11 */
1317
+ write(chunk2, encoding, callback) {
1318
+ socket.write(bytes_default().d().raw(chunk2).end(), callback);
1319
+ },
1320
+ destroy(error2, callback) {
1321
+ callback(error2);
1322
+ socket.write(bytes_default().f().str(error2 + bytes_default.N).end());
1323
+ stream = null;
1324
+ },
1325
+ final(callback) {
1326
+ socket.write(bytes_default().c().end());
1327
+ final = callback;
1328
+ }
1329
+ });
1330
+ query.resolve(stream);
1331
+ }
1332
+ function CopyData(x) {
1333
+ stream && (stream.push(x.subarray(5)) || socket.pause());
1334
+ }
1335
+ function CopyDone() {
1336
+ stream && stream.push(null);
1337
+ stream = null;
1338
+ }
1339
+ function NoticeResponse(x) {
1340
+ onnotice ? onnotice(parseError(x)) : console.log(parseError(x));
1341
+ }
1342
+ function EmptyQueryResponse() {
1343
+ }
1344
+ function FunctionCallResponse() {
1345
+ errored(Errors.notSupported("FunctionCallResponse"));
1346
+ }
1347
+ function NegotiateProtocolVersion() {
1348
+ errored(Errors.notSupported("NegotiateProtocolVersion"));
1349
+ }
1350
+ function UnknownMessage(x) {
1351
+ console.error("Postgres.js : Unknown Message:", x[0]);
1352
+ }
1353
+ function UnknownAuth(x, type) {
1354
+ console.error("Postgres.js : Unknown Auth:", type);
1355
+ }
1356
+ function Bind(parameters, types2, statement = "", portal = "") {
1357
+ let prev, type;
1358
+ bytes_default().B().str(portal + bytes_default.N).str(statement + bytes_default.N).i16(0).i16(parameters.length);
1359
+ parameters.forEach((x, i) => {
1360
+ if (x === null)
1361
+ return bytes_default.i32(4294967295);
1362
+ type = types2[i];
1363
+ parameters[i] = x = type in options.serializers ? options.serializers[type](x) : "" + x;
1364
+ prev = bytes_default.i;
1365
+ bytes_default.inc(4).str(x).i32(bytes_default.i - prev - 4, prev);
1366
+ });
1367
+ bytes_default.i16(0);
1368
+ return bytes_default.end();
1369
+ }
1370
+ function Parse(str, parameters, types2, name = "") {
1371
+ bytes_default().P().str(name + bytes_default.N).str(str + bytes_default.N).i16(parameters.length);
1372
+ parameters.forEach((x, i) => bytes_default.i32(types2[i] || 0));
1373
+ return bytes_default.end();
1374
+ }
1375
+ function Describe(x, name = "") {
1376
+ return bytes_default().D().str(x).str(name + bytes_default.N).end();
1377
+ }
1378
+ function Execute(portal = "", rows2 = 0) {
1379
+ return Buffer.concat([
1380
+ bytes_default().E().str(portal + bytes_default.N).i32(rows2).end(),
1381
+ Flush
1382
+ ]);
1383
+ }
1384
+ function Close(portal = "") {
1385
+ return Buffer.concat([
1386
+ bytes_default().C().str("P").str(portal + bytes_default.N).end(),
1387
+ bytes_default().S().end()
1388
+ ]);
1389
+ }
1390
+ function StartupMessage() {
1391
+ return cancelMessage || bytes_default().inc(4).i16(3).z(2).str(
1392
+ Object.entries(Object.assign(
1393
+ {
1394
+ user,
1395
+ database,
1396
+ client_encoding: "UTF8"
1397
+ },
1398
+ options.connection
1399
+ )).filter(([, v]) => v).map(([k, v]) => k + bytes_default.N + v).join(bytes_default.N)
1400
+ ).z(2).end(0);
1401
+ }
1402
+ }
1403
+ function parseError(x) {
1404
+ const error = {};
1405
+ let start = 5;
1406
+ for (let i = 5; i < x.length - 1; i++) {
1407
+ if (x[i] === 0) {
1408
+ error[errorFields[x[start]]] = x.toString("utf8", start + 1, i);
1409
+ start = i + 1;
1410
+ }
1411
+ }
1412
+ return error;
1413
+ }
1414
+ function md5(x) {
1415
+ return crypto.createHash("md5").update(x).digest("hex");
1416
+ }
1417
+ function hmac(key, x) {
1418
+ return crypto.createHmac("sha256", key).update(x).digest();
1419
+ }
1420
+ function sha256(x) {
1421
+ return crypto.createHash("sha256").update(x).digest();
1422
+ }
1423
+ function xor(a, b2) {
1424
+ const length = Math.max(a.length, b2.length);
1425
+ const buffer2 = Buffer.allocUnsafe(length);
1426
+ for (let i = 0; i < length; i++)
1427
+ buffer2[i] = a[i] ^ b2[i];
1428
+ return buffer2;
1429
+ }
1430
+ function timer(fn, seconds) {
1431
+ seconds = typeof seconds === "function" ? seconds() : seconds;
1432
+ if (!seconds)
1433
+ return { cancel: noop, start: noop };
1434
+ let timer2;
1435
+ return {
1436
+ cancel() {
1437
+ timer2 && (clearTimeout(timer2), timer2 = null);
1438
+ },
1439
+ start() {
1440
+ timer2 && clearTimeout(timer2);
1441
+ timer2 = setTimeout(done, seconds * 1e3, arguments);
1442
+ }
1443
+ };
1444
+ function done(args) {
1445
+ fn.apply(null, args);
1446
+ timer2 = null;
1447
+ }
1448
+ }
1449
+
1450
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/subscribe.js
1451
+ var noop2 = () => {
1452
+ };
1453
+ function Subscribe(postgres2, options) {
1454
+ const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {};
1455
+ let connection2, stream, ended = false;
1456
+ const sql = subscribe.sql = postgres2({
1457
+ ...options,
1458
+ transform: { column: {}, value: {}, row: {} },
1459
+ max: 1,
1460
+ fetch_types: false,
1461
+ idle_timeout: null,
1462
+ max_lifetime: null,
1463
+ connection: {
1464
+ ...options.connection,
1465
+ replication: "database"
1466
+ },
1467
+ onclose: async function() {
1468
+ if (ended)
1469
+ return;
1470
+ stream = null;
1471
+ state.pid = state.secret = void 0;
1472
+ connected(await init(sql, slot, options.publications));
1473
+ subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe()));
1474
+ },
1475
+ no_subscribe: true
1476
+ });
1477
+ const end = sql.end, close = sql.close;
1478
+ sql.end = async () => {
1479
+ ended = true;
1480
+ stream && await new Promise((r) => (stream.once("close", r), stream.end()));
1481
+ return end();
1482
+ };
1483
+ sql.close = async () => {
1484
+ stream && await new Promise((r) => (stream.once("close", r), stream.end()));
1485
+ return close();
1486
+ };
1487
+ return subscribe;
1488
+ async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) {
1489
+ event = parseEvent(event);
1490
+ if (!connection2)
1491
+ connection2 = init(sql, slot, options.publications);
1492
+ const subscriber = { fn, onsubscribe };
1493
+ const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event);
1494
+ const unsubscribe = () => {
1495
+ fns.delete(subscriber);
1496
+ fns.size === 0 && subscribers.delete(event);
1497
+ };
1498
+ return connection2.then((x) => {
1499
+ connected(x);
1500
+ onsubscribe();
1501
+ stream && stream.on("error", onerror);
1502
+ return { unsubscribe, state, sql };
1503
+ });
1504
+ }
1505
+ function connected(x) {
1506
+ stream = x.stream;
1507
+ state.pid = x.state.pid;
1508
+ state.secret = x.state.secret;
1509
+ }
1510
+ async function init(sql2, slot2, publications) {
1511
+ if (!publications)
1512
+ throw new Error("Missing publication names");
1513
+ const xs = await sql2.unsafe(
1514
+ `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`
1515
+ );
1516
+ const [x] = xs;
1517
+ const stream2 = await sql2.unsafe(
1518
+ `START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')`
1519
+ ).writable();
1520
+ const state2 = {
1521
+ lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex")))
1522
+ };
1523
+ stream2.on("data", data);
1524
+ stream2.on("error", error);
1525
+ stream2.on("close", sql2.close);
1526
+ return { stream: stream2, state: xs.state };
1527
+ function error(e) {
1528
+ console.error("Unexpected error during logical streaming - reconnecting", e);
1529
+ }
1530
+ function data(x2) {
1531
+ if (x2[0] === 119) {
1532
+ parse(x2.subarray(25), state2, sql2.options.parsers, handle, options.transform);
1533
+ } else if (x2[0] === 107 && x2[17]) {
1534
+ state2.lsn = x2.subarray(1, 9);
1535
+ pong();
1536
+ }
1537
+ }
1538
+ function handle(a, b2) {
1539
+ const path = b2.relation.schema + "." + b2.relation.table;
1540
+ call("*", a, b2);
1541
+ call("*:" + path, a, b2);
1542
+ b2.relation.keys.length && call("*:" + path + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2);
1543
+ call(b2.command, a, b2);
1544
+ call(b2.command + ":" + path, a, b2);
1545
+ b2.relation.keys.length && call(b2.command + ":" + path + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2);
1546
+ }
1547
+ function pong() {
1548
+ const x2 = Buffer.alloc(34);
1549
+ x2[0] = "r".charCodeAt(0);
1550
+ x2.fill(state2.lsn, 1);
1551
+ x2.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2e3, 0, 1)) * BigInt(1e3), 25);
1552
+ stream2.write(x2);
1553
+ }
1554
+ }
1555
+ function call(x, a, b2) {
1556
+ subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b2, x));
1557
+ }
1558
+ }
1559
+ function Time(x) {
1560
+ return new Date(Date.UTC(2e3, 0, 1) + Number(x / BigInt(1e3)));
1561
+ }
1562
+ function parse(x, state, parsers2, handle, transform) {
1563
+ const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc);
1564
+ Object.entries({
1565
+ R: (x2) => {
1566
+ let i = 1;
1567
+ const r = state[x2.readUInt32BE(i)] = {
1568
+ schema: x2.toString("utf8", i += 4, i = x2.indexOf(0, i)) || "pg_catalog",
1569
+ table: x2.toString("utf8", i + 1, i = x2.indexOf(0, i + 1)),
1570
+ columns: Array(x2.readUInt16BE(i += 2)),
1571
+ keys: []
1572
+ };
1573
+ i += 2;
1574
+ let columnIndex = 0, column;
1575
+ while (i < x2.length) {
1576
+ column = r.columns[columnIndex++] = {
1577
+ key: x2[i++],
1578
+ name: transform.column.from ? transform.column.from(x2.toString("utf8", i, i = x2.indexOf(0, i))) : x2.toString("utf8", i, i = x2.indexOf(0, i)),
1579
+ type: x2.readUInt32BE(i += 1),
1580
+ parser: parsers2[x2.readUInt32BE(i)],
1581
+ atttypmod: x2.readUInt32BE(i += 4)
1582
+ };
1583
+ column.key && r.keys.push(column);
1584
+ i += 4;
1585
+ }
1586
+ },
1587
+ Y: () => {
1588
+ },
1589
+ // Type
1590
+ O: () => {
1591
+ },
1592
+ // Origin
1593
+ B: (x2) => {
1594
+ state.date = Time(x2.readBigInt64BE(9));
1595
+ state.lsn = x2.subarray(1, 9);
1596
+ },
1597
+ I: (x2) => {
1598
+ let i = 1;
1599
+ const relation = state[x2.readUInt32BE(i)];
1600
+ const { row } = tuples(x2, relation.columns, i += 7, transform);
1601
+ handle(row, {
1602
+ command: "insert",
1603
+ relation
1604
+ });
1605
+ },
1606
+ D: (x2) => {
1607
+ let i = 1;
1608
+ const relation = state[x2.readUInt32BE(i)];
1609
+ i += 4;
1610
+ const key = x2[i] === 75;
1611
+ handle(
1612
+ key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform).row : null,
1613
+ {
1614
+ command: "delete",
1615
+ relation,
1616
+ key
1617
+ }
1618
+ );
1619
+ },
1620
+ U: (x2) => {
1621
+ let i = 1;
1622
+ const relation = state[x2.readUInt32BE(i)];
1623
+ i += 4;
1624
+ const key = x2[i] === 75;
1625
+ const xs = key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform) : null;
1626
+ xs && (i = xs.i);
1627
+ const { row } = tuples(x2, relation.columns, i + 3, transform);
1628
+ handle(row, {
1629
+ command: "update",
1630
+ relation,
1631
+ key,
1632
+ old: xs && xs.row
1633
+ });
1634
+ },
1635
+ T: () => {
1636
+ },
1637
+ // Truncate,
1638
+ C: () => {
1639
+ }
1640
+ // Commit
1641
+ }).reduce(char, {})[x[0]](x);
1642
+ }
1643
+ function tuples(x, columns, xi, transform) {
1644
+ let type, column, value;
1645
+ const row = transform.raw ? new Array(columns.length) : {};
1646
+ for (let i = 0; i < columns.length; i++) {
1647
+ type = x[xi++];
1648
+ column = columns[i];
1649
+ value = type === 110 ? null : type === 117 ? void 0 : column.parser === void 0 ? x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)) : column.parser.array === true ? column.parser(x.toString("utf8", xi + 5, xi += 4 + x.readUInt32BE(xi))) : column.parser(x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)));
1650
+ transform.raw ? row[i] = transform.raw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
1651
+ }
1652
+ return { i: xi, row: transform.row.from ? transform.row.from(row) : row };
1653
+ }
1654
+ function parseEvent(x) {
1655
+ const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || [];
1656
+ if (!xs)
1657
+ throw new Error("Malformed subscribe pattern: " + x);
1658
+ const [, command, path, key] = xs;
1659
+ return (command || "*") + (path ? ":" + (path.indexOf(".") === -1 ? "public." + path : path) : "") + (key ? "=" + key : "");
1660
+ }
1661
+
1662
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/large.js
1663
+ import Stream2 from "stream";
1664
+ function largeObject(sql, oid, mode = 131072 | 262144) {
1665
+ return new Promise(async (resolve, reject) => {
1666
+ await sql.begin(async (sql2) => {
1667
+ let finish;
1668
+ !oid && ([{ oid }] = await sql2`select lo_creat(-1) as oid`);
1669
+ const [{ fd }] = await sql2`select lo_open(${oid}, ${mode}) as fd`;
1670
+ const lo = {
1671
+ writable,
1672
+ readable,
1673
+ close: () => sql2`select lo_close(${fd})`.then(finish),
1674
+ tell: () => sql2`select lo_tell64(${fd})`,
1675
+ read: (x) => sql2`select loread(${fd}, ${x}) as data`,
1676
+ write: (x) => sql2`select lowrite(${fd}, ${x})`,
1677
+ truncate: (x) => sql2`select lo_truncate64(${fd}, ${x})`,
1678
+ seek: (x, whence = 0) => sql2`select lo_lseek64(${fd}, ${x}, ${whence})`,
1679
+ size: () => sql2`
1680
+ select
1681
+ lo_lseek64(${fd}, location, 0) as position,
1682
+ seek.size
1683
+ from (
1684
+ select
1685
+ lo_lseek64($1, 0, 2) as size,
1686
+ tell.location
1687
+ from (select lo_tell64($1) as location) tell
1688
+ ) seek
1689
+ `
1690
+ };
1691
+ resolve(lo);
1692
+ return new Promise(async (r) => finish = r);
1693
+ async function readable({
1694
+ highWaterMark = 2048 * 8,
1695
+ start = 0,
1696
+ end = Infinity
1697
+ } = {}) {
1698
+ let max = end - start;
1699
+ start && await lo.seek(start);
1700
+ return new Stream2.Readable({
1701
+ highWaterMark,
1702
+ async read(size2) {
1703
+ const l = size2 > max ? size2 - max : size2;
1704
+ max -= size2;
1705
+ const [{ data }] = await lo.read(l);
1706
+ this.push(data);
1707
+ if (data.length < size2)
1708
+ this.push(null);
1709
+ }
1710
+ });
1711
+ }
1712
+ async function writable({
1713
+ highWaterMark = 2048 * 8,
1714
+ start = 0
1715
+ } = {}) {
1716
+ start && await lo.seek(start);
1717
+ return new Stream2.Writable({
1718
+ highWaterMark,
1719
+ write(chunk, encoding, callback) {
1720
+ lo.write(chunk).then(() => callback(), callback);
1721
+ }
1722
+ });
1723
+ }
1724
+ }).catch(reject);
1725
+ });
1726
+ }
1727
+
1728
+ // ../../node_modules/.pnpm/postgres@3.4.8/node_modules/postgres/src/index.js
1729
+ Object.assign(Postgres, {
1730
+ PostgresError,
1731
+ toPascal,
1732
+ pascal,
1733
+ toCamel,
1734
+ camel,
1735
+ toKebab,
1736
+ kebab,
1737
+ fromPascal,
1738
+ fromCamel,
1739
+ fromKebab,
1740
+ BigInt: {
1741
+ to: 20,
1742
+ from: [20],
1743
+ parse: (x) => BigInt(x),
1744
+ // eslint-disable-line
1745
+ serialize: (x) => x.toString()
1746
+ }
1747
+ });
1748
+ var src_default = Postgres;
1749
+ function Postgres(a, b2) {
1750
+ const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options });
1751
+ let ending = false;
1752
+ const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full };
1753
+ const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose }));
1754
+ const sql = Sql(handler);
1755
+ Object.assign(sql, {
1756
+ get parameters() {
1757
+ return options.parameters;
1758
+ },
1759
+ largeObject: largeObject.bind(null, sql),
1760
+ subscribe,
1761
+ CLOSE,
1762
+ END: CLOSE,
1763
+ PostgresError,
1764
+ options,
1765
+ reserve,
1766
+ listen,
1767
+ begin,
1768
+ close,
1769
+ end
1770
+ });
1771
+ return sql;
1772
+ function Sql(handler2) {
1773
+ handler2.debug = options.debug;
1774
+ Object.entries(options.types).reduce((acc, [name, type]) => {
1775
+ acc[name] = (x) => new Parameter(x, type.to);
1776
+ return acc;
1777
+ }, typed);
1778
+ Object.assign(sql2, {
1779
+ types: typed,
1780
+ typed,
1781
+ unsafe,
1782
+ notify,
1783
+ array,
1784
+ json,
1785
+ file
1786
+ });
1787
+ return sql2;
1788
+ function typed(value, type) {
1789
+ return new Parameter(value, type);
1790
+ }
1791
+ function sql2(strings, ...args) {
1792
+ const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args);
1793
+ return query;
1794
+ }
1795
+ function unsafe(string, args = [], options2 = {}) {
1796
+ arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
1797
+ const query = new Query([string], args, handler2, cancel, {
1798
+ prepare: false,
1799
+ ...options2,
1800
+ simple: "simple" in options2 ? options2.simple : args.length === 0
1801
+ });
1802
+ return query;
1803
+ }
1804
+ function file(path, args = [], options2 = {}) {
1805
+ arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
1806
+ const query = new Query([], args, (query2) => {
1807
+ fs.readFile(path, "utf8", (err, string) => {
1808
+ if (err)
1809
+ return query2.reject(err);
1810
+ query2.strings = [string];
1811
+ handler2(query2);
1812
+ });
1813
+ }, cancel, {
1814
+ ...options2,
1815
+ simple: "simple" in options2 ? options2.simple : args.length === 0
1816
+ });
1817
+ return query;
1818
+ }
1819
+ }
1820
+ async function listen(name, fn, onlisten) {
1821
+ const listener = { fn, onlisten };
1822
+ const sql2 = listen.sql || (listen.sql = Postgres({
1823
+ ...options,
1824
+ max: 1,
1825
+ idle_timeout: null,
1826
+ max_lifetime: null,
1827
+ fetch_types: false,
1828
+ onclose() {
1829
+ Object.entries(listen.channels).forEach(([name2, { listeners }]) => {
1830
+ delete listen.channels[name2];
1831
+ Promise.all(listeners.map((l) => listen(name2, l.fn, l.onlisten).catch(() => {
1832
+ })));
1833
+ });
1834
+ },
1835
+ onnotify(c, x) {
1836
+ c in listen.channels && listen.channels[c].listeners.forEach((l) => l.fn(x));
1837
+ }
1838
+ }));
1839
+ const channels = listen.channels || (listen.channels = {}), exists = name in channels;
1840
+ if (exists) {
1841
+ channels[name].listeners.push(listener);
1842
+ const result2 = await channels[name].result;
1843
+ listener.onlisten && listener.onlisten();
1844
+ return { state: result2.state, unlisten };
1845
+ }
1846
+ channels[name] = { result: sql2`listen ${sql2.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] };
1847
+ const result = await channels[name].result;
1848
+ listener.onlisten && listener.onlisten();
1849
+ return { state: result.state, unlisten };
1850
+ async function unlisten() {
1851
+ if (name in channels === false)
1852
+ return;
1853
+ channels[name].listeners = channels[name].listeners.filter((x) => x !== listener);
1854
+ if (channels[name].listeners.length)
1855
+ return;
1856
+ delete channels[name];
1857
+ return sql2`unlisten ${sql2.unsafe('"' + name.replace(/"/g, '""') + '"')}`;
1858
+ }
1859
+ }
1860
+ async function notify(channel, payload) {
1861
+ return await sql`select pg_notify(${channel}, ${"" + payload})`;
1862
+ }
1863
+ async function reserve() {
1864
+ const queue = queue_default();
1865
+ const c = open.length ? open.shift() : await new Promise((resolve, reject) => {
1866
+ const query = { reserve: resolve, reject };
1867
+ queries.push(query);
1868
+ closed.length && connect(closed.shift(), query);
1869
+ });
1870
+ move(c, reserved);
1871
+ c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved);
1872
+ c.reserved.release = true;
1873
+ const sql2 = Sql(handler2);
1874
+ sql2.release = () => {
1875
+ c.reserved = null;
1876
+ onopen(c);
1877
+ };
1878
+ return sql2;
1879
+ function handler2(q) {
1880
+ c.queue === full ? queue.push(q) : c.execute(q) || move(c, full);
1881
+ }
1882
+ }
1883
+ async function begin(options2, fn) {
1884
+ !fn && (fn = options2, options2 = "");
1885
+ const queries2 = queue_default();
1886
+ let savepoints = 0, connection2, prepare = null;
1887
+ try {
1888
+ await sql.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute();
1889
+ return await Promise.race([
1890
+ scope(connection2, fn),
1891
+ new Promise((_, reject) => connection2.onclose = reject)
1892
+ ]);
1893
+ } catch (error) {
1894
+ throw error;
1895
+ }
1896
+ async function scope(c, fn2, name) {
1897
+ const sql2 = Sql(handler2);
1898
+ sql2.savepoint = savepoint;
1899
+ sql2.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi);
1900
+ let uncaughtError, result;
1901
+ name && await sql2`savepoint ${sql2(name)}`;
1902
+ try {
1903
+ result = await new Promise((resolve, reject) => {
1904
+ const x = fn2(sql2);
1905
+ Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject);
1906
+ });
1907
+ if (uncaughtError)
1908
+ throw uncaughtError;
1909
+ } catch (e) {
1910
+ await (name ? sql2`rollback to ${sql2(name)}` : sql2`rollback`);
1911
+ throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e;
1912
+ }
1913
+ if (!name) {
1914
+ prepare ? await sql2`prepare transaction '${sql2.unsafe(prepare)}'` : await sql2`commit`;
1915
+ }
1916
+ return result;
1917
+ function savepoint(name2, fn3) {
1918
+ if (name2 && Array.isArray(name2.raw))
1919
+ return savepoint((sql3) => sql3.apply(sql3, arguments));
1920
+ arguments.length === 1 && (fn3 = name2, name2 = null);
1921
+ return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : ""));
1922
+ }
1923
+ function handler2(q) {
1924
+ q.catch((e) => uncaughtError || (uncaughtError = e));
1925
+ c.queue === full ? queries2.push(q) : c.execute(q) || move(c, full);
1926
+ }
1927
+ }
1928
+ function onexecute(c) {
1929
+ connection2 = c;
1930
+ move(c, reserved);
1931
+ c.reserved = () => queries2.length ? c.execute(queries2.shift()) : move(c, reserved);
1932
+ }
1933
+ }
1934
+ function move(c, queue) {
1935
+ c.queue.remove(c);
1936
+ queue.push(c);
1937
+ c.queue = queue;
1938
+ queue === open ? c.idleTimer.start() : c.idleTimer.cancel();
1939
+ return c;
1940
+ }
1941
+ function json(x) {
1942
+ return new Parameter(x, 3802);
1943
+ }
1944
+ function array(x, type) {
1945
+ if (!Array.isArray(x))
1946
+ return array(Array.from(arguments));
1947
+ return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap);
1948
+ }
1949
+ function handler(query) {
1950
+ if (ending)
1951
+ return query.reject(Errors.connection("CONNECTION_ENDED", options, options));
1952
+ if (open.length)
1953
+ return go(open.shift(), query);
1954
+ if (closed.length)
1955
+ return connect(closed.shift(), query);
1956
+ busy.length ? go(busy.shift(), query) : queries.push(query);
1957
+ }
1958
+ function go(c, query) {
1959
+ return c.execute(query) ? move(c, busy) : move(c, full);
1960
+ }
1961
+ function cancel(query) {
1962
+ return new Promise((resolve, reject) => {
1963
+ query.state ? query.active ? connection_default(options).cancel(query.state, resolve, reject) : query.cancelled = { resolve, reject } : (queries.remove(query), query.cancelled = true, query.reject(Errors.generic("57014", "canceling statement due to user request")), resolve());
1964
+ });
1965
+ }
1966
+ async function end({ timeout = null } = {}) {
1967
+ if (ending)
1968
+ return ending;
1969
+ await 1;
1970
+ let timer2;
1971
+ return ending = Promise.race([
1972
+ new Promise((r) => timeout !== null && (timer2 = setTimeout(destroy, timeout * 1e3, r))),
1973
+ Promise.all(connections.map((c) => c.end()).concat(
1974
+ listen.sql ? listen.sql.end({ timeout: 0 }) : [],
1975
+ subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : []
1976
+ ))
1977
+ ]).then(() => clearTimeout(timer2));
1978
+ }
1979
+ async function close() {
1980
+ await Promise.all(connections.map((c) => c.end()));
1981
+ }
1982
+ async function destroy(resolve) {
1983
+ await Promise.all(connections.map((c) => c.terminate()));
1984
+ while (queries.length)
1985
+ queries.shift().reject(Errors.connection("CONNECTION_DESTROYED", options));
1986
+ resolve();
1987
+ }
1988
+ function connect(c, query) {
1989
+ move(c, connecting);
1990
+ c.connect(query);
1991
+ return c;
1992
+ }
1993
+ function onend(c) {
1994
+ move(c, ended);
1995
+ }
1996
+ function onopen(c) {
1997
+ if (queries.length === 0)
1998
+ return move(c, open);
1999
+ let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true;
2000
+ while (ready && queries.length && max-- > 0) {
2001
+ const query = queries.shift();
2002
+ if (query.reserve)
2003
+ return query.reserve(c);
2004
+ ready = c.execute(query);
2005
+ }
2006
+ ready ? move(c, busy) : move(c, full);
2007
+ }
2008
+ function onclose(c, e) {
2009
+ move(c, closed);
2010
+ c.reserved = null;
2011
+ c.onclose && (c.onclose(e), c.onclose = null);
2012
+ options.onclose && options.onclose(c.id);
2013
+ queries.length && connect(c, queries.shift());
2014
+ }
2015
+ }
2016
+ function parseOptions(a, b2) {
2017
+ if (a && a.shared)
2018
+ return a;
2019
+ const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url, multihost } = parseUrl(a), query = [...url.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url.hostname || env.PGHOST || "localhost", port = o.port || url.port || env.PGPORT || 5432, user = o.user || o.username || url.username || env.PGUSERNAME || env.PGUSER || osUsername();
2020
+ o.no_prepare && (o.prepare = false);
2021
+ query.sslmode && (query.ssl = query.sslmode, delete query.sslmode);
2022
+ "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout);
2023
+ query.sslrootcert === "system" && (query.ssl = "verify-full");
2024
+ const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"];
2025
+ const defaults = {
2026
+ max: globalThis.Cloudflare ? 3 : 10,
2027
+ ssl: false,
2028
+ sslnegotiation: null,
2029
+ idle_timeout: null,
2030
+ connect_timeout: 30,
2031
+ max_lifetime,
2032
+ max_pipeline: 100,
2033
+ backoff,
2034
+ keep_alive: 60,
2035
+ prepare: true,
2036
+ debug: false,
2037
+ fetch_types: true,
2038
+ publications: "alltables",
2039
+ target_session_attrs: null
2040
+ };
2041
+ return {
2042
+ host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]),
2043
+ port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)),
2044
+ path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port,
2045
+ database: o.database || o.db || (url.pathname || "").slice(1) || env.PGDATABASE || user,
2046
+ user,
2047
+ pass: o.pass || o.password || url.password || env.PGPASSWORD || "",
2048
+ ...Object.entries(defaults).reduce(
2049
+ (acc, [k, d]) => {
2050
+ const value = k in o ? o[k] : k in query ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d;
2051
+ acc[k] = typeof value === "string" && ints.includes(k) ? +value : value;
2052
+ return acc;
2053
+ },
2054
+ {}
2055
+ ),
2056
+ connection: {
2057
+ application_name: env.PGAPPNAME || "postgres.js",
2058
+ ...o.connection,
2059
+ ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || (acc[k] = v), acc), {})
2060
+ },
2061
+ types: o.types || {},
2062
+ target_session_attrs: tsa(o, url, env),
2063
+ onnotice: o.onnotice,
2064
+ onnotify: o.onnotify,
2065
+ onclose: o.onclose,
2066
+ onparameter: o.onparameter,
2067
+ socket: o.socket,
2068
+ transform: parseTransform(o.transform || { undefined: void 0 }),
2069
+ parameters: {},
2070
+ shared: { retries: 0, typeArrayMap: {} },
2071
+ ...mergeUserTypes(o.types)
2072
+ };
2073
+ }
2074
+ function tsa(o, url, env) {
2075
+ const x = o.target_session_attrs || url.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS;
2076
+ if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x))
2077
+ return x;
2078
+ throw new Error("target_session_attrs " + x + " is not supported");
2079
+ }
2080
+ function backoff(retries) {
2081
+ return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20);
2082
+ }
2083
+ function max_lifetime() {
2084
+ return 60 * (30 + Math.random() * 30);
2085
+ }
2086
+ function parseTransform(x) {
2087
+ return {
2088
+ undefined: x.undefined,
2089
+ column: {
2090
+ from: typeof x.column === "function" ? x.column : x.column && x.column.from,
2091
+ to: x.column && x.column.to
2092
+ },
2093
+ value: {
2094
+ from: typeof x.value === "function" ? x.value : x.value && x.value.from,
2095
+ to: x.value && x.value.to
2096
+ },
2097
+ row: {
2098
+ from: typeof x.row === "function" ? x.row : x.row && x.row.from,
2099
+ to: x.row && x.row.to
2100
+ }
2101
+ };
2102
+ }
2103
+ function parseUrl(url) {
2104
+ if (!url || typeof url !== "string")
2105
+ return { url: { searchParams: /* @__PURE__ */ new Map() } };
2106
+ let host = url;
2107
+ host = host.slice(host.indexOf("://") + 3).split(/[?/]/)[0];
2108
+ host = decodeURIComponent(host.slice(host.indexOf("@") + 1));
2109
+ const urlObj = new URL(url.replace(host, host.split(",")[0]));
2110
+ return {
2111
+ url: {
2112
+ username: decodeURIComponent(urlObj.username),
2113
+ password: decodeURIComponent(urlObj.password),
2114
+ host: urlObj.host,
2115
+ hostname: urlObj.hostname,
2116
+ port: urlObj.port,
2117
+ pathname: urlObj.pathname,
2118
+ searchParams: urlObj.searchParams
2119
+ },
2120
+ multihost: host.indexOf(",") > -1 && host
2121
+ };
2122
+ }
2123
+ function osUsername() {
2124
+ try {
2125
+ return os.userInfo().username;
2126
+ } catch (_) {
2127
+ return process.env.USERNAME || process.env.USER || process.env.LOGNAME;
2128
+ }
2129
+ }
2130
+
2131
+ export {
2132
+ src_default
2133
+ };