Socket
Socket
Sign inDemoInstall

bson

Package Overview
Dependencies
Maintainers
6
Versions
162
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bson - npm Package Compare versions

Comparing version 5.0.0-alpha.1 to 5.0.0-alpha.2

31

bson.d.ts

@@ -145,3 +145,2 @@ /**

BSONError,
BSONTypeError,
BSONType,

@@ -155,6 +154,20 @@ EJSON,

/** @public */
/**
* @public
* `BSONError` objects are thrown when runtime errors occur.
*/
export declare class BSONError extends Error {
/* Excluded from this release type: bsonError */
get name(): string;
constructor(message: string);
get name(): string;
/**
* @public
*
* All errors thrown from the BSON library inherit from `BSONError`.
* This method can assist with determining if an error originates from the BSON library
* even if it does not pass an `instanceof` check against this class' constructor.
*
* @param value - any javascript value that needs type checking
*/
static isBSONError(value: unknown): value is BSONError;
}

@@ -250,8 +263,2 @@

/** @public */
export declare class BSONTypeError extends TypeError {
constructor(message: string);
get name(): string;
}
/**

@@ -373,3 +380,5 @@ * Calculate the bson size for a passed in Javascript object.

export declare interface DeserializeOptions {
/** when deserializing a Long will fit it into a Number if it's smaller than 53 bits */
/** when deserializing a Long will return as a BigInt. */
useBigInt64?: boolean;
/** when deserializing a Long will fit it into a Number if it's smaller than 53 bits. */
promoteLongs?: boolean;

@@ -384,3 +393,3 @@ /** when deserializing a Binary will return it as a node.js Buffer instance. */

bsonRegExp?: boolean;
/** allows the buffer to be larger than the parsed BSON object */
/** allows the buffer to be larger than the parsed BSON object. */
allowObjectSmallerThanBufferSize?: boolean;

@@ -387,0 +396,0 @@ /** Offset into buffer to begin reading document from */

@@ -16,3 +16,3 @@ {

"types": "bson.d.ts",
"version": "5.0.0-alpha.1",
"version": "5.0.0-alpha.2",
"author": {

@@ -79,7 +79,7 @@ "name": "The MongoDB NodeJS Team",

"module": "./lib/bson.mjs",
"browser": "./lib/bson.mjs",
"exports": {
"browser": "./lib/bson.mjs",
"import": "./lib/bson.mjs",
"require": "./lib/bson.cjs"
"require": "./lib/bson.cjs",
"react-native": "./lib/bson.cjs",
"browser": "./lib/bson.mjs"
},

@@ -86,0 +86,0 @@ "engines": {

# BSON parser
BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. You can learn more about it in [the specification](http://bsonspec.org).
BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents.
You can learn more about it in [the specification](http://bsonspec.org).
This browser version of the BSON parser is compiled using [rollup](https://rollupjs.org/) and the current version is pre-compiled in the `dist` directory.
This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext).
### Table of Contents

@@ -35,103 +32,40 @@ - [Usage](#usage)

### Node (no bundling)
A simple example of how to use BSON in `Node.js`:
### Node.js or Bundling Usage
When using a bundler or Node.js you can import bson using the package name:
```js
const BSON = require('bson');
const Long = BSON.Long;
import { BSON, EJSON, ObjectId } from 'bson';
// or:
// const { BSON, EJSON, ObjectId } = require('bson');
// Serialize a document
const doc = { long: Long.fromNumber(100) };
const data = BSON.serialize(doc);
console.log('data:', data);
// Deserialize the resulting Buffer
const doc_2 = BSON.deserialize(data);
console.log('doc_2:', doc_2);
const bytes = BSON.serialize({ _id: new ObjectId() });
console.log(bytes);
const doc = BSON.deserialize(bytes);
console.log(EJSON.stringify(doc));
// {"_id":{"$oid":"..."}}
```
### Browser (no bundling)
### Browser Usage
If you are not using a bundler like webpack, you can include `dist/bson.bundle.js` using a script tag. It includes polyfills for built-in node types like `Buffer`.
If you are working directly in the browser without a bundler please use the `.mjs` bundle like so:
```html
<script src="./dist/bson.bundle.js"></script>
<script type="module">
import { BSON, EJSON, ObjectId } from './lib/bson.mjs';
<script>
function start() {
// Get the Long type
const Long = BSON.Long;
// Serialize a document
const doc = { long: Long.fromNumber(100) }
const data = BSON.serialize(doc);
console.log('data:', data);
// De serialize it again
const doc_2 = BSON.deserialize(data);
console.log('doc_2:', doc_2);
}
const bytes = BSON.serialize({ _id: new ObjectId() });
console.log(bytes);
const doc = BSON.deserialize(bytes);
console.log(EJSON.stringify(doc));
// {"_id":{"$oid":"..."}}
</script>
```
### Using webpack
## Installation
If using webpack, you can use your normal import/require syntax of your project to pull in the `bson` library.
ES6 Example:
```js
import { Long, serialize, deserialize } from 'bson';
// Serialize a document
const doc = { long: Long.fromNumber(100) };
const data = serialize(doc);
console.log('data:', data);
// De serialize it again
const doc_2 = deserialize(data);
console.log('doc_2:', doc_2);
```sh
npm install bson
```
ES5 Example:
```js
const BSON = require('bson');
const Long = BSON.Long;
// Serialize a document
const doc = { long: Long.fromNumber(100) };
const data = BSON.serialize(doc);
console.log('data:', data);
// Deserialize the resulting Buffer
const doc_2 = BSON.deserialize(data);
console.log('doc_2:', doc_2);
```
Depending on your settings, webpack will under the hood resolve to one of the following:
- `dist/bson.browser.esm.js` If your project is in the browser and using ES6 modules (Default for `webworker` and `web` targets)
- `dist/bson.browser.umd.js` If your project is in the browser and not using ES6 modules
- `dist/bson.esm.js` If your project is in Node.js and using ES6 modules (Default for `node` targets)
- `lib/bson.js` (the normal include path) If your project is in Node.js and not using ES6 modules
For more information, see [this page on webpack's `resolve.mainFields`](https://webpack.js.org/configuration/resolve/#resolvemainfields) and [the `package.json` for this project](./package.json#L52)
### Usage with Angular
Starting with Angular 6, Angular CLI removed the shim for `global` and other node built-in variables (original comment [here](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063)). If you are using BSON with Angular, you may need to add the following shim to your `polyfills.ts` file:
```js
// In polyfills.ts
(window as any).global = window;
```
- [Original Comment by Angular CLI](https://github.com/angular/angular-cli/issues/9827#issuecomment-386154063)
- [Original Source for Solution](https://stackoverflow.com/a/50488337/4930088)
## Installation
`npm install bson`
## Documentation

@@ -308,2 +242,3 @@

| [options.cacheFunctions] | <code>Object</code> | <code>false</code> | cache evaluated functions for reuse. |
| [options.useBigInt64] | <code>Object</code> | <code>false</code> | when deserializing a Long will return a BigInt. |
| [options.promoteLongs] | <code>Object</code> | <code>true</code> | when deserializing a Long will fit it into a Number if it's smaller than 53 bits |

@@ -314,3 +249,3 @@ | [options.promoteBuffers] | <code>Object</code> | <code>false</code> | when deserializing a Binary will return it as a node.js Buffer instance. |

| [options.bsonRegExp] | <code>Object</code> | <code>false</code> | return BSON regular expressions as BSONRegExp instances. |
| [options.allowObjectSmallerThanBufferSize] | <code>boolean</code> | <code>false</code> | allows the buffer to be larger than the parsed BSON object |
| [options.allowObjectSmallerThanBufferSize] | <code>boolean</code> | <code>false</code> | allows the buffer to be larger than the parsed BSON object. |

@@ -357,2 +292,59 @@ Deserialize data as BSON.

## Error Handling
It is our recommendation to use `BSONError.isBSONError()` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code. We guarantee `BSONError.isBSONError()` checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.
Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release.
This means `BSONError.isBSONError()` will always be able to accurately capture the errors that our BSON library throws.
Hypothetical example: A collection in our Db has an issue with UTF-8 data:
```ts
let documentCount = 0;
const cursor = collection.find({}, { utf8Validation: true });
try {
for await (const doc of cursor) documentCount += 1;
} catch (error) {
if (BSONError.isBSONError(error)) {
console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`);
return documentCount;
}
throw error;
}
```
## React Native
BSON requires that `TextEncoder`, `TextDecoder`, `atob`, `btoa`, and `crypto.getRandomValues` are available globally. These are present in most Javascript runtimes but require polyfilling in React Native. Polyfills for the missing functionality can be installed with the following command:
```sh
npm install --save react-native-get-random-values text-encoding-polyfill base-64
```
The following snippet should be placed at the top of the entrypoint (by default this is the root `index.js` file) for React Native projects using the BSON library. These lines must be placed for any code that imports `BSON`.
```typescript
// Required Polyfills For ReactNative
import {encode, decode} from 'base-64';
if (global.btoa == null) {
global.btoa = encode;
}
if (global.atob == null) {
global.atob = decode;
}
import 'text-encoding-polyfill';
import 'react-native-get-random-values';
```
Finally, import the `BSON` library like so:
```typescript
import { BSON, EJSON } from 'bson';
```
This will cause React Native to import the `node_modules/bson/lib/bson.cjs` bundle (see the `"react-native"` setting we have in the `"exports"` section of our [package.json](./package.json).)
### Technical Note about React Native module import
The `"exports"` definition in our `package.json` will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in [React Native's runtime hermes](https://hermesengine.dev/).
## FAQ

@@ -359,0 +351,0 @@

import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils';
import { isUint8Array } from './parser/utils';
import type { EJSONOptions } from './extended_json';
import { BSONError, BSONTypeError } from './error';
import { BSONError } from './error';
import { BSON_BINARY_SUBTYPE_UUID_NEW, BSON_MAJOR_VERSION } from './constants';

@@ -89,3 +89,3 @@ import { ByteUtils } from './utils/byte_utils';

) {
throw new BSONTypeError(
throw new BSONError(
'Binary can only be constructed from string, Buffer, TypedArray, or Array<number>'

@@ -125,5 +125,5 @@ );

if (typeof byteValue === 'string' && byteValue.length !== 1) {
throw new BSONTypeError('only accepts single character String');
throw new BSONError('only accepts single character String');
} else if (typeof byteValue !== 'number' && byteValue.length !== 1)
throw new BSONTypeError('only accepts single character Uint8Array or Array');
throw new BSONError('only accepts single character Uint8Array or Array');

@@ -141,3 +141,3 @@ // Decode the byte value once

if (decodedByte < 0 || decodedByte > 255) {
throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255');
throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
}

@@ -289,3 +289,3 @@

if (!data) {
throw new BSONTypeError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
}

@@ -344,3 +344,3 @@ return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);

} else {
throw new BSONTypeError(
throw new BSONError(
'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).'

@@ -347,0 +347,0 @@ );

@@ -52,3 +52,3 @@ import { Binary, UUID } from './binary';

};
export { BSONError, BSONTypeError } from './error';
export { BSONError } from './error';
export { BSONType } from './constants';

@@ -55,0 +55,0 @@ export { EJSON } from './extended_json';

import { BSON_MAJOR_VERSION } from './constants';
import { BSONTypeError } from './error';
import { BSONError } from './error';
import { Long } from './long';

@@ -117,3 +117,3 @@ import { isUint8Array } from './parser/utils';

function invalidErr(string: string, message: string) {
throw new BSONTypeError(`"${string}" is not a valid Decimal128 string - ${message}`);
throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
}

@@ -151,7 +151,7 @@

if (bytes.byteLength !== 16) {
throw new BSONTypeError('Decimal128 must take a Buffer of 16 bytes');
throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
}
this.bytes = bytes;
} else {
throw new BSONTypeError('Decimal128 must take a Buffer or string');
throw new BSONError('Decimal128 must take a Buffer or string');
}

@@ -211,3 +211,3 @@ }

if (representation.length >= 7000) {
throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
throw new BSONError('' + representation + ' not a valid Decimal128 string');
}

@@ -222,3 +222,3 @@

if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
throw new BSONError('' + representation + ' not a valid Decimal128 string');
}

@@ -295,3 +295,3 @@

if (sawRadix && !nDigitsRead)
throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
throw new BSONError('' + representation + ' not a valid Decimal128 string');

@@ -298,0 +298,0 @@ // Read exponent if exists

@@ -60,19 +60,11 @@ import { BSON_MAJOR_VERSION } from './constants';

// NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
// explicitly provided `-0` then we need to ensure the sign makes it into the output
if (Object.is(Math.sign(this.value), -0)) {
return { $numberDouble: `-${this.value.toFixed(1)}` };
// NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
// explicitly provided `-0` then we need to ensure the sign makes it into the output
return { $numberDouble: '-0.0' };
}
let $numberDouble: string;
if (Number.isInteger(this.value)) {
$numberDouble = this.value.toFixed(1);
if ($numberDouble.length >= 13) {
$numberDouble = this.value.toExponential(13).toUpperCase();
}
} else {
$numberDouble = this.value.toString();
}
return { $numberDouble };
return {
$numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
};
}

@@ -79,0 +71,0 @@

@@ -1,14 +0,20 @@

/** @public */
/**
* @public
* `BSONError` objects are thrown when runtime errors occur.
*/
export class BSONError extends Error {
constructor(message: string) {
super(message);
/**
* @internal
* The underlying algorithm for isBSONError may change to improve how strict it is
* about determining if an input is a BSONError. But it must remain backwards compatible
* with previous minors & patches of the current major version.
*/
protected get bsonError(): true {
return true;
}
get name(): string {
override get name(): string {
return 'BSONError';
}
}
/** @public */
export class BSONTypeError extends TypeError {
constructor(message: string) {

@@ -18,5 +24,23 @@ super(message);

get name(): string {
return 'BSONTypeError';
/**
* @public
*
* All errors thrown from the BSON library inherit from `BSONError`.
* This method can assist with determining if an error originates from the BSON library
* even if it does not pass an `instanceof` check against this class' constructor.
*
* @param value - any javascript value that needs type checking
*/
public static isBSONError(value: unknown): value is BSONError {
return (
value != null &&
typeof value === 'object' &&
'bsonError' in value &&
value.bsonError === true &&
// Do not access the following properties, just check existence
'name' in value &&
'message' in value &&
'stack' in value
);
}
}
import { Binary } from './binary';
import type { Document } from './bson';
import { Code } from './code';
import { BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN } from './constants';
import {
BSON_INT32_MAX,
BSON_INT32_MIN,
BSON_INT64_MAX,
BSON_INT64_MIN,
BSON_MAJOR_VERSION
} from './constants';
import { DBRef, isDBRefLike } from './db_ref';
import { Decimal128 } from './decimal128';
import { Double } from './double';
import { BSONError, BSONTypeError } from './error';
import { BSONError } from './error';
import { Int32 } from './int_32';

@@ -195,3 +201,3 @@ import { Long } from './long';

throw new BSONTypeError(
throw new BSONError(
'Converting circular structure to EJSON:\n' +

@@ -314,3 +320,3 @@ ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` +

typeof doc._bsontype === 'string' &&
doc[Symbol.for('@@mdb.bson.version')] == null
doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION
) {

@@ -329,3 +335,3 @@ throw new BSONError('Unsupported BSON version, bson types must be from bson 5.0 or later');

if (!mapper) {
throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
}

@@ -332,0 +338,0 @@ outDoc = mapper(outDoc);

import { BSON_MAJOR_VERSION } from './constants';
import { BSONError } from './error';
import type { EJSONOptions } from './extended_json';

@@ -253,3 +254,3 @@ import type { Timestamp } from './timestamp';

static fromString(str: string, unsigned?: boolean, radix?: number): Long {
if (str.length === 0) throw Error('empty string');
if (str.length === 0) throw new BSONError('empty string');
if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity')

@@ -264,6 +265,6 @@ return Long.ZERO;

radix = radix || 10;
if (radix < 2 || 36 < radix) throw RangeError('radix');
if (radix < 2 || 36 < radix) throw new BSONError('radix');
let p;
if ((p = str.indexOf('-')) > 0) throw Error('interior hyphen');
if ((p = str.indexOf('-')) > 0) throw new BSONError('interior hyphen');
else if (p === 0) {

@@ -436,3 +437,3 @@ return Long.fromString(str.substring(1), unsigned, radix).neg();

if (!Long.isLong(divisor)) divisor = Long.fromValue(divisor);
if (divisor.isZero()) throw Error('division by zero');
if (divisor.isZero()) throw new BSONError('division by zero');

@@ -965,3 +966,3 @@ // use wasm support if present

radix = radix || 10;
if (radix < 2 || 36 < radix) throw RangeError('radix');
if (radix < 2 || 36 < radix) throw new BSONError('radix');
if (this.isZero()) return '0';

@@ -968,0 +969,0 @@ if (this.isNegative()) {

import { BSON_MAJOR_VERSION } from './constants';
import { BSONTypeError } from './error';
import { BSONError } from './error';
import { isUint8Array } from './parser/utils';

@@ -60,5 +60,3 @@ import { BSONDataView, ByteUtils } from './utils/byte_utils';

if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
throw new BSONTypeError(
'Argument passed in must have an id that is of type string or Buffer'
);
throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
}

@@ -89,3 +87,3 @@ if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {

} else {
throw new BSONTypeError('Argument passed in must be a string of 12 bytes');
throw new BSONError('Argument passed in must be a string of 12 bytes');
}

@@ -95,3 +93,3 @@ } else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {

} else {
throw new BSONTypeError(
throw new BSONError(
'Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'

@@ -101,3 +99,3 @@ );

} else {
throw new BSONTypeError('Argument passed in does not match the accepted types');
throw new BSONError('Argument passed in does not match the accepted types');
}

@@ -278,3 +276,3 @@ // If we are caching the hex string

if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
throw new BSONTypeError(
throw new BSONError(
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'

@@ -281,0 +279,0 @@ );

import { Binary } from '../binary';
import type { Document } from '../bson';
import { BSONError } from '../error';
import * as constants from '../constants';

@@ -80,3 +81,13 @@ import { ByteUtils } from '../utils/byte_utils';

case 'object':
if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
if (
value != null &&
typeof value._bsontype === 'string' &&
value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION
) {
throw new BSONError('Unsupported BSON version, bson types must be from bson 5.0 or later');
} else if (
value == null ||
value['_bsontype'] === 'MinKey' ||
value['_bsontype'] === 'MaxKey'
) {
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;

@@ -83,0 +94,0 @@ } else if (value['_bsontype'] === 'ObjectId') {

@@ -17,3 +17,3 @@ import { Binary } from '../binary';

import { Timestamp } from '../timestamp';
import { ByteUtils } from '../utils/byte_utils';
import { BSONDataView, ByteUtils } from '../utils/byte_utils';
import { validateUtf8 } from '../validate_utf8';

@@ -23,3 +23,5 @@

export interface DeserializeOptions {
/** when deserializing a Long will fit it into a Number if it's smaller than 53 bits */
/** when deserializing a Long will return as a BigInt. */
useBigInt64?: boolean;
/** when deserializing a Long will fit it into a Number if it's smaller than 53 bits. */
promoteLongs?: boolean;

@@ -34,3 +36,3 @@ /** when deserializing a Binary will return it as a node.js Buffer instance. */

bsonRegExp?: boolean;
/** allows the buffer to be larger than the parsed BSON object */
/** allows the buffer to be larger than the parsed BSON object. */
allowObjectSmallerThanBufferSize?: boolean;

@@ -102,3 +104,3 @@ /** Offset into buffer to begin reading document from */

// Start deserializtion
// Start deserialization
return deserializeObject(buffer, index, options, isArray);

@@ -124,6 +126,15 @@ }

// Controls the promotion of values vs wrapper classes
const promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
const promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
const promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
const promoteBuffers = options.promoteBuffers ?? false;
const promoteLongs = options.promoteLongs ?? true;
const promoteValues = options.promoteValues ?? true;
const useBigInt64 = options.useBigInt64 ?? false;
if (useBigInt64 && !promoteValues) {
throw new BSONError('Must either request bigint or Long for int64 deserialization');
}
if (useBigInt64 && !promoteLongs) {
throw new BSONError('Must either request bigint or Long for int64 deserialization');
}
// Ensures default validation option if none given

@@ -331,2 +342,4 @@ const validation = options.validation == null ? { utf8: true } : options.validation;

// Unpack the low and high bits
const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8));
const lowBits =

@@ -343,4 +356,6 @@ buffer[index++] |

const long = new Long(lowBits, highBits);
// Promote the long if possible
if (promoteLongs && promoteValues === true) {
if (useBigInt64) {
value = dataview.getBigInt64(0, true);
} else if (promoteLongs && promoteValues === true) {
// Promote the long if possible
value =

@@ -347,0 +362,0 @@ long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)

@@ -8,3 +8,3 @@ import { Binary } from '../binary';

import type { Double } from '../double';
import { BSONError, BSONTypeError } from '../error';
import { BSONError } from '../error';
import type { Int32 } from '../int_32';

@@ -16,11 +16,3 @@ import { Long } from '../long';

import { ByteUtils } from '../utils/byte_utils';
import {
isAnyArrayBuffer,
isBigInt64Array,
isBigUInt64Array,
isDate,
isMap,
isRegExp,
isUint8Array
} from './utils';
import { isAnyArrayBuffer, isDate, isMap, isRegExp, isUint8Array } from './utils';

@@ -108,2 +100,16 @@ /** @public */

function serializeBigInt(buffer: Uint8Array, key: string, value: bigint, index: number) {
buffer[index++] = constants.BSON_DATA_LONG;
// Number of written bytes
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
// Encode the name
index += numberOfWrittenBytes;
buffer[index++] = 0;
NUMBER_SPACE.setBigInt64(0, value, true);
// Write BigInt value
buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index);
index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;
return index;
}
function serializeNull(buffer: Uint8Array, key: string, _: unknown, index: number) {

@@ -171,3 +177,3 @@ // Set long type

if (value.source && value.source.match(regexp) != null) {
throw Error('value ' + value.source + ' must not contain null bytes');
throw new BSONError('value ' + value.source + ' must not contain null bytes');
}

@@ -201,3 +207,3 @@ // Adjust the index

// null-terminated.
throw Error('pattern ' + value.pattern + ' must not contain null bytes');
throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
}

@@ -249,3 +255,3 @@

} else {
throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
}

@@ -684,3 +690,3 @@

} else if (typeof value === 'bigint') {
throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
index = serializeBigInt(buffer, key, value, index);
} else if (typeof value === 'boolean') {

@@ -710,3 +716,6 @@ index = serializeBoolean(buffer, key, value, index);

);
} else if (typeof value === 'object' && value[Symbol.for('@@mdb.bson.version')] == null) {
} else if (
typeof value === 'object' &&
value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION
) {
throw new BSONError('Unsupported BSON version, bson types must be from bson 5.0 or later');

@@ -748,3 +757,3 @@ } else if (value._bsontype === 'ObjectId') {

} else if (typeof value._bsontype !== 'undefined') {
throw new BSONTypeError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
}

@@ -765,4 +774,8 @@ }

const key = entry.value[0];
const value = entry.value[1];
let value = entry.value[1];
if (typeof value?.toBSON === 'function') {
value = value.toBSON();
}
// Check the type of the value

@@ -776,3 +789,3 @@ const type = typeof value;

// null-terminated.
throw Error('key ' + key + ' must not contain null bytes');
throw new BSONError('key ' + key + ' must not contain null bytes');
}

@@ -782,5 +795,5 @@

if ('$' === key[0]) {
throw Error('key ' + key + " must not start with '$'");
throw new BSONError('key ' + key + " must not start with '$'");
} else if (~key.indexOf('.')) {
throw Error('key ' + key + " must not contain '.'");
throw new BSONError('key ' + key + " must not contain '.'");
}

@@ -794,4 +807,4 @@ }

index = serializeNumber(buffer, key, value, index);
} else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) {
throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
} else if (type === 'bigint') {
index = serializeBigInt(buffer, key, value, index);
} else if (type === 'boolean') {

@@ -819,3 +832,6 @@ index = serializeBoolean(buffer, key, value, index);

);
} else if (typeof value === 'object' && value[Symbol.for('@@mdb.bson.version')] == null) {
} else if (
typeof value === 'object' &&
value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION
) {
throw new BSONError('Unsupported BSON version, bson types must be from bson 5.0 or later');

@@ -857,3 +873,3 @@ } else if (value._bsontype === 'ObjectId') {

} else if (typeof value._bsontype !== 'undefined') {
throw new BSONTypeError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
}

@@ -866,3 +882,3 @@ }

if (object != null && typeof object !== 'object') {
throw new BSONTypeError('toBSON function did not return an object');
throw new BSONError('toBSON function did not return an object');
}

@@ -887,3 +903,3 @@ }

// null-terminated.
throw Error('key ' + key + ' must not contain null bytes');
throw new BSONError('key ' + key + ' must not contain null bytes');
}

@@ -893,5 +909,5 @@

if ('$' === key[0]) {
throw Error('key ' + key + " must not start with '$'");
throw new BSONError('key ' + key + " must not start with '$'");
} else if (~key.indexOf('.')) {
throw Error('key ' + key + " must not contain '.'");
throw new BSONError('key ' + key + " must not contain '.'");
}

@@ -906,3 +922,3 @@ }

} else if (type === 'bigint') {
throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
index = serializeBigInt(buffer, key, value, index);
} else if (type === 'boolean') {

@@ -932,3 +948,6 @@ index = serializeBoolean(buffer, key, value, index);

);
} else if (typeof value === 'object' && value[Symbol.for('@@mdb.bson.version')] == null) {
} else if (
typeof value === 'object' &&
value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION
) {
throw new BSONError('Unsupported BSON version, bson types must be from bson 5.0 or later');

@@ -970,3 +989,3 @@ } else if (value._bsontype === 'ObjectId') {

} else if (typeof value._bsontype !== 'undefined') {
throw new BSONTypeError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
}

@@ -973,0 +992,0 @@ }

import { BSON_MAJOR_VERSION } from './constants';
import { BSONError, BSONTypeError } from './error';
import { BSONError } from './error';
import type { EJSONOptions } from './extended_json';

@@ -106,3 +106,3 @@

}
throw new BSONTypeError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
}

@@ -109,0 +109,0 @@

@@ -1,2 +0,2 @@

import { BSONTypeError } from './error';
import { BSONError } from './error';
import { ByteUtils } from './utils/byte_utils';

@@ -13,3 +13,3 @@

if (!uuidValidateString(hexString)) {
throw new BSONTypeError(
throw new BSONError(
'UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".'

@@ -16,0 +16,0 @@ );

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc