@point-hub/papi 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/lib/index.js +1601 -929
  2. package/package.json +10 -10
package/lib/index.js CHANGED
@@ -6688,28 +6688,17 @@ var require_bson = __commonJS((exports) => {
6688
6688
  return options.stylize;
6689
6689
  }
6690
6690
  };
6691
- var validateUtf8 = function(bytes, start, end) {
6692
- let continuation = 0;
6693
- for (let i = start;i < end; i += 1) {
6694
- const byte = bytes[i];
6695
- if (continuation) {
6696
- if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
6697
- return false;
6698
- }
6699
- continuation -= 1;
6700
- } else if (byte & FIRST_BIT) {
6701
- if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
6702
- continuation = 1;
6703
- } else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
6704
- continuation = 2;
6705
- } else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
6706
- continuation = 3;
6707
- } else {
6708
- return false;
6709
- }
6691
+ var parseUtf8 = function(buffer2, start, end, fatal) {
6692
+ if (fatal) {
6693
+ TextDecoderFatal ??= new TextDecoder("utf8", { fatal: true });
6694
+ try {
6695
+ return TextDecoderFatal.decode(buffer2.subarray(start, end));
6696
+ } catch (cause) {
6697
+ throw new BSONError("Invalid UTF-8 string in BSON document", { cause });
6710
6698
  }
6711
6699
  }
6712
- return !continuation;
6700
+ TextDecoderNonFatal ??= new TextDecoder("utf8", { fatal: false });
6701
+ return TextDecoderNonFatal.decode(buffer2.subarray(start, end));
6713
6702
  };
6714
6703
  var tryReadBasicLatin = function(uint8array, start, end) {
6715
6704
  if (uint8array.length === 0) {
@@ -6772,6 +6761,31 @@ var require_bson = __commonJS((exports) => {
6772
6761
  var isDBRefLike = function(value) {
6773
6762
  return value != null && typeof value === "object" && "$id" in value && value.$id != null && "$ref" in value && typeof value.$ref === "string" && (!("$db" in value) || ("$db" in value) && typeof value.$db === "string");
6774
6763
  };
6764
+ var removeLeadingZerosAndExplicitPlus = function(str) {
6765
+ if (str === "") {
6766
+ return str;
6767
+ }
6768
+ let startIndex = 0;
6769
+ const isNegative = str[startIndex] === "-";
6770
+ const isExplicitlyPositive = str[startIndex] === "+";
6771
+ if (isExplicitlyPositive || isNegative) {
6772
+ startIndex += 1;
6773
+ }
6774
+ let foundInsignificantZero = false;
6775
+ for (;startIndex < str.length && str[startIndex] === "0"; ++startIndex) {
6776
+ foundInsignificantZero = true;
6777
+ }
6778
+ if (!foundInsignificantZero) {
6779
+ return isExplicitlyPositive ? str.slice(1) : str;
6780
+ }
6781
+ return `${isNegative ? "-" : ""}${str.length === startIndex ? "0" : str.slice(startIndex)}`;
6782
+ };
6783
+ var validateStringCharacters = function(str, radix) {
6784
+ radix = radix ?? 10;
6785
+ const validCharacters = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, radix);
6786
+ const regex = new RegExp(`[^-+${validCharacters}]`, "i");
6787
+ return regex.test(str) ? false : str;
6788
+ };
6775
6789
  var isDigit = function(value) {
6776
6790
  return !isNaN(parseInt(value, 10));
6777
6791
  };
@@ -7265,12 +7279,7 @@ var require_bson = __commonJS((exports) => {
7265
7279
  index += 4;
7266
7280
  if (stringSize <= 0 || stringSize > buffer2.length - index || buffer2[index + stringSize - 1] !== 0)
7267
7281
  throw new BSONError("bad string length in bson");
7268
- if (validation != null && validation.utf8) {
7269
- if (!validateUtf8(buffer2, index, index + stringSize - 1)) {
7270
- throw new BSONError("Invalid UTF-8 string in BSON document");
7271
- }
7272
- }
7273
- const namespace = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, false);
7282
+ const namespace = ByteUtils.toUTF8(buffer2, index, index + stringSize - 1, shouldValidateKey);
7274
7283
  index = index + stringSize;
7275
7284
  const oidBuffer = ByteUtils.allocateUnsafe(12);
7276
7285
  for (let i2 = 0;i2 < 12; i2++)
@@ -8071,6 +8080,84 @@ var require_bson = __commonJS((exports) => {
8071
8080
  options = options || {};
8072
8081
  return parse(JSON.stringify(ejson), options);
8073
8082
  };
8083
+ var getSize = function(source, offset) {
8084
+ try {
8085
+ return NumberUtils.getNonnegativeInt32LE(source, offset);
8086
+ } catch (cause) {
8087
+ throw new BSONOffsetError("BSON size cannot be negative", offset, { cause });
8088
+ }
8089
+ };
8090
+ var findNull = function(bytes, offset) {
8091
+ let nullTerminatorOffset = offset;
8092
+ for (;bytes[nullTerminatorOffset] !== 0; nullTerminatorOffset++)
8093
+ ;
8094
+ if (nullTerminatorOffset === bytes.length - 1) {
8095
+ throw new BSONOffsetError("Null terminator not found", offset);
8096
+ }
8097
+ return nullTerminatorOffset;
8098
+ };
8099
+ var parseToElements = function(bytes, startOffset = 0) {
8100
+ startOffset ??= 0;
8101
+ if (bytes.length < 5) {
8102
+ throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
8103
+ }
8104
+ const documentSize = getSize(bytes, startOffset);
8105
+ if (documentSize > bytes.length - startOffset) {
8106
+ throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
8107
+ }
8108
+ if (bytes[startOffset + documentSize - 1] !== 0) {
8109
+ throw new BSONOffsetError("BSON documents must end in 0x00", startOffset + documentSize);
8110
+ }
8111
+ const elements = [];
8112
+ let offset = startOffset + 4;
8113
+ while (offset <= documentSize + startOffset) {
8114
+ const type = bytes[offset];
8115
+ offset += 1;
8116
+ if (type === 0) {
8117
+ if (offset - startOffset !== documentSize) {
8118
+ throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
8119
+ }
8120
+ break;
8121
+ }
8122
+ const nameOffset = offset;
8123
+ const nameLength = findNull(bytes, offset) - nameOffset;
8124
+ offset += nameLength + 1;
8125
+ let length;
8126
+ if (type === 1 || type === 18 || type === 9 || type === 17) {
8127
+ length = 8;
8128
+ } else if (type === 16) {
8129
+ length = 4;
8130
+ } else if (type === 7) {
8131
+ length = 12;
8132
+ } else if (type === 19) {
8133
+ length = 16;
8134
+ } else if (type === 8) {
8135
+ length = 1;
8136
+ } else if (type === 10 || type === 6 || type === 127 || type === 255) {
8137
+ length = 0;
8138
+ } else if (type === 11) {
8139
+ length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
8140
+ } else if (type === 3 || type === 4 || type === 15) {
8141
+ length = getSize(bytes, offset);
8142
+ } else if (type === 2 || type === 5 || type === 12 || type === 13 || type === 14) {
8143
+ length = getSize(bytes, offset) + 4;
8144
+ if (type === 5) {
8145
+ length += 1;
8146
+ }
8147
+ if (type === 12) {
8148
+ length += 12;
8149
+ }
8150
+ } else {
8151
+ throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, "0")} type byte`, offset);
8152
+ }
8153
+ if (length > documentSize) {
8154
+ throw new BSONOffsetError("value reports length larger than document", offset);
8155
+ }
8156
+ elements.push([type, nameOffset, nameLength, offset, length]);
8157
+ offset += length;
8158
+ }
8159
+ return elements;
8160
+ };
8074
8161
  var setInternalBufferSize = function(size) {
8075
8162
  if (buffer.length < size) {
8076
8163
  buffer = ByteUtils.allocate(size);
@@ -8205,15 +8292,18 @@ var require_bson = __commonJS((exports) => {
8205
8292
  super(message);
8206
8293
  }
8207
8294
  }
8208
- var FIRST_BIT = 128;
8209
- var FIRST_TWO_BITS = 192;
8210
- var FIRST_THREE_BITS = 224;
8211
- var FIRST_FOUR_BITS = 240;
8212
- var FIRST_FIVE_BITS = 248;
8213
- var TWO_BIT_CHAR = 192;
8214
- var THREE_BIT_CHAR = 224;
8215
- var FOUR_BIT_CHAR = 240;
8216
- var CONTINUING_CHAR = 128;
8295
+
8296
+ class BSONOffsetError extends BSONError {
8297
+ get name() {
8298
+ return "BSONOffsetError";
8299
+ }
8300
+ constructor(message, offset, options) {
8301
+ super(`${message}. offset: ${offset}`, options);
8302
+ this.offset = offset;
8303
+ }
8304
+ }
8305
+ var TextDecoderFatal;
8306
+ var TextDecoderNonFatal;
8217
8307
  var nodejsRandomBytes = (() => {
8218
8308
  try {
8219
8309
  return import.meta.require("crypto").randomBytes;
@@ -8274,9 +8364,7 @@ var require_bson = __commonJS((exports) => {
8274
8364
  if (fatal) {
8275
8365
  for (let i = 0;i < string.length; i++) {
8276
8366
  if (string.charCodeAt(i) === 65533) {
8277
- if (!validateUtf8(buffer2, start, end)) {
8278
- throw new BSONError("Invalid UTF-8 string in BSON document");
8279
- }
8367
+ parseUtf8(buffer2, start, end, true);
8280
8368
  break;
8281
8369
  }
8282
8370
  }
@@ -8384,14 +8472,7 @@ var require_bson = __commonJS((exports) => {
8384
8472
  if (basicLatin != null) {
8385
8473
  return basicLatin;
8386
8474
  }
8387
- if (fatal) {
8388
- try {
8389
- return new TextDecoder("utf8", { fatal }).decode(uint8array.slice(start, end));
8390
- } catch (cause) {
8391
- throw new BSONError("Invalid UTF-8 string in BSON document", { cause });
8392
- }
8393
- }
8394
- return new TextDecoder("utf8", { fatal }).decode(uint8array.slice(start, end));
8475
+ return parseUtf8(uint8array, start, end, fatal);
8395
8476
  },
8396
8477
  utf8ByteLength(input) {
8397
8478
  return new TextEncoder().encode(input).byteLength;
@@ -8483,16 +8564,16 @@ var require_bson = __commonJS((exports) => {
8483
8564
  return this.position;
8484
8565
  }
8485
8566
  toJSON() {
8486
- return ByteUtils.toBase64(this.buffer);
8567
+ return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
8487
8568
  }
8488
8569
  toString(encoding) {
8489
8570
  if (encoding === "hex")
8490
- return ByteUtils.toHex(this.buffer);
8571
+ return ByteUtils.toHex(this.buffer.subarray(0, this.position));
8491
8572
  if (encoding === "base64")
8492
- return ByteUtils.toBase64(this.buffer);
8573
+ return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
8493
8574
  if (encoding === "utf8" || encoding === "utf-8")
8494
- return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false);
8495
- return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength, false);
8575
+ return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
8576
+ return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
8496
8577
  }
8497
8578
  toExtendedJSON(options) {
8498
8579
  options = options || {};
@@ -8564,6 +8645,7 @@ var require_bson = __commonJS((exports) => {
8564
8645
  Binary.SUBTYPE_MD5 = 5;
8565
8646
  Binary.SUBTYPE_ENCRYPTED = 6;
8566
8647
  Binary.SUBTYPE_COLUMN = 7;
8648
+ Binary.SUBTYPE_SENSITIVE = 8;
8567
8649
  Binary.SUBTYPE_USER_DEFINED = 128;
8568
8650
  var UUID_BYTE_LENGTH = 16;
8569
8651
  var UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
@@ -8853,24 +8935,16 @@ var require_bson = __commonJS((exports) => {
8853
8935
  static fromBigInt(value, unsigned) {
8854
8936
  return Long.fromString(value.toString(), unsigned);
8855
8937
  }
8856
- static fromString(str, unsigned, radix) {
8938
+ static _fromString(str, unsigned, radix) {
8857
8939
  if (str.length === 0)
8858
8940
  throw new BSONError("empty string");
8859
- if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
8860
- return Long.ZERO;
8861
- if (typeof unsigned === "number") {
8862
- radix = unsigned, unsigned = false;
8863
- } else {
8864
- unsigned = !!unsigned;
8865
- }
8866
- radix = radix || 10;
8867
8941
  if (radix < 2 || 36 < radix)
8868
8942
  throw new BSONError("radix");
8869
8943
  let p;
8870
8944
  if ((p = str.indexOf("-")) > 0)
8871
8945
  throw new BSONError("interior hyphen");
8872
8946
  else if (p === 0) {
8873
- return Long.fromString(str.substring(1), unsigned, radix).neg();
8947
+ return Long._fromString(str.substring(1), unsigned, radix).neg();
8874
8948
  }
8875
8949
  const radixToPower = Long.fromNumber(Math.pow(radix, 8));
8876
8950
  let result = Long.ZERO;
@@ -8887,6 +8961,42 @@ var require_bson = __commonJS((exports) => {
8887
8961
  result.unsigned = unsigned;
8888
8962
  return result;
8889
8963
  }
8964
+ static fromStringStrict(str, unsignedOrRadix, radix) {
8965
+ let unsigned = false;
8966
+ if (typeof unsignedOrRadix === "number") {
8967
+ radix = unsignedOrRadix, unsignedOrRadix = false;
8968
+ } else {
8969
+ unsigned = !!unsignedOrRadix;
8970
+ }
8971
+ radix ??= 10;
8972
+ if (str.trim() !== str) {
8973
+ throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
8974
+ }
8975
+ if (!validateStringCharacters(str, radix)) {
8976
+ throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
8977
+ }
8978
+ const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
8979
+ const result = Long._fromString(cleanedStr, unsigned, radix);
8980
+ if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
8981
+ throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? "an unsigned" : "a signed"} 64-bit Long ${radix != null ? `with radix: ${radix}` : ""}`);
8982
+ }
8983
+ return result;
8984
+ }
8985
+ static fromString(str, unsignedOrRadix, radix) {
8986
+ let unsigned = false;
8987
+ if (typeof unsignedOrRadix === "number") {
8988
+ radix = unsignedOrRadix, unsignedOrRadix = false;
8989
+ } else {
8990
+ unsigned = !!unsignedOrRadix;
8991
+ }
8992
+ radix ??= 10;
8993
+ if (str === "NaN" && radix < 24) {
8994
+ return Long.ZERO;
8995
+ } else if ((str === "Infinity" || str === "+Infinity" || str === "-Infinity") && radix < 35) {
8996
+ return Long.ZERO;
8997
+ }
8998
+ return Long._fromString(str, unsigned, radix);
8999
+ }
8890
9000
  static fromBytes(bytes, unsigned, le) {
8891
9001
  return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
8892
9002
  }
@@ -9910,6 +10020,28 @@ var require_bson = __commonJS((exports) => {
9910
10020
  }
9911
10021
  this.value = +value;
9912
10022
  }
10023
+ static fromString(value) {
10024
+ const coercedValue = Number(value);
10025
+ if (value === "NaN")
10026
+ return new Double(NaN);
10027
+ if (value === "Infinity")
10028
+ return new Double(Infinity);
10029
+ if (value === "-Infinity")
10030
+ return new Double((-Infinity));
10031
+ if (!Number.isFinite(coercedValue)) {
10032
+ throw new BSONError(`Input: ${value} is not representable as a Double`);
10033
+ }
10034
+ if (value.trim() !== value) {
10035
+ throw new BSONError(`Input: '${value}' contains whitespace`);
10036
+ }
10037
+ if (value === "") {
10038
+ throw new BSONError(`Input is an empty string`);
10039
+ }
10040
+ if (/[^-0-9.+eE]/.test(value)) {
10041
+ throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
10042
+ }
10043
+ return new Double(coercedValue);
10044
+ }
9913
10045
  valueOf() {
9914
10046
  return this.value;
9915
10047
  }
@@ -9951,6 +10083,20 @@ var require_bson = __commonJS((exports) => {
9951
10083
  }
9952
10084
  this.value = +value | 0;
9953
10085
  }
10086
+ static fromString(value) {
10087
+ const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
10088
+ const coercedValue = Number(value);
10089
+ if (BSON_INT32_MAX < coercedValue) {
10090
+ throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
10091
+ } else if (BSON_INT32_MIN > coercedValue) {
10092
+ throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
10093
+ } else if (!Number.isSafeInteger(coercedValue)) {
10094
+ throw new BSONError(`Input: '${value}' is not a safe integer`);
10095
+ } else if (coercedValue.toString() !== cleanedValue) {
10096
+ throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
10097
+ }
10098
+ return new Int32(coercedValue);
10099
+ }
9954
10100
  valueOf() {
9955
10101
  return this.value;
9956
10102
  }
@@ -10005,7 +10151,15 @@ var require_bson = __commonJS((exports) => {
10005
10151
  }
10006
10152
  var FLOAT = new Float64Array(1);
10007
10153
  var FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
10154
+ FLOAT[0] = -1;
10155
+ var isBigEndian = FLOAT_BYTES[7] === 0;
10008
10156
  var NumberUtils = {
10157
+ getNonnegativeInt32LE(source, offset) {
10158
+ if (source[offset + 3] > 127) {
10159
+ throw new RangeError(`Size cannot be negative at offset: ${offset}`);
10160
+ }
10161
+ return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24;
10162
+ },
10009
10163
  getInt32LE(source, offset) {
10010
10164
  return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24;
10011
10165
  },
@@ -10020,7 +10174,17 @@ var require_bson = __commonJS((exports) => {
10020
10174
  const hi = NumberUtils.getUint32LE(source, offset + 4);
10021
10175
  return (BigInt(hi) << BigInt(32)) + BigInt(lo);
10022
10176
  },
10023
- getFloat64LE(source, offset) {
10177
+ getFloat64LE: isBigEndian ? (source, offset) => {
10178
+ FLOAT_BYTES[7] = source[offset];
10179
+ FLOAT_BYTES[6] = source[offset + 1];
10180
+ FLOAT_BYTES[5] = source[offset + 2];
10181
+ FLOAT_BYTES[4] = source[offset + 3];
10182
+ FLOAT_BYTES[3] = source[offset + 4];
10183
+ FLOAT_BYTES[2] = source[offset + 5];
10184
+ FLOAT_BYTES[1] = source[offset + 6];
10185
+ FLOAT_BYTES[0] = source[offset + 7];
10186
+ return FLOAT[0];
10187
+ } : (source, offset) => {
10024
10188
  FLOAT_BYTES[0] = source[offset];
10025
10189
  FLOAT_BYTES[1] = source[offset + 1];
10026
10190
  FLOAT_BYTES[2] = source[offset + 2];
@@ -10071,7 +10235,18 @@ var require_bson = __commonJS((exports) => {
10071
10235
  destination[offset + 7] = hi;
10072
10236
  return 8;
10073
10237
  },
10074
- setFloat64LE(destination, offset, value) {
10238
+ setFloat64LE: isBigEndian ? (destination, offset, value) => {
10239
+ FLOAT[0] = value;
10240
+ destination[offset] = FLOAT_BYTES[7];
10241
+ destination[offset + 1] = FLOAT_BYTES[6];
10242
+ destination[offset + 2] = FLOAT_BYTES[5];
10243
+ destination[offset + 3] = FLOAT_BYTES[4];
10244
+ destination[offset + 4] = FLOAT_BYTES[3];
10245
+ destination[offset + 5] = FLOAT_BYTES[2];
10246
+ destination[offset + 6] = FLOAT_BYTES[1];
10247
+ destination[offset + 7] = FLOAT_BYTES[0];
10248
+ return 8;
10249
+ } : (destination, offset, value) => {
10075
10250
  FLOAT[0] = value;
10076
10251
  destination[offset] = FLOAT_BYTES[0];
10077
10252
  destination[offset + 1] = FLOAT_BYTES[1];
@@ -10458,11 +10633,17 @@ var require_bson = __commonJS((exports) => {
10458
10633
  EJSON.serialize = EJSONserialize;
10459
10634
  EJSON.deserialize = EJSONdeserialize;
10460
10635
  Object.freeze(EJSON);
10636
+ var onDemand = Object.create(null);
10637
+ onDemand.parseToElements = parseToElements;
10638
+ onDemand.ByteUtils = ByteUtils;
10639
+ onDemand.NumberUtils = NumberUtils;
10640
+ Object.freeze(onDemand);
10461
10641
  var MAXSIZE = 1024 * 1024 * 17;
10462
10642
  var buffer = ByteUtils.allocate(MAXSIZE);
10463
10643
  var bson = Object.freeze({
10464
10644
  __proto__: null,
10465
10645
  BSONError,
10646
+ BSONOffsetError,
10466
10647
  BSONRegExp,
10467
10648
  BSONRuntimeError,
10468
10649
  BSONSymbol,
@@ -10485,12 +10666,14 @@ var require_bson = __commonJS((exports) => {
10485
10666
  calculateObjectSize,
10486
10667
  deserialize,
10487
10668
  deserializeStream,
10669
+ onDemand,
10488
10670
  serialize,
10489
10671
  serializeWithBufferAndIndex,
10490
10672
  setInternalBufferSize
10491
10673
  });
10492
10674
  exports.BSON = bson;
10493
10675
  exports.BSONError = BSONError;
10676
+ exports.BSONOffsetError = BSONOffsetError;
10494
10677
  exports.BSONRegExp = BSONRegExp;
10495
10678
  exports.BSONRuntimeError = BSONRuntimeError;
10496
10679
  exports.BSONSymbol = BSONSymbol;
@@ -10513,6 +10696,7 @@ var require_bson = __commonJS((exports) => {
10513
10696
  exports.calculateObjectSize = calculateObjectSize;
10514
10697
  exports.deserialize = deserialize;
10515
10698
  exports.deserializeStream = deserializeStream;
10699
+ exports.onDemand = onDemand;
10516
10700
  exports.serialize = serialize;
10517
10701
  exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
10518
10702
  exports.setInternalBufferSize = setInternalBufferSize;
@@ -10520,6 +10704,10 @@ var require_bson = __commonJS((exports) => {
10520
10704
 
10521
10705
  // node_modules/mongodb/lib/bson.js
10522
10706
  var require_bson2 = __commonJS((exports) => {
10707
+ var parseToElementsToArray = function(bytes, offset) {
10708
+ const res = bson_1.BSON.onDemand.parseToElements(bytes, offset);
10709
+ return Array.isArray(res) ? res : [...res];
10710
+ };
10523
10711
  var pluckBSONSerializeOptions = function(options) {
10524
10712
  const { fieldsAsRaw, useBigInt64, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw, enableUtf8Validation } = options;
10525
10713
  return {
@@ -10551,68 +10739,77 @@ var require_bson2 = __commonJS((exports) => {
10551
10739
  };
10552
10740
  };
10553
10741
  Object.defineProperty(exports, "__esModule", { value: true });
10554
- exports.resolveBSONOptions = exports.pluckBSONSerializeOptions = exports.UUID = exports.Timestamp = exports.serialize = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.EJSON = exports.Double = exports.deserialize = exports.Decimal128 = exports.DBRef = exports.Code = exports.calculateObjectSize = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.BSON = exports.Binary = undefined;
10742
+ exports.resolveBSONOptions = exports.pluckBSONSerializeOptions = exports.toUTF8 = exports.getBigInt64LE = exports.getFloat64LE = exports.getInt32LE = exports.parseToElementsToArray = exports.UUID = exports.Timestamp = exports.serialize = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.EJSON = exports.Double = exports.deserialize = exports.Decimal128 = exports.DBRef = exports.Code = exports.calculateObjectSize = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.BSONError = exports.BSON = exports.Binary = undefined;
10555
10743
  var bson_1 = require_bson();
10744
+ var bson_2 = require_bson();
10556
10745
  Object.defineProperty(exports, "Binary", { enumerable: true, get: function() {
10557
- return bson_1.Binary;
10746
+ return bson_2.Binary;
10558
10747
  } });
10559
10748
  Object.defineProperty(exports, "BSON", { enumerable: true, get: function() {
10560
- return bson_1.BSON;
10749
+ return bson_2.BSON;
10750
+ } });
10751
+ Object.defineProperty(exports, "BSONError", { enumerable: true, get: function() {
10752
+ return bson_2.BSONError;
10561
10753
  } });
10562
10754
  Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function() {
10563
- return bson_1.BSONRegExp;
10755
+ return bson_2.BSONRegExp;
10564
10756
  } });
10565
10757
  Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function() {
10566
- return bson_1.BSONSymbol;
10758
+ return bson_2.BSONSymbol;
10567
10759
  } });
10568
10760
  Object.defineProperty(exports, "BSONType", { enumerable: true, get: function() {
10569
- return bson_1.BSONType;
10761
+ return bson_2.BSONType;
10570
10762
  } });
10571
10763
  Object.defineProperty(exports, "calculateObjectSize", { enumerable: true, get: function() {
10572
- return bson_1.calculateObjectSize;
10764
+ return bson_2.calculateObjectSize;
10573
10765
  } });
10574
10766
  Object.defineProperty(exports, "Code", { enumerable: true, get: function() {
10575
- return bson_1.Code;
10767
+ return bson_2.Code;
10576
10768
  } });
10577
10769
  Object.defineProperty(exports, "DBRef", { enumerable: true, get: function() {
10578
- return bson_1.DBRef;
10770
+ return bson_2.DBRef;
10579
10771
  } });
10580
10772
  Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function() {
10581
- return bson_1.Decimal128;
10773
+ return bson_2.Decimal128;
10582
10774
  } });
10583
10775
  Object.defineProperty(exports, "deserialize", { enumerable: true, get: function() {
10584
- return bson_1.deserialize;
10776
+ return bson_2.deserialize;
10585
10777
  } });
10586
10778
  Object.defineProperty(exports, "Double", { enumerable: true, get: function() {
10587
- return bson_1.Double;
10779
+ return bson_2.Double;
10588
10780
  } });
10589
10781
  Object.defineProperty(exports, "EJSON", { enumerable: true, get: function() {
10590
- return bson_1.EJSON;
10782
+ return bson_2.EJSON;
10591
10783
  } });
10592
10784
  Object.defineProperty(exports, "Int32", { enumerable: true, get: function() {
10593
- return bson_1.Int32;
10785
+ return bson_2.Int32;
10594
10786
  } });
10595
10787
  Object.defineProperty(exports, "Long", { enumerable: true, get: function() {
10596
- return bson_1.Long;
10788
+ return bson_2.Long;
10597
10789
  } });
10598
10790
  Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function() {
10599
- return bson_1.MaxKey;
10791
+ return bson_2.MaxKey;
10600
10792
  } });
10601
10793
  Object.defineProperty(exports, "MinKey", { enumerable: true, get: function() {
10602
- return bson_1.MinKey;
10794
+ return bson_2.MinKey;
10603
10795
  } });
10604
10796
  Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function() {
10605
- return bson_1.ObjectId;
10797
+ return bson_2.ObjectId;
10606
10798
  } });
10607
10799
  Object.defineProperty(exports, "serialize", { enumerable: true, get: function() {
10608
- return bson_1.serialize;
10800
+ return bson_2.serialize;
10609
10801
  } });
10610
10802
  Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function() {
10611
- return bson_1.Timestamp;
10803
+ return bson_2.Timestamp;
10612
10804
  } });
10613
10805
  Object.defineProperty(exports, "UUID", { enumerable: true, get: function() {
10614
- return bson_1.UUID;
10806
+ return bson_2.UUID;
10615
10807
  } });
10808
+ exports.parseToElementsToArray = parseToElementsToArray;
10809
+ exports.getInt32LE = bson_1.BSON.onDemand.NumberUtils.getInt32LE;
10810
+ exports.getFloat64LE = bson_1.BSON.onDemand.NumberUtils.getFloat64LE;
10811
+ exports.getBigInt64LE = bson_1.BSON.onDemand.NumberUtils.getBigInt64LE;
10812
+ exports.toUTF8 = bson_1.BSON.onDemand.ByteUtils.toUTF8;
10616
10813
  exports.pluckBSONSerializeOptions = pluckBSONSerializeOptions;
10617
10814
  exports.resolveBSONOptions = resolveBSONOptions;
10618
10815
  });
@@ -10934,8 +11131,8 @@ var require_error = __commonJS((exports) => {
10934
11131
  exports.MongoKerberosError = MongoKerberosError;
10935
11132
 
10936
11133
  class MongoAWSError extends MongoRuntimeError {
10937
- constructor(message) {
10938
- super(message);
11134
+ constructor(message, options) {
11135
+ super(message, options);
10939
11136
  }
10940
11137
  get name() {
10941
11138
  return "MongoAWSError";
@@ -11109,8 +11306,9 @@ var require_error = __commonJS((exports) => {
11109
11306
  exports.MongoMissingCredentialsError = MongoMissingCredentialsError;
11110
11307
 
11111
11308
  class MongoMissingDependencyError extends MongoAPIError {
11112
- constructor(message, options = {}) {
11309
+ constructor(message, options) {
11113
11310
  super(message, options);
11311
+ this.dependencyName = options.dependencyName;
11114
11312
  }
11115
11313
  get name() {
11116
11314
  return "MongoMissingDependencyError";
@@ -11492,7 +11690,7 @@ var require_server_selection = __commonJS((exports) => {
11492
11690
  return [];
11493
11691
  };
11494
11692
  var latencyWindowReducer = function(topologyDescription, servers) {
11495
- const low = servers.reduce((min, server) => min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min), -1);
11693
+ const low = servers.reduce((min, server) => Math.min(server.roundTripTime, min), Infinity);
11496
11694
  const high = low + topologyDescription.localThresholdMS;
11497
11695
  return servers.reduce((result, server) => {
11498
11696
  if (server.roundTripTime <= high && server.roundTripTime >= low)
@@ -11824,6 +12022,9 @@ var require_write_concern = __commonJS((exports) => {
11824
12022
 
11825
12023
  // node_modules/mongodb/lib/utils.js
11826
12024
  var require_utils2 = __commonJS((exports) => {
12025
+ var isUint8Array = function(value) {
12026
+ return value != null && typeof value === "object" && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Uint8Array";
12027
+ };
11827
12028
  var hostMatchesWildcards = function(host, wildcards) {
11828
12029
  for (const wildcard of wildcards) {
11829
12030
  if (host === wildcard || wildcard.startsWith("*.") && host?.endsWith(wildcard.substring(2, wildcard.length)) || wildcard.startsWith("*/") && host?.endsWith(wildcard.substring(2, wildcard.length))) {
@@ -12167,7 +12368,7 @@ var require_utils2 = __commonJS((exports) => {
12167
12368
  return addressDomain.endsWith(srvHostDomain);
12168
12369
  };
12169
12370
  async function request(uri, options = {}) {
12170
- return new Promise((resolve, reject) => {
12371
+ return await new Promise((resolve, reject) => {
12171
12372
  const requestOptions = {
12172
12373
  method: "GET",
12173
12374
  timeout: 1e4,
@@ -12211,6 +12412,9 @@ var require_utils2 = __commonJS((exports) => {
12211
12412
  });
12212
12413
  return { promise, resolve, reject };
12213
12414
  };
12415
+ var squashError = function(_error) {
12416
+ return;
12417
+ };
12214
12418
  async function once(ee, name) {
12215
12419
  const { promise, resolve, reject } = promiseWithResolvers();
12216
12420
  const onEvent = (data) => resolve(data);
@@ -12225,12 +12429,36 @@ var require_utils2 = __commonJS((exports) => {
12225
12429
  throw error;
12226
12430
  }
12227
12431
  }
12432
+ var maybeAddIdToDocuments = function(coll, docOrDocs, options) {
12433
+ const forceServerObjectId = typeof options.forceServerObjectId === "boolean" ? options.forceServerObjectId : coll.s.db.options?.forceServerObjectId;
12434
+ if (forceServerObjectId === true) {
12435
+ return docOrDocs;
12436
+ }
12437
+ const transform = (doc) => {
12438
+ if (doc._id == null) {
12439
+ doc._id = coll.s.pkFactory.createPk();
12440
+ }
12441
+ return doc;
12442
+ };
12443
+ return Array.isArray(docOrDocs) ? docOrDocs.map(transform) : transform(docOrDocs);
12444
+ };
12445
+ async function fileIsAccessible(fileName, mode) {
12446
+ try {
12447
+ await fs_1.promises.access(fileName, mode);
12448
+ return true;
12449
+ } catch {
12450
+ return false;
12451
+ }
12452
+ }
12453
+ var noop = function() {
12454
+ return;
12455
+ };
12228
12456
  Object.defineProperty(exports, "__esModule", { value: true });
12229
- exports.DOCUMENT_DB_MSG = exports.COSMOS_DB_CHECK = exports.DOCUMENT_DB_CHECK = exports.TimeoutController = exports.request = exports.matchesParentDomain = exports.parseUnsignedInteger = exports.parseInteger = exports.compareObjectId = exports.commandSupportsReadConcern = exports.shuffle = exports.supportsRetryableWrites = exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isHello = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.calculateDurationInMs = exports.now = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.maxWireVersion = exports.uuidV4 = exports.makeCounter = exports.MongoDBCollectionNamespace = exports.MongoDBNamespace = exports.ns = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyRetryableWrites = exports.filterOptions = exports.mergeOptions = exports.isObject = exports.normalizeHintField = exports.hostMatchesWildcards = exports.ByteUtils = undefined;
12230
- exports.once = exports.randomBytes = exports.promiseWithResolvers = exports.isHostMatch = exports.COSMOS_DB_MSG = undefined;
12457
+ exports.DOCUMENT_DB_MSG = exports.COSMOS_DB_CHECK = exports.DOCUMENT_DB_CHECK = exports.request = exports.matchesParentDomain = exports.parseUnsignedInteger = exports.parseInteger = exports.compareObjectId = exports.commandSupportsReadConcern = exports.shuffle = exports.supportsRetryableWrites = exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isHello = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.calculateDurationInMs = exports.now = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.maxWireVersion = exports.uuidV4 = exports.makeCounter = exports.MongoDBCollectionNamespace = exports.MongoDBNamespace = exports.ns = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyRetryableWrites = exports.filterOptions = exports.mergeOptions = exports.isObject = exports.normalizeHintField = exports.hostMatchesWildcards = exports.isUint8Array = exports.ByteUtils = undefined;
12458
+ exports.noop = exports.fileIsAccessible = exports.maybeAddIdToDocuments = exports.once = exports.randomBytes = exports.squashError = exports.promiseWithResolvers = exports.isHostMatch = exports.COSMOS_DB_MSG = undefined;
12231
12459
  var crypto = import.meta.require("crypto");
12460
+ var fs_1 = import.meta.require("fs");
12232
12461
  var http = import.meta.require("http");
12233
- var timers_1 = import.meta.require("timers");
12234
12462
  var url = import.meta.require("url");
12235
12463
  var url_1 = import.meta.require("url");
12236
12464
  var util_1 = import.meta.require("util");
@@ -12256,6 +12484,7 @@ var require_utils2 = __commonJS((exports) => {
12256
12484
  return exports.ByteUtils.toLocalBufferType(uint8array).toString("base64");
12257
12485
  }
12258
12486
  };
12487
+ exports.isUint8Array = isUint8Array;
12259
12488
  exports.hostMatchesWildcards = hostMatchesWildcards;
12260
12489
  exports.normalizeHintField = normalizeHintField;
12261
12490
  var TO_STRING = (object) => Object.prototype.toString.call(object);
@@ -12568,28 +12797,18 @@ var require_utils2 = __commonJS((exports) => {
12568
12797
  exports.parseUnsignedInteger = parseUnsignedInteger;
12569
12798
  exports.matchesParentDomain = matchesParentDomain;
12570
12799
  exports.request = request;
12571
-
12572
- class TimeoutController extends AbortController {
12573
- constructor(timeout = 0, timeoutId = timeout > 0 ? (0, timers_1.setTimeout)(() => this.abort(), timeout) : null) {
12574
- super();
12575
- this.timeoutId = timeoutId;
12576
- }
12577
- clear() {
12578
- if (this.timeoutId != null) {
12579
- (0, timers_1.clearTimeout)(this.timeoutId);
12580
- }
12581
- this.timeoutId = null;
12582
- }
12583
- }
12584
- exports.TimeoutController = TimeoutController;
12585
12800
  exports.DOCUMENT_DB_CHECK = /(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/;
12586
12801
  exports.COSMOS_DB_CHECK = /\.cosmos\.azure\.com$/;
12587
12802
  exports.DOCUMENT_DB_MSG = "You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb";
12588
12803
  exports.COSMOS_DB_MSG = "You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb";
12589
12804
  exports.isHostMatch = isHostMatch;
12590
12805
  exports.promiseWithResolvers = promiseWithResolvers;
12806
+ exports.squashError = squashError;
12591
12807
  exports.randomBytes = (0, util_1.promisify)(crypto.randomBytes);
12592
12808
  exports.once = once;
12809
+ exports.maybeAddIdToDocuments = maybeAddIdToDocuments;
12810
+ exports.fileIsAccessible = fileIsAccessible;
12811
+ exports.noop = noop;
12593
12812
  });
12594
12813
 
12595
12814
  // node_modules/mongodb/lib/operations/operation.js
@@ -12686,9 +12905,14 @@ var require_execute_operation = __commonJS((exports) => {
12686
12905
  } else if (session.client !== client) {
12687
12906
  throw new error_1.MongoInvalidArgumentError("ClientSession must be from the same MongoClient");
12688
12907
  }
12908
+ if (session.explicit && session?.timeoutMS != null && operation.options.timeoutMS != null) {
12909
+ throw new error_1.MongoInvalidArgumentError("Do not specify timeoutMS on operation if already specified on an explicit session");
12910
+ }
12689
12911
  const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary;
12690
12912
  const inTransaction = !!session?.inTransaction();
12691
- if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary)) {
12913
+ const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION);
12914
+ const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION);
12915
+ if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary) && (hasReadAspect || operation.commandName === "runCommand")) {
12692
12916
  throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`);
12693
12917
  }
12694
12918
  if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) {
@@ -12702,26 +12926,28 @@ var require_execute_operation = __commonJS((exports) => {
12702
12926
  } else {
12703
12927
  selector = readPreference;
12704
12928
  }
12705
- const server = await topology.selectServerAsync(selector, {
12929
+ const server = await topology.selectServer(selector, {
12706
12930
  session,
12707
12931
  operationName: operation.commandName
12708
12932
  });
12709
12933
  if (session == null) {
12710
- return operation.execute(server, undefined);
12934
+ return await operation.execute(server, undefined);
12711
12935
  }
12712
12936
  if (!operation.hasAspect(operation_1.Aspect.RETRYABLE)) {
12713
12937
  try {
12714
12938
  return await operation.execute(server, session);
12715
12939
  } finally {
12716
12940
  if (session?.owner != null && session.owner === owner) {
12717
- await session.endSession().catch(() => null);
12941
+ try {
12942
+ await session.endSession();
12943
+ } catch (error) {
12944
+ (0, utils_1.squashError)(error);
12945
+ }
12718
12946
  }
12719
12947
  }
12720
12948
  }
12721
12949
  const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead;
12722
12950
  const willRetryWrite = topology.s.options.retryWrites && !inTransaction && (0, utils_1.supportsRetryableWrites)(server) && operation.canRetryWrite;
12723
- const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION);
12724
- const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION);
12725
12951
  const willRetry = hasReadAspect && willRetryRead || hasWriteAspect && willRetryWrite;
12726
12952
  if (hasWriteAspect && willRetryWrite) {
12727
12953
  operation.options.willRetryWrite = true;
@@ -12741,7 +12967,11 @@ var require_execute_operation = __commonJS((exports) => {
12741
12967
  throw operationError;
12742
12968
  } finally {
12743
12969
  if (session?.owner != null && session.owner === owner) {
12744
- await session.endSession().catch(() => null);
12970
+ try {
12971
+ await session.endSession();
12972
+ } catch (error) {
12973
+ (0, utils_1.squashError)(error);
12974
+ }
12745
12975
  }
12746
12976
  }
12747
12977
  }
@@ -12764,7 +12994,7 @@ var require_execute_operation = __commonJS((exports) => {
12764
12994
  if (originalError instanceof error_1.MongoNetworkError && session.isPinned && !session.inTransaction() && operation.hasAspect(operation_1.Aspect.CURSOR_CREATING)) {
12765
12995
  session.unpin({ force: true, forceClear: true });
12766
12996
  }
12767
- const server = await topology.selectServerAsync(selector, {
12997
+ const server = await topology.selectServer(selector, {
12768
12998
  session,
12769
12999
  operationName: operation.commandName,
12770
13000
  previousServer
@@ -12890,7 +13120,7 @@ var require_command = __commonJS((exports) => {
12890
13120
  if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) {
12891
13121
  cmd = (0, utils_1.decorateWithExplain)(cmd, this.explain);
12892
13122
  }
12893
- return server.command(this.ns, cmd, options);
13123
+ return await server.command(this.ns, cmd, options);
12894
13124
  }
12895
13125
  }
12896
13126
  exports.CommandOperation = CommandOperation;
@@ -12927,7 +13157,7 @@ var require_list_databases = __commonJS((exports) => {
12927
13157
  if ((0, utils_1.maxWireVersion)(server) >= 9 && this.options.comment !== undefined) {
12928
13158
  cmd.comment = this.options.comment;
12929
13159
  }
12930
- return super.executeCommand(server, session, cmd);
13160
+ return await super.executeCommand(server, session, cmd);
12931
13161
  }
12932
13162
  }
12933
13163
  exports.ListDatabasesOperation = ListDatabasesOperation;
@@ -12978,11 +13208,12 @@ var require_run_command = __commonJS((exports) => {
12978
13208
  }
12979
13209
  async execute(server, session) {
12980
13210
  this.server = server;
12981
- return server.command(this.ns, this.command, {
13211
+ const res = await server.command(this.ns, this.command, {
12982
13212
  ...this.options,
12983
13213
  readPreference: this.readPreference,
12984
13214
  session
12985
13215
  });
13216
+ return res;
12986
13217
  }
12987
13218
  }
12988
13219
  exports.RunCommandOperation = RunCommandOperation;
@@ -12999,11 +13230,12 @@ var require_run_command = __commonJS((exports) => {
12999
13230
  }
13000
13231
  async execute(server, session) {
13001
13232
  this.server = server;
13002
- return server.command(this.ns, this.command, {
13233
+ const res = await server.command(this.ns, this.command, {
13003
13234
  ...this.options,
13004
13235
  readPreference: this.readPreference,
13005
13236
  session
13006
13237
  });
13238
+ return res;
13007
13239
  }
13008
13240
  }
13009
13241
  exports.RunAdminCommandOperation = RunAdminCommandOperation;
@@ -13064,75 +13296,40 @@ var require_admin = __commonJS((exports) => {
13064
13296
  this.s = { db };
13065
13297
  }
13066
13298
  async command(command2, options) {
13067
- return (0, execute_operation_1.executeOperation)(this.s.db.client, new run_command_1.RunAdminCommandOperation(command2, {
13299
+ return await (0, execute_operation_1.executeOperation)(this.s.db.client, new run_command_1.RunAdminCommandOperation(command2, {
13068
13300
  ...(0, bson_1.resolveBSONOptions)(options),
13069
13301
  session: options?.session,
13070
13302
  readPreference: options?.readPreference
13071
13303
  }));
13072
13304
  }
13073
13305
  async buildInfo(options) {
13074
- return this.command({ buildinfo: 1 }, options);
13306
+ return await this.command({ buildinfo: 1 }, options);
13075
13307
  }
13076
13308
  async serverInfo(options) {
13077
- return this.command({ buildinfo: 1 }, options);
13309
+ return await this.command({ buildinfo: 1 }, options);
13078
13310
  }
13079
13311
  async serverStatus(options) {
13080
- return this.command({ serverStatus: 1 }, options);
13312
+ return await this.command({ serverStatus: 1 }, options);
13081
13313
  }
13082
13314
  async ping(options) {
13083
- return this.command({ ping: 1 }, options);
13315
+ return await this.command({ ping: 1 }, options);
13084
13316
  }
13085
13317
  async removeUser(username, options) {
13086
- return (0, execute_operation_1.executeOperation)(this.s.db.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: "admin", ...options }));
13318
+ return await (0, execute_operation_1.executeOperation)(this.s.db.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: "admin", ...options }));
13087
13319
  }
13088
13320
  async validateCollection(collectionName, options = {}) {
13089
- return (0, execute_operation_1.executeOperation)(this.s.db.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options));
13321
+ return await (0, execute_operation_1.executeOperation)(this.s.db.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options));
13090
13322
  }
13091
13323
  async listDatabases(options) {
13092
- return (0, execute_operation_1.executeOperation)(this.s.db.client, new list_databases_1.ListDatabasesOperation(this.s.db, options));
13324
+ return await (0, execute_operation_1.executeOperation)(this.s.db.client, new list_databases_1.ListDatabasesOperation(this.s.db, options));
13093
13325
  }
13094
13326
  async replSetGetStatus(options) {
13095
- return this.command({ replSetGetStatus: 1 }, options);
13327
+ return await this.command({ replSetGetStatus: 1 }, options);
13096
13328
  }
13097
13329
  }
13098
13330
  exports.Admin = Admin;
13099
13331
  });
13100
13332
 
13101
- // node_modules/mongodb/lib/operations/common_functions.js
13102
- var require_common_functions = __commonJS((exports) => {
13103
- async function indexInformation(db, name, options) {
13104
- if (options == null) {
13105
- options = {};
13106
- }
13107
- const full = options.full == null ? false : options.full;
13108
- const indexes = await db.collection(name).listIndexes(options).toArray();
13109
- if (full)
13110
- return indexes;
13111
- const info = {};
13112
- for (const index of indexes) {
13113
- info[index.name] = Object.entries(index.key);
13114
- }
13115
- return info;
13116
- }
13117
- var maybeAddIdToDocuments = function(coll, docOrDocs, options) {
13118
- const forceServerObjectId = typeof options.forceServerObjectId === "boolean" ? options.forceServerObjectId : coll.s.db.options?.forceServerObjectId;
13119
- if (forceServerObjectId === true) {
13120
- return docOrDocs;
13121
- }
13122
- const transform = (doc) => {
13123
- if (doc._id == null) {
13124
- doc._id = coll.s.pkFactory.createPk();
13125
- }
13126
- return doc;
13127
- };
13128
- return Array.isArray(docOrDocs) ? docOrDocs.map(transform) : transform(docOrDocs);
13129
- };
13130
- Object.defineProperty(exports, "__esModule", { value: true });
13131
- exports.maybeAddIdToDocuments = exports.indexInformation = undefined;
13132
- exports.indexInformation = indexInformation;
13133
- exports.maybeAddIdToDocuments = maybeAddIdToDocuments;
13134
- });
13135
-
13136
13333
  // node_modules/mongodb/lib/operations/delete.js
13137
13334
  var require_delete = __commonJS((exports) => {
13138
13335
  var makeDeleteStatement = function(filter, options) {
@@ -13190,7 +13387,8 @@ var require_delete = __commonJS((exports) => {
13190
13387
  throw new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`);
13191
13388
  }
13192
13389
  }
13193
- return super.executeCommand(server, session, command2);
13390
+ const res = await super.executeCommand(server, session, command2);
13391
+ return res;
13194
13392
  }
13195
13393
  }
13196
13394
  exports.DeleteOperation = DeleteOperation;
@@ -13286,10 +13484,10 @@ var require_insert = __commonJS((exports) => {
13286
13484
  Object.defineProperty(exports, "__esModule", { value: true });
13287
13485
  exports.InsertManyOperation = exports.InsertOneOperation = exports.InsertOperation = undefined;
13288
13486
  var error_1 = require_error();
13487
+ var utils_1 = require_utils2();
13289
13488
  var write_concern_1 = require_write_concern();
13290
13489
  var bulk_write_1 = require_bulk_write();
13291
13490
  var command_1 = require_command();
13292
- var common_functions_1 = require_common_functions();
13293
13491
  var operation_1 = require_operation();
13294
13492
 
13295
13493
  class InsertOperation extends command_1.CommandOperation {
@@ -13316,14 +13514,14 @@ var require_insert = __commonJS((exports) => {
13316
13514
  if (options.comment !== undefined) {
13317
13515
  command2.comment = options.comment;
13318
13516
  }
13319
- return super.executeCommand(server, session, command2);
13517
+ return await super.executeCommand(server, session, command2);
13320
13518
  }
13321
13519
  }
13322
13520
  exports.InsertOperation = InsertOperation;
13323
13521
 
13324
13522
  class InsertOneOperation extends InsertOperation {
13325
13523
  constructor(collection, doc, options) {
13326
- super(collection.s.namespace, (0, common_functions_1.maybeAddIdToDocuments)(collection, [doc], options), options);
13524
+ super(collection.s.namespace, (0, utils_1.maybeAddIdToDocuments)(collection, [doc], options), options);
13327
13525
  }
13328
13526
  async execute(server, session) {
13329
13527
  const res = await super.execute(server, session);
@@ -13454,7 +13652,7 @@ var require_update = __commonJS((exports) => {
13454
13652
  throw new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`);
13455
13653
  }
13456
13654
  }
13457
- return super.executeCommand(server, session, command2);
13655
+ return await super.executeCommand(server, session, command2);
13458
13656
  }
13459
13657
  }
13460
13658
  exports.UpdateOperation = UpdateOperation;
@@ -13647,7 +13845,7 @@ var require_common2 = __commonJS((exports) => {
13647
13845
  return;
13648
13846
  executeCommands(bulkOperation, options, callback);
13649
13847
  }
13650
- const finalOptions = (0, utils_1.resolveOptions)(bulkOperation, {
13848
+ const finalOptions = (0, utils_2.resolveOptions)(bulkOperation, {
13651
13849
  ...options,
13652
13850
  ordered: bulkOperation.isOrdered
13653
13851
  });
@@ -13710,13 +13908,13 @@ var require_common2 = __commonJS((exports) => {
13710
13908
  var util_1 = import.meta.require("util");
13711
13909
  var bson_1 = require_bson2();
13712
13910
  var error_1 = require_error();
13713
- var common_functions_1 = require_common_functions();
13714
13911
  var delete_1 = require_delete();
13715
13912
  var execute_operation_1 = require_execute_operation();
13716
13913
  var insert_1 = require_insert();
13717
13914
  var operation_1 = require_operation();
13718
13915
  var update_1 = require_update();
13719
13916
  var utils_1 = require_utils2();
13917
+ var utils_2 = require_utils2();
13720
13918
  var write_concern_1 = require_write_concern();
13721
13919
  var kServerError = Symbol("serverError");
13722
13920
  exports.BatchType = Object.freeze({
@@ -13915,14 +14113,14 @@ var require_common2 = __commonJS((exports) => {
13915
14113
  }));
13916
14114
  }
13917
14115
  updateOne(updateDocument) {
13918
- if (!(0, utils_1.hasAtomicOperators)(updateDocument)) {
14116
+ if (!(0, utils_2.hasAtomicOperators)(updateDocument)) {
13919
14117
  throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
13920
14118
  }
13921
14119
  const currentOp = buildCurrentOp(this.bulkOperation);
13922
14120
  return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: false }));
13923
14121
  }
13924
14122
  replaceOne(replacement) {
13925
- if ((0, utils_1.hasAtomicOperators)(replacement)) {
14123
+ if ((0, utils_2.hasAtomicOperators)(replacement)) {
13926
14124
  throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators");
13927
14125
  }
13928
14126
  const currentOp = buildCurrentOp(this.bulkOperation);
@@ -13989,7 +14187,7 @@ var require_common2 = __commonJS((exports) => {
13989
14187
  constructor(collection, options, isOrdered) {
13990
14188
  this.collection = collection;
13991
14189
  this.isOrdered = isOrdered;
13992
- const topology = (0, utils_1.getTopology)(collection);
14190
+ const topology = (0, utils_2.getTopology)(collection);
13993
14191
  options = options == null ? {} : options;
13994
14192
  const namespace = collection.s.namespace;
13995
14193
  const executed = false;
@@ -14001,7 +14199,7 @@ var require_common2 = __commonJS((exports) => {
14001
14199
  const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1000;
14002
14200
  const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2;
14003
14201
  let finalOptions = Object.assign({}, options);
14004
- finalOptions = (0, utils_1.applyRetryableWrites)(finalOptions, collection.s.db);
14202
+ finalOptions = (0, utils_2.applyRetryableWrites)(finalOptions, collection.s.db);
14005
14203
  const bulkResult = {
14006
14204
  ok: 1,
14007
14205
  writeErrors: [],
@@ -14044,7 +14242,7 @@ var require_common2 = __commonJS((exports) => {
14044
14242
  }
14045
14243
  }
14046
14244
  insert(document) {
14047
- (0, common_functions_1.maybeAddIdToDocuments)(this.collection, document, {
14245
+ (0, utils_1.maybeAddIdToDocuments)(this.collection, document, {
14048
14246
  forceServerObjectId: this.shouldForceServerObjectId()
14049
14247
  });
14050
14248
  return this.addToOperationsList(exports.BatchType.INSERT, document);
@@ -14065,7 +14263,7 @@ var require_common2 = __commonJS((exports) => {
14065
14263
  if ("insertOne" in op) {
14066
14264
  const forceServerObjectId = this.shouldForceServerObjectId();
14067
14265
  const document = op.insertOne && op.insertOne.document == null ? op.insertOne : op.insertOne.document;
14068
- (0, common_functions_1.maybeAddIdToDocuments)(this.collection, document, { forceServerObjectId });
14266
+ (0, utils_1.maybeAddIdToDocuments)(this.collection, document, { forceServerObjectId });
14069
14267
  return this.addToOperationsList(exports.BatchType.INSERT, document);
14070
14268
  }
14071
14269
  if ("replaceOne" in op || "updateOne" in op || "updateMany" in op) {
@@ -14074,7 +14272,7 @@ var require_common2 = __commonJS((exports) => {
14074
14272
  throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed");
14075
14273
  }
14076
14274
  const updateStatement = (0, update_1.makeUpdateStatement)(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false });
14077
- if ((0, utils_1.hasAtomicOperators)(updateStatement.u)) {
14275
+ if ((0, utils_2.hasAtomicOperators)(updateStatement.u)) {
14078
14276
  throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators");
14079
14277
  }
14080
14278
  return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement);
@@ -14087,7 +14285,7 @@ var require_common2 = __commonJS((exports) => {
14087
14285
  ...op.updateOne,
14088
14286
  multi: false
14089
14287
  });
14090
- if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) {
14288
+ if (!(0, utils_2.hasAtomicOperators)(updateStatement.u)) {
14091
14289
  throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
14092
14290
  }
14093
14291
  return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement);
@@ -14100,7 +14298,7 @@ var require_common2 = __commonJS((exports) => {
14100
14298
  ...op.updateMany,
14101
14299
  multi: true
14102
14300
  });
14103
- if (!(0, utils_1.hasAtomicOperators)(updateStatement.u)) {
14301
+ if (!(0, utils_2.hasAtomicOperators)(updateStatement.u)) {
14104
14302
  throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators");
14105
14303
  }
14106
14304
  return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement);
@@ -14166,7 +14364,7 @@ var require_common2 = __commonJS((exports) => {
14166
14364
  this.s.executed = true;
14167
14365
  const finalOptions = { ...this.s.options, ...options };
14168
14366
  const operation = new BulkWriteShimOperation(this, finalOptions);
14169
- return (0, execute_operation_1.executeOperation)(this.s.collection.client, operation);
14367
+ return await (0, execute_operation_1.executeOperation)(this.s.collection.client, operation);
14170
14368
  }
14171
14369
  handleWriteError(callback, writeResult) {
14172
14370
  if (this.s.bulkResult.writeErrors.length > 0) {
@@ -14392,7 +14590,8 @@ var require_aggregate = __commonJS((exports) => {
14392
14590
  if (options.batchSize && !this.hasWriteStage) {
14393
14591
  command2.cursor.batchSize = options.batchSize;
14394
14592
  }
14395
- return super.executeCommand(server, session, command2);
14593
+ const res = await super.executeCommand(server, session, command2);
14594
+ return res;
14396
14595
  }
14397
14596
  }
14398
14597
  exports.AggregateOperation = AggregateOperation;
@@ -14404,6 +14603,329 @@ var require_aggregate = __commonJS((exports) => {
14404
14603
  ]);
14405
14604
  });
14406
14605
 
14606
+ // node_modules/mongodb/lib/cmap/wire_protocol/on_demand/document.js
14607
+ var require_document = __commonJS((exports) => {
14608
+ Object.defineProperty(exports, "__esModule", { value: true });
14609
+ exports.OnDemandDocument = undefined;
14610
+ var bson_1 = require_bson2();
14611
+
14612
+ class OnDemandDocument {
14613
+ constructor(bson, offset = 0, isArray = false) {
14614
+ this.bson = bson;
14615
+ this.offset = offset;
14616
+ this.isArray = isArray;
14617
+ this.cache = Object.create(null);
14618
+ this.indexFound = Object.create(null);
14619
+ this.elements = (0, bson_1.parseToElementsToArray)(this.bson, offset);
14620
+ }
14621
+ isElementName(name, element) {
14622
+ const nameLength = element[2];
14623
+ const nameOffset = element[1];
14624
+ if (name.length !== nameLength)
14625
+ return false;
14626
+ for (let i = 0;i < name.length; i++) {
14627
+ if (this.bson[nameOffset + i] !== name.charCodeAt(i))
14628
+ return false;
14629
+ }
14630
+ return true;
14631
+ }
14632
+ getElement(name) {
14633
+ const cachedElement = this.cache[name];
14634
+ if (cachedElement === false)
14635
+ return null;
14636
+ if (cachedElement != null) {
14637
+ return cachedElement;
14638
+ }
14639
+ if (typeof name === "number") {
14640
+ if (this.isArray) {
14641
+ if (name < this.elements.length) {
14642
+ const element = this.elements[name];
14643
+ const cachedElement2 = { element, value: undefined };
14644
+ this.cache[name] = cachedElement2;
14645
+ this.indexFound[name] = true;
14646
+ return cachedElement2;
14647
+ } else {
14648
+ return null;
14649
+ }
14650
+ } else {
14651
+ return null;
14652
+ }
14653
+ }
14654
+ for (let index = 0;index < this.elements.length; index++) {
14655
+ const element = this.elements[index];
14656
+ if (!this.indexFound[index] && this.isElementName(name, element)) {
14657
+ const cachedElement2 = { element, value: undefined };
14658
+ this.cache[name] = cachedElement2;
14659
+ this.indexFound[index] = true;
14660
+ return cachedElement2;
14661
+ }
14662
+ }
14663
+ this.cache[name] = false;
14664
+ return null;
14665
+ }
14666
+ toJSValue(element, as) {
14667
+ const type = element[0];
14668
+ const offset = element[3];
14669
+ const length = element[4];
14670
+ if (as !== type) {
14671
+ return null;
14672
+ }
14673
+ switch (as) {
14674
+ case bson_1.BSONType.null:
14675
+ case bson_1.BSONType.undefined:
14676
+ return null;
14677
+ case bson_1.BSONType.double:
14678
+ return (0, bson_1.getFloat64LE)(this.bson, offset);
14679
+ case bson_1.BSONType.int:
14680
+ return (0, bson_1.getInt32LE)(this.bson, offset);
14681
+ case bson_1.BSONType.long:
14682
+ return (0, bson_1.getBigInt64LE)(this.bson, offset);
14683
+ case bson_1.BSONType.bool:
14684
+ return Boolean(this.bson[offset]);
14685
+ case bson_1.BSONType.objectId:
14686
+ return new bson_1.ObjectId(this.bson.subarray(offset, offset + 12));
14687
+ case bson_1.BSONType.timestamp:
14688
+ return new bson_1.Timestamp((0, bson_1.getBigInt64LE)(this.bson, offset));
14689
+ case bson_1.BSONType.string:
14690
+ return (0, bson_1.toUTF8)(this.bson, offset + 4, offset + length - 1, false);
14691
+ case bson_1.BSONType.binData: {
14692
+ const totalBinarySize = (0, bson_1.getInt32LE)(this.bson, offset);
14693
+ const subType = this.bson[offset + 4];
14694
+ if (subType === 2) {
14695
+ const subType2BinarySize = (0, bson_1.getInt32LE)(this.bson, offset + 1 + 4);
14696
+ if (subType2BinarySize < 0)
14697
+ throw new bson_1.BSONError("Negative binary type element size found for subtype 0x02");
14698
+ if (subType2BinarySize > totalBinarySize - 4)
14699
+ throw new bson_1.BSONError("Binary type with subtype 0x02 contains too long binary size");
14700
+ if (subType2BinarySize < totalBinarySize - 4)
14701
+ throw new bson_1.BSONError("Binary type with subtype 0x02 contains too short binary size");
14702
+ return new bson_1.Binary(this.bson.subarray(offset + 1 + 4 + 4, offset + 1 + 4 + 4 + subType2BinarySize), 2);
14703
+ }
14704
+ return new bson_1.Binary(this.bson.subarray(offset + 1 + 4, offset + 1 + 4 + totalBinarySize), subType);
14705
+ }
14706
+ case bson_1.BSONType.date:
14707
+ return new Date(Number((0, bson_1.getBigInt64LE)(this.bson, offset)));
14708
+ case bson_1.BSONType.object:
14709
+ return new OnDemandDocument(this.bson, offset);
14710
+ case bson_1.BSONType.array:
14711
+ return new OnDemandDocument(this.bson, offset, true);
14712
+ default:
14713
+ throw new bson_1.BSONError(`Unsupported BSON type: ${as}`);
14714
+ }
14715
+ }
14716
+ size() {
14717
+ return this.elements.length;
14718
+ }
14719
+ has(name) {
14720
+ const cachedElement = this.cache[name];
14721
+ if (cachedElement === false)
14722
+ return false;
14723
+ if (cachedElement != null)
14724
+ return true;
14725
+ return this.getElement(name) != null;
14726
+ }
14727
+ get(name, as, required) {
14728
+ const element = this.getElement(name);
14729
+ if (element == null) {
14730
+ if (required === true) {
14731
+ throw new bson_1.BSONError(`BSON element "${name}" is missing`);
14732
+ } else {
14733
+ return null;
14734
+ }
14735
+ }
14736
+ if (element.value == null) {
14737
+ const value = this.toJSValue(element.element, as);
14738
+ if (value == null) {
14739
+ if (required === true) {
14740
+ throw new bson_1.BSONError(`BSON element "${name}" is missing`);
14741
+ } else {
14742
+ return null;
14743
+ }
14744
+ }
14745
+ element.value = value;
14746
+ }
14747
+ return element.value;
14748
+ }
14749
+ getNumber(name, required) {
14750
+ const maybeBool = this.get(name, bson_1.BSONType.bool);
14751
+ const bool = maybeBool == null ? null : maybeBool ? 1 : 0;
14752
+ const maybeLong = this.get(name, bson_1.BSONType.long);
14753
+ const long = maybeLong == null ? null : Number(maybeLong);
14754
+ const result = bool ?? long ?? this.get(name, bson_1.BSONType.int) ?? this.get(name, bson_1.BSONType.double);
14755
+ if (required === true && result == null) {
14756
+ throw new bson_1.BSONError(`BSON element "${name}" is missing`);
14757
+ }
14758
+ return result;
14759
+ }
14760
+ toObject(options) {
14761
+ return bson_1.BSON.deserialize(this.bson, {
14762
+ ...options,
14763
+ index: this.offset,
14764
+ allowObjectSmallerThanBufferSize: true
14765
+ });
14766
+ }
14767
+ toBytes() {
14768
+ const size = (0, bson_1.getInt32LE)(this.bson, this.offset);
14769
+ return this.bson.subarray(this.offset, this.offset + size);
14770
+ }
14771
+ }
14772
+ exports.OnDemandDocument = OnDemandDocument;
14773
+ });
14774
+
14775
+ // node_modules/mongodb/lib/cmap/wire_protocol/responses.js
14776
+ var require_responses = __commonJS((exports) => {
14777
+ var isErrorResponse = function(bson) {
14778
+ const elements = (0, bson_1.parseToElementsToArray)(bson, 0);
14779
+ for (let eIdx = 0;eIdx < elements.length; eIdx++) {
14780
+ const element = elements[eIdx];
14781
+ if (element[2] === 2) {
14782
+ const nameOffset = element[1];
14783
+ if (bson[nameOffset] === 111 && bson[nameOffset + 1] === 107) {
14784
+ const valueOffset = element[3];
14785
+ const valueLength = element[4];
14786
+ for (let i = valueOffset;i < valueOffset + valueLength; i++) {
14787
+ if (bson[i] !== 0)
14788
+ return false;
14789
+ }
14790
+ return true;
14791
+ }
14792
+ }
14793
+ }
14794
+ return true;
14795
+ };
14796
+ Object.defineProperty(exports, "__esModule", { value: true });
14797
+ exports.CursorResponse = exports.MongoDBResponse = exports.isErrorResponse = undefined;
14798
+ var bson_1 = require_bson2();
14799
+ var error_1 = require_error();
14800
+ var utils_1 = require_utils2();
14801
+ var document_1 = require_document();
14802
+ exports.isErrorResponse = isErrorResponse;
14803
+
14804
+ class MongoDBResponse extends document_1.OnDemandDocument {
14805
+ static is(value) {
14806
+ return value instanceof MongoDBResponse;
14807
+ }
14808
+ get isError() {
14809
+ let isError = this.ok === 0;
14810
+ isError ||= this.has("errmsg");
14811
+ isError ||= this.has("code");
14812
+ isError ||= this.has("$err");
14813
+ return isError;
14814
+ }
14815
+ get recoveryToken() {
14816
+ return this.get("recoveryToken", bson_1.BSONType.object)?.toObject({
14817
+ promoteValues: false,
14818
+ promoteLongs: false,
14819
+ promoteBuffers: false
14820
+ }) ?? null;
14821
+ }
14822
+ get atClusterTime() {
14823
+ return this.get("cursor", bson_1.BSONType.object)?.get("atClusterTime", bson_1.BSONType.timestamp) ?? this.get("atClusterTime", bson_1.BSONType.timestamp);
14824
+ }
14825
+ get operationTime() {
14826
+ return this.get("operationTime", bson_1.BSONType.timestamp);
14827
+ }
14828
+ get ok() {
14829
+ return this.getNumber("ok") ? 1 : 0;
14830
+ }
14831
+ get $err() {
14832
+ return this.get("$err", bson_1.BSONType.string);
14833
+ }
14834
+ get errmsg() {
14835
+ return this.get("errmsg", bson_1.BSONType.string);
14836
+ }
14837
+ get code() {
14838
+ return this.getNumber("code");
14839
+ }
14840
+ get $clusterTime() {
14841
+ if (!("clusterTime" in this)) {
14842
+ const clusterTimeDoc = this.get("$clusterTime", bson_1.BSONType.object);
14843
+ if (clusterTimeDoc == null) {
14844
+ this.clusterTime = null;
14845
+ return null;
14846
+ }
14847
+ const clusterTime = clusterTimeDoc.get("clusterTime", bson_1.BSONType.timestamp, true);
14848
+ const signature = clusterTimeDoc.get("signature", bson_1.BSONType.object)?.toObject();
14849
+ this.clusterTime = { clusterTime, signature };
14850
+ }
14851
+ return this.clusterTime ?? null;
14852
+ }
14853
+ toObject(options) {
14854
+ const exactBSONOptions = {
14855
+ useBigInt64: options?.useBigInt64,
14856
+ promoteLongs: options?.promoteLongs,
14857
+ promoteValues: options?.promoteValues,
14858
+ promoteBuffers: options?.promoteBuffers,
14859
+ bsonRegExp: options?.bsonRegExp,
14860
+ raw: options?.raw ?? false,
14861
+ fieldsAsRaw: options?.fieldsAsRaw ?? {},
14862
+ validation: this.parseBsonSerializationOptions(options)
14863
+ };
14864
+ return super.toObject(exactBSONOptions);
14865
+ }
14866
+ parseBsonSerializationOptions(options) {
14867
+ const enableUtf8Validation = options?.enableUtf8Validation;
14868
+ if (enableUtf8Validation === false) {
14869
+ return { utf8: false };
14870
+ }
14871
+ return { utf8: { writeErrors: false } };
14872
+ }
14873
+ }
14874
+ MongoDBResponse.empty = new MongoDBResponse(new Uint8Array([13, 0, 0, 0, 16, 111, 107, 0, 1, 0, 0, 0, 0]));
14875
+ exports.MongoDBResponse = MongoDBResponse;
14876
+
14877
+ class CursorResponse extends MongoDBResponse {
14878
+ static is(value) {
14879
+ return value instanceof CursorResponse || value === CursorResponse.emptyGetMore;
14880
+ }
14881
+ constructor(bytes, offset, isArray) {
14882
+ super(bytes, offset, isArray);
14883
+ this.ns = null;
14884
+ this.batchSize = 0;
14885
+ this.iterated = 0;
14886
+ const cursor = this.get("cursor", bson_1.BSONType.object, true);
14887
+ const id = cursor.get("id", bson_1.BSONType.long, true);
14888
+ this.id = new bson_1.Long(Number(id & 0xffffffffn), Number(id >> 32n & 0xffffffffn));
14889
+ const namespace = cursor.get("ns", bson_1.BSONType.string);
14890
+ if (namespace != null)
14891
+ this.ns = (0, utils_1.ns)(namespace);
14892
+ if (cursor.has("firstBatch"))
14893
+ this.batch = cursor.get("firstBatch", bson_1.BSONType.array, true);
14894
+ else if (cursor.has("nextBatch"))
14895
+ this.batch = cursor.get("nextBatch", bson_1.BSONType.array, true);
14896
+ else
14897
+ throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");
14898
+ this.batchSize = this.batch.size();
14899
+ }
14900
+ get length() {
14901
+ return Math.max(this.batchSize - this.iterated, 0);
14902
+ }
14903
+ shift(options) {
14904
+ if (this.iterated >= this.batchSize) {
14905
+ return null;
14906
+ }
14907
+ const result = this.batch.get(this.iterated, bson_1.BSONType.object, true) ?? null;
14908
+ this.iterated += 1;
14909
+ if (options?.raw) {
14910
+ return result.toBytes();
14911
+ } else {
14912
+ return result.toObject(options);
14913
+ }
14914
+ }
14915
+ clear() {
14916
+ this.iterated = this.batchSize;
14917
+ }
14918
+ pushMany() {
14919
+ throw new Error("pushMany Unsupported method");
14920
+ }
14921
+ push() {
14922
+ throw new Error("push Unsupported method");
14923
+ }
14924
+ }
14925
+ CursorResponse.emptyGetMore = { id: new bson_1.Long(0), length: 0, shift: () => null };
14926
+ exports.CursorResponse = CursorResponse;
14927
+ });
14928
+
14407
14929
  // node_modules/mongodb/lib/mongo_logger.js
14408
14930
  var require_mongo_logger = __commonJS((exports) => {
14409
14931
  var parseSeverityFromString = function(s) {
@@ -14923,6 +15445,7 @@ var require_mongo_types = __commonJS((exports) => {
14923
15445
  var require_get_more = __commonJS((exports) => {
14924
15446
  Object.defineProperty(exports, "__esModule", { value: true });
14925
15447
  exports.GetMoreOperation = undefined;
15448
+ var responses_1 = require_responses();
14926
15449
  var error_1 = require_error();
14927
15450
  var utils_1 = require_utils2();
14928
15451
  var operation_1 = require_operation();
@@ -14967,7 +15490,7 @@ var require_get_more = __commonJS((exports) => {
14967
15490
  documentsReturnedIn: "nextBatch",
14968
15491
  ...this.options
14969
15492
  };
14970
- return server.command(this.ns, getMoreCmd, commandOptions);
15493
+ return await server.command(this.ns, getMoreCmd, commandOptions, this.options.useCursorResponse ? responses_1.CursorResponse : undefined);
14971
15494
  }
14972
15495
  }
14973
15496
  exports.GetMoreOperation = GetMoreOperation;
@@ -14979,6 +15502,7 @@ var require_kill_cursors = __commonJS((exports) => {
14979
15502
  Object.defineProperty(exports, "__esModule", { value: true });
14980
15503
  exports.KillCursorsOperation = undefined;
14981
15504
  var error_1 = require_error();
15505
+ var utils_1 = require_utils2();
14982
15506
  var operation_1 = require_operation();
14983
15507
 
14984
15508
  class KillCursorsOperation extends operation_1.AbstractOperation {
@@ -15005,7 +15529,8 @@ var require_kill_cursors = __commonJS((exports) => {
15005
15529
  };
15006
15530
  try {
15007
15531
  await server.command(this.ns, killCursorsCommand, { session });
15008
- } catch {
15532
+ } catch (error) {
15533
+ (0, utils_1.squashError)(error);
15009
15534
  }
15010
15535
  }
15011
15536
  }
@@ -15137,6 +15662,7 @@ var require_server_description = __commonJS((exports) => {
15137
15662
  this.minWireVersion = hello?.minWireVersion ?? 0;
15138
15663
  this.maxWireVersion = hello?.maxWireVersion ?? 0;
15139
15664
  this.roundTripTime = options?.roundTripTime ?? -1;
15665
+ this.minRoundTripTime = options?.minRoundTripTime ?? 0;
15140
15666
  this.lastUpdateTime = (0, utils_1.now)();
15141
15667
  this.lastWriteDate = hello?.lastWrite?.lastWriteDate ?? 0;
15142
15668
  this.error = options.error ?? null;
@@ -15287,6 +15813,7 @@ var require_topology_description = __commonJS((exports) => {
15287
15813
  };
15288
15814
  Object.defineProperty(exports, "__esModule", { value: true });
15289
15815
  exports.TopologyDescription = undefined;
15816
+ var bson_1 = require_bson2();
15290
15817
  var WIRE_CONSTANTS = require_constants();
15291
15818
  var error_1 = require_error();
15292
15819
  var utils_1 = require_utils2();
@@ -15463,6 +15990,9 @@ var require_topology_description = __commonJS((exports) => {
15463
15990
  hasServer(address) {
15464
15991
  return this.servers.has(address);
15465
15992
  }
15993
+ toJSON() {
15994
+ return bson_1.EJSON.serialize(this);
15995
+ }
15466
15996
  }
15467
15997
  exports.TopologyDescription = TopologyDescription;
15468
15998
  });
@@ -15643,12 +16173,12 @@ var require_sessions = __commonJS((exports) => {
15643
16173
  const loadBalancer = servers[0];
15644
16174
  if (options?.error == null || options?.force) {
15645
16175
  loadBalancer.pool.checkIn(conn);
16176
+ session[kPinnedConnection] = undefined;
15646
16177
  conn.emit(constants_1.UNPINNED, session.transaction.state !== transactions_1.TxnState.NO_TRANSACTION ? metrics_1.ConnectionPoolMetrics.TXN : metrics_1.ConnectionPoolMetrics.CURSOR);
15647
16178
  if (options?.forceClear) {
15648
16179
  loadBalancer.pool.clear({ serviceId: conn.serviceId });
15649
16180
  }
15650
16181
  }
15651
- session[kPinnedConnection] = undefined;
15652
16182
  }
15653
16183
  };
15654
16184
  var isMaxTimeMSExpiredError = function(err) {
@@ -15657,23 +16187,26 @@ var require_sessions = __commonJS((exports) => {
15657
16187
  }
15658
16188
  return err.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired || err.writeConcernError && err.writeConcernError.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired;
15659
16189
  };
15660
- var attemptTransactionCommit = function(session, startTime, fn, result, options) {
15661
- return session.commitTransaction().then(() => result, (err) => {
15662
- if (err instanceof error_1.MongoError && hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && !isMaxTimeMSExpiredError(err)) {
15663
- if (err.hasErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult)) {
15664
- return attemptTransactionCommit(session, startTime, fn, result, options);
16190
+ async function attemptTransactionCommit(session, startTime, fn, result, options) {
16191
+ try {
16192
+ await session.commitTransaction();
16193
+ return result;
16194
+ } catch (commitErr) {
16195
+ if (commitErr instanceof error_1.MongoError && hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && !isMaxTimeMSExpiredError(commitErr)) {
16196
+ if (commitErr.hasErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult)) {
16197
+ return await attemptTransactionCommit(session, startTime, fn, result, options);
15665
16198
  }
15666
- if (err.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
15667
- return attemptTransaction(session, startTime, fn, options);
16199
+ if (commitErr.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
16200
+ return await attemptTransaction(session, startTime, fn, options);
15668
16201
  }
15669
16202
  }
15670
- throw err;
15671
- });
15672
- };
16203
+ throw commitErr;
16204
+ }
16205
+ }
15673
16206
  var userExplicitlyEndedTransaction = function(session) {
15674
16207
  return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state);
15675
16208
  };
15676
- var attemptTransaction = function(session, startTime, fn, options = {}) {
16209
+ async function attemptTransaction(session, startTime, fn, options = {}) {
15677
16210
  session.startTransaction(options);
15678
16211
  let promise;
15679
16212
  try {
@@ -15682,59 +16215,55 @@ var require_sessions = __commonJS((exports) => {
15682
16215
  promise = Promise.reject(err);
15683
16216
  }
15684
16217
  if (!(0, utils_1.isPromiseLike)(promise)) {
15685
- session.abortTransaction().catch(() => null);
15686
- return Promise.reject(new error_1.MongoInvalidArgumentError("Function provided to `withTransaction` must return a Promise"));
16218
+ try {
16219
+ await session.abortTransaction();
16220
+ } catch (error) {
16221
+ (0, utils_1.squashError)(error);
16222
+ }
16223
+ throw new error_1.MongoInvalidArgumentError("Function provided to `withTransaction` must return a Promise");
15687
16224
  }
15688
- return promise.then((result) => {
16225
+ try {
16226
+ const result = await promise;
15689
16227
  if (userExplicitlyEndedTransaction(session)) {
15690
16228
  return result;
15691
16229
  }
15692
- return attemptTransactionCommit(session, startTime, fn, result, options);
15693
- }, (err) => {
15694
- function maybeRetryOrThrow(err2) {
15695
- if (err2 instanceof error_1.MongoError && err2.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError) && hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT)) {
15696
- return attemptTransaction(session, startTime, fn, options);
15697
- }
15698
- if (isMaxTimeMSExpiredError(err2)) {
15699
- err2.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
15700
- }
15701
- throw err2;
15702
- }
16230
+ return await attemptTransactionCommit(session, startTime, fn, result, options);
16231
+ } catch (err) {
15703
16232
  if (session.inTransaction()) {
15704
- return session.abortTransaction().then(() => maybeRetryOrThrow(err));
16233
+ await session.abortTransaction();
15705
16234
  }
15706
- return maybeRetryOrThrow(err);
15707
- });
15708
- };
15709
- var endTransaction = function(session, commandName, callback) {
16235
+ if (err instanceof error_1.MongoError && err.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError) && hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT)) {
16236
+ return await attemptTransaction(session, startTime, fn, options);
16237
+ }
16238
+ if (isMaxTimeMSExpiredError(err)) {
16239
+ err.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
16240
+ }
16241
+ throw err;
16242
+ }
16243
+ }
16244
+ async function endTransaction(session, commandName) {
15710
16245
  const txnState = session.transaction.state;
15711
16246
  if (txnState === transactions_1.TxnState.NO_TRANSACTION) {
15712
- callback(new error_1.MongoTransactionError("No transaction started"));
15713
- return;
16247
+ throw new error_1.MongoTransactionError("No transaction started");
15714
16248
  }
15715
16249
  if (commandName === "commitTransaction") {
15716
16250
  if (txnState === transactions_1.TxnState.STARTING_TRANSACTION || txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) {
15717
16251
  session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY);
15718
- callback();
15719
16252
  return;
15720
16253
  }
15721
16254
  if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) {
15722
- callback(new error_1.MongoTransactionError("Cannot call commitTransaction after calling abortTransaction"));
15723
- return;
16255
+ throw new error_1.MongoTransactionError("Cannot call commitTransaction after calling abortTransaction");
15724
16256
  }
15725
16257
  } else {
15726
16258
  if (txnState === transactions_1.TxnState.STARTING_TRANSACTION) {
15727
16259
  session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
15728
- callback();
15729
16260
  return;
15730
16261
  }
15731
16262
  if (txnState === transactions_1.TxnState.TRANSACTION_ABORTED) {
15732
- callback(new error_1.MongoTransactionError("Cannot call abortTransaction twice"));
15733
- return;
16263
+ throw new error_1.MongoTransactionError("Cannot call abortTransaction twice");
15734
16264
  }
15735
16265
  if (txnState === transactions_1.TxnState.TRANSACTION_COMMITTED || txnState === transactions_1.TxnState.TRANSACTION_COMMITTED_EMPTY) {
15736
- callback(new error_1.MongoTransactionError("Cannot call abortTransaction after calling commitTransaction"));
15737
- return;
16266
+ throw new error_1.MongoTransactionError("Cannot call abortTransaction after calling commitTransaction");
15738
16267
  }
15739
16268
  }
15740
16269
  const command2 = { [commandName]: 1 };
@@ -15753,55 +16282,79 @@ var require_sessions = __commonJS((exports) => {
15753
16282
  if (commandName === "commitTransaction" && session.transaction.options.maxTimeMS) {
15754
16283
  Object.assign(command2, { maxTimeMS: session.transaction.options.maxTimeMS });
15755
16284
  }
15756
- function commandHandler(error) {
16285
+ if (session.transaction.recoveryToken) {
16286
+ command2.recoveryToken = session.transaction.recoveryToken;
16287
+ }
16288
+ try {
16289
+ await (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(command2, {
16290
+ session,
16291
+ readPreference: read_preference_1.ReadPreference.primary,
16292
+ bypassPinningCheck: true
16293
+ }));
16294
+ if (command2.abortTransaction) {
16295
+ session.unpin();
16296
+ }
15757
16297
  if (commandName !== "commitTransaction") {
15758
16298
  session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
15759
16299
  if (session.loadBalanced) {
15760
16300
  maybeClearPinnedConnection(session, { force: false });
15761
16301
  }
15762
- return callback();
15763
- }
15764
- session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED);
15765
- if (error instanceof error_1.MongoError) {
15766
- if ((0, error_1.isRetryableWriteError)(error) || error instanceof error_1.MongoWriteConcernError || isMaxTimeMSExpiredError(error)) {
15767
- if (isUnknownTransactionCommitResult(error)) {
15768
- error.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
15769
- session.unpin({ error });
15770
- }
15771
- } else if (error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
15772
- session.unpin({ error });
15773
- }
16302
+ } else {
16303
+ session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED);
15774
16304
  }
15775
- callback(error);
15776
- }
15777
- if (session.transaction.recoveryToken) {
15778
- command2.recoveryToken = session.transaction.recoveryToken;
15779
- }
15780
- const handleFirstCommandAttempt = (error) => {
16305
+ } catch (firstAttemptErr) {
15781
16306
  if (command2.abortTransaction) {
15782
16307
  session.unpin();
15783
16308
  }
15784
- if (error instanceof error_1.MongoError && (0, error_1.isRetryableWriteError)(error)) {
16309
+ if (firstAttemptErr instanceof error_1.MongoError && (0, error_1.isRetryableWriteError)(firstAttemptErr)) {
15785
16310
  if (command2.commitTransaction) {
15786
16311
  session.unpin({ force: true });
15787
16312
  command2.writeConcern = Object.assign({ wtimeout: 1e4 }, command2.writeConcern, {
15788
16313
  w: "majority"
15789
16314
  });
15790
16315
  }
15791
- (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(command2, {
15792
- session,
15793
- readPreference: read_preference_1.ReadPreference.primary,
15794
- bypassPinningCheck: true
15795
- })).then(() => commandHandler(), commandHandler);
15796
- return;
16316
+ try {
16317
+ await (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(command2, {
16318
+ session,
16319
+ readPreference: read_preference_1.ReadPreference.primary,
16320
+ bypassPinningCheck: true
16321
+ }));
16322
+ if (commandName !== "commitTransaction") {
16323
+ session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
16324
+ if (session.loadBalanced) {
16325
+ maybeClearPinnedConnection(session, { force: false });
16326
+ }
16327
+ } else {
16328
+ session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED);
16329
+ }
16330
+ } catch (secondAttemptErr) {
16331
+ handleEndTransactionError(session, commandName, secondAttemptErr);
16332
+ }
16333
+ } else {
16334
+ handleEndTransactionError(session, commandName, firstAttemptErr);
15797
16335
  }
15798
- commandHandler(error);
15799
- };
15800
- (0, execute_operation_1.executeOperation)(session.client, new run_command_1.RunAdminCommandOperation(command2, {
15801
- session,
15802
- readPreference: read_preference_1.ReadPreference.primary,
15803
- bypassPinningCheck: true
15804
- })).then(() => handleFirstCommandAttempt(), handleFirstCommandAttempt);
16336
+ }
16337
+ }
16338
+ var handleEndTransactionError = function(session, commandName, error) {
16339
+ if (commandName !== "commitTransaction") {
16340
+ session.transaction.transition(transactions_1.TxnState.TRANSACTION_ABORTED);
16341
+ if (session.loadBalanced) {
16342
+ maybeClearPinnedConnection(session, { force: false });
16343
+ }
16344
+ return;
16345
+ }
16346
+ session.transaction.transition(transactions_1.TxnState.TRANSACTION_COMMITTED);
16347
+ if (error instanceof error_1.MongoError) {
16348
+ if ((0, error_1.isRetryableWriteError)(error) || error instanceof error_1.MongoWriteConcernError || isMaxTimeMSExpiredError(error)) {
16349
+ if (isUnknownTransactionCommitResult(error)) {
16350
+ error.addErrorLabel(error_1.MongoErrorLabel.UnknownTransactionCommitResult);
16351
+ session.unpin({ error });
16352
+ }
16353
+ } else if (error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) {
16354
+ session.unpin({ error });
16355
+ }
16356
+ }
16357
+ throw error;
15805
16358
  };
15806
16359
  var applySession = function(session, command2, options) {
15807
16360
  if (session.hasEnded) {
@@ -15867,7 +16420,7 @@ var require_sessions = __commonJS((exports) => {
15867
16420
  session.transaction._recoveryToken = document.recoveryToken;
15868
16421
  }
15869
16422
  if (session?.[kSnapshotEnabled] && session[kSnapshotTime] == null) {
15870
- const atClusterTime = document.cursor?.atClusterTime || document.atClusterTime;
16423
+ const atClusterTime = document.atClusterTime;
15871
16424
  if (atClusterTime) {
15872
16425
  session[kSnapshotTime] = atClusterTime;
15873
16426
  }
@@ -15876,7 +16429,6 @@ var require_sessions = __commonJS((exports) => {
15876
16429
  var _a;
15877
16430
  Object.defineProperty(exports, "__esModule", { value: true });
15878
16431
  exports.updateSessionFromResponse = exports.applySession = exports.ServerSessionPool = exports.ServerSession = exports.maybeClearPinnedConnection = exports.ClientSession = undefined;
15879
- var util_1 = import.meta.require("util");
15880
16432
  var bson_1 = require_bson2();
15881
16433
  var metrics_1 = require_metrics();
15882
16434
  var shared_1 = require_shared();
@@ -15919,6 +16471,7 @@ var require_sessions = __commonJS((exports) => {
15919
16471
  this.sessionPool = sessionPool;
15920
16472
  this.hasEnded = false;
15921
16473
  this.clientOptions = clientOptions;
16474
+ this.timeoutMS = options.defaultTimeoutMS ?? client.options?.timeoutMS;
15922
16475
  this.explicit = !!options.explicit;
15923
16476
  this[kServerSession] = this.explicit ? this.sessionPool.acquire() : null;
15924
16477
  this[kTxnNumberIncrement] = 0;
@@ -15929,7 +16482,7 @@ var require_sessions = __commonJS((exports) => {
15929
16482
  this.clusterTime = options.initialClusterTime;
15930
16483
  this.operationTime = undefined;
15931
16484
  this.owner = options.owner;
15932
- this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions);
16485
+ this.defaultTransactionOptions = { ...options.defaultTransactionOptions };
15933
16486
  this.transaction = new transactions_1.Transaction;
15934
16487
  }
15935
16488
  get id() {
@@ -15991,7 +16544,8 @@ var require_sessions = __commonJS((exports) => {
15991
16544
  this.hasEnded = true;
15992
16545
  this.emit("ended", this);
15993
16546
  }
15994
- } catch {
16547
+ } catch (error) {
16548
+ (0, utils_1.squashError)(error);
15995
16549
  } finally {
15996
16550
  maybeClearPinnedConnection(this, { force: true, ...options });
15997
16551
  }
@@ -16056,17 +16610,17 @@ var require_sessions = __commonJS((exports) => {
16056
16610
  this.transaction.transition(transactions_1.TxnState.STARTING_TRANSACTION);
16057
16611
  }
16058
16612
  async commitTransaction() {
16059
- return endTransactionAsync(this, "commitTransaction");
16613
+ return await endTransaction(this, "commitTransaction");
16060
16614
  }
16061
16615
  async abortTransaction() {
16062
- return endTransactionAsync(this, "abortTransaction");
16616
+ return await endTransaction(this, "abortTransaction");
16063
16617
  }
16064
16618
  toBSON() {
16065
16619
  throw new error_1.MongoRuntimeError("ClientSession cannot be serialized to BSON.");
16066
16620
  }
16067
16621
  async withTransaction(fn, options) {
16068
16622
  const startTime = (0, utils_1.now)();
16069
- return attemptTransaction(this, startTime, fn, options);
16623
+ return await attemptTransaction(this, startTime, fn, options);
16070
16624
  }
16071
16625
  }
16072
16626
  exports.ClientSession = ClientSession;
@@ -16083,7 +16637,6 @@ var require_sessions = __commonJS((exports) => {
16083
16637
  transactions_1.TxnState.TRANSACTION_COMMITTED,
16084
16638
  transactions_1.TxnState.TRANSACTION_ABORTED
16085
16639
  ]);
16086
- var endTransactionAsync = (0, util_1.promisify)(endTransaction);
16087
16640
 
16088
16641
  class ServerSession {
16089
16642
  constructor() {
@@ -16158,8 +16711,10 @@ var require_sessions = __commonJS((exports) => {
16158
16711
 
16159
16712
  // node_modules/mongodb/lib/cursor/abstract_cursor.js
16160
16713
  var require_abstract_cursor = __commonJS((exports) => {
16161
- async function next(cursor, { blocking, transform }) {
16714
+ async function next(cursor, { blocking, transform, shift }) {
16162
16715
  if (cursor.closed) {
16716
+ if (!shift)
16717
+ return false;
16163
16718
  return null;
16164
16719
  }
16165
16720
  do {
@@ -16167,12 +16722,18 @@ var require_abstract_cursor = __commonJS((exports) => {
16167
16722
  await cursor[kInit]();
16168
16723
  }
16169
16724
  if (cursor[kDocuments].length !== 0) {
16170
- const doc = cursor[kDocuments].shift();
16725
+ if (!shift)
16726
+ return true;
16727
+ const doc = cursor[kDocuments].shift(cursor[kOptions]);
16171
16728
  if (doc != null && transform && cursor[kTransform]) {
16172
16729
  try {
16173
16730
  return cursor[kTransform](doc);
16174
16731
  } catch (error) {
16175
- await cleanupCursor(cursor, { error, needsToEmitClosed: true }).catch(() => null);
16732
+ try {
16733
+ await cleanupCursor(cursor, { error, needsToEmitClosed: true });
16734
+ } catch (error2) {
16735
+ (0, utils_1.squashError)(error2);
16736
+ }
16176
16737
  throw error;
16177
16738
  }
16178
16739
  }
@@ -16180,27 +16741,40 @@ var require_abstract_cursor = __commonJS((exports) => {
16180
16741
  }
16181
16742
  if (cursor.isDead) {
16182
16743
  await cleanupCursor(cursor, {});
16744
+ if (!shift)
16745
+ return false;
16183
16746
  return null;
16184
16747
  }
16185
16748
  const batchSize = cursor[kOptions].batchSize || 1000;
16186
16749
  try {
16187
16750
  const response = await cursor.getMore(batchSize);
16188
- if (response) {
16751
+ if (responses_1.CursorResponse.is(response)) {
16752
+ cursor[kId] = response.id;
16753
+ cursor[kDocuments] = response;
16754
+ } else if (response) {
16189
16755
  const cursorId = typeof response.cursor.id === "number" ? bson_1.Long.fromNumber(response.cursor.id) : typeof response.cursor.id === "bigint" ? bson_1.Long.fromBigInt(response.cursor.id) : response.cursor.id;
16190
16756
  cursor[kDocuments].pushMany(response.cursor.nextBatch);
16191
16757
  cursor[kId] = cursorId;
16192
16758
  }
16193
16759
  } catch (error) {
16194
- await cleanupCursor(cursor, { error }).catch(() => null);
16760
+ try {
16761
+ await cleanupCursor(cursor, { error, needsToEmitClosed: true });
16762
+ } catch (error2) {
16763
+ (0, utils_1.squashError)(error2);
16764
+ }
16195
16765
  throw error;
16196
16766
  }
16197
16767
  if (cursor.isDead) {
16198
16768
  await cleanupCursor(cursor, {});
16199
16769
  }
16200
16770
  if (cursor[kDocuments].length === 0 && blocking === false) {
16771
+ if (!shift)
16772
+ return false;
16201
16773
  return null;
16202
16774
  }
16203
16775
  } while (!cursor.isDead || cursor[kDocuments].length !== 0);
16776
+ if (!shift)
16777
+ return false;
16204
16778
  return null;
16205
16779
  }
16206
16780
  async function cleanupCursor(cursor, options) {
@@ -16212,7 +16786,7 @@ var require_abstract_cursor = __commonJS((exports) => {
16212
16786
  const needsToEmitClosed = options?.needsToEmitClosed ?? cursor[kDocuments].length === 0;
16213
16787
  if (error) {
16214
16788
  if (cursor.loadBalanced && error instanceof error_1.MongoNetworkError) {
16215
- return completeCleanup();
16789
+ return await completeCleanup();
16216
16790
  }
16217
16791
  }
16218
16792
  if (cursorId == null || server == null || cursorId.isZero() || cursorNs == null) {
@@ -16251,10 +16825,12 @@ var require_abstract_cursor = __commonJS((exports) => {
16251
16825
  }
16252
16826
  cursor[kKilled] = true;
16253
16827
  if (session.hasEnded) {
16254
- return completeCleanup();
16828
+ return await completeCleanup();
16255
16829
  }
16256
16830
  try {
16257
- await (0, execute_operation_1.executeOperation)(cursor[kClient], new kill_cursors_1.KillCursorsOperation(cursorId, cursorNs, server, { session })).catch(() => null);
16831
+ await (0, execute_operation_1.executeOperation)(cursor[kClient], new kill_cursors_1.KillCursorsOperation(cursorId, cursorNs, server, { session }));
16832
+ } catch (error2) {
16833
+ (0, utils_1.squashError)(error2);
16258
16834
  } finally {
16259
16835
  await completeCleanup();
16260
16836
  }
@@ -16268,6 +16844,7 @@ var require_abstract_cursor = __commonJS((exports) => {
16268
16844
  exports.assertUninitialized = exports.AbstractCursor = exports.CURSOR_FLAGS = undefined;
16269
16845
  var stream_1 = import.meta.require("stream");
16270
16846
  var bson_1 = require_bson2();
16847
+ var responses_1 = require_responses();
16271
16848
  var error_1 = require_error();
16272
16849
  var mongo_types_1 = require_mongo_types();
16273
16850
  var execute_operation_1 = require_execute_operation();
@@ -16315,6 +16892,7 @@ var require_abstract_cursor = __commonJS((exports) => {
16315
16892
  readPreference: options.readPreference && options.readPreference instanceof read_preference_1.ReadPreference ? options.readPreference : read_preference_1.ReadPreference.primary,
16316
16893
  ...(0, bson_1.pluckBSONSerializeOptions)(options)
16317
16894
  };
16895
+ this[kOptions].timeoutMS = options.timeoutMS;
16318
16896
  const readConcern = read_concern_1.ReadConcern.fromOptions(options);
16319
16897
  if (readConcern) {
16320
16898
  this[kOptions].readConcern = readConcern;
@@ -16383,7 +16961,7 @@ var require_abstract_cursor = __commonJS((exports) => {
16383
16961
  const bufferedDocs = [];
16384
16962
  const documentsToRead = Math.min(number ?? this[kDocuments].length, this[kDocuments].length);
16385
16963
  for (let count = 0;count < documentsToRead; count++) {
16386
- const document = this[kDocuments].shift();
16964
+ const document = this[kDocuments].shift(this[kOptions]);
16387
16965
  if (document != null) {
16388
16966
  bufferedDocs.push(document);
16389
16967
  }
@@ -16400,7 +16978,11 @@ var require_abstract_cursor = __commonJS((exports) => {
16400
16978
  if (document === null) {
16401
16979
  if (!this.closed) {
16402
16980
  const message = "Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.";
16403
- await cleanupCursor(this, { needsToEmitClosed: true }).catch(() => null);
16981
+ try {
16982
+ await cleanupCursor(this, { needsToEmitClosed: true });
16983
+ } catch (error) {
16984
+ (0, utils_1.squashError)(error);
16985
+ }
16404
16986
  throw new error_1.MongoAPIError(message);
16405
16987
  }
16406
16988
  break;
@@ -16412,7 +16994,11 @@ var require_abstract_cursor = __commonJS((exports) => {
16412
16994
  }
16413
16995
  } finally {
16414
16996
  if (!this.closed) {
16415
- await this.close().catch(() => null);
16997
+ try {
16998
+ await this.close();
16999
+ } catch (error) {
17000
+ (0, utils_1.squashError)(error);
17001
+ }
16416
17002
  }
16417
17003
  }
16418
17004
  }
@@ -16444,24 +17030,19 @@ var require_abstract_cursor = __commonJS((exports) => {
16444
17030
  if (this[kDocuments].length !== 0) {
16445
17031
  return true;
16446
17032
  }
16447
- const doc = await next(this, { blocking: true, transform: false });
16448
- if (doc) {
16449
- this[kDocuments].unshift(doc);
16450
- return true;
16451
- }
16452
- return false;
17033
+ return await next(this, { blocking: true, transform: false, shift: false });
16453
17034
  }
16454
17035
  async next() {
16455
17036
  if (this[kId] === bson_1.Long.ZERO) {
16456
17037
  throw new error_1.MongoCursorExhaustedError;
16457
17038
  }
16458
- return next(this, { blocking: true, transform: true });
17039
+ return await next(this, { blocking: true, transform: true, shift: true });
16459
17040
  }
16460
17041
  async tryNext() {
16461
17042
  if (this[kId] === bson_1.Long.ZERO) {
16462
17043
  throw new error_1.MongoCursorExhaustedError;
16463
17044
  }
16464
- return next(this, { blocking: false, transform: true });
17045
+ return await next(this, { blocking: false, transform: true, shift: true });
16465
17046
  }
16466
17047
  async forEach(iterator) {
16467
17048
  if (typeof iterator !== "function") {
@@ -16560,26 +17141,32 @@ var require_abstract_cursor = __commonJS((exports) => {
16560
17141
  if (session) {
16561
17142
  if (session.explicit === false) {
16562
17143
  if (!session.hasEnded) {
16563
- session.endSession().catch(() => null);
17144
+ session.endSession().then(undefined, utils_1.squashError);
16564
17145
  }
16565
17146
  this[kSession] = this.client.startSession({ owner: this, explicit: false });
16566
17147
  }
16567
17148
  }
16568
17149
  }
16569
- async getMore(batchSize) {
17150
+ async getMore(batchSize, useCursorResponse = false) {
16570
17151
  const getMoreOperation = new get_more_1.GetMoreOperation(this[kNamespace], this[kId], this[kServer], {
16571
17152
  ...this[kOptions],
16572
17153
  session: this[kSession],
16573
- batchSize
17154
+ batchSize,
17155
+ useCursorResponse
16574
17156
  });
16575
- return (0, execute_operation_1.executeOperation)(this[kClient], getMoreOperation);
17157
+ return await (0, execute_operation_1.executeOperation)(this[kClient], getMoreOperation);
16576
17158
  }
16577
17159
  async[kInit]() {
16578
17160
  try {
16579
17161
  const state = await this._initialize(this[kSession]);
16580
17162
  const response = state.response;
16581
17163
  this[kServer] = state.server;
16582
- if (response.cursor) {
17164
+ if (responses_1.CursorResponse.is(response)) {
17165
+ this[kId] = response.id;
17166
+ if (response.ns)
17167
+ this[kNamespace] = response.ns;
17168
+ this[kDocuments] = response;
17169
+ } else if (response.cursor) {
16583
17170
  this[kId] = typeof response.cursor.id === "number" ? bson_1.Long.fromNumber(response.cursor.id) : typeof response.cursor.id === "bigint" ? bson_1.Long.fromBigInt(response.cursor.id) : response.cursor.id;
16584
17171
  if (response.cursor.ns) {
16585
17172
  this[kNamespace] = (0, utils_1.ns)(response.cursor.ns);
@@ -16626,11 +17213,11 @@ var require_abstract_cursor = __commonJS((exports) => {
16626
17213
  this._cursor.close().then(() => callback(error), (closeError) => callback(closeError));
16627
17214
  }
16628
17215
  _readNext() {
16629
- next(this._cursor, { blocking: true, transform: true }).then((result) => {
17216
+ next(this._cursor, { blocking: true, transform: true, shift: true }).then((result) => {
16630
17217
  if (result == null) {
16631
17218
  this.push(null);
16632
17219
  } else if (this.destroyed) {
16633
- this._cursor.close().catch(() => null);
17220
+ this._cursor.close().then(undefined, utils_1.squashError);
16634
17221
  } else {
16635
17222
  if (this.push(result)) {
16636
17223
  return this._readNext();
@@ -16639,7 +17226,7 @@ var require_abstract_cursor = __commonJS((exports) => {
16639
17226
  }
16640
17227
  }, (err) => {
16641
17228
  if (err.message.match(/server is closed/)) {
16642
- this._cursor.close().catch(() => null);
17229
+ this._cursor.close().then(undefined, utils_1.squashError);
16643
17230
  return this.push(null);
16644
17231
  }
16645
17232
  if (err.message.match(/operation was interrupted/)) {
@@ -16691,66 +17278,49 @@ var require_aggregation_cursor = __commonJS((exports) => {
16691
17278
  return { server: aggregateOperation.server, session, response };
16692
17279
  }
16693
17280
  async explain(verbosity) {
16694
- return (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], {
17281
+ return await (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], {
16695
17282
  ...this[kOptions],
16696
17283
  ...this.cursorOptions,
16697
17284
  explain: verbosity ?? true
16698
17285
  }));
16699
17286
  }
16700
- group($group) {
17287
+ addStage(stage) {
16701
17288
  (0, abstract_cursor_1.assertUninitialized)(this);
16702
- this[kPipeline].push({ $group });
17289
+ this[kPipeline].push(stage);
16703
17290
  return this;
16704
17291
  }
17292
+ group($group) {
17293
+ return this.addStage({ $group });
17294
+ }
16705
17295
  limit($limit) {
16706
- (0, abstract_cursor_1.assertUninitialized)(this);
16707
- this[kPipeline].push({ $limit });
16708
- return this;
17296
+ return this.addStage({ $limit });
16709
17297
  }
16710
17298
  match($match) {
16711
- (0, abstract_cursor_1.assertUninitialized)(this);
16712
- this[kPipeline].push({ $match });
16713
- return this;
17299
+ return this.addStage({ $match });
16714
17300
  }
16715
17301
  out($out) {
16716
- (0, abstract_cursor_1.assertUninitialized)(this);
16717
- this[kPipeline].push({ $out });
16718
- return this;
17302
+ return this.addStage({ $out });
16719
17303
  }
16720
17304
  project($project) {
16721
- (0, abstract_cursor_1.assertUninitialized)(this);
16722
- this[kPipeline].push({ $project });
16723
- return this;
17305
+ return this.addStage({ $project });
16724
17306
  }
16725
17307
  lookup($lookup) {
16726
- (0, abstract_cursor_1.assertUninitialized)(this);
16727
- this[kPipeline].push({ $lookup });
16728
- return this;
17308
+ return this.addStage({ $lookup });
16729
17309
  }
16730
17310
  redact($redact) {
16731
- (0, abstract_cursor_1.assertUninitialized)(this);
16732
- this[kPipeline].push({ $redact });
16733
- return this;
17311
+ return this.addStage({ $redact });
16734
17312
  }
16735
17313
  skip($skip) {
16736
- (0, abstract_cursor_1.assertUninitialized)(this);
16737
- this[kPipeline].push({ $skip });
16738
- return this;
17314
+ return this.addStage({ $skip });
16739
17315
  }
16740
17316
  sort($sort) {
16741
- (0, abstract_cursor_1.assertUninitialized)(this);
16742
- this[kPipeline].push({ $sort });
16743
- return this;
17317
+ return this.addStage({ $sort });
16744
17318
  }
16745
17319
  unwind($unwind) {
16746
- (0, abstract_cursor_1.assertUninitialized)(this);
16747
- this[kPipeline].push({ $unwind });
16748
- return this;
17320
+ return this.addStage({ $unwind });
16749
17321
  }
16750
17322
  geoNear($geoNear) {
16751
- (0, abstract_cursor_1.assertUninitialized)(this);
16752
- this[kPipeline].push({ $geoNear });
16753
- return this;
17323
+ return this.addStage({ $geoNear });
16754
17324
  }
16755
17325
  }
16756
17326
  exports.AggregationCursor = AggregationCursor;
@@ -16995,8 +17565,8 @@ var require_find = __commonJS((exports) => {
16995
17565
  var operation_1 = require_operation();
16996
17566
 
16997
17567
  class FindOperation extends command_1.CommandOperation {
16998
- constructor(collection, ns, filter = {}, options = {}) {
16999
- super(collection, options);
17568
+ constructor(ns, filter = {}, options = {}) {
17569
+ super(undefined, options);
17000
17570
  this.options = { ...options };
17001
17571
  delete this.options.writeConcern;
17002
17572
  this.ns = ns;
@@ -17015,12 +17585,12 @@ var require_find = __commonJS((exports) => {
17015
17585
  if (this.explain) {
17016
17586
  findCommand = (0, utils_1.decorateWithExplain)(findCommand, this.explain);
17017
17587
  }
17018
- return server.command(this.ns, findCommand, {
17588
+ return await server.command(this.ns, findCommand, {
17019
17589
  ...this.options,
17020
17590
  ...this.bsonOptions,
17021
17591
  documentsReturnedIn: "firstBatch",
17022
17592
  session
17023
- });
17593
+ }, undefined);
17024
17594
  }
17025
17595
  }
17026
17596
  exports.FindOperation = FindOperation;
@@ -17034,9 +17604,10 @@ var require_find = __commonJS((exports) => {
17034
17604
 
17035
17605
  // node_modules/mongodb/lib/cursor/find_cursor.js
17036
17606
  var require_find_cursor = __commonJS((exports) => {
17607
+ var _a;
17037
17608
  Object.defineProperty(exports, "__esModule", { value: true });
17038
17609
  exports.FindCursor = exports.FLAGS = undefined;
17039
- var bson_1 = require_bson2();
17610
+ var responses_1 = require_responses();
17040
17611
  var error_1 = require_error();
17041
17612
  var count_1 = require_count();
17042
17613
  var execute_operation_1 = require_execute_operation();
@@ -17059,6 +17630,7 @@ var require_find_cursor = __commonJS((exports) => {
17059
17630
  class FindCursor extends abstract_cursor_1.AbstractCursor {
17060
17631
  constructor(client, namespace, filter = {}, options = {}) {
17061
17632
  super(client, namespace, options);
17633
+ this[_a] = 0;
17062
17634
  this[kFilter] = filter;
17063
17635
  this[kBuiltOptions] = options;
17064
17636
  if (options.sort != null) {
@@ -17076,13 +17648,17 @@ var require_find_cursor = __commonJS((exports) => {
17076
17648
  return super.map(transform);
17077
17649
  }
17078
17650
  async _initialize(session) {
17079
- const findOperation = new find_1.FindOperation(undefined, this.namespace, this[kFilter], {
17651
+ const findOperation = new find_1.FindOperation(this.namespace, this[kFilter], {
17080
17652
  ...this[kBuiltOptions],
17081
17653
  ...this.cursorOptions,
17082
17654
  session
17083
17655
  });
17084
17656
  const response = await (0, execute_operation_1.executeOperation)(this.client, findOperation);
17085
- this[kNumReturned] = response.cursor?.firstBatch?.length;
17657
+ if (responses_1.CursorResponse.is(response)) {
17658
+ this[kNumReturned] = response.batchSize;
17659
+ } else {
17660
+ this[kNumReturned] = this[kNumReturned] + (response?.cursor?.firstBatch?.length ?? 0);
17661
+ }
17086
17662
  return { server: findOperation.server, session, response };
17087
17663
  }
17088
17664
  async getMore(batchSize) {
@@ -17091,13 +17667,19 @@ var require_find_cursor = __commonJS((exports) => {
17091
17667
  const limit = this[kBuiltOptions].limit;
17092
17668
  batchSize = limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize;
17093
17669
  if (batchSize <= 0) {
17094
- await this.close().catch(() => null);
17095
- return { cursor: { id: bson_1.Long.ZERO, nextBatch: [] } };
17670
+ try {
17671
+ await this.close();
17672
+ } catch (error) {
17673
+ (0, utils_1.squashError)(error);
17674
+ }
17675
+ return responses_1.CursorResponse.emptyGetMore;
17096
17676
  }
17097
17677
  }
17098
- const response = await super.getMore(batchSize);
17099
- if (response) {
17100
- this[kNumReturned] = this[kNumReturned] + response.cursor.nextBatch.length;
17678
+ const response = await super.getMore(batchSize, false);
17679
+ if (responses_1.CursorResponse.is(response)) {
17680
+ this[kNumReturned] = this[kNumReturned] + response.batchSize;
17681
+ } else {
17682
+ this[kNumReturned] = this[kNumReturned] + (response?.cursor?.nextBatch?.length ?? 0);
17101
17683
  }
17102
17684
  return response;
17103
17685
  }
@@ -17106,14 +17688,14 @@ var require_find_cursor = __commonJS((exports) => {
17106
17688
  if (typeof options === "boolean") {
17107
17689
  throw new error_1.MongoInvalidArgumentError("Invalid first parameter to count");
17108
17690
  }
17109
- return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this[kFilter], {
17691
+ return await (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this[kFilter], {
17110
17692
  ...this[kBuiltOptions],
17111
17693
  ...this.cursorOptions,
17112
17694
  ...options
17113
17695
  }));
17114
17696
  }
17115
17697
  async explain(verbosity) {
17116
- return (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(undefined, this.namespace, this[kFilter], {
17698
+ return await (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(this.namespace, this[kFilter], {
17117
17699
  ...this[kBuiltOptions],
17118
17700
  ...this.cursorOptions,
17119
17701
  explain: verbosity ?? true
@@ -17266,6 +17848,7 @@ var require_find_cursor = __commonJS((exports) => {
17266
17848
  }
17267
17849
  }
17268
17850
  exports.FindCursor = FindCursor;
17851
+ _a = kNumReturned;
17269
17852
  });
17270
17853
 
17271
17854
  // node_modules/mongodb/lib/operations/indexes.js
@@ -17276,7 +17859,7 @@ var require_indexes = __commonJS((exports) => {
17276
17859
  var isSingleIndexTuple = function(t) {
17277
17860
  return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]);
17278
17861
  };
17279
- var makeIndexSpec = function(indexSpec, options) {
17862
+ var constructIndexDescriptionMap = function(indexSpec) {
17280
17863
  const key = new Map;
17281
17864
  const indexSpecs = !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec;
17282
17865
  for (const spec of indexSpecs) {
@@ -17294,15 +17877,17 @@ var require_indexes = __commonJS((exports) => {
17294
17877
  }
17295
17878
  }
17296
17879
  }
17297
- return { ...options, key };
17880
+ return key;
17881
+ };
17882
+ var resolveIndexDescription = function(description) {
17883
+ const validProvidedOptions = Object.entries(description).filter(([optionName]) => VALID_INDEX_OPTIONS.has(optionName));
17884
+ return Object.fromEntries(validProvidedOptions.map(([name, value]) => name === "version" ? ["v", value] : [name, value]));
17298
17885
  };
17299
17886
  Object.defineProperty(exports, "__esModule", { value: true });
17300
- exports.IndexInformationOperation = exports.IndexExistsOperation = exports.ListIndexesOperation = exports.DropIndexOperation = exports.EnsureIndexOperation = exports.CreateIndexOperation = exports.CreateIndexesOperation = exports.IndexesOperation = undefined;
17887
+ exports.ListIndexesOperation = exports.DropIndexOperation = exports.CreateIndexesOperation = undefined;
17301
17888
  var error_1 = require_error();
17302
- var read_preference_1 = require_read_preference();
17303
17889
  var utils_1 = require_utils2();
17304
17890
  var command_1 = require_command();
17305
- var common_functions_1 = require_common_functions();
17306
17891
  var operation_1 = require_operation();
17307
17892
  var VALID_INDEX_OPTIONS = new Set([
17308
17893
  "background",
@@ -17327,28 +17912,6 @@ var require_indexes = __commonJS((exports) => {
17327
17912
  "wildcardProjection"
17328
17913
  ]);
17329
17914
 
17330
- class IndexesOperation extends operation_1.AbstractOperation {
17331
- constructor(collection, options) {
17332
- super(options);
17333
- this.options = options;
17334
- this.collection = collection;
17335
- }
17336
- get commandName() {
17337
- return "listIndexes";
17338
- }
17339
- async execute(_server, session) {
17340
- const coll = this.collection;
17341
- const options = this.options;
17342
- return (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, {
17343
- full: true,
17344
- ...options,
17345
- readPreference: this.readPreference,
17346
- session
17347
- });
17348
- }
17349
- }
17350
- exports.IndexesOperation = IndexesOperation;
17351
-
17352
17915
  class CreateIndexesOperation extends command_1.CommandOperation {
17353
17916
  constructor(parent, collectionName, indexes, options) {
17354
17917
  super(parent, options);
@@ -17356,8 +17919,8 @@ var require_indexes = __commonJS((exports) => {
17356
17919
  this.collectionName = collectionName;
17357
17920
  this.indexes = indexes.map((userIndex) => {
17358
17921
  const key = userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key));
17359
- const name = userIndex.name != null ? userIndex.name : Array.from(key).flat().join("_");
17360
- const validIndexOptions = Object.fromEntries(Object.entries({ ...userIndex }).filter(([optionName]) => VALID_INDEX_OPTIONS.has(optionName)));
17922
+ const name = userIndex.name ?? Array.from(key).flat().join("_");
17923
+ const validIndexOptions = resolveIndexDescription(userIndex);
17361
17924
  return {
17362
17925
  ...validIndexOptions,
17363
17926
  name,
@@ -17365,6 +17928,14 @@ var require_indexes = __commonJS((exports) => {
17365
17928
  };
17366
17929
  });
17367
17930
  }
17931
+ static fromIndexDescriptionArray(parent, collectionName, indexes, options) {
17932
+ return new CreateIndexesOperation(parent, collectionName, indexes, options);
17933
+ }
17934
+ static fromIndexSpecification(parent, collectionName, indexSpec, options = {}) {
17935
+ const key = constructIndexDescriptionMap(indexSpec);
17936
+ const description = { ...options, key };
17937
+ return new CreateIndexesOperation(parent, collectionName, [description], options);
17938
+ }
17368
17939
  get commandName() {
17369
17940
  return "createIndexes";
17370
17941
  }
@@ -17387,41 +17958,6 @@ var require_indexes = __commonJS((exports) => {
17387
17958
  }
17388
17959
  exports.CreateIndexesOperation = CreateIndexesOperation;
17389
17960
 
17390
- class CreateIndexOperation extends CreateIndexesOperation {
17391
- constructor(parent, collectionName, indexSpec, options) {
17392
- super(parent, collectionName, [makeIndexSpec(indexSpec, options)], options);
17393
- }
17394
- async execute(server, session) {
17395
- const indexNames = await super.execute(server, session);
17396
- return indexNames[0];
17397
- }
17398
- }
17399
- exports.CreateIndexOperation = CreateIndexOperation;
17400
-
17401
- class EnsureIndexOperation extends CreateIndexOperation {
17402
- constructor(db, collectionName, indexSpec, options) {
17403
- super(db, collectionName, indexSpec, options);
17404
- this.readPreference = read_preference_1.ReadPreference.primary;
17405
- this.db = db;
17406
- this.collectionName = collectionName;
17407
- }
17408
- get commandName() {
17409
- return "listIndexes";
17410
- }
17411
- async execute(server, session) {
17412
- const indexName = this.indexes[0].name;
17413
- const indexes = await this.db.collection(this.collectionName).listIndexes({ session }).toArray().catch((error) => {
17414
- if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound)
17415
- return [];
17416
- throw error;
17417
- });
17418
- if (indexName && indexes.some((index) => index.name === indexName))
17419
- return indexName;
17420
- return super.execute(server, session);
17421
- }
17422
- }
17423
- exports.EnsureIndexOperation = EnsureIndexOperation;
17424
-
17425
17961
  class DropIndexOperation extends command_1.CommandOperation {
17426
17962
  constructor(collection, indexName, options) {
17427
17963
  super(collection, options);
@@ -17434,7 +17970,7 @@ var require_indexes = __commonJS((exports) => {
17434
17970
  }
17435
17971
  async execute(server, session) {
17436
17972
  const cmd = { dropIndexes: this.collection.collectionName, index: this.indexName };
17437
- return super.executeCommand(server, session, cmd);
17973
+ return await super.executeCommand(server, session, cmd);
17438
17974
  }
17439
17975
  }
17440
17976
  exports.DropIndexOperation = DropIndexOperation;
@@ -17456,65 +17992,16 @@ var require_indexes = __commonJS((exports) => {
17456
17992
  if (serverWireVersion >= 9 && this.options.comment !== undefined) {
17457
17993
  command2.comment = this.options.comment;
17458
17994
  }
17459
- return super.executeCommand(server, session, command2);
17995
+ return await super.executeCommand(server, session, command2);
17460
17996
  }
17461
17997
  }
17462
17998
  exports.ListIndexesOperation = ListIndexesOperation;
17463
-
17464
- class IndexExistsOperation extends operation_1.AbstractOperation {
17465
- constructor(collection, indexes, options) {
17466
- super(options);
17467
- this.options = options;
17468
- this.collection = collection;
17469
- this.indexes = indexes;
17470
- }
17471
- get commandName() {
17472
- return "listIndexes";
17473
- }
17474
- async execute(server, session) {
17475
- const coll = this.collection;
17476
- const indexes = this.indexes;
17477
- const info = await (0, common_functions_1.indexInformation)(coll.s.db, coll.collectionName, {
17478
- ...this.options,
17479
- readPreference: this.readPreference,
17480
- session
17481
- });
17482
- if (!Array.isArray(indexes))
17483
- return info[indexes] != null;
17484
- return indexes.every((indexName) => info[indexName] != null);
17485
- }
17486
- }
17487
- exports.IndexExistsOperation = IndexExistsOperation;
17488
-
17489
- class IndexInformationOperation extends operation_1.AbstractOperation {
17490
- constructor(db, name, options) {
17491
- super(options);
17492
- this.options = options ?? {};
17493
- this.db = db;
17494
- this.name = name;
17495
- }
17496
- get commandName() {
17497
- return "listIndexes";
17498
- }
17499
- async execute(server, session) {
17500
- const db = this.db;
17501
- const name = this.name;
17502
- return (0, common_functions_1.indexInformation)(db, name, {
17503
- ...this.options,
17504
- readPreference: this.readPreference,
17505
- session
17506
- });
17507
- }
17508
- }
17509
- exports.IndexInformationOperation = IndexInformationOperation;
17510
17999
  (0, operation_1.defineAspects)(ListIndexesOperation, [
17511
18000
  operation_1.Aspect.READ_OPERATION,
17512
18001
  operation_1.Aspect.RETRYABLE,
17513
18002
  operation_1.Aspect.CURSOR_CREATING
17514
18003
  ]);
17515
18004
  (0, operation_1.defineAspects)(CreateIndexesOperation, [operation_1.Aspect.WRITE_OPERATION]);
17516
- (0, operation_1.defineAspects)(CreateIndexOperation, [operation_1.Aspect.WRITE_OPERATION]);
17517
- (0, operation_1.defineAspects)(EnsureIndexOperation, [operation_1.Aspect.WRITE_OPERATION]);
17518
18005
  (0, operation_1.defineAspects)(DropIndexOperation, [operation_1.Aspect.WRITE_OPERATION]);
17519
18006
  });
17520
18007
 
@@ -17685,7 +18172,7 @@ var require_drop = __commonJS((exports) => {
17685
18172
  }
17686
18173
  }
17687
18174
  }
17688
- return this.executeWithoutEncryptedFieldsCheck(server, session);
18175
+ return await this.executeWithoutEncryptedFieldsCheck(server, session);
17689
18176
  }
17690
18177
  async executeWithoutEncryptedFieldsCheck(server, session) {
17691
18178
  await super.executeCommand(server, session, { drop: this.name });
@@ -18169,40 +18656,40 @@ var require_collection = __commonJS((exports) => {
18169
18656
  this.s.collectionHint = (0, utils_1.normalizeHintField)(v);
18170
18657
  }
18171
18658
  async insertOne(doc, options) {
18172
- return (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options)));
18659
+ return await (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options)));
18173
18660
  }
18174
18661
  async insertMany(docs, options) {
18175
- return (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options ?? { ordered: true })));
18662
+ return await (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options ?? { ordered: true })));
18176
18663
  }
18177
18664
  async bulkWrite(operations, options) {
18178
18665
  if (!Array.isArray(operations)) {
18179
18666
  throw new error_1.MongoInvalidArgumentError('Argument "operations" must be an array of documents');
18180
18667
  }
18181
- return (0, execute_operation_1.executeOperation)(this.client, new bulk_write_1.BulkWriteOperation(this, operations, (0, utils_1.resolveOptions)(this, options ?? { ordered: true })));
18668
+ return await (0, execute_operation_1.executeOperation)(this.client, new bulk_write_1.BulkWriteOperation(this, operations, (0, utils_1.resolveOptions)(this, options ?? { ordered: true })));
18182
18669
  }
18183
18670
  async updateOne(filter, update, options) {
18184
- return (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateOneOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
18671
+ return await (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateOneOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
18185
18672
  }
18186
18673
  async replaceOne(filter, replacement, options) {
18187
- return (0, execute_operation_1.executeOperation)(this.client, new update_2.ReplaceOneOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
18674
+ return await (0, execute_operation_1.executeOperation)(this.client, new update_2.ReplaceOneOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
18188
18675
  }
18189
18676
  async updateMany(filter, update, options) {
18190
- return (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateManyOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
18677
+ return await (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateManyOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
18191
18678
  }
18192
18679
  async deleteOne(filter = {}, options = {}) {
18193
- return (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
18680
+ return await (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
18194
18681
  }
18195
18682
  async deleteMany(filter = {}, options = {}) {
18196
- return (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
18683
+ return await (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
18197
18684
  }
18198
18685
  async rename(newName, options) {
18199
- return (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this, newName, {
18686
+ return await (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this, newName, {
18200
18687
  ...options,
18201
18688
  readPreference: read_preference_1.ReadPreference.PRIMARY
18202
18689
  }));
18203
18690
  }
18204
18691
  async drop(options) {
18205
- return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options));
18692
+ return await (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options));
18206
18693
  }
18207
18694
  async findOne(filter = {}, options = {}) {
18208
18695
  const cursor = this.find(filter, options).limit(-1).batchSize(1);
@@ -18214,19 +18701,20 @@ var require_collection = __commonJS((exports) => {
18214
18701
  return new find_cursor_1.FindCursor(this.client, this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options));
18215
18702
  }
18216
18703
  async options(options) {
18217
- return (0, execute_operation_1.executeOperation)(this.client, new options_operation_1.OptionsOperation(this, (0, utils_1.resolveOptions)(this, options)));
18704
+ return await (0, execute_operation_1.executeOperation)(this.client, new options_operation_1.OptionsOperation(this, (0, utils_1.resolveOptions)(this, options)));
18218
18705
  }
18219
18706
  async isCapped(options) {
18220
- return (0, execute_operation_1.executeOperation)(this.client, new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options)));
18707
+ return await (0, execute_operation_1.executeOperation)(this.client, new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options)));
18221
18708
  }
18222
18709
  async createIndex(indexSpec, options) {
18223
- return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexOperation(this, this.collectionName, indexSpec, (0, utils_1.resolveOptions)(this, options)));
18710
+ const indexes = await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexSpecification(this, this.collectionName, indexSpec, (0, utils_1.resolveOptions)(this, options)));
18711
+ return indexes[0];
18224
18712
  }
18225
18713
  async createIndexes(indexSpecs, options) {
18226
- return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexesOperation(this, this.collectionName, indexSpecs, (0, utils_1.resolveOptions)(this, { ...options, maxTimeMS: undefined })));
18714
+ return await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexDescriptionArray(this, this.collectionName, indexSpecs, (0, utils_1.resolveOptions)(this, { ...options, maxTimeMS: undefined })));
18227
18715
  }
18228
18716
  async dropIndex(indexName, options) {
18229
- return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, indexName, {
18717
+ return await (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, indexName, {
18230
18718
  ...(0, utils_1.resolveOptions)(this, options),
18231
18719
  readPreference: read_preference_1.ReadPreference.primary
18232
18720
  }));
@@ -18243,31 +18731,42 @@ var require_collection = __commonJS((exports) => {
18243
18731
  return new list_indexes_cursor_1.ListIndexesCursor(this, (0, utils_1.resolveOptions)(this, options));
18244
18732
  }
18245
18733
  async indexExists(indexes, options) {
18246
- return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexExistsOperation(this, indexes, (0, utils_1.resolveOptions)(this, options)));
18734
+ const indexNames = Array.isArray(indexes) ? indexes : [indexes];
18735
+ const allIndexes = new Set(await this.listIndexes(options).map(({ name }) => name).toArray());
18736
+ return indexNames.every((name) => allIndexes.has(name));
18247
18737
  }
18248
18738
  async indexInformation(options) {
18249
- return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexInformationOperation(this.s.db, this.collectionName, (0, utils_1.resolveOptions)(this, options)));
18739
+ return await this.indexes({
18740
+ ...options,
18741
+ full: options?.full ?? false
18742
+ });
18250
18743
  }
18251
18744
  async estimatedDocumentCount(options) {
18252
- return (0, execute_operation_1.executeOperation)(this.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options)));
18745
+ return await (0, execute_operation_1.executeOperation)(this.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options)));
18253
18746
  }
18254
18747
  async countDocuments(filter = {}, options = {}) {
18255
- return (0, execute_operation_1.executeOperation)(this.client, new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
18748
+ return await (0, execute_operation_1.executeOperation)(this.client, new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
18256
18749
  }
18257
18750
  async distinct(key, filter = {}, options = {}) {
18258
- return (0, execute_operation_1.executeOperation)(this.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options)));
18751
+ return await (0, execute_operation_1.executeOperation)(this.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options)));
18259
18752
  }
18260
18753
  async indexes(options) {
18261
- return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexesOperation(this, (0, utils_1.resolveOptions)(this, options)));
18754
+ const indexes = await this.listIndexes(options).toArray();
18755
+ const full = options?.full ?? true;
18756
+ if (full) {
18757
+ return indexes;
18758
+ }
18759
+ const object = Object.fromEntries(indexes.map(({ name, key }) => [name, Object.entries(key)]));
18760
+ return object;
18262
18761
  }
18263
18762
  async findOneAndDelete(filter, options) {
18264
- return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndDeleteOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
18763
+ return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndDeleteOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
18265
18764
  }
18266
18765
  async findOneAndReplace(filter, replacement, options) {
18267
- return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
18766
+ return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
18268
18767
  }
18269
18768
  async findOneAndUpdate(filter, update, options) {
18270
- return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
18769
+ return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
18271
18770
  }
18272
18771
  aggregate(pipeline = [], options) {
18273
18772
  if (!Array.isArray(pipeline)) {
@@ -18289,7 +18788,7 @@ var require_collection = __commonJS((exports) => {
18289
18788
  return new ordered_1.OrderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options));
18290
18789
  }
18291
18790
  async count(filter = {}, options = {}) {
18292
- return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.fullNamespace, filter, (0, utils_1.resolveOptions)(this, options)));
18791
+ return await (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.fullNamespace, filter, (0, utils_1.resolveOptions)(this, options)));
18293
18792
  }
18294
18793
  listSearchIndexes(indexNameOrOptions, options) {
18295
18794
  options = typeof indexNameOrOptions === "object" ? indexNameOrOptions : options == null ? {} : options;
@@ -18301,13 +18800,13 @@ var require_collection = __commonJS((exports) => {
18301
18800
  return index;
18302
18801
  }
18303
18802
  async createSearchIndexes(descriptions) {
18304
- return (0, execute_operation_1.executeOperation)(this.client, new create_1.CreateSearchIndexesOperation(this, descriptions));
18803
+ return await (0, execute_operation_1.executeOperation)(this.client, new create_1.CreateSearchIndexesOperation(this, descriptions));
18305
18804
  }
18306
18805
  async dropSearchIndex(name) {
18307
- return (0, execute_operation_1.executeOperation)(this.client, new drop_2.DropSearchIndexOperation(this, name));
18806
+ return await (0, execute_operation_1.executeOperation)(this.client, new drop_2.DropSearchIndexOperation(this, name));
18308
18807
  }
18309
18808
  async updateSearchIndex(name, definition) {
18310
- return (0, execute_operation_1.executeOperation)(this.client, new update_1.UpdateSearchIndexOperation(this, name, definition));
18809
+ return await (0, execute_operation_1.executeOperation)(this.client, new update_1.UpdateSearchIndexOperation(this, name, definition));
18311
18810
  }
18312
18811
  }
18313
18812
  exports.Collection = Collection;
@@ -18439,7 +18938,7 @@ var require_list_collections = __commonJS((exports) => {
18439
18938
  return "listCollections";
18440
18939
  }
18441
18940
  async execute(server, session) {
18442
- return super.executeCommand(server, session, this.generateCommand((0, utils_1.maxWireVersion)(server)));
18941
+ return await super.executeCommand(server, session, this.generateCommand((0, utils_1.maxWireVersion)(server)));
18443
18942
  }
18444
18943
  generateCommand(wireVersion) {
18445
18944
  const command2 = {
@@ -18562,9 +19061,10 @@ var require_run_command_cursor = __commonJS((exports) => {
18562
19061
  const getMoreOperation = new get_more_1.GetMoreOperation(this.namespace, this.id, this.server, {
18563
19062
  ...this.cursorOptions,
18564
19063
  session: this.session,
18565
- ...this.getMoreOptions
19064
+ ...this.getMoreOptions,
19065
+ useCursorResponse: false
18566
19066
  });
18567
- return (0, execute_operation_1.executeOperation)(this.client, getMoreOperation);
19067
+ return await (0, execute_operation_1.executeOperation)(this.client, getMoreOperation);
18568
19068
  }
18569
19069
  }
18570
19070
  exports.RunCommandCursor = RunCommandCursor;
@@ -18671,7 +19171,7 @@ var require_create_collection = __commonJS((exports) => {
18671
19171
  }
18672
19172
  const coll = await this.executeWithoutEncryptedFieldsCheck(server, session);
18673
19173
  if (encryptedFields) {
18674
- const createIndexOp = new indexes_1.CreateIndexOperation(db, name, { __safeContent__: 1 }, {});
19174
+ const createIndexOp = indexes_1.CreateIndexesOperation.fromIndexSpecification(db, name, { __safeContent__: 1 }, {});
18675
19175
  await createIndexOp.execute(server, session);
18676
19176
  }
18677
19177
  return coll;
@@ -18797,7 +19297,7 @@ var require_stats = __commonJS((exports) => {
18797
19297
  if (this.options.scale != null) {
18798
19298
  command2.scale = this.options.scale;
18799
19299
  }
18800
- return super.executeCommand(server, session, command2);
19300
+ return await super.executeCommand(server, session, command2);
18801
19301
  }
18802
19302
  }
18803
19303
  exports.DbStatsOperation = DbStatsOperation;
@@ -18853,7 +19353,8 @@ var require_db = __commonJS((exports) => {
18853
19353
  "enableUtf8Validation",
18854
19354
  "promoteValues",
18855
19355
  "compression",
18856
- "retryWrites"
19356
+ "retryWrites",
19357
+ "timeoutMS"
18857
19358
  ];
18858
19359
 
18859
19360
  class Db {
@@ -18902,10 +19403,10 @@ var require_db = __commonJS((exports) => {
18902
19403
  return this.s.namespace.toString();
18903
19404
  }
18904
19405
  async createCollection(name, options) {
18905
- return (0, execute_operation_1.executeOperation)(this.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
19406
+ return await (0, execute_operation_1.executeOperation)(this.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
18906
19407
  }
18907
19408
  async command(command2, options) {
18908
- return (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunCommandOperation(this, command2, {
19409
+ return await (0, execute_operation_1.executeOperation)(this.client, new run_command_1.RunCommandOperation(this, command2, {
18909
19410
  ...(0, bson_1.resolveBSONOptions)(options),
18910
19411
  session: options?.session,
18911
19412
  readPreference: options?.readPreference
@@ -18924,37 +19425,38 @@ var require_db = __commonJS((exports) => {
18924
19425
  return new collection_1.Collection(this, name, (0, utils_1.resolveOptions)(this, options));
18925
19426
  }
18926
19427
  async stats(options) {
18927
- return (0, execute_operation_1.executeOperation)(this.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options)));
19428
+ return await (0, execute_operation_1.executeOperation)(this.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options)));
18928
19429
  }
18929
19430
  listCollections(filter = {}, options = {}) {
18930
19431
  return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.resolveOptions)(this, options));
18931
19432
  }
18932
19433
  async renameCollection(fromCollection, toCollection, options) {
18933
- return (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, { ...options, new_collection: true, readPreference: read_preference_1.ReadPreference.primary }));
19434
+ return await (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, { ...options, new_collection: true, readPreference: read_preference_1.ReadPreference.primary }));
18934
19435
  }
18935
19436
  async dropCollection(name, options) {
18936
- return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
19437
+ return await (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
18937
19438
  }
18938
19439
  async dropDatabase(options) {
18939
- return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options)));
19440
+ return await (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options)));
18940
19441
  }
18941
19442
  async collections(options) {
18942
- return (0, execute_operation_1.executeOperation)(this.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options)));
19443
+ return await (0, execute_operation_1.executeOperation)(this.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options)));
18943
19444
  }
18944
19445
  async createIndex(name, indexSpec, options) {
18945
- return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexOperation(this, name, indexSpec, (0, utils_1.resolveOptions)(this, options)));
19446
+ const indexes = await (0, execute_operation_1.executeOperation)(this.client, indexes_1.CreateIndexesOperation.fromIndexSpecification(this, name, indexSpec, options));
19447
+ return indexes[0];
18946
19448
  }
18947
19449
  async removeUser(username, options) {
18948
- return (0, execute_operation_1.executeOperation)(this.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options)));
19450
+ return await (0, execute_operation_1.executeOperation)(this.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options)));
18949
19451
  }
18950
19452
  async setProfilingLevel(level, options) {
18951
- return (0, execute_operation_1.executeOperation)(this.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options)));
19453
+ return await (0, execute_operation_1.executeOperation)(this.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options)));
18952
19454
  }
18953
19455
  async profilingLevel(options) {
18954
- return (0, execute_operation_1.executeOperation)(this.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options)));
19456
+ return await (0, execute_operation_1.executeOperation)(this.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options)));
18955
19457
  }
18956
19458
  async indexInformation(name, options) {
18957
- return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexInformationOperation(this, name, (0, utils_1.resolveOptions)(this, options)));
19459
+ return await this.collection(name).indexInformation((0, utils_1.resolveOptions)(this, options));
18958
19460
  }
18959
19461
  watch(pipeline = [], options = {}) {
18960
19462
  if (!Array.isArray(pipeline)) {
@@ -18993,43 +19495,45 @@ var require_deps = __commonJS((exports) => {
18993
19495
  });
18994
19496
  };
18995
19497
  var getKerberos = function() {
19498
+ let kerberos;
18996
19499
  try {
18997
- exports.Kerberos = (()=>{throw new Error(`Cannot require module "kerberos"`);})();
18998
- return exports.Kerberos;
18999
- } catch {
19000
- return exports.Kerberos;
19500
+ kerberos = (()=>{throw new Error(`Cannot require module "kerberos"`);})();
19501
+ } catch (error) {
19502
+ kerberos = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `kerberos` not found. Please install it to enable kerberos authentication", { cause: error, dependencyName: "kerberos" }));
19001
19503
  }
19504
+ return kerberos;
19002
19505
  };
19003
19506
  var getZstdLibrary = function() {
19507
+ let ZStandard;
19004
19508
  try {
19005
- exports.ZStandard = (()=>{throw new Error(`Cannot require module "@mongodb-js/zstd"`);})();
19006
- return exports.ZStandard;
19007
- } catch {
19008
- return exports.ZStandard;
19509
+ ZStandard = (()=>{throw new Error(`Cannot require module "@mongodb-js/zstd"`);})();
19510
+ } catch (error) {
19511
+ ZStandard = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression", { cause: error, dependencyName: "zstd" }));
19009
19512
  }
19513
+ return ZStandard;
19010
19514
  };
19011
19515
  var getAwsCredentialProvider = function() {
19012
19516
  try {
19013
19517
  const credentialProvider = (()=>{throw new Error(`Cannot require module "@aws-sdk/credential-providers"`);})();
19014
19518
  return credentialProvider;
19015
- } catch {
19016
- return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@aws-sdk/credential-providers` not found. Please install it to enable getting aws credentials via the official sdk."));
19519
+ } catch (error) {
19520
+ return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@aws-sdk/credential-providers` not found. Please install it to enable getting aws credentials via the official sdk.", { cause: error, dependencyName: "@aws-sdk/credential-providers" }));
19017
19521
  }
19018
19522
  };
19019
19523
  var getGcpMetadata = function() {
19020
19524
  try {
19021
19525
  const credentialProvider = (()=>{throw new Error(`Cannot require module "gcp-metadata"`);})();
19022
19526
  return credentialProvider;
19023
- } catch {
19024
- return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `gcp-metadata` not found. Please install it to enable getting gcp credentials via the official sdk."));
19527
+ } catch (error) {
19528
+ return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `gcp-metadata` not found. Please install it to enable getting gcp credentials via the official sdk.", { cause: error, dependencyName: "gcp-metadata" }));
19025
19529
  }
19026
19530
  };
19027
19531
  var getSnappy = function() {
19028
19532
  try {
19029
19533
  const value = (()=>{throw new Error(`Cannot require module "snappy"`);})();
19030
19534
  return value;
19031
- } catch (cause) {
19032
- const kModuleError = new error_1.MongoMissingDependencyError("Optional module `snappy` not found. Please install it to enable snappy compression", { cause });
19535
+ } catch (error) {
19536
+ const kModuleError = new error_1.MongoMissingDependencyError("Optional module `snappy` not found. Please install it to enable snappy compression", { cause: error, dependencyName: "snappy" });
19033
19537
  return { kModuleError };
19034
19538
  }
19035
19539
  };
@@ -19037,37 +19541,40 @@ var require_deps = __commonJS((exports) => {
19037
19541
  try {
19038
19542
  const value = (()=>{throw new Error(`Cannot require module "socks"`);})();
19039
19543
  return value;
19040
- } catch (cause) {
19041
- const kModuleError = new error_1.MongoMissingDependencyError("Optional module `socks` not found. Please install it to connections over a SOCKS5 proxy", { cause });
19544
+ } catch (error) {
19545
+ const kModuleError = new error_1.MongoMissingDependencyError("Optional module `socks` not found. Please install it to connections over a SOCKS5 proxy", { cause: error, dependencyName: "socks" });
19042
19546
  return { kModuleError };
19043
19547
  }
19044
19548
  };
19549
+ var loadAws4 = function() {
19550
+ let aws4;
19551
+ try {
19552
+ aws4 = (()=>{throw new Error(`Cannot require module "aws4"`);})();
19553
+ } catch (error) {
19554
+ aws4 = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `aws4` not found. Please install it to enable AWS authentication", { cause: error, dependencyName: "aws4" }));
19555
+ }
19556
+ return aws4;
19557
+ };
19045
19558
  var getMongoDBClientEncryption = function() {
19046
19559
  let mongodbClientEncryption = null;
19047
19560
  try {
19048
19561
  mongodbClientEncryption = (()=>{throw new Error(`Cannot require module "mongodb-client-encryption"`);})();
19049
- } catch (cause) {
19050
- const kModuleError = new error_1.MongoMissingDependencyError("Optional module `mongodb-client-encryption` not found. Please install it to use auto encryption or ClientEncryption.", { cause });
19562
+ } catch (error) {
19563
+ const kModuleError = new error_1.MongoMissingDependencyError("Optional module `mongodb-client-encryption` not found. Please install it to use auto encryption or ClientEncryption.", { cause: error, dependencyName: "mongodb-client-encryption" });
19051
19564
  return { kModuleError };
19052
19565
  }
19053
19566
  return mongodbClientEncryption;
19054
19567
  };
19055
19568
  Object.defineProperty(exports, "__esModule", { value: true });
19056
- exports.getMongoDBClientEncryption = exports.aws4 = exports.getSocks = exports.getSnappy = exports.getGcpMetadata = exports.getAwsCredentialProvider = exports.getZstdLibrary = exports.ZStandard = exports.getKerberos = exports.Kerberos = undefined;
19569
+ exports.getMongoDBClientEncryption = exports.aws4 = exports.getSocks = exports.getSnappy = exports.getGcpMetadata = exports.getAwsCredentialProvider = exports.getZstdLibrary = exports.getKerberos = undefined;
19057
19570
  var error_1 = require_error();
19058
- exports.Kerberos = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `kerberos` not found. Please install it to enable kerberos authentication"));
19059
19571
  exports.getKerberos = getKerberos;
19060
- exports.ZStandard = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression"));
19061
19572
  exports.getZstdLibrary = getZstdLibrary;
19062
19573
  exports.getAwsCredentialProvider = getAwsCredentialProvider;
19063
19574
  exports.getGcpMetadata = getGcpMetadata;
19064
19575
  exports.getSnappy = getSnappy;
19065
19576
  exports.getSocks = getSocks;
19066
- exports.aws4 = makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `aws4` not found. Please install it to enable AWS authentication"));
19067
- try {
19068
- exports.aws4 = (()=>{throw new Error(`Cannot require module "aws4"`);})();
19069
- } catch {
19070
- }
19577
+ exports.aws4 = loadAws4();
19071
19578
  exports.getMongoDBClientEncryption = getMongoDBClientEncryption;
19072
19579
  });
19073
19580
 
@@ -19109,7 +19616,8 @@ var require_auth_provider = __commonJS((exports) => {
19109
19616
  // node_modules/mongodb/lib/cmap/auth/gssapi.js
19110
19617
  var require_gssapi = __commonJS((exports) => {
19111
19618
  async function externalCommand(connection, command2) {
19112
- return connection.command((0, utils_1.ns)("$external.$cmd"), command2, undefined);
19619
+ const response = await connection.command((0, utils_1.ns)("$external.$cmd"), command2);
19620
+ return response;
19113
19621
  }
19114
19622
  async function makeKerberosClient(authContext) {
19115
19623
  const { hostAddress } = authContext.options;
@@ -19135,7 +19643,7 @@ var require_gssapi = __commonJS((exports) => {
19135
19643
  if ("SERVICE_REALM" in mechanismProperties) {
19136
19644
  spn = `${spn}@${mechanismProperties.SERVICE_REALM}`;
19137
19645
  }
19138
- return initializeClient(spn, initOptions);
19646
+ return await initializeClient(spn, initOptions);
19139
19647
  }
19140
19648
  var saslStart = function(payload) {
19141
19649
  return {
@@ -19160,12 +19668,12 @@ var require_gssapi = __commonJS((exports) => {
19160
19668
  if (retries === 0) {
19161
19669
  throw error;
19162
19670
  }
19163
- return negotiate(client, retries - 1, payload);
19671
+ return await negotiate(client, retries - 1, payload);
19164
19672
  }
19165
19673
  }
19166
19674
  async function finalize(client, user, payload) {
19167
19675
  const response = await client.unwrap(payload);
19168
- return client.wrap(response || "", { user });
19676
+ return await client.wrap(response || "", { user });
19169
19677
  }
19170
19678
  async function performGSSAPICanonicalizeHostName(host, mechanismProperties) {
19171
19679
  const mode = mechanismProperties.CANONICALIZE_HOST_NAME;
@@ -19178,10 +19686,10 @@ var require_gssapi = __commonJS((exports) => {
19178
19686
  const results = await dns.promises.resolvePtr(address);
19179
19687
  return results.length > 0 ? results[0] : host;
19180
19688
  } catch (error) {
19181
- return resolveCname(host);
19689
+ return await resolveCname(host);
19182
19690
  }
19183
19691
  } else {
19184
- return resolveCname(host);
19692
+ return await resolveCname(host);
19185
19693
  }
19186
19694
  }
19187
19695
  async function resolveCname(host) {
@@ -23152,7 +23660,7 @@ var require_lib3 = __commonJS((exports) => {
23152
23660
  var require_package = __commonJS((exports, module) => {
23153
23661
  module.exports = {
23154
23662
  name: "mongodb",
23155
- version: "6.5.0",
23663
+ version: "6.6.1",
23156
23664
  description: "The official MongoDB driver for Node.js",
23157
23665
  main: "lib/index.js",
23158
23666
  files: [
@@ -23178,7 +23686,7 @@ var require_package = __commonJS((exports, module) => {
23178
23686
  },
23179
23687
  dependencies: {
23180
23688
  "@mongodb-js/saslprep": "^1.1.5",
23181
- bson: "^6.4.0",
23689
+ bson: "^6.7.0",
23182
23690
  "mongodb-connection-string-url": "^3.0.0"
23183
23691
  },
23184
23692
  peerDependencies: {
@@ -23217,19 +23725,19 @@ var require_package = __commonJS((exports, module) => {
23217
23725
  "@aws-sdk/credential-providers": "^3.515.0",
23218
23726
  "@iarna/toml": "^2.2.5",
23219
23727
  "@istanbuljs/nyc-config-typescript": "^1.0.2",
23220
- "@microsoft/api-extractor": "^7.40.6",
23728
+ "@microsoft/api-extractor": "^7.43.1",
23221
23729
  "@microsoft/tsdoc-config": "^0.16.2",
23222
23730
  "@mongodb-js/zstd": "^1.2.0",
23223
- "@octokit/core": "^5.1.0",
23224
- "@types/chai": "^4.3.11",
23731
+ "@octokit/core": "^6.1.2",
23732
+ "@types/chai": "^4.3.14",
23225
23733
  "@types/chai-subset": "^1.3.5",
23226
23734
  "@types/express": "^4.17.21",
23227
23735
  "@types/kerberos": "^1.1.5",
23228
23736
  "@types/mocha": "^10.0.6",
23229
- "@types/node": "^20.11.20",
23737
+ "@types/node": "^20.12.7",
23230
23738
  "@types/saslprep": "^1.0.3",
23231
- "@types/semver": "^7.5.7",
23232
- "@types/sinon": "^10.0.20",
23739
+ "@types/semver": "^7.5.8",
23740
+ "@types/sinon": "^17.0.3",
23233
23741
  "@types/sinon-chai": "^3.2.12",
23234
23742
  "@types/whatwg-url": "^11.0.4",
23235
23743
  "@typescript-eslint/eslint-plugin": "^5.62.0",
@@ -23239,28 +23747,30 @@ var require_package = __commonJS((exports, module) => {
23239
23747
  chalk: "^4.1.2",
23240
23748
  eslint: "^8.56.0",
23241
23749
  "eslint-config-prettier": "^8.10.0",
23750
+ "eslint-plugin-github": "^4.10.2",
23242
23751
  "eslint-plugin-import": "^2.29.1",
23752
+ "eslint-plugin-mocha": "^10.4.1",
23243
23753
  "eslint-plugin-prettier": "^4.2.1",
23244
23754
  "eslint-plugin-simple-import-sort": "^10.0.0",
23245
23755
  "eslint-plugin-tsdoc": "^0.2.17",
23246
23756
  "eslint-plugin-unused-imports": "^2.0.0",
23247
- express: "^4.18.2",
23757
+ express: "^4.19.2",
23248
23758
  "gcp-metadata": "^5.3.0",
23249
23759
  "js-yaml": "^4.1.0",
23250
- mocha: "^10.3.0",
23760
+ mocha: "^10.4.0",
23251
23761
  "mocha-sinon": "^2.1.2",
23252
23762
  "mongodb-client-encryption": "^6.0.0",
23253
23763
  "mongodb-legacy": "^6.0.1",
23254
23764
  nyc: "^15.1.0",
23255
23765
  prettier: "^2.8.8",
23256
23766
  semver: "^7.6.0",
23257
- sinon: "^15.2.0",
23767
+ sinon: "^17.0.1",
23258
23768
  "sinon-chai": "^3.7.0",
23259
23769
  snappy: "^7.2.2",
23260
23770
  socks: "^2.8.1",
23261
23771
  "source-map-support": "^0.5.21",
23262
23772
  "ts-node": "^10.9.2",
23263
- tsd: "^0.30.6",
23773
+ tsd: "^0.31.0",
23264
23774
  typescript: "5.0",
23265
23775
  "typescript-cached-transpile": "^0.0.6",
23266
23776
  "v8-heapsnapshot": "^1.3.1",
@@ -23295,7 +23805,7 @@ var require_package = __commonJS((exports, module) => {
23295
23805
  "check:test": "mocha --config test/mocha_mongodb.json test/integration",
23296
23806
  "check:unit": "mocha test/unit",
23297
23807
  "check:ts": "node ./node_modules/typescript/bin/tsc -v && node ./node_modules/typescript/bin/tsc --noEmit",
23298
- "check:atlas": "mocha --config test/manual/mocharc.json test/manual/atlas_connectivity.test.js",
23808
+ "check:atlas": "mocha --config test/manual/mocharc.json test/manual/atlas_connectivity.test.ts",
23299
23809
  "check:drivers-atlas-testing": "mocha --config test/mocha_mongodb.json test/atlas/drivers_atlas_testing.test.ts",
23300
23810
  "check:adl": "mocha --config test/mocha_mongodb.json test/manual/atlas-data-lake-testing",
23301
23811
  "check:aws": "nyc mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_aws.test.ts",
@@ -23308,6 +23818,7 @@ var require_package = __commonJS((exports, module) => {
23308
23818
  "check:socks5": "mocha --config test/manual/mocharc.json test/manual/socks5.test.ts",
23309
23819
  "check:csfle": "mocha --config test/mocha_mongodb.json test/integration/client-side-encryption",
23310
23820
  "check:snappy": "mocha test/unit/assorted/snappy.test.js",
23821
+ "check:x509": "mocha test/manual/x509_auth.test.ts",
23311
23822
  "fix:eslint": "npm run check:eslint -- --fix",
23312
23823
  prepare: "node etc/prepare.js",
23313
23824
  "preview:docs": "ts-node etc/docs/preview.ts",
@@ -23377,7 +23888,7 @@ var require_client_metadata = __commonJS((exports) => {
23377
23888
  };
23378
23889
  async function getContainerMetadata() {
23379
23890
  const containerMetadata = {};
23380
- dockerPromise ??= fs_1.promises.access("/.dockerenv").then(() => true, () => false);
23891
+ dockerPromise ??= (0, utils_1.fileIsAccessible)("/.dockerenv");
23381
23892
  const isDocker = await dockerPromise;
23382
23893
  const { KUBERNETES_SERVICE_HOST = "" } = process2.env;
23383
23894
  const isKubernetes = KUBERNETES_SERVICE_HOST.length > 0 ? true : false;
@@ -23463,11 +23974,11 @@ var require_client_metadata = __commonJS((exports) => {
23463
23974
  };
23464
23975
  Object.defineProperty(exports, "__esModule", { value: true });
23465
23976
  exports.getFAASEnv = exports.addContainerMetadata = exports.makeClientMetadata = exports.LimitedSizeDocument = undefined;
23466
- var fs_1 = import.meta.require("fs");
23467
23977
  var os = import.meta.require("os");
23468
23978
  var process2 = import.meta.require("process");
23469
23979
  var bson_1 = require_bson2();
23470
23980
  var error_1 = require_error();
23981
+ var utils_1 = require_utils2();
23471
23982
  var NODE_DRIVER_VERSION = require_package().version;
23472
23983
 
23473
23984
  class LimitedSizeDocument {
@@ -23504,7 +24015,7 @@ var require_client_metadata = __commonJS((exports) => {
23504
24015
  // node_modules/mongodb/lib/cmap/commands.js
23505
24016
  var require_commands = __commonJS((exports) => {
23506
24017
  Object.defineProperty(exports, "__esModule", { value: true });
23507
- exports.OpCompressedRequest = exports.OpMsgResponse = exports.OpMsgRequest = exports.OpQueryResponse = exports.OpQueryRequest = undefined;
24018
+ exports.OpCompressedRequest = exports.OpMsgResponse = exports.OpMsgRequest = exports.OpReply = exports.OpQueryRequest = undefined;
23508
24019
  var BSON = require_bson2();
23509
24020
  var error_1 = require_error();
23510
24021
  var compression_1 = require_compression();
@@ -23649,9 +24160,10 @@ var require_commands = __commonJS((exports) => {
23649
24160
  }
23650
24161
  exports.OpQueryRequest = OpQueryRequest;
23651
24162
 
23652
- class OpQueryResponse {
24163
+ class OpReply {
23653
24164
  constructor(message, msgHeader, msgBody, opts) {
23654
- this.documents = new Array(0);
24165
+ this.index = 0;
24166
+ this.sections = [];
23655
24167
  this.moreToCome = false;
23656
24168
  this.parsed = false;
23657
24169
  this.raw = message;
@@ -23677,55 +24189,32 @@ var require_commands = __commonJS((exports) => {
23677
24189
  isParsed() {
23678
24190
  return this.parsed;
23679
24191
  }
23680
- parse(options) {
24192
+ parse() {
23681
24193
  if (this.parsed)
23682
- return;
23683
- options = options ?? {};
23684
- const raw = options.raw || false;
23685
- const documentsReturnedIn = options.documentsReturnedIn || null;
23686
- const useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64;
23687
- const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs;
23688
- const promoteValues = options.promoteValues ?? this.opts.promoteValues;
23689
- const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers;
23690
- const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp;
23691
- let bsonSize;
23692
- const _options = {
23693
- useBigInt64,
23694
- promoteLongs,
23695
- promoteValues,
23696
- promoteBuffers,
23697
- bsonRegExp
23698
- };
24194
+ return this.sections[0];
23699
24195
  this.index = 20;
23700
24196
  this.responseFlags = this.data.readInt32LE(0);
23701
24197
  this.cursorId = new BSON.Long(this.data.readInt32LE(4), this.data.readInt32LE(8));
23702
24198
  this.startingFrom = this.data.readInt32LE(12);
23703
24199
  this.numberReturned = this.data.readInt32LE(16);
23704
- this.documents = new Array(this.numberReturned);
24200
+ if (this.numberReturned < 0 || this.numberReturned > 2 ** 32 - 1) {
24201
+ throw new RangeError(`OP_REPLY numberReturned is an invalid array length ${this.numberReturned}`);
24202
+ }
23705
24203
  this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0;
23706
24204
  this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0;
23707
24205
  this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0;
23708
24206
  this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0;
23709
24207
  for (let i = 0;i < this.numberReturned; i++) {
23710
- bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24;
23711
- if (raw) {
23712
- this.documents[i] = this.data.slice(this.index, this.index + bsonSize);
23713
- } else {
23714
- this.documents[i] = BSON.deserialize(this.data.slice(this.index, this.index + bsonSize), _options);
23715
- }
24208
+ const bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24;
24209
+ const section = this.data.subarray(this.index, this.index + bsonSize);
24210
+ this.sections.push(section);
23716
24211
  this.index = this.index + bsonSize;
23717
24212
  }
23718
- if (this.documents.length === 1 && documentsReturnedIn != null && raw) {
23719
- const fieldsAsRaw = {};
23720
- fieldsAsRaw[documentsReturnedIn] = true;
23721
- _options.fieldsAsRaw = fieldsAsRaw;
23722
- const doc = BSON.deserialize(this.documents[0], _options);
23723
- this.documents = [doc];
23724
- }
23725
24213
  this.parsed = true;
24214
+ return this.sections[0];
23726
24215
  }
23727
24216
  }
23728
- exports.OpQueryResponse = OpQueryResponse;
24217
+ exports.OpReply = OpReply;
23729
24218
  var OPTS_CHECKSUM_PRESENT = 1;
23730
24219
  var OPTS_MORE_TO_COME = 2;
23731
24220
  var OPTS_EXHAUST_ALLOWED = 1 << 16;
@@ -23796,6 +24285,8 @@ var require_commands = __commonJS((exports) => {
23796
24285
 
23797
24286
  class OpMsgResponse {
23798
24287
  constructor(message, msgHeader, msgBody, opts) {
24288
+ this.index = 0;
24289
+ this.sections = [];
23799
24290
  this.parsed = false;
23800
24291
  this.raw = message;
23801
24292
  this.data = msgBody;
@@ -23820,57 +24311,27 @@ var require_commands = __commonJS((exports) => {
23820
24311
  this.promoteValues = typeof this.opts.promoteValues === "boolean" ? this.opts.promoteValues : true;
23821
24312
  this.promoteBuffers = typeof this.opts.promoteBuffers === "boolean" ? this.opts.promoteBuffers : false;
23822
24313
  this.bsonRegExp = typeof this.opts.bsonRegExp === "boolean" ? this.opts.bsonRegExp : false;
23823
- this.documents = [];
23824
24314
  }
23825
24315
  isParsed() {
23826
24316
  return this.parsed;
23827
24317
  }
23828
- parse(options) {
24318
+ parse() {
23829
24319
  if (this.parsed)
23830
- return;
23831
- options = options ?? {};
24320
+ return this.sections[0];
23832
24321
  this.index = 4;
23833
- const raw = options.raw || false;
23834
- const documentsReturnedIn = options.documentsReturnedIn || null;
23835
- const useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64;
23836
- const promoteLongs = options.promoteLongs ?? this.opts.promoteLongs;
23837
- const promoteValues = options.promoteValues ?? this.opts.promoteValues;
23838
- const promoteBuffers = options.promoteBuffers ?? this.opts.promoteBuffers;
23839
- const bsonRegExp = options.bsonRegExp ?? this.opts.bsonRegExp;
23840
- const validation = this.parseBsonSerializationOptions(options);
23841
- const bsonOptions = {
23842
- useBigInt64,
23843
- promoteLongs,
23844
- promoteValues,
23845
- promoteBuffers,
23846
- bsonRegExp,
23847
- validation
23848
- };
23849
24322
  while (this.index < this.data.length) {
23850
24323
  const payloadType = this.data.readUInt8(this.index++);
23851
24324
  if (payloadType === 0) {
23852
24325
  const bsonSize = this.data.readUInt32LE(this.index);
23853
- const bin = this.data.slice(this.index, this.index + bsonSize);
23854
- this.documents.push(raw ? bin : BSON.deserialize(bin, bsonOptions));
24326
+ const bin = this.data.subarray(this.index, this.index + bsonSize);
24327
+ this.sections.push(bin);
23855
24328
  this.index += bsonSize;
23856
24329
  } else if (payloadType === 1) {
23857
24330
  throw new error_1.MongoRuntimeError("OP_MSG Payload Type 1 detected unsupported protocol");
23858
24331
  }
23859
24332
  }
23860
- if (this.documents.length === 1 && documentsReturnedIn != null && raw) {
23861
- const fieldsAsRaw = {};
23862
- fieldsAsRaw[documentsReturnedIn] = true;
23863
- bsonOptions.fieldsAsRaw = fieldsAsRaw;
23864
- const doc = BSON.deserialize(this.documents[0], bsonOptions);
23865
- this.documents = [doc];
23866
- }
23867
24333
  this.parsed = true;
23868
- }
23869
- parseBsonSerializationOptions({ enableUtf8Validation }) {
23870
- if (enableUtf8Validation === false) {
23871
- return { utf8: false };
23872
- }
23873
- return { utf8: { writeErrors: false } };
24334
+ return this.sections[0];
23874
24335
  }
23875
24336
  }
23876
24337
  exports.OpMsgResponse = OpMsgResponse;
@@ -23924,20 +24385,20 @@ var require_compression = __commonJS((exports) => {
23924
24385
  switch (options.agreedCompressor) {
23925
24386
  case "snappy": {
23926
24387
  Snappy ??= loadSnappy();
23927
- return Snappy.compress(dataToBeCompressed);
24388
+ return await Snappy.compress(dataToBeCompressed);
23928
24389
  }
23929
24390
  case "zstd": {
23930
24391
  loadZstd();
23931
24392
  if ("kModuleError" in zstd) {
23932
24393
  throw zstd["kModuleError"];
23933
24394
  }
23934
- return zstd.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL);
24395
+ return await zstd.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL);
23935
24396
  }
23936
24397
  case "zlib": {
23937
24398
  if (options.zlibCompressionLevel) {
23938
24399
  zlibOptions.level = options.zlibCompressionLevel;
23939
24400
  }
23940
- return zlibDeflate(dataToBeCompressed, zlibOptions);
24401
+ return await zlibDeflate(dataToBeCompressed, zlibOptions);
23941
24402
  }
23942
24403
  default: {
23943
24404
  throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${options.agreedCompressor} failed to compress`);
@@ -23951,17 +24412,17 @@ var require_compression = __commonJS((exports) => {
23951
24412
  switch (compressorID) {
23952
24413
  case exports.Compressor.snappy: {
23953
24414
  Snappy ??= loadSnappy();
23954
- return Snappy.uncompress(compressedData, { asBuffer: true });
24415
+ return await Snappy.uncompress(compressedData, { asBuffer: true });
23955
24416
  }
23956
24417
  case exports.Compressor.zstd: {
23957
24418
  loadZstd();
23958
24419
  if ("kModuleError" in zstd) {
23959
24420
  throw zstd["kModuleError"];
23960
24421
  }
23961
- return zstd.decompress(compressedData);
24422
+ return await zstd.decompress(compressedData);
23962
24423
  }
23963
24424
  case exports.Compressor.zlib: {
23964
- return zlibInflate(compressedData);
24425
+ return await zlibInflate(compressedData);
23965
24426
  }
23966
24427
  default: {
23967
24428
  return compressedData;
@@ -23989,7 +24450,7 @@ var require_compression = __commonJS((exports) => {
23989
24450
  opCode: message.readInt32LE(12)
23990
24451
  };
23991
24452
  if (messageHeader.opCode !== constants_2.OP_COMPRESSED) {
23992
- const ResponseType2 = messageHeader.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpQueryResponse;
24453
+ const ResponseType2 = messageHeader.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpReply;
23993
24454
  const messageBody2 = message.subarray(MESSAGE_HEADER_SIZE);
23994
24455
  return new ResponseType2(message, messageHeader, messageBody2);
23995
24456
  }
@@ -24001,7 +24462,7 @@ var require_compression = __commonJS((exports) => {
24001
24462
  };
24002
24463
  const compressorID = message[MESSAGE_HEADER_SIZE + 8];
24003
24464
  const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9);
24004
- const ResponseType = header.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpQueryResponse;
24465
+ const ResponseType = header.opCode === constants_2.OP_MSG ? commands_1.OpMsgResponse : commands_1.OpReply;
24005
24466
  const messageBody = await decompress(compressorID, compressedBuffer);
24006
24467
  if (messageBody.length !== header.length) {
24007
24468
  throw new error_1.MongoDecompressionError("Message body and message header must be the same length");
@@ -24241,21 +24702,118 @@ var require_mongocryptd_manager = __commonJS((exports) => {
24241
24702
  exports.MongocryptdManager = MongocryptdManager;
24242
24703
  });
24243
24704
 
24705
+ // node_modules/mongodb/lib/cmap/auth/aws_temporary_credentials.js
24706
+ var require_aws_temporary_credentials = __commonJS((exports) => {
24707
+ Object.defineProperty(exports, "__esModule", { value: true });
24708
+ exports.LegacyAWSTemporaryCredentialProvider = exports.AWSSDKCredentialProvider = exports.AWSTemporaryCredentialProvider = undefined;
24709
+ var deps_1 = require_deps();
24710
+ var error_1 = require_error();
24711
+ var utils_1 = require_utils2();
24712
+ var AWS_RELATIVE_URI = "http://169.254.170.2";
24713
+ var AWS_EC2_URI = "http://169.254.169.254";
24714
+ var AWS_EC2_PATH = "/latest/meta-data/iam/security-credentials";
24715
+
24716
+ class AWSTemporaryCredentialProvider {
24717
+ static get awsSDK() {
24718
+ AWSTemporaryCredentialProvider._awsSDK ??= (0, deps_1.getAwsCredentialProvider)();
24719
+ return AWSTemporaryCredentialProvider._awsSDK;
24720
+ }
24721
+ static get isAWSSDKInstalled() {
24722
+ return !("kModuleError" in AWSTemporaryCredentialProvider.awsSDK);
24723
+ }
24724
+ }
24725
+ exports.AWSTemporaryCredentialProvider = AWSTemporaryCredentialProvider;
24726
+
24727
+ class AWSSDKCredentialProvider extends AWSTemporaryCredentialProvider {
24728
+ get provider() {
24729
+ if ("kModuleError" in AWSTemporaryCredentialProvider.awsSDK) {
24730
+ throw AWSTemporaryCredentialProvider.awsSDK.kModuleError;
24731
+ }
24732
+ if (this._provider) {
24733
+ return this._provider;
24734
+ }
24735
+ let { AWS_STS_REGIONAL_ENDPOINTS = "", AWS_REGION = "" } = process.env;
24736
+ AWS_STS_REGIONAL_ENDPOINTS = AWS_STS_REGIONAL_ENDPOINTS.toLowerCase();
24737
+ AWS_REGION = AWS_REGION.toLowerCase();
24738
+ const awsRegionSettingsExist = AWS_REGION.length !== 0 && AWS_STS_REGIONAL_ENDPOINTS.length !== 0;
24739
+ const LEGACY_REGIONS = new Set([
24740
+ "ap-northeast-1",
24741
+ "ap-south-1",
24742
+ "ap-southeast-1",
24743
+ "ap-southeast-2",
24744
+ "aws-global",
24745
+ "ca-central-1",
24746
+ "eu-central-1",
24747
+ "eu-north-1",
24748
+ "eu-west-1",
24749
+ "eu-west-2",
24750
+ "eu-west-3",
24751
+ "sa-east-1",
24752
+ "us-east-1",
24753
+ "us-east-2",
24754
+ "us-west-1",
24755
+ "us-west-2"
24756
+ ]);
24757
+ const useRegionalSts = AWS_STS_REGIONAL_ENDPOINTS === "regional" || AWS_STS_REGIONAL_ENDPOINTS === "legacy" && !LEGACY_REGIONS.has(AWS_REGION);
24758
+ this._provider = awsRegionSettingsExist && useRegionalSts ? AWSTemporaryCredentialProvider.awsSDK.fromNodeProviderChain({
24759
+ clientConfig: { region: AWS_REGION }
24760
+ }) : AWSTemporaryCredentialProvider.awsSDK.fromNodeProviderChain();
24761
+ return this._provider;
24762
+ }
24763
+ async getCredentials() {
24764
+ try {
24765
+ const creds = await this.provider();
24766
+ return {
24767
+ AccessKeyId: creds.accessKeyId,
24768
+ SecretAccessKey: creds.secretAccessKey,
24769
+ Token: creds.sessionToken,
24770
+ Expiration: creds.expiration
24771
+ };
24772
+ } catch (error) {
24773
+ throw new error_1.MongoAWSError(error.message, { cause: error });
24774
+ }
24775
+ }
24776
+ }
24777
+ exports.AWSSDKCredentialProvider = AWSSDKCredentialProvider;
24778
+
24779
+ class LegacyAWSTemporaryCredentialProvider extends AWSTemporaryCredentialProvider {
24780
+ async getCredentials() {
24781
+ if (process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) {
24782
+ return await (0, utils_1.request)(`${AWS_RELATIVE_URI}${process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`);
24783
+ }
24784
+ const token = await (0, utils_1.request)(`${AWS_EC2_URI}/latest/api/token`, {
24785
+ method: "PUT",
24786
+ json: false,
24787
+ headers: { "X-aws-ec2-metadata-token-ttl-seconds": 30 }
24788
+ });
24789
+ const roleName = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}`, {
24790
+ json: false,
24791
+ headers: { "X-aws-ec2-metadata-token": token }
24792
+ });
24793
+ const creds = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, {
24794
+ headers: { "X-aws-ec2-metadata-token": token }
24795
+ });
24796
+ return creds;
24797
+ }
24798
+ }
24799
+ exports.LegacyAWSTemporaryCredentialProvider = LegacyAWSTemporaryCredentialProvider;
24800
+ });
24801
+
24244
24802
  // node_modules/mongodb/lib/client-side-encryption/providers/aws.js
24245
24803
  var require_aws = __commonJS((exports) => {
24246
24804
  async function loadAWSCredentials(kmsProviders) {
24247
- const credentialProvider = (0, deps_1.getAwsCredentialProvider)();
24248
- if ("kModuleError" in credentialProvider) {
24249
- return kmsProviders;
24250
- }
24251
- const { fromNodeProviderChain } = credentialProvider;
24252
- const provider = fromNodeProviderChain();
24253
- const aws = await provider();
24805
+ const credentialProvider = new aws_temporary_credentials_1.AWSSDKCredentialProvider;
24806
+ const { SecretAccessKey = "", AccessKeyId = "", Token } = await credentialProvider.getCredentials();
24807
+ const aws = {
24808
+ secretAccessKey: SecretAccessKey,
24809
+ accessKeyId: AccessKeyId
24810
+ };
24811
+ Token != null && (aws.sessionToken = Token);
24254
24812
  return { ...kmsProviders, aws };
24255
24813
  }
24256
24814
  Object.defineProperty(exports, "__esModule", { value: true });
24257
24815
  exports.loadAWSCredentials = undefined;
24258
- var deps_1 = require_deps();
24816
+ var aws_temporary_credentials_1 = require_aws_temporary_credentials();
24259
24817
  exports.loadAWSCredentials = loadAWSCredentials;
24260
24818
  });
24261
24819
 
@@ -24327,13 +24885,15 @@ var require_azure = __commonJS((exports) => {
24327
24885
  };
24328
24886
  async function fetchAzureKMSToken(options = {}) {
24329
24887
  const { headers, url } = prepareRequest(options);
24330
- const response = await (0, utils_1.get)(url, { headers }).catch((error) => {
24888
+ try {
24889
+ const response = await (0, utils_1.get)(url, { headers });
24890
+ return await parseResponse(response);
24891
+ } catch (error) {
24331
24892
  if (error instanceof errors_1.MongoCryptKMSRequestNetworkTimeoutError) {
24332
24893
  throw new errors_1.MongoCryptAzureKMSRequestError(`[Azure KMS] ${error.message}`);
24333
24894
  }
24334
24895
  throw error;
24335
- });
24336
- return parseResponse(response);
24896
+ }
24337
24897
  }
24338
24898
  async function loadAzureCredentials(kmsProviders) {
24339
24899
  const azure = await exports.tokenCache.getToken();
@@ -24853,7 +25413,7 @@ var require_auto_encrypter = __commonJS((exports) => {
24853
25413
  proxyOptions: this._proxyOptions,
24854
25414
  tlsOptions: this._tlsOptions
24855
25415
  });
24856
- return stateMachine.execute(this, context);
25416
+ return await stateMachine.execute(this, context);
24857
25417
  }
24858
25418
  async decrypt(response, options = {}) {
24859
25419
  const buffer = Buffer.isBuffer(response) ? response : (0, bson_1.serialize)(response, options);
@@ -24872,7 +25432,7 @@ var require_auto_encrypter = __commonJS((exports) => {
24872
25432
  return result;
24873
25433
  }
24874
25434
  async askForKMSCredentials() {
24875
- return (0, providers_1.refreshKMSCredentials)(this._kmsProviders);
25435
+ return await (0, providers_1.refreshKMSCredentials)(this._kmsProviders);
24876
25436
  }
24877
25437
  get cryptSharedLibVersionInfo() {
24878
25438
  return this._mongocrypt.cryptSharedLibVersionInfo;
@@ -24965,19 +25525,27 @@ var require_encrypter = __commonJS((exports) => {
24965
25525
  (0, util_1.callbackify)(this.close.bind(this))(client, force, callback);
24966
25526
  }
24967
25527
  async close(client, force) {
24968
- const maybeError = await this.autoEncrypter.teardown(!!force).catch((e) => e);
25528
+ let error;
25529
+ try {
25530
+ await this.autoEncrypter.teardown(force);
25531
+ } catch (autoEncrypterError) {
25532
+ error = autoEncrypterError;
25533
+ }
24969
25534
  const internalClient = this[kInternalClient];
24970
25535
  if (internalClient != null && client !== internalClient) {
24971
- return internalClient.close(force);
25536
+ return await internalClient.close(force);
24972
25537
  }
24973
- if (maybeError) {
24974
- throw maybeError;
25538
+ if (error != null) {
25539
+ throw error;
24975
25540
  }
24976
25541
  }
24977
25542
  static checkForMongoCrypt() {
24978
25543
  const mongodbClientEncryption = (0, deps_1.getMongoDBClientEncryption)();
24979
25544
  if ("kModuleError" in mongodbClientEncryption) {
24980
- throw new error_1.MongoMissingDependencyError("Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project");
25545
+ throw new error_1.MongoMissingDependencyError("Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project", {
25546
+ cause: mongodbClientEncryption["kModuleError"],
25547
+ dependencyName: "mongodb-client-encryption"
25548
+ });
24981
25549
  }
24982
25550
  }
24983
25551
  }
@@ -25346,6 +25914,7 @@ var require_connection = __commonJS((exports) => {
25346
25914
  var stream_description_1 = require_stream_description();
25347
25915
  var compression_1 = require_compression();
25348
25916
  var on_data_1 = require_on_data();
25917
+ var responses_1 = require_responses();
25349
25918
  var shared_1 = require_shared();
25350
25919
  exports.hasSessionSupport = hasSessionSupport;
25351
25920
 
@@ -25431,7 +26000,7 @@ var require_connection = __commonJS((exports) => {
25431
26000
  }
25432
26001
  this.socket.destroy();
25433
26002
  this.error = error;
25434
- this.dataEvents?.throw(error).then(undefined, () => null);
26003
+ this.dataEvents?.throw(error).then(undefined, utils_1.squashError);
25435
26004
  this.closed = true;
25436
26005
  this.emit(Connection.CLOSE);
25437
26006
  }
@@ -25483,7 +26052,7 @@ var require_connection = __commonJS((exports) => {
25483
26052
  const message = this.supportsOpMsg ? new commands_1.OpMsgRequest(db, cmd, commandOptions) : new commands_1.OpQueryRequest(db, cmd, commandOptions);
25484
26053
  return message;
25485
26054
  }
25486
- async* sendWire(message, options) {
26055
+ async* sendWire(message, options, responseType) {
25487
26056
  this.throwIfAborted();
25488
26057
  if (typeof options.socketTimeoutMS === "number") {
25489
26058
  this.socket.setTimeout(options.socketTimeoutMS);
@@ -25496,24 +26065,14 @@ var require_connection = __commonJS((exports) => {
25496
26065
  zlibCompressionLevel: this.description.zlibCompressionLevel
25497
26066
  });
25498
26067
  if (options.noResponse) {
25499
- yield { ok: 1 };
26068
+ yield responses_1.MongoDBResponse.empty;
25500
26069
  return;
25501
26070
  }
25502
26071
  this.throwIfAborted();
25503
26072
  for await (const response of this.readMany()) {
25504
26073
  this.socket.setTimeout(0);
25505
- response.parse(options);
25506
- const [document] = response.documents;
25507
- if (!Buffer.isBuffer(document)) {
25508
- const { session } = options;
25509
- if (session) {
25510
- (0, sessions_1.updateSessionFromResponse)(session, document);
25511
- }
25512
- if (document.$clusterTime) {
25513
- this.clusterTime = document.$clusterTime;
25514
- this.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime);
25515
- }
25516
- }
26074
+ const bson = response.parse();
26075
+ const document = responseType == null ? new responses_1.MongoDBResponse(bson) : (0, responses_1.isErrorResponse)(bson) ? new responses_1.MongoDBResponse(bson) : new responseType(bson);
25517
26076
  yield document;
25518
26077
  this.throwIfAborted();
25519
26078
  if (typeof options.socketTimeoutMS === "number") {
@@ -25526,33 +26085,52 @@ var require_connection = __commonJS((exports) => {
25526
26085
  this.socket.setTimeout(0);
25527
26086
  }
25528
26087
  }
25529
- async* sendCommand(ns, command2, options = {}) {
26088
+ async* sendCommand(ns, command2, options, responseType) {
25530
26089
  const message = this.prepareCommand(ns.db, command2, options);
25531
26090
  let started = 0;
25532
26091
  if (this.shouldEmitAndLogCommand) {
25533
26092
  started = (0, utils_1.now)();
25534
26093
  this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_STARTED, message.databaseName, this.established, new command_monitoring_events_1.CommandStartedEvent(this, message, this.description.serverConnectionId));
25535
26094
  }
25536
- let document;
26095
+ const bsonOptions = options.documentsReturnedIn == null || !options.raw ? options : {
26096
+ ...options,
26097
+ raw: false,
26098
+ fieldsAsRaw: { [options.documentsReturnedIn]: true }
26099
+ };
26100
+ let document = undefined;
26101
+ let object = undefined;
25537
26102
  try {
25538
26103
  this.throwIfAborted();
25539
- for await (document of this.sendWire(message, options)) {
25540
- if (!Buffer.isBuffer(document) && document.writeConcernError) {
25541
- throw new error_1.MongoWriteConcernError(document.writeConcernError, document);
26104
+ for await (document of this.sendWire(message, options, responseType)) {
26105
+ object = undefined;
26106
+ if (options.session != null) {
26107
+ (0, sessions_1.updateSessionFromResponse)(options.session, document);
25542
26108
  }
25543
- if (!Buffer.isBuffer(document) && (document.ok === 0 || document.$err || document.errmsg || document.code)) {
25544
- throw new error_1.MongoServerError(document);
26109
+ if (document.$clusterTime) {
26110
+ this.clusterTime = document.$clusterTime;
26111
+ this.emit(Connection.CLUSTER_TIME_RECEIVED, document.$clusterTime);
26112
+ }
26113
+ if (document.has("writeConcernError")) {
26114
+ object ??= document.toObject(bsonOptions);
26115
+ throw new error_1.MongoWriteConcernError(object.writeConcernError, object);
26116
+ }
26117
+ if (document.isError) {
26118
+ throw new error_1.MongoServerError(object ??= document.toObject(bsonOptions));
25545
26119
  }
25546
26120
  if (this.shouldEmitAndLogCommand) {
25547
- this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_SUCCEEDED, message.databaseName, this.established, new command_monitoring_events_1.CommandSucceededEvent(this, message, options.noResponse ? undefined : document, started, this.description.serverConnectionId));
26121
+ this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_SUCCEEDED, message.databaseName, this.established, new command_monitoring_events_1.CommandSucceededEvent(this, message, options.noResponse ? undefined : object ??= document.toObject(bsonOptions), started, this.description.serverConnectionId));
26122
+ }
26123
+ if (responseType == null) {
26124
+ yield object ??= document.toObject(bsonOptions);
26125
+ } else {
26126
+ yield document;
25548
26127
  }
25549
- yield document;
25550
26128
  this.throwIfAborted();
25551
26129
  }
25552
26130
  } catch (error) {
25553
26131
  if (this.shouldEmitAndLogCommand) {
25554
26132
  if (error.name === "MongoWriteConcernError") {
25555
- this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_SUCCEEDED, message.databaseName, this.established, new command_monitoring_events_1.CommandSucceededEvent(this, message, options.noResponse ? undefined : document, started, this.description.serverConnectionId));
26133
+ this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_SUCCEEDED, message.databaseName, this.established, new command_monitoring_events_1.CommandSucceededEvent(this, message, options.noResponse ? undefined : object ??= document?.toObject(bsonOptions), started, this.description.serverConnectionId));
25556
26134
  } else {
25557
26135
  this.emitAndLogCommand(this.monitorCommands, Connection.COMMAND_FAILED, message.databaseName, this.established, new command_monitoring_events_1.CommandFailedEvent(this, message, error, started, this.description.serverConnectionId));
25558
26136
  }
@@ -25560,9 +26138,9 @@ var require_connection = __commonJS((exports) => {
25560
26138
  throw error;
25561
26139
  }
25562
26140
  }
25563
- async command(ns, command2, options = {}) {
26141
+ async command(ns, command2, options = {}, responseType) {
25564
26142
  this.throwIfAborted();
25565
- for await (const document of this.sendCommand(ns, command2, options)) {
26143
+ for await (const document of this.sendCommand(ns, command2, options, responseType)) {
25566
26144
  return document;
25567
26145
  }
25568
26146
  throw new error_1.MongoUnexpectedServerResponseError("Unable to get response from server");
@@ -25576,7 +26154,7 @@ var require_connection = __commonJS((exports) => {
25576
26154
  }
25577
26155
  throw new error_1.MongoUnexpectedServerResponseError("Server ended moreToCome unexpectedly");
25578
26156
  };
25579
- exhaustLoop().catch(replyListener);
26157
+ exhaustLoop().then(undefined, replyListener);
25580
26158
  }
25581
26159
  throwIfAborted() {
25582
26160
  if (this.error)
@@ -25590,7 +26168,7 @@ var require_connection = __commonJS((exports) => {
25590
26168
  const buffer = Buffer.concat(await finalCommand.toBin());
25591
26169
  if (this.socket.write(buffer))
25592
26170
  return;
25593
- return (0, utils_1.once)(this.socket, "drain");
26171
+ return await (0, utils_1.once)(this.socket, "drain");
25594
26172
  }
25595
26173
  async* readMany() {
25596
26174
  try {
@@ -25650,14 +26228,16 @@ var require_connection = __commonJS((exports) => {
25650
26228
  super(stream, options);
25651
26229
  this.autoEncrypter = options.autoEncrypter;
25652
26230
  }
25653
- async command(ns, cmd, options) {
26231
+ async command(ns, cmd, options, _responseType) {
25654
26232
  const { autoEncrypter } = this;
25655
26233
  if (!autoEncrypter) {
25656
- throw new error_1.MongoMissingDependencyError("No AutoEncrypter available for encryption");
26234
+ throw new error_1.MongoMissingDependencyError("No AutoEncrypter available for encryption", {
26235
+ dependencyName: "n/a"
26236
+ });
25657
26237
  }
25658
26238
  const serverWireVersion = (0, utils_1.maxWireVersion)(this);
25659
26239
  if (serverWireVersion === 0) {
25660
- return super.command(ns, cmd, options);
26240
+ return await super.command(ns, cmd, options, undefined);
25661
26241
  }
25662
26242
  if (serverWireVersion < 8) {
25663
26243
  throw new error_1.MongoCompatibilityError("Auto-encryption requires a minimum MongoDB version of 4.2");
@@ -25673,8 +26253,8 @@ var require_connection = __commonJS((exports) => {
25673
26253
  encrypted.indexes[offset].key = index;
25674
26254
  }
25675
26255
  }
25676
- const response = await super.command(ns, encrypted, options);
25677
- return autoEncrypter.decrypt(response, options);
26256
+ const response = await super.command(ns, encrypted, options, undefined);
26257
+ return await autoEncrypter.decrypt(response, options);
25678
26258
  }
25679
26259
  }
25680
26260
  exports.CryptoConnection = CryptoConnection;
@@ -25726,7 +26306,7 @@ var require_connect = __commonJS((exports) => {
25726
26306
  const authContext = new auth_provider_1.AuthContext(conn, credentials, options);
25727
26307
  conn.authContext = authContext;
25728
26308
  const handshakeDoc = await prepareHandshakeDocument(authContext);
25729
- const handshakeOptions = { ...options };
26309
+ const handshakeOptions = { ...options, raw: false };
25730
26310
  if (typeof options.connectTimeoutMS === "number") {
25731
26311
  handshakeOptions.socketTimeoutMS = options.connectTimeoutMS;
25732
26312
  }
@@ -25792,13 +26372,13 @@ var require_connect = __commonJS((exports) => {
25792
26372
  if (!provider2) {
25793
26373
  throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${providers_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`);
25794
26374
  }
25795
- return provider2.prepare(handshakeDoc, authContext);
26375
+ return await provider2.prepare(handshakeDoc, authContext);
25796
26376
  }
25797
26377
  const provider = authContext.options.authProviders.getOrCreateProvider(credentials.mechanism);
25798
26378
  if (!provider) {
25799
26379
  throw new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`);
25800
26380
  }
25801
- return provider.prepare(handshakeDoc, authContext);
26381
+ return await provider.prepare(handshakeDoc, authContext);
25802
26382
  }
25803
26383
  return handshakeDoc;
25804
26384
  }
@@ -25845,7 +26425,7 @@ var require_connect = __commonJS((exports) => {
25845
26425
  const existingSocket = options.existingSocket;
25846
26426
  let socket;
25847
26427
  if (options.proxyHost != null) {
25848
- return makeSocks5Connection({
26428
+ return await makeSocks5Connection({
25849
26429
  ...options,
25850
26430
  connectTimeoutMS
25851
26431
  });
@@ -26091,6 +26671,69 @@ var require_events = __commonJS((exports) => {
26091
26671
  exports.ServerHeartbeatFailedEvent = ServerHeartbeatFailedEvent;
26092
26672
  });
26093
26673
 
26674
+ // node_modules/mongodb/lib/timeout.js
26675
+ var require_timeout = __commonJS((exports) => {
26676
+ Object.defineProperty(exports, "__esModule", { value: true });
26677
+ exports.Timeout = exports.TimeoutError = undefined;
26678
+ var timers_1 = import.meta.require("timers");
26679
+ var error_1 = require_error();
26680
+ var utils_1 = require_utils2();
26681
+
26682
+ class TimeoutError extends Error {
26683
+ get name() {
26684
+ return "TimeoutError";
26685
+ }
26686
+ constructor(message, options) {
26687
+ super(message, options);
26688
+ }
26689
+ static is(error) {
26690
+ return error != null && typeof error === "object" && "name" in error && error.name === "TimeoutError";
26691
+ }
26692
+ }
26693
+ exports.TimeoutError = TimeoutError;
26694
+
26695
+ class Timeout extends Promise {
26696
+ get [Symbol.toStringTag]() {
26697
+ return "MongoDBTimeout";
26698
+ }
26699
+ constructor(executor = () => null, duration, unref = false) {
26700
+ let reject;
26701
+ if (duration < 0) {
26702
+ throw new error_1.MongoInvalidArgumentError("Cannot create a Timeout with a negative duration");
26703
+ }
26704
+ super((_, promiseReject) => {
26705
+ reject = promiseReject;
26706
+ executor(utils_1.noop, promiseReject);
26707
+ });
26708
+ this.ended = null;
26709
+ this.timedOut = false;
26710
+ this.duration = duration;
26711
+ this.start = Math.trunc(performance.now());
26712
+ if (this.duration > 0) {
26713
+ this.id = (0, timers_1.setTimeout)(() => {
26714
+ this.ended = Math.trunc(performance.now());
26715
+ this.timedOut = true;
26716
+ reject(new TimeoutError(`Expired after ${duration}ms`));
26717
+ }, this.duration);
26718
+ if (typeof this.id.unref === "function" && unref) {
26719
+ this.id.unref();
26720
+ }
26721
+ }
26722
+ }
26723
+ clear() {
26724
+ (0, timers_1.clearTimeout)(this.id);
26725
+ this.id = undefined;
26726
+ }
26727
+ static expires(durationMS, unref) {
26728
+ return new Timeout(undefined, durationMS, unref);
26729
+ }
26730
+ static is(timeout) {
26731
+ return typeof timeout === "object" && timeout != null && Symbol.toStringTag in timeout && timeout[Symbol.toStringTag] === "MongoDBTimeout" && "then" in timeout && typeof timeout.then === "function";
26732
+ }
26733
+ }
26734
+ exports.Timeout = Timeout;
26735
+ });
26736
+
26094
26737
  // node_modules/mongodb/lib/cmap/connection_pool_events.js
26095
26738
  var require_connection_pool_events = __commonJS((exports) => {
26096
26739
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -26268,6 +26911,7 @@ var require_connection_pool = __commonJS((exports) => {
26268
26911
  var constants_1 = require_constants2();
26269
26912
  var error_1 = require_error();
26270
26913
  var mongo_types_1 = require_mongo_types();
26914
+ var timeout_1 = require_timeout();
26271
26915
  var utils_1 = require_utils2();
26272
26916
  var connect_1 = require_connect();
26273
26917
  var connection_1 = require_connection();
@@ -26383,20 +27027,26 @@ var require_connection_pool = __commonJS((exports) => {
26383
27027
  this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_STARTED, new connection_pool_events_1.ConnectionCheckOutStartedEvent(this));
26384
27028
  const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS;
26385
27029
  const { promise, resolve, reject } = (0, utils_1.promiseWithResolvers)();
27030
+ const timeout = timeout_1.Timeout.expires(waitQueueTimeoutMS);
26386
27031
  const waitQueueMember = {
26387
27032
  resolve,
26388
27033
  reject,
26389
- timeoutController: new utils_1.TimeoutController(waitQueueTimeoutMS)
27034
+ timeout
26390
27035
  };
26391
- waitQueueMember.timeoutController.signal.addEventListener("abort", () => {
26392
- waitQueueMember[kCancelled] = true;
26393
- waitQueueMember.timeoutController.clear();
26394
- this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, "timeout"));
26395
- waitQueueMember.reject(new errors_1.WaitQueueTimeoutError(this.loadBalanced ? this.waitQueueErrorMetrics() : "Timed out while checking out a connection from connection pool", this.address));
26396
- });
26397
27036
  this[kWaitQueue].push(waitQueueMember);
26398
27037
  process.nextTick(() => this.processWaitQueue());
26399
- return promise;
27038
+ try {
27039
+ return await Promise.race([promise, waitQueueMember.timeout]);
27040
+ } catch (error) {
27041
+ if (timeout_1.TimeoutError.is(error)) {
27042
+ waitQueueMember[kCancelled] = true;
27043
+ waitQueueMember.timeout.clear();
27044
+ this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, "timeout"));
27045
+ const timeoutError = new errors_1.WaitQueueTimeoutError(this.loadBalanced ? this.waitQueueErrorMetrics() : "Timed out while checking out a connection from connection pool", this.address);
27046
+ throw timeoutError;
27047
+ }
27048
+ throw error;
27049
+ }
26400
27050
  }
26401
27051
  checkIn(connection) {
26402
27052
  if (!this[kCheckedOut].has(connection)) {
@@ -26620,7 +27270,7 @@ var require_connection_pool = __commonJS((exports) => {
26620
27270
  const reason = this.closed ? "poolClosed" : "connectionError";
26621
27271
  const error = this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this);
26622
27272
  this.emitAndLog(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, reason, error));
26623
- waitQueueMember.timeoutController.clear();
27273
+ waitQueueMember.timeout.clear();
26624
27274
  this[kWaitQueue].shift();
26625
27275
  waitQueueMember.reject(error);
26626
27276
  continue;
@@ -26635,7 +27285,7 @@ var require_connection_pool = __commonJS((exports) => {
26635
27285
  if (!this.destroyConnectionIfPerished(connection)) {
26636
27286
  this[kCheckedOut].add(connection);
26637
27287
  this.emitAndLog(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection));
26638
- waitQueueMember.timeoutController.clear();
27288
+ waitQueueMember.timeout.clear();
26639
27289
  this[kWaitQueue].shift();
26640
27290
  waitQueueMember.resolve(connection);
26641
27291
  }
@@ -26660,7 +27310,7 @@ var require_connection_pool = __commonJS((exports) => {
26660
27310
  this.emitAndLog(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection));
26661
27311
  waitQueueMember.resolve(connection);
26662
27312
  }
26663
- waitQueueMember.timeoutController.clear();
27313
+ waitQueueMember.timeout.clear();
26664
27314
  }
26665
27315
  process.nextTick(() => this.processWaitQueue());
26666
27316
  });
@@ -26684,13 +27334,6 @@ var require_connection_pool = __commonJS((exports) => {
26684
27334
 
26685
27335
  // node_modules/mongodb/lib/sdam/server.js
26686
27336
  var require_server = __commonJS((exports) => {
26687
- var calculateRoundTripTime = function(oldRtt, duration) {
26688
- if (oldRtt === -1) {
26689
- return duration;
26690
- }
26691
- const alpha = 0.2;
26692
- return alpha * duration + (1 - alpha) * oldRtt;
26693
- };
26694
27337
  var markServerUnknown = function(server, error) {
26695
27338
  if (server.loadBalanced) {
26696
27339
  return;
@@ -26773,7 +27416,8 @@ var require_server = __commonJS((exports) => {
26773
27416
  this.monitor.on("resetServer", (error) => markServerUnknown(this, error));
26774
27417
  this.monitor.on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => {
26775
27418
  this.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(this.description.hostAddress, event.reply, {
26776
- roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration)
27419
+ roundTripTime: this.monitor?.roundTripTime,
27420
+ minRoundTripTime: this.monitor?.minRoundTripTime
26777
27421
  }));
26778
27422
  if (this.s.state === common_1.STATE_CONNECTING) {
26779
27423
  stateTransition(this, common_1.STATE_CONNECTED);
@@ -26831,7 +27475,7 @@ var require_server = __commonJS((exports) => {
26831
27475
  this.monitor?.requestCheck();
26832
27476
  }
26833
27477
  }
26834
- async command(ns, cmd, options) {
27478
+ async command(ns, cmd, options, responseType) {
26835
27479
  if (ns.db == null || typeof ns === "string") {
26836
27480
  throw new error_1.MongoInvalidArgumentError("Namespace must not be a string");
26837
27481
  }
@@ -26863,7 +27507,7 @@ var require_server = __commonJS((exports) => {
26863
27507
  }
26864
27508
  try {
26865
27509
  try {
26866
- return await conn.command(ns, cmd, finalOptions);
27510
+ return await conn.command(ns, cmd, finalOptions, responseType);
26867
27511
  } catch (commandError) {
26868
27512
  throw this.decorateCommandError(conn, cmd, finalOptions, commandError);
26869
27513
  }
@@ -26871,7 +27515,7 @@ var require_server = __commonJS((exports) => {
26871
27515
  if (operationError instanceof error_1.MongoError && operationError.code === error_1.MONGODB_ERROR_CODES.Reauthenticate) {
26872
27516
  await this.pool.reauthenticate(conn);
26873
27517
  try {
26874
- return await conn.command(ns, cmd, finalOptions);
27518
+ return await conn.command(ns, cmd, finalOptions, responseType);
26875
27519
  } catch (commandError) {
26876
27520
  throw this.decorateCommandError(conn, cmd, finalOptions, commandError);
26877
27521
  }
@@ -26986,6 +27630,7 @@ var require_monitor = __commonJS((exports) => {
26986
27630
  monitor[kCancellationToken].emit("cancel");
26987
27631
  monitor.connection?.destroy();
26988
27632
  monitor.connection = null;
27633
+ monitor.clearRttSamples();
26989
27634
  };
26990
27635
  var useStreamingProtocol = function(monitor, topologyVersion) {
26991
27636
  if (topologyVersion == null)
@@ -27021,7 +27666,8 @@ var require_monitor = __commonJS((exports) => {
27021
27666
  if (!("isWritablePrimary" in hello)) {
27022
27667
  hello.isWritablePrimary = hello[constants_1.LEGACY_HELLO_COMMAND];
27023
27668
  }
27024
- const duration = isAwaitable && monitor.rttPinger ? monitor.rttPinger.roundTripTime : (0, utils_1.calculateDurationInMs)(start);
27669
+ const duration = isAwaitable && monitor.rttPinger ? monitor.rttPinger.latestRtt ?? (0, utils_1.calculateDurationInMs)(start) : (0, utils_1.calculateDurationInMs)(start);
27670
+ monitor.addRttSample(duration);
27025
27671
  monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, monitor[kServer].topology.s.id, hello.connectionId, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, hello, isAwaitable));
27026
27672
  if (isAwaitable) {
27027
27673
  monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_STARTED, monitor[kServer].topology.s.id, undefined, new events_1.ServerHeartbeatStartedEvent(monitor.address, true));
@@ -27046,7 +27692,7 @@ var require_monitor = __commonJS((exports) => {
27046
27692
  exhaustAllowed: true
27047
27693
  } : { socketTimeoutMS: connectTimeoutMS };
27048
27694
  if (isAwaitable && monitor.rttPinger == null) {
27049
- monitor.rttPinger = new RTTPinger(monitor[kCancellationToken], Object.assign({ heartbeatFrequencyMS: monitor.options.heartbeatFrequencyMS }, monitor.connectOptions));
27695
+ monitor.rttPinger = new RTTPinger(monitor);
27050
27696
  }
27051
27697
  start = (0, utils_1.now)();
27052
27698
  if (isAwaitable) {
@@ -27077,8 +27723,10 @@ var require_monitor = __commonJS((exports) => {
27077
27723
  connection2.destroy();
27078
27724
  return;
27079
27725
  }
27726
+ const duration = (0, utils_1.calculateDurationInMs)(start);
27727
+ monitor.addRttSample(duration);
27080
27728
  monitor.connection = connection2;
27081
- monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, monitor[kServer].topology.s.id, connection2.hello?.connectionId, new events_1.ServerHeartbeatSucceededEvent(monitor.address, (0, utils_1.calculateDurationInMs)(start), connection2.hello, useStreamingProtocol(monitor, connection2.hello?.topologyVersion)));
27729
+ monitor.emitAndLogHeartbeat(server_1.Server.SERVER_HEARTBEAT_SUCCEEDED, monitor[kServer].topology.s.id, connection2.hello?.connectionId, new events_1.ServerHeartbeatSucceededEvent(monitor.address, duration, connection2.hello, useStreamingProtocol(monitor, connection2.hello?.topologyVersion)));
27082
27730
  callback(undefined, connection2.hello);
27083
27731
  }, (error) => {
27084
27732
  monitor.connection = null;
@@ -27122,44 +27770,8 @@ var require_monitor = __commonJS((exports) => {
27122
27770
  counter: bson_1.Long.isLong(tv.counter) ? tv.counter : bson_1.Long.fromNumber(tv.counter)
27123
27771
  };
27124
27772
  };
27125
- var measureRoundTripTime = function(rttPinger, options) {
27126
- const start = (0, utils_1.now)();
27127
- options.cancellationToken = rttPinger[kCancellationToken];
27128
- const heartbeatFrequencyMS = options.heartbeatFrequencyMS;
27129
- if (rttPinger.closed) {
27130
- return;
27131
- }
27132
- function measureAndReschedule(conn) {
27133
- if (rttPinger.closed) {
27134
- conn?.destroy();
27135
- return;
27136
- }
27137
- if (rttPinger.connection == null) {
27138
- rttPinger.connection = conn;
27139
- }
27140
- rttPinger[kRoundTripTime] = (0, utils_1.calculateDurationInMs)(start);
27141
- rttPinger[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(rttPinger, options), heartbeatFrequencyMS);
27142
- }
27143
- const connection = rttPinger.connection;
27144
- if (connection == null) {
27145
- (0, connect_1.connect)(options).then((connection2) => {
27146
- measureAndReschedule(connection2);
27147
- }, () => {
27148
- rttPinger.connection = undefined;
27149
- rttPinger[kRoundTripTime] = 0;
27150
- });
27151
- return;
27152
- }
27153
- const commandName = connection.serverApi?.version || connection.helloOk ? "hello" : constants_1.LEGACY_HELLO_COMMAND;
27154
- connection.command((0, utils_1.ns)("admin.$cmd"), { [commandName]: 1 }, undefined).then(() => measureAndReschedule(), () => {
27155
- rttPinger.connection?.destroy();
27156
- rttPinger.connection = undefined;
27157
- rttPinger[kRoundTripTime] = 0;
27158
- return;
27159
- });
27160
- };
27161
27773
  Object.defineProperty(exports, "__esModule", { value: true });
27162
- exports.MonitorInterval = exports.RTTPinger = exports.Monitor = exports.ServerMonitoringMode = undefined;
27774
+ exports.RTTSampler = exports.MonitorInterval = exports.RTTPinger = exports.Monitor = exports.ServerMonitoringMode = undefined;
27163
27775
  var timers_1 = import.meta.require("timers");
27164
27776
  var bson_1 = require_bson2();
27165
27777
  var connect_1 = require_connect();
@@ -27175,7 +27787,6 @@ var require_monitor = __commonJS((exports) => {
27175
27787
  var kServer = Symbol("server");
27176
27788
  var kMonitorId = Symbol("monitorId");
27177
27789
  var kCancellationToken = Symbol("cancellationToken");
27178
- var kRoundTripTime = Symbol("roundTripTime");
27179
27790
  var STATE_IDLE = "idle";
27180
27791
  var STATE_MONITORING = "monitoring";
27181
27792
  var stateTransition = (0, utils_1.makeStateMachine)({
@@ -27212,6 +27823,7 @@ var require_monitor = __commonJS((exports) => {
27212
27823
  });
27213
27824
  this.isRunningInFaasEnv = (0, client_metadata_1.getFAASEnv)() != null;
27214
27825
  this.mongoLogger = this[kServer].topology.client?.mongoLogger;
27826
+ this.rttSampler = new RTTSampler(10);
27215
27827
  const cancellationToken = this[kCancellationToken];
27216
27828
  const connectOptions = {
27217
27829
  id: "<monitor>",
@@ -27273,20 +27885,39 @@ var require_monitor = __commonJS((exports) => {
27273
27885
  this.emit("close");
27274
27886
  stateTransition(this, common_1.STATE_CLOSED);
27275
27887
  }
27888
+ get roundTripTime() {
27889
+ return this.rttSampler.average();
27890
+ }
27891
+ get minRoundTripTime() {
27892
+ return this.rttSampler.min();
27893
+ }
27894
+ get latestRtt() {
27895
+ return this.rttSampler.last ?? 0;
27896
+ }
27897
+ addRttSample(rtt) {
27898
+ this.rttSampler.addSample(rtt);
27899
+ }
27900
+ clearRttSamples() {
27901
+ this.rttSampler.clear();
27902
+ }
27276
27903
  }
27277
27904
  exports.Monitor = Monitor;
27278
27905
 
27279
27906
  class RTTPinger {
27280
- constructor(cancellationToken, options) {
27907
+ constructor(monitor) {
27281
27908
  this.connection = undefined;
27282
- this[kCancellationToken] = cancellationToken;
27283
- this[kRoundTripTime] = 0;
27909
+ this[kCancellationToken] = monitor[kCancellationToken];
27284
27910
  this.closed = false;
27285
- const heartbeatFrequencyMS = options.heartbeatFrequencyMS;
27286
- this[kMonitorId] = (0, timers_1.setTimeout)(() => measureRoundTripTime(this, options), heartbeatFrequencyMS);
27911
+ this.monitor = monitor;
27912
+ this.latestRtt = monitor.latestRtt;
27913
+ const heartbeatFrequencyMS = monitor.options.heartbeatFrequencyMS;
27914
+ this[kMonitorId] = (0, timers_1.setTimeout)(() => this.measureRoundTripTime(), heartbeatFrequencyMS);
27287
27915
  }
27288
27916
  get roundTripTime() {
27289
- return this[kRoundTripTime];
27917
+ return this.monitor.roundTripTime;
27918
+ }
27919
+ get minRoundTripTime() {
27920
+ return this.monitor.minRoundTripTime;
27290
27921
  }
27291
27922
  close() {
27292
27923
  this.closed = true;
@@ -27294,6 +27925,41 @@ var require_monitor = __commonJS((exports) => {
27294
27925
  this.connection?.destroy();
27295
27926
  this.connection = undefined;
27296
27927
  }
27928
+ measureAndReschedule(start, conn) {
27929
+ if (start == null) {
27930
+ start = (0, utils_1.now)();
27931
+ }
27932
+ if (this.closed) {
27933
+ conn?.destroy();
27934
+ return;
27935
+ }
27936
+ if (this.connection == null) {
27937
+ this.connection = conn;
27938
+ }
27939
+ this.latestRtt = (0, utils_1.calculateDurationInMs)(start);
27940
+ this[kMonitorId] = (0, timers_1.setTimeout)(() => this.measureRoundTripTime(), this.monitor.options.heartbeatFrequencyMS);
27941
+ }
27942
+ measureRoundTripTime() {
27943
+ const start = (0, utils_1.now)();
27944
+ if (this.closed) {
27945
+ return;
27946
+ }
27947
+ const connection = this.connection;
27948
+ if (connection == null) {
27949
+ (0, connect_1.connect)(this.monitor.connectOptions).then((connection2) => {
27950
+ this.measureAndReschedule(start, connection2);
27951
+ }, () => {
27952
+ this.connection = undefined;
27953
+ });
27954
+ return;
27955
+ }
27956
+ const commandName = connection.serverApi?.version || connection.helloOk ? "hello" : constants_1.LEGACY_HELLO_COMMAND;
27957
+ connection.command((0, utils_1.ns)("admin.$cmd"), { [commandName]: 1 }, undefined).then(() => this.measureAndReschedule(), () => {
27958
+ this.connection?.destroy();
27959
+ this.connection = undefined;
27960
+ return;
27961
+ });
27962
+ }
27297
27963
  }
27298
27964
  exports.RTTPinger = RTTPinger;
27299
27965
 
@@ -27382,6 +28048,50 @@ var require_monitor = __commonJS((exports) => {
27382
28048
  }
27383
28049
  }
27384
28050
  exports.MonitorInterval = MonitorInterval;
28051
+
28052
+ class RTTSampler {
28053
+ constructor(windowSize = 10) {
28054
+ this.rttSamples = new Float64Array(windowSize);
28055
+ this.length = 0;
28056
+ this.writeIndex = 0;
28057
+ }
28058
+ addSample(sample) {
28059
+ this.rttSamples[this.writeIndex++] = sample;
28060
+ if (this.length < this.rttSamples.length) {
28061
+ this.length++;
28062
+ }
28063
+ this.writeIndex %= this.rttSamples.length;
28064
+ }
28065
+ min() {
28066
+ if (this.length < 2)
28067
+ return 0;
28068
+ let min = this.rttSamples[0];
28069
+ for (let i = 1;i < this.length; i++) {
28070
+ if (this.rttSamples[i] < min)
28071
+ min = this.rttSamples[i];
28072
+ }
28073
+ return min;
28074
+ }
28075
+ average() {
28076
+ if (this.length === 0)
28077
+ return 0;
28078
+ let sum = 0;
28079
+ for (let i = 0;i < this.length; i++) {
28080
+ sum += this.rttSamples[i];
28081
+ }
28082
+ return sum / this.length;
28083
+ }
28084
+ get last() {
28085
+ if (this.length === 0)
28086
+ return null;
28087
+ return this.rttSamples[this.writeIndex === 0 ? this.length - 1 : this.writeIndex - 1];
28088
+ }
28089
+ clear() {
28090
+ this.length = 0;
28091
+ this.writeIndex = 0;
28092
+ }
28093
+ }
28094
+ exports.RTTSampler = RTTSampler;
27385
28095
  });
27386
28096
 
27387
28097
  // node_modules/mongodb/lib/connection_string.js
@@ -27395,8 +28105,7 @@ var require_connection_string = __commonJS((exports) => {
27395
28105
  }
27396
28106
  const lookupAddress = options.srvHost;
27397
28107
  const txtResolutionPromise = dns.promises.resolveTxt(lookupAddress);
27398
- txtResolutionPromise.catch(() => {
27399
- });
28108
+ txtResolutionPromise.then(undefined, utils_1.squashError);
27400
28109
  const addresses = await dns.promises.resolveSrv(`_${options.srvServiceName}._tcp.${lookupAddress}`);
27401
28110
  if (addresses.length === 0) {
27402
28111
  throw new error_1.MongoAPIError("No addresses found at host");
@@ -27693,8 +28402,7 @@ var require_connection_string = __commonJS((exports) => {
27693
28402
  }
27694
28403
  mongoOptions.mongoLoggerOptions = mongo_logger_1.MongoLogger.resolveOptions(loggerEnvOptions, loggerClientOptions);
27695
28404
  mongoOptions.metadata = (0, client_metadata_1.makeClientMetadata)(mongoOptions);
27696
- mongoOptions.extendedMetadata = (0, client_metadata_1.addContainerMetadata)(mongoOptions.metadata).catch(() => {
27697
- });
28405
+ mongoOptions.extendedMetadata = (0, client_metadata_1.addContainerMetadata)(mongoOptions.metadata).then(undefined, utils_1.squashError);
27698
28406
  return mongoOptions;
27699
28407
  };
27700
28408
  var validateLoadBalancedOptions = function(hosts, mongoOptions, isSrv) {
@@ -28429,7 +29137,7 @@ var require_mongocr = __commonJS((exports) => {
28429
29137
 
28430
29138
  // node_modules/mongodb/lib/cmap/auth/mongodb_aws.js
28431
29139
  var require_mongodb_aws = __commonJS((exports) => {
28432
- async function makeTempCredentials(credentials, provider) {
29140
+ async function makeTempCredentials(credentials, awsCredentialFetcher) {
28433
29141
  function makeMongoCredentialsFromAWSTemp(creds) {
28434
29142
  if (!creds.AccessKeyId || !creds.SecretAccessKey) {
28435
29143
  throw new error_1.MongoMissingCredentialsError("Could not obtain temporary MONGODB-AWS credentials");
@@ -28444,36 +29152,8 @@ var require_mongodb_aws = __commonJS((exports) => {
28444
29152
  }
28445
29153
  });
28446
29154
  }
28447
- if (provider && !("kModuleError" in MongoDBAWS.credentialProvider)) {
28448
- try {
28449
- const creds = await provider();
28450
- return makeMongoCredentialsFromAWSTemp({
28451
- AccessKeyId: creds.accessKeyId,
28452
- SecretAccessKey: creds.secretAccessKey,
28453
- Token: creds.sessionToken,
28454
- Expiration: creds.expiration
28455
- });
28456
- } catch (error) {
28457
- throw new error_1.MongoAWSError(error.message);
28458
- }
28459
- } else {
28460
- if (process2.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) {
28461
- return makeMongoCredentialsFromAWSTemp(await (0, utils_1.request)(`${AWS_RELATIVE_URI}${process2.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}`));
28462
- }
28463
- const token = await (0, utils_1.request)(`${AWS_EC2_URI}/latest/api/token`, {
28464
- method: "PUT",
28465
- json: false,
28466
- headers: { "X-aws-ec2-metadata-token-ttl-seconds": 30 }
28467
- });
28468
- const roleName = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}`, {
28469
- json: false,
28470
- headers: { "X-aws-ec2-metadata-token": token }
28471
- });
28472
- const creds = await (0, utils_1.request)(`${AWS_EC2_URI}/${AWS_EC2_PATH}/${roleName}`, {
28473
- headers: { "X-aws-ec2-metadata-token": token }
28474
- });
28475
- return makeMongoCredentialsFromAWSTemp(creds);
28476
- }
29155
+ const temporaryCredentials = await awsCredentialFetcher.getCredentials();
29156
+ return makeMongoCredentialsFromAWSTemp(temporaryCredentials);
28477
29157
  }
28478
29158
  var deriveRegion = function(host) {
28479
29159
  const parts = host.split(".");
@@ -28484,36 +29164,15 @@ var require_mongodb_aws = __commonJS((exports) => {
28484
29164
  };
28485
29165
  Object.defineProperty(exports, "__esModule", { value: true });
28486
29166
  exports.MongoDBAWS = undefined;
28487
- var process2 = import.meta.require("process");
28488
29167
  var BSON = require_bson2();
28489
29168
  var deps_1 = require_deps();
28490
29169
  var error_1 = require_error();
28491
29170
  var utils_1 = require_utils2();
28492
29171
  var auth_provider_1 = require_auth_provider();
29172
+ var aws_temporary_credentials_1 = require_aws_temporary_credentials();
28493
29173
  var mongo_credentials_1 = require_mongo_credentials();
28494
29174
  var providers_1 = require_providers();
28495
- var LEGACY_REGIONS = new Set([
28496
- "ap-northeast-1",
28497
- "ap-south-1",
28498
- "ap-southeast-1",
28499
- "ap-southeast-2",
28500
- "aws-global",
28501
- "ca-central-1",
28502
- "eu-central-1",
28503
- "eu-north-1",
28504
- "eu-west-1",
28505
- "eu-west-2",
28506
- "eu-west-3",
28507
- "sa-east-1",
28508
- "us-east-1",
28509
- "us-east-2",
28510
- "us-west-1",
28511
- "us-west-2"
28512
- ]);
28513
29175
  var ASCII_N = 110;
28514
- var AWS_RELATIVE_URI = "http://169.254.170.2";
28515
- var AWS_EC2_URI = "http://169.254.169.254";
28516
- var AWS_EC2_PATH = "/latest/meta-data/iam/security-credentials";
28517
29176
  var bsonOptions = {
28518
29177
  useBigInt64: false,
28519
29178
  promoteLongs: true,
@@ -28525,17 +29184,7 @@ var require_mongodb_aws = __commonJS((exports) => {
28525
29184
  class MongoDBAWS extends auth_provider_1.AuthProvider {
28526
29185
  constructor() {
28527
29186
  super();
28528
- MongoDBAWS.credentialProvider ??= (0, deps_1.getAwsCredentialProvider)();
28529
- let { AWS_STS_REGIONAL_ENDPOINTS = "", AWS_REGION = "" } = process2.env;
28530
- AWS_STS_REGIONAL_ENDPOINTS = AWS_STS_REGIONAL_ENDPOINTS.toLowerCase();
28531
- AWS_REGION = AWS_REGION.toLowerCase();
28532
- const awsRegionSettingsExist = AWS_REGION.length !== 0 && AWS_STS_REGIONAL_ENDPOINTS.length !== 0;
28533
- const useRegionalSts = AWS_STS_REGIONAL_ENDPOINTS === "regional" || AWS_STS_REGIONAL_ENDPOINTS === "legacy" && !LEGACY_REGIONS.has(AWS_REGION);
28534
- if ("fromNodeProviderChain" in MongoDBAWS.credentialProvider) {
28535
- this.provider = awsRegionSettingsExist && useRegionalSts ? MongoDBAWS.credentialProvider.fromNodeProviderChain({
28536
- clientConfig: { region: AWS_REGION }
28537
- }) : MongoDBAWS.credentialProvider.fromNodeProviderChain();
28538
- }
29187
+ this.credentialFetcher = aws_temporary_credentials_1.AWSTemporaryCredentialProvider.isAWSSDKInstalled ? new aws_temporary_credentials_1.AWSSDKCredentialProvider : new aws_temporary_credentials_1.LegacyAWSTemporaryCredentialProvider;
28539
29188
  }
28540
29189
  async auth(authContext) {
28541
29190
  const { connection } = authContext;
@@ -28550,7 +29199,7 @@ var require_mongodb_aws = __commonJS((exports) => {
28550
29199
  throw new error_1.MongoCompatibilityError("MONGODB-AWS authentication requires MongoDB version 4.4 or later");
28551
29200
  }
28552
29201
  if (!authContext.credentials.username) {
28553
- authContext.credentials = await makeTempCredentials(authContext.credentials, this.provider);
29202
+ authContext.credentials = await makeTempCredentials(authContext.credentials, this.credentialFetcher);
28554
29203
  }
28555
29204
  const { credentials } = authContext;
28556
29205
  const accessKeyId = credentials.username;
@@ -28629,7 +29278,7 @@ var require_service_workflow = __commonJS((exports) => {
28629
29278
  async execute(connection, credentials) {
28630
29279
  const token = await this.getToken(credentials);
28631
29280
  const command2 = commandDocument(token);
28632
- return connection.command((0, utils_1.ns)(credentials.source), command2, undefined);
29281
+ return await connection.command((0, utils_1.ns)(credentials.source), command2, undefined);
28633
29282
  }
28634
29283
  async speculativeAuth(credentials) {
28635
29284
  const token = await this.getToken(credentials);
@@ -28660,7 +29309,7 @@ var require_aws_service_workflow = __commonJS((exports) => {
28660
29309
  if (!tokenFile) {
28661
29310
  throw new error_1.MongoAWSError(TOKEN_MISSING_ERROR);
28662
29311
  }
28663
- return fs.promises.readFile(tokenFile, "utf8");
29312
+ return await fs.promises.readFile(tokenFile, "utf8");
28664
29313
  }
28665
29314
  }
28666
29315
  exports.AwsServiceWorkflow = AwsServiceWorkflow;
@@ -28794,7 +29443,7 @@ var require_callback_lock_cache = __commonJS((exports) => {
28794
29443
  return async (info, context) => {
28795
29444
  await lock;
28796
29445
  lock = lock.then(() => callback(info, context));
28797
- return lock;
29446
+ return await lock;
28798
29447
  };
28799
29448
  };
28800
29449
  var hashFunctions = function(requestFn, refreshFn) {
@@ -29667,9 +30316,9 @@ var require_scram = __commonJS((exports) => {
29667
30316
  async auth(authContext) {
29668
30317
  const { reauthenticating, response } = authContext;
29669
30318
  if (response?.speculativeAuthenticate && !reauthenticating) {
29670
- return continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext);
30319
+ return await continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext);
29671
30320
  }
29672
- return executeScram(this.cryptoMethod, authContext);
30321
+ return await executeScram(this.cryptoMethod, authContext);
29673
30322
  }
29674
30323
  }
29675
30324
  var _hiCache = {};
@@ -29893,7 +30542,7 @@ var require_srv_polling = __commonJS((exports) => {
29893
30542
  (0, timers_1.clearTimeout)(this._timeout);
29894
30543
  }
29895
30544
  this._timeout = (0, timers_1.setTimeout)(() => {
29896
- this._poll().catch(() => null);
30545
+ this._poll().then(undefined, utils_1.squashError);
29897
30546
  }, this.intervalMS);
29898
30547
  }
29899
30548
  success(srvRecords) {
@@ -30006,20 +30655,18 @@ var require_topology = __commonJS((exports) => {
30006
30655
  }
30007
30656
  }
30008
30657
  };
30009
- var drainWaitQueue = function(queue, err) {
30658
+ var drainWaitQueue = function(queue, drainError) {
30010
30659
  while (queue.length) {
30011
30660
  const waitQueueMember = queue.shift();
30012
30661
  if (!waitQueueMember) {
30013
30662
  continue;
30014
30663
  }
30015
- waitQueueMember.timeoutController.clear();
30664
+ waitQueueMember.timeout.clear();
30016
30665
  if (!waitQueueMember[kCancelled]) {
30017
- if (err) {
30018
- if (waitQueueMember.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
30019
- waitQueueMember.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, waitQueueMember.topologyDescription, err, waitQueueMember.operationName));
30020
- }
30666
+ if (waitQueueMember.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
30667
+ waitQueueMember.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, waitQueueMember.topologyDescription, drainError, waitQueueMember.operationName));
30021
30668
  }
30022
- waitQueueMember.callback(err);
30669
+ waitQueueMember.reject(drainError);
30023
30670
  }
30024
30671
  }
30025
30672
  };
@@ -30044,12 +30691,12 @@ var require_topology = __commonJS((exports) => {
30044
30691
  const serverSelector = waitQueueMember.serverSelector;
30045
30692
  const previousServer = waitQueueMember.previousServer;
30046
30693
  selectedDescriptions = serverSelector ? serverSelector(topology.description, serverDescriptions, previousServer ? [previousServer] : []) : serverDescriptions;
30047
- } catch (e) {
30048
- waitQueueMember.timeoutController.clear();
30694
+ } catch (selectorError) {
30695
+ waitQueueMember.timeout.clear();
30049
30696
  if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
30050
- topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, e, waitQueueMember.operationName));
30697
+ topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, selectorError, waitQueueMember.operationName));
30051
30698
  }
30052
- waitQueueMember.callback(e);
30699
+ waitQueueMember.reject(selectorError);
30053
30700
  continue;
30054
30701
  }
30055
30702
  let selectedServer;
@@ -30071,22 +30718,22 @@ var require_topology = __commonJS((exports) => {
30071
30718
  selectedServer = server1 && server2 && server1.s.operationCount < server2.s.operationCount ? server1 : server2;
30072
30719
  }
30073
30720
  if (!selectedServer) {
30074
- const error = new error_1.MongoServerSelectionError("server selection returned a server description but the server was not found in the topology", topology.description);
30721
+ const serverSelectionError = new error_1.MongoServerSelectionError("server selection returned a server description but the server was not found in the topology", topology.description);
30075
30722
  if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
30076
- topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, error, waitQueueMember.operationName));
30723
+ topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(waitQueueMember.serverSelector, topology.description, serverSelectionError, waitQueueMember.operationName));
30077
30724
  }
30078
- waitQueueMember.callback(error);
30725
+ waitQueueMember.reject(serverSelectionError);
30079
30726
  return;
30080
30727
  }
30081
30728
  const transaction = waitQueueMember.transaction;
30082
30729
  if (isSharded && transaction && transaction.isActive && selectedServer) {
30083
30730
  transaction.pinServer(selectedServer);
30084
30731
  }
30085
- waitQueueMember.timeoutController.clear();
30732
+ waitQueueMember.timeout.clear();
30086
30733
  if (topology.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
30087
30734
  topology.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionSucceededEvent(waitQueueMember.serverSelector, waitQueueMember.topologyDescription, selectedServer.pool.address, waitQueueMember.operationName));
30088
30735
  }
30089
- waitQueueMember.callback(undefined, selectedServer);
30736
+ waitQueueMember.resolve(selectedServer);
30090
30737
  }
30091
30738
  if (topology[kWaitQueue].length > 0) {
30092
30739
  for (const [, server] of topology.s.servers) {
@@ -30103,13 +30750,13 @@ var require_topology = __commonJS((exports) => {
30103
30750
  };
30104
30751
  Object.defineProperty(exports, "__esModule", { value: true });
30105
30752
  exports.ServerCapabilities = exports.Topology = undefined;
30106
- var util_1 = import.meta.require("util");
30107
30753
  var connection_string_1 = require_connection_string();
30108
30754
  var constants_1 = require_constants2();
30109
30755
  var error_1 = require_error();
30110
30756
  var mongo_logger_1 = require_mongo_logger();
30111
30757
  var mongo_types_1 = require_mongo_types();
30112
30758
  var read_preference_1 = require_read_preference();
30759
+ var timeout_1 = require_timeout();
30113
30760
  var utils_1 = require_utils2();
30114
30761
  var common_1 = require_common();
30115
30762
  var events_1 = require_events();
@@ -30133,7 +30780,6 @@ var require_topology = __commonJS((exports) => {
30133
30780
  constructor(client, seeds, options) {
30134
30781
  super();
30135
30782
  this.client = client;
30136
- this.selectServerAsync = (0, util_1.promisify)((selector, options2, callback) => this.selectServer(selector, options2, callback));
30137
30783
  options = options ?? {
30138
30784
  hosts: [utils_1.HostAddress.fromString("localhost:27017")],
30139
30785
  ...Object.fromEntries(connection_string_1.DEFAULT_OPTIONS.entries()),
@@ -30189,6 +30835,7 @@ var require_topology = __commonJS((exports) => {
30189
30835
  });
30190
30836
  this.on(Topology.TOPOLOGY_DESCRIPTION_CHANGED, this.s.detectShardedTopology);
30191
30837
  }
30838
+ this.connectionLock = undefined;
30192
30839
  }
30193
30840
  detectShardedTopology(event) {
30194
30841
  const previousType = event.previousDescription.type;
@@ -30222,15 +30869,20 @@ var require_topology = __commonJS((exports) => {
30222
30869
  get capabilities() {
30223
30870
  return new ServerCapabilities(this.lastHello());
30224
30871
  }
30225
- connect(options, callback) {
30226
- if (typeof options === "function")
30227
- callback = options, options = {};
30872
+ async connect(options) {
30873
+ this.connectionLock ??= this._connect(options);
30874
+ try {
30875
+ await this.connectionLock;
30876
+ return this;
30877
+ } finally {
30878
+ this.connectionLock = undefined;
30879
+ }
30880
+ return this;
30881
+ }
30882
+ async _connect(options) {
30228
30883
  options = options ?? {};
30229
30884
  if (this.s.state === common_1.STATE_CONNECTED) {
30230
- if (typeof callback === "function") {
30231
- callback();
30232
- }
30233
- return;
30885
+ return this;
30234
30886
  }
30235
30887
  stateTransition(this, common_1.STATE_CONNECTING);
30236
30888
  this.emitAndLog(Topology.TOPOLOGY_OPENING, new events_1.TopologyOpeningEvent(this.s.id));
@@ -30248,29 +30900,26 @@ var require_topology = __commonJS((exports) => {
30248
30900
  this.serverUpdateHandler(newDescription);
30249
30901
  }
30250
30902
  }
30251
- const exitWithError = (error) => callback ? callback(error) : this.emit(Topology.ERROR, error);
30252
30903
  const readPreference = options.readPreference ?? read_preference_1.ReadPreference.primary;
30253
30904
  const selectServerOptions = { operationName: "ping", ...options };
30254
- this.selectServer((0, server_selection_1.readPreferenceServerSelector)(readPreference), selectServerOptions, (err, server) => {
30255
- if (err) {
30256
- this.close();
30257
- return exitWithError(err);
30258
- }
30905
+ try {
30906
+ const server = await this.selectServer((0, server_selection_1.readPreferenceServerSelector)(readPreference), selectServerOptions);
30259
30907
  const skipPingOnConnect = this.s.options[Symbol.for("@@mdb.skipPingOnConnect")] === true;
30260
30908
  if (!skipPingOnConnect && server && this.s.credentials) {
30261
- server.command((0, utils_1.ns)("admin.$cmd"), { ping: 1 }, {}).then(() => {
30262
- stateTransition(this, common_1.STATE_CONNECTED);
30263
- this.emit(Topology.OPEN, this);
30264
- this.emit(Topology.CONNECT, this);
30265
- callback?.(undefined, this);
30266
- }, exitWithError);
30267
- return;
30909
+ await server.command((0, utils_1.ns)("admin.$cmd"), { ping: 1 }, {});
30910
+ stateTransition(this, common_1.STATE_CONNECTED);
30911
+ this.emit(Topology.OPEN, this);
30912
+ this.emit(Topology.CONNECT, this);
30913
+ return this;
30268
30914
  }
30269
30915
  stateTransition(this, common_1.STATE_CONNECTED);
30270
30916
  this.emit(Topology.OPEN, this);
30271
30917
  this.emit(Topology.CONNECT, this);
30272
- callback?.(undefined, this);
30273
- });
30918
+ return this;
30919
+ } catch (error) {
30920
+ this.close();
30921
+ throw error;
30922
+ }
30274
30923
  }
30275
30924
  close() {
30276
30925
  if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) {
@@ -30291,7 +30940,7 @@ var require_topology = __commonJS((exports) => {
30291
30940
  stateTransition(this, common_1.STATE_CLOSED);
30292
30941
  this.emitAndLog(Topology.TOPOLOGY_CLOSED, new events_1.TopologyClosedEvent(this.s.id));
30293
30942
  }
30294
- selectServer(selector, options, callback) {
30943
+ async selectServer(selector, options) {
30295
30944
  let serverSelector;
30296
30945
  if (typeof selector !== "function") {
30297
30946
  if (typeof selector === "string") {
@@ -30320,32 +30969,39 @@ var require_topology = __commonJS((exports) => {
30320
30969
  if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
30321
30970
  this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionSucceededEvent(selector, this.description, transaction.server.pool.address, options.operationName));
30322
30971
  }
30323
- callback(undefined, transaction.server);
30324
- return;
30972
+ return transaction.server;
30325
30973
  }
30974
+ const { promise: serverPromise, resolve, reject } = (0, utils_1.promiseWithResolvers)();
30975
+ const timeout = timeout_1.Timeout.expires(options.serverSelectionTimeoutMS ?? 0);
30326
30976
  const waitQueueMember = {
30327
30977
  serverSelector,
30328
30978
  topologyDescription: this.description,
30329
30979
  mongoLogger: this.client.mongoLogger,
30330
30980
  transaction,
30331
- callback,
30332
- timeoutController: new utils_1.TimeoutController(options.serverSelectionTimeoutMS),
30981
+ resolve,
30982
+ reject,
30983
+ timeout,
30333
30984
  startTime: (0, utils_1.now)(),
30334
30985
  operationName: options.operationName,
30335
30986
  waitingLogged: false,
30336
30987
  previousServer: options.previousServer
30337
30988
  };
30338
- waitQueueMember.timeoutController.signal.addEventListener("abort", () => {
30339
- waitQueueMember[kCancelled] = true;
30340
- waitQueueMember.timeoutController.clear();
30341
- const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${options.serverSelectionTimeoutMS} ms`, this.description);
30342
- if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
30343
- this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(selector, this.description, timeoutError, options.operationName));
30344
- }
30345
- waitQueueMember.callback(timeoutError);
30346
- });
30347
30989
  this[kWaitQueue].push(waitQueueMember);
30348
30990
  processWaitQueue(this);
30991
+ try {
30992
+ return await Promise.race([serverPromise, waitQueueMember.timeout]);
30993
+ } catch (error) {
30994
+ if (timeout_1.TimeoutError.is(error)) {
30995
+ waitQueueMember[kCancelled] = true;
30996
+ timeout.clear();
30997
+ const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${options.serverSelectionTimeoutMS} ms`, this.description);
30998
+ if (this.client.mongoLogger?.willLog(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, mongo_logger_1.SeverityLevel.DEBUG)) {
30999
+ this.client.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.SERVER_SELECTION, new server_selection_events_1.ServerSelectionFailedEvent(selector, this.description, timeoutError, options.operationName));
31000
+ }
31001
+ throw timeoutError;
31002
+ }
31003
+ throw error;
31004
+ }
30349
31005
  }
30350
31006
  serverUpdateHandler(serverDescription) {
30351
31007
  if (!this.s.description.hasServer(serverDescription.address)) {
@@ -30473,7 +31129,6 @@ var require_mongo_client = __commonJS((exports) => {
30473
31129
  Object.defineProperty(exports, "__esModule", { value: true });
30474
31130
  exports.MongoClient = exports.ServerApiVersion = undefined;
30475
31131
  var fs_1 = import.meta.require("fs");
30476
- var util_1 = import.meta.require("util");
30477
31132
  var bson_1 = require_bson2();
30478
31133
  var change_stream_1 = require_change_stream();
30479
31134
  var mongo_credentials_1 = require_mongo_credentials();
@@ -30570,7 +31225,7 @@ var require_mongo_client = __commonJS((exports) => {
30570
31225
  }
30571
31226
  async connect() {
30572
31227
  if (this.connectionLock) {
30573
- return this.connectionLock;
31228
+ return await this.connectionLock;
30574
31229
  }
30575
31230
  try {
30576
31231
  this.connectionLock = this._connect();
@@ -30624,7 +31279,7 @@ var require_mongo_client = __commonJS((exports) => {
30624
31279
  }
30625
31280
  const topologyConnect = async () => {
30626
31281
  try {
30627
- await (0, util_1.promisify)((callback) => this.topology?.connect(options, callback))();
31282
+ await this.topology?.connect(options);
30628
31283
  } catch (error) {
30629
31284
  this.topology?.close();
30630
31285
  throw error;
@@ -30659,7 +31314,11 @@ var require_mongo_client = __commonJS((exports) => {
30659
31314
  if (servers.length !== 0) {
30660
31315
  const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id);
30661
31316
  if (endSessions.length !== 0) {
30662
- await (0, execute_operation_1.executeOperation)(this, new run_command_1.RunAdminCommandOperation({ endSessions }, { readPreference: read_preference_1.ReadPreference.primaryPreferred, noResponse: true })).catch(() => null);
31317
+ try {
31318
+ await (0, execute_operation_1.executeOperation)(this, new run_command_1.RunAdminCommandOperation({ endSessions }, { readPreference: read_preference_1.ReadPreference.primaryPreferred, noResponse: true }));
31319
+ } catch (error) {
31320
+ (0, utils_1.squashError)(error);
31321
+ }
30663
31322
  }
30664
31323
  }
30665
31324
  const topology = this.topology;
@@ -30681,7 +31340,7 @@ var require_mongo_client = __commonJS((exports) => {
30681
31340
  }
30682
31341
  static async connect(url, options) {
30683
31342
  const client = new this(url, options);
30684
- return client.connect();
31343
+ return await client.connect();
30685
31344
  }
30686
31345
  startSession(options) {
30687
31346
  const session = new sessions_1.ClientSession(this, this.s.sessionPool, { explicit: true, ...options }, this[kOptions]);
@@ -30706,7 +31365,8 @@ var require_mongo_client = __commonJS((exports) => {
30706
31365
  } finally {
30707
31366
  try {
30708
31367
  await session.endSession();
30709
- } catch {
31368
+ } catch (error) {
31369
+ (0, utils_1.squashError)(error);
30710
31370
  }
30711
31371
  }
30712
31372
  }
@@ -30805,7 +31465,8 @@ var require_change_stream = __commonJS((exports) => {
30805
31465
  } catch (error2) {
30806
31466
  try {
30807
31467
  await this.close();
30808
- } catch {
31468
+ } catch (error3) {
31469
+ (0, utils_1.squashError)(error3);
30809
31470
  }
30810
31471
  throw error2;
30811
31472
  }
@@ -30825,7 +31486,8 @@ var require_change_stream = __commonJS((exports) => {
30825
31486
  } catch (error2) {
30826
31487
  try {
30827
31488
  await this.close();
30828
- } catch {
31489
+ } catch (error3) {
31490
+ (0, utils_1.squashError)(error3);
30829
31491
  }
30830
31492
  throw error2;
30831
31493
  }
@@ -30844,7 +31506,8 @@ var require_change_stream = __commonJS((exports) => {
30844
31506
  } catch (error2) {
30845
31507
  try {
30846
31508
  await this.close();
30847
- } catch {
31509
+ } catch (error3) {
31510
+ (0, utils_1.squashError)(error3);
30848
31511
  }
30849
31512
  throw error2;
30850
31513
  }
@@ -30862,7 +31525,8 @@ var require_change_stream = __commonJS((exports) => {
30862
31525
  } finally {
30863
31526
  try {
30864
31527
  await this.close();
30865
- } catch {
31528
+ } catch (error) {
31529
+ (0, utils_1.squashError)(error);
30866
31530
  }
30867
31531
  }
30868
31532
  }
@@ -30918,7 +31582,7 @@ var require_change_stream = __commonJS((exports) => {
30918
31582
  }
30919
31583
  _closeEmitterModeWithError(error) {
30920
31584
  this.emit(ChangeStream.ERROR, error);
30921
- this.close().catch(() => null);
31585
+ this.close().then(undefined, utils_1.squashError);
30922
31586
  }
30923
31587
  _streamEvents(cursor) {
30924
31588
  this._setIsEmitter();
@@ -30961,13 +31625,13 @@ var require_change_stream = __commonJS((exports) => {
30961
31625
  return;
30962
31626
  if ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) {
30963
31627
  this._endStream();
30964
- this.cursor.close().catch(() => null);
31628
+ this.cursor.close().then(undefined, utils_1.squashError);
30965
31629
  const topology = (0, utils_1.getTopology)(this.parent);
30966
- topology.selectServer(this.cursor.readPreference, { operationName: "reconnect topology in change stream" }, (serverSelectionError) => {
30967
- if (serverSelectionError)
30968
- return this._closeEmitterModeWithError(changeStreamError);
31630
+ topology.selectServer(this.cursor.readPreference, {
31631
+ operationName: "reconnect topology in change stream"
31632
+ }).then(() => {
30969
31633
  this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions);
30970
- });
31634
+ }, () => this._closeEmitterModeWithError(changeStreamError));
30971
31635
  } else {
30972
31636
  this._closeEmitterModeWithError(changeStreamError);
30973
31637
  }
@@ -30979,14 +31643,19 @@ var require_change_stream = __commonJS((exports) => {
30979
31643
  if (!(0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) {
30980
31644
  try {
30981
31645
  await this.close();
30982
- } catch {
31646
+ } catch (error) {
31647
+ (0, utils_1.squashError)(error);
30983
31648
  }
30984
31649
  throw changeStreamError;
30985
31650
  }
30986
- await this.cursor.close().catch(() => null);
31651
+ try {
31652
+ await this.cursor.close();
31653
+ } catch (error) {
31654
+ (0, utils_1.squashError)(error);
31655
+ }
30987
31656
  const topology = (0, utils_1.getTopology)(this.parent);
30988
31657
  try {
30989
- await topology.selectServerAsync(this.cursor.readPreference, {
31658
+ await topology.selectServer(this.cursor.readPreference, {
30990
31659
  operationName: "reconnect topology in change stream"
30991
31660
  });
30992
31661
  this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions);
@@ -31021,17 +31690,12 @@ var require_download = __commonJS((exports) => {
31021
31690
  return;
31022
31691
  if (!stream.s.file)
31023
31692
  return;
31024
- const handleReadResult = ({ error, doc }) => {
31025
- if (stream.destroyed) {
31026
- return;
31027
- }
31028
- if (error) {
31029
- stream.destroy(error);
31693
+ const handleReadResult = (doc) => {
31694
+ if (stream.destroyed)
31030
31695
  return;
31031
- }
31032
31696
  if (!doc) {
31033
31697
  stream.push(null);
31034
- stream.s.cursor?.close().then(() => null, (error2) => stream.destroy(error2));
31698
+ stream.s.cursor?.close().then(undefined, (error) => stream.destroy(error));
31035
31699
  return;
31036
31700
  }
31037
31701
  if (!stream.s.file)
@@ -31075,7 +31739,11 @@ var require_download = __commonJS((exports) => {
31075
31739
  stream.push(buf);
31076
31740
  return;
31077
31741
  };
31078
- stream.s.cursor.next().then((doc) => handleReadResult({ error: null, doc }), (error) => handleReadResult({ error, doc: null }));
31742
+ stream.s.cursor.next().then(handleReadResult, (error) => {
31743
+ if (stream.destroyed)
31744
+ return;
31745
+ stream.destroy(error);
31746
+ });
31079
31747
  };
31080
31748
  var init2 = function(stream) {
31081
31749
  const findOneOptions = {};
@@ -31088,10 +31756,9 @@ var require_download = __commonJS((exports) => {
31088
31756
  if (stream.s.options && stream.s.options.skip) {
31089
31757
  findOneOptions.skip = stream.s.options.skip;
31090
31758
  }
31091
- const handleReadResult = ({ error, doc }) => {
31092
- if (error) {
31093
- return stream.destroy(error);
31094
- }
31759
+ const handleReadResult = (doc) => {
31760
+ if (stream.destroyed)
31761
+ return;
31095
31762
  if (!doc) {
31096
31763
  const identifier = stream.s.filter._id ? stream.s.filter._id.toString() : stream.s.filter.filename;
31097
31764
  const errmsg = `FileNotFound: file ${identifier} was not found`;
@@ -31109,8 +31776,8 @@ var require_download = __commonJS((exports) => {
31109
31776
  }
31110
31777
  try {
31111
31778
  stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options);
31112
- } catch (error2) {
31113
- return stream.destroy(error2);
31779
+ } catch (error) {
31780
+ return stream.destroy(error);
31114
31781
  }
31115
31782
  const filter = { files_id: doc._id };
31116
31783
  if (stream.s.options && stream.s.options.start != null) {
@@ -31127,13 +31794,17 @@ var require_download = __commonJS((exports) => {
31127
31794
  stream.s.file = doc;
31128
31795
  try {
31129
31796
  stream.s.bytesToTrim = handleEndOption(stream, doc, stream.s.cursor, stream.s.options);
31130
- } catch (error2) {
31131
- return stream.destroy(error2);
31797
+ } catch (error) {
31798
+ return stream.destroy(error);
31132
31799
  }
31133
31800
  stream.emit(GridFSBucketReadStream.FILE, doc);
31134
31801
  return;
31135
31802
  };
31136
- stream.s.files.findOne(stream.s.filter, findOneOptions).then((doc) => handleReadResult({ error: null, doc }), (error) => handleReadResult({ error, doc: null }));
31803
+ stream.s.files.findOne(stream.s.filter, findOneOptions).then(handleReadResult, (error) => {
31804
+ if (stream.destroyed)
31805
+ return;
31806
+ stream.destroy(error);
31807
+ });
31137
31808
  };
31138
31809
  var waitForFile = function(stream, callback) {
31139
31810
  if (stream.s.file) {
@@ -31412,6 +32083,7 @@ var require_upload = __commonJS((exports) => {
31412
32083
  var stream_1 = import.meta.require("stream");
31413
32084
  var bson_1 = require_bson2();
31414
32085
  var error_1 = require_error();
32086
+ var utils_1 = require_utils2();
31415
32087
  var write_concern_1 = require_write_concern();
31416
32088
 
31417
32089
  class GridFSBucketWriteStream extends stream_1.Writable {
@@ -31443,7 +32115,7 @@ var require_upload = __commonJS((exports) => {
31443
32115
  checkIndexes(this).then(() => {
31444
32116
  this.bucket.s.checkedIndexes = true;
31445
32117
  this.bucket.emit("index");
31446
- }, () => null);
32118
+ }, utils_1.squashError);
31447
32119
  }
31448
32120
  }
31449
32121
  _construct(callback) {
@@ -31667,7 +32339,7 @@ var require_client_encryption = __commonJS((exports) => {
31667
32339
  }
31668
32340
  async deleteKey(_id) {
31669
32341
  const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
31670
- return this._keyVaultClient.db(dbName).collection(collectionName).deleteOne({ _id }, { writeConcern: { w: "majority" } });
32342
+ return await this._keyVaultClient.db(dbName).collection(collectionName).deleteOne({ _id }, { writeConcern: { w: "majority" } });
31671
32343
  }
31672
32344
  getKeys() {
31673
32345
  const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
@@ -31675,11 +32347,11 @@ var require_client_encryption = __commonJS((exports) => {
31675
32347
  }
31676
32348
  async getKey(_id) {
31677
32349
  const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
31678
- return this._keyVaultClient.db(dbName).collection(collectionName).findOne({ _id }, { readConcern: { level: "majority" } });
32350
+ return await this._keyVaultClient.db(dbName).collection(collectionName).findOne({ _id }, { readConcern: { level: "majority" } });
31679
32351
  }
31680
32352
  async getKeyByAltName(keyAltName) {
31681
32353
  const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
31682
- return this._keyVaultClient.db(dbName).collection(collectionName).findOne({ keyAltNames: keyAltName }, { readConcern: { level: "majority" } });
32354
+ return await this._keyVaultClient.db(dbName).collection(collectionName).findOne({ keyAltNames: keyAltName }, { readConcern: { level: "majority" } });
31683
32355
  }
31684
32356
  async addKeyAltName(_id, keyAltName) {
31685
32357
  const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);
@@ -31741,10 +32413,10 @@ var require_client_encryption = __commonJS((exports) => {
31741
32413
  }
31742
32414
  }
31743
32415
  async encrypt(value, options) {
31744
- return this._encrypt(value, false, options);
32416
+ return await this._encrypt(value, false, options);
31745
32417
  }
31746
32418
  async encryptExpression(expression, options) {
31747
- return this._encrypt(expression, true, options);
32419
+ return await this._encrypt(expression, true, options);
31748
32420
  }
31749
32421
  async decrypt(value) {
31750
32422
  const valueBuffer = (0, bson_1.serialize)({ v: value });
@@ -31757,7 +32429,7 @@ var require_client_encryption = __commonJS((exports) => {
31757
32429
  return v;
31758
32430
  }
31759
32431
  async askForKMSCredentials() {
31760
- return (0, index_1.refreshKMSCredentials)(this._kmsProviders);
32432
+ return await (0, index_1.refreshKMSCredentials)(this._kmsProviders);
31761
32433
  }
31762
32434
  static get libmongocryptVersion() {
31763
32435
  return ClientEncryption.getMongoCrypt().libmongocryptVersion;
@@ -59782,17 +60454,17 @@ var httpStatus = [
59782
60454
 
59783
60455
  // node_modules/@point-hub/express-error-handler/lib/api-error.js
59784
60456
  class ApiError extends BaseError {
59785
- constructor(codeStatus, message, errors) {
60457
+ constructor(codeStatus, options) {
59786
60458
  const status = find(codeStatus);
59787
60459
  if (!status) {
59788
60460
  throw new Error(`Error codeStatus "${codeStatus}" not found`);
59789
60461
  }
59790
60462
  const error = status;
59791
- if (message) {
59792
- error.message = message;
60463
+ if (options === null || options === undefined ? undefined : options.message) {
60464
+ error.message = options.message;
59793
60465
  }
59794
- if (error.code === 422 && errors) {
59795
- error.errors = errors;
60466
+ if (error.code >= 400 && error.code <= 500 && (options === null || options === undefined ? undefined : options.errors)) {
60467
+ error.errors = options.errors;
59796
60468
  }
59797
60469
  super(error);
59798
60470
  }