bson 4.5.2 → 4.6.1

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 (56) hide show
  1. package/bower.json +1 -1
  2. package/bson.d.ts +39 -3
  3. package/dist/bson.browser.esm.js +320 -187
  4. package/dist/bson.browser.esm.js.map +1 -1
  5. package/dist/bson.browser.umd.js +323 -186
  6. package/dist/bson.browser.umd.js.map +1 -1
  7. package/dist/bson.bundle.js +323 -186
  8. package/dist/bson.bundle.js.map +1 -1
  9. package/dist/bson.esm.js +320 -187
  10. package/dist/bson.esm.js.map +1 -1
  11. package/lib/binary.js +11 -6
  12. package/lib/binary.js.map +1 -1
  13. package/lib/bson.js +11 -3
  14. package/lib/bson.js.map +1 -1
  15. package/lib/constants.js +5 -1
  16. package/lib/constants.js.map +1 -1
  17. package/lib/decimal128.js +13 -5
  18. package/lib/decimal128.js.map +1 -1
  19. package/lib/ensure_buffer.js +3 -2
  20. package/lib/ensure_buffer.js.map +1 -1
  21. package/lib/error.js +55 -0
  22. package/lib/error.js.map +1 -0
  23. package/lib/extended_json.js +11 -5
  24. package/lib/extended_json.js.map +1 -1
  25. package/lib/int_32.js +1 -1
  26. package/lib/int_32.js.map +1 -1
  27. package/lib/objectid.js +42 -47
  28. package/lib/objectid.js.map +1 -1
  29. package/lib/parser/calculate_size.js +2 -2
  30. package/lib/parser/calculate_size.js.map +1 -1
  31. package/lib/parser/deserializer.js +131 -53
  32. package/lib/parser/deserializer.js.map +1 -1
  33. package/lib/parser/serializer.js +16 -20
  34. package/lib/parser/serializer.js.map +1 -1
  35. package/lib/regexp.js +9 -2
  36. package/lib/regexp.js.map +1 -1
  37. package/lib/uuid.js +2 -1
  38. package/lib/uuid.js.map +1 -1
  39. package/lib/uuid_utils.js +2 -1
  40. package/lib/uuid_utils.js.map +1 -1
  41. package/package.json +4 -2
  42. package/src/binary.ts +11 -6
  43. package/src/bson.ts +7 -1
  44. package/src/constants.ts +6 -0
  45. package/src/decimal128.ts +12 -5
  46. package/src/ensure_buffer.ts +3 -2
  47. package/src/error.ts +23 -0
  48. package/src/extended_json.ts +13 -5
  49. package/src/int_32.ts +1 -1
  50. package/src/objectid.ts +44 -62
  51. package/src/parser/calculate_size.ts +2 -2
  52. package/src/parser/deserializer.ts +159 -57
  53. package/src/parser/serializer.ts +16 -17
  54. package/src/regexp.ts +14 -2
  55. package/src/uuid.ts +2 -1
  56. package/src/uuid_utils.ts +2 -1
@@ -2031,6 +2031,97 @@ buffer$1.SlowBuffer;
2031
2031
  buffer$1.INSPECT_MAX_BYTES;
2032
2032
  buffer$1.kMaxLength;
2033
2033
 
2034
+ /*! *****************************************************************************
2035
+ Copyright (c) Microsoft Corporation.
2036
+
2037
+ Permission to use, copy, modify, and/or distribute this software for any
2038
+ purpose with or without fee is hereby granted.
2039
+
2040
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2041
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2042
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2043
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2044
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2045
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2046
+ PERFORMANCE OF THIS SOFTWARE.
2047
+ ***************************************************************************** */
2048
+
2049
+ /* global Reflect, Promise */
2050
+ var _extendStatics = function extendStatics(d, b) {
2051
+ _extendStatics = Object.setPrototypeOf || {
2052
+ __proto__: []
2053
+ } instanceof Array && function (d, b) {
2054
+ d.__proto__ = b;
2055
+ } || function (d, b) {
2056
+ for (var p in b) {
2057
+ if (b.hasOwnProperty(p)) d[p] = b[p];
2058
+ }
2059
+ };
2060
+
2061
+ return _extendStatics(d, b);
2062
+ };
2063
+
2064
+ function __extends(d, b) {
2065
+ _extendStatics(d, b);
2066
+
2067
+ function __() {
2068
+ this.constructor = d;
2069
+ }
2070
+
2071
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2072
+ }
2073
+
2074
+ var _assign = function __assign() {
2075
+ _assign = Object.assign || function __assign(t) {
2076
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
2077
+ s = arguments[i];
2078
+
2079
+ for (var p in s) {
2080
+ if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
2081
+ }
2082
+ }
2083
+
2084
+ return t;
2085
+ };
2086
+
2087
+ return _assign.apply(this, arguments);
2088
+ };
2089
+
2090
+ /** @public */
2091
+ var BSONError = /** @class */ (function (_super) {
2092
+ __extends(BSONError, _super);
2093
+ function BSONError(message) {
2094
+ var _this = _super.call(this, message) || this;
2095
+ Object.setPrototypeOf(_this, BSONError.prototype);
2096
+ return _this;
2097
+ }
2098
+ Object.defineProperty(BSONError.prototype, "name", {
2099
+ get: function () {
2100
+ return 'BSONError';
2101
+ },
2102
+ enumerable: false,
2103
+ configurable: true
2104
+ });
2105
+ return BSONError;
2106
+ }(Error));
2107
+ /** @public */
2108
+ var BSONTypeError = /** @class */ (function (_super) {
2109
+ __extends(BSONTypeError, _super);
2110
+ function BSONTypeError(message) {
2111
+ var _this = _super.call(this, message) || this;
2112
+ Object.setPrototypeOf(_this, BSONTypeError.prototype);
2113
+ return _this;
2114
+ }
2115
+ Object.defineProperty(BSONTypeError.prototype, "name", {
2116
+ get: function () {
2117
+ return 'BSONTypeError';
2118
+ },
2119
+ enumerable: false,
2120
+ configurable: true
2121
+ });
2122
+ return BSONTypeError;
2123
+ }(TypeError));
2124
+
2034
2125
  function checkForMath(potentialGlobal) {
2035
2126
  // eslint-disable-next-line eqeqeq
2036
2127
  return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal;
@@ -2142,7 +2233,7 @@ function deprecate(fn, message) {
2142
2233
  * @param potentialBuffer - The potential buffer
2143
2234
  * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
2144
2235
  * wraps a passed in Uint8Array
2145
- * @throws TypeError If anything other than a Buffer or Uint8Array is passed in
2236
+ * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in
2146
2237
  */
2147
2238
  function ensureBuffer(potentialBuffer) {
2148
2239
  if (ArrayBuffer.isView(potentialBuffer)) {
@@ -2151,7 +2242,7 @@ function ensureBuffer(potentialBuffer) {
2151
2242
  if (isAnyArrayBuffer(potentialBuffer)) {
2152
2243
  return buffer_1.from(potentialBuffer);
2153
2244
  }
2154
- throw new TypeError('Must use either Buffer or TypedArray');
2245
+ throw new BSONTypeError('Must use either Buffer or TypedArray');
2155
2246
  }
2156
2247
 
2157
2248
  // Validation regex for v4 uuid (validates with or without dashes)
@@ -2161,7 +2252,7 @@ var uuidValidateString = function (str) {
2161
2252
  };
2162
2253
  var uuidHexStringToBuffer = function (hexString) {
2163
2254
  if (!uuidValidateString(hexString)) {
2164
- throw new TypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".');
2255
+ throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".');
2165
2256
  }
2166
2257
  var sanitizedHexString = hexString.replace(/-/g, '');
2167
2258
  return buffer_1.from(sanitizedHexString, 'hex');
@@ -2209,7 +2300,7 @@ var UUID = /** @class */ (function () {
2209
2300
  this.id = uuidHexStringToBuffer(input);
2210
2301
  }
2211
2302
  else {
2212
- throw new TypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).');
2303
+ throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).');
2213
2304
  }
2214
2305
  }
2215
2306
  Object.defineProperty(UUID.prototype, "id", {
@@ -2367,7 +2458,7 @@ var Binary = /** @class */ (function () {
2367
2458
  !ArrayBuffer.isView(buffer) &&
2368
2459
  !(buffer instanceof ArrayBuffer) &&
2369
2460
  !Array.isArray(buffer)) {
2370
- throw new TypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
2461
+ throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
2371
2462
  }
2372
2463
  this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT;
2373
2464
  if (buffer == null) {
@@ -2399,10 +2490,10 @@ var Binary = /** @class */ (function () {
2399
2490
  Binary.prototype.put = function (byteValue) {
2400
2491
  // If it's a string and a has more than one character throw an error
2401
2492
  if (typeof byteValue === 'string' && byteValue.length !== 1) {
2402
- throw new TypeError('only accepts single character String');
2493
+ throw new BSONTypeError('only accepts single character String');
2403
2494
  }
2404
2495
  else if (typeof byteValue !== 'number' && byteValue.length !== 1)
2405
- throw new TypeError('only accepts single character Uint8Array or Array');
2496
+ throw new BSONTypeError('only accepts single character Uint8Array or Array');
2406
2497
  // Decode the byte value once
2407
2498
  var decodedByte;
2408
2499
  if (typeof byteValue === 'string') {
@@ -2415,7 +2506,7 @@ var Binary = /** @class */ (function () {
2415
2506
  decodedByte = byteValue[0];
2416
2507
  }
2417
2508
  if (decodedByte < 0 || decodedByte > 255) {
2418
- throw new TypeError('only accepts number in a valid unsigned byte range 0-255');
2509
+ throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255');
2419
2510
  }
2420
2511
  if (this.buffer.length > this.position) {
2421
2512
  this.buffer[this.position++] = decodedByte;
@@ -2515,7 +2606,7 @@ var Binary = /** @class */ (function () {
2515
2606
  if (this.sub_type === Binary.SUBTYPE_UUID) {
2516
2607
  return new UUID(this.buffer.slice(0, this.position));
2517
2608
  }
2518
- throw new Error("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
2609
+ throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
2519
2610
  };
2520
2611
  /** @internal */
2521
2612
  Binary.fromExtendedJSON = function (doc, options) {
@@ -2539,7 +2630,7 @@ var Binary = /** @class */ (function () {
2539
2630
  data = uuidHexStringToBuffer(doc.$uuid);
2540
2631
  }
2541
2632
  if (!data) {
2542
- throw new TypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
2633
+ throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
2543
2634
  }
2544
2635
  return new Binary(data, type);
2545
2636
  };
@@ -2570,6 +2661,10 @@ var Binary = /** @class */ (function () {
2570
2661
  Binary.SUBTYPE_UUID = 4;
2571
2662
  /** MD5 BSON type */
2572
2663
  Binary.SUBTYPE_MD5 = 5;
2664
+ /** Encrypted BSON type */
2665
+ Binary.SUBTYPE_ENCRYPTED = 6;
2666
+ /** Column BSON type */
2667
+ Binary.SUBTYPE_COLUMN = 7;
2573
2668
  /** User BSON type */
2574
2669
  Binary.SUBTYPE_USER_DEFINED = 128;
2575
2670
  return Binary;
@@ -3688,7 +3783,7 @@ function lessThan(left, right) {
3688
3783
  return false;
3689
3784
  }
3690
3785
  function invalidErr(string, message) {
3691
- throw new TypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
3786
+ throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
3692
3787
  }
3693
3788
  /**
3694
3789
  * A class representation of the BSON Decimal128 type.
@@ -3705,9 +3800,15 @@ var Decimal128 = /** @class */ (function () {
3705
3800
  if (typeof bytes === 'string') {
3706
3801
  this.bytes = Decimal128.fromString(bytes).bytes;
3707
3802
  }
3708
- else {
3803
+ else if (isUint8Array(bytes)) {
3804
+ if (bytes.byteLength !== 16) {
3805
+ throw new BSONTypeError('Decimal128 must take a Buffer of 16 bytes');
3806
+ }
3709
3807
  this.bytes = bytes;
3710
3808
  }
3809
+ else {
3810
+ throw new BSONTypeError('Decimal128 must take a Buffer or string');
3811
+ }
3711
3812
  }
3712
3813
  /**
3713
3814
  * Create a Decimal128 instance from a string representation
@@ -3755,7 +3856,7 @@ var Decimal128 = /** @class */ (function () {
3755
3856
  // TODO: implementing a custom parsing for this, or refactoring the regex would yield
3756
3857
  // further gains.
3757
3858
  if (representation.length >= 7000) {
3758
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
3859
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
3759
3860
  }
3760
3861
  // Results
3761
3862
  var stringMatch = representation.match(PARSE_STRING_REGEXP);
@@ -3763,7 +3864,7 @@ var Decimal128 = /** @class */ (function () {
3763
3864
  var nanMatch = representation.match(PARSE_NAN_REGEXP);
3764
3865
  // Validate the string
3765
3866
  if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
3766
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
3867
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
3767
3868
  }
3768
3869
  if (stringMatch) {
3769
3870
  // full_match = stringMatch[0]
@@ -3825,7 +3926,7 @@ var Decimal128 = /** @class */ (function () {
3825
3926
  index = index + 1;
3826
3927
  }
3827
3928
  if (sawRadix && !nDigitsRead)
3828
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
3929
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
3829
3930
  // Read exponent if exists
3830
3931
  if (representation[index] === 'e' || representation[index] === 'E') {
3831
3932
  // Read exponent digits
@@ -4342,7 +4443,7 @@ var Int32 = /** @class */ (function () {
4342
4443
  if (value instanceof Number) {
4343
4444
  value = value.valueOf();
4344
4445
  }
4345
- this.value = +value;
4446
+ this.value = +value | 0;
4346
4447
  }
4347
4448
  /**
4348
4449
  * Access the number value.
@@ -4448,50 +4549,57 @@ var ObjectId = /** @class */ (function () {
4448
4549
  /**
4449
4550
  * Create an ObjectId type
4450
4551
  *
4451
- * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
4552
+ * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
4452
4553
  */
4453
- function ObjectId(id) {
4554
+ function ObjectId(inputId) {
4454
4555
  if (!(this instanceof ObjectId))
4455
- return new ObjectId(id);
4456
- // Duck-typing to support ObjectId from different npm packages
4457
- if (id instanceof ObjectId) {
4458
- this[kId] = id.id;
4459
- this.__id = id.__id;
4460
- }
4461
- if (typeof id === 'object' && id && 'id' in id) {
4462
- if ('toHexString' in id && typeof id.toHexString === 'function') {
4463
- this[kId] = buffer_1.from(id.toHexString(), 'hex');
4556
+ return new ObjectId(inputId);
4557
+ // workingId is set based on type of input and whether valid id exists for the input
4558
+ var workingId;
4559
+ if (typeof inputId === 'object' && inputId && 'id' in inputId) {
4560
+ if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
4561
+ throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer');
4562
+ }
4563
+ if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
4564
+ workingId = buffer_1.from(inputId.toHexString(), 'hex');
4464
4565
  }
4465
4566
  else {
4466
- this[kId] = typeof id.id === 'string' ? buffer_1.from(id.id) : id.id;
4567
+ workingId = inputId.id;
4467
4568
  }
4468
4569
  }
4469
- // The most common use case (blank id, new objectId instance)
4470
- if (id == null || typeof id === 'number') {
4570
+ else {
4571
+ workingId = inputId;
4572
+ }
4573
+ // the following cases use workingId to construct an ObjectId
4574
+ if (workingId == null || typeof workingId === 'number') {
4575
+ // The most common use case (blank id, new objectId instance)
4471
4576
  // Generate a new id
4472
- this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined);
4473
- // If we are caching the hex string
4474
- if (ObjectId.cacheHexString) {
4475
- this.__id = this.id.toString('hex');
4476
- }
4577
+ this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
4477
4578
  }
4478
- if (ArrayBuffer.isView(id) && id.byteLength === 12) {
4479
- this[kId] = ensureBuffer(id);
4579
+ else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
4580
+ this[kId] = ensureBuffer(workingId);
4480
4581
  }
4481
- if (typeof id === 'string') {
4482
- if (id.length === 12) {
4483
- var bytes = buffer_1.from(id);
4582
+ else if (typeof workingId === 'string') {
4583
+ if (workingId.length === 12) {
4584
+ var bytes = buffer_1.from(workingId);
4484
4585
  if (bytes.byteLength === 12) {
4485
4586
  this[kId] = bytes;
4486
4587
  }
4588
+ else {
4589
+ throw new BSONTypeError('Argument passed in must be a string of 12 bytes');
4590
+ }
4487
4591
  }
4488
- else if (id.length === 24 && checkForHexRegExp.test(id)) {
4489
- this[kId] = buffer_1.from(id, 'hex');
4592
+ else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
4593
+ this[kId] = buffer_1.from(workingId, 'hex');
4490
4594
  }
4491
4595
  else {
4492
- throw new TypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters');
4596
+ throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters');
4493
4597
  }
4494
4598
  }
4599
+ else {
4600
+ throw new BSONTypeError('Argument passed in does not match the accepted types');
4601
+ }
4602
+ // If we are caching the hex string
4495
4603
  if (ObjectId.cacheHexString) {
4496
4604
  this.__id = this.id.toString('hex');
4497
4605
  }
@@ -4555,7 +4663,7 @@ var ObjectId = /** @class */ (function () {
4555
4663
  */
4556
4664
  ObjectId.generate = function (time) {
4557
4665
  if ('number' !== typeof time) {
4558
- time = ~~(Date.now() / 1000);
4666
+ time = Math.floor(Date.now() / 1000);
4559
4667
  }
4560
4668
  var inc = ObjectId.getInc();
4561
4669
  var buffer = buffer_1.alloc(12);
@@ -4654,7 +4762,7 @@ var ObjectId = /** @class */ (function () {
4654
4762
  ObjectId.createFromHexString = function (hexString) {
4655
4763
  // Throw an error if it's not a valid setup
4656
4764
  if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
4657
- throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
4765
+ throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
4658
4766
  }
4659
4767
  return new ObjectId(buffer_1.from(hexString, 'hex'));
4660
4768
  };
@@ -4666,26 +4774,13 @@ var ObjectId = /** @class */ (function () {
4666
4774
  ObjectId.isValid = function (id) {
4667
4775
  if (id == null)
4668
4776
  return false;
4669
- if (typeof id === 'number') {
4670
- return true;
4671
- }
4672
- if (typeof id === 'string') {
4673
- return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));
4674
- }
4675
- if (id instanceof ObjectId) {
4676
- return true;
4677
- }
4678
- if (isUint8Array(id) && id.length === 12) {
4777
+ try {
4778
+ new ObjectId(id);
4679
4779
  return true;
4680
4780
  }
4681
- // Duck-Typing detection of ObjectId like objects
4682
- if (typeof id === 'object' && 'toHexString' in id && typeof id.toHexString === 'function') {
4683
- if (typeof id.id === 'string') {
4684
- return id.id.length === 12;
4685
- }
4686
- return id.toHexString().length === 24 && checkForHexRegExp.test(id.id.toString('hex'));
4781
+ catch (_a) {
4782
+ return false;
4687
4783
  }
4688
- return false;
4689
4784
  };
4690
4785
  /** @internal */
4691
4786
  ObjectId.prototype.toExtendedJSON = function () {
@@ -4710,7 +4805,7 @@ var ObjectId = /** @class */ (function () {
4710
4805
  return "new ObjectId(\"" + this.toHexString() + "\")";
4711
4806
  };
4712
4807
  /** @internal */
4713
- ObjectId.index = ~~(Math.random() * 0xffffff);
4808
+ ObjectId.index = Math.floor(Math.random() * 0xffffff);
4714
4809
  return ObjectId;
4715
4810
  }());
4716
4811
  // Deprecated methods
@@ -4745,6 +4840,12 @@ var BSONRegExp = /** @class */ (function () {
4745
4840
  return new BSONRegExp(pattern, options);
4746
4841
  this.pattern = pattern;
4747
4842
  this.options = alphabetize(options !== null && options !== void 0 ? options : '');
4843
+ if (this.pattern.indexOf('\x00') !== -1) {
4844
+ throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern));
4845
+ }
4846
+ if (this.options.indexOf('\x00') !== -1) {
4847
+ throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options));
4848
+ }
4748
4849
  // Validate options
4749
4850
  for (var i = 0; i < this.options.length; i++) {
4750
4851
  if (!(this.options[i] === 'i' ||
@@ -4753,7 +4854,7 @@ var BSONRegExp = /** @class */ (function () {
4753
4854
  this.options[i] === 'l' ||
4754
4855
  this.options[i] === 's' ||
4755
4856
  this.options[i] === 'u')) {
4756
- throw new Error("The regular expression option [" + this.options[i] + "] is not supported");
4857
+ throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported");
4757
4858
  }
4758
4859
  }
4759
4860
  }
@@ -4784,7 +4885,7 @@ var BSONRegExp = /** @class */ (function () {
4784
4885
  if ('$regularExpression' in doc) {
4785
4886
  return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
4786
4887
  }
4787
- throw new TypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
4888
+ throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
4788
4889
  };
4789
4890
  return BSONRegExp;
4790
4891
  }());
@@ -4833,46 +4934,6 @@ var BSONSymbol = /** @class */ (function () {
4833
4934
  }());
4834
4935
  Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' });
4835
4936
 
4836
- /*! *****************************************************************************
4837
- Copyright (c) Microsoft Corporation.
4838
-
4839
- Permission to use, copy, modify, and/or distribute this software for any
4840
- purpose with or without fee is hereby granted.
4841
-
4842
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
4843
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
4844
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
4845
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
4846
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4847
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4848
- PERFORMANCE OF THIS SOFTWARE.
4849
- ***************************************************************************** */
4850
-
4851
- /* global Reflect, Promise */
4852
- var _extendStatics = function extendStatics(d, b) {
4853
- _extendStatics = Object.setPrototypeOf || {
4854
- __proto__: []
4855
- } instanceof Array && function (d, b) {
4856
- d.__proto__ = b;
4857
- } || function (d, b) {
4858
- for (var p in b) {
4859
- if (b.hasOwnProperty(p)) d[p] = b[p];
4860
- }
4861
- };
4862
-
4863
- return _extendStatics(d, b);
4864
- };
4865
-
4866
- function __extends(d, b) {
4867
- _extendStatics(d, b);
4868
-
4869
- function __() {
4870
- this.constructor = d;
4871
- }
4872
-
4873
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4874
- }
4875
-
4876
4937
  /** @public */
4877
4938
  var LongWithoutOverridesClass = Long;
4878
4939
  /** @public */
@@ -5087,7 +5148,7 @@ function serializeValue(value, options) {
5087
5148
  var current = props[props.length - 1];
5088
5149
  var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
5089
5150
  var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
5090
- throw new TypeError('Converting circular structure to EJSON:\n' +
5151
+ throw new BSONTypeError('Converting circular structure to EJSON:\n' +
5091
5152
  (" " + leadingPart + alreadySeen + circularPart + current + "\n") +
5092
5153
  (" " + leadingSpace + "\\" + dashes + "/"));
5093
5154
  }
@@ -5160,7 +5221,7 @@ var BSON_TYPE_MAPPINGS = {
5160
5221
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
5161
5222
  function serializeDocument(doc, options) {
5162
5223
  if (doc == null || typeof doc !== 'object')
5163
- throw new Error('not an object instance');
5224
+ throw new BSONError('not an object instance');
5164
5225
  var bsontype = doc._bsontype;
5165
5226
  if (typeof bsontype === 'undefined') {
5166
5227
  // It's a regular object. Recursively serialize its property values.
@@ -5187,7 +5248,7 @@ function serializeDocument(doc, options) {
5187
5248
  // Copy the object into this library's version of that type.
5188
5249
  var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
5189
5250
  if (!mapper) {
5190
- throw new TypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
5251
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
5191
5252
  }
5192
5253
  outDoc = mapper(outDoc);
5193
5254
  }
@@ -5201,7 +5262,7 @@ function serializeDocument(doc, options) {
5201
5262
  return outDoc.toExtendedJSON(options);
5202
5263
  }
5203
5264
  else {
5204
- throw new Error('_bsontype must be a string, but was: ' + typeof bsontype);
5265
+ throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
5205
5266
  }
5206
5267
  }
5207
5268
  /**
@@ -5236,7 +5297,12 @@ var EJSON;
5236
5297
  finalOptions.strict = !finalOptions.relaxed;
5237
5298
  if (typeof finalOptions.strict === 'boolean')
5238
5299
  finalOptions.relaxed = !finalOptions.strict;
5239
- return JSON.parse(text, function (_key, value) { return deserializeValue(value, finalOptions); });
5300
+ return JSON.parse(text, function (key, value) {
5301
+ if (key.indexOf('\x00') !== -1) {
5302
+ throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key));
5303
+ }
5304
+ return deserializeValue(value, finalOptions);
5305
+ });
5240
5306
  }
5241
5307
  EJSON.parse = parse;
5242
5308
  /**
@@ -5494,6 +5560,10 @@ var BSON_BINARY_SUBTYPE_UUID = 3;
5494
5560
  var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
5495
5561
  /** Binary MD5 Type @internal */
5496
5562
  var BSON_BINARY_SUBTYPE_MD5 = 5;
5563
+ /** Encrypted BSON type @internal */
5564
+ var BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
5565
+ /** Column BSON type @internal */
5566
+ var BSON_BINARY_SUBTYPE_COLUMN = 7;
5497
5567
  /** Binary User Defined Type @internal */
5498
5568
  var BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
5499
5569
 
@@ -5506,7 +5576,7 @@ function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) {
5506
5576
  }
5507
5577
  else {
5508
5578
  // If we have toBSON defined, override the current object
5509
- if (object.toBSON) {
5579
+ if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
5510
5580
  object = object.toBSON();
5511
5581
  }
5512
5582
  // Calculate size
@@ -5524,7 +5594,7 @@ value, serializeFunctions, isArray, ignoreUndefined) {
5524
5594
  if (isArray === void 0) { isArray = false; }
5525
5595
  if (ignoreUndefined === void 0) { ignoreUndefined = false; }
5526
5596
  // If we have toBSON defined, override the current object
5527
- if (value && value.toBSON) {
5597
+ if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
5528
5598
  value = value.toBSON();
5529
5599
  }
5530
5600
  switch (typeof value) {
@@ -5738,20 +5808,20 @@ function deserialize$1(buffer, options, isArray) {
5738
5808
  (buffer[index + 2] << 16) |
5739
5809
  (buffer[index + 3] << 24);
5740
5810
  if (size < 5) {
5741
- throw new Error("bson size must be >= 5, is " + size);
5811
+ throw new BSONError("bson size must be >= 5, is " + size);
5742
5812
  }
5743
5813
  if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
5744
- throw new Error("buffer length " + buffer.length + " must be >= bson size " + size);
5814
+ throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size);
5745
5815
  }
5746
5816
  if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
5747
- throw new Error("buffer length " + buffer.length + " must === bson size " + size);
5817
+ throw new BSONError("buffer length " + buffer.length + " must === bson size " + size);
5748
5818
  }
5749
5819
  if (size + index > buffer.byteLength) {
5750
- throw new Error("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
5820
+ throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
5751
5821
  }
5752
5822
  // Illegal end value
5753
5823
  if (buffer[index + size - 1] !== 0) {
5754
- throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
5824
+ throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
5755
5825
  }
5756
5826
  // Start deserializtion
5757
5827
  return deserializeObject(buffer, index, options, isArray);
@@ -5770,16 +5840,53 @@ function deserializeObject(buffer, index, options, isArray) {
5770
5840
  var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
5771
5841
  var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
5772
5842
  var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
5843
+ // Ensures default validation option if none given
5844
+ var validation = options.validation == null ? { utf8: true } : options.validation;
5845
+ // Shows if global utf-8 validation is enabled or disabled
5846
+ var globalUTFValidation = true;
5847
+ // Reflects utf-8 validation setting regardless of global or specific key validation
5848
+ var validationSetting;
5849
+ // Set of keys either to enable or disable validation on
5850
+ var utf8KeysSet = new Set();
5851
+ // Check for boolean uniformity and empty validation option
5852
+ var utf8ValidatedKeys = validation.utf8;
5853
+ if (typeof utf8ValidatedKeys === 'boolean') {
5854
+ validationSetting = utf8ValidatedKeys;
5855
+ }
5856
+ else {
5857
+ globalUTFValidation = false;
5858
+ var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
5859
+ return utf8ValidatedKeys[key];
5860
+ });
5861
+ if (utf8ValidationValues.length === 0) {
5862
+ throw new BSONError('UTF-8 validation setting cannot be empty');
5863
+ }
5864
+ if (typeof utf8ValidationValues[0] !== 'boolean') {
5865
+ throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
5866
+ }
5867
+ validationSetting = utf8ValidationValues[0];
5868
+ // Ensures boolean uniformity in utf-8 validation (all true or all false)
5869
+ if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) {
5870
+ throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
5871
+ }
5872
+ }
5873
+ // Add keys to set that will either be validated or not based on validationSetting
5874
+ if (!globalUTFValidation) {
5875
+ for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) {
5876
+ var key = _a[_i];
5877
+ utf8KeysSet.add(key);
5878
+ }
5879
+ }
5773
5880
  // Set the start index
5774
5881
  var startIndex = index;
5775
5882
  // Validate that we have at least 4 bytes of buffer
5776
5883
  if (buffer.length < 5)
5777
- throw new Error('corrupt bson message < 5 bytes long');
5884
+ throw new BSONError('corrupt bson message < 5 bytes long');
5778
5885
  // Read the document size
5779
5886
  var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
5780
5887
  // Ensure buffer is valid size
5781
5888
  if (size < 5 || size > buffer.length)
5782
- throw new Error('corrupt bson message');
5889
+ throw new BSONError('corrupt bson message');
5783
5890
  // Create holding object
5784
5891
  var object = isArray ? [] : {};
5785
5892
  // Used for arrays to skip having to perform utf8 decoding
@@ -5801,8 +5908,17 @@ function deserializeObject(buffer, index, options, isArray) {
5801
5908
  }
5802
5909
  // If are at the end of the buffer there is a problem with the document
5803
5910
  if (i >= buffer.byteLength)
5804
- throw new Error('Bad BSON Document: illegal CString');
5911
+ throw new BSONError('Bad BSON Document: illegal CString');
5912
+ // Represents the key
5805
5913
  var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);
5914
+ // shouldValidateKey is true if the key should be validated, false otherwise
5915
+ var shouldValidateKey = true;
5916
+ if (globalUTFValidation || utf8KeysSet.has(name)) {
5917
+ shouldValidateKey = validationSetting;
5918
+ }
5919
+ else {
5920
+ shouldValidateKey = !validationSetting;
5921
+ }
5806
5922
  if (isPossibleDBRef !== false && name[0] === '$') {
5807
5923
  isPossibleDBRef = allowedDBRefKeys.test(name);
5808
5924
  }
@@ -5815,17 +5931,10 @@ function deserializeObject(buffer, index, options, isArray) {
5815
5931
  (buffer[index++] << 24);
5816
5932
  if (stringSize <= 0 ||
5817
5933
  stringSize > buffer.length - index ||
5818
- buffer[index + stringSize - 1] !== 0)
5819
- throw new Error('bad string length in bson');
5820
- value = buffer.toString('utf8', index, index + stringSize - 1);
5821
- for (var i_1 = 0; i_1 < value.length; i_1++) {
5822
- if (value.charCodeAt(i_1) === 0xfffd) {
5823
- if (!validateUtf8(buffer, index, index + stringSize - 1)) {
5824
- throw new Error('Invalid UTF-8 string in BSON document');
5825
- }
5826
- break;
5827
- }
5934
+ buffer[index + stringSize - 1] !== 0) {
5935
+ throw new BSONError('bad string length in bson');
5828
5936
  }
5937
+ value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
5829
5938
  index = index + stringSize;
5830
5939
  }
5831
5940
  else if (elementType === BSON_DATA_OID) {
@@ -5865,7 +5974,7 @@ function deserializeObject(buffer, index, options, isArray) {
5865
5974
  }
5866
5975
  else if (elementType === BSON_DATA_BOOLEAN) {
5867
5976
  if (buffer[index] !== 0 && buffer[index] !== 1)
5868
- throw new Error('illegal boolean type value');
5977
+ throw new BSONError('illegal boolean type value');
5869
5978
  value = buffer[index++] === 1;
5870
5979
  }
5871
5980
  else if (elementType === BSON_DATA_OBJECT) {
@@ -5875,13 +5984,17 @@ function deserializeObject(buffer, index, options, isArray) {
5875
5984
  (buffer[index + 2] << 16) |
5876
5985
  (buffer[index + 3] << 24);
5877
5986
  if (objectSize <= 0 || objectSize > buffer.length - index)
5878
- throw new Error('bad embedded document length in bson');
5987
+ throw new BSONError('bad embedded document length in bson');
5879
5988
  // We have a raw value
5880
5989
  if (raw) {
5881
5990
  value = buffer.slice(index, index + objectSize);
5882
5991
  }
5883
5992
  else {
5884
- value = deserializeObject(buffer, _index, options, false);
5993
+ var objectOptions = options;
5994
+ if (!globalUTFValidation) {
5995
+ objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } });
5996
+ }
5997
+ value = deserializeObject(buffer, _index, objectOptions, false);
5885
5998
  }
5886
5999
  index = index + objectSize;
5887
6000
  }
@@ -5902,12 +6015,15 @@ function deserializeObject(buffer, index, options, isArray) {
5902
6015
  }
5903
6016
  arrayOptions['raw'] = true;
5904
6017
  }
6018
+ if (!globalUTFValidation) {
6019
+ arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } });
6020
+ }
5905
6021
  value = deserializeObject(buffer, _index, arrayOptions, true);
5906
6022
  index = index + objectSize;
5907
6023
  if (buffer[index - 1] !== 0)
5908
- throw new Error('invalid array terminator byte');
6024
+ throw new BSONError('invalid array terminator byte');
5909
6025
  if (index !== stopIndex)
5910
- throw new Error('corrupted array bson');
6026
+ throw new BSONError('corrupted array bson');
5911
6027
  }
5912
6028
  else if (elementType === BSON_DATA_UNDEFINED) {
5913
6029
  value = undefined;
@@ -5963,10 +6079,10 @@ function deserializeObject(buffer, index, options, isArray) {
5963
6079
  var subType = buffer[index++];
5964
6080
  // Did we have a negative binary size, throw
5965
6081
  if (binarySize < 0)
5966
- throw new Error('Negative binary type element size found');
6082
+ throw new BSONError('Negative binary type element size found');
5967
6083
  // Is the length longer than the document
5968
6084
  if (binarySize > buffer.byteLength)
5969
- throw new Error('Binary type size larger than document size');
6085
+ throw new BSONError('Binary type size larger than document size');
5970
6086
  // Decode as raw Buffer object if options specifies it
5971
6087
  if (buffer['slice'] != null) {
5972
6088
  // If we have subtype 2 skip the 4 bytes for the size
@@ -5977,11 +6093,11 @@ function deserializeObject(buffer, index, options, isArray) {
5977
6093
  (buffer[index++] << 16) |
5978
6094
  (buffer[index++] << 24);
5979
6095
  if (binarySize < 0)
5980
- throw new Error('Negative binary type element size found for subtype 0x02');
6096
+ throw new BSONError('Negative binary type element size found for subtype 0x02');
5981
6097
  if (binarySize > totalBinarySize - 4)
5982
- throw new Error('Binary type with subtype 0x02 contains too long binary size');
6098
+ throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
5983
6099
  if (binarySize < totalBinarySize - 4)
5984
- throw new Error('Binary type with subtype 0x02 contains too short binary size');
6100
+ throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
5985
6101
  }
5986
6102
  if (promoteBuffers && promoteValues) {
5987
6103
  value = buffer.slice(index, index + binarySize);
@@ -6000,11 +6116,11 @@ function deserializeObject(buffer, index, options, isArray) {
6000
6116
  (buffer[index++] << 16) |
6001
6117
  (buffer[index++] << 24);
6002
6118
  if (binarySize < 0)
6003
- throw new Error('Negative binary type element size found for subtype 0x02');
6119
+ throw new BSONError('Negative binary type element size found for subtype 0x02');
6004
6120
  if (binarySize > totalBinarySize - 4)
6005
- throw new Error('Binary type with subtype 0x02 contains too long binary size');
6121
+ throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
6006
6122
  if (binarySize < totalBinarySize - 4)
6007
- throw new Error('Binary type with subtype 0x02 contains too short binary size');
6123
+ throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
6008
6124
  }
6009
6125
  // Copy the data
6010
6126
  for (i = 0; i < binarySize; i++) {
@@ -6029,7 +6145,7 @@ function deserializeObject(buffer, index, options, isArray) {
6029
6145
  }
6030
6146
  // If are at the end of the buffer there is a problem with the document
6031
6147
  if (i >= buffer.length)
6032
- throw new Error('Bad BSON Document: illegal CString');
6148
+ throw new BSONError('Bad BSON Document: illegal CString');
6033
6149
  // Return the C string
6034
6150
  var source = buffer.toString('utf8', index, i);
6035
6151
  // Create the regexp
@@ -6042,7 +6158,7 @@ function deserializeObject(buffer, index, options, isArray) {
6042
6158
  }
6043
6159
  // If are at the end of the buffer there is a problem with the document
6044
6160
  if (i >= buffer.length)
6045
- throw new Error('Bad BSON Document: illegal CString');
6161
+ throw new BSONError('Bad BSON Document: illegal CString');
6046
6162
  // Return the C string
6047
6163
  var regExpOptions = buffer.toString('utf8', index, i);
6048
6164
  index = i + 1;
@@ -6073,7 +6189,7 @@ function deserializeObject(buffer, index, options, isArray) {
6073
6189
  }
6074
6190
  // If are at the end of the buffer there is a problem with the document
6075
6191
  if (i >= buffer.length)
6076
- throw new Error('Bad BSON Document: illegal CString');
6192
+ throw new BSONError('Bad BSON Document: illegal CString');
6077
6193
  // Return the C string
6078
6194
  var source = buffer.toString('utf8', index, i);
6079
6195
  index = i + 1;
@@ -6085,7 +6201,7 @@ function deserializeObject(buffer, index, options, isArray) {
6085
6201
  }
6086
6202
  // If are at the end of the buffer there is a problem with the document
6087
6203
  if (i >= buffer.length)
6088
- throw new Error('Bad BSON Document: illegal CString');
6204
+ throw new BSONError('Bad BSON Document: illegal CString');
6089
6205
  // Return the C string
6090
6206
  var regExpOptions = buffer.toString('utf8', index, i);
6091
6207
  index = i + 1;
@@ -6099,9 +6215,10 @@ function deserializeObject(buffer, index, options, isArray) {
6099
6215
  (buffer[index++] << 24);
6100
6216
  if (stringSize <= 0 ||
6101
6217
  stringSize > buffer.length - index ||
6102
- buffer[index + stringSize - 1] !== 0)
6103
- throw new Error('bad string length in bson');
6104
- var symbol = buffer.toString('utf8', index, index + stringSize - 1);
6218
+ buffer[index + stringSize - 1] !== 0) {
6219
+ throw new BSONError('bad string length in bson');
6220
+ }
6221
+ var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
6105
6222
  value = promoteValues ? symbol : new BSONSymbol(symbol);
6106
6223
  index = index + stringSize;
6107
6224
  }
@@ -6129,9 +6246,10 @@ function deserializeObject(buffer, index, options, isArray) {
6129
6246
  (buffer[index++] << 24);
6130
6247
  if (stringSize <= 0 ||
6131
6248
  stringSize > buffer.length - index ||
6132
- buffer[index + stringSize - 1] !== 0)
6133
- throw new Error('bad string length in bson');
6134
- var functionString = buffer.toString('utf8', index, index + stringSize - 1);
6249
+ buffer[index + stringSize - 1] !== 0) {
6250
+ throw new BSONError('bad string length in bson');
6251
+ }
6252
+ var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
6135
6253
  // If we are evaluating the functions
6136
6254
  if (evalFunctions) {
6137
6255
  // If we have cache enabled let's look for the md5 of the function in the cache
@@ -6156,7 +6274,7 @@ function deserializeObject(buffer, index, options, isArray) {
6156
6274
  (buffer[index++] << 24);
6157
6275
  // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
6158
6276
  if (totalSize < 4 + 4 + 4 + 1) {
6159
- throw new Error('code_w_scope total size shorter minimum expected length');
6277
+ throw new BSONError('code_w_scope total size shorter minimum expected length');
6160
6278
  }
6161
6279
  // Get the code string size
6162
6280
  var stringSize = buffer[index++] |
@@ -6166,10 +6284,11 @@ function deserializeObject(buffer, index, options, isArray) {
6166
6284
  // Check if we have a valid string
6167
6285
  if (stringSize <= 0 ||
6168
6286
  stringSize > buffer.length - index ||
6169
- buffer[index + stringSize - 1] !== 0)
6170
- throw new Error('bad string length in bson');
6287
+ buffer[index + stringSize - 1] !== 0) {
6288
+ throw new BSONError('bad string length in bson');
6289
+ }
6171
6290
  // Javascript function
6172
- var functionString = buffer.toString('utf8', index, index + stringSize - 1);
6291
+ var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
6173
6292
  // Update parse index position
6174
6293
  index = index + stringSize;
6175
6294
  // Parse the element
@@ -6185,11 +6304,11 @@ function deserializeObject(buffer, index, options, isArray) {
6185
6304
  index = index + objectSize;
6186
6305
  // Check if field length is too short
6187
6306
  if (totalSize < 4 + 4 + objectSize + stringSize) {
6188
- throw new Error('code_w_scope total size is too short, truncating scope');
6307
+ throw new BSONError('code_w_scope total size is too short, truncating scope');
6189
6308
  }
6190
6309
  // Check if totalSize field is too long
6191
6310
  if (totalSize > 4 + 4 + objectSize + stringSize) {
6192
- throw new Error('code_w_scope total size is too long, clips outer document');
6311
+ throw new BSONError('code_w_scope total size is too long, clips outer document');
6193
6312
  }
6194
6313
  // If we are evaluating the functions
6195
6314
  if (evalFunctions) {
@@ -6217,10 +6336,12 @@ function deserializeObject(buffer, index, options, isArray) {
6217
6336
  if (stringSize <= 0 ||
6218
6337
  stringSize > buffer.length - index ||
6219
6338
  buffer[index + stringSize - 1] !== 0)
6220
- throw new Error('bad string length in bson');
6339
+ throw new BSONError('bad string length in bson');
6221
6340
  // Namespace
6222
- if (!validateUtf8(buffer, index, index + stringSize - 1)) {
6223
- throw new Error('Invalid UTF-8 string in BSON document');
6341
+ if (validation != null && validation.utf8) {
6342
+ if (!validateUtf8(buffer, index, index + stringSize - 1)) {
6343
+ throw new BSONError('Invalid UTF-8 string in BSON document');
6344
+ }
6224
6345
  }
6225
6346
  var namespace = buffer.toString('utf8', index, index + stringSize - 1);
6226
6347
  // Update parse index position
@@ -6235,7 +6356,7 @@ function deserializeObject(buffer, index, options, isArray) {
6235
6356
  value = new DBRef(namespace, oid);
6236
6357
  }
6237
6358
  else {
6238
- throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
6359
+ throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
6239
6360
  }
6240
6361
  if (name === '__proto__') {
6241
6362
  Object.defineProperty(object, name, {
@@ -6252,8 +6373,8 @@ function deserializeObject(buffer, index, options, isArray) {
6252
6373
  // Check if the deserialization was against a valid array/object
6253
6374
  if (size !== index - startIndex) {
6254
6375
  if (isArray)
6255
- throw new Error('corrupt array bson');
6256
- throw new Error('corrupt object bson');
6376
+ throw new BSONError('corrupt array bson');
6377
+ throw new BSONError('corrupt object bson');
6257
6378
  }
6258
6379
  // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef
6259
6380
  if (!isPossibleDBRef)
@@ -6282,6 +6403,21 @@ function isolateEval(functionString, functionCache, object) {
6282
6403
  // Set the object
6283
6404
  return functionCache[functionString].bind(object);
6284
6405
  }
6406
+ function getValidatedString(buffer, start, end, shouldValidateUtf8) {
6407
+ var value = buffer.toString('utf8', start, end);
6408
+ // if utf8 validation is on, do the check
6409
+ if (shouldValidateUtf8) {
6410
+ for (var i = 0; i < value.length; i++) {
6411
+ if (value.charCodeAt(i) === 0xfffd) {
6412
+ if (!validateUtf8(buffer, start, end)) {
6413
+ throw new BSONError('Invalid UTF-8 string in BSON document');
6414
+ }
6415
+ break;
6416
+ }
6417
+ }
6418
+ }
6419
+ return value;
6420
+ }
6285
6421
 
6286
6422
  // Copyright (c) 2008, Fair Oaks Labs, Inc.
6287
6423
  function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) {
@@ -6566,7 +6702,7 @@ function serializeObjectId(buffer, key, value, index, isArray) {
6566
6702
  buffer.set(value.id.subarray(0, 12), index);
6567
6703
  }
6568
6704
  else {
6569
- throw new TypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
6705
+ throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
6570
6706
  }
6571
6707
  // Adjust index
6572
6708
  return index + 12;
@@ -6605,7 +6741,7 @@ function serializeObject(buffer, key, value, index, checkKeys, depth, serializeF
6605
6741
  if (path === void 0) { path = []; }
6606
6742
  for (var i = 0; i < path.length; i++) {
6607
6743
  if (path[i] === value)
6608
- throw new Error('cyclic dependency detected');
6744
+ throw new BSONError('cyclic dependency detected');
6609
6745
  }
6610
6746
  // Push value to stack
6611
6747
  path.push(value);
@@ -6906,9 +7042,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
6906
7042
  var key = '' + i;
6907
7043
  var value = object[i];
6908
7044
  // Is there an override value
6909
- if (value && value.toBSON) {
6910
- if (typeof value.toBSON !== 'function')
6911
- throw new TypeError('toBSON is not a function');
7045
+ if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
6912
7046
  value = value.toBSON();
6913
7047
  }
6914
7048
  if (typeof value === 'string') {
@@ -6918,7 +7052,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
6918
7052
  index = serializeNumber(buffer, key, value, index, true);
6919
7053
  }
6920
7054
  else if (typeof value === 'bigint') {
6921
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
7055
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
6922
7056
  }
6923
7057
  else if (typeof value === 'boolean') {
6924
7058
  index = serializeBoolean(buffer, key, value, index, true);
@@ -6980,7 +7114,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
6980
7114
  index = serializeMinMax(buffer, key, value, index, true);
6981
7115
  }
6982
7116
  else if (typeof value['_bsontype'] !== 'undefined') {
6983
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7117
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
6984
7118
  }
6985
7119
  }
6986
7120
  }
@@ -7022,7 +7156,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7022
7156
  index = serializeNumber(buffer, key, value, index);
7023
7157
  }
7024
7158
  else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) {
7025
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
7159
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
7026
7160
  }
7027
7161
  else if (type === 'boolean') {
7028
7162
  index = serializeBoolean(buffer, key, value, index);
@@ -7079,26 +7213,23 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7079
7213
  index = serializeMinMax(buffer, key, value, index);
7080
7214
  }
7081
7215
  else if (typeof value['_bsontype'] !== 'undefined') {
7082
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7216
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7083
7217
  }
7084
7218
  }
7085
7219
  }
7086
7220
  else {
7087
- // Did we provide a custom serialization method
7088
- if (object.toBSON) {
7089
- if (typeof object.toBSON !== 'function')
7090
- throw new TypeError('toBSON is not a function');
7221
+ if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
7222
+ // Provided a custom serialization method
7091
7223
  object = object.toBSON();
7092
- if (object != null && typeof object !== 'object')
7093
- throw new TypeError('toBSON function did not return an object');
7224
+ if (object != null && typeof object !== 'object') {
7225
+ throw new BSONTypeError('toBSON function did not return an object');
7226
+ }
7094
7227
  }
7095
7228
  // Iterate over all the keys
7096
7229
  for (var key in object) {
7097
7230
  var value = object[key];
7098
7231
  // Is there an override value
7099
- if (value && value.toBSON) {
7100
- if (typeof value.toBSON !== 'function')
7101
- throw new TypeError('toBSON is not a function');
7232
+ if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
7102
7233
  value = value.toBSON();
7103
7234
  }
7104
7235
  // Check the type of the value
@@ -7126,7 +7257,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7126
7257
  index = serializeNumber(buffer, key, value, index);
7127
7258
  }
7128
7259
  else if (type === 'bigint') {
7129
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
7260
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
7130
7261
  }
7131
7262
  else if (type === 'boolean') {
7132
7263
  index = serializeBoolean(buffer, key, value, index);
@@ -7187,7 +7318,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7187
7318
  index = serializeMinMax(buffer, key, value, index);
7188
7319
  }
7189
7320
  else if (typeof value['_bsontype'] !== 'undefined') {
7190
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7321
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7191
7322
  }
7192
7323
  }
7193
7324
  }
@@ -7360,9 +7491,11 @@ var BSON = {
7360
7491
  serializeWithBufferAndIndex: serializeWithBufferAndIndex,
7361
7492
  deserialize: deserialize,
7362
7493
  calculateObjectSize: calculateObjectSize,
7363
- deserializeStream: deserializeStream
7494
+ deserializeStream: deserializeStream,
7495
+ BSONError: BSONError,
7496
+ BSONTypeError: BSONTypeError
7364
7497
  };
7365
7498
 
7366
7499
  export default BSON;
7367
- export { BSONRegExp, BSONSymbol, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, LongWithoutOverridesClass, bsonMap as Map, MaxKey, MinKey, ObjectId as ObjectID, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize };
7500
+ export { BSONError, BSONRegExp, BSONSymbol, BSONTypeError, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_COLUMN, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_ENCRYPTED, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, LongWithoutOverridesClass, bsonMap as Map, MaxKey, MinKey, ObjectId as ObjectID, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize };
7368
7501
  //# sourceMappingURL=bson.browser.esm.js.map