opusdev/vector-similarity-api
1
1# BSON parser2 3BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents.4You can learn more about it in [the specification](http://bsonspec.org).5 6### Table of Contents7 8- [Usage](#usage)9- [Bugs/Feature Requests](#bugs--feature-requests)10- [Installation](#installation)11- [Documentation](#documentation)12- [FAQ](#faq)13 14 15### Release Integrity16 17Releases are created automatically and signed using the [Node team's GPG key](https://pgp.mongodb.com/node-driver.asc). This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:18 19```shell20gpg --import node-driver.asc21```22 23The GitHub release contains a detached signature file for the NPM package (named24`bson-X.Y.Z.tgz.sig`).25 26The following command returns the link npm package. 27```shell28npm view bson@vX.Y.Z dist.tarball 29```30 31Using the result of the above command, a `curl` command can return the official npm package for the release.32 33To verify the integrity of the downloaded package, run the following command:34```shell35gpg --verify bson-X.Y.Z.tgz.sig bson-X.Y.Z.tgz36```37 38>[!Note]39No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.40 41## Bugs / Feature Requests42 43Think you've found a bug? Want to see a new feature in `bson`? Please open a case in our issue management tool, JIRA:44 451. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org)462. Navigate to the NODE project: [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE)473. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it.48 49Bug reports in JIRA for the NODE driver project are **public**.50 51## Usage52 53To build a new version perform the following operations:54 55```56npm install57npm run build58```59 60### Node.js or Bundling Usage61 62When using a bundler or Node.js you can import bson using the package name:63 64```js65import { BSON, EJSON, ObjectId } from 'bson';66// or:67// const { BSON, EJSON, ObjectId } = require('bson');68 69const bytes = BSON.serialize({ _id: new ObjectId() });70console.log(bytes);71const doc = BSON.deserialize(bytes);72console.log(EJSON.stringify(doc));73// {"_id":{"$oid":"..."}}74```75 76### Browser Usage77 78If you are working directly in the browser without a bundler please use the `.mjs` bundle like so:79 80```html81<script type="module">82 import { BSON, EJSON, ObjectId } from './lib/bson.mjs';83 84 const bytes = BSON.serialize({ _id: new ObjectId() });85 console.log(bytes);86 const doc = BSON.deserialize(bytes);87 console.log(EJSON.stringify(doc));88 // {"_id":{"$oid":"..."}}89</script>90```91 92## Installation93 94```sh95npm install bson96```97 98### MongoDB Node.js Driver Version Compatibility99 100Only the following version combinations with the [MongoDB Node.js Driver](https://github.com/mongodb/node-mongodb-native) are considered stable.101 102| | `bson@1.x` | `bson@4.x` | `bson@5.x` | `bson@6.x` |103| ------------- | ---------- | ---------- | ---------- | ---------- |104| `mongodb@6.x` | N/A | N/A | N/A | ✓ |105| `mongodb@5.x` | N/A | N/A | ✓ | N/A |106| `mongodb@4.x` | N/A | ✓ | N/A | N/A |107| `mongodb@3.x` | ✓ | N/A | N/A | N/A |108 109## Documentation110 111### BSON112 113[API documentation](https://mongodb.github.io/node-mongodb-native/Next/modules/BSON.html)114 115<a name="EJSON"></a>116 117### EJSON118 119- [EJSON](#EJSON)120 121 - [.parse(text, [options])](#EJSON.parse)122 123 - [.stringify(value, [replacer], [space], [options])](#EJSON.stringify)124 125 - [.serialize(bson, [options])](#EJSON.serialize)126 127 - [.deserialize(ejson, [options])](#EJSON.deserialize)128 129<a name="EJSON.parse"></a>130 131#### _EJSON_.parse(text, [options])132 133| Param | Type | Default | Description |134| ----------------- | -------------------- | ----------------- | ---------------------------------------------------------------------------------- |135| text | <code>string</code> | | |136| [options] | <code>object</code> | | Optional settings |137| [options.relaxed] | <code>boolean</code> | <code>true</code> | Attempt to return native JS types where possible, rather than BSON types (if true) |138 139Parse an Extended JSON string, constructing the JavaScript value or object described by that140string.141 142**Example**143 144```js145const { EJSON } = require('bson');146const text = '{ "int32": { "$numberInt": "10" } }';147 148// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }149console.log(EJSON.parse(text, { relaxed: false }));150 151// prints { int32: 10 }152console.log(EJSON.parse(text));153```154 155<a name="EJSON.stringify"></a>156 157#### _EJSON_.stringify(value, [replacer], [space], [options])158 159| Param | Type | Default | Description |160| ----------------- | ------------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |161| value | <code>object</code> | | The value to convert to extended JSON |162| [replacer] | <code>function</code> \| <code>array</code> | | 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 |163| [space] | <code>string</code> \| <code>number</code> | | A String or Number object that's used to insert white space into the output JSON string for readability purposes. |164| [options] | <code>object</code> | | Optional settings |165| [options.relaxed] | <code>boolean</code> | <code>true</code> | Enabled Extended JSON's `relaxed` mode |166| [options.legacy] | <code>boolean</code> | <code>true</code> | Output in Extended JSON v1 |167 168Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer169function is specified or optionally including only the specified properties if a replacer array170is specified.171 172**Example**173 174```js175const { EJSON } = require('bson');176const Int32 = require('mongodb').Int32;177const doc = { int32: new Int32(10) };178 179// prints '{"int32":{"$numberInt":"10"}}'180console.log(EJSON.stringify(doc, { relaxed: false }));181 182// prints '{"int32":10}'183console.log(EJSON.stringify(doc));184```185 186<a name="EJSON.serialize"></a>187 188#### _EJSON_.serialize(bson, [options])189 190| Param | Type | Description |191| --------- | ------------------- | ---------------------------------------------------- |192| bson | <code>object</code> | The object to serialize |193| [options] | <code>object</code> | Optional settings passed to the `stringify` function |194 195Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.196 197<a name="EJSON.deserialize"></a>198 199#### _EJSON_.deserialize(ejson, [options])200 201| Param | Type | Description |202| --------- | ------------------- | -------------------------------------------- |203| ejson | <code>object</code> | The Extended JSON object to deserialize |204| [options] | <code>object</code> | Optional settings passed to the parse method |205 206Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types207 208## Error Handling209 210It 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.211 212Any 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.213This means `BSONError.isBSONError()` will always be able to accurately capture the errors that our BSON library throws.214 215Hypothetical example: A collection in our Db has an issue with UTF-8 data:216 217```ts218let documentCount = 0;219const cursor = collection.find({}, { utf8Validation: true });220try {221 for await (const doc of cursor) documentCount += 1;222} catch (error) {223 if (BSONError.isBSONError(error)) {224 console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`);225 return documentCount;226 }227 throw error;228}229```230 231## React Native232 233BSON vendors the required polyfills for `TextEncoder`, `TextDecoder`, `atob`, `btoa` imported from React Native and therefore doesn't expect users to polyfill these. One additional polyfill, `crypto.getRandomValues` is recommended and can be installed with the following command:234 235```sh236npm install --save react-native-get-random-values237```238 239The 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`.240 241```typescript242// Required Polyfills For ReactNative243import 'react-native-get-random-values';244```245 246Finally, import the `BSON` library like so:247 248```typescript249import { BSON, EJSON } from 'bson';250```251 252This will cause React Native to import the `node_modules/bson/lib/bson.rn.cjs` bundle (see the `"react-native"` setting we have in the `"exports"` section of our [package.json](./package.json).)253 254### Technical Note about React Native module import255 256The `"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/).257 258## FAQ259 260#### Why does `undefined` get converted to `null`?261 262The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys.263 264#### How do I add custom serialization logic?265 266This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize.267 268```javascript269const BSON = require('bson');270 271class CustomSerialize {272 toBSON() {273 return 42;274 }275}276 277const obj = { answer: new CustomSerialize() };278// "{ answer: 42 }"279console.log(BSON.deserialize(BSON.serialize(obj)));280```281 