bson 4.7.0 → 5.0.0-alpha.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 (98) hide show
  1. package/bson.d.ts +207 -259
  2. package/lib/bson.bundle.js +4033 -0
  3. package/lib/bson.bundle.js.map +1 -0
  4. package/lib/bson.cjs +4028 -0
  5. package/lib/bson.cjs.map +1 -0
  6. package/lib/bson.mjs +4002 -0
  7. package/lib/bson.mjs.map +1 -0
  8. package/package.json +49 -62
  9. package/src/binary.ts +63 -52
  10. package/src/bson.ts +27 -108
  11. package/src/code.ts +24 -14
  12. package/src/constants.ts +28 -0
  13. package/src/db_ref.ts +13 -8
  14. package/src/decimal128.ts +31 -25
  15. package/src/double.ts +7 -5
  16. package/src/error.ts +0 -2
  17. package/src/extended_json.ts +148 -148
  18. package/src/index.ts +19 -0
  19. package/src/int_32.ts +7 -5
  20. package/src/long.ts +16 -16
  21. package/src/max_key.ts +6 -6
  22. package/src/min_key.ts +6 -6
  23. package/src/objectid.ts +41 -74
  24. package/src/parser/calculate_size.ts +39 -63
  25. package/src/parser/deserializer.ts +41 -112
  26. package/src/parser/serializer.ts +234 -341
  27. package/src/parser/utils.ts +1 -99
  28. package/src/regexp.ts +16 -5
  29. package/src/symbol.ts +7 -5
  30. package/src/timestamp.ts +62 -27
  31. package/src/utils/byte_utils.ts +61 -0
  32. package/src/utils/node_byte_utils.ts +141 -0
  33. package/src/utils/web_byte_utils.ts +190 -0
  34. package/src/uuid_utils.ts +15 -15
  35. package/bower.json +0 -26
  36. package/dist/bson.browser.esm.js +0 -7470
  37. package/dist/bson.browser.esm.js.map +0 -1
  38. package/dist/bson.browser.umd.js +0 -7537
  39. package/dist/bson.browser.umd.js.map +0 -1
  40. package/dist/bson.bundle.js +0 -7536
  41. package/dist/bson.bundle.js.map +0 -1
  42. package/dist/bson.esm.js +0 -5436
  43. package/dist/bson.esm.js.map +0 -1
  44. package/lib/binary.js +0 -426
  45. package/lib/binary.js.map +0 -1
  46. package/lib/bson.js +0 -251
  47. package/lib/bson.js.map +0 -1
  48. package/lib/code.js +0 -46
  49. package/lib/code.js.map +0 -1
  50. package/lib/constants.js +0 -82
  51. package/lib/constants.js.map +0 -1
  52. package/lib/db_ref.js +0 -97
  53. package/lib/db_ref.js.map +0 -1
  54. package/lib/decimal128.js +0 -669
  55. package/lib/decimal128.js.map +0 -1
  56. package/lib/double.js +0 -76
  57. package/lib/double.js.map +0 -1
  58. package/lib/ensure_buffer.js +0 -25
  59. package/lib/ensure_buffer.js.map +0 -1
  60. package/lib/error.js +0 -55
  61. package/lib/error.js.map +0 -1
  62. package/lib/extended_json.js +0 -390
  63. package/lib/extended_json.js.map +0 -1
  64. package/lib/int_32.js +0 -58
  65. package/lib/int_32.js.map +0 -1
  66. package/lib/long.js +0 -900
  67. package/lib/long.js.map +0 -1
  68. package/lib/map.js +0 -123
  69. package/lib/map.js.map +0 -1
  70. package/lib/max_key.js +0 -33
  71. package/lib/max_key.js.map +0 -1
  72. package/lib/min_key.js +0 -33
  73. package/lib/min_key.js.map +0 -1
  74. package/lib/objectid.js +0 -299
  75. package/lib/objectid.js.map +0 -1
  76. package/lib/parser/calculate_size.js +0 -194
  77. package/lib/parser/calculate_size.js.map +0 -1
  78. package/lib/parser/deserializer.js +0 -665
  79. package/lib/parser/deserializer.js.map +0 -1
  80. package/lib/parser/serializer.js +0 -867
  81. package/lib/parser/serializer.js.map +0 -1
  82. package/lib/parser/utils.js +0 -115
  83. package/lib/parser/utils.js.map +0 -1
  84. package/lib/regexp.js +0 -74
  85. package/lib/regexp.js.map +0 -1
  86. package/lib/symbol.js +0 -48
  87. package/lib/symbol.js.map +0 -1
  88. package/lib/timestamp.js +0 -102
  89. package/lib/timestamp.js.map +0 -1
  90. package/lib/utils/global.js +0 -18
  91. package/lib/utils/global.js.map +0 -1
  92. package/lib/uuid_utils.js +0 -35
  93. package/lib/uuid_utils.js.map +0 -1
  94. package/lib/validate_utf8.js +0 -47
  95. package/lib/validate_utf8.js.map +0 -1
  96. package/src/ensure_buffer.ts +0 -27
  97. package/src/map.ts +0 -119
  98. package/src/utils/global.ts +0 -22
package/src/binary.ts CHANGED
@@ -1,13 +1,12 @@
1
- import { Buffer } from 'buffer';
2
- import { ensureBuffer } from './ensure_buffer';
3
1
  import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils';
4
- import { isUint8Array, randomBytes } from './parser/utils';
2
+ import { isUint8Array } from './parser/utils';
5
3
  import type { EJSONOptions } from './extended_json';
6
4
  import { BSONError, BSONTypeError } from './error';
7
5
  import { BSON_BINARY_SUBTYPE_UUID_NEW } from './constants';
6
+ import { ByteUtils } from './utils/byte_utils';
8
7
 
9
8
  /** @public */
10
- export type BinarySequence = Uint8Array | Buffer | number[];
9
+ export type BinarySequence = Uint8Array | number[];
11
10
 
12
11
  /** @public */
13
12
  export interface BinaryExtendedLegacy {
@@ -29,7 +28,13 @@ export interface BinaryExtended {
29
28
  * @category BSONType
30
29
  */
31
30
  export class Binary {
32
- _bsontype!: 'Binary';
31
+ get _bsontype(): 'Binary' {
32
+ return 'Binary';
33
+ }
34
+ /** @internal */
35
+ get [Symbol.for('@@mdb.bson.version')](): 5 {
36
+ return 5;
37
+ }
33
38
 
34
39
  /**
35
40
  * Binary default subtype
@@ -58,7 +63,7 @@ export class Binary {
58
63
  /** User BSON type */
59
64
  static readonly SUBTYPE_USER_DEFINED = 128;
60
65
 
61
- buffer!: Buffer;
66
+ buffer!: Uint8Array;
62
67
  sub_type!: number;
63
68
  position!: number;
64
69
 
@@ -74,8 +79,6 @@ export class Binary {
74
79
  * @param subType - the option binary type.
75
80
  */
76
81
  constructor(buffer?: string | BinarySequence, subType?: number) {
77
- if (!(this instanceof Binary)) return new Binary(buffer, subType);
78
-
79
82
  if (
80
83
  !(buffer == null) &&
81
84
  !(typeof buffer === 'string') &&
@@ -92,18 +95,18 @@ export class Binary {
92
95
 
93
96
  if (buffer == null) {
94
97
  // create an empty binary buffer
95
- this.buffer = Buffer.alloc(Binary.BUFFER_SIZE);
98
+ this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
96
99
  this.position = 0;
97
100
  } else {
98
101
  if (typeof buffer === 'string') {
99
102
  // string
100
- this.buffer = Buffer.from(buffer, 'binary');
103
+ this.buffer = ByteUtils.fromISO88591(buffer);
101
104
  } else if (Array.isArray(buffer)) {
102
105
  // number[]
103
- this.buffer = Buffer.from(buffer);
106
+ this.buffer = ByteUtils.fromNumberArray(buffer);
104
107
  } else {
105
108
  // Buffer | TypedArray | ArrayBuffer
106
- this.buffer = ensureBuffer(buffer);
109
+ this.buffer = ByteUtils.toLocalBufferType(buffer);
107
110
  }
108
111
 
109
112
  this.position = this.buffer.byteLength;
@@ -115,7 +118,7 @@ export class Binary {
115
118
  *
116
119
  * @param byteValue - a single byte we wish to write.
117
120
  */
118
- put(byteValue: string | number | Uint8Array | Buffer | number[]): void {
121
+ put(byteValue: string | number | Uint8Array | number[]): void {
119
122
  // If it's a string and a has more than one character throw an error
120
123
  if (typeof byteValue === 'string' && byteValue.length !== 1) {
121
124
  throw new BSONTypeError('only accepts single character String');
@@ -136,13 +139,12 @@ export class Binary {
136
139
  throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255');
137
140
  }
138
141
 
139
- if (this.buffer.length > this.position) {
142
+ if (this.buffer.byteLength > this.position) {
140
143
  this.buffer[this.position++] = decodedByte;
141
144
  } else {
142
- const buffer = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length);
143
- // Combine the two buffers together
144
- this.buffer.copy(buffer, 0, 0, this.buffer.length);
145
- this.buffer = buffer;
145
+ const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
146
+ newSpace.set(this.buffer, 0);
147
+ this.buffer = newSpace;
146
148
  this.buffer[this.position++] = decodedByte;
147
149
  }
148
150
  }
@@ -157,20 +159,21 @@ export class Binary {
157
159
  offset = typeof offset === 'number' ? offset : this.position;
158
160
 
159
161
  // If the buffer is to small let's extend the buffer
160
- if (this.buffer.length < offset + sequence.length) {
161
- const buffer = Buffer.alloc(this.buffer.length + sequence.length);
162
- this.buffer.copy(buffer, 0, 0, this.buffer.length);
162
+ if (this.buffer.byteLength < offset + sequence.length) {
163
+ const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
164
+ newSpace.set(this.buffer, 0);
163
165
 
164
166
  // Assign the new buffer
165
- this.buffer = buffer;
167
+ this.buffer = newSpace;
166
168
  }
167
169
 
168
170
  if (ArrayBuffer.isView(sequence)) {
169
- this.buffer.set(ensureBuffer(sequence), offset);
171
+ this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
170
172
  this.position =
171
173
  offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
172
174
  } else if (typeof sequence === 'string') {
173
- this.buffer.write(sequence, offset, sequence.length, 'binary');
175
+ const bytes = ByteUtils.fromISO88591(sequence);
176
+ this.buffer.set(bytes, offset);
174
177
  this.position =
175
178
  offset + sequence.length > this.position ? offset + sequence.length : this.position;
176
179
  }
@@ -207,7 +210,8 @@ export class Binary {
207
210
  if (asRaw) {
208
211
  return this.buffer.slice(0, this.position);
209
212
  }
210
- return this.buffer.toString('binary', 0, this.position);
213
+ // TODO(NODE-4361): remove binary string support, value(true) should be the default / only option here.
214
+ return ByteUtils.toISO88591(this.buffer.subarray(0, this.position));
211
215
  }
212
216
 
213
217
  /** the length of the binary sequence */
@@ -216,17 +220,20 @@ export class Binary {
216
220
  }
217
221
 
218
222
  toJSON(): string {
219
- return this.buffer.toString('base64');
223
+ return ByteUtils.toBase64(this.buffer);
220
224
  }
221
225
 
222
- toString(format?: string): string {
223
- return this.buffer.toString(format);
226
+ toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string {
227
+ if (encoding === 'hex') return ByteUtils.toHex(this.buffer);
228
+ if (encoding === 'base64') return ByteUtils.toBase64(this.buffer);
229
+ if (encoding === 'utf8' || encoding === 'utf-8') return ByteUtils.toUTF8(this.buffer);
230
+ return ByteUtils.toUTF8(this.buffer);
224
231
  }
225
232
 
226
233
  /** @internal */
227
234
  toExtendedJSON(options?: EJSONOptions): BinaryExtendedLegacy | BinaryExtended {
228
235
  options = options || {};
229
- const base64String = this.buffer.toString('base64');
236
+ const base64String = ByteUtils.toBase64(this.buffer);
230
237
 
231
238
  const subType = Number(this.sub_type).toString(16);
232
239
  if (options.legacy) {
@@ -259,16 +266,16 @@ export class Binary {
259
266
  options?: EJSONOptions
260
267
  ): Binary {
261
268
  options = options || {};
262
- let data: Buffer | undefined;
269
+ let data: Uint8Array | undefined;
263
270
  let type;
264
271
  if ('$binary' in doc) {
265
272
  if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
266
273
  type = doc.$type ? parseInt(doc.$type, 16) : 0;
267
- data = Buffer.from(doc.$binary, 'base64');
274
+ data = ByteUtils.fromBase64(doc.$binary);
268
275
  } else {
269
276
  if (typeof doc.$binary !== 'string') {
270
277
  type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
271
- data = Buffer.from(doc.$binary.base64, 'base64');
278
+ data = ByteUtils.fromBase64(doc.$binary.base64);
272
279
  }
273
280
  }
274
281
  } else if ('$uuid' in doc) {
@@ -287,13 +294,10 @@ export class Binary {
287
294
  }
288
295
 
289
296
  inspect(): string {
290
- const asBuffer = this.value(true);
291
- return `new Binary(Buffer.from("${asBuffer.toString('hex')}", "hex"), ${this.sub_type})`;
297
+ return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`;
292
298
  }
293
299
  }
294
300
 
295
- Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' });
296
-
297
301
  /** @public */
298
302
  export type UUIDExtended = {
299
303
  $uuid: string;
@@ -305,6 +309,11 @@ const UUID_BYTE_LENGTH = 16;
305
309
  * @public
306
310
  */
307
311
  export class UUID extends Binary {
312
+ /** @internal */
313
+ get [Symbol.for('@@mdb.bson.version')](): 5 {
314
+ return 5;
315
+ }
316
+
308
317
  static cacheHexString: boolean;
309
318
 
310
319
  /** UUID hexString cache @internal */
@@ -315,16 +324,16 @@ export class UUID extends Binary {
315
324
  *
316
325
  * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
317
326
  */
318
- constructor(input?: string | Buffer | UUID) {
319
- let bytes;
327
+ constructor(input?: string | Uint8Array | UUID) {
328
+ let bytes: Uint8Array;
320
329
  let hexStr;
321
330
  if (input == null) {
322
331
  bytes = UUID.generate();
323
332
  } else if (input instanceof UUID) {
324
- bytes = Buffer.from(input.buffer);
333
+ bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
325
334
  hexStr = input.__id;
326
335
  } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
327
- bytes = ensureBuffer(input);
336
+ bytes = ByteUtils.toLocalBufferType(input);
328
337
  } else if (typeof input === 'string') {
329
338
  bytes = uuidHexStringToBuffer(input);
330
339
  } else {
@@ -340,11 +349,11 @@ export class UUID extends Binary {
340
349
  * The UUID bytes
341
350
  * @readonly
342
351
  */
343
- get id(): Buffer {
352
+ get id(): Uint8Array {
344
353
  return this.buffer;
345
354
  }
346
355
 
347
- set id(value: Buffer) {
356
+ set id(value: Uint8Array) {
348
357
  this.buffer = value;
349
358
 
350
359
  if (UUID.cacheHexString) {
@@ -373,8 +382,10 @@ export class UUID extends Binary {
373
382
  /**
374
383
  * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
375
384
  */
376
- toString(encoding?: string): string {
377
- return encoding ? this.id.toString(encoding) : this.toHexString();
385
+ toString(encoding?: 'hex' | 'base64'): string {
386
+ if (encoding === 'hex') return ByteUtils.toHex(this.id);
387
+ if (encoding === 'base64') return ByteUtils.toBase64(this.id);
388
+ return this.toHexString();
378
389
  }
379
390
 
380
391
  /**
@@ -390,17 +401,17 @@ export class UUID extends Binary {
390
401
  *
391
402
  * @param otherId - UUID instance to compare against.
392
403
  */
393
- equals(otherId: string | Buffer | UUID): boolean {
404
+ equals(otherId: string | Uint8Array | UUID): boolean {
394
405
  if (!otherId) {
395
406
  return false;
396
407
  }
397
408
 
398
409
  if (otherId instanceof UUID) {
399
- return otherId.id.equals(this.id);
410
+ return ByteUtils.equals(otherId.id, this.id);
400
411
  }
401
412
 
402
413
  try {
403
- return new UUID(otherId).id.equals(this.id);
414
+ return ByteUtils.equals(new UUID(otherId).id, this.id);
404
415
  } catch {
405
416
  return false;
406
417
  }
@@ -416,22 +427,22 @@ export class UUID extends Binary {
416
427
  /**
417
428
  * Generates a populated buffer containing a v4 uuid
418
429
  */
419
- static generate(): Buffer {
420
- const bytes = randomBytes(UUID_BYTE_LENGTH);
430
+ static generate(): Uint8Array {
431
+ const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
421
432
 
422
433
  // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
423
434
  // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js
424
435
  bytes[6] = (bytes[6] & 0x0f) | 0x40;
425
436
  bytes[8] = (bytes[8] & 0x3f) | 0x80;
426
437
 
427
- return Buffer.from(bytes);
438
+ return bytes;
428
439
  }
429
440
 
430
441
  /**
431
442
  * Checks if a value is a valid bson UUID
432
443
  * @param input - UUID, string or Buffer to validate.
433
444
  */
434
- static isValid(input: string | Buffer | UUID): boolean {
445
+ static isValid(input: string | Uint8Array | UUID): boolean {
435
446
  if (!input) {
436
447
  return false;
437
448
  }
@@ -446,7 +457,7 @@ export class UUID extends Binary {
446
457
 
447
458
  if (isUint8Array(input)) {
448
459
  // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3)
449
- if (input.length !== UUID_BYTE_LENGTH) {
460
+ if (input.byteLength !== UUID_BYTE_LENGTH) {
450
461
  return false;
451
462
  }
452
463
 
package/src/bson.ts CHANGED
@@ -1,68 +1,27 @@
1
- import { Buffer } from 'buffer';
2
1
  import { Binary, UUID } from './binary';
3
2
  import { Code } from './code';
4
3
  import { DBRef } from './db_ref';
5
4
  import { Decimal128 } from './decimal128';
6
5
  import { Double } from './double';
7
- import { ensureBuffer } from './ensure_buffer';
8
- import { EJSON } from './extended_json';
9
6
  import { Int32 } from './int_32';
10
7
  import { Long } from './long';
11
- import { Map } from './map';
12
8
  import { MaxKey } from './max_key';
13
9
  import { MinKey } from './min_key';
14
10
  import { ObjectId } from './objectid';
15
- import { BSONError, BSONTypeError } from './error';
16
- import { calculateObjectSize as internalCalculateObjectSize } from './parser/calculate_size';
11
+ import { internalCalculateObjectSize } from './parser/calculate_size';
17
12
  // Parts of the parser
18
- import { deserialize as internalDeserialize, DeserializeOptions } from './parser/deserializer';
19
- import { serializeInto as internalSerialize, SerializeOptions } from './parser/serializer';
13
+ import { internalDeserialize, DeserializeOptions } from './parser/deserializer';
14
+ import { serializeInto, SerializeOptions } from './parser/serializer';
20
15
  import { BSONRegExp } from './regexp';
21
16
  import { BSONSymbol } from './symbol';
22
17
  import { Timestamp } from './timestamp';
18
+ import { ByteUtils } from './utils/byte_utils';
23
19
  export type { UUIDExtended, BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary';
24
20
  export type { CodeExtended } from './code';
25
- export {
26
- BSON_BINARY_SUBTYPE_BYTE_ARRAY,
27
- BSON_BINARY_SUBTYPE_DEFAULT,
28
- BSON_BINARY_SUBTYPE_FUNCTION,
29
- BSON_BINARY_SUBTYPE_MD5,
30
- BSON_BINARY_SUBTYPE_USER_DEFINED,
31
- BSON_BINARY_SUBTYPE_UUID,
32
- BSON_BINARY_SUBTYPE_UUID_NEW,
33
- BSON_BINARY_SUBTYPE_ENCRYPTED,
34
- BSON_BINARY_SUBTYPE_COLUMN,
35
- BSON_DATA_ARRAY,
36
- BSON_DATA_BINARY,
37
- BSON_DATA_BOOLEAN,
38
- BSON_DATA_CODE,
39
- BSON_DATA_CODE_W_SCOPE,
40
- BSON_DATA_DATE,
41
- BSON_DATA_DBPOINTER,
42
- BSON_DATA_DECIMAL128,
43
- BSON_DATA_INT,
44
- BSON_DATA_LONG,
45
- BSON_DATA_MAX_KEY,
46
- BSON_DATA_MIN_KEY,
47
- BSON_DATA_NULL,
48
- BSON_DATA_NUMBER,
49
- BSON_DATA_OBJECT,
50
- BSON_DATA_OID,
51
- BSON_DATA_REGEXP,
52
- BSON_DATA_STRING,
53
- BSON_DATA_SYMBOL,
54
- BSON_DATA_TIMESTAMP,
55
- BSON_DATA_UNDEFINED,
56
- BSON_INT32_MAX,
57
- BSON_INT32_MIN,
58
- BSON_INT64_MAX,
59
- BSON_INT64_MIN
60
- } from './constants';
61
21
  export type { DBRefLike } from './db_ref';
62
22
  export type { Decimal128Extended } from './decimal128';
63
23
  export type { DoubleExtended } from './double';
64
24
  export type { EJSONOptions } from './extended_json';
65
- export { EJSON } from './extended_json';
66
25
  export type { Int32Extended } from './int_32';
67
26
  export type { LongExtended } from './long';
68
27
  export type { MaxKeyExtended } from './max_key';
@@ -71,11 +30,11 @@ export type { ObjectIdExtended, ObjectIdLike } from './objectid';
71
30
  export type { BSONRegExpExtended, BSONRegExpExtendedLegacy } from './regexp';
72
31
  export type { BSONSymbolExtended } from './symbol';
73
32
  export type { LongWithoutOverrides, TimestampExtended, TimestampOverrides } from './timestamp';
74
- export { LongWithoutOverridesClass } from './timestamp';
33
+ export type { LongWithoutOverridesClass } from './timestamp';
75
34
  export type { SerializeOptions, DeserializeOptions };
35
+
76
36
  export {
77
37
  Code,
78
- Map,
79
38
  BSONSymbol,
80
39
  DBRef,
81
40
  Binary,
@@ -88,13 +47,11 @@ export {
88
47
  MinKey,
89
48
  MaxKey,
90
49
  BSONRegExp,
91
- Decimal128,
92
- // In 4.0.0 and 4.0.1, this property name was changed to ObjectId to match the class name.
93
- // This caused interoperability problems with previous versions of the library, so in
94
- // later builds we changed it back to ObjectID (capital D) to match legacy implementations.
95
- ObjectId as ObjectID
50
+ Decimal128
96
51
  };
97
52
  export { BSONError, BSONTypeError } from './error';
53
+ export { BSONType } from './constants';
54
+ export { EJSON } from './extended_json';
98
55
 
99
56
  /** @public */
100
57
  export interface Document {
@@ -107,7 +64,7 @@ export interface Document {
107
64
  const MAXSIZE = 1024 * 1024 * 17;
108
65
 
109
66
  // Current Internal Temporary Serialization Buffer
110
- let buffer = Buffer.alloc(MAXSIZE);
67
+ let buffer = ByteUtils.allocate(MAXSIZE);
111
68
 
112
69
  /**
113
70
  * Sets the size of the internal serialization buffer.
@@ -118,7 +75,7 @@ let buffer = Buffer.alloc(MAXSIZE);
118
75
  export function setInternalBufferSize(size: number): void {
119
76
  // Resize the internal serialization buffer if needed
120
77
  if (buffer.length < size) {
121
- buffer = Buffer.alloc(size);
78
+ buffer = ByteUtils.allocate(size);
122
79
  }
123
80
  }
124
81
 
@@ -129,7 +86,7 @@ export function setInternalBufferSize(size: number): void {
129
86
  * @returns Buffer object containing the serialized object.
130
87
  * @public
131
88
  */
132
- export function serialize(object: Document, options: SerializeOptions = {}): Buffer {
89
+ export function serialize(object: Document, options: SerializeOptions = {}): Uint8Array {
133
90
  // Unpack the options
134
91
  const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
135
92
  const serializeFunctions =
@@ -141,11 +98,11 @@ export function serialize(object: Document, options: SerializeOptions = {}): Buf
141
98
 
142
99
  // Resize the internal serialization buffer if needed
143
100
  if (buffer.length < minInternalBufferSize) {
144
- buffer = Buffer.alloc(minInternalBufferSize);
101
+ buffer = ByteUtils.allocate(minInternalBufferSize);
145
102
  }
146
103
 
147
104
  // Attempt to serialize
148
- const serializationIndex = internalSerialize(
105
+ const serializationIndex = serializeInto(
149
106
  buffer,
150
107
  object,
151
108
  checkKeys,
@@ -153,14 +110,14 @@ export function serialize(object: Document, options: SerializeOptions = {}): Buf
153
110
  0,
154
111
  serializeFunctions,
155
112
  ignoreUndefined,
156
- []
113
+ null
157
114
  );
158
115
 
159
116
  // Create the final buffer
160
- const finishedBuffer = Buffer.alloc(serializationIndex);
117
+ const finishedBuffer = ByteUtils.allocate(serializationIndex);
161
118
 
162
119
  // Copy into the finished buffer
163
- buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length);
120
+ finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
164
121
 
165
122
  // Return the buffer
166
123
  return finishedBuffer;
@@ -177,7 +134,7 @@ export function serialize(object: Document, options: SerializeOptions = {}): Buf
177
134
  */
178
135
  export function serializeWithBufferAndIndex(
179
136
  object: Document,
180
- finalBuffer: Buffer,
137
+ finalBuffer: Uint8Array,
181
138
  options: SerializeOptions = {}
182
139
  ): number {
183
140
  // Unpack the options
@@ -189,16 +146,18 @@ export function serializeWithBufferAndIndex(
189
146
  const startIndex = typeof options.index === 'number' ? options.index : 0;
190
147
 
191
148
  // Attempt to serialize
192
- const serializationIndex = internalSerialize(
149
+ const serializationIndex = serializeInto(
193
150
  buffer,
194
151
  object,
195
152
  checkKeys,
196
153
  0,
197
154
  0,
198
155
  serializeFunctions,
199
- ignoreUndefined
156
+ ignoreUndefined,
157
+ null
200
158
  );
201
- buffer.copy(finalBuffer, startIndex, 0, serializationIndex);
159
+
160
+ finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
202
161
 
203
162
  // Return the index
204
163
  return startIndex + serializationIndex - 1;
@@ -211,11 +170,8 @@ export function serializeWithBufferAndIndex(
211
170
  * @returns returns the deserialized Javascript Object.
212
171
  * @public
213
172
  */
214
- export function deserialize(
215
- buffer: Buffer | ArrayBufferView | ArrayBuffer,
216
- options: DeserializeOptions = {}
217
- ): Document {
218
- return internalDeserialize(buffer instanceof Buffer ? buffer : ensureBuffer(buffer), options);
173
+ export function deserialize(buffer: Uint8Array, options: DeserializeOptions = {}): Document {
174
+ return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
219
175
  }
220
176
 
221
177
  /** @public */
@@ -258,7 +214,7 @@ export function calculateObjectSize(
258
214
  * @public
259
215
  */
260
216
  export function deserializeStream(
261
- data: Buffer | ArrayBufferView | ArrayBuffer,
217
+ data: Uint8Array | ArrayBuffer,
262
218
  startIndex: number,
263
219
  numberOfDocuments: number,
264
220
  documents: Document[],
@@ -269,7 +225,7 @@ export function deserializeStream(
269
225
  { allowObjectSmallerThanBufferSize: true, index: 0 },
270
226
  options
271
227
  );
272
- const bufferData = ensureBuffer(data);
228
+ const bufferData = ByteUtils.toLocalBufferType(data);
273
229
 
274
230
  let index = startIndex;
275
231
  // Loop over all documents
@@ -291,40 +247,3 @@ export function deserializeStream(
291
247
  // Return object containing end index of parsing and list of documents
292
248
  return index;
293
249
  }
294
-
295
- /**
296
- * BSON default export
297
- * @deprecated Please use named exports
298
- * @privateRemarks
299
- * We want to someday deprecate the default export,
300
- * so none of the new TS types are being exported on the default
301
- * @public
302
- */
303
- const BSON = {
304
- Binary,
305
- Code,
306
- DBRef,
307
- Decimal128,
308
- Double,
309
- Int32,
310
- Long,
311
- UUID,
312
- Map,
313
- MaxKey,
314
- MinKey,
315
- ObjectId,
316
- ObjectID: ObjectId,
317
- BSONRegExp,
318
- BSONSymbol,
319
- Timestamp,
320
- EJSON,
321
- setInternalBufferSize,
322
- serialize,
323
- serializeWithBufferAndIndex,
324
- deserialize,
325
- calculateObjectSize,
326
- deserializeStream,
327
- BSONError,
328
- BSONTypeError
329
- };
330
- export default BSON;
package/src/code.ts CHANGED
@@ -2,7 +2,7 @@ import type { Document } from './bson';
2
2
 
3
3
  /** @public */
4
4
  export interface CodeExtended {
5
- $code: string | Function;
5
+ $code: string;
6
6
  $scope?: Document;
7
7
  }
8
8
 
@@ -12,23 +12,35 @@ export interface CodeExtended {
12
12
  * @category BSONType
13
13
  */
14
14
  export class Code {
15
- _bsontype!: 'Code';
15
+ get _bsontype(): 'Code' {
16
+ return 'Code';
17
+ }
18
+ /** @internal */
19
+ get [Symbol.for('@@mdb.bson.version')](): 5 {
20
+ return 5;
21
+ }
22
+
23
+ code: string;
24
+
25
+ // a code instance having a null scope is what determines whether
26
+ // it is BSONType 0x0D (just code) / 0x0F (code with scope)
27
+ scope: Document | null;
16
28
 
17
- code!: string | Function;
18
- scope?: Document;
19
29
  /**
20
30
  * @param code - a string or function.
21
31
  * @param scope - an optional scope for the function.
22
32
  */
23
- constructor(code: string | Function, scope?: Document) {
24
- if (!(this instanceof Code)) return new Code(code, scope);
25
-
26
- this.code = code;
27
- this.scope = scope;
33
+ constructor(code: string | Function, scope?: Document | null) {
34
+ this.code = code.toString();
35
+ this.scope = scope ?? null;
28
36
  }
29
37
 
30
- toJSON(): { code: string | Function; scope?: Document } {
31
- return { code: this.code, scope: this.scope };
38
+ toJSON(): { code: string; scope?: Document } {
39
+ if (this.scope != null) {
40
+ return { code: this.code, scope: this.scope };
41
+ }
42
+
43
+ return { code: this.code };
32
44
  }
33
45
 
34
46
  /** @internal */
@@ -53,9 +65,7 @@ export class Code {
53
65
  inspect(): string {
54
66
  const codeJson = this.toJSON();
55
67
  return `new Code("${String(codeJson.code)}"${
56
- codeJson.scope ? `, ${JSON.stringify(codeJson.scope)}` : ''
68
+ codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''
57
69
  })`;
58
70
  }
59
71
  }
60
-
61
- Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' });
package/src/constants.ts CHANGED
@@ -108,3 +108,31 @@ export const BSON_BINARY_SUBTYPE_COLUMN = 7;
108
108
 
109
109
  /** Binary User Defined Type @internal */
110
110
  export const BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
111
+
112
+ /** @public */
113
+ export const BSONType = Object.freeze({
114
+ double: 1,
115
+ string: 2,
116
+ object: 3,
117
+ array: 4,
118
+ binData: 5,
119
+ undefined: 6,
120
+ objectId: 7,
121
+ bool: 8,
122
+ date: 9,
123
+ null: 10,
124
+ regex: 11,
125
+ dbPointer: 12,
126
+ javascript: 13,
127
+ symbol: 14,
128
+ javascriptWithScope: 15,
129
+ int: 16,
130
+ timestamp: 17,
131
+ long: 18,
132
+ decimal: 19,
133
+ minKey: -1,
134
+ maxKey: 127
135
+ } as const);
136
+
137
+ /** @public */
138
+ export type BSONType = typeof BSONType[keyof typeof BSONType];