UNPKG

23.4 kBTypeScriptView Raw
1// Type definitions for bson 4.0
2// Project: https://github.com/mongodb/js-bson
3// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi>
4// Federico Caselli <https://github.com/CaselIT>
5// Justin Grant <https://github.com/justingrant>
6// Mikael Lirbank <https://github.com/lirbank>
7// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
8
9/// <reference types="node"/>
10
11interface CommonSerializeOptions {
12 /** {default:false}, the serializer will check if keys are valid. */
13 checkKeys?: boolean | undefined;
14 /** {default:false}, serialize the javascript functions. */
15 serializeFunctions?: boolean | undefined;
16 /** {default:true}, ignore undefined fields. */
17 ignoreUndefined?: boolean | undefined;
18}
19
20export interface SerializeOptions extends CommonSerializeOptions {
21 /** {default:1024*1024*17}, minimum size of the internal temporary serialization buffer. */
22 minInternalBufferSize?: number | undefined;
23}
24
25export interface SerializeWithBufferAndIndexOptions extends CommonSerializeOptions {
26 /** {default:0}, the index in the buffer where we wish to start serializing into. */
27 index?: number | undefined;
28}
29
30export interface DeserializeOptions {
31 /** {default:false}, evaluate functions in the BSON document scoped to the object deserialized. */
32 evalFunctions?: boolean | undefined;
33 /** {default:false}, cache evaluated functions for reuse. */
34 cacheFunctions?: boolean | undefined;
35 /** {default:false}, use a crc32 code for caching, otherwise use the string of the function. */
36 cacheFunctionsCrc32?: boolean | undefined;
37 /** {default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits. */
38 promoteLongs?: boolean | undefined;
39 /** {default:false}, deserialize Binary data directly into node.js Buffer object. */
40 promoteBuffers?: boolean | undefined;
41 /** {default:false}, when deserializing will promote BSON values to their Node.js closest equivalent types. */
42 promoteValues?: boolean | undefined;
43 /** {default:null}, allow to specify if there what fields we wish to return as unserialized raw buffer. */
44 fieldsAsRaw?: { readonly [fieldName: string]: boolean } | undefined;
45 /** {default:false}, return BSON regular expressions as BSONRegExp instances. */
46 bsonRegExp?: boolean | undefined;
47 /** {default:false}, allows the buffer to be larger than the parsed BSON object. */
48 allowObjectSmallerThanBufferSize?: boolean | undefined;
49}
50
51export interface CalculateObjectSizeOptions {
52 /** {default:false}, serialize the javascript functions */
53 serializeFunctions?: boolean | undefined;
54 /** {default:true}, ignore undefined fields. */
55 ignoreUndefined?: boolean | undefined;
56}
57
58
59/**
60 * Serialize a Javascript object.
61 *
62 * @param object The Javascript object to serialize.
63 * @param options Serialize options.
64 * @return The Buffer object containing the serialized object.
65 */
66export function serialize(object: any, options?: SerializeOptions): Buffer;
67
68/**
69 * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.
70 *
71 * @param object The Javascript object to serialize.
72 * @param buffer The Buffer you pre-allocated to store the serialized BSON object.
73 * @param options Serialize options.
74 * @returns The index pointing to the last written byte in the buffer
75 */
76export function serializeWithBufferAndIndex(object: any, buffer: Buffer, options?: SerializeWithBufferAndIndexOptions): number;
77
78/**
79 * Deserialize data as BSON.
80 *
81 * @param buffer The buffer containing the serialized set of BSON documents.
82 * @param options Deserialize options.
83 * @returns The deserialized Javascript Object.
84 */
85export function deserialize(buffer: Buffer, options?: DeserializeOptions): any;
86
87/**
88 * Calculate the bson size for a passed in Javascript object.
89 *
90 * @param {Object} object the Javascript object to calculate the BSON byte size for.
91 * @param {CalculateObjectSizeOptions} Options
92 * @return {Number} returns the number of bytes the BSON object will take up.
93 */
94export function calculateObjectSize(object: any, options?: CalculateObjectSizeOptions): number;
95
96/**
97 * Deserialize stream data as BSON documents.
98 *
99 * @param data The buffer containing the serialized set of BSON documents.
100 * @param startIndex The start index in the data Buffer where the deserialization is to start.
101 * @param numberOfDocuments Number of documents to deserialize
102 * @param documents An array where to store the deserialized documents
103 * @param docStartIndex The index in the documents array from where to start inserting documents
104 * @param options Additional options used for the deserialization
105 * @returns The next index in the buffer after deserialization of the `numberOfDocuments`
106 */
107export function deserializeStream(
108 data: Buffer,
109 startIndex: number,
110 numberOfDocuments: number,
111 documents: Array<any>,
112 docStartIndex: number,
113 options?: DeserializeOptions
114): number;
115
116/** A class representation of the BSON Binary type. */
117export class Binary {
118
119 static readonly SUBTYPE_DEFAULT: number;
120 static readonly SUBTYPE_FUNCTION: number;
121 static readonly SUBTYPE_BYTE_ARRAY: number;
122 static readonly SUBTYPE_UUID_OLD: number;
123 static readonly SUBTYPE_UUID: number;
124 static readonly SUBTYPE_MD5: number;
125 static readonly SUBTYPE_USER_DEFINED: number;
126
127 /**
128 * @param buffer A buffer object containing the binary data
129 * @param subType Binary data subtype
130 */
131 constructor(buffer: Buffer, subType?: number);
132
133 /** The underlying Buffer which stores the binary data. */
134 readonly buffer: Buffer;
135 /** Binary data subtype */
136 readonly sub_type?: number | undefined;
137
138 /** The length of the binary. */
139 length(): number;
140 /** Updates this binary with byte_value */
141 put(byte_value: number | string): void;
142 /** Reads length bytes starting at position. */
143 read(position: number, length: number): Buffer;
144 /** Returns the value of this binary as a string. */
145 value(): string;
146 /** Writes a buffer or string to the binary */
147 write(buffer: Buffer | string, offset: number): void;
148}
149
150/** A class representation of the BSON Code type. */
151export class Code {
152
153 /**
154 * @param code A string or function.
155 * @param scope An optional scope for the function.
156 */
157 constructor(code: string | Function, scope?: any);
158
159 readonly code: string | Function;
160 readonly scope?: any;
161
162}
163
164/**
165 * A class representation of the BSON DBRef type.
166 */
167export class DBRef {
168 /**
169 * @param namespace The collection name.
170 * @param oid The reference ObjectId.
171 * @param db Optional db name, if omitted the reference is local to the current db
172 */
173 constructor(namespace: string, oid: ObjectId, db?: string);
174 namespace: string;
175 oid: ObjectId;
176 db?: string | undefined;
177}
178
179/** A class representation of the BSON Double type. */
180export class Double {
181 /**
182 * @param value The number we want to represent as a double.
183 */
184 constructor(value: number);
185
186 /**
187 * https://github.com/mongodb/js-bson/blob/master/lib/double.js#L17
188 */
189 value: number;
190
191
192 valueOf(): number;
193}
194
195/** A class representation of the BSON Int32 type. */
196export class Int32 {
197 /**
198 * @param value The number we want to represent as an int32.
199 */
200 constructor(value: number);
201
202 valueOf(): number;
203}
204
205/**
206 * Base class for Long and Timestamp.
207 * In original js-node@1.0.x code 'Timestamp' is a 100% copy-paste of 'Long'
208 * with 'Long' replaced by 'Timestamp' (changed to inheritance in js-node@2.0.0)
209 */
210declare class LongLike<T> {
211
212 /**
213 * @param low The low (signed) 32 bits.
214 * @param high The high (signed) 32 bits.
215 */
216 constructor(low: number, high: number);
217
218 /** Returns the sum of `this` and the `other`. */
219 add(other: T): T;
220 /** Returns the bitwise-AND of `this` and the `other`. */
221 and(other: T): T;
222 /**
223 * Compares `this` with the given `other`.
224 * @returns 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.
225 */
226 compare(other: T): number;
227 /** Returns `this` divided by the given `other`. */
228 div(other: T): T;
229 /** Return whether `this` equals the `other` */
230 equals(other: T): boolean;
231 /** Return the high 32-bits value. */
232 getHighBits(): number;
233 /** Return the low 32-bits value. */
234 getLowBits(): number;
235 /** Return the low unsigned 32-bits value. */
236 getLowBitsUnsigned(): number;
237 /** Returns the number of bits needed to represent the absolute value of `this`. */
238 getNumBitsAbs(): number;
239 /** Return whether `this` is greater than the `other`. */
240 greaterThan(other: T): boolean;
241 /** Return whether `this` is greater than or equal to the `other`. */
242 greaterThanOrEqual(other: T): boolean;
243 /** Return whether `this` value is negative. */
244 isNegative(): boolean;
245 /** Return whether `this` value is odd. */
246 isOdd(): boolean;
247 /** Return whether `this` value is zero. */
248 isZero(): boolean;
249 /** Return whether `this` is less than the `other`. */
250 lessThan(other: T): boolean;
251 /** Return whether `this` is less than or equal to the `other`. */
252 lessThanOrEqual(other: T): boolean;
253 /** Returns `this` modulo the given `other`. */
254 modulo(other: T): T;
255 /** Returns the product of `this` and the given `other`. */
256 multiply(other: T): T;
257 /** The negation of this value. */
258 negate(): T;
259 /** The bitwise-NOT of this value. */
260 not(): T;
261 /** Return whether `this` does not equal to the `other`. */
262 notEquals(other: T): boolean;
263 /** Returns the bitwise-OR of `this` and the given `other`. */
264 or(other: T): T;
265 /**
266 * Returns `this` with bits shifted to the left by the given amount.
267 * @param numBits The number of bits by which to shift.
268 */
269 shiftLeft(numBits: number): T;
270 /**
271 * Returns `this` with bits shifted to the right by the given amount.
272 * @param numBits The number of bits by which to shift.
273 */
274 shiftRight(numBits: number): T;
275 /**
276 * Returns `this` with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.
277 * @param numBits The number of bits by which to shift.
278 */
279 shiftRightUnsigned(numBits: number): T;
280 /** Returns the difference of `this` and the given `other`. */
281 subtract(other: T): T;
282 /** Return the int value (low 32 bits). */
283 toInt(): number;
284 /** Return the JSON value. */
285 toJSON(): string;
286 /** Returns closest floating-point representation to `this` value */
287 toNumber(): number;
288 /**
289 * Return as a string
290 * @param radix the radix in which the text should be written. {default:10}
291 */
292 toString(radix?: number): string;
293 /** Returns the bitwise-XOR of `this` and the given `other`. */
294 xor(other: T): T;
295
296}
297
298/**
299 * A class representation of the BSON Long type, a 64-bit two's-complement
300 * integer value, which faithfully simulates the behavior of a Java "Long". This
301 * implementation is derived from LongLib in GWT.
302 */
303export class Long extends LongLike<Long> {
304
305 static readonly MAX_VALUE: Long;
306 static readonly MIN_VALUE: Long;
307 static readonly NEG_ONE: Long;
308 static readonly ONE: Long;
309 static readonly ZERO: Long;
310
311 /** Returns a Long representing the given (32-bit) integer value. */
312 static fromInt(i: number): Long;
313 /** Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. */
314 static fromNumber(n: number): Long;
315 /**
316 * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
317 * @param lowBits The low 32-bits.
318 * @param highBits The high 32-bits.
319 */
320 static fromBits(lowBits: number, highBits: number): Long;
321 /**
322 * Returns a Long representation of the given string
323 * @param opt_radix The radix in which the text is written. {default:10}
324 */
325 static fromString(s: string, opt_radix?: number): Long;
326
327}
328
329/** A class representation of the BSON Decimal128 type. */
330export class Decimal128 {
331
332 /** Create a Decimal128 instance from a string representation. */
333 static fromString(s: string): Decimal128;
334
335 /**
336 * @param bytes A buffer containing the raw Decimal128 bytes.
337 */
338 constructor(bytes: Buffer);
339
340 /** A buffer containing the raw Decimal128 bytes. */
341 readonly bytes: Buffer;
342
343 toJSON(): string;
344 toString(): string;
345}
346
347/** A class representation of the BSON MaxKey type. */
348export class MaxKey {
349 constructor();
350}
351
352/** A class representation of the BSON MinKey type. */
353export class MinKey {
354 constructor();
355}
356
357/** A class representation of the BSON ObjectId type. */
358export class ObjectId {
359 /**
360 * Create a new ObjectId instance
361 * @param {(string|number|ObjectId)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
362 */
363 constructor(id?: string | number | ObjectId);
364 /** The generation time of this ObjectId instance */
365 generationTime: number;
366 /** If true cache the hex string representation of ObjectId */
367 static cacheHexString?: boolean | undefined;
368 /**
369 * Creates an ObjectId from a hex string representation of an ObjectId.
370 * @param {string} hexString create a ObjectId from a passed in 24 byte hexstring.
371 * @return {ObjectId} return the created ObjectId
372 */
373 static createFromHexString(hexString: string): ObjectId;
374 /**
375 * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
376 * @param {number} time an integer number representing a number of seconds.
377 * @return {ObjectId} return the created ObjectId
378 */
379 static createFromTime(time: number): ObjectId;
380 /**
381 * Checks if a value is a valid bson ObjectId
382 *
383 * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
384 */
385 static isValid(id: string | number | ObjectId): boolean;
386 /**
387 * Compares the equality of this ObjectId with `otherID`.
388 * @param {ObjectId|string} otherID ObjectId instance to compare against.
389 * @return {boolean} the result of comparing two ObjectId's
390 */
391 equals(otherID: ObjectId | string): boolean;
392 /**
393 * Generate a 12 byte id string used in ObjectId's
394 * @param {number} time optional parameter allowing to pass in a second based timestamp.
395 * @return {string} return the 12 byte id binary string.
396 */
397 static generate(time?: number): Buffer;
398
399 /**
400 * Converts the id into a 24 character hex string for printing
401 *
402 * @param format - The Buffer toString format parameter.
403 * @internal
404 */
405 toString(format?: string): string;
406
407 /**
408 * Returns the generation date (accurate up to the second) that this ID was generated.
409 * @return {Date} the generation date
410 */
411 getTimestamp(): Date;
412 /**
413 * Return the ObjectId id as a 24 byte hex string representation
414 * @return {string} return the 24 byte hex string representation.
415 */
416 toHexString(): string;
417}
418
419/**
420 * ObjectID (with capital "D") is deprecated. Use ObjectId (lowercase "d") instead.
421 * @deprecated
422 */
423export { ObjectId as ObjectID };
424
425/** A class representation of the BSON RegExp type. */
426export class BSONRegExp {
427
428 constructor(pattern: string, options: string);
429
430 readonly pattern: string;
431 readonly options: string;
432
433}
434
435/**
436 * A class representation of the BSON Symbol type.
437 * @deprecated
438 */
439export class Symbol {
440
441 constructor(value: string);
442
443 /** Access the wrapped string value. */
444 valueOf(): string;
445
446}
447
448/** A class representation of the BSON Timestamp type. */
449export class Timestamp extends LongLike<Timestamp> {
450
451 static readonly MAX_VALUE: Timestamp;
452 static readonly MIN_VALUE: Timestamp;
453 static readonly NEG_ONE: Timestamp;
454 static readonly ONE: Timestamp;
455 static readonly ZERO: Timestamp;
456
457 /** Returns a Timestamp represented by the given (32-bit) integer value */
458 static fromInt(value: number): Timestamp;
459 /** Returns a Timestamp representing the given number value, provided that it is a finite number. */
460 static fromNumber(value: number): Timestamp;
461 /**
462 * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
463 * @param lowBits The low 32-bits.
464 * @param highBits The high 32-bits.
465 */
466 static fromBits(lowBits: number, highBits: number): Timestamp;
467 /**
468 * Returns a Timestamp from the given string.
469 * @param opt_radix The radix in which the text is written. {default:10}
470 */
471 static fromString(str: string, opt_radix?: number): Timestamp;
472
473}
474
475/**
476 * Functions for serializing JavaScript objects into Mongodb Extended JSON (EJSON).
477 * @namespace EJSON
478 */
479export namespace EJSON {
480
481 /**
482 * Parse an Extended JSON string, constructing the JavaScript value or object described by that
483 * string.
484 *
485 * @memberof EJSON
486 * @param {string} text
487 * @param {object} [options] Optional settings
488 * @param {boolean} [options.relaxed=true] Attempt to return native JS types where possible, rather than BSON types (if true)
489 * @return {object}
490 *
491 * @example
492 * const { EJSON } = require('bson');
493 * const text = '{ "int32": { "$numberInt": "10" } }';
494 *
495 * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
496 * console.log(EJSON.parse(text, { relaxed: false }));
497 *
498 * // prints { int32: 10 }
499 * console.log(EJSON.parse(text));
500 */
501 export function parse(text: string, options?: {relaxed?: boolean | undefined;}): {};
502
503 /**
504 * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
505 *
506 * @memberof EJSON
507 * @param {object} ejson The Extended JSON object to deserialize
508 * @param {object} [options] Optional settings passed to the parse method
509 * @return {object}
510 */
511 export function deserialize(ejson: {}, options?: {relaxed?: boolean | undefined;}): {};
512
513 /**
514 * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
515 *
516 * @memberof EJSON
517 * @param {object} bson The object to serialize
518 * @param {object} [options] Optional settings passed to the `stringify` function
519 * @return {object}
520 */
521 export function serialize(bson: {}, options?: {relaxed?: boolean | undefined;}): {};
522
523 /**
524 * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
525 * function is specified or optionally including only the specified properties if a replacer array
526 * is specified.
527 *
528 * @memberof EJSON
529 * @param {object} value The value to convert to extended JSON
530 * @param {function|array} [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
531 * @param {string|number} [space] A String or Number object that's used to insert white space into the output JSON string for readability purposes.
532 * @param {object} [options] Optional settings.
533 * @param {boolean} [options.relaxed=true] Enabled Extended JSON's `relaxed` mode
534 * @returns {string}
535 *
536 * @example
537 * const { EJSON, Int32 } = require('bson');
538 * const doc = { int32: new Int32(10) };
539 *
540 * // prints '{"int32":{"$numberInt":"10"}}'
541 * console.log(EJSON.stringify(doc, { relaxed: false }));
542 *
543 * // prints '{"int32":10}'
544 * console.log(EJSON.stringify(doc));
545 */
546 export function stringify(
547 value: {},
548 options?: {relaxed?: boolean | undefined;}
549 ): string;
550
551 /**
552 * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
553 * function is specified or optionally including only the specified properties if a replacer array
554 * is specified.
555 *
556 * @memberof EJSON
557 * @param {object} value The value to convert to extended JSON
558 * @param {function|array} [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
559 * @param {string|number} [space] A String or Number object that's used to insert white space into the output JSON string for readability purposes.
560 * @param {object} [options] Optional settings.
561 * @param {boolean} [options.relaxed=true] Enabled Extended JSON's `relaxed` mode
562 * @returns {string}
563 *
564 * @example
565 * const { EJSON, Int32 } = require('bson');
566 * const doc = { int32: new Int32(10) };
567 *
568 * // prints '{"int32":{"$numberInt":"10"}}'
569 * console.log(EJSON.stringify(doc, { relaxed: false }));
570 *
571 * // prints '{"int32":10}'
572 * console.log(EJSON.stringify(doc));
573 */
574
575 export function stringify(
576 value: {},
577 replacer: ((key: string, value: any) => any) | Array<string|number> | null | undefined,
578 options?: {relaxed?: boolean | undefined;}
579 ): string;
580 /**
581 * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
582 * function is specified or optionally including only the specified properties if a replacer array
583 * is specified.
584 *
585 * @memberof EJSON
586 * @param {object} value The value to convert to extended JSON
587 * @param {function|array} [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
588 * @param {string|number} [space] A String or Number object that's used to insert white space into the output JSON string for readability purposes.
589 * @param {object} [options] Optional settings.
590 * @param {boolean} [options.relaxed=true] Enabled Extended JSON's `relaxed` mode
591 * @returns {string}
592 *
593 * @example
594 * const { EJSON, Int32 } = require('bson');
595 * const doc = { int32: new Int32(10) };
596 *
597 * // prints '{"int32":{"$numberInt":"10"}}'
598 * console.log(EJSON.stringify(doc, { relaxed: false }));
599 *
600 * // prints '{"int32":10}'
601 * console.log(EJSON.stringify(doc));
602 */
603 export function stringify(
604 value: {},
605 replacer: ((key: string, value: any) => any) | Array<string | number> | null | undefined,
606 indents?: string | number,
607 options?: {relaxed?: boolean | undefined;}
608 ): string;
609}