@tradejs/cli 2.0.5 → 2.0.7

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.
@@ -975,11 +975,16 @@ var require_pg_types = __commonJS({
975
975
  var require_defaults = __commonJS({
976
976
  "../../node_modules/pg/lib/defaults.js"(exports2, module2) {
977
977
  "use strict";
978
+ var user;
979
+ try {
980
+ user = process.platform === "win32" ? process.env.USERNAME : process.env.USER;
981
+ } catch {
982
+ }
978
983
  module2.exports = {
979
984
  // database host. defaults to localhost
980
985
  host: "localhost",
981
986
  // database user's name
982
- user: process.platform === "win32" ? process.env.USERNAME : process.env.USER,
987
+ user,
983
988
  // name of database to connect
984
989
  database: void 0,
985
990
  // database user's password
@@ -1004,6 +1009,8 @@ var require_defaults = __commonJS({
1004
1009
  idleTimeoutMillis: 3e4,
1005
1010
  client_encoding: "",
1006
1011
  ssl: false,
1012
+ // SSL negotiation style: 'postgres' (traditional SSLRequest) or 'direct'
1013
+ sslnegotiation: void 0,
1007
1014
  application_name: void 0,
1008
1015
  fallback_application_name: void 0,
1009
1016
  options: void 0,
@@ -1038,8 +1045,7 @@ var require_utils = __commonJS({
1038
1045
  "../../node_modules/pg/lib/utils.js"(exports2, module2) {
1039
1046
  "use strict";
1040
1047
  var defaults2 = require_defaults();
1041
- var util = require("util");
1042
- var { isDate } = util.types || util;
1048
+ var { isDate } = require("util/types");
1043
1049
  function escapeElement(elementRepresentation) {
1044
1050
  const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
1045
1051
  return '"' + escaped + '"';
@@ -1048,28 +1054,23 @@ var require_utils = __commonJS({
1048
1054
  let result = "{";
1049
1055
  for (let i = 0; i < val.length; i++) {
1050
1056
  if (i > 0) {
1051
- result = result + ",";
1052
- }
1053
- if (val[i] === null || typeof val[i] === "undefined") {
1054
- result = result + "NULL";
1055
- } else if (Array.isArray(val[i])) {
1056
- result = result + arrayString(val[i]);
1057
- } else if (ArrayBuffer.isView(val[i])) {
1058
- let item = val[i];
1057
+ result += ",";
1058
+ }
1059
+ let item = val[i];
1060
+ if (item == null) {
1061
+ result += "NULL";
1062
+ } else if (Array.isArray(item)) {
1063
+ result += arrayString(item);
1064
+ } else if (ArrayBuffer.isView(item)) {
1059
1065
  if (!(item instanceof Buffer)) {
1060
- const buf = Buffer.from(item.buffer, item.byteOffset, item.byteLength);
1061
- if (buf.length === item.byteLength) {
1062
- item = buf;
1063
- } else {
1064
- item = buf.slice(item.byteOffset, item.byteOffset + item.byteLength);
1065
- }
1066
+ item = Buffer.from(item.buffer, item.byteOffset, item.byteLength);
1066
1067
  }
1067
1068
  result += "\\\\x" + item.toString("hex");
1068
1069
  } else {
1069
- result += escapeElement(prepareValue(val[i]));
1070
+ result += escapeElement(prepareValue(item));
1070
1071
  }
1071
1072
  }
1072
- result = result + "}";
1073
+ result += "}";
1073
1074
  return result;
1074
1075
  }
1075
1076
  var prepareValue = function(val, seen) {
@@ -1081,11 +1082,7 @@ var require_utils = __commonJS({
1081
1082
  return val;
1082
1083
  }
1083
1084
  if (ArrayBuffer.isView(val)) {
1084
- const buf = Buffer.from(val.buffer, val.byteOffset, val.byteLength);
1085
- if (buf.length === val.byteLength) {
1086
- return buf;
1087
- }
1088
- return buf.slice(val.byteOffset, val.byteOffset + val.byteLength);
1085
+ return Buffer.from(val.buffer, val.byteOffset, val.byteLength);
1089
1086
  }
1090
1087
  if (isDate(val)) {
1091
1088
  if (defaults2.parseInputDatesAsUTC) {
@@ -1191,47 +1188,9 @@ var require_utils = __commonJS({
1191
1188
  }
1192
1189
  });
1193
1190
 
1194
- // ../../node_modules/pg/lib/crypto/utils-legacy.js
1195
- var require_utils_legacy = __commonJS({
1196
- "../../node_modules/pg/lib/crypto/utils-legacy.js"(exports2, module2) {
1197
- "use strict";
1198
- var nodeCrypto = require("crypto");
1199
- function md5(string) {
1200
- return nodeCrypto.createHash("md5").update(string, "utf-8").digest("hex");
1201
- }
1202
- function postgresMd5PasswordHash(user, password, salt) {
1203
- const inner = md5(password + user);
1204
- const outer = md5(Buffer.concat([Buffer.from(inner), salt]));
1205
- return "md5" + outer;
1206
- }
1207
- function sha256(text) {
1208
- return nodeCrypto.createHash("sha256").update(text).digest();
1209
- }
1210
- function hashByName(hashName, text) {
1211
- hashName = hashName.replace(/(\D)-/, "$1");
1212
- return nodeCrypto.createHash(hashName).update(text).digest();
1213
- }
1214
- function hmacSha256(key, msg) {
1215
- return nodeCrypto.createHmac("sha256", key).update(msg).digest();
1216
- }
1217
- async function deriveKey(password, salt, iterations) {
1218
- return nodeCrypto.pbkdf2Sync(password, salt, iterations, 32, "sha256");
1219
- }
1220
- module2.exports = {
1221
- postgresMd5PasswordHash,
1222
- randomBytes: nodeCrypto.randomBytes,
1223
- deriveKey,
1224
- sha256,
1225
- hashByName,
1226
- hmacSha256,
1227
- md5
1228
- };
1229
- }
1230
- });
1231
-
1232
- // ../../node_modules/pg/lib/crypto/utils-webcrypto.js
1233
- var require_utils_webcrypto = __commonJS({
1234
- "../../node_modules/pg/lib/crypto/utils-webcrypto.js"(exports2, module2) {
1191
+ // ../../node_modules/pg/lib/crypto/utils.js
1192
+ var require_utils2 = __commonJS({
1193
+ "../../node_modules/pg/lib/crypto/utils.js"(exports2, module2) {
1235
1194
  "use strict";
1236
1195
  var nodeCrypto = require("crypto");
1237
1196
  module2.exports = {
@@ -1281,19 +1240,6 @@ var require_utils_webcrypto = __commonJS({
1281
1240
  }
1282
1241
  });
1283
1242
 
1284
- // ../../node_modules/pg/lib/crypto/utils.js
1285
- var require_utils2 = __commonJS({
1286
- "../../node_modules/pg/lib/crypto/utils.js"(exports2, module2) {
1287
- "use strict";
1288
- var useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split(".")[0]) < 15;
1289
- if (useLegacyCrypto) {
1290
- module2.exports = require_utils_legacy();
1291
- } else {
1292
- module2.exports = require_utils_webcrypto();
1293
- }
1294
- }
1295
- });
1296
-
1297
1243
  // ../../node_modules/pg/lib/crypto/cert-signatures.js
1298
1244
  var require_cert_signatures = __commonJS({
1299
1245
  "../../node_modules/pg/lib/crypto/cert-signatures.js"(exports2, module2) {
@@ -1414,7 +1360,13 @@ var require_sasl = __commonJS({
1414
1360
  "use strict";
1415
1361
  var crypto = require_utils2();
1416
1362
  var { signatureAlgorithmHashFromCertificate } = require_cert_signatures();
1417
- function startSession(mechanisms, stream) {
1363
+ function saslprep(password) {
1364
+ const nonAsciiSpace = /[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g;
1365
+ const mappedToNothing = /[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g;
1366
+ return password.replace(nonAsciiSpace, " ").replace(mappedToNothing, "").normalize("NFKC");
1367
+ }
1368
+ var DEFAULT_MAX_SCRAM_ITERATIONS = 1e5;
1369
+ function startSession(mechanisms, stream, scramMaxIterations = DEFAULT_MAX_SCRAM_ITERATIONS) {
1418
1370
  const candidates = ["SCRAM-SHA-256"];
1419
1371
  if (stream) candidates.unshift("SCRAM-SHA-256-PLUS");
1420
1372
  const mechanism = candidates.find((candidate) => mechanisms.includes(candidate));
@@ -1430,7 +1382,8 @@ var require_sasl = __commonJS({
1430
1382
  mechanism,
1431
1383
  clientNonce,
1432
1384
  response: gs2Header + ",,n=*,r=" + clientNonce,
1433
- message: "SASLInitialResponse"
1385
+ message: "SASLInitialResponse",
1386
+ scramMaxIterations
1434
1387
  };
1435
1388
  }
1436
1389
  async function continueSession(session, password, serverData, stream) {
@@ -1452,6 +1405,12 @@ var require_sasl = __commonJS({
1452
1405
  } else if (sv.nonce.length === session.clientNonce.length) {
1453
1406
  throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");
1454
1407
  }
1408
+ const scramMaxIterations = typeof session.scramMaxIterations === "number" ? session.scramMaxIterations : DEFAULT_MAX_SCRAM_ITERATIONS;
1409
+ if (scramMaxIterations !== 0 && sv.iteration > scramMaxIterations) {
1410
+ throw new Error(
1411
+ "SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration count " + sv.iteration + " exceeds scramMaxIterations of " + scramMaxIterations
1412
+ );
1413
+ }
1455
1414
  const clientFirstMessageBare = "n=*,r=" + session.clientNonce;
1456
1415
  const serverFirstMessage = "r=" + sv.nonce + ",s=" + sv.salt + ",i=" + sv.iteration;
1457
1416
  let channelBinding = stream ? "eSws" : "biws";
@@ -1466,7 +1425,7 @@ var require_sasl = __commonJS({
1466
1425
  const clientFinalMessageWithoutProof = "c=" + channelBinding + ",r=" + sv.nonce;
1467
1426
  const authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof;
1468
1427
  const saltBytes = Buffer.from(sv.salt, "base64");
1469
- const saltedPassword = await crypto.deriveKey(password, saltBytes, sv.iteration);
1428
+ const saltedPassword = await crypto.deriveKey(saslprep(password), saltBytes, sv.iteration);
1470
1429
  const clientKey = await crypto.hmacSha256(saltedPassword, "Client Key");
1471
1430
  const storedKey = await crypto.sha256(clientKey);
1472
1431
  const clientSignature = await crypto.hmacSha256(storedKey, authMessage);
@@ -1542,7 +1501,11 @@ var require_sasl = __commonJS({
1542
1501
  }
1543
1502
  function parseServerFinalMessage(serverData) {
1544
1503
  const attrPairs = parseAttributePairs(serverData);
1504
+ const error = attrPairs.get("e");
1545
1505
  const serverSignature = attrPairs.get("v");
1506
+ if (error) {
1507
+ throw new Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server returned error: "${error}"`);
1508
+ }
1546
1509
  if (!serverSignature) {
1547
1510
  throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");
1548
1511
  } else if (!isBase64(serverSignature)) {
@@ -1570,7 +1533,8 @@ var require_sasl = __commonJS({
1570
1533
  module2.exports = {
1571
1534
  startSession,
1572
1535
  continueSession,
1573
- finalizeSession
1536
+ finalizeSession,
1537
+ DEFAULT_MAX_SCRAM_ITERATIONS
1574
1538
  };
1575
1539
  }
1576
1540
  });
@@ -1619,7 +1583,7 @@ var require_pg_connection_string = __commonJS({
1619
1583
  const config2 = str.split(" ");
1620
1584
  return { host: config2[0], database: config2[1] };
1621
1585
  }
1622
- const config = {};
1586
+ const config = /* @__PURE__ */ Object.create(null);
1623
1587
  let result;
1624
1588
  let dummyHost = false;
1625
1589
  if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) {
@@ -1634,6 +1598,7 @@ var require_pg_connection_string = __commonJS({
1634
1598
  }
1635
1599
  } catch (err) {
1636
1600
  err.input && (err.input = "*****REDACTED*****");
1601
+ throw err;
1637
1602
  }
1638
1603
  for (const entry of result.searchParams.entries()) {
1639
1604
  config[entry[0]] = entry[1];
@@ -1666,6 +1631,9 @@ var require_pg_connection_string = __commonJS({
1666
1631
  if (config.sslcert || config.sslkey || config.sslrootcert || config.sslmode) {
1667
1632
  config.ssl = {};
1668
1633
  }
1634
+ if (config.sslnegotiation === "direct" && config.ssl === void 0) {
1635
+ config.ssl = true;
1636
+ }
1669
1637
  const fs = config.sslcert || config.sslkey || config.sslrootcert ? require("fs") : null;
1670
1638
  if (config.sslcert) {
1671
1639
  config.ssl.cert = fs.readFileSync(config.sslcert).toString();
@@ -1722,6 +1690,9 @@ var require_pg_connection_string = __commonJS({
1722
1690
  case "require":
1723
1691
  case "verify-ca":
1724
1692
  case "verify-full": {
1693
+ if (config.sslmode !== "verify-full") {
1694
+ deprecatedSslModeWarning(config.sslmode);
1695
+ }
1725
1696
  break;
1726
1697
  }
1727
1698
  case "no-verify": {
@@ -1738,7 +1709,7 @@ var require_pg_connection_string = __commonJS({
1738
1709
  c[key] = value;
1739
1710
  }
1740
1711
  return c;
1741
- }, {});
1712
+ }, /* @__PURE__ */ Object.create(null));
1742
1713
  return connectionOptions;
1743
1714
  }
1744
1715
  function toClientConfig(config) {
@@ -1765,12 +1736,25 @@ var require_pg_connection_string = __commonJS({
1765
1736
  }
1766
1737
  }
1767
1738
  return c;
1768
- }, {});
1739
+ }, /* @__PURE__ */ Object.create(null));
1769
1740
  return poolConfig;
1770
1741
  }
1771
1742
  function parseIntoClientConfig(str) {
1772
1743
  return toClientConfig(parse(str));
1773
1744
  }
1745
+ function deprecatedSslModeWarning(sslmode) {
1746
+ if (!deprecatedSslModeWarning.warned && typeof process !== "undefined" && process.emitWarning) {
1747
+ deprecatedSslModeWarning.warned = true;
1748
+ process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
1749
+ In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.
1750
+
1751
+ To prepare for this change:
1752
+ - If you want the current behavior, explicitly use 'sslmode=verify-full'
1753
+ - If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${sslmode}'
1754
+
1755
+ See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`);
1756
+ }
1757
+ }
1774
1758
  module2.exports = parse;
1775
1759
  parse.parse = parse;
1776
1760
  parse.toClientConfig = toClientConfig;
@@ -1786,13 +1770,16 @@ var require_connection_parameters = __commonJS({
1786
1770
  var defaults2 = require_defaults();
1787
1771
  var parse = require_pg_connection_string().parse;
1788
1772
  var val = function(key, config, envVar) {
1773
+ if (config[key]) {
1774
+ return config[key];
1775
+ }
1789
1776
  if (envVar === void 0) {
1790
1777
  envVar = process.env["PG" + key.toUpperCase()];
1791
1778
  } else if (envVar === false) {
1792
1779
  } else {
1793
1780
  envVar = process.env[envVar];
1794
1781
  }
1795
- return config[key] || envVar || defaults2[key];
1782
+ return envVar || defaults2[key];
1796
1783
  };
1797
1784
  var readSSLConfigFromEnvironment = function() {
1798
1785
  switch (process.env.PGSSLMODE) {
@@ -1852,6 +1839,15 @@ var require_connection_parameters = __commonJS({
1852
1839
  enumerable: false
1853
1840
  });
1854
1841
  }
1842
+ this.sslnegotiation = val("sslnegotiation", config, "PGSSLNEGOTIATION");
1843
+ if (this.sslnegotiation !== void 0 && this.sslnegotiation !== "postgres" && this.sslnegotiation !== "direct") {
1844
+ throw new Error(
1845
+ `Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".`
1846
+ );
1847
+ }
1848
+ if (this.sslnegotiation === "direct" && !this.ssl) {
1849
+ throw new Error("sslnegotiation=direct requires SSL to be enabled");
1850
+ }
1855
1851
  this.client_encoding = val("client_encoding", config);
1856
1852
  this.replication = val("replication", config);
1857
1853
  this.isDomainSocket = !(this.host || "").indexOf("/");
@@ -1890,6 +1886,7 @@ var require_connection_parameters = __commonJS({
1890
1886
  add(params, ssl, "sslkey");
1891
1887
  add(params, ssl, "sslcert");
1892
1888
  add(params, ssl, "sslrootcert");
1889
+ add(params, this, "sslnegotiation");
1893
1890
  if (this.database) {
1894
1891
  params.push("dbname=" + quoteParamValue(this.database));
1895
1892
  }
@@ -1990,7 +1987,7 @@ var require_result = __commonJS({
1990
1987
  if (this.fields.length) {
1991
1988
  this._parsers = new Array(fieldDescriptions.length);
1992
1989
  }
1993
- const row = {};
1990
+ const row = /* @__PURE__ */ Object.create(null);
1994
1991
  for (let i = 0; i < fieldDescriptions.length; i++) {
1995
1992
  const desc = fieldDescriptions[i];
1996
1993
  row[desc.name] = null;
@@ -2185,6 +2182,8 @@ var require_query = __commonJS({
2185
2182
  valueMapper: utils.prepareValue
2186
2183
  });
2187
2184
  } catch (err) {
2185
+ connection.close({ type: "S", name: this.name });
2186
+ connection.sync();
2188
2187
  this.handleError(err, connection);
2189
2188
  return;
2190
2189
  }
@@ -2204,9 +2203,9 @@ var require_query = __commonJS({
2204
2203
  }
2205
2204
  });
2206
2205
 
2207
- // ../../node_modules/pg-protocol/dist/messages.js
2206
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/messages.js
2208
2207
  var require_messages = __commonJS({
2209
- "../../node_modules/pg-protocol/dist/messages.js"(exports2) {
2208
+ "../../node_modules/pg/node_modules/pg-protocol/dist/messages.js"(exports2) {
2210
2209
  "use strict";
2211
2210
  Object.defineProperty(exports2, "__esModule", { value: true });
2212
2211
  exports2.NoticeMessage = exports2.DataRowMessage = exports2.CommandCompleteMessage = exports2.ReadyForQueryMessage = exports2.NotificationResponseMessage = exports2.BackendKeyDataMessage = exports2.AuthenticationMD5Password = exports2.ParameterStatusMessage = exports2.ParameterDescriptionMessage = exports2.RowDescriptionMessage = exports2.Field = exports2.CopyResponse = exports2.CopyDataMessage = exports2.DatabaseError = exports2.copyDone = exports2.emptyQuery = exports2.replicationStart = exports2.portalSuspended = exports2.noData = exports2.closeComplete = exports2.bindComplete = exports2.parseComplete = void 0;
@@ -2369,9 +2368,9 @@ var require_messages = __commonJS({
2369
2368
  }
2370
2369
  });
2371
2370
 
2372
- // ../../node_modules/pg-protocol/dist/buffer-writer.js
2371
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/buffer-writer.js
2373
2372
  var require_buffer_writer = __commonJS({
2374
- "../../node_modules/pg-protocol/dist/buffer-writer.js"(exports2) {
2373
+ "../../node_modules/pg/node_modules/pg-protocol/dist/buffer-writer.js"(exports2) {
2375
2374
  "use strict";
2376
2375
  Object.defineProperty(exports2, "__esModule", { value: true });
2377
2376
  exports2.Writer = void 0;
@@ -2424,6 +2423,25 @@ var require_buffer_writer = __commonJS({
2424
2423
  this.offset += len;
2425
2424
  return this;
2426
2425
  }
2426
+ // Write an Int32 byte-length prefix immediately followed by the string's UTF-8
2427
+ // bytes. Postgres' Bind wire format prefixes every parameter with its length,
2428
+ // and doing it in one method computes Buffer.byteLength ONCE — the previous
2429
+ // `addInt32(Buffer.byteLength(s)).addString(s)` pairing scanned the string
2430
+ // three times (byteLength for the prefix, byteLength again inside addString,
2431
+ // then the encode), which is costly for large text parameters.
2432
+ addInt32PrefixedString(string) {
2433
+ const len = Buffer.byteLength(string);
2434
+ this.ensure(4 + len);
2435
+ const buffer = this.buffer;
2436
+ let offset = this.offset;
2437
+ buffer[offset++] = len >>> 24 & 255;
2438
+ buffer[offset++] = len >>> 16 & 255;
2439
+ buffer[offset++] = len >>> 8 & 255;
2440
+ buffer[offset++] = len >>> 0 & 255;
2441
+ buffer.write(string, offset, "utf-8");
2442
+ this.offset = offset + len;
2443
+ return this;
2444
+ }
2427
2445
  add(otherBuffer) {
2428
2446
  this.ensure(otherBuffer.length);
2429
2447
  otherBuffer.copy(this.buffer, this.offset);
@@ -2445,14 +2463,18 @@ var require_buffer_writer = __commonJS({
2445
2463
  this.buffer = Buffer.allocUnsafe(this.size);
2446
2464
  return result;
2447
2465
  }
2466
+ clear() {
2467
+ this.offset = 5;
2468
+ this.headerPosition = 0;
2469
+ }
2448
2470
  };
2449
2471
  exports2.Writer = Writer;
2450
2472
  }
2451
2473
  });
2452
2474
 
2453
- // ../../node_modules/pg-protocol/dist/serializer.js
2475
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/serializer.js
2454
2476
  var require_serializer = __commonJS({
2455
- "../../node_modules/pg-protocol/dist/serializer.js"(exports2) {
2477
+ "../../node_modules/pg/node_modules/pg-protocol/dist/serializer.js"(exports2) {
2456
2478
  "use strict";
2457
2479
  Object.defineProperty(exports2, "__esModule", { value: true });
2458
2480
  exports2.serialize = void 0;
@@ -2481,7 +2503,7 @@ var require_serializer = __commonJS({
2481
2503
  );
2482
2504
  };
2483
2505
  var sendSASLInitialResponseMessage = function(mechanism, initialResponse) {
2484
- writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse);
2506
+ writer.addCString(mechanism).addInt32PrefixedString(initialResponse);
2485
2507
  return writer.flush(
2486
2508
  112
2487
2509
  /* code.startup */
@@ -2540,8 +2562,7 @@ var require_serializer = __commonJS({
2540
2562
  0
2541
2563
  /* ParamType.STRING */
2542
2564
  );
2543
- paramWriter.addInt32(Buffer.byteLength(mappedVal));
2544
- paramWriter.addString(mappedVal);
2565
+ paramWriter.addInt32PrefixedString(mappedVal);
2545
2566
  }
2546
2567
  }
2547
2568
  };
@@ -2553,7 +2574,13 @@ var require_serializer = __commonJS({
2553
2574
  const len = values.length;
2554
2575
  writer.addCString(portal).addCString(statement);
2555
2576
  writer.addInt16(len);
2556
- writeValues(values, config.valueMapper);
2577
+ try {
2578
+ writeValues(values, config.valueMapper);
2579
+ } catch (err) {
2580
+ writer.clear();
2581
+ paramWriter.clear();
2582
+ throw err;
2583
+ }
2557
2584
  writer.addInt16(len);
2558
2585
  writer.add(paramWriter.flush());
2559
2586
  writer.addInt16(1);
@@ -2667,17 +2694,16 @@ var require_serializer = __commonJS({
2667
2694
  }
2668
2695
  });
2669
2696
 
2670
- // ../../node_modules/pg-protocol/dist/buffer-reader.js
2697
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/buffer-reader.js
2671
2698
  var require_buffer_reader = __commonJS({
2672
- "../../node_modules/pg-protocol/dist/buffer-reader.js"(exports2) {
2699
+ "../../node_modules/pg/node_modules/pg-protocol/dist/buffer-reader.js"(exports2) {
2673
2700
  "use strict";
2674
2701
  Object.defineProperty(exports2, "__esModule", { value: true });
2675
2702
  exports2.BufferReader = void 0;
2676
- var emptyBuffer = Buffer.allocUnsafe(0);
2677
2703
  var BufferReader = class {
2678
2704
  constructor(offset = 0) {
2679
2705
  this.offset = offset;
2680
- this.buffer = emptyBuffer;
2706
+ this.buffer = Buffer.allocUnsafe(0);
2681
2707
  this.encoding = "utf-8";
2682
2708
  }
2683
2709
  setBuffer(offset, buffer) {
@@ -2712,7 +2738,7 @@ var require_buffer_reader = __commonJS({
2712
2738
  cstring() {
2713
2739
  const start = this.offset;
2714
2740
  let end = start;
2715
- while (this.buffer[end++] !== 0) {
2741
+ while (this.buffer[end++]) {
2716
2742
  }
2717
2743
  this.offset = end;
2718
2744
  return this.buffer.toString(this.encoding, start, end - 1);
@@ -2727,9 +2753,9 @@ var require_buffer_reader = __commonJS({
2727
2753
  }
2728
2754
  });
2729
2755
 
2730
- // ../../node_modules/pg-protocol/dist/parser.js
2756
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/parser.js
2731
2757
  var require_parser = __commonJS({
2732
- "../../node_modules/pg-protocol/dist/parser.js"(exports2) {
2758
+ "../../node_modules/pg/node_modules/pg-protocol/dist/parser.js"(exports2) {
2733
2759
  "use strict";
2734
2760
  Object.defineProperty(exports2, "__esModule", { value: true });
2735
2761
  exports2.Parser = void 0;
@@ -2738,6 +2764,7 @@ var require_parser = __commonJS({
2738
2764
  var CODE_LENGTH = 1;
2739
2765
  var LEN_LENGTH = 4;
2740
2766
  var HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH;
2767
+ var LATEINIT_LENGTH = -1;
2741
2768
  var emptyBuffer = Buffer.allocUnsafe(0);
2742
2769
  var Parser = class {
2743
2770
  constructor(opts) {
@@ -2803,229 +2830,243 @@ var require_parser = __commonJS({
2803
2830
  }
2804
2831
  }
2805
2832
  handlePacket(offset, code, length, bytes) {
2833
+ const { reader } = this;
2834
+ reader.setBuffer(offset, bytes);
2835
+ let message;
2806
2836
  switch (code) {
2807
2837
  case 50:
2808
- return messages_1.bindComplete;
2838
+ message = messages_1.bindComplete;
2839
+ break;
2809
2840
  case 49:
2810
- return messages_1.parseComplete;
2841
+ message = messages_1.parseComplete;
2842
+ break;
2811
2843
  case 51:
2812
- return messages_1.closeComplete;
2844
+ message = messages_1.closeComplete;
2845
+ break;
2813
2846
  case 110:
2814
- return messages_1.noData;
2847
+ message = messages_1.noData;
2848
+ break;
2815
2849
  case 115:
2816
- return messages_1.portalSuspended;
2850
+ message = messages_1.portalSuspended;
2851
+ break;
2817
2852
  case 99:
2818
- return messages_1.copyDone;
2853
+ message = messages_1.copyDone;
2854
+ break;
2819
2855
  case 87:
2820
- return messages_1.replicationStart;
2856
+ message = messages_1.replicationStart;
2857
+ break;
2821
2858
  case 73:
2822
- return messages_1.emptyQuery;
2859
+ message = messages_1.emptyQuery;
2860
+ break;
2823
2861
  case 68:
2824
- return this.parseDataRowMessage(offset, length, bytes);
2862
+ message = parseDataRowMessage(reader);
2863
+ break;
2825
2864
  case 67:
2826
- return this.parseCommandCompleteMessage(offset, length, bytes);
2865
+ message = parseCommandCompleteMessage(reader);
2866
+ break;
2827
2867
  case 90:
2828
- return this.parseReadyForQueryMessage(offset, length, bytes);
2868
+ message = parseReadyForQueryMessage(reader);
2869
+ break;
2829
2870
  case 65:
2830
- return this.parseNotificationMessage(offset, length, bytes);
2871
+ message = parseNotificationMessage(reader);
2872
+ break;
2831
2873
  case 82:
2832
- return this.parseAuthenticationResponse(offset, length, bytes);
2874
+ message = parseAuthenticationResponse(reader, length);
2875
+ break;
2833
2876
  case 83:
2834
- return this.parseParameterStatusMessage(offset, length, bytes);
2877
+ message = parseParameterStatusMessage(reader);
2878
+ break;
2835
2879
  case 75:
2836
- return this.parseBackendKeyData(offset, length, bytes);
2880
+ message = parseBackendKeyData(reader);
2881
+ break;
2837
2882
  case 69:
2838
- return this.parseErrorMessage(offset, length, bytes, "error");
2883
+ message = parseErrorMessage(reader, "error");
2884
+ break;
2839
2885
  case 78:
2840
- return this.parseErrorMessage(offset, length, bytes, "notice");
2841
- case 84:
2842
- return this.parseRowDescriptionMessage(offset, length, bytes);
2843
- case 116:
2844
- return this.parseParameterDescriptionMessage(offset, length, bytes);
2845
- case 71:
2846
- return this.parseCopyInMessage(offset, length, bytes);
2847
- case 72:
2848
- return this.parseCopyOutMessage(offset, length, bytes);
2849
- case 100:
2850
- return this.parseCopyData(offset, length, bytes);
2851
- default:
2852
- return new messages_1.DatabaseError("received invalid response: " + code.toString(16), length, "error");
2853
- }
2854
- }
2855
- parseReadyForQueryMessage(offset, length, bytes) {
2856
- this.reader.setBuffer(offset, bytes);
2857
- const status = this.reader.string(1);
2858
- return new messages_1.ReadyForQueryMessage(length, status);
2859
- }
2860
- parseCommandCompleteMessage(offset, length, bytes) {
2861
- this.reader.setBuffer(offset, bytes);
2862
- const text = this.reader.cstring();
2863
- return new messages_1.CommandCompleteMessage(length, text);
2864
- }
2865
- parseCopyData(offset, length, bytes) {
2866
- const chunk = bytes.slice(offset, offset + (length - 4));
2867
- return new messages_1.CopyDataMessage(length, chunk);
2868
- }
2869
- parseCopyInMessage(offset, length, bytes) {
2870
- return this.parseCopyMessage(offset, length, bytes, "copyInResponse");
2871
- }
2872
- parseCopyOutMessage(offset, length, bytes) {
2873
- return this.parseCopyMessage(offset, length, bytes, "copyOutResponse");
2874
- }
2875
- parseCopyMessage(offset, length, bytes, messageName) {
2876
- this.reader.setBuffer(offset, bytes);
2877
- const isBinary = this.reader.byte() !== 0;
2878
- const columnCount = this.reader.int16();
2879
- const message = new messages_1.CopyResponse(length, messageName, isBinary, columnCount);
2880
- for (let i = 0; i < columnCount; i++) {
2881
- message.columnTypes[i] = this.reader.int16();
2882
- }
2883
- return message;
2884
- }
2885
- parseNotificationMessage(offset, length, bytes) {
2886
- this.reader.setBuffer(offset, bytes);
2887
- const processId = this.reader.int32();
2888
- const channel = this.reader.cstring();
2889
- const payload = this.reader.cstring();
2890
- return new messages_1.NotificationResponseMessage(length, processId, channel, payload);
2891
- }
2892
- parseRowDescriptionMessage(offset, length, bytes) {
2893
- this.reader.setBuffer(offset, bytes);
2894
- const fieldCount = this.reader.int16();
2895
- const message = new messages_1.RowDescriptionMessage(length, fieldCount);
2896
- for (let i = 0; i < fieldCount; i++) {
2897
- message.fields[i] = this.parseField();
2898
- }
2899
- return message;
2900
- }
2901
- parseField() {
2902
- const name = this.reader.cstring();
2903
- const tableID = this.reader.uint32();
2904
- const columnID = this.reader.int16();
2905
- const dataTypeID = this.reader.uint32();
2906
- const dataTypeSize = this.reader.int16();
2907
- const dataTypeModifier = this.reader.int32();
2908
- const mode = this.reader.int16() === 0 ? "text" : "binary";
2909
- return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode);
2910
- }
2911
- parseParameterDescriptionMessage(offset, length, bytes) {
2912
- this.reader.setBuffer(offset, bytes);
2913
- const parameterCount = this.reader.int16();
2914
- const message = new messages_1.ParameterDescriptionMessage(length, parameterCount);
2915
- for (let i = 0; i < parameterCount; i++) {
2916
- message.dataTypeIDs[i] = this.reader.int32();
2917
- }
2918
- return message;
2919
- }
2920
- parseDataRowMessage(offset, length, bytes) {
2921
- this.reader.setBuffer(offset, bytes);
2922
- const fieldCount = this.reader.int16();
2923
- const fields = new Array(fieldCount);
2924
- for (let i = 0; i < fieldCount; i++) {
2925
- const len = this.reader.int32();
2926
- fields[i] = len === -1 ? null : this.reader.string(len);
2927
- }
2928
- return new messages_1.DataRowMessage(length, fields);
2929
- }
2930
- parseParameterStatusMessage(offset, length, bytes) {
2931
- this.reader.setBuffer(offset, bytes);
2932
- const name = this.reader.cstring();
2933
- const value = this.reader.cstring();
2934
- return new messages_1.ParameterStatusMessage(length, name, value);
2935
- }
2936
- parseBackendKeyData(offset, length, bytes) {
2937
- this.reader.setBuffer(offset, bytes);
2938
- const processID = this.reader.int32();
2939
- const secretKey = this.reader.int32();
2940
- return new messages_1.BackendKeyDataMessage(length, processID, secretKey);
2941
- }
2942
- parseAuthenticationResponse(offset, length, bytes) {
2943
- this.reader.setBuffer(offset, bytes);
2944
- const code = this.reader.int32();
2945
- const message = {
2946
- name: "authenticationOk",
2947
- length
2948
- };
2949
- switch (code) {
2950
- case 0:
2886
+ message = parseErrorMessage(reader, "notice");
2951
2887
  break;
2952
- case 3:
2953
- if (message.length === 8) {
2954
- message.name = "authenticationCleartextPassword";
2955
- }
2888
+ case 84:
2889
+ message = parseRowDescriptionMessage(reader);
2956
2890
  break;
2957
- case 5:
2958
- if (message.length === 12) {
2959
- message.name = "authenticationMD5Password";
2960
- const salt = this.reader.bytes(4);
2961
- return new messages_1.AuthenticationMD5Password(length, salt);
2962
- }
2891
+ case 116:
2892
+ message = parseParameterDescriptionMessage(reader);
2963
2893
  break;
2964
- case 10:
2965
- {
2966
- message.name = "authenticationSASL";
2967
- message.mechanisms = [];
2968
- let mechanism;
2969
- do {
2970
- mechanism = this.reader.cstring();
2971
- if (mechanism) {
2972
- message.mechanisms.push(mechanism);
2973
- }
2974
- } while (mechanism);
2975
- }
2894
+ case 71:
2895
+ message = parseCopyInMessage(reader);
2976
2896
  break;
2977
- case 11:
2978
- message.name = "authenticationSASLContinue";
2979
- message.data = this.reader.string(length - 8);
2897
+ case 72:
2898
+ message = parseCopyOutMessage(reader);
2980
2899
  break;
2981
- case 12:
2982
- message.name = "authenticationSASLFinal";
2983
- message.data = this.reader.string(length - 8);
2900
+ case 100:
2901
+ message = parseCopyData(reader, length);
2984
2902
  break;
2985
2903
  default:
2986
- throw new Error("Unknown authenticationOk message type " + code);
2904
+ return new messages_1.DatabaseError("received invalid response: " + code.toString(16), length, "error");
2987
2905
  }
2988
- return message;
2989
- }
2990
- parseErrorMessage(offset, length, bytes, name) {
2991
- this.reader.setBuffer(offset, bytes);
2992
- const fields = {};
2993
- let fieldType = this.reader.string(1);
2994
- while (fieldType !== "\0") {
2995
- fields[fieldType] = this.reader.cstring();
2996
- fieldType = this.reader.string(1);
2997
- }
2998
- const messageValue = fields.M;
2999
- const message = name === "notice" ? new messages_1.NoticeMessage(length, messageValue) : new messages_1.DatabaseError(messageValue, length, name);
3000
- message.severity = fields.S;
3001
- message.code = fields.C;
3002
- message.detail = fields.D;
3003
- message.hint = fields.H;
3004
- message.position = fields.P;
3005
- message.internalPosition = fields.p;
3006
- message.internalQuery = fields.q;
3007
- message.where = fields.W;
3008
- message.schema = fields.s;
3009
- message.table = fields.t;
3010
- message.column = fields.c;
3011
- message.dataType = fields.d;
3012
- message.constraint = fields.n;
3013
- message.file = fields.F;
3014
- message.line = fields.L;
3015
- message.routine = fields.R;
2906
+ reader.setBuffer(0, emptyBuffer);
2907
+ message.length = length;
3016
2908
  return message;
3017
2909
  }
3018
2910
  };
3019
2911
  exports2.Parser = Parser;
2912
+ var parseReadyForQueryMessage = (reader) => {
2913
+ const status = reader.string(1);
2914
+ return new messages_1.ReadyForQueryMessage(LATEINIT_LENGTH, status);
2915
+ };
2916
+ var parseCommandCompleteMessage = (reader) => {
2917
+ const text = reader.cstring();
2918
+ return new messages_1.CommandCompleteMessage(LATEINIT_LENGTH, text);
2919
+ };
2920
+ var parseCopyData = (reader, length) => {
2921
+ const chunk = reader.bytes(length - 4);
2922
+ return new messages_1.CopyDataMessage(LATEINIT_LENGTH, chunk);
2923
+ };
2924
+ var parseCopyInMessage = (reader) => parseCopyMessage(reader, "copyInResponse");
2925
+ var parseCopyOutMessage = (reader) => parseCopyMessage(reader, "copyOutResponse");
2926
+ var parseCopyMessage = (reader, messageName) => {
2927
+ const isBinary = reader.byte() !== 0;
2928
+ const columnCount = reader.int16();
2929
+ const message = new messages_1.CopyResponse(LATEINIT_LENGTH, messageName, isBinary, columnCount);
2930
+ for (let i = 0; i < columnCount; i++) {
2931
+ message.columnTypes[i] = reader.int16();
2932
+ }
2933
+ return message;
2934
+ };
2935
+ var parseNotificationMessage = (reader) => {
2936
+ const processId = reader.int32();
2937
+ const channel = reader.cstring();
2938
+ const payload = reader.cstring();
2939
+ return new messages_1.NotificationResponseMessage(LATEINIT_LENGTH, processId, channel, payload);
2940
+ };
2941
+ var parseRowDescriptionMessage = (reader) => {
2942
+ const fieldCount = reader.int16();
2943
+ const message = new messages_1.RowDescriptionMessage(LATEINIT_LENGTH, fieldCount);
2944
+ for (let i = 0; i < fieldCount; i++) {
2945
+ message.fields[i] = parseField(reader);
2946
+ }
2947
+ return message;
2948
+ };
2949
+ var parseField = (reader) => {
2950
+ const name = reader.cstring();
2951
+ const tableID = reader.uint32();
2952
+ const columnID = reader.int16();
2953
+ const dataTypeID = reader.uint32();
2954
+ const dataTypeSize = reader.int16();
2955
+ const dataTypeModifier = reader.int32();
2956
+ const mode = reader.int16() === 0 ? "text" : "binary";
2957
+ return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode);
2958
+ };
2959
+ var parseParameterDescriptionMessage = (reader) => {
2960
+ const parameterCount = reader.int16();
2961
+ const message = new messages_1.ParameterDescriptionMessage(LATEINIT_LENGTH, parameterCount);
2962
+ for (let i = 0; i < parameterCount; i++) {
2963
+ message.dataTypeIDs[i] = reader.int32();
2964
+ }
2965
+ return message;
2966
+ };
2967
+ var parseDataRowMessage = (reader) => {
2968
+ const fieldCount = reader.int16();
2969
+ const fields = new Array(fieldCount);
2970
+ for (let i = 0; i < fieldCount; i++) {
2971
+ const len = reader.int32();
2972
+ fields[i] = len === -1 ? null : reader.string(len);
2973
+ }
2974
+ return new messages_1.DataRowMessage(LATEINIT_LENGTH, fields);
2975
+ };
2976
+ var parseParameterStatusMessage = (reader) => {
2977
+ const name = reader.cstring();
2978
+ const value = reader.cstring();
2979
+ return new messages_1.ParameterStatusMessage(LATEINIT_LENGTH, name, value);
2980
+ };
2981
+ var parseBackendKeyData = (reader) => {
2982
+ const processID = reader.int32();
2983
+ const secretKey = reader.int32();
2984
+ return new messages_1.BackendKeyDataMessage(LATEINIT_LENGTH, processID, secretKey);
2985
+ };
2986
+ var parseAuthenticationResponse = (reader, length) => {
2987
+ const code = reader.int32();
2988
+ const message = {
2989
+ name: "authenticationOk",
2990
+ length
2991
+ };
2992
+ switch (code) {
2993
+ case 0:
2994
+ break;
2995
+ case 3:
2996
+ if (message.length === 8) {
2997
+ message.name = "authenticationCleartextPassword";
2998
+ }
2999
+ break;
3000
+ case 5:
3001
+ if (message.length === 12) {
3002
+ message.name = "authenticationMD5Password";
3003
+ const salt = reader.bytes(4);
3004
+ return new messages_1.AuthenticationMD5Password(LATEINIT_LENGTH, salt);
3005
+ }
3006
+ break;
3007
+ case 10:
3008
+ {
3009
+ message.name = "authenticationSASL";
3010
+ message.mechanisms = [];
3011
+ let mechanism;
3012
+ do {
3013
+ mechanism = reader.cstring();
3014
+ if (mechanism) {
3015
+ message.mechanisms.push(mechanism);
3016
+ }
3017
+ } while (mechanism);
3018
+ }
3019
+ break;
3020
+ case 11:
3021
+ message.name = "authenticationSASLContinue";
3022
+ message.data = reader.string(length - 8);
3023
+ break;
3024
+ case 12:
3025
+ message.name = "authenticationSASLFinal";
3026
+ message.data = reader.string(length - 8);
3027
+ break;
3028
+ default:
3029
+ throw new Error("Unknown authenticationOk message type " + code);
3030
+ }
3031
+ return message;
3032
+ };
3033
+ var parseErrorMessage = (reader, name) => {
3034
+ const fields = {};
3035
+ let fieldType = reader.string(1);
3036
+ while (fieldType !== "\0") {
3037
+ fields[fieldType] = reader.cstring();
3038
+ fieldType = reader.string(1);
3039
+ }
3040
+ const messageValue = fields.M;
3041
+ const message = name === "notice" ? new messages_1.NoticeMessage(LATEINIT_LENGTH, messageValue) : new messages_1.DatabaseError(messageValue, LATEINIT_LENGTH, name);
3042
+ message.severity = fields.S;
3043
+ message.code = fields.C;
3044
+ message.detail = fields.D;
3045
+ message.hint = fields.H;
3046
+ message.position = fields.P;
3047
+ message.internalPosition = fields.p;
3048
+ message.internalQuery = fields.q;
3049
+ message.where = fields.W;
3050
+ message.schema = fields.s;
3051
+ message.table = fields.t;
3052
+ message.column = fields.c;
3053
+ message.dataType = fields.d;
3054
+ message.constraint = fields.n;
3055
+ message.file = fields.F;
3056
+ message.line = fields.L;
3057
+ message.routine = fields.R;
3058
+ return message;
3059
+ };
3020
3060
  }
3021
3061
  });
3022
3062
 
3023
- // ../../node_modules/pg-protocol/dist/index.js
3063
+ // ../../node_modules/pg/node_modules/pg-protocol/dist/index.js
3024
3064
  var require_dist = __commonJS({
3025
- "../../node_modules/pg-protocol/dist/index.js"(exports2) {
3065
+ "../../node_modules/pg/node_modules/pg-protocol/dist/index.js"(exports2) {
3026
3066
  "use strict";
3027
3067
  Object.defineProperty(exports2, "__esModule", { value: true });
3028
- exports2.DatabaseError = exports2.serialize = exports2.parse = void 0;
3068
+ exports2.DatabaseError = exports2.serialize = void 0;
3069
+ exports2.parse = parse;
3029
3070
  var messages_1 = require_messages();
3030
3071
  Object.defineProperty(exports2, "DatabaseError", { enumerable: true, get: function() {
3031
3072
  return messages_1.DatabaseError;
@@ -3040,7 +3081,6 @@ var require_dist = __commonJS({
3040
3081
  stream.on("data", (buffer) => parser.parse(buffer, callback));
3041
3082
  return new Promise((resolve) => stream.on("end", () => resolve()));
3042
3083
  }
3043
- exports2.parse = parse;
3044
3084
  }
3045
3085
  });
3046
3086
 
@@ -3126,7 +3166,8 @@ var require_connection = __commonJS({
3126
3166
  "use strict";
3127
3167
  var EventEmitter = require("events").EventEmitter;
3128
3168
  var { parse, serialize } = require_dist();
3129
- var { getStream, getSecureStream } = require_stream();
3169
+ var stream = require_stream();
3170
+ var { getStream } = stream;
3130
3171
  var flushBuffer = serialize.flush();
3131
3172
  var syncBuffer = serialize.sync();
3132
3173
  var endBuffer = serialize.end();
@@ -3140,9 +3181,9 @@ var require_connection = __commonJS({
3140
3181
  }
3141
3182
  this._keepAlive = config.keepAlive;
3142
3183
  this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis;
3143
- this.lastBuffer = false;
3144
3184
  this.parsedStatements = {};
3145
3185
  this.ssl = config.ssl || false;
3186
+ this.sslNegotiation = config.sslNegotiation || "postgres";
3146
3187
  this._ending = false;
3147
3188
  this._emitMessage = false;
3148
3189
  const self = this;
@@ -3176,6 +3217,11 @@ var require_connection = __commonJS({
3176
3217
  if (!this.ssl) {
3177
3218
  return this.attachListeners(this.stream);
3178
3219
  }
3220
+ if (this.sslNegotiation === "direct") {
3221
+ return this.stream.once("connect", function() {
3222
+ self.upgradeToSSL(host, reportStreamError);
3223
+ });
3224
+ }
3179
3225
  this.stream.once("data", function(buffer) {
3180
3226
  const responseCode = buffer.toString("utf8");
3181
3227
  switch (responseCode) {
@@ -3188,31 +3234,38 @@ var require_connection = __commonJS({
3188
3234
  self.stream.end();
3189
3235
  return self.emit("error", new Error("There was an error establishing an SSL connection"));
3190
3236
  }
3191
- const options = {
3192
- socket: self.stream
3193
- };
3194
- if (self.ssl !== true) {
3195
- Object.assign(options, self.ssl);
3196
- if ("key" in self.ssl) {
3197
- options.key = self.ssl.key;
3198
- }
3199
- }
3200
- const net = require("net");
3201
- if (net.isIP && net.isIP(host) === 0) {
3202
- options.servername = host;
3203
- }
3204
- try {
3205
- self.stream = getSecureStream(options);
3206
- } catch (err) {
3207
- return self.emit("error", err);
3208
- }
3209
- self.attachListeners(self.stream);
3210
- self.stream.on("error", reportStreamError);
3211
- self.emit("sslconnect");
3237
+ self.upgradeToSSL(host, reportStreamError);
3212
3238
  });
3213
3239
  }
3214
- attachListeners(stream) {
3215
- parse(stream, (msg) => {
3240
+ upgradeToSSL(host, reportStreamError) {
3241
+ const self = this;
3242
+ const options = {
3243
+ socket: self.stream
3244
+ };
3245
+ if (self.ssl !== true) {
3246
+ Object.assign(options, self.ssl);
3247
+ if ("key" in self.ssl) {
3248
+ options.key = self.ssl.key;
3249
+ }
3250
+ }
3251
+ if (self.sslNegotiation === "direct") {
3252
+ options.ALPNProtocols = ["postgresql"];
3253
+ }
3254
+ const net = require("net");
3255
+ if (net.isIP && net.isIP(host) === 0) {
3256
+ options.servername = host;
3257
+ }
3258
+ try {
3259
+ self.stream = stream.getSecureStream(options);
3260
+ } catch (err) {
3261
+ return self.emit("error", err);
3262
+ }
3263
+ self.attachListeners(self.stream);
3264
+ self.stream.on("error", reportStreamError);
3265
+ self.emit("sslconnect");
3266
+ }
3267
+ attachListeners(stream2) {
3268
+ parse(stream2, (msg) => {
3216
3269
  const eventName = msg.name === "error" ? "errorMessage" : msg.name;
3217
3270
  if (this._emitMessage) {
3218
3271
  this.emit("message", msg);
@@ -3603,6 +3656,7 @@ var require_client = __commonJS({
3603
3656
  "use strict";
3604
3657
  var EventEmitter = require("events").EventEmitter;
3605
3658
  var utils = require_utils();
3659
+ var nodeUtils = require("util");
3606
3660
  var sasl = require_sasl();
3607
3661
  var TypeOverrides2 = require_type_overrides();
3608
3662
  var ConnectionParameters = require_connection_parameters();
@@ -3610,6 +3664,41 @@ var require_client = __commonJS({
3610
3664
  var defaults2 = require_defaults();
3611
3665
  var Connection2 = require_connection();
3612
3666
  var crypto = require_utils2();
3667
+ var activeQueryDeprecationNotice = nodeUtils.deprecate(
3668
+ () => {
3669
+ },
3670
+ "Client.activeQuery is deprecated and will be removed in pg@9.0"
3671
+ );
3672
+ var queryQueueDeprecationNotice = nodeUtils.deprecate(
3673
+ () => {
3674
+ },
3675
+ "Client.queryQueue is deprecated and will be removed in pg@9.0."
3676
+ );
3677
+ var pgPassDeprecationNotice = nodeUtils.deprecate(
3678
+ () => {
3679
+ },
3680
+ "pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."
3681
+ );
3682
+ var byoPromiseDeprecationNotice = nodeUtils.deprecate(
3683
+ () => {
3684
+ },
3685
+ "Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."
3686
+ );
3687
+ var queryQueueLengthDeprecationNotice = nodeUtils.deprecate(
3688
+ () => {
3689
+ },
3690
+ "Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."
3691
+ );
3692
+ function coerceNumberOrDefault(value, defaultValue) {
3693
+ if (typeof value === "number") {
3694
+ return Number.isFinite(value) ? value : defaultValue;
3695
+ }
3696
+ if (typeof value === "string" && value.trim() !== "") {
3697
+ const n = Number(value);
3698
+ return Number.isFinite(n) ? n : defaultValue;
3699
+ }
3700
+ return defaultValue;
3701
+ }
3613
3702
  var Client2 = class extends EventEmitter {
3614
3703
  constructor(config) {
3615
3704
  super();
@@ -3626,6 +3715,9 @@ var require_client = __commonJS({
3626
3715
  });
3627
3716
  this.replication = this.connectionParameters.replication;
3628
3717
  const c = config || {};
3718
+ if (c.Promise) {
3719
+ byoPromiseDeprecationNotice();
3720
+ }
3629
3721
  this._Promise = c.Promise || global.Promise;
3630
3722
  this._types = new TypeOverrides2(c.types);
3631
3723
  this._ending = false;
@@ -3634,19 +3726,24 @@ var require_client = __commonJS({
3634
3726
  this._connected = false;
3635
3727
  this._connectionError = false;
3636
3728
  this._queryable = true;
3729
+ this._activeQuery = null;
3730
+ this._txStatus = null;
3637
3731
  this.enableChannelBinding = Boolean(c.enableChannelBinding);
3732
+ this.scramMaxIterations = coerceNumberOrDefault(c.scramMaxIterations, sasl.DEFAULT_MAX_SCRAM_ITERATIONS);
3638
3733
  this.connection = c.connection || new Connection2({
3639
3734
  stream: c.stream,
3640
3735
  ssl: this.connectionParameters.ssl,
3736
+ sslNegotiation: this.connectionParameters.sslnegotiation,
3641
3737
  keepAlive: c.keepAlive || false,
3642
3738
  keepAliveInitialDelayMillis: c.keepAliveInitialDelayMillis || 0,
3643
3739
  encoding: this.connectionParameters.client_encoding || "utf8"
3644
3740
  });
3645
- this.queryQueue = [];
3741
+ this._queryQueue = [];
3646
3742
  this.binary = c.binary || defaults2.binary;
3647
3743
  this.processID = null;
3648
3744
  this.secretKey = null;
3649
3745
  this.ssl = this.connectionParameters.ssl || false;
3746
+ this.sslNegotiation = this.connectionParameters.sslnegotiation || "postgres";
3650
3747
  if (this.ssl && this.ssl.key) {
3651
3748
  Object.defineProperty(this.ssl, "key", {
3652
3749
  enumerable: false
@@ -3654,18 +3751,30 @@ var require_client = __commonJS({
3654
3751
  }
3655
3752
  this._connectionTimeoutMillis = c.connectionTimeoutMillis || 0;
3656
3753
  }
3754
+ get activeQuery() {
3755
+ activeQueryDeprecationNotice();
3756
+ return this._activeQuery;
3757
+ }
3758
+ set activeQuery(val) {
3759
+ activeQueryDeprecationNotice();
3760
+ this._activeQuery = val;
3761
+ }
3762
+ _getActiveQuery() {
3763
+ return this._activeQuery;
3764
+ }
3657
3765
  _errorAllQueries(err) {
3658
3766
  const enqueueError = (query) => {
3659
3767
  process.nextTick(() => {
3660
3768
  query.handleError(err, this.connection);
3661
3769
  });
3662
3770
  };
3663
- if (this.activeQuery) {
3664
- enqueueError(this.activeQuery);
3665
- this.activeQuery = null;
3771
+ const activeQuery = this._getActiveQuery();
3772
+ if (activeQuery) {
3773
+ enqueueError(activeQuery);
3774
+ this._activeQuery = null;
3666
3775
  }
3667
- this.queryQueue.forEach(enqueueError);
3668
- this.queryQueue.length = 0;
3776
+ this._queryQueue.forEach(enqueueError);
3777
+ this._queryQueue.length = 0;
3669
3778
  }
3670
3779
  _connect(callback) {
3671
3780
  const self = this;
@@ -3695,7 +3804,9 @@ var require_client = __commonJS({
3695
3804
  }
3696
3805
  con.on("connect", function() {
3697
3806
  if (self.ssl) {
3698
- con.requestSsl();
3807
+ if (self.sslNegotiation !== "direct") {
3808
+ con.requestSsl();
3809
+ }
3699
3810
  } else {
3700
3811
  con.startup(self.getStartupConf());
3701
3812
  }
@@ -3735,7 +3846,7 @@ var require_client = __commonJS({
3735
3846
  if (error) {
3736
3847
  reject(error);
3737
3848
  } else {
3738
- resolve();
3849
+ resolve(this);
3739
3850
  }
3740
3851
  });
3741
3852
  });
@@ -3761,12 +3872,10 @@ var require_client = __commonJS({
3761
3872
  con.on("copyData", this._handleCopyData.bind(this));
3762
3873
  con.on("notification", this._handleNotification.bind(this));
3763
3874
  }
3764
- // TODO(bmc): deprecate pgpass "built in" integration since this.password can be a function
3765
- // it can be supplied by the user if required - this is a breaking change!
3766
- _checkPgPass(cb) {
3875
+ _getPassword(cb) {
3767
3876
  const con = this.connection;
3768
3877
  if (typeof this.password === "function") {
3769
- this._Promise.resolve().then(() => this.password()).then((pass) => {
3878
+ this._Promise.resolve().then(() => this.password(this.connectionParameters)).then((pass) => {
3770
3879
  if (pass !== void 0) {
3771
3880
  if (typeof pass !== "string") {
3772
3881
  con.emit("error", new TypeError("Password must be a string"));
@@ -3787,6 +3896,7 @@ var require_client = __commonJS({
3787
3896
  const pgPass = require_lib();
3788
3897
  pgPass(this.connectionParameters, (pass) => {
3789
3898
  if (void 0 !== pass) {
3899
+ pgPassDeprecationNotice();
3790
3900
  this.connectionParameters.password = this.password = pass;
3791
3901
  }
3792
3902
  cb();
@@ -3797,12 +3907,12 @@ var require_client = __commonJS({
3797
3907
  }
3798
3908
  }
3799
3909
  _handleAuthCleartextPassword(msg) {
3800
- this._checkPgPass(() => {
3910
+ this._getPassword(() => {
3801
3911
  this.connection.password(this.password);
3802
3912
  });
3803
3913
  }
3804
3914
  _handleAuthMD5Password(msg) {
3805
- this._checkPgPass(async () => {
3915
+ this._getPassword(async () => {
3806
3916
  try {
3807
3917
  const hashedPassword = await crypto.postgresMd5PasswordHash(this.user, this.password, msg.salt);
3808
3918
  this.connection.password(hashedPassword);
@@ -3812,9 +3922,13 @@ var require_client = __commonJS({
3812
3922
  });
3813
3923
  }
3814
3924
  _handleAuthSASL(msg) {
3815
- this._checkPgPass(() => {
3925
+ this._getPassword(() => {
3816
3926
  try {
3817
- this.saslSession = sasl.startSession(msg.mechanisms, this.enableChannelBinding && this.connection.stream);
3927
+ this.saslSession = sasl.startSession(
3928
+ msg.mechanisms,
3929
+ this.enableChannelBinding && this.connection.stream,
3930
+ this.scramMaxIterations
3931
+ );
3818
3932
  this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism, this.saslSession.response);
3819
3933
  } catch (err) {
3820
3934
  this.connection.emit("error", err);
@@ -3857,8 +3971,9 @@ var require_client = __commonJS({
3857
3971
  }
3858
3972
  this.emit("connect");
3859
3973
  }
3860
- const { activeQuery } = this;
3861
- this.activeQuery = null;
3974
+ const activeQuery = this._getActiveQuery();
3975
+ this._activeQuery = null;
3976
+ this._txStatus = msg?.status ?? null;
3862
3977
  this.readyForQuery = true;
3863
3978
  if (activeQuery) {
3864
3979
  activeQuery.handleReadyForQuery(this.connection);
@@ -3894,49 +4009,87 @@ var require_client = __commonJS({
3894
4009
  if (this._connecting) {
3895
4010
  return this._handleErrorWhileConnecting(msg);
3896
4011
  }
3897
- const activeQuery = this.activeQuery;
4012
+ const activeQuery = this._getActiveQuery();
3898
4013
  if (!activeQuery) {
3899
4014
  this._handleErrorEvent(msg);
3900
4015
  return;
3901
4016
  }
3902
- this.activeQuery = null;
4017
+ this._activeQuery = null;
3903
4018
  activeQuery.handleError(msg, this.connection);
3904
4019
  }
3905
4020
  _handleRowDescription(msg) {
3906
- this.activeQuery.handleRowDescription(msg);
4021
+ const activeQuery = this._getActiveQuery();
4022
+ if (activeQuery == null) {
4023
+ const error = new Error("Received unexpected rowDescription message from backend.");
4024
+ this._handleErrorEvent(error);
4025
+ return;
4026
+ }
4027
+ activeQuery.handleRowDescription(msg);
3907
4028
  }
3908
4029
  _handleDataRow(msg) {
3909
- this.activeQuery.handleDataRow(msg);
4030
+ const activeQuery = this._getActiveQuery();
4031
+ if (activeQuery == null) {
4032
+ const error = new Error("Received unexpected dataRow message from backend.");
4033
+ this._handleErrorEvent(error);
4034
+ return;
4035
+ }
4036
+ activeQuery.handleDataRow(msg);
3910
4037
  }
3911
4038
  _handlePortalSuspended(msg) {
3912
- this.activeQuery.handlePortalSuspended(this.connection);
4039
+ const activeQuery = this._getActiveQuery();
4040
+ if (activeQuery == null) {
4041
+ const error = new Error("Received unexpected portalSuspended message from backend.");
4042
+ this._handleErrorEvent(error);
4043
+ return;
4044
+ }
4045
+ activeQuery.handlePortalSuspended(this.connection);
3913
4046
  }
3914
4047
  _handleEmptyQuery(msg) {
3915
- this.activeQuery.handleEmptyQuery(this.connection);
4048
+ const activeQuery = this._getActiveQuery();
4049
+ if (activeQuery == null) {
4050
+ const error = new Error("Received unexpected emptyQuery message from backend.");
4051
+ this._handleErrorEvent(error);
4052
+ return;
4053
+ }
4054
+ activeQuery.handleEmptyQuery(this.connection);
3916
4055
  }
3917
4056
  _handleCommandComplete(msg) {
3918
- if (this.activeQuery == null) {
4057
+ const activeQuery = this._getActiveQuery();
4058
+ if (activeQuery == null) {
3919
4059
  const error = new Error("Received unexpected commandComplete message from backend.");
3920
4060
  this._handleErrorEvent(error);
3921
4061
  return;
3922
4062
  }
3923
- this.activeQuery.handleCommandComplete(msg, this.connection);
4063
+ activeQuery.handleCommandComplete(msg, this.connection);
3924
4064
  }
3925
4065
  _handleParseComplete() {
3926
- if (this.activeQuery == null) {
4066
+ const activeQuery = this._getActiveQuery();
4067
+ if (activeQuery == null) {
3927
4068
  const error = new Error("Received unexpected parseComplete message from backend.");
3928
4069
  this._handleErrorEvent(error);
3929
4070
  return;
3930
4071
  }
3931
- if (this.activeQuery.name) {
3932
- this.connection.parsedStatements[this.activeQuery.name] = this.activeQuery.text;
4072
+ if (activeQuery.name) {
4073
+ this.connection.parsedStatements[activeQuery.name] = activeQuery.text;
3933
4074
  }
3934
4075
  }
3935
4076
  _handleCopyInResponse(msg) {
3936
- this.activeQuery.handleCopyInResponse(this.connection);
4077
+ const activeQuery = this._getActiveQuery();
4078
+ if (activeQuery == null) {
4079
+ const error = new Error("Received unexpected copyInResponse message from backend.");
4080
+ this._handleErrorEvent(error);
4081
+ return;
4082
+ }
4083
+ activeQuery.handleCopyInResponse(this.connection);
3937
4084
  }
3938
4085
  _handleCopyData(msg) {
3939
- this.activeQuery.handleCopyData(msg, this.connection);
4086
+ const activeQuery = this._getActiveQuery();
4087
+ if (activeQuery == null) {
4088
+ const error = new Error("Received unexpected copyData message from backend.");
4089
+ this._handleErrorEvent(error);
4090
+ return;
4091
+ }
4092
+ activeQuery.handleCopyData(msg, this.connection);
3940
4093
  }
3941
4094
  _handleNotification(msg) {
3942
4095
  this.emit("notification", msg);
@@ -3982,8 +4135,8 @@ var require_client = __commonJS({
3982
4135
  con.on("connect", function() {
3983
4136
  con.cancel(client.processID, client.secretKey);
3984
4137
  });
3985
- } else if (client.queryQueue.indexOf(query) !== -1) {
3986
- client.queryQueue.splice(client.queryQueue.indexOf(query), 1);
4138
+ } else if (client._queryQueue.indexOf(query) !== -1) {
4139
+ client._queryQueue.splice(client._queryQueue.indexOf(query), 1);
3987
4140
  }
3988
4141
  }
3989
4142
  setTypeParser(oid, format, parseFn) {
@@ -4003,20 +4156,21 @@ var require_client = __commonJS({
4003
4156
  }
4004
4157
  _pulseQueryQueue() {
4005
4158
  if (this.readyForQuery === true) {
4006
- this.activeQuery = this.queryQueue.shift();
4007
- if (this.activeQuery) {
4159
+ this._activeQuery = this._queryQueue.shift();
4160
+ const activeQuery = this._getActiveQuery();
4161
+ if (activeQuery) {
4008
4162
  this.readyForQuery = false;
4009
4163
  this.hasExecuted = true;
4010
- const queryError = this.activeQuery.submit(this.connection);
4164
+ const queryError = activeQuery.submit(this.connection);
4011
4165
  if (queryError) {
4012
4166
  process.nextTick(() => {
4013
- this.activeQuery.handleError(queryError, this.connection);
4167
+ activeQuery.handleError(queryError, this.connection);
4014
4168
  this.readyForQuery = true;
4015
4169
  this._pulseQueryQueue();
4016
4170
  });
4017
4171
  }
4018
4172
  } else if (this.hasExecuted) {
4019
- this.activeQuery = null;
4173
+ this._activeQuery = null;
4020
4174
  this.emit("drain");
4021
4175
  }
4022
4176
  }
@@ -4024,19 +4178,19 @@ var require_client = __commonJS({
4024
4178
  query(config, values, callback) {
4025
4179
  let query;
4026
4180
  let result;
4027
- let readTimeout;
4028
- let readTimeoutTimer;
4029
- let queryCallback;
4030
- if (config === null || config === void 0) {
4181
+ if (config == null) {
4031
4182
  throw new TypeError("Client was passed a null or undefined query");
4032
- } else if (typeof config.submit === "function") {
4033
- readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4183
+ }
4184
+ if (typeof config.submit === "function") {
4034
4185
  result = query = config;
4035
- if (typeof values === "function") {
4036
- query.callback = query.callback || values;
4186
+ if (!query.callback) {
4187
+ if (typeof values === "function") {
4188
+ query.callback = values;
4189
+ } else if (callback) {
4190
+ query.callback = callback;
4191
+ }
4037
4192
  }
4038
4193
  } else {
4039
- readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4040
4194
  query = new Query2(config, values, callback);
4041
4195
  if (!query.callback) {
4042
4196
  result = new this._Promise((resolve, reject) => {
@@ -4045,11 +4199,15 @@ var require_client = __commonJS({
4045
4199
  Error.captureStackTrace(err);
4046
4200
  throw err;
4047
4201
  });
4202
+ } else if (typeof query.callback !== "function") {
4203
+ throw new TypeError("callback is not a function");
4048
4204
  }
4049
4205
  }
4206
+ const readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4050
4207
  if (readTimeout) {
4051
- queryCallback = query.callback;
4052
- readTimeoutTimer = setTimeout(() => {
4208
+ const queryCallback = query.callback || (() => {
4209
+ });
4210
+ const readTimeoutTimer = setTimeout(() => {
4053
4211
  const error = new Error("Query read timeout");
4054
4212
  process.nextTick(() => {
4055
4213
  query.handleError(error, this.connection);
@@ -4057,9 +4215,9 @@ var require_client = __commonJS({
4057
4215
  queryCallback(error);
4058
4216
  query.callback = () => {
4059
4217
  };
4060
- const index = this.queryQueue.indexOf(query);
4218
+ const index = this._queryQueue.indexOf(query);
4061
4219
  if (index > -1) {
4062
- this.queryQueue.splice(index, 1);
4220
+ this._queryQueue.splice(index, 1);
4063
4221
  }
4064
4222
  this._pulseQueryQueue();
4065
4223
  }, readTimeout);
@@ -4086,7 +4244,10 @@ var require_client = __commonJS({
4086
4244
  });
4087
4245
  return result;
4088
4246
  }
4089
- this.queryQueue.push(query);
4247
+ if (this._queryQueue.length > 0) {
4248
+ queryQueueLengthDeprecationNotice();
4249
+ }
4250
+ this._queryQueue.push(query);
4090
4251
  this._pulseQueryQueue();
4091
4252
  return result;
4092
4253
  }
@@ -4096,16 +4257,20 @@ var require_client = __commonJS({
4096
4257
  unref() {
4097
4258
  this.connection.unref();
4098
4259
  }
4260
+ getTransactionStatus() {
4261
+ return this._txStatus;
4262
+ }
4099
4263
  end(cb) {
4100
4264
  this._ending = true;
4101
4265
  if (!this.connection._connecting || this._ended) {
4102
4266
  if (cb) {
4103
4267
  cb();
4268
+ return;
4104
4269
  } else {
4105
4270
  return this._Promise.resolve();
4106
4271
  }
4107
4272
  }
4108
- if (this.activeQuery || !this._queryable) {
4273
+ if (this._getActiveQuery() || !this._queryable) {
4109
4274
  this.connection.stream.destroy();
4110
4275
  } else {
4111
4276
  this.connection.end();
@@ -4118,6 +4283,10 @@ var require_client = __commonJS({
4118
4283
  });
4119
4284
  }
4120
4285
  }
4286
+ get queryQueue() {
4287
+ queryQueueDeprecationNotice();
4288
+ return this._queryQueue;
4289
+ }
4121
4290
  };
4122
4291
  Client2.Query = Query2;
4123
4292
  module2.exports = Client2;
@@ -4216,6 +4385,13 @@ var require_pg_pool = __commonJS({
4216
4385
  this.ending = false;
4217
4386
  this.ended = false;
4218
4387
  }
4388
+ _promiseTry(f) {
4389
+ const Promise2 = this.Promise;
4390
+ if (typeof Promise2.try === "function") {
4391
+ return Promise2.try(f);
4392
+ }
4393
+ return new Promise2((resolve) => resolve(f()));
4394
+ }
4219
4395
  _isFull() {
4220
4396
  return this._clients.length >= this.options.max;
4221
4397
  }
@@ -4319,9 +4495,15 @@ var require_pg_pool = __commonJS({
4319
4495
  let timeoutHit = false;
4320
4496
  if (this.options.connectionTimeoutMillis) {
4321
4497
  tid = setTimeout(() => {
4322
- this.log("ending client due to timeout");
4323
- timeoutHit = true;
4324
- client.connection ? client.connection.stream.destroy() : client.end();
4498
+ if (client.connection) {
4499
+ this.log("ending client due to timeout");
4500
+ timeoutHit = true;
4501
+ client.connection.stream.destroy();
4502
+ } else if (!client.isConnected()) {
4503
+ this.log("ending client due to timeout");
4504
+ timeoutHit = true;
4505
+ client.end();
4506
+ }
4325
4507
  }, this.options.connectionTimeoutMillis);
4326
4508
  }
4327
4509
  this.log("connecting new client");
@@ -4342,27 +4524,47 @@ var require_pg_pool = __commonJS({
4342
4524
  }
4343
4525
  } else {
4344
4526
  this.log("new client connected");
4345
- if (this.options.maxLifetimeSeconds !== 0) {
4346
- const maxLifetimeTimeout = setTimeout(() => {
4347
- this.log("ending client due to expired lifetime");
4348
- this._expired.add(client);
4349
- const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client);
4350
- if (idleIndex !== -1) {
4351
- this._acquireClient(
4352
- client,
4353
- new PendingItem((err2, client2, clientRelease) => clientRelease()),
4354
- idleListener,
4355
- false
4356
- );
4527
+ if (this.options.onConnect) {
4528
+ this._promiseTry(() => this.options.onConnect(client)).then(
4529
+ () => {
4530
+ this._afterConnect(client, pendingItem, idleListener);
4531
+ },
4532
+ (hookErr) => {
4533
+ this._clients = this._clients.filter((c) => c !== client);
4534
+ client.end(() => {
4535
+ this._pulseQueue();
4536
+ if (!pendingItem.timedOut) {
4537
+ pendingItem.callback(hookErr, void 0, NOOP);
4538
+ }
4539
+ });
4357
4540
  }
4358
- }, this.options.maxLifetimeSeconds * 1e3);
4359
- maxLifetimeTimeout.unref();
4360
- client.once("end", () => clearTimeout(maxLifetimeTimeout));
4541
+ );
4542
+ return;
4361
4543
  }
4362
- return this._acquireClient(client, pendingItem, idleListener, true);
4544
+ return this._afterConnect(client, pendingItem, idleListener);
4363
4545
  }
4364
4546
  });
4365
4547
  }
4548
+ _afterConnect(client, pendingItem, idleListener) {
4549
+ if (this.options.maxLifetimeSeconds !== 0) {
4550
+ const maxLifetimeTimeout = setTimeout(() => {
4551
+ this.log("ending client due to expired lifetime");
4552
+ this._expired.add(client);
4553
+ const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client);
4554
+ if (idleIndex !== -1) {
4555
+ this._acquireClient(
4556
+ client,
4557
+ new PendingItem((err, client2, clientRelease) => clientRelease()),
4558
+ idleListener,
4559
+ false
4560
+ );
4561
+ }
4562
+ }, this.options.maxLifetimeSeconds * 1e3);
4563
+ maxLifetimeTimeout.unref();
4564
+ client.once("end", () => clearTimeout(maxLifetimeTimeout));
4565
+ }
4566
+ return this._acquireClient(client, pendingItem, idleListener, true);
4567
+ }
4366
4568
  // acquire a client for a pending work item
4367
4569
  _acquireClient(client, pendingItem, idleListener, isNew) {
4368
4570
  if (isNew) {
@@ -4423,8 +4625,10 @@ var require_pg_pool = __commonJS({
4423
4625
  let tid;
4424
4626
  if (this.options.idleTimeoutMillis && this._isAboveMin()) {
4425
4627
  tid = setTimeout(() => {
4426
- this.log("remove idle client");
4427
- this._remove(client, this._pulseQueue.bind(this));
4628
+ if (this._isAboveMin()) {
4629
+ this.log("remove idle client");
4630
+ this._remove(client, this._pulseQueue.bind(this));
4631
+ }
4428
4632
  }, this.options.idleTimeoutMillis);
4429
4633
  if (this.options.allowExitOnIdle) {
4430
4634
  tid.unref();
@@ -4660,6 +4864,7 @@ var require_query2 = __commonJS({
4660
4864
  var require_client2 = __commonJS({
4661
4865
  "../../node_modules/pg/lib/native/client.js"(exports2, module2) {
4662
4866
  "use strict";
4867
+ var nodeUtils = require("util");
4663
4868
  var Native;
4664
4869
  try {
4665
4870
  Native = require("pg-native");
@@ -4671,6 +4876,11 @@ var require_client2 = __commonJS({
4671
4876
  var util = require("util");
4672
4877
  var ConnectionParameters = require_connection_parameters();
4673
4878
  var NativeQuery = require_query2();
4879
+ var queryQueueLengthDeprecationNotice = nodeUtils.deprecate(
4880
+ () => {
4881
+ },
4882
+ "Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."
4883
+ );
4674
4884
  var Client2 = module2.exports = function(config) {
4675
4885
  EventEmitter.call(this);
4676
4886
  config = config || {};
@@ -4743,7 +4953,7 @@ var require_client2 = __commonJS({
4743
4953
  });
4744
4954
  self.emit("connect");
4745
4955
  self._pulseQueryQueue(true);
4746
- cb();
4956
+ cb(null, this);
4747
4957
  });
4748
4958
  });
4749
4959
  };
@@ -4757,7 +4967,7 @@ var require_client2 = __commonJS({
4757
4967
  if (error) {
4758
4968
  reject(error);
4759
4969
  } else {
4760
- resolve();
4970
+ resolve(this);
4761
4971
  }
4762
4972
  });
4763
4973
  });
@@ -4792,7 +5002,8 @@ var require_client2 = __commonJS({
4792
5002
  }
4793
5003
  }
4794
5004
  if (readTimeout) {
4795
- queryCallback = query.callback;
5005
+ queryCallback = query.callback || (() => {
5006
+ });
4796
5007
  readTimeoutTimer = setTimeout(() => {
4797
5008
  const error = new Error("Query read timeout");
4798
5009
  process.nextTick(() => {
@@ -4826,6 +5037,9 @@ var require_client2 = __commonJS({
4826
5037
  });
4827
5038
  return result;
4828
5039
  }
5040
+ if (this._queryQueue.length > 0) {
5041
+ queryQueueLengthDeprecationNotice();
5042
+ }
4829
5043
  this._queryQueue.push(query);
4830
5044
  this._pulseQueryQueue();
4831
5045
  return result;
@@ -4833,8 +5047,11 @@ var require_client2 = __commonJS({
4833
5047
  Client2.prototype.end = function(cb) {
4834
5048
  const self = this;
4835
5049
  this._ending = true;
4836
- if (!this._connected) {
4837
- this.once("connect", this.end.bind(this, cb));
5050
+ if (this._connecting && !this._connected) {
5051
+ this.once("connect", () => {
5052
+ this.end(() => {
5053
+ });
5054
+ });
4838
5055
  }
4839
5056
  let result;
4840
5057
  if (!cb) {
@@ -4843,6 +5060,7 @@ var require_client2 = __commonJS({
4843
5060
  });
4844
5061
  }
4845
5062
  this.native.end(function() {
5063
+ self._connected = false;
4846
5064
  self._errorAllQueries(new Error("Connection terminated"));
4847
5065
  process.nextTick(() => {
4848
5066
  self.emit("end");
@@ -4893,6 +5111,12 @@ var require_client2 = __commonJS({
4893
5111
  Client2.prototype.getTypeParser = function(oid, format) {
4894
5112
  return this._types.getTypeParser(oid, format);
4895
5113
  };
5114
+ Client2.prototype.isConnected = function() {
5115
+ return this._connected;
5116
+ };
5117
+ Client2.prototype.getTransactionStatus = function() {
5118
+ return this.native.getTransactionStatus();
5119
+ };
4896
5120
  }
4897
5121
  });
4898
5122
 
@@ -4924,9 +5148,9 @@ var require_lib2 = __commonJS({
4924
5148
  }
4925
5149
  };
4926
5150
  };
4927
- var PG = function(clientConstructor) {
5151
+ var PG = function(clientConstructor2) {
4928
5152
  this.defaults = defaults2;
4929
- this.Client = clientConstructor;
5153
+ this.Client = clientConstructor2;
4930
5154
  this.Query = this.Client.Query;
4931
5155
  this.Pool = poolFactory(this.Client);
4932
5156
  this._pools = [];
@@ -4939,29 +5163,34 @@ var require_lib2 = __commonJS({
4939
5163
  this.Result = Result2;
4940
5164
  this.utils = utils;
4941
5165
  };
4942
- if (typeof process.env.NODE_PG_FORCE_NATIVE !== "undefined") {
4943
- module2.exports = new PG(require_native());
4944
- } else {
4945
- module2.exports = new PG(Client2);
4946
- Object.defineProperty(module2.exports, "native", {
4947
- configurable: true,
4948
- enumerable: false,
4949
- get() {
4950
- let native = null;
4951
- try {
4952
- native = new PG(require_native());
4953
- } catch (err) {
4954
- if (err.code !== "MODULE_NOT_FOUND") {
4955
- throw err;
4956
- }
5166
+ var clientConstructor = Client2;
5167
+ var forceNative = false;
5168
+ try {
5169
+ forceNative = !!process.env.NODE_PG_FORCE_NATIVE;
5170
+ } catch {
5171
+ }
5172
+ if (forceNative) {
5173
+ clientConstructor = require_native();
5174
+ }
5175
+ module2.exports = new PG(clientConstructor);
5176
+ Object.defineProperty(module2.exports, "native", {
5177
+ configurable: true,
5178
+ enumerable: false,
5179
+ get() {
5180
+ let native = null;
5181
+ try {
5182
+ native = new PG(require_native());
5183
+ } catch (err) {
5184
+ if (err.code !== "MODULE_NOT_FOUND") {
5185
+ throw err;
4957
5186
  }
4958
- Object.defineProperty(module2.exports, "native", {
4959
- value: native
4960
- });
4961
- return native;
4962
5187
  }
4963
- });
4964
- }
5188
+ Object.defineProperty(module2.exports, "native", {
5189
+ value: native
5190
+ });
5191
+ return native;
5192
+ }
5193
+ });
4965
5194
  }
4966
5195
  });
4967
5196