bson 4.5.1 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/HISTORY.md +572 -0
  2. package/bower.json +1 -1
  3. package/bson.d.ts +70 -13
  4. package/dist/bson.browser.esm.js +314 -177
  5. package/dist/bson.browser.esm.js.map +1 -1
  6. package/dist/bson.browser.umd.js +317 -176
  7. package/dist/bson.browser.umd.js.map +1 -1
  8. package/dist/bson.bundle.js +317 -176
  9. package/dist/bson.bundle.js.map +1 -1
  10. package/dist/bson.esm.js +314 -177
  11. package/dist/bson.esm.js.map +1 -1
  12. package/lib/binary.js +11 -9
  13. package/lib/binary.js.map +1 -1
  14. package/lib/bson.js +11 -3
  15. package/lib/bson.js.map +1 -1
  16. package/lib/code.js +0 -1
  17. package/lib/code.js.map +1 -1
  18. package/lib/constants.js +5 -1
  19. package/lib/constants.js.map +1 -1
  20. package/lib/db_ref.js +0 -1
  21. package/lib/db_ref.js.map +1 -1
  22. package/lib/decimal128.js +6 -5
  23. package/lib/decimal128.js.map +1 -1
  24. package/lib/double.js +3 -1
  25. package/lib/double.js.map +1 -1
  26. package/lib/ensure_buffer.js +3 -2
  27. package/lib/ensure_buffer.js.map +1 -1
  28. package/lib/error.js +55 -0
  29. package/lib/error.js.map +1 -0
  30. package/lib/extended_json.js +11 -5
  31. package/lib/extended_json.js.map +1 -1
  32. package/lib/int_32.js +4 -2
  33. package/lib/int_32.js.map +1 -1
  34. package/lib/objectid.js +39 -35
  35. package/lib/objectid.js.map +1 -1
  36. package/lib/parser/deserializer.js +131 -53
  37. package/lib/parser/deserializer.js.map +1 -1
  38. package/lib/parser/serializer.js +13 -12
  39. package/lib/parser/serializer.js.map +1 -1
  40. package/lib/regexp.js +9 -2
  41. package/lib/regexp.js.map +1 -1
  42. package/lib/symbol.js +0 -2
  43. package/lib/symbol.js.map +1 -1
  44. package/lib/uuid.js +4 -4
  45. package/lib/uuid.js.map +1 -1
  46. package/lib/uuid_utils.js +2 -1
  47. package/lib/uuid_utils.js.map +1 -1
  48. package/package.json +16 -3
  49. package/src/binary.ts +12 -10
  50. package/src/bson.ts +7 -1
  51. package/src/code.ts +0 -1
  52. package/src/constants.ts +6 -0
  53. package/src/db_ref.ts +0 -1
  54. package/src/decimal128.ts +6 -5
  55. package/src/double.ts +4 -1
  56. package/src/ensure_buffer.ts +3 -2
  57. package/src/error.ts +23 -0
  58. package/src/extended_json.ts +13 -5
  59. package/src/int_32.ts +5 -2
  60. package/src/objectid.ts +40 -43
  61. package/src/parser/deserializer.ts +159 -57
  62. package/src/parser/serializer.ts +13 -12
  63. package/src/regexp.ts +14 -2
  64. package/src/symbol.ts +0 -2
  65. package/src/uuid.ts +4 -4
  66. 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", {
@@ -2249,14 +2340,13 @@ var UUID = /** @class */ (function () {
2249
2340
  };
2250
2341
  /**
2251
2342
  * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
2252
- * @internal
2253
2343
  */
2254
2344
  UUID.prototype.toString = function (encoding) {
2255
2345
  return encoding ? this.id.toString(encoding) : this.toHexString();
2256
2346
  };
2257
2347
  /**
2258
- * Converts the id into its JSON string representation. A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
2259
- * @internal
2348
+ * Converts the id into its JSON string representation.
2349
+ * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
2260
2350
  */
2261
2351
  UUID.prototype.toJSON = function () {
2262
2352
  return this.toHexString();
@@ -2368,7 +2458,7 @@ var Binary = /** @class */ (function () {
2368
2458
  !ArrayBuffer.isView(buffer) &&
2369
2459
  !(buffer instanceof ArrayBuffer) &&
2370
2460
  !Array.isArray(buffer)) {
2371
- 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>');
2372
2462
  }
2373
2463
  this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT;
2374
2464
  if (buffer == null) {
@@ -2400,10 +2490,10 @@ var Binary = /** @class */ (function () {
2400
2490
  Binary.prototype.put = function (byteValue) {
2401
2491
  // If it's a string and a has more than one character throw an error
2402
2492
  if (typeof byteValue === 'string' && byteValue.length !== 1) {
2403
- throw new TypeError('only accepts single character String');
2493
+ throw new BSONTypeError('only accepts single character String');
2404
2494
  }
2405
2495
  else if (typeof byteValue !== 'number' && byteValue.length !== 1)
2406
- throw new TypeError('only accepts single character Uint8Array or Array');
2496
+ throw new BSONTypeError('only accepts single character Uint8Array or Array');
2407
2497
  // Decode the byte value once
2408
2498
  var decodedByte;
2409
2499
  if (typeof byteValue === 'string') {
@@ -2416,7 +2506,7 @@ var Binary = /** @class */ (function () {
2416
2506
  decodedByte = byteValue[0];
2417
2507
  }
2418
2508
  if (decodedByte < 0 || decodedByte > 255) {
2419
- 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');
2420
2510
  }
2421
2511
  if (this.buffer.length > this.position) {
2422
2512
  this.buffer[this.position++] = decodedByte;
@@ -2488,11 +2578,9 @@ var Binary = /** @class */ (function () {
2488
2578
  Binary.prototype.length = function () {
2489
2579
  return this.position;
2490
2580
  };
2491
- /** @internal */
2492
2581
  Binary.prototype.toJSON = function () {
2493
2582
  return this.buffer.toString('base64');
2494
2583
  };
2495
- /** @internal */
2496
2584
  Binary.prototype.toString = function (format) {
2497
2585
  return this.buffer.toString(format);
2498
2586
  };
@@ -2514,12 +2602,11 @@ var Binary = /** @class */ (function () {
2514
2602
  }
2515
2603
  };
2516
2604
  };
2517
- /** @internal */
2518
2605
  Binary.prototype.toUUID = function () {
2519
2606
  if (this.sub_type === Binary.SUBTYPE_UUID) {
2520
2607
  return new UUID(this.buffer.slice(0, this.position));
2521
2608
  }
2522
- 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.");
2523
2610
  };
2524
2611
  /** @internal */
2525
2612
  Binary.fromExtendedJSON = function (doc, options) {
@@ -2543,7 +2630,7 @@ var Binary = /** @class */ (function () {
2543
2630
  data = uuidHexStringToBuffer(doc.$uuid);
2544
2631
  }
2545
2632
  if (!data) {
2546
- throw new TypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
2633
+ throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
2547
2634
  }
2548
2635
  return new Binary(data, type);
2549
2636
  };
@@ -2574,6 +2661,10 @@ var Binary = /** @class */ (function () {
2574
2661
  Binary.SUBTYPE_UUID = 4;
2575
2662
  /** MD5 BSON type */
2576
2663
  Binary.SUBTYPE_MD5 = 5;
2664
+ /** Encrypted BSON type */
2665
+ Binary.SUBTYPE_ENCRYPTED = 6;
2666
+ /** Column BSON type */
2667
+ Binary.SUBTYPE_COLUMN = 7;
2577
2668
  /** User BSON type */
2578
2669
  Binary.SUBTYPE_USER_DEFINED = 128;
2579
2670
  return Binary;
@@ -2595,7 +2686,6 @@ var Code = /** @class */ (function () {
2595
2686
  this.code = code;
2596
2687
  this.scope = scope;
2597
2688
  }
2598
- /** @internal */
2599
2689
  Code.prototype.toJSON = function () {
2600
2690
  return { code: this.code, scope: this.scope };
2601
2691
  };
@@ -2667,7 +2757,6 @@ var DBRef = /** @class */ (function () {
2667
2757
  enumerable: false,
2668
2758
  configurable: true
2669
2759
  });
2670
- /** @internal */
2671
2760
  DBRef.prototype.toJSON = function () {
2672
2761
  var o = Object.assign({
2673
2762
  $ref: this.collection,
@@ -3694,7 +3783,7 @@ function lessThan(left, right) {
3694
3783
  return false;
3695
3784
  }
3696
3785
  function invalidErr(string, message) {
3697
- throw new TypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
3786
+ throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
3698
3787
  }
3699
3788
  /**
3700
3789
  * A class representation of the BSON Decimal128 type.
@@ -3761,7 +3850,7 @@ var Decimal128 = /** @class */ (function () {
3761
3850
  // TODO: implementing a custom parsing for this, or refactoring the regex would yield
3762
3851
  // further gains.
3763
3852
  if (representation.length >= 7000) {
3764
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
3853
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
3765
3854
  }
3766
3855
  // Results
3767
3856
  var stringMatch = representation.match(PARSE_STRING_REGEXP);
@@ -3769,7 +3858,7 @@ var Decimal128 = /** @class */ (function () {
3769
3858
  var nanMatch = representation.match(PARSE_NAN_REGEXP);
3770
3859
  // Validate the string
3771
3860
  if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
3772
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
3861
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
3773
3862
  }
3774
3863
  if (stringMatch) {
3775
3864
  // full_match = stringMatch[0]
@@ -3831,7 +3920,7 @@ var Decimal128 = /** @class */ (function () {
3831
3920
  index = index + 1;
3832
3921
  }
3833
3922
  if (sawRadix && !nDigitsRead)
3834
- throw new TypeError('' + representation + ' not a valid Decimal128 string');
3923
+ throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
3835
3924
  // Read exponent if exists
3836
3925
  if (representation[index] === 'e' || representation[index] === 'E') {
3837
3926
  // Read exponent digits
@@ -3862,7 +3951,7 @@ var Decimal128 = /** @class */ (function () {
3862
3951
  lastDigit = nDigitsStored - 1;
3863
3952
  significantDigits = nDigits;
3864
3953
  if (significantDigits !== 1) {
3865
- while (representation[firstNonZero + significantDigits - 1] === '0') {
3954
+ while (digits[firstNonZero + significantDigits - 1] === 0) {
3866
3955
  significantDigits = significantDigits - 1;
3867
3956
  }
3868
3957
  }
@@ -4287,10 +4376,12 @@ var Double = /** @class */ (function () {
4287
4376
  Double.prototype.valueOf = function () {
4288
4377
  return this.value;
4289
4378
  };
4290
- /** @internal */
4291
4379
  Double.prototype.toJSON = function () {
4292
4380
  return this.value;
4293
4381
  };
4382
+ Double.prototype.toString = function (radix) {
4383
+ return this.value.toString(radix);
4384
+ };
4294
4385
  /** @internal */
4295
4386
  Double.prototype.toExtendedJSON = function (options) {
4296
4387
  if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
@@ -4346,7 +4437,7 @@ var Int32 = /** @class */ (function () {
4346
4437
  if (value instanceof Number) {
4347
4438
  value = value.valueOf();
4348
4439
  }
4349
- this.value = +value;
4440
+ this.value = +value | 0;
4350
4441
  }
4351
4442
  /**
4352
4443
  * Access the number value.
@@ -4356,7 +4447,9 @@ var Int32 = /** @class */ (function () {
4356
4447
  Int32.prototype.valueOf = function () {
4357
4448
  return this.value;
4358
4449
  };
4359
- /** @internal */
4450
+ Int32.prototype.toString = function (radix) {
4451
+ return this.value.toString(radix);
4452
+ };
4360
4453
  Int32.prototype.toJSON = function () {
4361
4454
  return this.value;
4362
4455
  };
@@ -4450,50 +4543,57 @@ var ObjectId = /** @class */ (function () {
4450
4543
  /**
4451
4544
  * Create an ObjectId type
4452
4545
  *
4453
- * @param id - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
4546
+ * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
4454
4547
  */
4455
- function ObjectId(id) {
4548
+ function ObjectId(inputId) {
4456
4549
  if (!(this instanceof ObjectId))
4457
- return new ObjectId(id);
4458
- // Duck-typing to support ObjectId from different npm packages
4459
- if (id instanceof ObjectId) {
4460
- this[kId] = id.id;
4461
- this.__id = id.__id;
4462
- }
4463
- if (typeof id === 'object' && id && 'id' in id) {
4464
- if ('toHexString' in id && typeof id.toHexString === 'function') {
4465
- this[kId] = buffer_1.from(id.toHexString(), 'hex');
4550
+ return new ObjectId(inputId);
4551
+ // workingId is set based on type of input and whether valid id exists for the input
4552
+ var workingId;
4553
+ if (typeof inputId === 'object' && inputId && 'id' in inputId) {
4554
+ if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
4555
+ throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer');
4556
+ }
4557
+ if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
4558
+ workingId = buffer_1.from(inputId.toHexString(), 'hex');
4466
4559
  }
4467
4560
  else {
4468
- this[kId] = typeof id.id === 'string' ? buffer_1.from(id.id) : id.id;
4561
+ workingId = inputId.id;
4469
4562
  }
4470
4563
  }
4471
- // The most common use case (blank id, new objectId instance)
4472
- if (id == null || typeof id === 'number') {
4564
+ else {
4565
+ workingId = inputId;
4566
+ }
4567
+ // the following cases use workingId to construct an ObjectId
4568
+ if (workingId == null || typeof workingId === 'number') {
4569
+ // The most common use case (blank id, new objectId instance)
4473
4570
  // Generate a new id
4474
- this[kId] = ObjectId.generate(typeof id === 'number' ? id : undefined);
4475
- // If we are caching the hex string
4476
- if (ObjectId.cacheHexString) {
4477
- this.__id = this.id.toString('hex');
4478
- }
4571
+ this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
4479
4572
  }
4480
- if (ArrayBuffer.isView(id) && id.byteLength === 12) {
4481
- this[kId] = ensureBuffer(id);
4573
+ else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
4574
+ this[kId] = ensureBuffer(workingId);
4482
4575
  }
4483
- if (typeof id === 'string') {
4484
- if (id.length === 12) {
4485
- var bytes = buffer_1.from(id);
4576
+ else if (typeof workingId === 'string') {
4577
+ if (workingId.length === 12) {
4578
+ var bytes = buffer_1.from(workingId);
4486
4579
  if (bytes.byteLength === 12) {
4487
4580
  this[kId] = bytes;
4488
4581
  }
4582
+ else {
4583
+ throw new BSONTypeError('Argument passed in must be a string of 12 bytes');
4584
+ }
4489
4585
  }
4490
- else if (id.length === 24 && checkForHexRegExp.test(id)) {
4491
- this[kId] = buffer_1.from(id, 'hex');
4586
+ else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
4587
+ this[kId] = buffer_1.from(workingId, 'hex');
4492
4588
  }
4493
4589
  else {
4494
- throw new TypeError('Argument passed in must be a Buffer or string of 12 bytes or a string of 24 hex characters');
4590
+ throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters');
4495
4591
  }
4496
4592
  }
4593
+ else {
4594
+ throw new BSONTypeError('Argument passed in does not match the accepted types');
4595
+ }
4596
+ // If we are caching the hex string
4497
4597
  if (ObjectId.cacheHexString) {
4498
4598
  this.__id = this.id.toString('hex');
4499
4599
  }
@@ -4557,7 +4657,7 @@ var ObjectId = /** @class */ (function () {
4557
4657
  */
4558
4658
  ObjectId.generate = function (time) {
4559
4659
  if ('number' !== typeof time) {
4560
- time = ~~(Date.now() / 1000);
4660
+ time = Math.floor(Date.now() / 1000);
4561
4661
  }
4562
4662
  var inc = ObjectId.getInc();
4563
4663
  var buffer = buffer_1.alloc(12);
@@ -4583,7 +4683,6 @@ var ObjectId = /** @class */ (function () {
4583
4683
  * Converts the id into a 24 character hex string for printing
4584
4684
  *
4585
4685
  * @param format - The Buffer toString format parameter.
4586
- * @internal
4587
4686
  */
4588
4687
  ObjectId.prototype.toString = function (format) {
4589
4688
  // Is the id a buffer then use the buffer toString method to return the format
@@ -4591,10 +4690,7 @@ var ObjectId = /** @class */ (function () {
4591
4690
  return this.id.toString(format);
4592
4691
  return this.toHexString();
4593
4692
  };
4594
- /**
4595
- * Converts to its JSON the 24 character hex string representation.
4596
- * @internal
4597
- */
4693
+ /** Converts to its JSON the 24 character hex string representation. */
4598
4694
  ObjectId.prototype.toJSON = function () {
4599
4695
  return this.toHexString();
4600
4696
  };
@@ -4660,7 +4756,7 @@ var ObjectId = /** @class */ (function () {
4660
4756
  ObjectId.createFromHexString = function (hexString) {
4661
4757
  // Throw an error if it's not a valid setup
4662
4758
  if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
4663
- throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
4759
+ throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
4664
4760
  }
4665
4761
  return new ObjectId(buffer_1.from(hexString, 'hex'));
4666
4762
  };
@@ -4716,7 +4812,7 @@ var ObjectId = /** @class */ (function () {
4716
4812
  return "new ObjectId(\"" + this.toHexString() + "\")";
4717
4813
  };
4718
4814
  /** @internal */
4719
- ObjectId.index = ~~(Math.random() * 0xffffff);
4815
+ ObjectId.index = Math.floor(Math.random() * 0xffffff);
4720
4816
  return ObjectId;
4721
4817
  }());
4722
4818
  // Deprecated methods
@@ -4751,6 +4847,12 @@ var BSONRegExp = /** @class */ (function () {
4751
4847
  return new BSONRegExp(pattern, options);
4752
4848
  this.pattern = pattern;
4753
4849
  this.options = alphabetize(options !== null && options !== void 0 ? options : '');
4850
+ if (this.pattern.indexOf('\x00') !== -1) {
4851
+ throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern));
4852
+ }
4853
+ if (this.options.indexOf('\x00') !== -1) {
4854
+ throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options));
4855
+ }
4754
4856
  // Validate options
4755
4857
  for (var i = 0; i < this.options.length; i++) {
4756
4858
  if (!(this.options[i] === 'i' ||
@@ -4759,7 +4861,7 @@ var BSONRegExp = /** @class */ (function () {
4759
4861
  this.options[i] === 'l' ||
4760
4862
  this.options[i] === 's' ||
4761
4863
  this.options[i] === 'u')) {
4762
- throw new Error("The regular expression option [" + this.options[i] + "] is not supported");
4864
+ throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported");
4763
4865
  }
4764
4866
  }
4765
4867
  }
@@ -4790,7 +4892,7 @@ var BSONRegExp = /** @class */ (function () {
4790
4892
  if ('$regularExpression' in doc) {
4791
4893
  return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
4792
4894
  }
4793
- throw new TypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
4895
+ throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
4794
4896
  };
4795
4897
  return BSONRegExp;
4796
4898
  }());
@@ -4813,7 +4915,6 @@ var BSONSymbol = /** @class */ (function () {
4813
4915
  BSONSymbol.prototype.valueOf = function () {
4814
4916
  return this.value;
4815
4917
  };
4816
- /** @internal */
4817
4918
  BSONSymbol.prototype.toString = function () {
4818
4919
  return this.value;
4819
4920
  };
@@ -4821,7 +4922,6 @@ var BSONSymbol = /** @class */ (function () {
4821
4922
  BSONSymbol.prototype.inspect = function () {
4822
4923
  return "new BSONSymbol(\"" + this.value + "\")";
4823
4924
  };
4824
- /** @internal */
4825
4925
  BSONSymbol.prototype.toJSON = function () {
4826
4926
  return this.value;
4827
4927
  };
@@ -4841,46 +4941,6 @@ var BSONSymbol = /** @class */ (function () {
4841
4941
  }());
4842
4942
  Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' });
4843
4943
 
4844
- /*! *****************************************************************************
4845
- Copyright (c) Microsoft Corporation.
4846
-
4847
- Permission to use, copy, modify, and/or distribute this software for any
4848
- purpose with or without fee is hereby granted.
4849
-
4850
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
4851
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
4852
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
4853
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
4854
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4855
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4856
- PERFORMANCE OF THIS SOFTWARE.
4857
- ***************************************************************************** */
4858
-
4859
- /* global Reflect, Promise */
4860
- var _extendStatics = function extendStatics(d, b) {
4861
- _extendStatics = Object.setPrototypeOf || {
4862
- __proto__: []
4863
- } instanceof Array && function (d, b) {
4864
- d.__proto__ = b;
4865
- } || function (d, b) {
4866
- for (var p in b) {
4867
- if (b.hasOwnProperty(p)) d[p] = b[p];
4868
- }
4869
- };
4870
-
4871
- return _extendStatics(d, b);
4872
- };
4873
-
4874
- function __extends(d, b) {
4875
- _extendStatics(d, b);
4876
-
4877
- function __() {
4878
- this.constructor = d;
4879
- }
4880
-
4881
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4882
- }
4883
-
4884
4944
  /** @public */
4885
4945
  var LongWithoutOverridesClass = Long;
4886
4946
  /** @public */
@@ -5095,7 +5155,7 @@ function serializeValue(value, options) {
5095
5155
  var current = props[props.length - 1];
5096
5156
  var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
5097
5157
  var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
5098
- throw new TypeError('Converting circular structure to EJSON:\n' +
5158
+ throw new BSONTypeError('Converting circular structure to EJSON:\n' +
5099
5159
  (" " + leadingPart + alreadySeen + circularPart + current + "\n") +
5100
5160
  (" " + leadingSpace + "\\" + dashes + "/"));
5101
5161
  }
@@ -5168,7 +5228,7 @@ var BSON_TYPE_MAPPINGS = {
5168
5228
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
5169
5229
  function serializeDocument(doc, options) {
5170
5230
  if (doc == null || typeof doc !== 'object')
5171
- throw new Error('not an object instance');
5231
+ throw new BSONError('not an object instance');
5172
5232
  var bsontype = doc._bsontype;
5173
5233
  if (typeof bsontype === 'undefined') {
5174
5234
  // It's a regular object. Recursively serialize its property values.
@@ -5195,7 +5255,7 @@ function serializeDocument(doc, options) {
5195
5255
  // Copy the object into this library's version of that type.
5196
5256
  var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
5197
5257
  if (!mapper) {
5198
- throw new TypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
5258
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
5199
5259
  }
5200
5260
  outDoc = mapper(outDoc);
5201
5261
  }
@@ -5209,7 +5269,7 @@ function serializeDocument(doc, options) {
5209
5269
  return outDoc.toExtendedJSON(options);
5210
5270
  }
5211
5271
  else {
5212
- throw new Error('_bsontype must be a string, but was: ' + typeof bsontype);
5272
+ throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
5213
5273
  }
5214
5274
  }
5215
5275
  /**
@@ -5244,7 +5304,12 @@ var EJSON;
5244
5304
  finalOptions.strict = !finalOptions.relaxed;
5245
5305
  if (typeof finalOptions.strict === 'boolean')
5246
5306
  finalOptions.relaxed = !finalOptions.strict;
5247
- return JSON.parse(text, function (_key, value) { return deserializeValue(value, finalOptions); });
5307
+ return JSON.parse(text, function (key, value) {
5308
+ if (key.indexOf('\x00') !== -1) {
5309
+ throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key));
5310
+ }
5311
+ return deserializeValue(value, finalOptions);
5312
+ });
5248
5313
  }
5249
5314
  EJSON.parse = parse;
5250
5315
  /**
@@ -5502,6 +5567,10 @@ var BSON_BINARY_SUBTYPE_UUID = 3;
5502
5567
  var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
5503
5568
  /** Binary MD5 Type @internal */
5504
5569
  var BSON_BINARY_SUBTYPE_MD5 = 5;
5570
+ /** Encrypted BSON type @internal */
5571
+ var BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
5572
+ /** Column BSON type @internal */
5573
+ var BSON_BINARY_SUBTYPE_COLUMN = 7;
5505
5574
  /** Binary User Defined Type @internal */
5506
5575
  var BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
5507
5576
 
@@ -5746,20 +5815,20 @@ function deserialize$1(buffer, options, isArray) {
5746
5815
  (buffer[index + 2] << 16) |
5747
5816
  (buffer[index + 3] << 24);
5748
5817
  if (size < 5) {
5749
- throw new Error("bson size must be >= 5, is " + size);
5818
+ throw new BSONError("bson size must be >= 5, is " + size);
5750
5819
  }
5751
5820
  if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
5752
- throw new Error("buffer length " + buffer.length + " must be >= bson size " + size);
5821
+ throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size);
5753
5822
  }
5754
5823
  if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
5755
- throw new Error("buffer length " + buffer.length + " must === bson size " + size);
5824
+ throw new BSONError("buffer length " + buffer.length + " must === bson size " + size);
5756
5825
  }
5757
5826
  if (size + index > buffer.byteLength) {
5758
- throw new Error("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
5827
+ throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
5759
5828
  }
5760
5829
  // Illegal end value
5761
5830
  if (buffer[index + size - 1] !== 0) {
5762
- throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
5831
+ throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
5763
5832
  }
5764
5833
  // Start deserializtion
5765
5834
  return deserializeObject(buffer, index, options, isArray);
@@ -5778,16 +5847,53 @@ function deserializeObject(buffer, index, options, isArray) {
5778
5847
  var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
5779
5848
  var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
5780
5849
  var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
5850
+ // Ensures default validation option if none given
5851
+ var validation = options.validation == null ? { utf8: true } : options.validation;
5852
+ // Shows if global utf-8 validation is enabled or disabled
5853
+ var globalUTFValidation = true;
5854
+ // Reflects utf-8 validation setting regardless of global or specific key validation
5855
+ var validationSetting;
5856
+ // Set of keys either to enable or disable validation on
5857
+ var utf8KeysSet = new Set();
5858
+ // Check for boolean uniformity and empty validation option
5859
+ var utf8ValidatedKeys = validation.utf8;
5860
+ if (typeof utf8ValidatedKeys === 'boolean') {
5861
+ validationSetting = utf8ValidatedKeys;
5862
+ }
5863
+ else {
5864
+ globalUTFValidation = false;
5865
+ var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
5866
+ return utf8ValidatedKeys[key];
5867
+ });
5868
+ if (utf8ValidationValues.length === 0) {
5869
+ throw new BSONError('UTF-8 validation setting cannot be empty');
5870
+ }
5871
+ if (typeof utf8ValidationValues[0] !== 'boolean') {
5872
+ throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
5873
+ }
5874
+ validationSetting = utf8ValidationValues[0];
5875
+ // Ensures boolean uniformity in utf-8 validation (all true or all false)
5876
+ if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) {
5877
+ throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
5878
+ }
5879
+ }
5880
+ // Add keys to set that will either be validated or not based on validationSetting
5881
+ if (!globalUTFValidation) {
5882
+ for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) {
5883
+ var key = _a[_i];
5884
+ utf8KeysSet.add(key);
5885
+ }
5886
+ }
5781
5887
  // Set the start index
5782
5888
  var startIndex = index;
5783
5889
  // Validate that we have at least 4 bytes of buffer
5784
5890
  if (buffer.length < 5)
5785
- throw new Error('corrupt bson message < 5 bytes long');
5891
+ throw new BSONError('corrupt bson message < 5 bytes long');
5786
5892
  // Read the document size
5787
5893
  var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
5788
5894
  // Ensure buffer is valid size
5789
5895
  if (size < 5 || size > buffer.length)
5790
- throw new Error('corrupt bson message');
5896
+ throw new BSONError('corrupt bson message');
5791
5897
  // Create holding object
5792
5898
  var object = isArray ? [] : {};
5793
5899
  // Used for arrays to skip having to perform utf8 decoding
@@ -5809,8 +5915,17 @@ function deserializeObject(buffer, index, options, isArray) {
5809
5915
  }
5810
5916
  // If are at the end of the buffer there is a problem with the document
5811
5917
  if (i >= buffer.byteLength)
5812
- throw new Error('Bad BSON Document: illegal CString');
5918
+ throw new BSONError('Bad BSON Document: illegal CString');
5919
+ // Represents the key
5813
5920
  var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);
5921
+ // shouldValidateKey is true if the key should be validated, false otherwise
5922
+ var shouldValidateKey = true;
5923
+ if (globalUTFValidation || utf8KeysSet.has(name)) {
5924
+ shouldValidateKey = validationSetting;
5925
+ }
5926
+ else {
5927
+ shouldValidateKey = !validationSetting;
5928
+ }
5814
5929
  if (isPossibleDBRef !== false && name[0] === '$') {
5815
5930
  isPossibleDBRef = allowedDBRefKeys.test(name);
5816
5931
  }
@@ -5823,17 +5938,10 @@ function deserializeObject(buffer, index, options, isArray) {
5823
5938
  (buffer[index++] << 24);
5824
5939
  if (stringSize <= 0 ||
5825
5940
  stringSize > buffer.length - index ||
5826
- buffer[index + stringSize - 1] !== 0)
5827
- throw new Error('bad string length in bson');
5828
- value = buffer.toString('utf8', index, index + stringSize - 1);
5829
- for (var i_1 = 0; i_1 < value.length; i_1++) {
5830
- if (value.charCodeAt(i_1) === 0xfffd) {
5831
- if (!validateUtf8(buffer, index, index + stringSize - 1)) {
5832
- throw new Error('Invalid UTF-8 string in BSON document');
5833
- }
5834
- break;
5835
- }
5941
+ buffer[index + stringSize - 1] !== 0) {
5942
+ throw new BSONError('bad string length in bson');
5836
5943
  }
5944
+ value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
5837
5945
  index = index + stringSize;
5838
5946
  }
5839
5947
  else if (elementType === BSON_DATA_OID) {
@@ -5873,7 +5981,7 @@ function deserializeObject(buffer, index, options, isArray) {
5873
5981
  }
5874
5982
  else if (elementType === BSON_DATA_BOOLEAN) {
5875
5983
  if (buffer[index] !== 0 && buffer[index] !== 1)
5876
- throw new Error('illegal boolean type value');
5984
+ throw new BSONError('illegal boolean type value');
5877
5985
  value = buffer[index++] === 1;
5878
5986
  }
5879
5987
  else if (elementType === BSON_DATA_OBJECT) {
@@ -5883,13 +5991,17 @@ function deserializeObject(buffer, index, options, isArray) {
5883
5991
  (buffer[index + 2] << 16) |
5884
5992
  (buffer[index + 3] << 24);
5885
5993
  if (objectSize <= 0 || objectSize > buffer.length - index)
5886
- throw new Error('bad embedded document length in bson');
5994
+ throw new BSONError('bad embedded document length in bson');
5887
5995
  // We have a raw value
5888
5996
  if (raw) {
5889
5997
  value = buffer.slice(index, index + objectSize);
5890
5998
  }
5891
5999
  else {
5892
- value = deserializeObject(buffer, _index, options, false);
6000
+ var objectOptions = options;
6001
+ if (!globalUTFValidation) {
6002
+ objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } });
6003
+ }
6004
+ value = deserializeObject(buffer, _index, objectOptions, false);
5893
6005
  }
5894
6006
  index = index + objectSize;
5895
6007
  }
@@ -5910,12 +6022,15 @@ function deserializeObject(buffer, index, options, isArray) {
5910
6022
  }
5911
6023
  arrayOptions['raw'] = true;
5912
6024
  }
6025
+ if (!globalUTFValidation) {
6026
+ arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } });
6027
+ }
5913
6028
  value = deserializeObject(buffer, _index, arrayOptions, true);
5914
6029
  index = index + objectSize;
5915
6030
  if (buffer[index - 1] !== 0)
5916
- throw new Error('invalid array terminator byte');
6031
+ throw new BSONError('invalid array terminator byte');
5917
6032
  if (index !== stopIndex)
5918
- throw new Error('corrupted array bson');
6033
+ throw new BSONError('corrupted array bson');
5919
6034
  }
5920
6035
  else if (elementType === BSON_DATA_UNDEFINED) {
5921
6036
  value = undefined;
@@ -5971,10 +6086,10 @@ function deserializeObject(buffer, index, options, isArray) {
5971
6086
  var subType = buffer[index++];
5972
6087
  // Did we have a negative binary size, throw
5973
6088
  if (binarySize < 0)
5974
- throw new Error('Negative binary type element size found');
6089
+ throw new BSONError('Negative binary type element size found');
5975
6090
  // Is the length longer than the document
5976
6091
  if (binarySize > buffer.byteLength)
5977
- throw new Error('Binary type size larger than document size');
6092
+ throw new BSONError('Binary type size larger than document size');
5978
6093
  // Decode as raw Buffer object if options specifies it
5979
6094
  if (buffer['slice'] != null) {
5980
6095
  // If we have subtype 2 skip the 4 bytes for the size
@@ -5985,11 +6100,11 @@ function deserializeObject(buffer, index, options, isArray) {
5985
6100
  (buffer[index++] << 16) |
5986
6101
  (buffer[index++] << 24);
5987
6102
  if (binarySize < 0)
5988
- throw new Error('Negative binary type element size found for subtype 0x02');
6103
+ throw new BSONError('Negative binary type element size found for subtype 0x02');
5989
6104
  if (binarySize > totalBinarySize - 4)
5990
- throw new Error('Binary type with subtype 0x02 contains too long binary size');
6105
+ throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
5991
6106
  if (binarySize < totalBinarySize - 4)
5992
- throw new Error('Binary type with subtype 0x02 contains too short binary size');
6107
+ throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
5993
6108
  }
5994
6109
  if (promoteBuffers && promoteValues) {
5995
6110
  value = buffer.slice(index, index + binarySize);
@@ -6008,11 +6123,11 @@ function deserializeObject(buffer, index, options, isArray) {
6008
6123
  (buffer[index++] << 16) |
6009
6124
  (buffer[index++] << 24);
6010
6125
  if (binarySize < 0)
6011
- throw new Error('Negative binary type element size found for subtype 0x02');
6126
+ throw new BSONError('Negative binary type element size found for subtype 0x02');
6012
6127
  if (binarySize > totalBinarySize - 4)
6013
- throw new Error('Binary type with subtype 0x02 contains too long binary size');
6128
+ throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
6014
6129
  if (binarySize < totalBinarySize - 4)
6015
- throw new Error('Binary type with subtype 0x02 contains too short binary size');
6130
+ throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
6016
6131
  }
6017
6132
  // Copy the data
6018
6133
  for (i = 0; i < binarySize; i++) {
@@ -6037,7 +6152,7 @@ function deserializeObject(buffer, index, options, isArray) {
6037
6152
  }
6038
6153
  // If are at the end of the buffer there is a problem with the document
6039
6154
  if (i >= buffer.length)
6040
- throw new Error('Bad BSON Document: illegal CString');
6155
+ throw new BSONError('Bad BSON Document: illegal CString');
6041
6156
  // Return the C string
6042
6157
  var source = buffer.toString('utf8', index, i);
6043
6158
  // Create the regexp
@@ -6050,7 +6165,7 @@ function deserializeObject(buffer, index, options, isArray) {
6050
6165
  }
6051
6166
  // If are at the end of the buffer there is a problem with the document
6052
6167
  if (i >= buffer.length)
6053
- throw new Error('Bad BSON Document: illegal CString');
6168
+ throw new BSONError('Bad BSON Document: illegal CString');
6054
6169
  // Return the C string
6055
6170
  var regExpOptions = buffer.toString('utf8', index, i);
6056
6171
  index = i + 1;
@@ -6081,7 +6196,7 @@ function deserializeObject(buffer, index, options, isArray) {
6081
6196
  }
6082
6197
  // If are at the end of the buffer there is a problem with the document
6083
6198
  if (i >= buffer.length)
6084
- throw new Error('Bad BSON Document: illegal CString');
6199
+ throw new BSONError('Bad BSON Document: illegal CString');
6085
6200
  // Return the C string
6086
6201
  var source = buffer.toString('utf8', index, i);
6087
6202
  index = i + 1;
@@ -6093,7 +6208,7 @@ function deserializeObject(buffer, index, options, isArray) {
6093
6208
  }
6094
6209
  // If are at the end of the buffer there is a problem with the document
6095
6210
  if (i >= buffer.length)
6096
- throw new Error('Bad BSON Document: illegal CString');
6211
+ throw new BSONError('Bad BSON Document: illegal CString');
6097
6212
  // Return the C string
6098
6213
  var regExpOptions = buffer.toString('utf8', index, i);
6099
6214
  index = i + 1;
@@ -6107,9 +6222,10 @@ function deserializeObject(buffer, index, options, isArray) {
6107
6222
  (buffer[index++] << 24);
6108
6223
  if (stringSize <= 0 ||
6109
6224
  stringSize > buffer.length - index ||
6110
- buffer[index + stringSize - 1] !== 0)
6111
- throw new Error('bad string length in bson');
6112
- var symbol = buffer.toString('utf8', index, index + stringSize - 1);
6225
+ buffer[index + stringSize - 1] !== 0) {
6226
+ throw new BSONError('bad string length in bson');
6227
+ }
6228
+ var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
6113
6229
  value = promoteValues ? symbol : new BSONSymbol(symbol);
6114
6230
  index = index + stringSize;
6115
6231
  }
@@ -6137,9 +6253,10 @@ function deserializeObject(buffer, index, options, isArray) {
6137
6253
  (buffer[index++] << 24);
6138
6254
  if (stringSize <= 0 ||
6139
6255
  stringSize > buffer.length - index ||
6140
- buffer[index + stringSize - 1] !== 0)
6141
- throw new Error('bad string length in bson');
6142
- var functionString = buffer.toString('utf8', index, index + stringSize - 1);
6256
+ buffer[index + stringSize - 1] !== 0) {
6257
+ throw new BSONError('bad string length in bson');
6258
+ }
6259
+ var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
6143
6260
  // If we are evaluating the functions
6144
6261
  if (evalFunctions) {
6145
6262
  // If we have cache enabled let's look for the md5 of the function in the cache
@@ -6164,7 +6281,7 @@ function deserializeObject(buffer, index, options, isArray) {
6164
6281
  (buffer[index++] << 24);
6165
6282
  // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
6166
6283
  if (totalSize < 4 + 4 + 4 + 1) {
6167
- throw new Error('code_w_scope total size shorter minimum expected length');
6284
+ throw new BSONError('code_w_scope total size shorter minimum expected length');
6168
6285
  }
6169
6286
  // Get the code string size
6170
6287
  var stringSize = buffer[index++] |
@@ -6174,10 +6291,11 @@ function deserializeObject(buffer, index, options, isArray) {
6174
6291
  // Check if we have a valid string
6175
6292
  if (stringSize <= 0 ||
6176
6293
  stringSize > buffer.length - index ||
6177
- buffer[index + stringSize - 1] !== 0)
6178
- throw new Error('bad string length in bson');
6294
+ buffer[index + stringSize - 1] !== 0) {
6295
+ throw new BSONError('bad string length in bson');
6296
+ }
6179
6297
  // Javascript function
6180
- var functionString = buffer.toString('utf8', index, index + stringSize - 1);
6298
+ var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
6181
6299
  // Update parse index position
6182
6300
  index = index + stringSize;
6183
6301
  // Parse the element
@@ -6193,11 +6311,11 @@ function deserializeObject(buffer, index, options, isArray) {
6193
6311
  index = index + objectSize;
6194
6312
  // Check if field length is too short
6195
6313
  if (totalSize < 4 + 4 + objectSize + stringSize) {
6196
- throw new Error('code_w_scope total size is too short, truncating scope');
6314
+ throw new BSONError('code_w_scope total size is too short, truncating scope');
6197
6315
  }
6198
6316
  // Check if totalSize field is too long
6199
6317
  if (totalSize > 4 + 4 + objectSize + stringSize) {
6200
- throw new Error('code_w_scope total size is too long, clips outer document');
6318
+ throw new BSONError('code_w_scope total size is too long, clips outer document');
6201
6319
  }
6202
6320
  // If we are evaluating the functions
6203
6321
  if (evalFunctions) {
@@ -6225,10 +6343,12 @@ function deserializeObject(buffer, index, options, isArray) {
6225
6343
  if (stringSize <= 0 ||
6226
6344
  stringSize > buffer.length - index ||
6227
6345
  buffer[index + stringSize - 1] !== 0)
6228
- throw new Error('bad string length in bson');
6346
+ throw new BSONError('bad string length in bson');
6229
6347
  // Namespace
6230
- if (!validateUtf8(buffer, index, index + stringSize - 1)) {
6231
- throw new Error('Invalid UTF-8 string in BSON document');
6348
+ if (validation != null && validation.utf8) {
6349
+ if (!validateUtf8(buffer, index, index + stringSize - 1)) {
6350
+ throw new BSONError('Invalid UTF-8 string in BSON document');
6351
+ }
6232
6352
  }
6233
6353
  var namespace = buffer.toString('utf8', index, index + stringSize - 1);
6234
6354
  // Update parse index position
@@ -6243,7 +6363,7 @@ function deserializeObject(buffer, index, options, isArray) {
6243
6363
  value = new DBRef(namespace, oid);
6244
6364
  }
6245
6365
  else {
6246
- throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
6366
+ throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
6247
6367
  }
6248
6368
  if (name === '__proto__') {
6249
6369
  Object.defineProperty(object, name, {
@@ -6260,8 +6380,8 @@ function deserializeObject(buffer, index, options, isArray) {
6260
6380
  // Check if the deserialization was against a valid array/object
6261
6381
  if (size !== index - startIndex) {
6262
6382
  if (isArray)
6263
- throw new Error('corrupt array bson');
6264
- throw new Error('corrupt object bson');
6383
+ throw new BSONError('corrupt array bson');
6384
+ throw new BSONError('corrupt object bson');
6265
6385
  }
6266
6386
  // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef
6267
6387
  if (!isPossibleDBRef)
@@ -6290,6 +6410,21 @@ function isolateEval(functionString, functionCache, object) {
6290
6410
  // Set the object
6291
6411
  return functionCache[functionString].bind(object);
6292
6412
  }
6413
+ function getValidatedString(buffer, start, end, shouldValidateUtf8) {
6414
+ var value = buffer.toString('utf8', start, end);
6415
+ // if utf8 validation is on, do the check
6416
+ if (shouldValidateUtf8) {
6417
+ for (var i = 0; i < value.length; i++) {
6418
+ if (value.charCodeAt(i) === 0xfffd) {
6419
+ if (!validateUtf8(buffer, start, end)) {
6420
+ throw new BSONError('Invalid UTF-8 string in BSON document');
6421
+ }
6422
+ break;
6423
+ }
6424
+ }
6425
+ }
6426
+ return value;
6427
+ }
6293
6428
 
6294
6429
  // Copyright (c) 2008, Fair Oaks Labs, Inc.
6295
6430
  function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) {
@@ -6574,7 +6709,7 @@ function serializeObjectId(buffer, key, value, index, isArray) {
6574
6709
  buffer.set(value.id.subarray(0, 12), index);
6575
6710
  }
6576
6711
  else {
6577
- throw new TypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
6712
+ throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
6578
6713
  }
6579
6714
  // Adjust index
6580
6715
  return index + 12;
@@ -6613,7 +6748,7 @@ function serializeObject(buffer, key, value, index, checkKeys, depth, serializeF
6613
6748
  if (path === void 0) { path = []; }
6614
6749
  for (var i = 0; i < path.length; i++) {
6615
6750
  if (path[i] === value)
6616
- throw new Error('cyclic dependency detected');
6751
+ throw new BSONError('cyclic dependency detected');
6617
6752
  }
6618
6753
  // Push value to stack
6619
6754
  path.push(value);
@@ -6916,7 +7051,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
6916
7051
  // Is there an override value
6917
7052
  if (value && value.toBSON) {
6918
7053
  if (typeof value.toBSON !== 'function')
6919
- throw new TypeError('toBSON is not a function');
7054
+ throw new BSONTypeError('toBSON is not a function');
6920
7055
  value = value.toBSON();
6921
7056
  }
6922
7057
  if (typeof value === 'string') {
@@ -6926,7 +7061,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
6926
7061
  index = serializeNumber(buffer, key, value, index, true);
6927
7062
  }
6928
7063
  else if (typeof value === 'bigint') {
6929
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
7064
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
6930
7065
  }
6931
7066
  else if (typeof value === 'boolean') {
6932
7067
  index = serializeBoolean(buffer, key, value, index, true);
@@ -6988,7 +7123,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
6988
7123
  index = serializeMinMax(buffer, key, value, index, true);
6989
7124
  }
6990
7125
  else if (typeof value['_bsontype'] !== 'undefined') {
6991
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7126
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
6992
7127
  }
6993
7128
  }
6994
7129
  }
@@ -7030,7 +7165,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7030
7165
  index = serializeNumber(buffer, key, value, index);
7031
7166
  }
7032
7167
  else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) {
7033
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
7168
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
7034
7169
  }
7035
7170
  else if (type === 'boolean') {
7036
7171
  index = serializeBoolean(buffer, key, value, index);
@@ -7087,7 +7222,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7087
7222
  index = serializeMinMax(buffer, key, value, index);
7088
7223
  }
7089
7224
  else if (typeof value['_bsontype'] !== 'undefined') {
7090
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7225
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7091
7226
  }
7092
7227
  }
7093
7228
  }
@@ -7095,10 +7230,10 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7095
7230
  // Did we provide a custom serialization method
7096
7231
  if (object.toBSON) {
7097
7232
  if (typeof object.toBSON !== 'function')
7098
- throw new TypeError('toBSON is not a function');
7233
+ throw new BSONTypeError('toBSON is not a function');
7099
7234
  object = object.toBSON();
7100
7235
  if (object != null && typeof object !== 'object')
7101
- throw new TypeError('toBSON function did not return an object');
7236
+ throw new BSONTypeError('toBSON function did not return an object');
7102
7237
  }
7103
7238
  // Iterate over all the keys
7104
7239
  for (var key in object) {
@@ -7106,7 +7241,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7106
7241
  // Is there an override value
7107
7242
  if (value && value.toBSON) {
7108
7243
  if (typeof value.toBSON !== 'function')
7109
- throw new TypeError('toBSON is not a function');
7244
+ throw new BSONTypeError('toBSON is not a function');
7110
7245
  value = value.toBSON();
7111
7246
  }
7112
7247
  // Check the type of the value
@@ -7134,7 +7269,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7134
7269
  index = serializeNumber(buffer, key, value, index);
7135
7270
  }
7136
7271
  else if (type === 'bigint') {
7137
- throw new TypeError('Unsupported type BigInt, please use Decimal128');
7272
+ throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
7138
7273
  }
7139
7274
  else if (type === 'boolean') {
7140
7275
  index = serializeBoolean(buffer, key, value, index);
@@ -7195,7 +7330,7 @@ function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializ
7195
7330
  index = serializeMinMax(buffer, key, value, index);
7196
7331
  }
7197
7332
  else if (typeof value['_bsontype'] !== 'undefined') {
7198
- throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7333
+ throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
7199
7334
  }
7200
7335
  }
7201
7336
  }
@@ -7368,9 +7503,11 @@ var BSON = {
7368
7503
  serializeWithBufferAndIndex: serializeWithBufferAndIndex,
7369
7504
  deserialize: deserialize,
7370
7505
  calculateObjectSize: calculateObjectSize,
7371
- deserializeStream: deserializeStream
7506
+ deserializeStream: deserializeStream,
7507
+ BSONError: BSONError,
7508
+ BSONTypeError: BSONTypeError
7372
7509
  };
7373
7510
 
7374
7511
  export default BSON;
7375
- 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 };
7512
+ 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 };
7376
7513
  //# sourceMappingURL=bson.browser.esm.js.map