bson 4.0.4 → 4.2.2

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 (90) hide show
  1. package/HISTORY.md +56 -1
  2. package/README.md +7 -9
  3. package/bower.json +1 -1
  4. package/bson.d.ts +983 -0
  5. package/dist/bson.browser.esm.js +7261 -5004
  6. package/dist/bson.browser.esm.js.map +1 -0
  7. package/dist/bson.browser.umd.js +7319 -5099
  8. package/dist/bson.browser.umd.js.map +1 -0
  9. package/dist/bson.bundle.js +8168 -9216
  10. package/dist/bson.bundle.js.map +1 -0
  11. package/dist/bson.esm.js +5643 -5409
  12. package/dist/bson.esm.js.map +1 -0
  13. package/etc/prepare.js +19 -0
  14. package/lib/binary.js +194 -377
  15. package/lib/binary.js.map +1 -0
  16. package/lib/bson.js +200 -243
  17. package/lib/bson.js.map +1 -0
  18. package/lib/code.js +36 -39
  19. package/lib/code.js.map +1 -0
  20. package/lib/constants.js +78 -203
  21. package/lib/constants.js.map +1 -0
  22. package/lib/db_ref.js +79 -79
  23. package/lib/db_ref.js.map +1 -0
  24. package/lib/decimal128.js +647 -760
  25. package/lib/decimal128.js.map +1 -0
  26. package/lib/double.js +61 -58
  27. package/lib/double.js.map +1 -0
  28. package/lib/ensure_buffer.js +22 -18
  29. package/lib/ensure_buffer.js.map +1 -0
  30. package/lib/extended_json.js +305 -322
  31. package/lib/extended_json.js.map +1 -0
  32. package/lib/float_parser.js +98 -104
  33. package/lib/float_parser.js.map +1 -0
  34. package/lib/int_32.js +45 -47
  35. package/lib/int_32.js.map +1 -0
  36. package/lib/long.js +876 -16
  37. package/lib/long.js.map +1 -0
  38. package/lib/map.js +123 -124
  39. package/lib/map.js.map +1 -0
  40. package/lib/max_key.js +21 -23
  41. package/lib/max_key.js.map +1 -0
  42. package/lib/min_key.js +21 -23
  43. package/lib/min_key.js.map +1 -0
  44. package/lib/objectid.js +264 -382
  45. package/lib/objectid.js.map +1 -0
  46. package/lib/parser/calculate_size.js +185 -224
  47. package/lib/parser/calculate_size.js.map +1 -0
  48. package/lib/parser/deserializer.js +543 -620
  49. package/lib/parser/deserializer.js.map +1 -0
  50. package/lib/parser/serializer.js +774 -918
  51. package/lib/parser/serializer.js.map +1 -0
  52. package/lib/parser/utils.js +81 -30
  53. package/lib/parser/utils.js.map +1 -0
  54. package/lib/regexp.js +54 -70
  55. package/lib/regexp.js.map +1 -0
  56. package/lib/symbol.js +40 -56
  57. package/lib/symbol.js.map +1 -0
  58. package/lib/timestamp.js +70 -95
  59. package/lib/timestamp.js.map +1 -0
  60. package/lib/uuid.js +48 -0
  61. package/lib/uuid.js.map +1 -0
  62. package/lib/validate_utf8.js +32 -33
  63. package/lib/validate_utf8.js.map +1 -0
  64. package/package.json +53 -31
  65. package/src/binary.ts +270 -0
  66. package/src/bson.ts +326 -0
  67. package/src/code.ts +57 -0
  68. package/src/constants.ts +104 -0
  69. package/src/db_ref.ts +115 -0
  70. package/src/decimal128.ts +801 -0
  71. package/src/double.ts +85 -0
  72. package/src/ensure_buffer.ts +26 -0
  73. package/src/extended_json.ts +395 -0
  74. package/src/float_parser.ts +152 -0
  75. package/src/int_32.ts +64 -0
  76. package/src/long.ts +1000 -0
  77. package/src/map.ts +139 -0
  78. package/src/max_key.ts +33 -0
  79. package/src/min_key.ts +33 -0
  80. package/src/objectid.ts +377 -0
  81. package/src/parser/calculate_size.ts +230 -0
  82. package/src/parser/deserializer.ts +655 -0
  83. package/src/parser/serializer.ts +1069 -0
  84. package/src/parser/utils.ts +93 -0
  85. package/src/regexp.ts +92 -0
  86. package/src/symbol.ts +57 -0
  87. package/src/timestamp.ts +103 -0
  88. package/src/uuid.ts +57 -0
  89. package/src/validate_utf8.ts +47 -0
  90. package/lib/fnv1a.js +0 -48
package/src/double.ts ADDED
@@ -0,0 +1,85 @@
1
+ import type { EJSONOptions } from './extended_json';
2
+
3
+ /** @public */
4
+ export interface DoubleExtended {
5
+ $numberDouble: string;
6
+ }
7
+
8
+ /**
9
+ * A class representation of the BSON Double type.
10
+ * @public
11
+ */
12
+ export class Double {
13
+ _bsontype!: 'Double';
14
+
15
+ value: number;
16
+ /**
17
+ * Create a Double type
18
+ *
19
+ * @param value - the number we want to represent as a double.
20
+ */
21
+ constructor(value: number) {
22
+ if ((value as unknown) instanceof Number) {
23
+ value = value.valueOf();
24
+ }
25
+
26
+ this.value = +value;
27
+ }
28
+
29
+ /**
30
+ * Access the number value.
31
+ *
32
+ * @returns returns the wrapped double number.
33
+ */
34
+ valueOf(): number {
35
+ return this.value;
36
+ }
37
+
38
+ /** @internal */
39
+ toJSON(): number {
40
+ return this.value;
41
+ }
42
+
43
+ /** @internal */
44
+ toExtendedJSON(options?: EJSONOptions): number | DoubleExtended {
45
+ if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
46
+ return this.value;
47
+ }
48
+
49
+ // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
50
+ // explicitly provided `-0` then we need to ensure the sign makes it into the output
51
+ if (Object.is(Math.sign(this.value), -0)) {
52
+ return { $numberDouble: `-${this.value.toFixed(1)}` };
53
+ }
54
+
55
+ let $numberDouble: string;
56
+ if (Number.isInteger(this.value)) {
57
+ $numberDouble = this.value.toFixed(1);
58
+ if ($numberDouble.length >= 13) {
59
+ $numberDouble = this.value.toExponential(13).toUpperCase();
60
+ }
61
+ } else {
62
+ $numberDouble = this.value.toString();
63
+ }
64
+
65
+ return { $numberDouble };
66
+ }
67
+
68
+ /** @internal */
69
+ static fromExtendedJSON(doc: DoubleExtended, options?: EJSONOptions): number | Double {
70
+ const doubleValue = parseFloat(doc.$numberDouble);
71
+ return options && options.relaxed ? doubleValue : new Double(doubleValue);
72
+ }
73
+
74
+ /** @internal */
75
+ [Symbol.for('nodejs.util.inspect.custom')](): string {
76
+ return this.inspect();
77
+ }
78
+
79
+ inspect(): string {
80
+ const eJSON = this.toExtendedJSON() as DoubleExtended;
81
+ return `Double(${eJSON.$numberDouble})`;
82
+ }
83
+ }
84
+
85
+ Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' });
@@ -0,0 +1,26 @@
1
+ import { Buffer } from 'buffer';
2
+ import { isBuffer } from './parser/utils';
3
+
4
+ /**
5
+ * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
6
+ *
7
+ * @param potentialBuffer - The potential buffer
8
+ * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
9
+ * wraps a passed in Uint8Array
10
+ * @throws TypeError If anything other than a Buffer or Uint8Array is passed in
11
+ */
12
+ export function ensureBuffer(potentialBuffer: Buffer | ArrayBufferView | ArrayBuffer): Buffer {
13
+ if (isBuffer(potentialBuffer)) {
14
+ return potentialBuffer;
15
+ }
16
+
17
+ if (ArrayBuffer.isView(potentialBuffer)) {
18
+ return Buffer.from(potentialBuffer.buffer);
19
+ }
20
+
21
+ if (potentialBuffer instanceof ArrayBuffer) {
22
+ return Buffer.from(potentialBuffer);
23
+ }
24
+
25
+ throw new TypeError('Must use either Buffer or TypedArray');
26
+ }
@@ -0,0 +1,395 @@
1
+ import { Binary } from './binary';
2
+ import type { Document } from './bson';
3
+ import { Code } from './code';
4
+ import { DBRef } from './db_ref';
5
+ import { Decimal128 } from './decimal128';
6
+ import { Double } from './double';
7
+ import { Int32 } from './int_32';
8
+ import { Long } from './long';
9
+ import { MaxKey } from './max_key';
10
+ import { MinKey } from './min_key';
11
+ import { ObjectId } from './objectid';
12
+ import { isObjectLike } from './parser/utils';
13
+ import { BSONRegExp } from './regexp';
14
+ import { BSONSymbol } from './symbol';
15
+ import { Timestamp } from './timestamp';
16
+
17
+ /** @public */
18
+ export type EJSONOptions = EJSON.Options;
19
+
20
+ /** @internal */
21
+ type BSONType =
22
+ | Binary
23
+ | Code
24
+ | DBRef
25
+ | Decimal128
26
+ | Double
27
+ | Int32
28
+ | Long
29
+ | MaxKey
30
+ | MinKey
31
+ | ObjectId
32
+ | BSONRegExp
33
+ | BSONSymbol
34
+ | Timestamp;
35
+
36
+ export function isBSONType(value: unknown): value is BSONType {
37
+ return (
38
+ isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string'
39
+ );
40
+ }
41
+
42
+ // INT32 boundaries
43
+ const BSON_INT32_MAX = 0x7fffffff;
44
+ const BSON_INT32_MIN = -0x80000000;
45
+ // INT64 boundaries
46
+ const BSON_INT64_MAX = 0x7fffffffffffffff;
47
+ const BSON_INT64_MIN = -0x8000000000000000;
48
+
49
+ // all the types where we don't need to do any special processing and can just pass the EJSON
50
+ //straight to type.fromExtendedJSON
51
+ const keysToCodecs = {
52
+ $oid: ObjectId,
53
+ $binary: Binary,
54
+ $uuid: Binary,
55
+ $symbol: BSONSymbol,
56
+ $numberInt: Int32,
57
+ $numberDecimal: Decimal128,
58
+ $numberDouble: Double,
59
+ $numberLong: Long,
60
+ $minKey: MinKey,
61
+ $maxKey: MaxKey,
62
+ $regex: BSONRegExp,
63
+ $regularExpression: BSONRegExp,
64
+ $timestamp: Timestamp
65
+ } as const;
66
+
67
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
68
+ function deserializeValue(value: any, options: EJSON.Options = {}) {
69
+ if (typeof value === 'number') {
70
+ if (options.relaxed || options.legacy) {
71
+ return value;
72
+ }
73
+
74
+ // if it's an integer, should interpret as smallest BSON integer
75
+ // that can represent it exactly. (if out of range, interpret as double.)
76
+ if (Math.floor(value) === value) {
77
+ if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) return new Int32(value);
78
+ if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) return Long.fromNumber(value);
79
+ }
80
+
81
+ // If the number is a non-integer or out of integer range, should interpret as BSON Double.
82
+ return new Double(value);
83
+ }
84
+
85
+ // from here on out we're looking for bson types, so bail if its not an object
86
+ if (value == null || typeof value !== 'object') return value;
87
+
88
+ // upgrade deprecated undefined to null
89
+ if (value.$undefined) return null;
90
+
91
+ const keys = Object.keys(value).filter(
92
+ k => k.startsWith('$') && value[k] != null
93
+ ) as (keyof typeof keysToCodecs)[];
94
+ for (let i = 0; i < keys.length; i++) {
95
+ const c = keysToCodecs[keys[i]];
96
+ if (c) return c.fromExtendedJSON(value, options);
97
+ }
98
+
99
+ if (value.$date != null) {
100
+ const d = value.$date;
101
+ const date = new Date();
102
+
103
+ if (options.legacy) {
104
+ if (typeof d === 'number') date.setTime(d);
105
+ else if (typeof d === 'string') date.setTime(Date.parse(d));
106
+ } else {
107
+ if (typeof d === 'string') date.setTime(Date.parse(d));
108
+ else if (Long.isLong(d)) date.setTime(d.toNumber());
109
+ else if (typeof d === 'number' && options.relaxed) date.setTime(d);
110
+ }
111
+ return date;
112
+ }
113
+
114
+ if (value.$code != null) {
115
+ const copy = Object.assign({}, value);
116
+ if (value.$scope) {
117
+ copy.$scope = deserializeValue(value.$scope);
118
+ }
119
+
120
+ return Code.fromExtendedJSON(value);
121
+ }
122
+
123
+ if (value.$ref != null || value.$dbPointer != null) {
124
+ const v = value.$ref ? value : value.$dbPointer;
125
+
126
+ // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
127
+ // because of the order JSON.parse goes through the document
128
+ if (v instanceof DBRef) return v;
129
+
130
+ const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
131
+ let valid = true;
132
+ dollarKeys.forEach(k => {
133
+ if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
134
+ });
135
+
136
+ // only make DBRef if $ keys are all valid
137
+ if (valid) return DBRef.fromExtendedJSON(v);
138
+ }
139
+
140
+ return value;
141
+ }
142
+
143
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
144
+ function serializeArray(array: any[], options: EJSON.Options): any[] {
145
+ return array.map((v: unknown) => serializeValue(v, options));
146
+ }
147
+
148
+ function getISOString(date: Date) {
149
+ const isoStr = date.toISOString();
150
+ // we should only show milliseconds in timestamp if they're non-zero
151
+ return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
152
+ }
153
+
154
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
155
+ function serializeValue(value: any, options: EJSON.Options): any {
156
+ if (Array.isArray(value)) return serializeArray(value, options);
157
+
158
+ if (value === undefined) return null;
159
+
160
+ if (value instanceof Date) {
161
+ const dateNum = value.getTime(),
162
+ // is it in year range 1970-9999?
163
+ inRange = dateNum > -1 && dateNum < 253402318800000;
164
+
165
+ if (options.legacy) {
166
+ return options.relaxed && inRange
167
+ ? { $date: value.getTime() }
168
+ : { $date: getISOString(value) };
169
+ }
170
+ return options.relaxed && inRange
171
+ ? { $date: getISOString(value) }
172
+ : { $date: { $numberLong: value.getTime().toString() } };
173
+ }
174
+
175
+ if (typeof value === 'number' && !options.relaxed) {
176
+ // it's an integer
177
+ if (Math.floor(value) === value) {
178
+ const int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX,
179
+ int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX;
180
+
181
+ // interpret as being of the smallest BSON integer type that can represent the number exactly
182
+ if (int32Range) return { $numberInt: value.toString() };
183
+ if (int64Range) return { $numberLong: value.toString() };
184
+ }
185
+ return { $numberDouble: value.toString() };
186
+ }
187
+
188
+ if (value instanceof RegExp) {
189
+ let flags = value.flags;
190
+ if (flags === undefined) {
191
+ const match = value.toString().match(/[gimuy]*$/);
192
+ if (match) {
193
+ flags = match[0];
194
+ }
195
+ }
196
+
197
+ const rx = new BSONRegExp(value.source, flags);
198
+ return rx.toExtendedJSON(options);
199
+ }
200
+
201
+ if (value != null && typeof value === 'object') return serializeDocument(value, options);
202
+ return value;
203
+ }
204
+
205
+ const BSON_TYPE_MAPPINGS = {
206
+ Binary: (o: Binary) => new Binary(o.value(), o.sub_type),
207
+ Code: (o: Code) => new Code(o.code, o.scope),
208
+ DBRef: (o: DBRef) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), // "namespace" for 1.x library backwards compat
209
+ Decimal128: (o: Decimal128) => new Decimal128(o.bytes),
210
+ Double: (o: Double) => new Double(o.value),
211
+ Int32: (o: Int32) => new Int32(o.value),
212
+ Long: (
213
+ o: Long & {
214
+ low_: number;
215
+ high_: number;
216
+ unsigned_: boolean | undefined;
217
+ }
218
+ ) =>
219
+ Long.fromBits(
220
+ // underscore variants for 1.x backwards compatibility
221
+ o.low != null ? o.low : o.low_,
222
+ o.low != null ? o.high : o.high_,
223
+ o.low != null ? o.unsigned : o.unsigned_
224
+ ),
225
+ MaxKey: () => new MaxKey(),
226
+ MinKey: () => new MinKey(),
227
+ ObjectID: (o: ObjectId) => new ObjectId(o),
228
+ ObjectId: (o: ObjectId) => new ObjectId(o), // support 4.0.0/4.0.1 before _bsontype was reverted back to ObjectID
229
+ BSONRegExp: (o: BSONRegExp) => new BSONRegExp(o.pattern, o.options),
230
+ Symbol: (o: BSONSymbol) => new BSONSymbol(o.value),
231
+ Timestamp: (o: Timestamp) => Timestamp.fromBits(o.low, o.high)
232
+ } as const;
233
+
234
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
235
+ function serializeDocument(doc: any, options: EJSON.Options) {
236
+ if (doc == null || typeof doc !== 'object') throw new Error('not an object instance');
237
+
238
+ const bsontype: BSONType['_bsontype'] = doc._bsontype;
239
+ if (typeof bsontype === 'undefined') {
240
+ // It's a regular object. Recursively serialize its property values.
241
+ const _doc: Document = {};
242
+ for (const name in doc) {
243
+ _doc[name] = serializeValue(doc[name], options);
244
+ }
245
+ return _doc;
246
+ } else if (isBSONType(doc)) {
247
+ // the "document" is really just a BSON type object
248
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
249
+ let outDoc: any = doc;
250
+ if (typeof outDoc.toExtendedJSON !== 'function') {
251
+ // There's no EJSON serialization function on the object. It's probably an
252
+ // object created by a previous version of this library (or another library)
253
+ // that's duck-typing objects to look like they were generated by this library).
254
+ // Copy the object into this library's version of that type.
255
+ const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
256
+ if (!mapper) {
257
+ throw new TypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
258
+ }
259
+ outDoc = mapper(outDoc);
260
+ }
261
+
262
+ // Two BSON types may have nested objects that may need to be serialized too
263
+ if (bsontype === 'Code' && outDoc.scope) {
264
+ outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
265
+ } else if (bsontype === 'DBRef' && outDoc.oid) {
266
+ outDoc = new DBRef(
267
+ outDoc.collection,
268
+ serializeValue(outDoc.oid, options),
269
+ outDoc.db,
270
+ outDoc.fields
271
+ );
272
+ }
273
+
274
+ return outDoc.toExtendedJSON(options);
275
+ } else {
276
+ throw new Error('_bsontype must be a string, but was: ' + typeof bsontype);
277
+ }
278
+ }
279
+
280
+ /**
281
+ * EJSON parse / stringify API
282
+ * @public
283
+ */
284
+ // the namespace here is used to emulate `export * as EJSON from '...'`
285
+ // which as of now (sept 2020) api-extractor does not support
286
+ // eslint-disable-next-line @typescript-eslint/no-namespace
287
+ export namespace EJSON {
288
+ export interface Options {
289
+ /** Output using the Extended JSON v1 spec */
290
+ legacy?: boolean;
291
+ /** Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types */
292
+ relaxed?: boolean;
293
+ /**
294
+ * Disable Extended JSON's `relaxed` mode, which attempts to return BSON types where possible, rather than native JS types
295
+ * @deprecated Please use the relaxed property instead
296
+ */
297
+ strict?: boolean;
298
+ }
299
+
300
+ /**
301
+ * Parse an Extended JSON string, constructing the JavaScript value or object described by that
302
+ * string.
303
+ *
304
+ * @example
305
+ * ```js
306
+ * const { EJSON } = require('bson');
307
+ * const text = '{ "int32": { "$numberInt": "10" } }';
308
+ *
309
+ * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
310
+ * console.log(EJSON.parse(text, { relaxed: false }));
311
+ *
312
+ * // prints { int32: 10 }
313
+ * console.log(EJSON.parse(text));
314
+ * ```
315
+ */
316
+ export function parse(text: string, options?: EJSON.Options): SerializableTypes {
317
+ const finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options);
318
+
319
+ // relaxed implies not strict
320
+ if (typeof finalOptions.relaxed === 'boolean') finalOptions.strict = !finalOptions.relaxed;
321
+ if (typeof finalOptions.strict === 'boolean') finalOptions.relaxed = !finalOptions.strict;
322
+
323
+ return JSON.parse(text, (_key, value) => deserializeValue(value, finalOptions));
324
+ }
325
+
326
+ export type JSONPrimitive = string | number | boolean | null;
327
+ export type SerializableTypes = Document | Array<JSONPrimitive | Document> | JSONPrimitive;
328
+
329
+ /**
330
+ * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
331
+ * function is specified or optionally including only the specified properties if a replacer array
332
+ * is specified.
333
+ *
334
+ * @param value - The value to convert to extended JSON
335
+ * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
336
+ * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
337
+ * @param options - Optional settings
338
+ *
339
+ * @example
340
+ * ```js
341
+ * const { EJSON } = require('bson');
342
+ * const Int32 = require('mongodb').Int32;
343
+ * const doc = { int32: new Int32(10) };
344
+ *
345
+ * // prints '{"int32":{"$numberInt":"10"}}'
346
+ * console.log(EJSON.stringify(doc, { relaxed: false }));
347
+ *
348
+ * // prints '{"int32":10}'
349
+ * console.log(EJSON.stringify(doc));
350
+ * ```
351
+ */
352
+ export function stringify(
353
+ value: SerializableTypes,
354
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
355
+ replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSON.Options,
356
+ space?: string | number,
357
+ options?: EJSON.Options
358
+ ): string {
359
+ if (space != null && typeof space === 'object') {
360
+ options = space;
361
+ space = 0;
362
+ }
363
+ if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
364
+ options = replacer;
365
+ replacer = undefined;
366
+ space = 0;
367
+ }
368
+ options = Object.assign({}, { relaxed: true, legacy: false }, options);
369
+
370
+ const doc = serializeValue(value, options);
371
+ return JSON.stringify(doc, replacer as Parameters<JSON['stringify']>[1], space);
372
+ }
373
+
374
+ /**
375
+ * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
376
+ *
377
+ * @param value - The object to serialize
378
+ * @param options - Optional settings passed to the `stringify` function
379
+ */
380
+ export function serialize(value: SerializableTypes, options?: EJSON.Options): Document {
381
+ options = options || {};
382
+ return JSON.parse(stringify(value, options));
383
+ }
384
+
385
+ /**
386
+ * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
387
+ *
388
+ * @param ejson - The Extended JSON object to deserialize
389
+ * @param options - Optional settings passed to the parse method
390
+ */
391
+ export function deserialize(ejson: Document, options?: EJSON.Options): SerializableTypes {
392
+ options = options || {};
393
+ return parse(JSON.stringify(ejson), options);
394
+ }
395
+ }
@@ -0,0 +1,152 @@
1
+ // Copyright (c) 2008, Fair Oaks Labs, Inc.
2
+ // All rights reserved.
3
+ //
4
+ // Redistribution and use in source and binary forms, with or without
5
+ // modification, are permitted provided that the following conditions are met:
6
+ //
7
+ // * Redistributions of source code must retain the above copyright notice,
8
+ // this list of conditions and the following disclaimer.
9
+ //
10
+ // * Redistributions in binary form must reproduce the above copyright notice,
11
+ // this list of conditions and the following disclaimer in the documentation
12
+ // and/or other materials provided with the distribution.
13
+ //
14
+ // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors
15
+ // may be used to endorse or promote products derived from this software
16
+ // without specific prior written permission.
17
+ //
18
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
+ // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22
+ // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23
+ // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24
+ // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25
+ // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26
+ // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27
+ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
+ // POSSIBILITY OF SUCH DAMAGE.
29
+ //
30
+ //
31
+ // Modifications to writeIEEE754 to support negative zeroes made by Brian White
32
+
33
+ type NumericalSequence = { [index: number]: number };
34
+
35
+ export function readIEEE754(
36
+ buffer: NumericalSequence,
37
+ offset: number,
38
+ endian: 'big' | 'little',
39
+ mLen: number,
40
+ nBytes: number
41
+ ): number {
42
+ let e: number;
43
+ let m: number;
44
+ const bBE = endian === 'big';
45
+ const eLen = nBytes * 8 - mLen - 1;
46
+ const eMax = (1 << eLen) - 1;
47
+ const eBias = eMax >> 1;
48
+ let nBits = -7;
49
+ let i = bBE ? 0 : nBytes - 1;
50
+ const d = bBE ? 1 : -1;
51
+ let s = buffer[offset + i];
52
+
53
+ i += d;
54
+
55
+ e = s & ((1 << -nBits) - 1);
56
+ s >>= -nBits;
57
+ nBits += eLen;
58
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
59
+
60
+ m = e & ((1 << -nBits) - 1);
61
+ e >>= -nBits;
62
+ nBits += mLen;
63
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
64
+
65
+ if (e === 0) {
66
+ e = 1 - eBias;
67
+ } else if (e === eMax) {
68
+ return m ? NaN : (s ? -1 : 1) * Infinity;
69
+ } else {
70
+ m = m + Math.pow(2, mLen);
71
+ e = e - eBias;
72
+ }
73
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
74
+ }
75
+
76
+ export function writeIEEE754(
77
+ buffer: NumericalSequence,
78
+ value: number,
79
+ offset: number,
80
+ endian: 'big' | 'little',
81
+ mLen: number,
82
+ nBytes: number
83
+ ): void {
84
+ let e: number;
85
+ let m: number;
86
+ let c: number;
87
+ const bBE = endian === 'big';
88
+ let eLen = nBytes * 8 - mLen - 1;
89
+ const eMax = (1 << eLen) - 1;
90
+ const eBias = eMax >> 1;
91
+ const rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
92
+ let i = bBE ? nBytes - 1 : 0;
93
+ const d = bBE ? -1 : 1;
94
+ const s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
95
+
96
+ value = Math.abs(value);
97
+
98
+ if (isNaN(value) || value === Infinity) {
99
+ m = isNaN(value) ? 1 : 0;
100
+ e = eMax;
101
+ } else {
102
+ e = Math.floor(Math.log(value) / Math.LN2);
103
+ if (value * (c = Math.pow(2, -e)) < 1) {
104
+ e--;
105
+ c *= 2;
106
+ }
107
+ if (e + eBias >= 1) {
108
+ value += rt / c;
109
+ } else {
110
+ value += rt * Math.pow(2, 1 - eBias);
111
+ }
112
+ if (value * c >= 2) {
113
+ e++;
114
+ c /= 2;
115
+ }
116
+
117
+ if (e + eBias >= eMax) {
118
+ m = 0;
119
+ e = eMax;
120
+ } else if (e + eBias >= 1) {
121
+ m = (value * c - 1) * Math.pow(2, mLen);
122
+ e = e + eBias;
123
+ } else {
124
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
125
+ e = 0;
126
+ }
127
+ }
128
+
129
+ if (isNaN(value)) m = 0;
130
+
131
+ while (mLen >= 8) {
132
+ buffer[offset + i] = m & 0xff;
133
+ i += d;
134
+ m /= 256;
135
+ mLen -= 8;
136
+ }
137
+
138
+ e = (e << mLen) | m;
139
+
140
+ if (isNaN(value)) e += 8;
141
+
142
+ eLen += mLen;
143
+
144
+ while (eLen > 0) {
145
+ buffer[offset + i] = e & 0xff;
146
+ i += d;
147
+ e /= 256;
148
+ eLen -= 8;
149
+ }
150
+
151
+ buffer[offset + i - d] |= s * 128;
152
+ }