manfa940 пре 3 недеља
комит
14198d79d0
100 измењених фајлова са 34030 додато и 0 уклоњено
  1. 170 0
      entryPoint.js
  2. 16 0
      node_modules/.bin/bcrypt
  3. 17 0
      node_modules/.bin/bcrypt.cmd
  4. 28 0
      node_modules/.bin/bcrypt.ps1
  5. 16 0
      node_modules/.bin/semver
  6. 17 0
      node_modules/.bin/semver.cmd
  7. 28 0
      node_modules/.bin/semver.ps1
  8. 1164 0
      node_modules/.package-lock.json
  9. 22 0
      node_modules/@mongodb-js/saslprep/LICENSE
  10. 4 0
      node_modules/@mongodb-js/saslprep/dist/.esm-wrapper.mjs
  11. 5 0
      node_modules/@mongodb-js/saslprep/dist/browser.d.ts
  12. 1 0
      node_modules/@mongodb-js/saslprep/dist/browser.d.ts.map
  13. 12 0
      node_modules/@mongodb-js/saslprep/dist/browser.js
  14. 1 0
      node_modules/@mongodb-js/saslprep/dist/browser.js.map
  15. 3 0
      node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts
  16. 1 0
      node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts.map
  17. 2 0
      node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js
  18. 1 0
      node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js.map
  19. 3 0
      node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts
  20. 1 0
      node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts.map
  21. 3 0
      node_modules/@mongodb-js/saslprep/dist/code-points-data.js
  22. 1 0
      node_modules/@mongodb-js/saslprep/dist/code-points-data.js.map
  23. 7 0
      node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts
  24. 1 0
      node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts.map
  25. 881 0
      node_modules/@mongodb-js/saslprep/dist/code-points-src.js
  26. 0 0
      node_modules/@mongodb-js/saslprep/dist/code-points-src.js.map
  27. 2 0
      node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts
  28. 1 0
      node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts.map
  29. 83 0
      node_modules/@mongodb-js/saslprep/dist/generate-code-points.js
  30. 0 0
      node_modules/@mongodb-js/saslprep/dist/generate-code-points.js.map
  31. 11 0
      node_modules/@mongodb-js/saslprep/dist/index.d.ts
  32. 1 0
      node_modules/@mongodb-js/saslprep/dist/index.d.ts.map
  33. 65 0
      node_modules/@mongodb-js/saslprep/dist/index.js
  34. 0 0
      node_modules/@mongodb-js/saslprep/dist/index.js.map
  35. 10 0
      node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts
  36. 1 0
      node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts.map
  37. 32 0
      node_modules/@mongodb-js/saslprep/dist/memory-code-points.js
  38. 1 0
      node_modules/@mongodb-js/saslprep/dist/memory-code-points.js.map
  39. 10 0
      node_modules/@mongodb-js/saslprep/dist/node.d.ts
  40. 1 0
      node_modules/@mongodb-js/saslprep/dist/node.d.ts.map
  41. 15 0
      node_modules/@mongodb-js/saslprep/dist/node.js
  42. 1 0
      node_modules/@mongodb-js/saslprep/dist/node.js.map
  43. 2 0
      node_modules/@mongodb-js/saslprep/dist/util.d.ts
  44. 1 0
      node_modules/@mongodb-js/saslprep/dist/util.d.ts.map
  45. 11 0
      node_modules/@mongodb-js/saslprep/dist/util.js
  46. 1 0
      node_modules/@mongodb-js/saslprep/dist/util.js.map
  47. 87 0
      node_modules/@mongodb-js/saslprep/package.json
  48. 29 0
      node_modules/@mongodb-js/saslprep/readme.md
  49. 21 0
      node_modules/@types/webidl-conversions/LICENSE
  50. 15 0
      node_modules/@types/webidl-conversions/README.md
  51. 91 0
      node_modules/@types/webidl-conversions/index.d.ts
  52. 30 0
      node_modules/@types/webidl-conversions/package.json
  53. 21 0
      node_modules/@types/whatwg-url/LICENSE
  54. 15 0
      node_modules/@types/whatwg-url/README.md
  55. 172 0
      node_modules/@types/whatwg-url/index.d.ts
  56. 22 0
      node_modules/@types/whatwg-url/lib/URL-impl.d.ts
  57. 66 0
      node_modules/@types/whatwg-url/lib/URL.d.ts
  58. 20 0
      node_modules/@types/whatwg-url/lib/URLSearchParams-impl.d.ts
  59. 92 0
      node_modules/@types/whatwg-url/lib/URLSearchParams.d.ts
  60. 38 0
      node_modules/@types/whatwg-url/package.json
  61. 4 0
      node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts
  62. 250 0
      node_modules/accepts/HISTORY.md
  63. 23 0
      node_modules/accepts/LICENSE
  64. 140 0
      node_modules/accepts/README.md
  65. 238 0
      node_modules/accepts/index.js
  66. 47 0
      node_modules/accepts/package.json
  67. 27 0
      node_modules/bcryptjs/LICENSE
  68. 201 0
      node_modules/bcryptjs/README.md
  69. 23 0
      node_modules/bcryptjs/bin/bcrypt
  70. 3 0
      node_modules/bcryptjs/index.d.ts
  71. 1159 0
      node_modules/bcryptjs/index.js
  72. 76 0
      node_modules/bcryptjs/package.json
  73. 157 0
      node_modules/bcryptjs/types.d.ts
  74. 3 0
      node_modules/bcryptjs/umd/index.d.ts
  75. 1220 0
      node_modules/bcryptjs/umd/index.js
  76. 3 0
      node_modules/bcryptjs/umd/package.json
  77. 157 0
      node_modules/bcryptjs/umd/types.d.ts
  78. 23 0
      node_modules/body-parser/LICENSE
  79. 494 0
      node_modules/body-parser/README.md
  80. 80 0
      node_modules/body-parser/index.js
  81. 250 0
      node_modules/body-parser/lib/read.js
  82. 166 0
      node_modules/body-parser/lib/types/json.js
  83. 43 0
      node_modules/body-parser/lib/types/raw.js
  84. 37 0
      node_modules/body-parser/lib/types/text.js
  85. 142 0
      node_modules/body-parser/lib/types/urlencoded.js
  86. 96 0
      node_modules/body-parser/lib/utils.js
  87. 52 0
      node_modules/body-parser/package.json
  88. 201 0
      node_modules/bson/LICENSE.md
  89. 291 0
      node_modules/bson/README.md
  90. 1729 0
      node_modules/bson/bson.d.ts
  91. 19 0
      node_modules/bson/etc/prepare.js
  92. 4675 0
      node_modules/bson/lib/bson.bundle.js
  93. 0 0
      node_modules/bson/lib/bson.bundle.js.map
  94. 4670 0
      node_modules/bson/lib/bson.cjs
  95. 0 0
      node_modules/bson/lib/bson.cjs.map
  96. 4639 0
      node_modules/bson/lib/bson.mjs
  97. 0 0
      node_modules/bson/lib/bson.mjs.map
  98. 4639 0
      node_modules/bson/lib/bson.node.mjs
  99. 0 0
      node_modules/bson/lib/bson.node.mjs.map
  100. 4680 0
      node_modules/bson/lib/bson.rn.cjs

+ 170 - 0
entryPoint.js

@@ -0,0 +1,170 @@
+
+//---------------------------------------//LOAD TOOLS//---------------------------------------//
+
+
+const express = require('express');
+const mongoose = require('mongoose');
+const jwt = require('jsonwebtoken');
+const bcrypt = require('bcryptjs');
+
+const app = express();
+app.use(express.json()); 
+
+
+//---------------------------------------//CONNECT TO SCHOOL DATABASE//---------------------------------------//
+
+
+//const dbServerAddress = "mongodb://192.168.131.172:27017/manfa940_database";
+const dbServerAddress = "mongodb://manfa940:Dm29070@$@192.168.131.172:27017/manfa940_database?authSource=admin";
+const dbLocalAddress = "mongodb://127.0.0.1:27017/manfa940_database";
+const mySecretKey = "super_secret_key_123"; 
+
+mongoose.connect(dbServerAddress)
+  .then(() => console.log("Success: Connected to School Server!"))
+  .catch(err => console.log("Error: Could not connect", err));
+
+
+//---------------------------------------//SCHEMAS//---------------------------------------//
+
+
+// User (Name, Password, and Money)
+
+const userSchema = new mongoose.Schema({
+  username: { type: String, required: true },
+  password: { type: String, required: true },
+  balance: { type: Number, default: 50 } 
+});
+
+
+// Plant
+
+const plantSchema = new mongoose.Schema({
+  owner: mongoose.Schema.Types.ObjectId,
+  type: String,
+  sequence: String, // Random code to remember
+  quality: { type: Number, default: 0 } 
+});
+
+const User = mongoose.model('User', userSchema);
+const Plant = mongoose.model('Plant', plantSchema);
+
+
+//---------------------------------------//SECURITY CHECK//---------------------------------------//
+
+
+// Checks if user is logged in
+
+const checkLogin = (req, res, next) => {
+  const token = req.headers['authorization']?.split(' ')[1];
+  
+  if (!token) return res.send("You are not logged in!");
+
+  jwt.verify(token, mySecretKey, (err, data) => {
+    if (err) return res.send("Token is bad!");
+    req.userId = data.id;
+    next();
+  });
+};
+
+
+//---------------------------------------//GAME ACTIONS//---------------------------------------//
+
+
+// Create Account
+
+app.post('/register', async (req, res) => {
+  const pass = await bcrypt.hash(req.body.password, 10);
+  const newUser = new User({ username: req.body.username, password: pass });
+  await newUser.save();
+  res.send("Account created!");
+});
+
+
+// Login
+
+app.post('/login', async (req, res) => {
+  const findUser = await User.findOne({ username: req.body.username });
+  if (!findUser) return res.send("User not found");
+
+  const checkPass = await bcrypt.compare(req.body.password, findUser.password);
+  if (!checkPass) return res.send("Wrong password");
+
+  const myToken = jwt.sign({ id: findUser._id }, mySecretKey);
+  res.json({ token: myToken });
+});
+
+
+// Plant a flower (Costs $10)
+
+app.post('/plant', checkLogin, async (req, res) => {
+  const player = await User.findById(req.userId);
+  if (player.balance < 10) return res.send("You are too poor!");
+
+  // Random 6 letter code
+  let code = "";
+  let letters = "1234";
+  for (let i = 0; i < 7; i++) {
+    code += letters.charAt(Math.floor(Math.random() * 7));
+  }
+
+  const newPlant = new Plant({ owner: req.userId, type: "Fern", sequence: code });
+  player.balance = player.balance - 10;
+  
+  await player.save();
+  await newPlant.save();
+
+  res.json({ msg: "Planted! Remember this code:", code: code });
+});
+
+
+// Grow plant by typing code
+
+app.post('/grow/:id', checkLogin, async (req, res) => {
+  const myPlant = await Plant.findById(req.params.id);
+  const userTyped = req.body.typedCode;
+
+
+  // Check how many letters are correct
+
+  let score = 0;
+  if (userTyped[0] === myPlant.sequence[0]) score++;
+  if (userTyped[1] === myPlant.sequence[1]) score++;
+  if (userTyped[2] === myPlant.sequence[2]) score++;
+  if (userTyped[3] === myPlant.sequence[3]) score++;
+  if (userTyped[4] === myPlant.sequence[4]) score++;
+  if (userTyped[5] === myPlant.sequence[5]) score++;
+  if (userTyped[6] === myPlant.sequence[6]) score++;
+
+  myPlant.quality = score / 7;
+  await myPlant.save();
+  res.send("Growth finished! Quality is: " + myPlant.quality);
+});
+
+
+// Sell plant for money
+
+app.post('/sell/:id', checkLogin, async (req, res) => {
+  const myPlant = await Plant.findById(req.params.id);
+  
+
+  // Money earned is $20 (profit from base price) * quality
+  
+  let moneyEarned = 20 * myPlant.quality;
+
+  const player = await User.findById(req.userId);
+  player.balance = player.balance + moneyEarned;
+
+  await player.save();
+  await Plant.deleteOne({ _id: req.params.id });
+
+  res.send("Sold! You got $" + moneyEarned);
+});
+
+
+//---------------------------------------//START SERVER//---------------------------------------//
+
+
+app.listen(3000, () => {
+  console.log("Game is running on port 3000");
+});
+

+ 16 - 0
node_modules/.bin/bcrypt

@@ -0,0 +1,16 @@
+#!/bin/sh
+basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
+
+case `uname` in
+    *CYGWIN*|*MINGW*|*MSYS*)
+        if command -v cygpath > /dev/null 2>&1; then
+            basedir=`cygpath -w "$basedir"`
+        fi
+    ;;
+esac
+
+if [ -x "$basedir/node" ]; then
+  exec "$basedir/node"  "$basedir/../bcryptjs/bin/bcrypt" "$@"
+else 
+  exec node  "$basedir/../bcryptjs/bin/bcrypt" "$@"
+fi

+ 17 - 0
node_modules/.bin/bcrypt.cmd

@@ -0,0 +1,17 @@
+@ECHO off
+GOTO start
+:find_dp0
+SET dp0=%~dp0
+EXIT /b
+:start
+SETLOCAL
+CALL :find_dp0
+
+IF EXIST "%dp0%\node.exe" (
+  SET "_prog=%dp0%\node.exe"
+) ELSE (
+  SET "_prog=node"
+  SET PATHEXT=%PATHEXT:;.JS;=;%
+)
+
+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%"  "%dp0%\..\bcryptjs\bin\bcrypt" %*

+ 28 - 0
node_modules/.bin/bcrypt.ps1

@@ -0,0 +1,28 @@
+#!/usr/bin/env pwsh
+$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
+
+$exe=""
+if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
+  # Fix case when both the Windows and Linux builds of Node
+  # are installed in the same directory
+  $exe=".exe"
+}
+$ret=0
+if (Test-Path "$basedir/node$exe") {
+  # Support pipeline input
+  if ($MyInvocation.ExpectingInput) {
+    $input | & "$basedir/node$exe"  "$basedir/../bcryptjs/bin/bcrypt" $args
+  } else {
+    & "$basedir/node$exe"  "$basedir/../bcryptjs/bin/bcrypt" $args
+  }
+  $ret=$LASTEXITCODE
+} else {
+  # Support pipeline input
+  if ($MyInvocation.ExpectingInput) {
+    $input | & "node$exe"  "$basedir/../bcryptjs/bin/bcrypt" $args
+  } else {
+    & "node$exe"  "$basedir/../bcryptjs/bin/bcrypt" $args
+  }
+  $ret=$LASTEXITCODE
+}
+exit $ret

+ 16 - 0
node_modules/.bin/semver

@@ -0,0 +1,16 @@
+#!/bin/sh
+basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
+
+case `uname` in
+    *CYGWIN*|*MINGW*|*MSYS*)
+        if command -v cygpath > /dev/null 2>&1; then
+            basedir=`cygpath -w "$basedir"`
+        fi
+    ;;
+esac
+
+if [ -x "$basedir/node" ]; then
+  exec "$basedir/node"  "$basedir/../semver/bin/semver.js" "$@"
+else 
+  exec node  "$basedir/../semver/bin/semver.js" "$@"
+fi

+ 17 - 0
node_modules/.bin/semver.cmd

@@ -0,0 +1,17 @@
+@ECHO off
+GOTO start
+:find_dp0
+SET dp0=%~dp0
+EXIT /b
+:start
+SETLOCAL
+CALL :find_dp0
+
+IF EXIST "%dp0%\node.exe" (
+  SET "_prog=%dp0%\node.exe"
+) ELSE (
+  SET "_prog=node"
+  SET PATHEXT=%PATHEXT:;.JS;=;%
+)
+
+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%"  "%dp0%\..\semver\bin\semver.js" %*

+ 28 - 0
node_modules/.bin/semver.ps1

@@ -0,0 +1,28 @@
+#!/usr/bin/env pwsh
+$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
+
+$exe=""
+if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
+  # Fix case when both the Windows and Linux builds of Node
+  # are installed in the same directory
+  $exe=".exe"
+}
+$ret=0
+if (Test-Path "$basedir/node$exe") {
+  # Support pipeline input
+  if ($MyInvocation.ExpectingInput) {
+    $input | & "$basedir/node$exe"  "$basedir/../semver/bin/semver.js" $args
+  } else {
+    & "$basedir/node$exe"  "$basedir/../semver/bin/semver.js" $args
+  }
+  $ret=$LASTEXITCODE
+} else {
+  # Support pipeline input
+  if ($MyInvocation.ExpectingInput) {
+    $input | & "node$exe"  "$basedir/../semver/bin/semver.js" $args
+  } else {
+    & "node$exe"  "$basedir/../semver/bin/semver.js" $args
+  }
+  $ret=$LASTEXITCODE
+}
+exit $ret

+ 1164 - 0
node_modules/.package-lock.json

@@ -0,0 +1,1164 @@
+{
+  "name": "flora_api_game",
+  "version": "1.0.0",
+  "lockfileVersion": 3,
+  "requires": true,
+  "packages": {
+    "node_modules/@mongodb-js/saslprep": {
+      "version": "1.4.4",
+      "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.4.4.tgz",
+      "integrity": "sha512-p7X/ytJDIdwUfFL/CLOhKgdfJe1Fa8uw9seJYvdOmnP9JBWGWHW69HkOixXS6Wy9yvGf1MbhcS6lVmrhy4jm2g==",
+      "license": "MIT",
+      "dependencies": {
+        "sparse-bitfield": "^3.0.3"
+      }
+    },
+    "node_modules/@types/webidl-conversions": {
+      "version": "7.0.3",
+      "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz",
+      "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==",
+      "license": "MIT"
+    },
+    "node_modules/@types/whatwg-url": {
+      "version": "13.0.0",
+      "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-13.0.0.tgz",
+      "integrity": "sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==",
+      "license": "MIT",
+      "dependencies": {
+        "@types/webidl-conversions": "*"
+      }
+    },
+    "node_modules/accepts": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
+      "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
+      "license": "MIT",
+      "dependencies": {
+        "mime-types": "^3.0.0",
+        "negotiator": "^1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/bcryptjs": {
+      "version": "3.0.3",
+      "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz",
+      "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==",
+      "license": "BSD-3-Clause",
+      "bin": {
+        "bcrypt": "bin/bcrypt"
+      }
+    },
+    "node_modules/body-parser": {
+      "version": "2.2.1",
+      "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.1.tgz",
+      "integrity": "sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==",
+      "license": "MIT",
+      "dependencies": {
+        "bytes": "^3.1.2",
+        "content-type": "^1.0.5",
+        "debug": "^4.4.3",
+        "http-errors": "^2.0.0",
+        "iconv-lite": "^0.7.0",
+        "on-finished": "^2.4.1",
+        "qs": "^6.14.0",
+        "raw-body": "^3.0.1",
+        "type-is": "^2.0.1"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/bson": {
+      "version": "7.0.0",
+      "resolved": "https://registry.npmjs.org/bson/-/bson-7.0.0.tgz",
+      "integrity": "sha512-Kwc6Wh4lQ5OmkqqKhYGKIuELXl+EPYSCObVE6bWsp1T/cGkOCBN0I8wF/T44BiuhHyNi1mmKVPXk60d41xZ7kw==",
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=20.19.0"
+      }
+    },
+    "node_modules/buffer-equal-constant-time": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
+      "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
+      "license": "BSD-3-Clause"
+    },
+    "node_modules/bytes": {
+      "version": "3.1.2",
+      "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+      "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/call-bind-apply-helpers": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+      "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/call-bound": {
+      "version": "1.0.4",
+      "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+      "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.2",
+        "get-intrinsic": "^1.3.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/content-disposition": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz",
+      "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/content-type": {
+      "version": "1.0.5",
+      "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+      "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/cookie": {
+      "version": "0.7.2",
+      "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+      "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/cookie-signature": {
+      "version": "1.2.2",
+      "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+      "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=6.6.0"
+      }
+    },
+    "node_modules/debug": {
+      "version": "4.4.3",
+      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+      "license": "MIT",
+      "dependencies": {
+        "ms": "^2.1.3"
+      },
+      "engines": {
+        "node": ">=6.0"
+      },
+      "peerDependenciesMeta": {
+        "supports-color": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/depd": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+      "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/dunder-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+      "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "gopd": "^1.2.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/ecdsa-sig-formatter": {
+      "version": "1.0.11",
+      "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
+      "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "safe-buffer": "^5.0.1"
+      }
+    },
+    "node_modules/ee-first": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+      "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+      "license": "MIT"
+    },
+    "node_modules/encodeurl": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+      "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/es-define-property": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+      "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-errors": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+      "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/es-object-atoms": {
+      "version": "1.1.1",
+      "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+      "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/escape-html": {
+      "version": "1.0.3",
+      "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+      "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+      "license": "MIT"
+    },
+    "node_modules/etag": {
+      "version": "1.8.1",
+      "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+      "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/express": {
+      "version": "5.2.1",
+      "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
+      "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
+      "license": "MIT",
+      "dependencies": {
+        "accepts": "^2.0.0",
+        "body-parser": "^2.2.1",
+        "content-disposition": "^1.0.0",
+        "content-type": "^1.0.5",
+        "cookie": "^0.7.1",
+        "cookie-signature": "^1.2.1",
+        "debug": "^4.4.0",
+        "depd": "^2.0.0",
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "etag": "^1.8.1",
+        "finalhandler": "^2.1.0",
+        "fresh": "^2.0.0",
+        "http-errors": "^2.0.0",
+        "merge-descriptors": "^2.0.0",
+        "mime-types": "^3.0.0",
+        "on-finished": "^2.4.1",
+        "once": "^1.4.0",
+        "parseurl": "^1.3.3",
+        "proxy-addr": "^2.0.7",
+        "qs": "^6.14.0",
+        "range-parser": "^1.2.1",
+        "router": "^2.2.0",
+        "send": "^1.1.0",
+        "serve-static": "^2.2.0",
+        "statuses": "^2.0.1",
+        "type-is": "^2.0.1",
+        "vary": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/finalhandler": {
+      "version": "2.1.1",
+      "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
+      "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.0",
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "on-finished": "^2.4.1",
+        "parseurl": "^1.3.3",
+        "statuses": "^2.0.1"
+      },
+      "engines": {
+        "node": ">= 18.0.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/forwarded": {
+      "version": "0.2.0",
+      "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+      "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/fresh": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
+      "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/function-bind": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+      "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+      "license": "MIT",
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/get-intrinsic": {
+      "version": "1.3.0",
+      "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+      "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bind-apply-helpers": "^1.0.2",
+        "es-define-property": "^1.0.1",
+        "es-errors": "^1.3.0",
+        "es-object-atoms": "^1.1.1",
+        "function-bind": "^1.1.2",
+        "get-proto": "^1.0.1",
+        "gopd": "^1.2.0",
+        "has-symbols": "^1.1.0",
+        "hasown": "^2.0.2",
+        "math-intrinsics": "^1.1.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/get-proto": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+      "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+      "license": "MIT",
+      "dependencies": {
+        "dunder-proto": "^1.0.1",
+        "es-object-atoms": "^1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/gopd": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+      "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/has-symbols": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+      "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/hasown": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
+      "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+      "license": "MIT",
+      "dependencies": {
+        "function-bind": "^1.1.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/http-errors": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
+      "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
+      "license": "MIT",
+      "dependencies": {
+        "depd": "~2.0.0",
+        "inherits": "~2.0.4",
+        "setprototypeof": "~1.2.0",
+        "statuses": "~2.0.2",
+        "toidentifier": "~1.0.1"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/iconv-lite": {
+      "version": "0.7.1",
+      "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.1.tgz",
+      "integrity": "sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==",
+      "license": "MIT",
+      "dependencies": {
+        "safer-buffer": ">= 2.1.2 < 3.0.0"
+      },
+      "engines": {
+        "node": ">=0.10.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/inherits": {
+      "version": "2.0.4",
+      "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+      "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+      "license": "ISC"
+    },
+    "node_modules/ipaddr.js": {
+      "version": "1.9.1",
+      "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+      "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/is-promise": {
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+      "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
+      "license": "MIT"
+    },
+    "node_modules/jsonwebtoken": {
+      "version": "9.0.3",
+      "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
+      "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
+      "license": "MIT",
+      "dependencies": {
+        "jws": "^4.0.1",
+        "lodash.includes": "^4.3.0",
+        "lodash.isboolean": "^3.0.3",
+        "lodash.isinteger": "^4.0.4",
+        "lodash.isnumber": "^3.0.3",
+        "lodash.isplainobject": "^4.0.6",
+        "lodash.isstring": "^4.0.1",
+        "lodash.once": "^4.0.0",
+        "ms": "^2.1.1",
+        "semver": "^7.5.4"
+      },
+      "engines": {
+        "node": ">=12",
+        "npm": ">=6"
+      }
+    },
+    "node_modules/jwa": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
+      "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
+      "license": "MIT",
+      "dependencies": {
+        "buffer-equal-constant-time": "^1.0.1",
+        "ecdsa-sig-formatter": "1.0.11",
+        "safe-buffer": "^5.0.1"
+      }
+    },
+    "node_modules/jws": {
+      "version": "4.0.1",
+      "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
+      "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
+      "license": "MIT",
+      "dependencies": {
+        "jwa": "^2.0.1",
+        "safe-buffer": "^5.0.1"
+      }
+    },
+    "node_modules/kareem": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/kareem/-/kareem-3.0.0.tgz",
+      "integrity": "sha512-RKhaOBSPN8L7y4yAgNhDT2602G5FD6QbOIISbjN9D6mjHPeqeg7K+EB5IGSU5o81/X2Gzm3ICnAvQW3x3OP8HA==",
+      "license": "Apache-2.0",
+      "engines": {
+        "node": ">=18.0.0"
+      }
+    },
+    "node_modules/lodash.includes": {
+      "version": "4.3.0",
+      "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
+      "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isboolean": {
+      "version": "3.0.3",
+      "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
+      "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isinteger": {
+      "version": "4.0.4",
+      "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
+      "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isnumber": {
+      "version": "3.0.3",
+      "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
+      "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isplainobject": {
+      "version": "4.0.6",
+      "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
+      "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.isstring": {
+      "version": "4.0.1",
+      "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
+      "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
+      "license": "MIT"
+    },
+    "node_modules/lodash.once": {
+      "version": "4.1.1",
+      "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
+      "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
+      "license": "MIT"
+    },
+    "node_modules/math-intrinsics": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+      "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      }
+    },
+    "node_modules/media-typer": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
+      "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/memory-pager": {
+      "version": "1.5.0",
+      "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz",
+      "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==",
+      "license": "MIT"
+    },
+    "node_modules/merge-descriptors": {
+      "version": "2.0.0",
+      "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+      "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/sindresorhus"
+      }
+    },
+    "node_modules/mime-db": {
+      "version": "1.54.0",
+      "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+      "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/mime-types": {
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
+      "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
+      "license": "MIT",
+      "dependencies": {
+        "mime-db": "^1.54.0"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/mongodb": {
+      "version": "7.0.0",
+      "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.0.0.tgz",
+      "integrity": "sha512-vG/A5cQrvGGvZm2mTnCSz1LUcbOPl83hfB6bxULKQ8oFZauyox/2xbZOoGNl+64m8VBrETkdGCDBdOsCr3F3jg==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@mongodb-js/saslprep": "^1.3.0",
+        "bson": "^7.0.0",
+        "mongodb-connection-string-url": "^7.0.0"
+      },
+      "engines": {
+        "node": ">=20.19.0"
+      },
+      "peerDependencies": {
+        "@aws-sdk/credential-providers": "^3.806.0",
+        "@mongodb-js/zstd": "^7.0.0",
+        "gcp-metadata": "^7.0.1",
+        "kerberos": "^7.0.0",
+        "mongodb-client-encryption": ">=7.0.0 <7.1.0",
+        "snappy": "^7.3.2",
+        "socks": "^2.8.6"
+      },
+      "peerDependenciesMeta": {
+        "@aws-sdk/credential-providers": {
+          "optional": true
+        },
+        "@mongodb-js/zstd": {
+          "optional": true
+        },
+        "gcp-metadata": {
+          "optional": true
+        },
+        "kerberos": {
+          "optional": true
+        },
+        "mongodb-client-encryption": {
+          "optional": true
+        },
+        "snappy": {
+          "optional": true
+        },
+        "socks": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/mongodb-connection-string-url": {
+      "version": "7.0.0",
+      "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-7.0.0.tgz",
+      "integrity": "sha512-irhhjRVLE20hbkRl4zpAYLnDMM+zIZnp0IDB9akAFFUZp/3XdOfwwddc7y6cNvF2WCEtfTYRwYbIfYa2kVY0og==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@types/whatwg-url": "^13.0.0",
+        "whatwg-url": "^14.1.0"
+      },
+      "engines": {
+        "node": ">=20.19.0"
+      }
+    },
+    "node_modules/mongoose": {
+      "version": "9.1.1",
+      "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-9.1.1.tgz",
+      "integrity": "sha512-/CgKSAmjzgIj4o1FyWZIpQ2rmUQlhalwWd4l/Ht3XUVWscHRHev1TIwKz1ADNC5tHHyOQEaUDkEh0jI91c4Ydw==",
+      "license": "MIT",
+      "dependencies": {
+        "kareem": "3.0.0",
+        "mongodb": "~7.0",
+        "mpath": "0.9.0",
+        "mquery": "6.0.0",
+        "ms": "2.1.3",
+        "sift": "17.1.3"
+      },
+      "engines": {
+        "node": ">=20.19.0"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/mongoose"
+      }
+    },
+    "node_modules/mpath": {
+      "version": "0.9.0",
+      "resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz",
+      "integrity": "sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=4.0.0"
+      }
+    },
+    "node_modules/mquery": {
+      "version": "6.0.0",
+      "resolved": "https://registry.npmjs.org/mquery/-/mquery-6.0.0.tgz",
+      "integrity": "sha512-b2KQNsmgtkscfeDgkYMcWGn9vZI9YoXh802VDEwE6qc50zxBFQ0Oo8ROkawbPAsXCY1/Z1yp0MagqsZStPWJjw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=20.19.0"
+      }
+    },
+    "node_modules/ms": {
+      "version": "2.1.3",
+      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+      "license": "MIT"
+    },
+    "node_modules/negotiator": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
+      "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/object-inspect": {
+      "version": "1.13.4",
+      "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+      "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/on-finished": {
+      "version": "2.4.1",
+      "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+      "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+      "license": "MIT",
+      "dependencies": {
+        "ee-first": "1.1.1"
+      },
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/once": {
+      "version": "1.4.0",
+      "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+      "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+      "license": "ISC",
+      "dependencies": {
+        "wrappy": "1"
+      }
+    },
+    "node_modules/parseurl": {
+      "version": "1.3.3",
+      "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+      "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/path-to-regexp": {
+      "version": "8.3.0",
+      "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
+      "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
+      "license": "MIT",
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/proxy-addr": {
+      "version": "2.0.7",
+      "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+      "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+      "license": "MIT",
+      "dependencies": {
+        "forwarded": "0.2.0",
+        "ipaddr.js": "1.9.1"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/punycode": {
+      "version": "2.3.1",
+      "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+      "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=6"
+      }
+    },
+    "node_modules/qs": {
+      "version": "6.14.1",
+      "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz",
+      "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==",
+      "license": "BSD-3-Clause",
+      "dependencies": {
+        "side-channel": "^1.1.0"
+      },
+      "engines": {
+        "node": ">=0.6"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/range-parser": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
+      "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/raw-body": {
+      "version": "3.0.2",
+      "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
+      "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
+      "license": "MIT",
+      "dependencies": {
+        "bytes": "~3.1.2",
+        "http-errors": "~2.0.1",
+        "iconv-lite": "~0.7.0",
+        "unpipe": "~1.0.0"
+      },
+      "engines": {
+        "node": ">= 0.10"
+      }
+    },
+    "node_modules/router": {
+      "version": "2.2.0",
+      "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
+      "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.0",
+        "depd": "^2.0.0",
+        "is-promise": "^4.0.0",
+        "parseurl": "^1.3.3",
+        "path-to-regexp": "^8.0.0"
+      },
+      "engines": {
+        "node": ">= 18"
+      }
+    },
+    "node_modules/safe-buffer": {
+      "version": "5.2.1",
+      "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+      "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+      "funding": [
+        {
+          "type": "github",
+          "url": "https://github.com/sponsors/feross"
+        },
+        {
+          "type": "patreon",
+          "url": "https://www.patreon.com/feross"
+        },
+        {
+          "type": "consulting",
+          "url": "https://feross.org/support"
+        }
+      ],
+      "license": "MIT"
+    },
+    "node_modules/safer-buffer": {
+      "version": "2.1.2",
+      "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+      "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+      "license": "MIT"
+    },
+    "node_modules/semver": {
+      "version": "7.7.3",
+      "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
+      "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
+      "license": "ISC",
+      "bin": {
+        "semver": "bin/semver.js"
+      },
+      "engines": {
+        "node": ">=10"
+      }
+    },
+    "node_modules/send": {
+      "version": "1.2.1",
+      "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
+      "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
+      "license": "MIT",
+      "dependencies": {
+        "debug": "^4.4.3",
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "etag": "^1.8.1",
+        "fresh": "^2.0.0",
+        "http-errors": "^2.0.1",
+        "mime-types": "^3.0.2",
+        "ms": "^2.1.3",
+        "on-finished": "^2.4.1",
+        "range-parser": "^1.2.1",
+        "statuses": "^2.0.2"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/serve-static": {
+      "version": "2.2.1",
+      "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",
+      "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
+      "license": "MIT",
+      "dependencies": {
+        "encodeurl": "^2.0.0",
+        "escape-html": "^1.0.3",
+        "parseurl": "^1.3.3",
+        "send": "^1.2.0"
+      },
+      "engines": {
+        "node": ">= 18"
+      },
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/express"
+      }
+    },
+    "node_modules/setprototypeof": {
+      "version": "1.2.0",
+      "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+      "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+      "license": "ISC"
+    },
+    "node_modules/side-channel": {
+      "version": "1.1.0",
+      "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
+      "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "object-inspect": "^1.13.3",
+        "side-channel-list": "^1.0.0",
+        "side-channel-map": "^1.0.1",
+        "side-channel-weakmap": "^1.0.2"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-list": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
+      "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
+      "license": "MIT",
+      "dependencies": {
+        "es-errors": "^1.3.0",
+        "object-inspect": "^1.13.3"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-map": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+      "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bound": "^1.0.2",
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.5",
+        "object-inspect": "^1.13.3"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/side-channel-weakmap": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+      "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+      "license": "MIT",
+      "dependencies": {
+        "call-bound": "^1.0.2",
+        "es-errors": "^1.3.0",
+        "get-intrinsic": "^1.2.5",
+        "object-inspect": "^1.13.3",
+        "side-channel-map": "^1.0.1"
+      },
+      "engines": {
+        "node": ">= 0.4"
+      },
+      "funding": {
+        "url": "https://github.com/sponsors/ljharb"
+      }
+    },
+    "node_modules/sift": {
+      "version": "17.1.3",
+      "resolved": "https://registry.npmjs.org/sift/-/sift-17.1.3.tgz",
+      "integrity": "sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==",
+      "license": "MIT"
+    },
+    "node_modules/sparse-bitfield": {
+      "version": "3.0.3",
+      "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz",
+      "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==",
+      "license": "MIT",
+      "dependencies": {
+        "memory-pager": "^1.0.2"
+      }
+    },
+    "node_modules/statuses": {
+      "version": "2.0.2",
+      "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
+      "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/toidentifier": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+      "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.6"
+      }
+    },
+    "node_modules/tr46": {
+      "version": "5.1.1",
+      "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
+      "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
+      "license": "MIT",
+      "dependencies": {
+        "punycode": "^2.3.1"
+      },
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/type-is": {
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",
+      "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",
+      "license": "MIT",
+      "dependencies": {
+        "content-type": "^1.0.5",
+        "media-typer": "^1.1.0",
+        "mime-types": "^3.0.0"
+      },
+      "engines": {
+        "node": ">= 0.6"
+      }
+    },
+    "node_modules/unpipe": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+      "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/vary": {
+      "version": "1.1.2",
+      "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+      "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+      "license": "MIT",
+      "engines": {
+        "node": ">= 0.8"
+      }
+    },
+    "node_modules/webidl-conversions": {
+      "version": "7.0.0",
+      "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
+      "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
+      "license": "BSD-2-Clause",
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/whatwg-url": {
+      "version": "14.2.0",
+      "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
+      "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
+      "license": "MIT",
+      "dependencies": {
+        "tr46": "^5.1.0",
+        "webidl-conversions": "^7.0.0"
+      },
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/wrappy": {
+      "version": "1.0.2",
+      "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+      "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+      "license": "ISC"
+    }
+  }
+}

+ 22 - 0
node_modules/@mongodb-js/saslprep/LICENSE

@@ -0,0 +1,22 @@
+Copyright (c) 2014 Dmitry Tsvettsikh
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.

+ 4 - 0
node_modules/@mongodb-js/saslprep/dist/.esm-wrapper.mjs

@@ -0,0 +1,4 @@
+import mod from "./node.js";
+
+export default mod;
+export const saslprep = mod.saslprep;

+ 5 - 0
node_modules/@mongodb-js/saslprep/dist/browser.d.ts

@@ -0,0 +1,5 @@
+declare const saslprep: (input: string, opts?: {
+    allowUnassigned?: boolean;
+} | undefined) => string;
+export = saslprep;
+//# sourceMappingURL=browser.d.ts.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/browser.d.ts.map

@@ -0,0 +1 @@
+{"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAMA,QAAA,MAAM,QAAQ;;wBAAmC,CAAC;AAIlD,SAAS,QAAQ,CAAC"}

+ 12 - 0
node_modules/@mongodb-js/saslprep/dist/browser.js

@@ -0,0 +1,12 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+const index_1 = __importDefault(require("./index"));
+const memory_code_points_1 = require("./memory-code-points");
+const code_points_data_browser_1 = __importDefault(require("./code-points-data-browser"));
+const codePoints = (0, memory_code_points_1.createMemoryCodePoints)(code_points_data_browser_1.default);
+const saslprep = index_1.default.bind(null, codePoints);
+Object.assign(saslprep, { saslprep, default: saslprep });
+module.exports = saslprep;
+//# sourceMappingURL=browser.js.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/browser.js.map

@@ -0,0 +1 @@
+{"version":3,"file":"browser.js","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":";;;;AAAA,oDAAgC;AAChC,6DAA8D;AAC9D,0FAA8C;AAE9C,MAAM,UAAU,GAAG,IAAA,2CAAsB,EAAC,kCAAI,CAAC,CAAC;AAEhD,MAAM,QAAQ,GAAG,eAAS,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;AAEzD,iBAAS,QAAQ,CAAC"}

+ 3 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts

@@ -0,0 +1,3 @@
+declare const data: Buffer<ArrayBuffer>;
+export default data;
+//# sourceMappingURL=code-points-data-browser.d.ts.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.d.ts.map

@@ -0,0 +1 @@
+{"version":3,"file":"code-points-data-browser.d.ts","sourceRoot":"","sources":["../src/code-points-data-browser.ts"],"names":[],"mappings":"AAAA,QAAA,MAAM,IAAI,qBAGT,CAAC;AACF,eAAe,IAAI,CAAC"}

Разлика између датотеке није приказан због своје велике величине
+ 2 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js


+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-data-browser.js.map

@@ -0,0 +1 @@
+{"version":3,"file":"code-points-data-browser.js","sourceRoot":"","sources":["../src/code-points-data-browser.ts"],"names":[],"mappings":";;AAAA,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CACtB,8sliBAA8sliB,EAC9sliB,QAAQ,CACT,CAAC;AACF,kBAAe,IAAI,CAAC"}

+ 3 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts

@@ -0,0 +1,3 @@
+declare const _default: Buffer<ArrayBufferLike>;
+export default _default;
+//# sourceMappingURL=code-points-data.d.ts.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-data.d.ts.map

@@ -0,0 +1 @@
+{"version":3,"file":"code-points-data.d.ts","sourceRoot":"","sources":["../src/code-points-data.ts"],"names":[],"mappings":";AAEA,wBAKE"}

Разлика између датотеке није приказан због своје велике величине
+ 3 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-data.js


+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-data.js.map

@@ -0,0 +1 @@
+{"version":3,"file":"code-points-data.js","sourceRoot":"","sources":["../src/code-points-data.ts"],"names":[],"mappings":";;AAAA,+BAAkC;AAElC,kBAAe,IAAA,iBAAU,EACvB,MAAM,CAAC,IAAI,CACT,knFAAknF,EAClnF,QAAQ,CACT,CACF,CAAC"}

+ 7 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts

@@ -0,0 +1,7 @@
+export declare const unassigned_code_points: Set<number>;
+export declare const commonly_mapped_to_nothing: Set<number>;
+export declare const non_ASCII_space_characters: Set<number>;
+export declare const prohibited_characters: Set<number>;
+export declare const bidirectional_r_al: Set<number>;
+export declare const bidirectional_l: Set<number>;
+//# sourceMappingURL=code-points-src.d.ts.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-src.d.ts.map

@@ -0,0 +1 @@
+{"version":3,"file":"code-points-src.d.ts","sourceRoot":"","sources":["../src/code-points-src.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,sBAAsB,aA6YjC,CAAC;AAMH,eAAO,MAAM,0BAA0B,aAIrC,CAAC;AAMH,eAAO,MAAM,0BAA0B,aASrC,CAAC;AAMH,eAAO,MAAM,qBAAqB,aA6GhC,CAAC;AAMH,eAAO,MAAM,kBAAkB,aAmC7B,CAAC;AAMH,eAAO,MAAM,eAAe,aAyW1B,CAAC"}

+ 881 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-src.js

@@ -0,0 +1,881 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.bidirectional_l = exports.bidirectional_r_al = exports.prohibited_characters = exports.non_ASCII_space_characters = exports.commonly_mapped_to_nothing = exports.unassigned_code_points = void 0;
+const util_1 = require("./util");
+exports.unassigned_code_points = new Set([
+    0x0221,
+    ...(0, util_1.range)(0x0234, 0x024f),
+    ...(0, util_1.range)(0x02ae, 0x02af),
+    ...(0, util_1.range)(0x02ef, 0x02ff),
+    ...(0, util_1.range)(0x0350, 0x035f),
+    ...(0, util_1.range)(0x0370, 0x0373),
+    ...(0, util_1.range)(0x0376, 0x0379),
+    ...(0, util_1.range)(0x037b, 0x037d),
+    ...(0, util_1.range)(0x037f, 0x0383),
+    0x038b,
+    0x038d,
+    0x03a2,
+    0x03cf,
+    ...(0, util_1.range)(0x03f7, 0x03ff),
+    0x0487,
+    0x04cf,
+    ...(0, util_1.range)(0x04f6, 0x04f7),
+    ...(0, util_1.range)(0x04fa, 0x04ff),
+    ...(0, util_1.range)(0x0510, 0x0530),
+    ...(0, util_1.range)(0x0557, 0x0558),
+    0x0560,
+    0x0588,
+    ...(0, util_1.range)(0x058b, 0x0590),
+    0x05a2,
+    0x05ba,
+    ...(0, util_1.range)(0x05c5, 0x05cf),
+    ...(0, util_1.range)(0x05eb, 0x05ef),
+    ...(0, util_1.range)(0x05f5, 0x060b),
+    ...(0, util_1.range)(0x060d, 0x061a),
+    ...(0, util_1.range)(0x061c, 0x061e),
+    0x0620,
+    ...(0, util_1.range)(0x063b, 0x063f),
+    ...(0, util_1.range)(0x0656, 0x065f),
+    ...(0, util_1.range)(0x06ee, 0x06ef),
+    0x06ff,
+    0x070e,
+    ...(0, util_1.range)(0x072d, 0x072f),
+    ...(0, util_1.range)(0x074b, 0x077f),
+    ...(0, util_1.range)(0x07b2, 0x0900),
+    0x0904,
+    ...(0, util_1.range)(0x093a, 0x093b),
+    ...(0, util_1.range)(0x094e, 0x094f),
+    ...(0, util_1.range)(0x0955, 0x0957),
+    ...(0, util_1.range)(0x0971, 0x0980),
+    0x0984,
+    ...(0, util_1.range)(0x098d, 0x098e),
+    ...(0, util_1.range)(0x0991, 0x0992),
+    0x09a9,
+    0x09b1,
+    ...(0, util_1.range)(0x09b3, 0x09b5),
+    ...(0, util_1.range)(0x09ba, 0x09bb),
+    0x09bd,
+    ...(0, util_1.range)(0x09c5, 0x09c6),
+    ...(0, util_1.range)(0x09c9, 0x09ca),
+    ...(0, util_1.range)(0x09ce, 0x09d6),
+    ...(0, util_1.range)(0x09d8, 0x09db),
+    0x09de,
+    ...(0, util_1.range)(0x09e4, 0x09e5),
+    ...(0, util_1.range)(0x09fb, 0x0a01),
+    ...(0, util_1.range)(0x0a03, 0x0a04),
+    ...(0, util_1.range)(0x0a0b, 0x0a0e),
+    ...(0, util_1.range)(0x0a11, 0x0a12),
+    0x0a29,
+    0x0a31,
+    0x0a34,
+    0x0a37,
+    ...(0, util_1.range)(0x0a3a, 0x0a3b),
+    0x0a3d,
+    ...(0, util_1.range)(0x0a43, 0x0a46),
+    ...(0, util_1.range)(0x0a49, 0x0a4a),
+    ...(0, util_1.range)(0x0a4e, 0x0a58),
+    0x0a5d,
+    ...(0, util_1.range)(0x0a5f, 0x0a65),
+    ...(0, util_1.range)(0x0a75, 0x0a80),
+    0x0a84,
+    0x0a8c,
+    0x0a8e,
+    0x0a92,
+    0x0aa9,
+    0x0ab1,
+    0x0ab4,
+    ...(0, util_1.range)(0x0aba, 0x0abb),
+    0x0ac6,
+    0x0aca,
+    ...(0, util_1.range)(0x0ace, 0x0acf),
+    ...(0, util_1.range)(0x0ad1, 0x0adf),
+    ...(0, util_1.range)(0x0ae1, 0x0ae5),
+    ...(0, util_1.range)(0x0af0, 0x0b00),
+    0x0b04,
+    ...(0, util_1.range)(0x0b0d, 0x0b0e),
+    ...(0, util_1.range)(0x0b11, 0x0b12),
+    0x0b29,
+    0x0b31,
+    ...(0, util_1.range)(0x0b34, 0x0b35),
+    ...(0, util_1.range)(0x0b3a, 0x0b3b),
+    ...(0, util_1.range)(0x0b44, 0x0b46),
+    ...(0, util_1.range)(0x0b49, 0x0b4a),
+    ...(0, util_1.range)(0x0b4e, 0x0b55),
+    ...(0, util_1.range)(0x0b58, 0x0b5b),
+    0x0b5e,
+    ...(0, util_1.range)(0x0b62, 0x0b65),
+    ...(0, util_1.range)(0x0b71, 0x0b81),
+    0x0b84,
+    ...(0, util_1.range)(0x0b8b, 0x0b8d),
+    0x0b91,
+    ...(0, util_1.range)(0x0b96, 0x0b98),
+    0x0b9b,
+    0x0b9d,
+    ...(0, util_1.range)(0x0ba0, 0x0ba2),
+    ...(0, util_1.range)(0x0ba5, 0x0ba7),
+    ...(0, util_1.range)(0x0bab, 0x0bad),
+    0x0bb6,
+    ...(0, util_1.range)(0x0bba, 0x0bbd),
+    ...(0, util_1.range)(0x0bc3, 0x0bc5),
+    0x0bc9,
+    ...(0, util_1.range)(0x0bce, 0x0bd6),
+    ...(0, util_1.range)(0x0bd8, 0x0be6),
+    ...(0, util_1.range)(0x0bf3, 0x0c00),
+    0x0c04,
+    0x0c0d,
+    0x0c11,
+    0x0c29,
+    0x0c34,
+    ...(0, util_1.range)(0x0c3a, 0x0c3d),
+    0x0c45,
+    0x0c49,
+    ...(0, util_1.range)(0x0c4e, 0x0c54),
+    ...(0, util_1.range)(0x0c57, 0x0c5f),
+    ...(0, util_1.range)(0x0c62, 0x0c65),
+    ...(0, util_1.range)(0x0c70, 0x0c81),
+    0x0c84,
+    0x0c8d,
+    0x0c91,
+    0x0ca9,
+    0x0cb4,
+    ...(0, util_1.range)(0x0cba, 0x0cbd),
+    0x0cc5,
+    0x0cc9,
+    ...(0, util_1.range)(0x0cce, 0x0cd4),
+    ...(0, util_1.range)(0x0cd7, 0x0cdd),
+    0x0cdf,
+    ...(0, util_1.range)(0x0ce2, 0x0ce5),
+    ...(0, util_1.range)(0x0cf0, 0x0d01),
+    0x0d04,
+    0x0d0d,
+    0x0d11,
+    0x0d29,
+    ...(0, util_1.range)(0x0d3a, 0x0d3d),
+    ...(0, util_1.range)(0x0d44, 0x0d45),
+    0x0d49,
+    ...(0, util_1.range)(0x0d4e, 0x0d56),
+    ...(0, util_1.range)(0x0d58, 0x0d5f),
+    ...(0, util_1.range)(0x0d62, 0x0d65),
+    ...(0, util_1.range)(0x0d70, 0x0d81),
+    0x0d84,
+    ...(0, util_1.range)(0x0d97, 0x0d99),
+    0x0db2,
+    0x0dbc,
+    ...(0, util_1.range)(0x0dbe, 0x0dbf),
+    ...(0, util_1.range)(0x0dc7, 0x0dc9),
+    ...(0, util_1.range)(0x0dcb, 0x0dce),
+    0x0dd5,
+    0x0dd7,
+    ...(0, util_1.range)(0x0de0, 0x0df1),
+    ...(0, util_1.range)(0x0df5, 0x0e00),
+    ...(0, util_1.range)(0x0e3b, 0x0e3e),
+    ...(0, util_1.range)(0x0e5c, 0x0e80),
+    0x0e83,
+    ...(0, util_1.range)(0x0e85, 0x0e86),
+    0x0e89,
+    ...(0, util_1.range)(0x0e8b, 0x0e8c),
+    ...(0, util_1.range)(0x0e8e, 0x0e93),
+    0x0e98,
+    0x0ea0,
+    0x0ea4,
+    0x0ea6,
+    ...(0, util_1.range)(0x0ea8, 0x0ea9),
+    0x0eac,
+    0x0eba,
+    ...(0, util_1.range)(0x0ebe, 0x0ebf),
+    0x0ec5,
+    0x0ec7,
+    ...(0, util_1.range)(0x0ece, 0x0ecf),
+    ...(0, util_1.range)(0x0eda, 0x0edb),
+    ...(0, util_1.range)(0x0ede, 0x0eff),
+    0x0f48,
+    ...(0, util_1.range)(0x0f6b, 0x0f70),
+    ...(0, util_1.range)(0x0f8c, 0x0f8f),
+    0x0f98,
+    0x0fbd,
+    ...(0, util_1.range)(0x0fcd, 0x0fce),
+    ...(0, util_1.range)(0x0fd0, 0x0fff),
+    0x1022,
+    0x1028,
+    0x102b,
+    ...(0, util_1.range)(0x1033, 0x1035),
+    ...(0, util_1.range)(0x103a, 0x103f),
+    ...(0, util_1.range)(0x105a, 0x109f),
+    ...(0, util_1.range)(0x10c6, 0x10cf),
+    ...(0, util_1.range)(0x10f9, 0x10fa),
+    ...(0, util_1.range)(0x10fc, 0x10ff),
+    ...(0, util_1.range)(0x115a, 0x115e),
+    ...(0, util_1.range)(0x11a3, 0x11a7),
+    ...(0, util_1.range)(0x11fa, 0x11ff),
+    0x1207,
+    0x1247,
+    0x1249,
+    ...(0, util_1.range)(0x124e, 0x124f),
+    0x1257,
+    0x1259,
+    ...(0, util_1.range)(0x125e, 0x125f),
+    0x1287,
+    0x1289,
+    ...(0, util_1.range)(0x128e, 0x128f),
+    0x12af,
+    0x12b1,
+    ...(0, util_1.range)(0x12b6, 0x12b7),
+    0x12bf,
+    0x12c1,
+    ...(0, util_1.range)(0x12c6, 0x12c7),
+    0x12cf,
+    0x12d7,
+    0x12ef,
+    0x130f,
+    0x1311,
+    ...(0, util_1.range)(0x1316, 0x1317),
+    0x131f,
+    0x1347,
+    ...(0, util_1.range)(0x135b, 0x1360),
+    ...(0, util_1.range)(0x137d, 0x139f),
+    ...(0, util_1.range)(0x13f5, 0x1400),
+    ...(0, util_1.range)(0x1677, 0x167f),
+    ...(0, util_1.range)(0x169d, 0x169f),
+    ...(0, util_1.range)(0x16f1, 0x16ff),
+    0x170d,
+    ...(0, util_1.range)(0x1715, 0x171f),
+    ...(0, util_1.range)(0x1737, 0x173f),
+    ...(0, util_1.range)(0x1754, 0x175f),
+    0x176d,
+    0x1771,
+    ...(0, util_1.range)(0x1774, 0x177f),
+    ...(0, util_1.range)(0x17dd, 0x17df),
+    ...(0, util_1.range)(0x17ea, 0x17ff),
+    0x180f,
+    ...(0, util_1.range)(0x181a, 0x181f),
+    ...(0, util_1.range)(0x1878, 0x187f),
+    ...(0, util_1.range)(0x18aa, 0x1dff),
+    ...(0, util_1.range)(0x1e9c, 0x1e9f),
+    ...(0, util_1.range)(0x1efa, 0x1eff),
+    ...(0, util_1.range)(0x1f16, 0x1f17),
+    ...(0, util_1.range)(0x1f1e, 0x1f1f),
+    ...(0, util_1.range)(0x1f46, 0x1f47),
+    ...(0, util_1.range)(0x1f4e, 0x1f4f),
+    0x1f58,
+    0x1f5a,
+    0x1f5c,
+    0x1f5e,
+    ...(0, util_1.range)(0x1f7e, 0x1f7f),
+    0x1fb5,
+    0x1fc5,
+    ...(0, util_1.range)(0x1fd4, 0x1fd5),
+    0x1fdc,
+    ...(0, util_1.range)(0x1ff0, 0x1ff1),
+    0x1ff5,
+    0x1fff,
+    ...(0, util_1.range)(0x2053, 0x2056),
+    ...(0, util_1.range)(0x2058, 0x205e),
+    ...(0, util_1.range)(0x2064, 0x2069),
+    ...(0, util_1.range)(0x2072, 0x2073),
+    ...(0, util_1.range)(0x208f, 0x209f),
+    ...(0, util_1.range)(0x20b2, 0x20cf),
+    ...(0, util_1.range)(0x20eb, 0x20ff),
+    ...(0, util_1.range)(0x213b, 0x213c),
+    ...(0, util_1.range)(0x214c, 0x2152),
+    ...(0, util_1.range)(0x2184, 0x218f),
+    ...(0, util_1.range)(0x23cf, 0x23ff),
+    ...(0, util_1.range)(0x2427, 0x243f),
+    ...(0, util_1.range)(0x244b, 0x245f),
+    0x24ff,
+    ...(0, util_1.range)(0x2614, 0x2615),
+    0x2618,
+    ...(0, util_1.range)(0x267e, 0x267f),
+    ...(0, util_1.range)(0x268a, 0x2700),
+    0x2705,
+    ...(0, util_1.range)(0x270a, 0x270b),
+    0x2728,
+    0x274c,
+    0x274e,
+    ...(0, util_1.range)(0x2753, 0x2755),
+    0x2757,
+    ...(0, util_1.range)(0x275f, 0x2760),
+    ...(0, util_1.range)(0x2795, 0x2797),
+    0x27b0,
+    ...(0, util_1.range)(0x27bf, 0x27cf),
+    ...(0, util_1.range)(0x27ec, 0x27ef),
+    ...(0, util_1.range)(0x2b00, 0x2e7f),
+    0x2e9a,
+    ...(0, util_1.range)(0x2ef4, 0x2eff),
+    ...(0, util_1.range)(0x2fd6, 0x2fef),
+    ...(0, util_1.range)(0x2ffc, 0x2fff),
+    0x3040,
+    ...(0, util_1.range)(0x3097, 0x3098),
+    ...(0, util_1.range)(0x3100, 0x3104),
+    ...(0, util_1.range)(0x312d, 0x3130),
+    0x318f,
+    ...(0, util_1.range)(0x31b8, 0x31ef),
+    ...(0, util_1.range)(0x321d, 0x321f),
+    ...(0, util_1.range)(0x3244, 0x3250),
+    ...(0, util_1.range)(0x327c, 0x327e),
+    ...(0, util_1.range)(0x32cc, 0x32cf),
+    0x32ff,
+    ...(0, util_1.range)(0x3377, 0x337a),
+    ...(0, util_1.range)(0x33de, 0x33df),
+    0x33ff,
+    ...(0, util_1.range)(0x4db6, 0x4dff),
+    ...(0, util_1.range)(0x9fa6, 0x9fff),
+    ...(0, util_1.range)(0xa48d, 0xa48f),
+    ...(0, util_1.range)(0xa4c7, 0xabff),
+    ...(0, util_1.range)(0xd7a4, 0xd7ff),
+    ...(0, util_1.range)(0xfa2e, 0xfa2f),
+    ...(0, util_1.range)(0xfa6b, 0xfaff),
+    ...(0, util_1.range)(0xfb07, 0xfb12),
+    ...(0, util_1.range)(0xfb18, 0xfb1c),
+    0xfb37,
+    0xfb3d,
+    0xfb3f,
+    0xfb42,
+    0xfb45,
+    ...(0, util_1.range)(0xfbb2, 0xfbd2),
+    ...(0, util_1.range)(0xfd40, 0xfd4f),
+    ...(0, util_1.range)(0xfd90, 0xfd91),
+    ...(0, util_1.range)(0xfdc8, 0xfdcf),
+    ...(0, util_1.range)(0xfdfd, 0xfdff),
+    ...(0, util_1.range)(0xfe10, 0xfe1f),
+    ...(0, util_1.range)(0xfe24, 0xfe2f),
+    ...(0, util_1.range)(0xfe47, 0xfe48),
+    0xfe53,
+    0xfe67,
+    ...(0, util_1.range)(0xfe6c, 0xfe6f),
+    0xfe75,
+    ...(0, util_1.range)(0xfefd, 0xfefe),
+    0xff00,
+    ...(0, util_1.range)(0xffbf, 0xffc1),
+    ...(0, util_1.range)(0xffc8, 0xffc9),
+    ...(0, util_1.range)(0xffd0, 0xffd1),
+    ...(0, util_1.range)(0xffd8, 0xffd9),
+    ...(0, util_1.range)(0xffdd, 0xffdf),
+    0xffe7,
+    ...(0, util_1.range)(0xffef, 0xfff8),
+    ...(0, util_1.range)(0x10000, 0x102ff),
+    0x1031f,
+    ...(0, util_1.range)(0x10324, 0x1032f),
+    ...(0, util_1.range)(0x1034b, 0x103ff),
+    ...(0, util_1.range)(0x10426, 0x10427),
+    ...(0, util_1.range)(0x1044e, 0x1cfff),
+    ...(0, util_1.range)(0x1d0f6, 0x1d0ff),
+    ...(0, util_1.range)(0x1d127, 0x1d129),
+    ...(0, util_1.range)(0x1d1de, 0x1d3ff),
+    0x1d455,
+    0x1d49d,
+    ...(0, util_1.range)(0x1d4a0, 0x1d4a1),
+    ...(0, util_1.range)(0x1d4a3, 0x1d4a4),
+    ...(0, util_1.range)(0x1d4a7, 0x1d4a8),
+    0x1d4ad,
+    0x1d4ba,
+    0x1d4bc,
+    0x1d4c1,
+    0x1d4c4,
+    0x1d506,
+    ...(0, util_1.range)(0x1d50b, 0x1d50c),
+    0x1d515,
+    0x1d51d,
+    0x1d53a,
+    0x1d53f,
+    0x1d545,
+    ...(0, util_1.range)(0x1d547, 0x1d549),
+    0x1d551,
+    ...(0, util_1.range)(0x1d6a4, 0x1d6a7),
+    ...(0, util_1.range)(0x1d7ca, 0x1d7cd),
+    ...(0, util_1.range)(0x1d800, 0x1fffd),
+    ...(0, util_1.range)(0x2a6d7, 0x2f7ff),
+    ...(0, util_1.range)(0x2fa1e, 0x2fffd),
+    ...(0, util_1.range)(0x30000, 0x3fffd),
+    ...(0, util_1.range)(0x40000, 0x4fffd),
+    ...(0, util_1.range)(0x50000, 0x5fffd),
+    ...(0, util_1.range)(0x60000, 0x6fffd),
+    ...(0, util_1.range)(0x70000, 0x7fffd),
+    ...(0, util_1.range)(0x80000, 0x8fffd),
+    ...(0, util_1.range)(0x90000, 0x9fffd),
+    ...(0, util_1.range)(0xa0000, 0xafffd),
+    ...(0, util_1.range)(0xb0000, 0xbfffd),
+    ...(0, util_1.range)(0xc0000, 0xcfffd),
+    ...(0, util_1.range)(0xd0000, 0xdfffd),
+    0xe0000,
+    ...(0, util_1.range)(0xe0002, 0xe001f),
+    ...(0, util_1.range)(0xe0080, 0xefffd),
+]);
+exports.commonly_mapped_to_nothing = new Set([
+    0x00ad, 0x034f, 0x1806, 0x180b, 0x180c, 0x180d, 0x200b, 0x200c, 0x200d,
+    0x2060, 0xfe00, 0xfe01, 0xfe02, 0xfe03, 0xfe04, 0xfe05, 0xfe06, 0xfe07,
+    0xfe08, 0xfe09, 0xfe0a, 0xfe0b, 0xfe0c, 0xfe0d, 0xfe0e, 0xfe0f, 0xfeff,
+]);
+exports.non_ASCII_space_characters = new Set([
+    0x00a0, 0x1680,
+    0x2000, 0x2001, 0x2002,
+    0x2003, 0x2004,
+    0x2005, 0x2006,
+    0x2007, 0x2008,
+    0x2009, 0x200a,
+    0x200b, 0x202f,
+    0x205f, 0x3000,
+]);
+exports.prohibited_characters = new Set([
+    ...exports.non_ASCII_space_characters,
+    ...(0, util_1.range)(0, 0x001f),
+    0x007f,
+    ...(0, util_1.range)(0x0080, 0x009f),
+    0x06dd,
+    0x070f,
+    0x180e,
+    0x200c,
+    0x200d,
+    0x2028,
+    0x2029,
+    0x2060,
+    0x2061,
+    0x2062,
+    0x2063,
+    ...(0, util_1.range)(0x206a, 0x206f),
+    0xfeff,
+    ...(0, util_1.range)(0xfff9, 0xfffc),
+    ...(0, util_1.range)(0x1d173, 0x1d17a),
+    ...(0, util_1.range)(0xe000, 0xf8ff),
+    ...(0, util_1.range)(0xf0000, 0xffffd),
+    ...(0, util_1.range)(0x100000, 0x10fffd),
+    ...(0, util_1.range)(0xfdd0, 0xfdef),
+    ...(0, util_1.range)(0xfffe, 0xffff),
+    ...(0, util_1.range)(0x1fffe, 0x1ffff),
+    ...(0, util_1.range)(0x2fffe, 0x2ffff),
+    ...(0, util_1.range)(0x3fffe, 0x3ffff),
+    ...(0, util_1.range)(0x4fffe, 0x4ffff),
+    ...(0, util_1.range)(0x5fffe, 0x5ffff),
+    ...(0, util_1.range)(0x6fffe, 0x6ffff),
+    ...(0, util_1.range)(0x7fffe, 0x7ffff),
+    ...(0, util_1.range)(0x8fffe, 0x8ffff),
+    ...(0, util_1.range)(0x9fffe, 0x9ffff),
+    ...(0, util_1.range)(0xafffe, 0xaffff),
+    ...(0, util_1.range)(0xbfffe, 0xbffff),
+    ...(0, util_1.range)(0xcfffe, 0xcffff),
+    ...(0, util_1.range)(0xdfffe, 0xdffff),
+    ...(0, util_1.range)(0xefffe, 0xeffff),
+    ...(0, util_1.range)(0x10fffe, 0x10ffff),
+    ...(0, util_1.range)(0xd800, 0xdfff),
+    0xfff9,
+    0xfffa,
+    0xfffb,
+    0xfffc,
+    0xfffd,
+    ...(0, util_1.range)(0x2ff0, 0x2ffb),
+    0x0340,
+    0x0341,
+    0x200e,
+    0x200f,
+    0x202a,
+    0x202b,
+    0x202c,
+    0x202d,
+    0x202e,
+    0x206a,
+    0x206b,
+    0x206c,
+    0x206d,
+    0x206e,
+    0x206f,
+    0xe0001,
+    ...(0, util_1.range)(0xe0020, 0xe007f),
+]);
+exports.bidirectional_r_al = new Set([
+    0x05be,
+    0x05c0,
+    0x05c3,
+    ...(0, util_1.range)(0x05d0, 0x05ea),
+    ...(0, util_1.range)(0x05f0, 0x05f4),
+    0x061b,
+    0x061f,
+    ...(0, util_1.range)(0x0621, 0x063a),
+    ...(0, util_1.range)(0x0640, 0x064a),
+    ...(0, util_1.range)(0x066d, 0x066f),
+    ...(0, util_1.range)(0x0671, 0x06d5),
+    0x06dd,
+    ...(0, util_1.range)(0x06e5, 0x06e6),
+    ...(0, util_1.range)(0x06fa, 0x06fe),
+    ...(0, util_1.range)(0x0700, 0x070d),
+    0x0710,
+    ...(0, util_1.range)(0x0712, 0x072c),
+    ...(0, util_1.range)(0x0780, 0x07a5),
+    0x07b1,
+    0x200f,
+    0xfb1d,
+    ...(0, util_1.range)(0xfb1f, 0xfb28),
+    ...(0, util_1.range)(0xfb2a, 0xfb36),
+    ...(0, util_1.range)(0xfb38, 0xfb3c),
+    0xfb3e,
+    ...(0, util_1.range)(0xfb40, 0xfb41),
+    ...(0, util_1.range)(0xfb43, 0xfb44),
+    ...(0, util_1.range)(0xfb46, 0xfbb1),
+    ...(0, util_1.range)(0xfbd3, 0xfd3d),
+    ...(0, util_1.range)(0xfd50, 0xfd8f),
+    ...(0, util_1.range)(0xfd92, 0xfdc7),
+    ...(0, util_1.range)(0xfdf0, 0xfdfc),
+    ...(0, util_1.range)(0xfe70, 0xfe74),
+    ...(0, util_1.range)(0xfe76, 0xfefc),
+]);
+exports.bidirectional_l = new Set([
+    ...(0, util_1.range)(0x0041, 0x005a),
+    ...(0, util_1.range)(0x0061, 0x007a),
+    0x00aa,
+    0x00b5,
+    0x00ba,
+    ...(0, util_1.range)(0x00c0, 0x00d6),
+    ...(0, util_1.range)(0x00d8, 0x00f6),
+    ...(0, util_1.range)(0x00f8, 0x0220),
+    ...(0, util_1.range)(0x0222, 0x0233),
+    ...(0, util_1.range)(0x0250, 0x02ad),
+    ...(0, util_1.range)(0x02b0, 0x02b8),
+    ...(0, util_1.range)(0x02bb, 0x02c1),
+    ...(0, util_1.range)(0x02d0, 0x02d1),
+    ...(0, util_1.range)(0x02e0, 0x02e4),
+    0x02ee,
+    0x037a,
+    0x0386,
+    ...(0, util_1.range)(0x0388, 0x038a),
+    0x038c,
+    ...(0, util_1.range)(0x038e, 0x03a1),
+    ...(0, util_1.range)(0x03a3, 0x03ce),
+    ...(0, util_1.range)(0x03d0, 0x03f5),
+    ...(0, util_1.range)(0x0400, 0x0482),
+    ...(0, util_1.range)(0x048a, 0x04ce),
+    ...(0, util_1.range)(0x04d0, 0x04f5),
+    ...(0, util_1.range)(0x04f8, 0x04f9),
+    ...(0, util_1.range)(0x0500, 0x050f),
+    ...(0, util_1.range)(0x0531, 0x0556),
+    ...(0, util_1.range)(0x0559, 0x055f),
+    ...(0, util_1.range)(0x0561, 0x0587),
+    0x0589,
+    0x0903,
+    ...(0, util_1.range)(0x0905, 0x0939),
+    ...(0, util_1.range)(0x093d, 0x0940),
+    ...(0, util_1.range)(0x0949, 0x094c),
+    0x0950,
+    ...(0, util_1.range)(0x0958, 0x0961),
+    ...(0, util_1.range)(0x0964, 0x0970),
+    ...(0, util_1.range)(0x0982, 0x0983),
+    ...(0, util_1.range)(0x0985, 0x098c),
+    ...(0, util_1.range)(0x098f, 0x0990),
+    ...(0, util_1.range)(0x0993, 0x09a8),
+    ...(0, util_1.range)(0x09aa, 0x09b0),
+    0x09b2,
+    ...(0, util_1.range)(0x09b6, 0x09b9),
+    ...(0, util_1.range)(0x09be, 0x09c0),
+    ...(0, util_1.range)(0x09c7, 0x09c8),
+    ...(0, util_1.range)(0x09cb, 0x09cc),
+    0x09d7,
+    ...(0, util_1.range)(0x09dc, 0x09dd),
+    ...(0, util_1.range)(0x09df, 0x09e1),
+    ...(0, util_1.range)(0x09e6, 0x09f1),
+    ...(0, util_1.range)(0x09f4, 0x09fa),
+    ...(0, util_1.range)(0x0a05, 0x0a0a),
+    ...(0, util_1.range)(0x0a0f, 0x0a10),
+    ...(0, util_1.range)(0x0a13, 0x0a28),
+    ...(0, util_1.range)(0x0a2a, 0x0a30),
+    ...(0, util_1.range)(0x0a32, 0x0a33),
+    ...(0, util_1.range)(0x0a35, 0x0a36),
+    ...(0, util_1.range)(0x0a38, 0x0a39),
+    ...(0, util_1.range)(0x0a3e, 0x0a40),
+    ...(0, util_1.range)(0x0a59, 0x0a5c),
+    0x0a5e,
+    ...(0, util_1.range)(0x0a66, 0x0a6f),
+    ...(0, util_1.range)(0x0a72, 0x0a74),
+    0x0a83,
+    ...(0, util_1.range)(0x0a85, 0x0a8b),
+    0x0a8d,
+    ...(0, util_1.range)(0x0a8f, 0x0a91),
+    ...(0, util_1.range)(0x0a93, 0x0aa8),
+    ...(0, util_1.range)(0x0aaa, 0x0ab0),
+    ...(0, util_1.range)(0x0ab2, 0x0ab3),
+    ...(0, util_1.range)(0x0ab5, 0x0ab9),
+    ...(0, util_1.range)(0x0abd, 0x0ac0),
+    0x0ac9,
+    ...(0, util_1.range)(0x0acb, 0x0acc),
+    0x0ad0,
+    0x0ae0,
+    ...(0, util_1.range)(0x0ae6, 0x0aef),
+    ...(0, util_1.range)(0x0b02, 0x0b03),
+    ...(0, util_1.range)(0x0b05, 0x0b0c),
+    ...(0, util_1.range)(0x0b0f, 0x0b10),
+    ...(0, util_1.range)(0x0b13, 0x0b28),
+    ...(0, util_1.range)(0x0b2a, 0x0b30),
+    ...(0, util_1.range)(0x0b32, 0x0b33),
+    ...(0, util_1.range)(0x0b36, 0x0b39),
+    ...(0, util_1.range)(0x0b3d, 0x0b3e),
+    0x0b40,
+    ...(0, util_1.range)(0x0b47, 0x0b48),
+    ...(0, util_1.range)(0x0b4b, 0x0b4c),
+    0x0b57,
+    ...(0, util_1.range)(0x0b5c, 0x0b5d),
+    ...(0, util_1.range)(0x0b5f, 0x0b61),
+    ...(0, util_1.range)(0x0b66, 0x0b70),
+    0x0b83,
+    ...(0, util_1.range)(0x0b85, 0x0b8a),
+    ...(0, util_1.range)(0x0b8e, 0x0b90),
+    ...(0, util_1.range)(0x0b92, 0x0b95),
+    ...(0, util_1.range)(0x0b99, 0x0b9a),
+    0x0b9c,
+    ...(0, util_1.range)(0x0b9e, 0x0b9f),
+    ...(0, util_1.range)(0x0ba3, 0x0ba4),
+    ...(0, util_1.range)(0x0ba8, 0x0baa),
+    ...(0, util_1.range)(0x0bae, 0x0bb5),
+    ...(0, util_1.range)(0x0bb7, 0x0bb9),
+    ...(0, util_1.range)(0x0bbe, 0x0bbf),
+    ...(0, util_1.range)(0x0bc1, 0x0bc2),
+    ...(0, util_1.range)(0x0bc6, 0x0bc8),
+    ...(0, util_1.range)(0x0bca, 0x0bcc),
+    0x0bd7,
+    ...(0, util_1.range)(0x0be7, 0x0bf2),
+    ...(0, util_1.range)(0x0c01, 0x0c03),
+    ...(0, util_1.range)(0x0c05, 0x0c0c),
+    ...(0, util_1.range)(0x0c0e, 0x0c10),
+    ...(0, util_1.range)(0x0c12, 0x0c28),
+    ...(0, util_1.range)(0x0c2a, 0x0c33),
+    ...(0, util_1.range)(0x0c35, 0x0c39),
+    ...(0, util_1.range)(0x0c41, 0x0c44),
+    ...(0, util_1.range)(0x0c60, 0x0c61),
+    ...(0, util_1.range)(0x0c66, 0x0c6f),
+    ...(0, util_1.range)(0x0c82, 0x0c83),
+    ...(0, util_1.range)(0x0c85, 0x0c8c),
+    ...(0, util_1.range)(0x0c8e, 0x0c90),
+    ...(0, util_1.range)(0x0c92, 0x0ca8),
+    ...(0, util_1.range)(0x0caa, 0x0cb3),
+    ...(0, util_1.range)(0x0cb5, 0x0cb9),
+    0x0cbe,
+    ...(0, util_1.range)(0x0cc0, 0x0cc4),
+    ...(0, util_1.range)(0x0cc7, 0x0cc8),
+    ...(0, util_1.range)(0x0cca, 0x0ccb),
+    ...(0, util_1.range)(0x0cd5, 0x0cd6),
+    0x0cde,
+    ...(0, util_1.range)(0x0ce0, 0x0ce1),
+    ...(0, util_1.range)(0x0ce6, 0x0cef),
+    ...(0, util_1.range)(0x0d02, 0x0d03),
+    ...(0, util_1.range)(0x0d05, 0x0d0c),
+    ...(0, util_1.range)(0x0d0e, 0x0d10),
+    ...(0, util_1.range)(0x0d12, 0x0d28),
+    ...(0, util_1.range)(0x0d2a, 0x0d39),
+    ...(0, util_1.range)(0x0d3e, 0x0d40),
+    ...(0, util_1.range)(0x0d46, 0x0d48),
+    ...(0, util_1.range)(0x0d4a, 0x0d4c),
+    0x0d57,
+    ...(0, util_1.range)(0x0d60, 0x0d61),
+    ...(0, util_1.range)(0x0d66, 0x0d6f),
+    ...(0, util_1.range)(0x0d82, 0x0d83),
+    ...(0, util_1.range)(0x0d85, 0x0d96),
+    ...(0, util_1.range)(0x0d9a, 0x0db1),
+    ...(0, util_1.range)(0x0db3, 0x0dbb),
+    0x0dbd,
+    ...(0, util_1.range)(0x0dc0, 0x0dc6),
+    ...(0, util_1.range)(0x0dcf, 0x0dd1),
+    ...(0, util_1.range)(0x0dd8, 0x0ddf),
+    ...(0, util_1.range)(0x0df2, 0x0df4),
+    ...(0, util_1.range)(0x0e01, 0x0e30),
+    ...(0, util_1.range)(0x0e32, 0x0e33),
+    ...(0, util_1.range)(0x0e40, 0x0e46),
+    ...(0, util_1.range)(0x0e4f, 0x0e5b),
+    ...(0, util_1.range)(0x0e81, 0x0e82),
+    0x0e84,
+    ...(0, util_1.range)(0x0e87, 0x0e88),
+    0x0e8a,
+    0x0e8d,
+    ...(0, util_1.range)(0x0e94, 0x0e97),
+    ...(0, util_1.range)(0x0e99, 0x0e9f),
+    ...(0, util_1.range)(0x0ea1, 0x0ea3),
+    0x0ea5,
+    0x0ea7,
+    ...(0, util_1.range)(0x0eaa, 0x0eab),
+    ...(0, util_1.range)(0x0ead, 0x0eb0),
+    ...(0, util_1.range)(0x0eb2, 0x0eb3),
+    0x0ebd,
+    ...(0, util_1.range)(0x0ec0, 0x0ec4),
+    0x0ec6,
+    ...(0, util_1.range)(0x0ed0, 0x0ed9),
+    ...(0, util_1.range)(0x0edc, 0x0edd),
+    ...(0, util_1.range)(0x0f00, 0x0f17),
+    ...(0, util_1.range)(0x0f1a, 0x0f34),
+    0x0f36,
+    0x0f38,
+    ...(0, util_1.range)(0x0f3e, 0x0f47),
+    ...(0, util_1.range)(0x0f49, 0x0f6a),
+    0x0f7f,
+    0x0f85,
+    ...(0, util_1.range)(0x0f88, 0x0f8b),
+    ...(0, util_1.range)(0x0fbe, 0x0fc5),
+    ...(0, util_1.range)(0x0fc7, 0x0fcc),
+    0x0fcf,
+    ...(0, util_1.range)(0x1000, 0x1021),
+    ...(0, util_1.range)(0x1023, 0x1027),
+    ...(0, util_1.range)(0x1029, 0x102a),
+    0x102c,
+    0x1031,
+    0x1038,
+    ...(0, util_1.range)(0x1040, 0x1057),
+    ...(0, util_1.range)(0x10a0, 0x10c5),
+    ...(0, util_1.range)(0x10d0, 0x10f8),
+    0x10fb,
+    ...(0, util_1.range)(0x1100, 0x1159),
+    ...(0, util_1.range)(0x115f, 0x11a2),
+    ...(0, util_1.range)(0x11a8, 0x11f9),
+    ...(0, util_1.range)(0x1200, 0x1206),
+    ...(0, util_1.range)(0x1208, 0x1246),
+    0x1248,
+    ...(0, util_1.range)(0x124a, 0x124d),
+    ...(0, util_1.range)(0x1250, 0x1256),
+    0x1258,
+    ...(0, util_1.range)(0x125a, 0x125d),
+    ...(0, util_1.range)(0x1260, 0x1286),
+    0x1288,
+    ...(0, util_1.range)(0x128a, 0x128d),
+    ...(0, util_1.range)(0x1290, 0x12ae),
+    0x12b0,
+    ...(0, util_1.range)(0x12b2, 0x12b5),
+    ...(0, util_1.range)(0x12b8, 0x12be),
+    0x12c0,
+    ...(0, util_1.range)(0x12c2, 0x12c5),
+    ...(0, util_1.range)(0x12c8, 0x12ce),
+    ...(0, util_1.range)(0x12d0, 0x12d6),
+    ...(0, util_1.range)(0x12d8, 0x12ee),
+    ...(0, util_1.range)(0x12f0, 0x130e),
+    0x1310,
+    ...(0, util_1.range)(0x1312, 0x1315),
+    ...(0, util_1.range)(0x1318, 0x131e),
+    ...(0, util_1.range)(0x1320, 0x1346),
+    ...(0, util_1.range)(0x1348, 0x135a),
+    ...(0, util_1.range)(0x1361, 0x137c),
+    ...(0, util_1.range)(0x13a0, 0x13f4),
+    ...(0, util_1.range)(0x1401, 0x1676),
+    ...(0, util_1.range)(0x1681, 0x169a),
+    ...(0, util_1.range)(0x16a0, 0x16f0),
+    ...(0, util_1.range)(0x1700, 0x170c),
+    ...(0, util_1.range)(0x170e, 0x1711),
+    ...(0, util_1.range)(0x1720, 0x1731),
+    ...(0, util_1.range)(0x1735, 0x1736),
+    ...(0, util_1.range)(0x1740, 0x1751),
+    ...(0, util_1.range)(0x1760, 0x176c),
+    ...(0, util_1.range)(0x176e, 0x1770),
+    ...(0, util_1.range)(0x1780, 0x17b6),
+    ...(0, util_1.range)(0x17be, 0x17c5),
+    ...(0, util_1.range)(0x17c7, 0x17c8),
+    ...(0, util_1.range)(0x17d4, 0x17da),
+    0x17dc,
+    ...(0, util_1.range)(0x17e0, 0x17e9),
+    ...(0, util_1.range)(0x1810, 0x1819),
+    ...(0, util_1.range)(0x1820, 0x1877),
+    ...(0, util_1.range)(0x1880, 0x18a8),
+    ...(0, util_1.range)(0x1e00, 0x1e9b),
+    ...(0, util_1.range)(0x1ea0, 0x1ef9),
+    ...(0, util_1.range)(0x1f00, 0x1f15),
+    ...(0, util_1.range)(0x1f18, 0x1f1d),
+    ...(0, util_1.range)(0x1f20, 0x1f45),
+    ...(0, util_1.range)(0x1f48, 0x1f4d),
+    ...(0, util_1.range)(0x1f50, 0x1f57),
+    0x1f59,
+    0x1f5b,
+    0x1f5d,
+    ...(0, util_1.range)(0x1f5f, 0x1f7d),
+    ...(0, util_1.range)(0x1f80, 0x1fb4),
+    ...(0, util_1.range)(0x1fb6, 0x1fbc),
+    0x1fbe,
+    ...(0, util_1.range)(0x1fc2, 0x1fc4),
+    ...(0, util_1.range)(0x1fc6, 0x1fcc),
+    ...(0, util_1.range)(0x1fd0, 0x1fd3),
+    ...(0, util_1.range)(0x1fd6, 0x1fdb),
+    ...(0, util_1.range)(0x1fe0, 0x1fec),
+    ...(0, util_1.range)(0x1ff2, 0x1ff4),
+    ...(0, util_1.range)(0x1ff6, 0x1ffc),
+    0x200e,
+    0x2071,
+    0x207f,
+    0x2102,
+    0x2107,
+    ...(0, util_1.range)(0x210a, 0x2113),
+    0x2115,
+    ...(0, util_1.range)(0x2119, 0x211d),
+    0x2124,
+    0x2126,
+    0x2128,
+    ...(0, util_1.range)(0x212a, 0x212d),
+    ...(0, util_1.range)(0x212f, 0x2131),
+    ...(0, util_1.range)(0x2133, 0x2139),
+    ...(0, util_1.range)(0x213d, 0x213f),
+    ...(0, util_1.range)(0x2145, 0x2149),
+    ...(0, util_1.range)(0x2160, 0x2183),
+    ...(0, util_1.range)(0x2336, 0x237a),
+    0x2395,
+    ...(0, util_1.range)(0x249c, 0x24e9),
+    ...(0, util_1.range)(0x3005, 0x3007),
+    ...(0, util_1.range)(0x3021, 0x3029),
+    ...(0, util_1.range)(0x3031, 0x3035),
+    ...(0, util_1.range)(0x3038, 0x303c),
+    ...(0, util_1.range)(0x3041, 0x3096),
+    ...(0, util_1.range)(0x309d, 0x309f),
+    ...(0, util_1.range)(0x30a1, 0x30fa),
+    ...(0, util_1.range)(0x30fc, 0x30ff),
+    ...(0, util_1.range)(0x3105, 0x312c),
+    ...(0, util_1.range)(0x3131, 0x318e),
+    ...(0, util_1.range)(0x3190, 0x31b7),
+    ...(0, util_1.range)(0x31f0, 0x321c),
+    ...(0, util_1.range)(0x3220, 0x3243),
+    ...(0, util_1.range)(0x3260, 0x327b),
+    ...(0, util_1.range)(0x327f, 0x32b0),
+    ...(0, util_1.range)(0x32c0, 0x32cb),
+    ...(0, util_1.range)(0x32d0, 0x32fe),
+    ...(0, util_1.range)(0x3300, 0x3376),
+    ...(0, util_1.range)(0x337b, 0x33dd),
+    ...(0, util_1.range)(0x33e0, 0x33fe),
+    ...(0, util_1.range)(0x3400, 0x4db5),
+    ...(0, util_1.range)(0x4e00, 0x9fa5),
+    ...(0, util_1.range)(0xa000, 0xa48c),
+    ...(0, util_1.range)(0xac00, 0xd7a3),
+    ...(0, util_1.range)(0xd800, 0xfa2d),
+    ...(0, util_1.range)(0xfa30, 0xfa6a),
+    ...(0, util_1.range)(0xfb00, 0xfb06),
+    ...(0, util_1.range)(0xfb13, 0xfb17),
+    ...(0, util_1.range)(0xff21, 0xff3a),
+    ...(0, util_1.range)(0xff41, 0xff5a),
+    ...(0, util_1.range)(0xff66, 0xffbe),
+    ...(0, util_1.range)(0xffc2, 0xffc7),
+    ...(0, util_1.range)(0xffca, 0xffcf),
+    ...(0, util_1.range)(0xffd2, 0xffd7),
+    ...(0, util_1.range)(0xffda, 0xffdc),
+    ...(0, util_1.range)(0x10300, 0x1031e),
+    ...(0, util_1.range)(0x10320, 0x10323),
+    ...(0, util_1.range)(0x10330, 0x1034a),
+    ...(0, util_1.range)(0x10400, 0x10425),
+    ...(0, util_1.range)(0x10428, 0x1044d),
+    ...(0, util_1.range)(0x1d000, 0x1d0f5),
+    ...(0, util_1.range)(0x1d100, 0x1d126),
+    ...(0, util_1.range)(0x1d12a, 0x1d166),
+    ...(0, util_1.range)(0x1d16a, 0x1d172),
+    ...(0, util_1.range)(0x1d183, 0x1d184),
+    ...(0, util_1.range)(0x1d18c, 0x1d1a9),
+    ...(0, util_1.range)(0x1d1ae, 0x1d1dd),
+    ...(0, util_1.range)(0x1d400, 0x1d454),
+    ...(0, util_1.range)(0x1d456, 0x1d49c),
+    ...(0, util_1.range)(0x1d49e, 0x1d49f),
+    0x1d4a2,
+    ...(0, util_1.range)(0x1d4a5, 0x1d4a6),
+    ...(0, util_1.range)(0x1d4a9, 0x1d4ac),
+    ...(0, util_1.range)(0x1d4ae, 0x1d4b9),
+    0x1d4bb,
+    ...(0, util_1.range)(0x1d4bd, 0x1d4c0),
+    ...(0, util_1.range)(0x1d4c2, 0x1d4c3),
+    ...(0, util_1.range)(0x1d4c5, 0x1d505),
+    ...(0, util_1.range)(0x1d507, 0x1d50a),
+    ...(0, util_1.range)(0x1d50d, 0x1d514),
+    ...(0, util_1.range)(0x1d516, 0x1d51c),
+    ...(0, util_1.range)(0x1d51e, 0x1d539),
+    ...(0, util_1.range)(0x1d53b, 0x1d53e),
+    ...(0, util_1.range)(0x1d540, 0x1d544),
+    0x1d546,
+    ...(0, util_1.range)(0x1d54a, 0x1d550),
+    ...(0, util_1.range)(0x1d552, 0x1d6a3),
+    ...(0, util_1.range)(0x1d6a8, 0x1d7c9),
+    ...(0, util_1.range)(0x20000, 0x2a6d6),
+    ...(0, util_1.range)(0x2f800, 0x2fa1d),
+    ...(0, util_1.range)(0xf0000, 0xffffd),
+    ...(0, util_1.range)(0x100000, 0x10fffd),
+]);
+//# sourceMappingURL=code-points-src.js.map

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
node_modules/@mongodb-js/saslprep/dist/code-points-src.js.map


+ 2 - 0
node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts

@@ -0,0 +1,2 @@
+export {};
+//# sourceMappingURL=generate-code-points.d.ts.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/generate-code-points.d.ts.map

@@ -0,0 +1 @@
+{"version":3,"file":"generate-code-points.d.ts","sourceRoot":"","sources":["../src/generate-code-points.ts"],"names":[],"mappings":""}

+ 83 - 0
node_modules/@mongodb-js/saslprep/dist/generate-code-points.js

@@ -0,0 +1,83 @@
+"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || (function () {
+    var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function (o) {
+            var ar = [];
+            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+            return ar;
+        };
+        return ownKeys(o);
+    };
+    return function (mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+        __setModuleDefault(result, mod);
+        return result;
+    };
+})();
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+const zlib_1 = require("zlib");
+const sparse_bitfield_1 = __importDefault(require("sparse-bitfield"));
+const codePoints = __importStar(require("./code-points-src"));
+const fs_1 = require("fs");
+const prettier = __importStar(require("prettier"));
+const unassigned_code_points = (0, sparse_bitfield_1.default)();
+const commonly_mapped_to_nothing = (0, sparse_bitfield_1.default)();
+const non_ascii_space_characters = (0, sparse_bitfield_1.default)();
+const prohibited_characters = (0, sparse_bitfield_1.default)();
+const bidirectional_r_al = (0, sparse_bitfield_1.default)();
+const bidirectional_l = (0, sparse_bitfield_1.default)();
+function traverse(bits, src) {
+    for (const code of src.keys()) {
+        bits.set(code, true);
+    }
+    const buffer = bits.toBuffer();
+    return Buffer.concat([createSize(buffer), buffer]);
+}
+function createSize(buffer) {
+    const buf = Buffer.alloc(4);
+    buf.writeUInt32BE(buffer.length);
+    return buf;
+}
+const memory = [];
+memory.push(traverse(unassigned_code_points, codePoints.unassigned_code_points), traverse(commonly_mapped_to_nothing, codePoints.commonly_mapped_to_nothing), traverse(non_ascii_space_characters, codePoints.non_ASCII_space_characters), traverse(prohibited_characters, codePoints.prohibited_characters), traverse(bidirectional_r_al, codePoints.bidirectional_r_al), traverse(bidirectional_l, codePoints.bidirectional_l));
+async function writeCodepoints() {
+    const config = await prettier.resolveConfig(__dirname);
+    const formatOptions = { ...config, parser: 'typescript' };
+    function write(stream, chunk) {
+        return new Promise((resolve) => stream.write(chunk, () => resolve()));
+    }
+    await write((0, fs_1.createWriteStream)(process.argv[2]), await prettier.format(`import { gunzipSync } from 'zlib';
+
+  export default gunzipSync(
+    Buffer.from(
+      '${(0, zlib_1.gzipSync)(Buffer.concat(memory), { level: 9 }).toString('base64')}',
+      'base64'
+    )
+  );
+  `, formatOptions));
+    const fsStreamUncompressedData = (0, fs_1.createWriteStream)(process.argv[3]);
+    await write(fsStreamUncompressedData, await prettier.format(`const data = Buffer.from('${Buffer.concat(memory).toString('base64')}', 'base64');\nexport default data;\n`, formatOptions));
+}
+writeCodepoints().catch((error) => console.error('error occurred generating saslprep codepoint data', { error }));
+//# sourceMappingURL=generate-code-points.js.map

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
node_modules/@mongodb-js/saslprep/dist/generate-code-points.js.map


+ 11 - 0
node_modules/@mongodb-js/saslprep/dist/index.d.ts

@@ -0,0 +1,11 @@
+import type { createMemoryCodePoints } from './memory-code-points';
+declare function saslprep({ unassigned_code_points, commonly_mapped_to_nothing, non_ASCII_space_characters, prohibited_characters, bidirectional_r_al, bidirectional_l, }: ReturnType<typeof createMemoryCodePoints>, input: string, opts?: {
+    allowUnassigned?: boolean;
+}): string;
+declare namespace saslprep {
+    export var saslprep: typeof import(".");
+    var _a: typeof import(".");
+    export { _a as default };
+}
+export = saslprep;
+//# sourceMappingURL=index.d.ts.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/index.d.ts.map

@@ -0,0 +1 @@
+{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAsCnE,iBAAS,QAAQ,CACf,EACE,sBAAsB,EACtB,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,kBAAkB,EAClB,eAAe,GAChB,EAAE,UAAU,CAAC,OAAO,sBAAsB,CAAC,EAC5C,KAAK,EAAE,MAAM,EACb,IAAI,GAAE;IAAE,eAAe,CAAC,EAAE,OAAO,CAAA;CAAO,GACvC,MAAM,CAqGR;kBAhHQ,QAAQ;;;;;AAoHjB,SAAS,QAAQ,CAAC"}

+ 65 - 0
node_modules/@mongodb-js/saslprep/dist/index.js

@@ -0,0 +1,65 @@
+"use strict";
+const getCodePoint = (character) => character.codePointAt(0);
+const first = (x) => x[0];
+const last = (x) => x[x.length - 1];
+function toCodePoints(input) {
+    const codepoints = [];
+    const size = input.length;
+    for (let i = 0; i < size; i += 1) {
+        const before = input.charCodeAt(i);
+        if (before >= 0xd800 && before <= 0xdbff && size > i + 1) {
+            const next = input.charCodeAt(i + 1);
+            if (next >= 0xdc00 && next <= 0xdfff) {
+                codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000);
+                i += 1;
+                continue;
+            }
+        }
+        codepoints.push(before);
+    }
+    return codepoints;
+}
+function saslprep({ unassigned_code_points, commonly_mapped_to_nothing, non_ASCII_space_characters, prohibited_characters, bidirectional_r_al, bidirectional_l, }, input, opts = {}) {
+    const mapping2space = non_ASCII_space_characters;
+    const mapping2nothing = commonly_mapped_to_nothing;
+    if (typeof input !== 'string') {
+        throw new TypeError('Expected string.');
+    }
+    if (input.length === 0) {
+        return '';
+    }
+    const mapped_input = toCodePoints(input)
+        .map((character) => (mapping2space.get(character) ? 0x20 : character))
+        .filter((character) => !mapping2nothing.get(character));
+    const normalized_input = String.fromCodePoint
+        .apply(null, mapped_input)
+        .normalize('NFKC');
+    const normalized_map = toCodePoints(normalized_input);
+    const hasProhibited = normalized_map.some((character) => prohibited_characters.get(character));
+    if (hasProhibited) {
+        throw new Error('Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3');
+    }
+    if (opts.allowUnassigned !== true) {
+        const hasUnassigned = normalized_map.some((character) => unassigned_code_points.get(character));
+        if (hasUnassigned) {
+            throw new Error('Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5');
+        }
+    }
+    const hasBidiRAL = normalized_map.some((character) => bidirectional_r_al.get(character));
+    const hasBidiL = normalized_map.some((character) => bidirectional_l.get(character));
+    if (hasBidiRAL && hasBidiL) {
+        throw new Error('String must not contain RandALCat and LCat at the same time,' +
+            ' see https://tools.ietf.org/html/rfc3454#section-6');
+    }
+    const isFirstBidiRAL = bidirectional_r_al.get(getCodePoint(first(normalized_input)));
+    const isLastBidiRAL = bidirectional_r_al.get(getCodePoint(last(normalized_input)));
+    if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) {
+        throw new Error('Bidirectional RandALCat character must be the first and the last' +
+            ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6');
+    }
+    return normalized_input;
+}
+saslprep.saslprep = saslprep;
+saslprep.default = saslprep;
+module.exports = saslprep;
+//# sourceMappingURL=index.js.map

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
node_modules/@mongodb-js/saslprep/dist/index.js.map


+ 10 - 0
node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts

@@ -0,0 +1,10 @@
+import bitfield from 'sparse-bitfield';
+export declare function createMemoryCodePoints(data: Buffer): {
+    unassigned_code_points: bitfield.BitFieldInstance;
+    commonly_mapped_to_nothing: bitfield.BitFieldInstance;
+    non_ASCII_space_characters: bitfield.BitFieldInstance;
+    prohibited_characters: bitfield.BitFieldInstance;
+    bidirectional_r_al: bitfield.BitFieldInstance;
+    bidirectional_l: bitfield.BitFieldInstance;
+};
+//# sourceMappingURL=memory-code-points.d.ts.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/memory-code-points.d.ts.map

@@ -0,0 +1 @@
+{"version":3,"file":"memory-code-points.d.ts","sourceRoot":"","sources":["../src/memory-code-points.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AAEvC,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM;;;;;;;EA+BlD"}

+ 32 - 0
node_modules/@mongodb-js/saslprep/dist/memory-code-points.js

@@ -0,0 +1,32 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.createMemoryCodePoints = createMemoryCodePoints;
+const sparse_bitfield_1 = __importDefault(require("sparse-bitfield"));
+function createMemoryCodePoints(data) {
+    let offset = 0;
+    function read() {
+        const size = data.readUInt32BE(offset);
+        offset += 4;
+        const codepoints = data.slice(offset, offset + size);
+        offset += size;
+        return (0, sparse_bitfield_1.default)({ buffer: codepoints });
+    }
+    const unassigned_code_points = read();
+    const commonly_mapped_to_nothing = read();
+    const non_ASCII_space_characters = read();
+    const prohibited_characters = read();
+    const bidirectional_r_al = read();
+    const bidirectional_l = read();
+    return {
+        unassigned_code_points,
+        commonly_mapped_to_nothing,
+        non_ASCII_space_characters,
+        prohibited_characters,
+        bidirectional_r_al,
+        bidirectional_l,
+    };
+}
+//# sourceMappingURL=memory-code-points.js.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/memory-code-points.js.map

@@ -0,0 +1 @@
+{"version":3,"file":"memory-code-points.js","sourceRoot":"","sources":["../src/memory-code-points.ts"],"names":[],"mappings":";;;;;AAEA,wDA+BC;AAjCD,sEAAuC;AAEvC,SAAgB,sBAAsB,CAAC,IAAY;IACjD,IAAI,MAAM,GAAG,CAAC,CAAC;IAKf,SAAS,IAAI;QACX,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;QACvC,MAAM,IAAI,CAAC,CAAC;QAEZ,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC;QACrD,MAAM,IAAI,IAAI,CAAC;QAEf,OAAO,IAAA,yBAAQ,EAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CAAC;IAC1C,CAAC;IAED,MAAM,sBAAsB,GAAG,IAAI,EAAE,CAAC;IACtC,MAAM,0BAA0B,GAAG,IAAI,EAAE,CAAC;IAC1C,MAAM,0BAA0B,GAAG,IAAI,EAAE,CAAC;IAC1C,MAAM,qBAAqB,GAAG,IAAI,EAAE,CAAC;IACrC,MAAM,kBAAkB,GAAG,IAAI,EAAE,CAAC;IAClC,MAAM,eAAe,GAAG,IAAI,EAAE,CAAC;IAE/B,OAAO;QACL,sBAAsB;QACtB,0BAA0B;QAC1B,0BAA0B;QAC1B,qBAAqB;QACrB,kBAAkB;QAClB,eAAe;KAChB,CAAC;AACJ,CAAC"}

+ 10 - 0
node_modules/@mongodb-js/saslprep/dist/node.d.ts

@@ -0,0 +1,10 @@
+declare function saslprep(input: string, opts?: {
+    allowUnassigned?: boolean;
+}): string;
+declare namespace saslprep {
+    export var saslprep: typeof import("./node");
+    var _a: typeof import("./node");
+    export { _a as default };
+}
+export = saslprep;
+//# sourceMappingURL=node.d.ts.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/node.d.ts.map

@@ -0,0 +1 @@
+{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAMA,iBAAS,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;IAAE,eAAe,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,MAAM,CAE7E;kBAFQ,QAAQ;;;;;AAOjB,SAAS,QAAQ,CAAC"}

+ 15 - 0
node_modules/@mongodb-js/saslprep/dist/node.js

@@ -0,0 +1,15 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+const index_1 = __importDefault(require("./index"));
+const memory_code_points_1 = require("./memory-code-points");
+const code_points_data_1 = __importDefault(require("./code-points-data"));
+const codePoints = (0, memory_code_points_1.createMemoryCodePoints)(code_points_data_1.default);
+function saslprep(input, opts) {
+    return (0, index_1.default)(codePoints, input, opts);
+}
+saslprep.saslprep = saslprep;
+saslprep.default = saslprep;
+module.exports = saslprep;
+//# sourceMappingURL=node.js.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/node.js.map

@@ -0,0 +1 @@
+{"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":";;;;AAAA,oDAAgC;AAChC,6DAA8D;AAC9D,0EAAsC;AAEtC,MAAM,UAAU,GAAG,IAAA,2CAAsB,EAAC,0BAAI,CAAC,CAAC;AAEhD,SAAS,QAAQ,CAAC,KAAa,EAAE,IAAoC;IACnE,OAAO,IAAA,eAAS,EAAC,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;AAC5C,CAAC;AAED,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC7B,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;AAE5B,iBAAS,QAAQ,CAAC"}

+ 2 - 0
node_modules/@mongodb-js/saslprep/dist/util.d.ts

@@ -0,0 +1,2 @@
+export declare function range(from: number, to: number): number[];
+//# sourceMappingURL=util.d.ts.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/util.d.ts.map

@@ -0,0 +1 @@
+{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAGA,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,CAQxD"}

+ 11 - 0
node_modules/@mongodb-js/saslprep/dist/util.js

@@ -0,0 +1,11 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.range = range;
+function range(from, to) {
+    const list = new Array(to - from + 1);
+    for (let i = 0; i < list.length; i += 1) {
+        list[i] = from + i;
+    }
+    return list;
+}
+//# sourceMappingURL=util.js.map

+ 1 - 0
node_modules/@mongodb-js/saslprep/dist/util.js.map

@@ -0,0 +1 @@
+{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;AAGA,sBAQC;AARD,SAAgB,KAAK,CAAC,IAAY,EAAE,EAAU;IAE5C,MAAM,IAAI,GAAG,IAAI,KAAK,CAAC,EAAE,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC;IAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACxC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}

+ 87 - 0
node_modules/@mongodb-js/saslprep/package.json

@@ -0,0 +1,87 @@
+{
+  "name": "@mongodb-js/saslprep",
+  "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013",
+  "keywords": [
+    "sasl",
+    "saslprep",
+    "stringprep",
+    "rfc4013",
+    "4013"
+  ],
+  "author": "Dmitry Tsvettsikh <me@reklatsmasters.com>",
+  "publishConfig": {
+    "access": "public"
+  },
+  "main": "dist/node.js",
+  "bugs": {
+    "url": "https://jira.mongodb.org/projects/COMPASS/issues",
+    "email": "compass@mongodb.com"
+  },
+  "homepage": "https://github.com/mongodb-js/devtools-shared/tree/main/packages/saslprep",
+  "version": "1.4.4",
+  "repository": {
+    "type": "git",
+    "url": "https://github.com/mongodb-js/devtools-shared.git"
+  },
+  "files": [
+    "dist"
+  ],
+  "license": "MIT",
+  "exports": {
+    "browser": {
+      "types": "./dist/browser.d.ts",
+      "default": "./dist/browser.js"
+    },
+    "import": {
+      "types": "./dist/node.d.ts",
+      "default": "./dist/.esm-wrapper.mjs"
+    },
+    "require": {
+      "types": "./dist/node.d.ts",
+      "default": "./dist/node.js"
+    }
+  },
+  "types": "./dist/node.d.ts",
+  "scripts": {
+    "gen-code-points": "ts-node src/generate-code-points.ts src/code-points-data.ts src/code-points-data-browser.ts",
+    "bootstrap": "npm run compile",
+    "prepublishOnly": "npm run compile",
+    "compile": "npm run gen-code-points && tsc -p tsconfig.json && gen-esm-wrapper . ./dist/.esm-wrapper.mjs",
+    "typecheck": "tsc --noEmit",
+    "eslint": "eslint",
+    "prettier": "prettier",
+    "lint": "npm run eslint . && npm run prettier -- --check .",
+    "depcheck": "depcheck",
+    "check": "npm run typecheck && npm run lint && npm run depcheck",
+    "check-ci": "npm run check",
+    "test": "mocha",
+    "test-cov": "nyc -x \"**/*.spec.*\" --reporter=lcov --reporter=text --reporter=html npm run test",
+    "test-watch": "npm run test -- --watch",
+    "test-ci": "npm run test-cov",
+    "reformat": "npm run prettier -- --write ."
+  },
+  "dependencies": {
+    "sparse-bitfield": "^3.0.3"
+  },
+  "devDependencies": {
+    "@mongodb-js/eslint-config-devtools": "^0.11.2",
+    "@mongodb-js/mocha-config-devtools": "^1.1.0",
+    "@mongodb-js/prettier-config-devtools": "^1.0.2",
+    "@mongodb-js/tsconfig-devtools": "^1.1.0",
+    "@types/chai": "^4.2.21",
+    "@types/mocha": "^9.1.1",
+    "@types/node": "^22.15.30",
+    "@types/sinon-chai": "^3.2.5",
+    "@types/sparse-bitfield": "^3.0.1",
+    "chai": "^4.5.0",
+    "depcheck": "^1.4.7",
+    "eslint": "^7.25.0 || ^8.0.0",
+    "gen-esm-wrapper": "^1.1.3",
+    "mocha": "^8.4.0",
+    "nyc": "^15.1.0",
+    "prettier": "^3.5.3",
+    "sinon": "^9.2.3",
+    "typescript": "^5.8.2"
+  },
+  "gitHead": "da4372646f24ef7c9ef6bb8224d0cf1f53be7540"
+}

+ 29 - 0
node_modules/@mongodb-js/saslprep/readme.md

@@ -0,0 +1,29 @@
+# saslprep
+
+_Note: This is a fork of the original [`saslprep`](https://www.npmjs.com/package/saslprep) npm package
+and provides equivalent functionality._
+
+Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013)
+
+### Usage
+
+```js
+const saslprep = require('@mongodb-js/saslprep');
+
+saslprep('password\u00AD'); // password
+saslprep('password\u0007'); // Error: prohibited character
+```
+
+### API
+
+##### `saslprep(input: String, opts: Options): String`
+
+Normalize user name or password.
+
+##### `Options.allowUnassigned: bool`
+
+A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default.
+
+## License
+
+MIT, 2017-2019 (c) Dmitriy Tsvettsikh

+ 21 - 0
node_modules/@types/webidl-conversions/LICENSE

@@ -0,0 +1,21 @@
+    MIT License
+
+    Copyright (c) Microsoft Corporation.
+
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be included in all
+    copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+    SOFTWARE

+ 15 - 0
node_modules/@types/webidl-conversions/README.md

@@ -0,0 +1,15 @@
+# Installation
+> `npm install --save @types/webidl-conversions`
+
+# Summary
+This package contains type definitions for webidl-conversions (https://github.com/jsdom/webidl-conversions#readme).
+
+# Details
+Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/webidl-conversions.
+
+### Additional Details
+ * Last updated: Tue, 07 Nov 2023 15:11:36 GMT
+ * Dependencies: none
+
+# Credits
+These definitions were written by [ExE Boss](https://github.com/ExE-Boss), and [BendingBender](https://github.com/BendingBender).

+ 91 - 0
node_modules/@types/webidl-conversions/index.d.ts

@@ -0,0 +1,91 @@
+declare namespace WebIDLConversions {
+    interface Globals {
+        [key: string]: unknown;
+
+        Number: (value?: unknown) => number;
+        String: (value?: unknown) => string;
+        TypeError: new(message?: string) => TypeError;
+    }
+
+    interface Options {
+        context?: string | undefined;
+        globals?: Globals | undefined;
+    }
+
+    interface IntegerOptions extends Options {
+        enforceRange?: boolean | undefined;
+        clamp?: boolean | undefined;
+    }
+
+    interface StringOptions extends Options {
+        treatNullAsEmptyString?: boolean | undefined;
+    }
+
+    interface BufferSourceOptions extends Options {
+        allowShared?: boolean | undefined;
+    }
+
+    type IntegerConversion = (V: unknown, opts?: IntegerOptions) => number;
+    type StringConversion = (V: unknown, opts?: StringOptions) => string;
+    type NumberConversion = (V: unknown, opts?: Options) => number;
+}
+
+declare const WebIDLConversions: {
+    any<V>(V: V, opts?: WebIDLConversions.Options): V;
+    undefined(V?: unknown, opts?: WebIDLConversions.Options): void;
+    boolean(V: unknown, opts?: WebIDLConversions.Options): boolean;
+
+    byte(V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
+    octet(V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
+
+    short(V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
+    ["unsigned short"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
+
+    long(V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
+    ["unsigned long"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
+
+    ["long long"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
+    ["unsigned long long"](V: unknown, opts?: WebIDLConversions.IntegerOptions): number;
+
+    double(V: unknown, opts?: WebIDLConversions.Options): number;
+    ["unrestricted double"](V: unknown, opts?: WebIDLConversions.Options): number;
+
+    float(V: unknown, opts?: WebIDLConversions.Options): number;
+    ["unrestricted float"](V: unknown, opts?: WebIDLConversions.Options): number;
+
+    DOMString(V: unknown, opts?: WebIDLConversions.StringOptions): string;
+    ByteString(V: unknown, opts?: WebIDLConversions.StringOptions): string;
+    USVString(V: unknown, opts?: WebIDLConversions.StringOptions): string;
+
+    object<V>(V: V, opts?: WebIDLConversions.Options): V extends object ? V : V & object;
+    ArrayBuffer(
+        V: unknown,
+        opts?: WebIDLConversions.BufferSourceOptions & { allowShared?: false | undefined },
+    ): ArrayBuffer;
+    ArrayBuffer(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferLike;
+    DataView(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): DataView;
+
+    Int8Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int8Array;
+    Int16Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int16Array;
+    Int32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int32Array;
+
+    Uint8Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint8Array;
+    Uint16Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint16Array;
+    Uint32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint32Array;
+    Uint8ClampedArray(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint8ClampedArray;
+
+    Float32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Float32Array;
+    Float64Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Float64Array;
+
+    ArrayBufferView(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferView;
+    BufferSource(
+        V: unknown,
+        opts?: WebIDLConversions.BufferSourceOptions & { allowShared?: false | undefined },
+    ): ArrayBuffer | ArrayBufferView;
+    BufferSource(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferLike | ArrayBufferView;
+
+    DOMTimeStamp(V: unknown, opts?: WebIDLConversions.Options): number;
+};
+
+// This can't use ES6 style exports, as those can't have spaces in export names.
+export = WebIDLConversions;

+ 30 - 0
node_modules/@types/webidl-conversions/package.json

@@ -0,0 +1,30 @@
+{
+    "name": "@types/webidl-conversions",
+    "version": "7.0.3",
+    "description": "TypeScript definitions for webidl-conversions",
+    "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/webidl-conversions",
+    "license": "MIT",
+    "contributors": [
+        {
+            "name": "ExE Boss",
+            "githubUsername": "ExE-Boss",
+            "url": "https://github.com/ExE-Boss"
+        },
+        {
+            "name": "BendingBender",
+            "githubUsername": "BendingBender",
+            "url": "https://github.com/BendingBender"
+        }
+    ],
+    "main": "",
+    "types": "index.d.ts",
+    "repository": {
+        "type": "git",
+        "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
+        "directory": "types/webidl-conversions"
+    },
+    "scripts": {},
+    "dependencies": {},
+    "typesPublisherContentHash": "ff1514e10869784e8b7cca9c4099a4213d3f14b48c198b1bf116300df94bf608",
+    "typeScriptVersion": "4.5"
+}

+ 21 - 0
node_modules/@types/whatwg-url/LICENSE

@@ -0,0 +1,21 @@
+    MIT License
+
+    Copyright (c) Microsoft Corporation.
+
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be included in all
+    copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+    SOFTWARE

+ 15 - 0
node_modules/@types/whatwg-url/README.md

@@ -0,0 +1,15 @@
+# Installation
+> `npm install --save @types/whatwg-url`
+
+# Summary
+This package contains type definitions for whatwg-url (https://github.com/jsdom/whatwg-url#readme).
+
+# Details
+Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/whatwg-url.
+
+### Additional Details
+ * Last updated: Tue, 12 Nov 2024 00:46:36 GMT
+ * Dependencies: [@types/webidl-conversions](https://npmjs.com/package/@types/webidl-conversions)
+
+# Credits
+These definitions were written by [Alexander Marks](https://github.com/aomarks), [ExE Boss](https://github.com/ExE-Boss), and [BendingBender](https://github.com/BendingBender).

+ 172 - 0
node_modules/@types/whatwg-url/index.d.ts

@@ -0,0 +1,172 @@
+/// <reference lib="es2020"/>
+/** https://url.spec.whatwg.org/#url-representation */
+export interface URLRecord {
+    scheme: string;
+    username: string;
+    password: string;
+    host: string | number | IPv6Address | null;
+    port: number | null;
+    path: string | string[];
+    query: string | null;
+    fragment: string | null;
+}
+
+/** https://url.spec.whatwg.org/#concept-ipv6 */
+export type IPv6Address = [number, number, number, number, number, number, number, number];
+
+/** https://url.spec.whatwg.org/#url-class */
+export class URL {
+    constructor(url: string, base?: string | URL);
+
+    static canParse(url: string, base?: string): boolean;
+
+    get href(): string;
+    set href(V: string);
+
+    get origin(): string;
+
+    get protocol(): string;
+    set protocol(V: string);
+
+    get username(): string;
+    set username(V: string);
+
+    get password(): string;
+    set password(V: string);
+
+    get host(): string;
+    set host(V: string);
+
+    get hostname(): string;
+    set hostname(V: string);
+
+    get port(): string;
+    set port(V: string);
+
+    get pathname(): string;
+    set pathname(V: string);
+
+    get search(): string;
+    set search(V: string);
+
+    get searchParams(): URLSearchParams;
+
+    get hash(): string;
+    set hash(V: string);
+
+    toJSON(): string;
+
+    readonly [Symbol.toStringTag]: "URL";
+}
+
+/** https://url.spec.whatwg.org/#interface-urlsearchparams */
+export class URLSearchParams {
+    constructor(
+        init?:
+            | ReadonlyArray<readonly [name: string, value: string]>
+            | Iterable<readonly [name: string, value: string]>
+            | { readonly [name: string]: string }
+            | string,
+    );
+
+    get size(): number;
+    append(name: string, value: string): void;
+    delete(name: string, value?: string): void;
+    get(name: string): string | null;
+    getAll(name: string): string[];
+    has(name: string, value?: string): boolean;
+    set(name: string, value: string): void;
+    sort(): void;
+
+    keys(): IterableIterator<string>;
+    values(): IterableIterator<string>;
+    entries(): IterableIterator<[name: string, value: string]>;
+    forEach<THIS_ARG = void>(
+        callback: (this: THIS_ARG, value: string, name: string, searchParams: this) => void,
+        thisArg?: THIS_ARG,
+    ): void;
+
+    readonly [Symbol.toStringTag]: "URLSearchParams";
+    [Symbol.iterator](): IterableIterator<[name: string, value: string]>;
+}
+
+/** https://url.spec.whatwg.org/#concept-url-parser */
+export function parseURL(input: string, options?: { readonly baseURL?: URLRecord | undefined }): URLRecord | null;
+
+/** https://url.spec.whatwg.org/#concept-basic-url-parser */
+export function basicURLParse(
+    input: string,
+    options?: {
+        baseURL?: URLRecord | undefined;
+        url?: URLRecord | undefined;
+        stateOverride?: StateOverride | undefined;
+    },
+): URLRecord | null;
+
+/** https://url.spec.whatwg.org/#scheme-start-state */
+export type StateOverride =
+    | "scheme start"
+    | "scheme"
+    | "no scheme"
+    | "special relative or authority"
+    | "path or authority"
+    | "relative"
+    | "relative slash"
+    | "special authority slashes"
+    | "special authority ignore slashes"
+    | "authority"
+    | "host"
+    | "hostname"
+    | "port"
+    | "file"
+    | "file slash"
+    | "file host"
+    | "path start"
+    | "path"
+    | "opaque path"
+    | "query"
+    | "fragment";
+
+/** https://url.spec.whatwg.org/#concept-url-serializer */
+export function serializeURL(urlRecord: URLRecord, excludeFragment?: boolean): string;
+
+/** https://url.spec.whatwg.org/#concept-host-serializer */
+export function serializeHost(host: string | number | IPv6Address): string;
+
+/** https://url.spec.whatwg.org/#url-path-serializer */
+export function serializePath(urlRecord: URLRecord): string;
+
+/** https://url.spec.whatwg.org/#serialize-an-integer */
+export function serializeInteger(number: number): string;
+
+/** https://html.spec.whatwg.org#ascii-serialisation-of-an-origin */
+export function serializeURLOrigin(urlRecord: URLRecord): string;
+
+/** https://url.spec.whatwg.org/#set-the-username */
+export function setTheUsername(urlRecord: URLRecord, username: string): void;
+
+/** https://url.spec.whatwg.org/#set-the-password */
+export function setThePassword(urlRecord: URLRecord, password: string): void;
+
+/** https://url.spec.whatwg.org/#url-opaque-path */
+export function hasAnOpaquePath(urlRecord: URLRecord): boolean;
+
+/** https://url.spec.whatwg.org/#cannot-have-a-username-password-port */
+export function cannotHaveAUsernamePasswordPort(urlRecord: URLRecord): boolean;
+
+/** https://url.spec.whatwg.org/#percent-decode */
+export function percentDecodeBytes(buffer: TypedArray): Uint8Array;
+
+/** https://url.spec.whatwg.org/#string-percent-decode */
+export function percentDecodeString(string: string): Uint8Array;
+
+export type TypedArray =
+    | Uint8Array
+    | Uint8ClampedArray
+    | Uint16Array
+    | Uint32Array
+    | Int8Array
+    | Int16Array
+    | Int32Array
+    | Float32Array
+    | Float64Array;

+ 22 - 0
node_modules/@types/whatwg-url/lib/URL-impl.d.ts

@@ -0,0 +1,22 @@
+import { Globals } from "webidl-conversions";
+import { implementation as URLSearchParamsImpl } from "./URLSearchParams-impl";
+
+declare class URLImpl {
+    constructor(globalObject: Globals, constructorArgs: readonly [url: string, base?: string]);
+
+    href: string;
+    readonly origin: string;
+    protocol: string;
+    username: string;
+    password: string;
+    host: string;
+    hostname: string;
+    port: string;
+    pathname: string;
+    search: string;
+    readonly searchParams: URLSearchParamsImpl;
+    hash: string;
+
+    toJSON(): string;
+}
+export { URLImpl as implementation };

+ 66 - 0
node_modules/@types/whatwg-url/lib/URL.d.ts

@@ -0,0 +1,66 @@
+import { URL } from "../index";
+import { implementation as URLImpl } from "./URL-impl";
+
+/**
+ * Checks whether `obj` is a `URL` object with an implementation
+ * provided by this package.
+ */
+export function is(obj: unknown): obj is URL;
+
+/**
+ * Checks whether `obj` is a `URLImpl` WebIDL2JS implementation object
+ * provided by this package.
+ */
+export function isImpl(obj: unknown): obj is URLImpl;
+
+/**
+ * Converts the `URL` wrapper into a `URLImpl` object.
+ *
+ * @throws {TypeError} If `obj` is not a `URL` wrapper instance provided by this package.
+ */
+export function convert(globalObject: object, obj: unknown, { context }?: { context: string }): URLImpl;
+
+/**
+ * Creates a new `URL` instance.
+ *
+ * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor
+ *         registry or a `URL` constructor provided by this package
+ *         in the WebIDL2JS constructor registry.
+ */
+export function create(globalObject: object, constructorArgs: readonly [url: string, base?: string]): URL;
+
+/**
+ * Calls `create()` and returns the internal `URLImpl`.
+ *
+ * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor
+ *         registry or a `URL` constructor provided by this package
+ *         in the WebIDL2JS constructor registry.
+ */
+export function createImpl(globalObject: object, constructorArgs: readonly [url: string, base?: string]): URLImpl;
+
+/**
+ * Initializes the `URL` instance, called by `create()`.
+ *
+ * Useful when manually sub-classing a non-constructable wrapper object.
+ */
+export function setup<T extends URL>(
+    obj: T,
+    globalObject: object,
+    constructorArgs: readonly [url: string, base?: string],
+): T;
+
+/**
+ * Creates a new `URL` object without runing the constructor steps.
+ *
+ * Useful when implementing specifications that initialize objects
+ * in different ways than their constructors do.
+ */
+declare function _new(globalObject: object, newTarget?: new(url: string, base?: string) => URL): URLImpl;
+export { _new as new };
+
+/**
+ * Installs the `URL` constructor onto the `globalObject`.
+ *
+ * @throws {Error} If the target `globalObject` doesn't have an `Error` constructor.
+ */
+export function install(globalObject: object, globalNames: readonly string[]): void;

+ 20 - 0
node_modules/@types/whatwg-url/lib/URLSearchParams-impl.d.ts

@@ -0,0 +1,20 @@
+declare class URLSearchParamsImpl {
+    constructor(
+        globalObject: object,
+        constructorArgs: readonly [
+            init?: ReadonlyArray<readonly [name: string, value: string]> | { readonly [name: string]: string } | string,
+        ],
+        privateData: { readonly doNotStripQMark?: boolean | undefined },
+    );
+
+    append(name: string, value: string): void;
+    delete(name: string): void;
+    get(name: string): string | null;
+    getAll(name: string): string[];
+    has(name: string): boolean;
+    set(name: string, value: string): void;
+    sort(): void;
+
+    [Symbol.iterator](): IterableIterator<[name: string, value: string]>;
+}
+export { URLSearchParamsImpl as implementation };

+ 92 - 0
node_modules/@types/whatwg-url/lib/URLSearchParams.d.ts

@@ -0,0 +1,92 @@
+import { URLSearchParams } from "../index";
+import { implementation as URLSearchParamsImpl } from "./URLSearchParams-impl";
+
+/**
+ * Checks whether `obj` is a `URLSearchParams` object with an implementation
+ * provided by this package.
+ */
+export function is(obj: unknown): obj is URLSearchParams;
+
+/**
+ * Checks whether `obj` is a `URLSearchParamsImpl` WebIDL2JS implementation object
+ * provided by this package.
+ */
+export function isImpl(obj: unknown): obj is URLSearchParamsImpl;
+
+/**
+ * Converts the `URLSearchParams` wrapper into a `URLSearchParamsImpl` object.
+ *
+ * @throws {TypeError} If `obj` is not a `URLSearchParams` wrapper instance provided by this package.
+ */
+export function convert(globalObject: object, obj: unknown, { context }?: { context: string }): URLSearchParamsImpl;
+
+export function createDefaultIterator<TIteratorKind extends "key" | "value" | "key+value">(
+    globalObject: object,
+    target: URLSearchParamsImpl,
+    kind: TIteratorKind,
+): IterableIterator<TIteratorKind extends "key" | "value" ? string : [name: string, value: string]>;
+
+/**
+ * Creates a new `URLSearchParams` instance.
+ *
+ * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor
+ *         registry or a `URLSearchParams` constructor provided by this package
+ *         in the WebIDL2JS constructor registry.
+ */
+export function create(
+    globalObject: object,
+    constructorArgs?: readonly [
+        init: ReadonlyArray<[name: string, value: string]> | { readonly [name: string]: string } | string,
+    ],
+    privateData?: { doNotStripQMark?: boolean | undefined },
+): URLSearchParams;
+
+/**
+ * Calls `create()` and returns the internal `URLSearchParamsImpl`.
+ *
+ * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor
+ *         registry or a `URLSearchParams` constructor provided by this package
+ *         in the WebIDL2JS constructor registry.
+ */
+export function createImpl(
+    globalObject: object,
+    constructorArgs?: readonly [
+        init: ReadonlyArray<[name: string, value: string]> | { readonly [name: string]: string } | string,
+    ],
+    privateData?: { doNotStripQMark?: boolean | undefined },
+): URLSearchParamsImpl;
+
+/**
+ * Initializes the `URLSearchParams` instance, called by `create()`.
+ *
+ * Useful when manually sub-classing a non-constructable wrapper object.
+ */
+export function setup<T extends URLSearchParams>(
+    obj: T,
+    globalObject: object,
+    constructorArgs?: readonly [
+        init: ReadonlyArray<[name: string, value: string]> | { readonly [name: string]: string } | string,
+    ],
+    privateData?: { doNotStripQMark?: boolean | undefined },
+): T;
+
+/**
+ * Creates a new `URLSearchParams` object without runing the constructor steps.
+ *
+ * Useful when implementing specifications that initialize objects
+ * in different ways than their constructors do.
+ */
+declare function _new(
+    globalObject: object,
+    newTarget?: new(
+        init: ReadonlyArray<[name: string, value: string]> | { readonly [name: string]: string } | string,
+    ) => URLSearchParams,
+): URLSearchParamsImpl;
+export { _new as new };
+
+/**
+ * Installs the `URLSearchParams` constructor onto the `globalObject`.
+ *
+ * @throws {Error} If the target `globalObject` doesn't have an `Error` constructor.
+ */
+export function install(globalObject: object, globalNames: readonly string[]): void;

+ 38 - 0
node_modules/@types/whatwg-url/package.json

@@ -0,0 +1,38 @@
+{
+    "name": "@types/whatwg-url",
+    "version": "13.0.0",
+    "description": "TypeScript definitions for whatwg-url",
+    "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/whatwg-url",
+    "license": "MIT",
+    "contributors": [
+        {
+            "name": "Alexander Marks",
+            "githubUsername": "aomarks",
+            "url": "https://github.com/aomarks"
+        },
+        {
+            "name": "ExE Boss",
+            "githubUsername": "ExE-Boss",
+            "url": "https://github.com/ExE-Boss"
+        },
+        {
+            "name": "BendingBender",
+            "githubUsername": "BendingBender",
+            "url": "https://github.com/BendingBender"
+        }
+    ],
+    "main": "",
+    "types": "index.d.ts",
+    "repository": {
+        "type": "git",
+        "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
+        "directory": "types/whatwg-url"
+    },
+    "scripts": {},
+    "dependencies": {
+        "@types/webidl-conversions": "*"
+    },
+    "peerDependencies": {},
+    "typesPublisherContentHash": "fd4818c1b74d8ef43c58e984d60d82658280822821b6ea5d4978f4007f29c39c",
+    "typeScriptVersion": "4.9"
+}

+ 4 - 0
node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts

@@ -0,0 +1,4 @@
+import * as URL from "./lib/URL";
+import * as URLSearchParams from "./lib/URLSearchParams";
+
+export { URL, URLSearchParams };

+ 250 - 0
node_modules/accepts/HISTORY.md

@@ -0,0 +1,250 @@
+2.0.0 / 2024-08-31
+==================
+
+  * Drop node <18 support
+  * deps: mime-types@^3.0.0
+  * deps: negotiator@^1.0.0
+
+1.3.8 / 2022-02-02
+==================
+
+  * deps: mime-types@~2.1.34
+    - deps: mime-db@~1.51.0
+  * deps: negotiator@0.6.3
+
+1.3.7 / 2019-04-29
+==================
+
+  * deps: negotiator@0.6.2
+    - Fix sorting charset, encoding, and language with extra parameters
+
+1.3.6 / 2019-04-28
+==================
+
+  * deps: mime-types@~2.1.24
+    - deps: mime-db@~1.40.0
+
+1.3.5 / 2018-02-28
+==================
+
+  * deps: mime-types@~2.1.18
+    - deps: mime-db@~1.33.0
+
+1.3.4 / 2017-08-22
+==================
+
+  * deps: mime-types@~2.1.16
+    - deps: mime-db@~1.29.0
+
+1.3.3 / 2016-05-02
+==================
+
+  * deps: mime-types@~2.1.11
+    - deps: mime-db@~1.23.0
+  * deps: negotiator@0.6.1
+    - perf: improve `Accept` parsing speed
+    - perf: improve `Accept-Charset` parsing speed
+    - perf: improve `Accept-Encoding` parsing speed
+    - perf: improve `Accept-Language` parsing speed
+
+1.3.2 / 2016-03-08
+==================
+
+  * deps: mime-types@~2.1.10
+    - Fix extension of `application/dash+xml`
+    - Update primary extension for `audio/mp4`
+    - deps: mime-db@~1.22.0
+
+1.3.1 / 2016-01-19
+==================
+
+  * deps: mime-types@~2.1.9
+    - deps: mime-db@~1.21.0
+
+1.3.0 / 2015-09-29
+==================
+
+  * deps: mime-types@~2.1.7
+    - deps: mime-db@~1.19.0
+  * deps: negotiator@0.6.0
+    - Fix including type extensions in parameters in `Accept` parsing
+    - Fix parsing `Accept` parameters with quoted equals
+    - Fix parsing `Accept` parameters with quoted semicolons
+    - Lazy-load modules from main entry point
+    - perf: delay type concatenation until needed
+    - perf: enable strict mode
+    - perf: hoist regular expressions
+    - perf: remove closures getting spec properties
+    - perf: remove a closure from media type parsing
+    - perf: remove property delete from media type parsing
+
+1.2.13 / 2015-09-06
+===================
+
+  * deps: mime-types@~2.1.6
+    - deps: mime-db@~1.18.0
+
+1.2.12 / 2015-07-30
+===================
+
+  * deps: mime-types@~2.1.4
+    - deps: mime-db@~1.16.0
+
+1.2.11 / 2015-07-16
+===================
+
+  * deps: mime-types@~2.1.3
+    - deps: mime-db@~1.15.0
+
+1.2.10 / 2015-07-01
+===================
+
+  * deps: mime-types@~2.1.2
+    - deps: mime-db@~1.14.0
+
+1.2.9 / 2015-06-08
+==================
+
+  * deps: mime-types@~2.1.1
+    - perf: fix deopt during mapping
+
+1.2.8 / 2015-06-07
+==================
+
+  * deps: mime-types@~2.1.0
+    - deps: mime-db@~1.13.0
+  * perf: avoid argument reassignment & argument slice
+  * perf: avoid negotiator recursive construction
+  * perf: enable strict mode
+  * perf: remove unnecessary bitwise operator
+
+1.2.7 / 2015-05-10
+==================
+
+  * deps: negotiator@0.5.3
+    - Fix media type parameter matching to be case-insensitive
+
+1.2.6 / 2015-05-07
+==================
+
+  * deps: mime-types@~2.0.11
+    - deps: mime-db@~1.9.1
+  * deps: negotiator@0.5.2
+    - Fix comparing media types with quoted values
+    - Fix splitting media types with quoted commas
+
+1.2.5 / 2015-03-13
+==================
+
+  * deps: mime-types@~2.0.10
+    - deps: mime-db@~1.8.0
+
+1.2.4 / 2015-02-14
+==================
+
+  * Support Node.js 0.6
+  * deps: mime-types@~2.0.9
+    - deps: mime-db@~1.7.0
+  * deps: negotiator@0.5.1
+    - Fix preference sorting to be stable for long acceptable lists
+
+1.2.3 / 2015-01-31
+==================
+
+  * deps: mime-types@~2.0.8
+    - deps: mime-db@~1.6.0
+
+1.2.2 / 2014-12-30
+==================
+
+  * deps: mime-types@~2.0.7
+    - deps: mime-db@~1.5.0
+
+1.2.1 / 2014-12-30
+==================
+
+  * deps: mime-types@~2.0.5
+    - deps: mime-db@~1.3.1
+
+1.2.0 / 2014-12-19
+==================
+
+  * deps: negotiator@0.5.0
+    - Fix list return order when large accepted list
+    - Fix missing identity encoding when q=0 exists
+    - Remove dynamic building of Negotiator class
+
+1.1.4 / 2014-12-10
+==================
+
+  * deps: mime-types@~2.0.4
+    - deps: mime-db@~1.3.0
+
+1.1.3 / 2014-11-09
+==================
+
+  * deps: mime-types@~2.0.3
+    - deps: mime-db@~1.2.0
+
+1.1.2 / 2014-10-14
+==================
+
+  * deps: negotiator@0.4.9
+    - Fix error when media type has invalid parameter
+
+1.1.1 / 2014-09-28
+==================
+
+  * deps: mime-types@~2.0.2
+    - deps: mime-db@~1.1.0
+  * deps: negotiator@0.4.8
+    - Fix all negotiations to be case-insensitive
+    - Stable sort preferences of same quality according to client order
+
+1.1.0 / 2014-09-02
+==================
+
+  * update `mime-types`
+
+1.0.7 / 2014-07-04
+==================
+
+  * Fix wrong type returned from `type` when match after unknown extension
+
+1.0.6 / 2014-06-24
+==================
+
+  * deps: negotiator@0.4.7
+
+1.0.5 / 2014-06-20
+==================
+
+ * fix crash when unknown extension given
+
+1.0.4 / 2014-06-19
+==================
+
+  * use `mime-types`
+
+1.0.3 / 2014-06-11
+==================
+
+  * deps: negotiator@0.4.6
+    - Order by specificity when quality is the same
+
+1.0.2 / 2014-05-29
+==================
+
+  * Fix interpretation when header not in request
+  * deps: pin negotiator@0.4.5
+
+1.0.1 / 2014-01-18
+==================
+
+  * Identity encoding isn't always acceptable
+  * deps: negotiator@~0.4.0
+
+1.0.0 / 2013-12-27
+==================
+
+  * Genesis

+ 23 - 0
node_modules/accepts/LICENSE

@@ -0,0 +1,23 @@
+(The MIT License)
+
+Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
+Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 140 - 0
node_modules/accepts/README.md

@@ -0,0 +1,140 @@
+# accepts
+
+[![NPM Version][npm-version-image]][npm-url]
+[![NPM Downloads][npm-downloads-image]][npm-url]
+[![Node.js Version][node-version-image]][node-version-url]
+[![Build Status][github-actions-ci-image]][github-actions-ci-url]
+[![Test Coverage][coveralls-image]][coveralls-url]
+
+Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
+Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
+
+In addition to negotiator, it allows:
+
+- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
+  as well as `('text/html', 'application/json')`.
+- Allows type shorthands such as `json`.
+- Returns `false` when no types match
+- Treats non-existent headers as `*`
+
+## Installation
+
+This is a [Node.js](https://nodejs.org/en/) module available through the
+[npm registry](https://www.npmjs.com/). Installation is done using the
+[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
+
+```sh
+$ npm install accepts
+```
+
+## API
+
+```js
+var accepts = require('accepts')
+```
+
+### accepts(req)
+
+Create a new `Accepts` object for the given `req`.
+
+#### .charset(charsets)
+
+Return the first accepted charset. If nothing in `charsets` is accepted,
+then `false` is returned.
+
+#### .charsets()
+
+Return the charsets that the request accepts, in the order of the client's
+preference (most preferred first).
+
+#### .encoding(encodings)
+
+Return the first accepted encoding. If nothing in `encodings` is accepted,
+then `false` is returned.
+
+#### .encodings()
+
+Return the encodings that the request accepts, in the order of the client's
+preference (most preferred first).
+
+#### .language(languages)
+
+Return the first accepted language. If nothing in `languages` is accepted,
+then `false` is returned.
+
+#### .languages()
+
+Return the languages that the request accepts, in the order of the client's
+preference (most preferred first).
+
+#### .type(types)
+
+Return the first accepted type (and it is returned as the same text as what
+appears in the `types` array). If nothing in `types` is accepted, then `false`
+is returned.
+
+The `types` array can contain full MIME types or file extensions. Any value
+that is not a full MIME type is passed to `require('mime-types').lookup`.
+
+#### .types()
+
+Return the types that the request accepts, in the order of the client's
+preference (most preferred first).
+
+## Examples
+
+### Simple type negotiation
+
+This simple example shows how to use `accepts` to return a different typed
+respond body based on what the client wants to accept. The server lists it's
+preferences in order and will get back the best match between the client and
+server.
+
+```js
+var accepts = require('accepts')
+var http = require('http')
+
+function app (req, res) {
+  var accept = accepts(req)
+
+  // the order of this list is significant; should be server preferred order
+  switch (accept.type(['json', 'html'])) {
+    case 'json':
+      res.setHeader('Content-Type', 'application/json')
+      res.write('{"hello":"world!"}')
+      break
+    case 'html':
+      res.setHeader('Content-Type', 'text/html')
+      res.write('<b>hello, world!</b>')
+      break
+    default:
+      // the fallback is text/plain, so no need to specify it above
+      res.setHeader('Content-Type', 'text/plain')
+      res.write('hello, world!')
+      break
+  }
+
+  res.end()
+}
+
+http.createServer(app).listen(3000)
+```
+
+You can test this out with the cURL program:
+```sh
+curl -I -H'Accept: text/html' http://localhost:3000/
+```
+
+## License
+
+[MIT](LICENSE)
+
+[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
+[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
+[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci
+[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml
+[node-version-image]: https://badgen.net/npm/node/accepts
+[node-version-url]: https://nodejs.org/en/download
+[npm-downloads-image]: https://badgen.net/npm/dm/accepts
+[npm-url]: https://npmjs.org/package/accepts
+[npm-version-image]: https://badgen.net/npm/v/accepts

+ 238 - 0
node_modules/accepts/index.js

@@ -0,0 +1,238 @@
+/*!
+ * accepts
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var Negotiator = require('negotiator')
+var mime = require('mime-types')
+
+/**
+ * Module exports.
+ * @public
+ */
+
+module.exports = Accepts
+
+/**
+ * Create a new Accepts object for the given req.
+ *
+ * @param {object} req
+ * @public
+ */
+
+function Accepts (req) {
+  if (!(this instanceof Accepts)) {
+    return new Accepts(req)
+  }
+
+  this.headers = req.headers
+  this.negotiator = new Negotiator(req)
+}
+
+/**
+ * Check if the given `type(s)` is acceptable, returning
+ * the best match when true, otherwise `undefined`, in which
+ * case you should respond with 406 "Not Acceptable".
+ *
+ * The `type` value may be a single mime type string
+ * such as "application/json", the extension name
+ * such as "json" or an array `["json", "html", "text/plain"]`. When a list
+ * or array is given the _best_ match, if any is returned.
+ *
+ * Examples:
+ *
+ *     // Accept: text/html
+ *     this.types('html');
+ *     // => "html"
+ *
+ *     // Accept: text/*, application/json
+ *     this.types('html');
+ *     // => "html"
+ *     this.types('text/html');
+ *     // => "text/html"
+ *     this.types('json', 'text');
+ *     // => "json"
+ *     this.types('application/json');
+ *     // => "application/json"
+ *
+ *     // Accept: text/*, application/json
+ *     this.types('image/png');
+ *     this.types('png');
+ *     // => undefined
+ *
+ *     // Accept: text/*;q=.5, application/json
+ *     this.types(['html', 'json']);
+ *     this.types('html', 'json');
+ *     // => "json"
+ *
+ * @param {String|Array} types...
+ * @return {String|Array|Boolean}
+ * @public
+ */
+
+Accepts.prototype.type =
+Accepts.prototype.types = function (types_) {
+  var types = types_
+
+  // support flattened arguments
+  if (types && !Array.isArray(types)) {
+    types = new Array(arguments.length)
+    for (var i = 0; i < types.length; i++) {
+      types[i] = arguments[i]
+    }
+  }
+
+  // no types, return all requested types
+  if (!types || types.length === 0) {
+    return this.negotiator.mediaTypes()
+  }
+
+  // no accept header, return first given type
+  if (!this.headers.accept) {
+    return types[0]
+  }
+
+  var mimes = types.map(extToMime)
+  var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
+  var first = accepts[0]
+
+  return first
+    ? types[mimes.indexOf(first)]
+    : false
+}
+
+/**
+ * Return accepted encodings or best fit based on `encodings`.
+ *
+ * Given `Accept-Encoding: gzip, deflate`
+ * an array sorted by quality is returned:
+ *
+ *     ['gzip', 'deflate']
+ *
+ * @param {String|Array} encodings...
+ * @return {String|Array}
+ * @public
+ */
+
+Accepts.prototype.encoding =
+Accepts.prototype.encodings = function (encodings_) {
+  var encodings = encodings_
+
+  // support flattened arguments
+  if (encodings && !Array.isArray(encodings)) {
+    encodings = new Array(arguments.length)
+    for (var i = 0; i < encodings.length; i++) {
+      encodings[i] = arguments[i]
+    }
+  }
+
+  // no encodings, return all requested encodings
+  if (!encodings || encodings.length === 0) {
+    return this.negotiator.encodings()
+  }
+
+  return this.negotiator.encodings(encodings)[0] || false
+}
+
+/**
+ * Return accepted charsets or best fit based on `charsets`.
+ *
+ * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
+ * an array sorted by quality is returned:
+ *
+ *     ['utf-8', 'utf-7', 'iso-8859-1']
+ *
+ * @param {String|Array} charsets...
+ * @return {String|Array}
+ * @public
+ */
+
+Accepts.prototype.charset =
+Accepts.prototype.charsets = function (charsets_) {
+  var charsets = charsets_
+
+  // support flattened arguments
+  if (charsets && !Array.isArray(charsets)) {
+    charsets = new Array(arguments.length)
+    for (var i = 0; i < charsets.length; i++) {
+      charsets[i] = arguments[i]
+    }
+  }
+
+  // no charsets, return all requested charsets
+  if (!charsets || charsets.length === 0) {
+    return this.negotiator.charsets()
+  }
+
+  return this.negotiator.charsets(charsets)[0] || false
+}
+
+/**
+ * Return accepted languages or best fit based on `langs`.
+ *
+ * Given `Accept-Language: en;q=0.8, es, pt`
+ * an array sorted by quality is returned:
+ *
+ *     ['es', 'pt', 'en']
+ *
+ * @param {String|Array} langs...
+ * @return {Array|String}
+ * @public
+ */
+
+Accepts.prototype.lang =
+Accepts.prototype.langs =
+Accepts.prototype.language =
+Accepts.prototype.languages = function (languages_) {
+  var languages = languages_
+
+  // support flattened arguments
+  if (languages && !Array.isArray(languages)) {
+    languages = new Array(arguments.length)
+    for (var i = 0; i < languages.length; i++) {
+      languages[i] = arguments[i]
+    }
+  }
+
+  // no languages, return all requested languages
+  if (!languages || languages.length === 0) {
+    return this.negotiator.languages()
+  }
+
+  return this.negotiator.languages(languages)[0] || false
+}
+
+/**
+ * Convert extnames to mime.
+ *
+ * @param {String} type
+ * @return {String}
+ * @private
+ */
+
+function extToMime (type) {
+  return type.indexOf('/') === -1
+    ? mime.lookup(type)
+    : type
+}
+
+/**
+ * Check if mime is valid.
+ *
+ * @param {String} type
+ * @return {Boolean}
+ * @private
+ */
+
+function validMime (type) {
+  return typeof type === 'string'
+}

+ 47 - 0
node_modules/accepts/package.json

@@ -0,0 +1,47 @@
+{
+  "name": "accepts",
+  "description": "Higher-level content negotiation",
+  "version": "2.0.0",
+  "contributors": [
+    "Douglas Christopher Wilson <doug@somethingdoug.com>",
+    "Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
+  ],
+  "license": "MIT",
+  "repository": "jshttp/accepts",
+  "dependencies": {
+    "mime-types": "^3.0.0",
+    "negotiator": "^1.0.0"
+  },
+  "devDependencies": {
+    "deep-equal": "1.0.1",
+    "eslint": "7.32.0",
+    "eslint-config-standard": "14.1.1",
+    "eslint-plugin-import": "2.25.4",
+    "eslint-plugin-markdown": "2.2.1",
+    "eslint-plugin-node": "11.1.0",
+    "eslint-plugin-promise": "4.3.1",
+    "eslint-plugin-standard": "4.1.0",
+    "mocha": "9.2.0",
+    "nyc": "15.1.0"
+  },
+  "files": [
+    "LICENSE",
+    "HISTORY.md",
+    "index.js"
+  ],
+  "engines": {
+    "node": ">= 0.6"
+  },
+  "scripts": {
+    "lint": "eslint .",
+    "test": "mocha --reporter spec --check-leaks --bail test/",
+    "test-ci": "nyc --reporter=lcov --reporter=text npm test",
+    "test-cov": "nyc --reporter=html --reporter=text npm test"
+  },
+  "keywords": [
+    "content",
+    "negotiation",
+    "accept",
+    "accepts"
+  ]
+}

+ 27 - 0
node_modules/bcryptjs/LICENSE

@@ -0,0 +1,27 @@
+bcrypt.js
+---------
+Copyright (c) 2012 Nevins Bartolomeo <nevins.bartolomeo@gmail.com>
+Copyright (c) 2012 Shane Girish <shaneGirish@gmail.com>
+Copyright (c) 2025 Daniel Wirtz <dcode@dcode.io>
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. The name of the author may not be used to endorse or promote products
+   derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 201 - 0
node_modules/bcryptjs/README.md

@@ -0,0 +1,201 @@
+# bcrypt.js
+
+Optimized bcrypt in JavaScript with zero dependencies, with TypeScript support. Compatible to the C++
+[bcrypt](https://npmjs.org/package/bcrypt) binding on Node.js and also working in the browser.
+
+[![Build Status](https://img.shields.io/github/actions/workflow/status/dcodeIO/bcrypt.js/test.yml?branch=main&label=test&logo=github)](https://github.com/dcodeIO/bcrypt.js/actions/workflows/test.yml) [![Publish Status](https://img.shields.io/github/actions/workflow/status/dcodeIO/bcrypt.js/publish.yml?branch=main&label=publish&logo=github)](https://github.com/dcodeIO/bcrypt.js/actions/workflows/publish.yml) [![npm](https://img.shields.io/npm/v/bcryptjs.svg?label=npm&color=007acc&logo=npm)](https://www.npmjs.com/package/bcryptjs)
+
+## Security considerations
+
+Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the
+iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with
+increasing computation power. ([see](http://en.wikipedia.org/wiki/Bcrypt))
+
+While bcrypt.js is compatible to the C++ bcrypt binding, it is written in pure JavaScript and thus slower ([about 30%](https://github.com/dcodeIO/bcrypt.js/wiki/Benchmark)), effectively reducing the number of iterations that can be
+processed in an equal time span.
+
+The maximum input length is 72 bytes (note that UTF-8 encoded characters use up to 4 bytes) and the length of generated
+hashes is 60 characters. Note that maximum input length is not implicitly checked by the library for compatibility with
+the C++ binding on Node.js, but should be checked with `bcrypt.truncates(password)` where necessary.
+
+## Usage
+
+The package exports an ECMAScript module with an UMD fallback.
+
+```
+$> npm install bcryptjs
+```
+
+```ts
+import bcrypt from "bcryptjs";
+```
+
+### Usage with a CDN
+
+- From GitHub via [jsDelivr](https://www.jsdelivr.com):<br />
+  `https://cdn.jsdelivr.net/gh/dcodeIO/bcrypt.js@TAG/index.js` (ESM)
+- From npm via [jsDelivr](https://www.jsdelivr.com):<br />
+  `https://cdn.jsdelivr.net/npm/bcryptjs@VERSION/index.js` (ESM)<br />
+  `https://cdn.jsdelivr.net/npm/bcryptjs@VERSION/umd/index.js` (UMD)
+- From npm via [unpkg](https://unpkg.com):<br />
+  `https://unpkg.com/bcryptjs@VERSION/index.js` (ESM)<br />
+  `https://unpkg.com/bcryptjs@VERSION/umd/index.js` (UMD)
+
+Replace `TAG` respectively `VERSION` with a [specific version](https://github.com/dcodeIO/bcrypt.js/releases) or omit it (not recommended in production) to use latest.
+
+When using the ESM variant in a browser, the `crypto` import needs to be stubbed out, for example using an [import map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap). Bundlers should omit it automatically.
+
+### Usage - Sync
+
+To hash a password:
+
+```ts
+const salt = bcrypt.genSaltSync(10);
+const hash = bcrypt.hashSync("B4c0/\/", salt);
+// Store hash in your password DB
+```
+
+To check a password:
+
+```ts
+// Load hash from your password DB
+bcrypt.compareSync("B4c0/\/", hash); // true
+bcrypt.compareSync("not_bacon", hash); // false
+```
+
+Auto-gen a salt and hash:
+
+```ts
+const hash = bcrypt.hashSync("bacon", 10);
+```
+
+### Usage - Async
+
+To hash a password:
+
+```ts
+const salt = await bcrypt.genSalt(10);
+const hash = await bcrypt.hash("B4c0/\/", salt);
+// Store hash in your password DB
+```
+
+```ts
+bcrypt.genSalt(10, (err, salt) => {
+  bcrypt.hash("B4c0/\/", salt, function (err, hash) {
+    // Store hash in your password DB
+  });
+});
+```
+
+To check a password:
+
+```ts
+// Load hash from your password DB
+await bcrypt.compare("B4c0/\/", hash); // true
+await bcrypt.compare("not_bacon", hash); // false
+```
+
+```ts
+// Load hash from your password DB
+bcrypt.compare("B4c0/\/", hash, (err, res) => {
+  // res === true
+});
+bcrypt.compare("not_bacon", hash, (err, res) => {
+  // res === false
+});
+```
+
+Auto-gen a salt and hash:
+
+```ts
+await bcrypt.hash("B4c0/\/", 10);
+// Store hash in your password DB
+```
+
+```ts
+bcrypt.hash("B4c0/\/", 10, (err, hash) => {
+  // Store hash in your password DB
+});
+```
+
+**Note:** Under the hood, asynchronous APIs split an operation into small chunks. After the completion of a chunk, the execution of the next chunk is placed on the back of the [JS event queue](https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop), efficiently yielding for other computation to execute.
+
+### Usage - Command Line
+
+```
+Usage: bcrypt <input> [rounds|salt]
+```
+
+## API
+
+### Callback types
+
+- **Callback<`T`>**: `(err: Error | null, result?: T) => void`<br />
+  Called with an error on failure or a value of type `T` upon success.
+
+- **ProgressCallback**: `(percentage: number) => void`<br />
+  Called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
+
+- **RandomFallback**: `(length: number) => number[]`<br />
+  Called to obtain random bytes when both [Web Crypto API](http://www.w3.org/TR/WebCryptoAPI/) and Node.js
+  [crypto](http://nodejs.org/api/crypto.html) are not available.
+
+### Functions
+
+- bcrypt.**genSaltSync**(rounds?: `number`): `string`<br />
+  Synchronously generates a salt. Number of rounds defaults to 10 when omitted.
+
+- bcrypt.**genSalt**(rounds?: `number`): `Promise<string>`<br />
+  Asynchronously generates a salt. Number of rounds defaults to 10 when omitted.
+
+- bcrypt.**genSalt**([rounds: `number`, ]callback: `Callback<string>`): `void`<br />
+  Asynchronously generates a salt. Number of rounds defaults to 10 when omitted.
+
+- bcrypt.**truncates**(password: `string`): `boolean`<br />
+  Tests if a password will be truncated when hashed, that is its length is greater than 72 bytes when converted to UTF-8.
+
+- bcrypt.**hashSync**(password: `string`, salt?: `number | string`): `string`
+  Synchronously generates a hash for the given password. Number of rounds defaults to 10 when omitted.
+
+- bcrypt.**hash**(password: `string`, salt: `number | string`): `Promise<string>`<br />
+  Asynchronously generates a hash for the given password.
+
+- bcrypt.**hash**(password: `string`, salt: `number | string`, callback: `Callback<string>`, progressCallback?: `ProgressCallback`): `void`<br />
+  Asynchronously generates a hash for the given password.
+
+- bcrypt.**compareSync**(password: `string`, hash: `string`): `boolean`<br />
+  Synchronously tests a password against a hash.
+
+- bcrypt.**compare**(password: `string`, hash: `string`): `Promise<boolean>`<br />
+  Asynchronously compares a password against a hash.
+
+- bcrypt.**compare**(password: `string`, hash: `string`, callback: `Callback<boolean>`, progressCallback?: `ProgressCallback`)<br />
+  Asynchronously compares a password against a hash.
+
+- bcrypt.**getRounds**(hash: `string`): `number`<br />
+  Gets the number of rounds used to encrypt the specified hash.
+
+- bcrypt.**getSalt**(hash: `string`): `string`<br />
+  Gets the salt portion from a hash. Does not validate the hash.
+
+- bcrypt.**setRandomFallback**(random: `RandomFallback`): `void`<br />
+  Sets the pseudo random number generator to use as a fallback if neither [Web Crypto API](http://www.w3.org/TR/WebCryptoAPI/) nor Node.js [crypto](http://nodejs.org/api/crypto.html) are available. Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly!
+
+## Building
+
+Building the UMD fallback:
+
+```
+$> npm run build
+```
+
+Running the [tests](./tests):
+
+```
+$> npm test
+```
+
+## Credits
+
+Based on work started by Shane Girish at [bcrypt-nodejs](https://github.com/shaneGirish/bcrypt-nodejs), which is itself
+based on [javascript-bcrypt](http://code.google.com/p/javascript-bcrypt/) (New BSD-licensed).

+ 23 - 0
node_modules/bcryptjs/bin/bcrypt

@@ -0,0 +1,23 @@
+#!/usr/bin/env node
+
+import path from "node:path";
+import bcrypt from "../index.js";
+
+if (process.argv.length < 3) {
+  console.log(
+    "Usage: " + path.basename(process.argv[1]) + " <input> [rounds|salt]",
+  );
+  process.exit(1);
+} else {
+  var salt;
+  if (process.argv.length > 3) {
+    salt = process.argv[3];
+    var rounds = parseInt(salt, 10);
+    if (rounds == salt) {
+      salt = bcrypt.genSaltSync(rounds);
+    }
+  } else {
+    salt = bcrypt.genSaltSync();
+  }
+  console.log(bcrypt.hashSync(process.argv[2], salt));
+}

+ 3 - 0
node_modules/bcryptjs/index.d.ts

@@ -0,0 +1,3 @@
+import * as bcrypt from "./types.js";
+export * from "./types.js";
+export default bcrypt;

+ 1159 - 0
node_modules/bcryptjs/index.js

@@ -0,0 +1,1159 @@
+/*
+ Copyright (c) 2012 Nevins Bartolomeo <nevins.bartolomeo@gmail.com>
+ Copyright (c) 2012 Shane Girish <shaneGirish@gmail.com>
+ Copyright (c) 2025 Daniel Wirtz <dcode@dcode.io>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. The name of the author may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// The Node.js crypto module is used as a fallback for the Web Crypto API. When
+// building for the browser, inclusion of the crypto module should be disabled,
+// which the package hints at in its package.json for bundlers that support it.
+import nodeCrypto from "crypto";
+
+/**
+ * The random implementation to use as a fallback.
+ * @type {?function(number):!Array.<number>}
+ * @inner
+ */
+var randomFallback = null;
+
+/**
+ * Generates cryptographically secure random bytes.
+ * @function
+ * @param {number} len Bytes length
+ * @returns {!Array.<number>} Random bytes
+ * @throws {Error} If no random implementation is available
+ * @inner
+ */
+function randomBytes(len) {
+  // Web Crypto API. Globally available in the browser and in Node.js >=23.
+  try {
+    return crypto.getRandomValues(new Uint8Array(len));
+  } catch {}
+  // Node.js crypto module for non-browser environments.
+  try {
+    return nodeCrypto.randomBytes(len);
+  } catch {}
+  // Custom fallback specified with `setRandomFallback`.
+  if (!randomFallback) {
+    throw Error(
+      "Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative",
+    );
+  }
+  return randomFallback(len);
+}
+
+/**
+ * Sets the pseudo random number generator to use as a fallback if neither node's `crypto` module nor the Web Crypto
+ *  API is available. Please note: It is highly important that the PRNG used is cryptographically secure and that it
+ *  is seeded properly!
+ * @param {?function(number):!Array.<number>} random Function taking the number of bytes to generate as its
+ *  sole argument, returning the corresponding array of cryptographically secure random byte values.
+ * @see http://nodejs.org/api/crypto.html
+ * @see http://www.w3.org/TR/WebCryptoAPI/
+ */
+export function setRandomFallback(random) {
+  randomFallback = random;
+}
+
+/**
+ * Synchronously generates a salt.
+ * @param {number=} rounds Number of rounds to use, defaults to 10 if omitted
+ * @param {number=} seed_length Not supported.
+ * @returns {string} Resulting salt
+ * @throws {Error} If a random fallback is required but not set
+ */
+export function genSaltSync(rounds, seed_length) {
+  rounds = rounds || GENSALT_DEFAULT_LOG2_ROUNDS;
+  if (typeof rounds !== "number")
+    throw Error(
+      "Illegal arguments: " + typeof rounds + ", " + typeof seed_length,
+    );
+  if (rounds < 4) rounds = 4;
+  else if (rounds > 31) rounds = 31;
+  var salt = [];
+  salt.push("$2b$");
+  if (rounds < 10) salt.push("0");
+  salt.push(rounds.toString());
+  salt.push("$");
+  salt.push(base64_encode(randomBytes(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN)); // May throw
+  return salt.join("");
+}
+
+/**
+ * Asynchronously generates a salt.
+ * @param {(number|function(Error, string=))=} rounds Number of rounds to use, defaults to 10 if omitted
+ * @param {(number|function(Error, string=))=} seed_length Not supported.
+ * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting salt
+ * @returns {!Promise} If `callback` has been omitted
+ * @throws {Error} If `callback` is present but not a function
+ */
+export function genSalt(rounds, seed_length, callback) {
+  if (typeof seed_length === "function")
+    (callback = seed_length), (seed_length = undefined); // Not supported.
+  if (typeof rounds === "function") (callback = rounds), (rounds = undefined);
+  if (typeof rounds === "undefined") rounds = GENSALT_DEFAULT_LOG2_ROUNDS;
+  else if (typeof rounds !== "number")
+    throw Error("illegal arguments: " + typeof rounds);
+
+  function _async(callback) {
+    nextTick(function () {
+      // Pretty thin, but salting is fast enough
+      try {
+        callback(null, genSaltSync(rounds));
+      } catch (err) {
+        callback(err);
+      }
+    });
+  }
+
+  if (callback) {
+    if (typeof callback !== "function")
+      throw Error("Illegal callback: " + typeof callback);
+    _async(callback);
+  } else
+    return new Promise(function (resolve, reject) {
+      _async(function (err, res) {
+        if (err) {
+          reject(err);
+          return;
+        }
+        resolve(res);
+      });
+    });
+}
+
+/**
+ * Synchronously generates a hash for the given password.
+ * @param {string} password Password to hash
+ * @param {(number|string)=} salt Salt length to generate or salt to use, default to 10
+ * @returns {string} Resulting hash
+ */
+export function hashSync(password, salt) {
+  if (typeof salt === "undefined") salt = GENSALT_DEFAULT_LOG2_ROUNDS;
+  if (typeof salt === "number") salt = genSaltSync(salt);
+  if (typeof password !== "string" || typeof salt !== "string")
+    throw Error("Illegal arguments: " + typeof password + ", " + typeof salt);
+  return _hash(password, salt);
+}
+
+/**
+ * Asynchronously generates a hash for the given password.
+ * @param {string} password Password to hash
+ * @param {number|string} salt Salt length to generate or salt to use
+ * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash
+ * @param {function(number)=} progressCallback Callback successively called with the percentage of rounds completed
+ *  (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
+ * @returns {!Promise} If `callback` has been omitted
+ * @throws {Error} If `callback` is present but not a function
+ */
+export function hash(password, salt, callback, progressCallback) {
+  function _async(callback) {
+    if (typeof password === "string" && typeof salt === "number")
+      genSalt(salt, function (err, salt) {
+        _hash(password, salt, callback, progressCallback);
+      });
+    else if (typeof password === "string" && typeof salt === "string")
+      _hash(password, salt, callback, progressCallback);
+    else
+      nextTick(
+        callback.bind(
+          this,
+          Error("Illegal arguments: " + typeof password + ", " + typeof salt),
+        ),
+      );
+  }
+
+  if (callback) {
+    if (typeof callback !== "function")
+      throw Error("Illegal callback: " + typeof callback);
+    _async(callback);
+  } else
+    return new Promise(function (resolve, reject) {
+      _async(function (err, res) {
+        if (err) {
+          reject(err);
+          return;
+        }
+        resolve(res);
+      });
+    });
+}
+
+/**
+ * Compares two strings of the same length in constant time.
+ * @param {string} known Must be of the correct length
+ * @param {string} unknown Must be the same length as `known`
+ * @returns {boolean}
+ * @inner
+ */
+function safeStringCompare(known, unknown) {
+  var diff = known.length ^ unknown.length;
+  for (var i = 0; i < known.length; ++i) {
+    diff |= known.charCodeAt(i) ^ unknown.charCodeAt(i);
+  }
+  return diff === 0;
+}
+
+/**
+ * Synchronously tests a password against a hash.
+ * @param {string} password Password to compare
+ * @param {string} hash Hash to test against
+ * @returns {boolean} true if matching, otherwise false
+ * @throws {Error} If an argument is illegal
+ */
+export function compareSync(password, hash) {
+  if (typeof password !== "string" || typeof hash !== "string")
+    throw Error("Illegal arguments: " + typeof password + ", " + typeof hash);
+  if (hash.length !== 60) return false;
+  return safeStringCompare(
+    hashSync(password, hash.substring(0, hash.length - 31)),
+    hash,
+  );
+}
+
+/**
+ * Asynchronously tests a password against a hash.
+ * @param {string} password Password to compare
+ * @param {string} hashValue Hash to test against
+ * @param {function(Error, boolean)=} callback Callback receiving the error, if any, otherwise the result
+ * @param {function(number)=} progressCallback Callback successively called with the percentage of rounds completed
+ *  (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
+ * @returns {!Promise} If `callback` has been omitted
+ * @throws {Error} If `callback` is present but not a function
+ */
+export function compare(password, hashValue, callback, progressCallback) {
+  function _async(callback) {
+    if (typeof password !== "string" || typeof hashValue !== "string") {
+      nextTick(
+        callback.bind(
+          this,
+          Error(
+            "Illegal arguments: " + typeof password + ", " + typeof hashValue,
+          ),
+        ),
+      );
+      return;
+    }
+    if (hashValue.length !== 60) {
+      nextTick(callback.bind(this, null, false));
+      return;
+    }
+    hash(
+      password,
+      hashValue.substring(0, 29),
+      function (err, comp) {
+        if (err) callback(err);
+        else callback(null, safeStringCompare(comp, hashValue));
+      },
+      progressCallback,
+    );
+  }
+
+  if (callback) {
+    if (typeof callback !== "function")
+      throw Error("Illegal callback: " + typeof callback);
+    _async(callback);
+  } else
+    return new Promise(function (resolve, reject) {
+      _async(function (err, res) {
+        if (err) {
+          reject(err);
+          return;
+        }
+        resolve(res);
+      });
+    });
+}
+
+/**
+ * Gets the number of rounds used to encrypt the specified hash.
+ * @param {string} hash Hash to extract the used number of rounds from
+ * @returns {number} Number of rounds used
+ * @throws {Error} If `hash` is not a string
+ */
+export function getRounds(hash) {
+  if (typeof hash !== "string")
+    throw Error("Illegal arguments: " + typeof hash);
+  return parseInt(hash.split("$")[2], 10);
+}
+
+/**
+ * Gets the salt portion from a hash. Does not validate the hash.
+ * @param {string} hash Hash to extract the salt from
+ * @returns {string} Extracted salt part
+ * @throws {Error} If `hash` is not a string or otherwise invalid
+ */
+export function getSalt(hash) {
+  if (typeof hash !== "string")
+    throw Error("Illegal arguments: " + typeof hash);
+  if (hash.length !== 60)
+    throw Error("Illegal hash length: " + hash.length + " != 60");
+  return hash.substring(0, 29);
+}
+
+/**
+ * Tests if a password will be truncated when hashed, that is its length is
+ * greater than 72 bytes when converted to UTF-8.
+ * @param {string} password The password to test
+ * @returns {boolean} `true` if truncated, otherwise `false`
+ */
+export function truncates(password) {
+  if (typeof password !== "string")
+    throw Error("Illegal arguments: " + typeof password);
+  return utf8Length(password) > 72;
+}
+
+/**
+ * Continues with the callback after yielding to the event loop.
+ * @function
+ * @param {function(...[*])} callback Callback to execute
+ * @inner
+ */
+var nextTick =
+  typeof setImmediate === "function"
+    ? setImmediate
+    : typeof scheduler === "object" && typeof scheduler.postTask === "function"
+      ? scheduler.postTask.bind(scheduler)
+      : setTimeout;
+
+/** Calculates the byte length of a string encoded as UTF8. */
+function utf8Length(string) {
+  var len = 0,
+    c = 0;
+  for (var i = 0; i < string.length; ++i) {
+    c = string.charCodeAt(i);
+    if (c < 128) len += 1;
+    else if (c < 2048) len += 2;
+    else if (
+      (c & 0xfc00) === 0xd800 &&
+      (string.charCodeAt(i + 1) & 0xfc00) === 0xdc00
+    ) {
+      ++i;
+      len += 4;
+    } else len += 3;
+  }
+  return len;
+}
+
+/** Converts a string to an array of UTF8 bytes. */
+function utf8Array(string) {
+  var offset = 0,
+    c1,
+    c2;
+  var buffer = new Array(utf8Length(string));
+  for (var i = 0, k = string.length; i < k; ++i) {
+    c1 = string.charCodeAt(i);
+    if (c1 < 128) {
+      buffer[offset++] = c1;
+    } else if (c1 < 2048) {
+      buffer[offset++] = (c1 >> 6) | 192;
+      buffer[offset++] = (c1 & 63) | 128;
+    } else if (
+      (c1 & 0xfc00) === 0xd800 &&
+      ((c2 = string.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
+    ) {
+      c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
+      ++i;
+      buffer[offset++] = (c1 >> 18) | 240;
+      buffer[offset++] = ((c1 >> 12) & 63) | 128;
+      buffer[offset++] = ((c1 >> 6) & 63) | 128;
+      buffer[offset++] = (c1 & 63) | 128;
+    } else {
+      buffer[offset++] = (c1 >> 12) | 224;
+      buffer[offset++] = ((c1 >> 6) & 63) | 128;
+      buffer[offset++] = (c1 & 63) | 128;
+    }
+  }
+  return buffer;
+}
+
+// A base64 implementation for the bcrypt algorithm. This is partly non-standard.
+
+/**
+ * bcrypt's own non-standard base64 dictionary.
+ * @type {!Array.<string>}
+ * @const
+ * @inner
+ **/
+var BASE64_CODE =
+  "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
+
+/**
+ * @type {!Array.<number>}
+ * @const
+ * @inner
+ **/
+var BASE64_INDEX = [
+  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+  -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
+  -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+  16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1, -1, 28,
+  29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+  48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1,
+];
+
+/**
+ * Encodes a byte array to base64 with up to len bytes of input.
+ * @param {!Array.<number>} b Byte array
+ * @param {number} len Maximum input length
+ * @returns {string}
+ * @inner
+ */
+function base64_encode(b, len) {
+  var off = 0,
+    rs = [],
+    c1,
+    c2;
+  if (len <= 0 || len > b.length) throw Error("Illegal len: " + len);
+  while (off < len) {
+    c1 = b[off++] & 0xff;
+    rs.push(BASE64_CODE[(c1 >> 2) & 0x3f]);
+    c1 = (c1 & 0x03) << 4;
+    if (off >= len) {
+      rs.push(BASE64_CODE[c1 & 0x3f]);
+      break;
+    }
+    c2 = b[off++] & 0xff;
+    c1 |= (c2 >> 4) & 0x0f;
+    rs.push(BASE64_CODE[c1 & 0x3f]);
+    c1 = (c2 & 0x0f) << 2;
+    if (off >= len) {
+      rs.push(BASE64_CODE[c1 & 0x3f]);
+      break;
+    }
+    c2 = b[off++] & 0xff;
+    c1 |= (c2 >> 6) & 0x03;
+    rs.push(BASE64_CODE[c1 & 0x3f]);
+    rs.push(BASE64_CODE[c2 & 0x3f]);
+  }
+  return rs.join("");
+}
+
+/**
+ * Decodes a base64 encoded string to up to len bytes of output.
+ * @param {string} s String to decode
+ * @param {number} len Maximum output length
+ * @returns {!Array.<number>}
+ * @inner
+ */
+function base64_decode(s, len) {
+  var off = 0,
+    slen = s.length,
+    olen = 0,
+    rs = [],
+    c1,
+    c2,
+    c3,
+    c4,
+    o,
+    code;
+  if (len <= 0) throw Error("Illegal len: " + len);
+  while (off < slen - 1 && olen < len) {
+    code = s.charCodeAt(off++);
+    c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
+    code = s.charCodeAt(off++);
+    c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
+    if (c1 == -1 || c2 == -1) break;
+    o = (c1 << 2) >>> 0;
+    o |= (c2 & 0x30) >> 4;
+    rs.push(String.fromCharCode(o));
+    if (++olen >= len || off >= slen) break;
+    code = s.charCodeAt(off++);
+    c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
+    if (c3 == -1) break;
+    o = ((c2 & 0x0f) << 4) >>> 0;
+    o |= (c3 & 0x3c) >> 2;
+    rs.push(String.fromCharCode(o));
+    if (++olen >= len || off >= slen) break;
+    code = s.charCodeAt(off++);
+    c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
+    o = ((c3 & 0x03) << 6) >>> 0;
+    o |= c4;
+    rs.push(String.fromCharCode(o));
+    ++olen;
+  }
+  var res = [];
+  for (off = 0; off < olen; off++) res.push(rs[off].charCodeAt(0));
+  return res;
+}
+
+/**
+ * @type {number}
+ * @const
+ * @inner
+ */
+var BCRYPT_SALT_LEN = 16;
+
+/**
+ * @type {number}
+ * @const
+ * @inner
+ */
+var GENSALT_DEFAULT_LOG2_ROUNDS = 10;
+
+/**
+ * @type {number}
+ * @const
+ * @inner
+ */
+var BLOWFISH_NUM_ROUNDS = 16;
+
+/**
+ * @type {number}
+ * @const
+ * @inner
+ */
+var MAX_EXECUTION_TIME = 100;
+
+/**
+ * @type {Array.<number>}
+ * @const
+ * @inner
+ */
+var P_ORIG = [
+  0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
+  0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
+  0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b,
+];
+
+/**
+ * @type {Array.<number>}
+ * @const
+ * @inner
+ */
+var S_ORIG = [
+  0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
+  0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
+  0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
+  0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
+  0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
+  0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
+  0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
+  0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
+  0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
+  0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
+  0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
+  0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
+  0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
+  0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
+  0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
+  0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
+  0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
+  0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
+  0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
+  0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
+  0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
+  0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
+  0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
+  0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
+  0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
+  0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
+  0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
+  0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
+  0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
+  0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
+  0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
+  0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
+  0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
+  0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
+  0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
+  0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
+  0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
+  0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
+  0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
+  0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
+  0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
+  0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
+  0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, 0x4b7a70e9, 0xb5b32944,
+  0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
+  0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29,
+  0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
+  0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26,
+  0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
+  0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c,
+  0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
+  0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6,
+  0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
+  0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f,
+  0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
+  0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810,
+  0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
+  0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa,
+  0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
+  0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55,
+  0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
+  0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1,
+  0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
+  0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78,
+  0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
+  0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883,
+  0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
+  0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170,
+  0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
+  0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7,
+  0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
+  0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099,
+  0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
+  0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263,
+  0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
+  0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3,
+  0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
+  0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7,
+  0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
+  0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d,
+  0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
+  0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460,
+  0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
+  0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484,
+  0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
+  0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a,
+  0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
+  0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a,
+  0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
+  0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785,
+  0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
+  0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900,
+  0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
+  0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9,
+  0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
+  0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397,
+  0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
+  0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9,
+  0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
+  0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f,
+  0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
+  0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e,
+  0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
+  0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd,
+  0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
+  0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8,
+  0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
+  0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c,
+  0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
+  0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b,
+  0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
+  0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386,
+  0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
+  0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0,
+  0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
+  0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2,
+  0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
+  0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770,
+  0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
+  0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c,
+  0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
+  0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa,
+  0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
+  0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63,
+  0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
+  0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9,
+  0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
+  0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4,
+  0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
+  0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
+  0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
+  0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
+  0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
+  0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
+  0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
+  0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
+  0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
+  0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
+  0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
+  0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
+  0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
+  0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
+  0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
+  0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
+  0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
+  0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
+  0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
+  0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
+  0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
+  0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
+  0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
+  0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
+  0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
+  0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
+  0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
+  0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
+  0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
+  0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
+  0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
+  0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
+  0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
+  0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
+  0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
+  0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
+  0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
+  0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
+  0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
+  0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
+  0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
+  0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
+  0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
+  0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6,
+];
+
+/**
+ * @type {Array.<number>}
+ * @const
+ * @inner
+ */
+var C_ORIG = [
+  0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274,
+];
+
+/**
+ * @param {Array.<number>} lr
+ * @param {number} off
+ * @param {Array.<number>} P
+ * @param {Array.<number>} S
+ * @returns {Array.<number>}
+ * @inner
+ */
+function _encipher(lr, off, P, S) {
+  // This is our bottleneck: 1714/1905 ticks / 90% - see profile.txt
+  var n,
+    l = lr[off],
+    r = lr[off + 1];
+
+  l ^= P[0];
+
+  /*
+    for (var i=0, k=BLOWFISH_NUM_ROUNDS-2; i<=k;)
+        // Feistel substitution on left word
+        n  = S[l >>> 24],
+        n += S[0x100 | ((l >> 16) & 0xff)],
+        n ^= S[0x200 | ((l >> 8) & 0xff)],
+        n += S[0x300 | (l & 0xff)],
+        r ^= n ^ P[++i],
+        // Feistel substitution on right word
+        n  = S[r >>> 24],
+        n += S[0x100 | ((r >> 16) & 0xff)],
+        n ^= S[0x200 | ((r >> 8) & 0xff)],
+        n += S[0x300 | (r & 0xff)],
+        l ^= n ^ P[++i];
+    */
+
+  //The following is an unrolled version of the above loop.
+  //Iteration 0
+  n = S[l >>> 24];
+  n += S[0x100 | ((l >> 16) & 0xff)];
+  n ^= S[0x200 | ((l >> 8) & 0xff)];
+  n += S[0x300 | (l & 0xff)];
+  r ^= n ^ P[1];
+  n = S[r >>> 24];
+  n += S[0x100 | ((r >> 16) & 0xff)];
+  n ^= S[0x200 | ((r >> 8) & 0xff)];
+  n += S[0x300 | (r & 0xff)];
+  l ^= n ^ P[2];
+  //Iteration 1
+  n = S[l >>> 24];
+  n += S[0x100 | ((l >> 16) & 0xff)];
+  n ^= S[0x200 | ((l >> 8) & 0xff)];
+  n += S[0x300 | (l & 0xff)];
+  r ^= n ^ P[3];
+  n = S[r >>> 24];
+  n += S[0x100 | ((r >> 16) & 0xff)];
+  n ^= S[0x200 | ((r >> 8) & 0xff)];
+  n += S[0x300 | (r & 0xff)];
+  l ^= n ^ P[4];
+  //Iteration 2
+  n = S[l >>> 24];
+  n += S[0x100 | ((l >> 16) & 0xff)];
+  n ^= S[0x200 | ((l >> 8) & 0xff)];
+  n += S[0x300 | (l & 0xff)];
+  r ^= n ^ P[5];
+  n = S[r >>> 24];
+  n += S[0x100 | ((r >> 16) & 0xff)];
+  n ^= S[0x200 | ((r >> 8) & 0xff)];
+  n += S[0x300 | (r & 0xff)];
+  l ^= n ^ P[6];
+  //Iteration 3
+  n = S[l >>> 24];
+  n += S[0x100 | ((l >> 16) & 0xff)];
+  n ^= S[0x200 | ((l >> 8) & 0xff)];
+  n += S[0x300 | (l & 0xff)];
+  r ^= n ^ P[7];
+  n = S[r >>> 24];
+  n += S[0x100 | ((r >> 16) & 0xff)];
+  n ^= S[0x200 | ((r >> 8) & 0xff)];
+  n += S[0x300 | (r & 0xff)];
+  l ^= n ^ P[8];
+  //Iteration 4
+  n = S[l >>> 24];
+  n += S[0x100 | ((l >> 16) & 0xff)];
+  n ^= S[0x200 | ((l >> 8) & 0xff)];
+  n += S[0x300 | (l & 0xff)];
+  r ^= n ^ P[9];
+  n = S[r >>> 24];
+  n += S[0x100 | ((r >> 16) & 0xff)];
+  n ^= S[0x200 | ((r >> 8) & 0xff)];
+  n += S[0x300 | (r & 0xff)];
+  l ^= n ^ P[10];
+  //Iteration 5
+  n = S[l >>> 24];
+  n += S[0x100 | ((l >> 16) & 0xff)];
+  n ^= S[0x200 | ((l >> 8) & 0xff)];
+  n += S[0x300 | (l & 0xff)];
+  r ^= n ^ P[11];
+  n = S[r >>> 24];
+  n += S[0x100 | ((r >> 16) & 0xff)];
+  n ^= S[0x200 | ((r >> 8) & 0xff)];
+  n += S[0x300 | (r & 0xff)];
+  l ^= n ^ P[12];
+  //Iteration 6
+  n = S[l >>> 24];
+  n += S[0x100 | ((l >> 16) & 0xff)];
+  n ^= S[0x200 | ((l >> 8) & 0xff)];
+  n += S[0x300 | (l & 0xff)];
+  r ^= n ^ P[13];
+  n = S[r >>> 24];
+  n += S[0x100 | ((r >> 16) & 0xff)];
+  n ^= S[0x200 | ((r >> 8) & 0xff)];
+  n += S[0x300 | (r & 0xff)];
+  l ^= n ^ P[14];
+  //Iteration 7
+  n = S[l >>> 24];
+  n += S[0x100 | ((l >> 16) & 0xff)];
+  n ^= S[0x200 | ((l >> 8) & 0xff)];
+  n += S[0x300 | (l & 0xff)];
+  r ^= n ^ P[15];
+  n = S[r >>> 24];
+  n += S[0x100 | ((r >> 16) & 0xff)];
+  n ^= S[0x200 | ((r >> 8) & 0xff)];
+  n += S[0x300 | (r & 0xff)];
+  l ^= n ^ P[16];
+
+  lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1];
+  lr[off + 1] = l;
+  return lr;
+}
+
+/**
+ * @param {Array.<number>} data
+ * @param {number} offp
+ * @returns {{key: number, offp: number}}
+ * @inner
+ */
+function _streamtoword(data, offp) {
+  for (var i = 0, word = 0; i < 4; ++i)
+    (word = (word << 8) | (data[offp] & 0xff)),
+      (offp = (offp + 1) % data.length);
+  return { key: word, offp: offp };
+}
+
+/**
+ * @param {Array.<number>} key
+ * @param {Array.<number>} P
+ * @param {Array.<number>} S
+ * @inner
+ */
+function _key(key, P, S) {
+  var offset = 0,
+    lr = [0, 0],
+    plen = P.length,
+    slen = S.length,
+    sw;
+  for (var i = 0; i < plen; i++)
+    (sw = _streamtoword(key, offset)),
+      (offset = sw.offp),
+      (P[i] = P[i] ^ sw.key);
+  for (i = 0; i < plen; i += 2)
+    (lr = _encipher(lr, 0, P, S)), (P[i] = lr[0]), (P[i + 1] = lr[1]);
+  for (i = 0; i < slen; i += 2)
+    (lr = _encipher(lr, 0, P, S)), (S[i] = lr[0]), (S[i + 1] = lr[1]);
+}
+
+/**
+ * Expensive key schedule Blowfish.
+ * @param {Array.<number>} data
+ * @param {Array.<number>} key
+ * @param {Array.<number>} P
+ * @param {Array.<number>} S
+ * @inner
+ */
+function _ekskey(data, key, P, S) {
+  var offp = 0,
+    lr = [0, 0],
+    plen = P.length,
+    slen = S.length,
+    sw;
+  for (var i = 0; i < plen; i++)
+    (sw = _streamtoword(key, offp)), (offp = sw.offp), (P[i] = P[i] ^ sw.key);
+  offp = 0;
+  for (i = 0; i < plen; i += 2)
+    (sw = _streamtoword(data, offp)),
+      (offp = sw.offp),
+      (lr[0] ^= sw.key),
+      (sw = _streamtoword(data, offp)),
+      (offp = sw.offp),
+      (lr[1] ^= sw.key),
+      (lr = _encipher(lr, 0, P, S)),
+      (P[i] = lr[0]),
+      (P[i + 1] = lr[1]);
+  for (i = 0; i < slen; i += 2)
+    (sw = _streamtoword(data, offp)),
+      (offp = sw.offp),
+      (lr[0] ^= sw.key),
+      (sw = _streamtoword(data, offp)),
+      (offp = sw.offp),
+      (lr[1] ^= sw.key),
+      (lr = _encipher(lr, 0, P, S)),
+      (S[i] = lr[0]),
+      (S[i + 1] = lr[1]);
+}
+
+/**
+ * Internaly crypts a string.
+ * @param {Array.<number>} b Bytes to crypt
+ * @param {Array.<number>} salt Salt bytes to use
+ * @param {number} rounds Number of rounds
+ * @param {function(Error, Array.<number>=)=} callback Callback receiving the error, if any, and the resulting bytes. If
+ *  omitted, the operation will be performed synchronously.
+ *  @param {function(number)=} progressCallback Callback called with the current progress
+ * @returns {!Array.<number>|undefined} Resulting bytes if callback has been omitted, otherwise `undefined`
+ * @inner
+ */
+function _crypt(b, salt, rounds, callback, progressCallback) {
+  var cdata = C_ORIG.slice(),
+    clen = cdata.length,
+    err;
+
+  // Validate
+  if (rounds < 4 || rounds > 31) {
+    err = Error("Illegal number of rounds (4-31): " + rounds);
+    if (callback) {
+      nextTick(callback.bind(this, err));
+      return;
+    } else throw err;
+  }
+  if (salt.length !== BCRYPT_SALT_LEN) {
+    err = Error(
+      "Illegal salt length: " + salt.length + " != " + BCRYPT_SALT_LEN,
+    );
+    if (callback) {
+      nextTick(callback.bind(this, err));
+      return;
+    } else throw err;
+  }
+  rounds = (1 << rounds) >>> 0;
+
+  var P,
+    S,
+    i = 0,
+    j;
+
+  //Use typed arrays when available - huge speedup!
+  if (typeof Int32Array === "function") {
+    P = new Int32Array(P_ORIG);
+    S = new Int32Array(S_ORIG);
+  } else {
+    P = P_ORIG.slice();
+    S = S_ORIG.slice();
+  }
+
+  _ekskey(salt, b, P, S);
+
+  /**
+   * Calcualtes the next round.
+   * @returns {Array.<number>|undefined} Resulting array if callback has been omitted, otherwise `undefined`
+   * @inner
+   */
+  function next() {
+    if (progressCallback) progressCallback(i / rounds);
+    if (i < rounds) {
+      var start = Date.now();
+      for (; i < rounds; ) {
+        i = i + 1;
+        _key(b, P, S);
+        _key(salt, P, S);
+        if (Date.now() - start > MAX_EXECUTION_TIME) break;
+      }
+    } else {
+      for (i = 0; i < 64; i++)
+        for (j = 0; j < clen >> 1; j++) _encipher(cdata, j << 1, P, S);
+      var ret = [];
+      for (i = 0; i < clen; i++)
+        ret.push(((cdata[i] >> 24) & 0xff) >>> 0),
+          ret.push(((cdata[i] >> 16) & 0xff) >>> 0),
+          ret.push(((cdata[i] >> 8) & 0xff) >>> 0),
+          ret.push((cdata[i] & 0xff) >>> 0);
+      if (callback) {
+        callback(null, ret);
+        return;
+      } else return ret;
+    }
+    if (callback) nextTick(next);
+  }
+
+  // Async
+  if (typeof callback !== "undefined") {
+    next();
+
+    // Sync
+  } else {
+    var res;
+    while (true) if (typeof (res = next()) !== "undefined") return res || [];
+  }
+}
+
+/**
+ * Internally hashes a password.
+ * @param {string} password Password to hash
+ * @param {?string} salt Salt to use, actually never null
+ * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash. If omitted,
+ *  hashing is performed synchronously.
+ *  @param {function(number)=} progressCallback Callback called with the current progress
+ * @returns {string|undefined} Resulting hash if callback has been omitted, otherwise `undefined`
+ * @inner
+ */
+function _hash(password, salt, callback, progressCallback) {
+  var err;
+  if (typeof password !== "string" || typeof salt !== "string") {
+    err = Error("Invalid string / salt: Not a string");
+    if (callback) {
+      nextTick(callback.bind(this, err));
+      return;
+    } else throw err;
+  }
+
+  // Validate the salt
+  var minor, offset;
+  if (salt.charAt(0) !== "$" || salt.charAt(1) !== "2") {
+    err = Error("Invalid salt version: " + salt.substring(0, 2));
+    if (callback) {
+      nextTick(callback.bind(this, err));
+      return;
+    } else throw err;
+  }
+  if (salt.charAt(2) === "$") (minor = String.fromCharCode(0)), (offset = 3);
+  else {
+    minor = salt.charAt(2);
+    if (
+      (minor !== "a" && minor !== "b" && minor !== "y") ||
+      salt.charAt(3) !== "$"
+    ) {
+      err = Error("Invalid salt revision: " + salt.substring(2, 4));
+      if (callback) {
+        nextTick(callback.bind(this, err));
+        return;
+      } else throw err;
+    }
+    offset = 4;
+  }
+
+  // Extract number of rounds
+  if (salt.charAt(offset + 2) > "$") {
+    err = Error("Missing salt rounds");
+    if (callback) {
+      nextTick(callback.bind(this, err));
+      return;
+    } else throw err;
+  }
+  var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10,
+    r2 = parseInt(salt.substring(offset + 1, offset + 2), 10),
+    rounds = r1 + r2,
+    real_salt = salt.substring(offset + 3, offset + 25);
+  password += minor >= "a" ? "\x00" : "";
+
+  var passwordb = utf8Array(password),
+    saltb = base64_decode(real_salt, BCRYPT_SALT_LEN);
+
+  /**
+   * Finishes hashing.
+   * @param {Array.<number>} bytes Byte array
+   * @returns {string}
+   * @inner
+   */
+  function finish(bytes) {
+    var res = [];
+    res.push("$2");
+    if (minor >= "a") res.push(minor);
+    res.push("$");
+    if (rounds < 10) res.push("0");
+    res.push(rounds.toString());
+    res.push("$");
+    res.push(base64_encode(saltb, saltb.length));
+    res.push(base64_encode(bytes, C_ORIG.length * 4 - 1));
+    return res.join("");
+  }
+
+  // Sync
+  if (typeof callback == "undefined")
+    return finish(_crypt(passwordb, saltb, rounds));
+  // Async
+  else {
+    _crypt(
+      passwordb,
+      saltb,
+      rounds,
+      function (err, bytes) {
+        if (err) callback(err, null);
+        else callback(null, finish(bytes));
+      },
+      progressCallback,
+    );
+  }
+}
+
+/**
+ * Encodes a byte array to base64 with up to len bytes of input, using the custom bcrypt alphabet.
+ * @function
+ * @param {!Array.<number>} bytes Byte array
+ * @param {number} length Maximum input length
+ * @returns {string}
+ */
+export function encodeBase64(bytes, length) {
+  return base64_encode(bytes, length);
+}
+
+/**
+ * Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet.
+ * @function
+ * @param {string} string String to decode
+ * @param {number} length Maximum output length
+ * @returns {!Array.<number>}
+ */
+export function decodeBase64(string, length) {
+  return base64_decode(string, length);
+}
+
+export default {
+  setRandomFallback,
+  genSaltSync,
+  genSalt,
+  hashSync,
+  hash,
+  compareSync,
+  compare,
+  getRounds,
+  getSalt,
+  truncates,
+  encodeBase64,
+  decodeBase64,
+};

+ 76 - 0
node_modules/bcryptjs/package.json

@@ -0,0 +1,76 @@
+{
+  "name": "bcryptjs",
+  "description": "Optimized bcrypt in plain JavaScript with zero dependencies, with TypeScript support. Compatible to 'bcrypt'.",
+  "version": "3.0.3",
+  "author": "Daniel Wirtz <dcode@dcode.io>",
+  "contributors": [
+    "Shane Girish <shaneGirish@gmail.com> (https://github.com/shaneGirish)",
+    "Alex Murray <> (https://github.com/alexmurray)",
+    "Nicolas Pelletier <> (https://github.com/NicolasPelletier)",
+    "Josh Rogers <> (https://github.com/geekymole)",
+    "Noah Isaacson <noah@nisaacson.com> (https://github.com/nisaacson)"
+  ],
+  "repository": {
+    "type": "url",
+    "url": "https://github.com/dcodeIO/bcrypt.js.git"
+  },
+  "bugs": {
+    "url": "https://github.com/dcodeIO/bcrypt.js/issues"
+  },
+  "keywords": [
+    "bcrypt",
+    "password",
+    "auth",
+    "authentication",
+    "encryption",
+    "crypt",
+    "crypto"
+  ],
+  "type": "module",
+  "main": "umd/index.js",
+  "types": "umd/index.d.ts",
+  "exports": {
+    ".": {
+      "import": {
+        "types": "./index.d.ts",
+        "default": "./index.js"
+      },
+      "require": {
+        "types": "./umd/index.d.ts",
+        "default": "./umd/index.js"
+      }
+    }
+  },
+  "bin": {
+    "bcrypt": "bin/bcrypt"
+  },
+  "license": "BSD-3-Clause",
+  "scripts": {
+    "build": "node scripts/build.js",
+    "lint": "prettier --check .",
+    "format": "prettier --write .",
+    "test": "npm run test:unit && npm run test:typescript",
+    "test:unit": "node tests",
+    "test:typescript": "tsc --project tests/typescript/tsconfig.esnext.json && tsc --project tests/typescript/tsconfig.nodenext.json && tsc --project tests/typescript/tsconfig.commonjs.json && tsc --project tests/typescript/tsconfig.global.json"
+  },
+  "files": [
+    "index.js",
+    "index.d.ts",
+    "types.d.ts",
+    "umd/index.js",
+    "umd/index.d.ts",
+    "umd/types.d.ts",
+    "umd/package.json",
+    "LICENSE",
+    "README.md"
+  ],
+  "browser": {
+    "crypto": false
+  },
+  "devDependencies": {
+    "bcrypt": "^5.1.1",
+    "esm2umd": "^0.3.1",
+    "prettier": "^3.5.0",
+    "typescript": "^5.7.3"
+  }
+}

+ 157 - 0
node_modules/bcryptjs/types.d.ts

@@ -0,0 +1,157 @@
+// Originally imported from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8b36dbdf95b624b8a7cd7f8416f06c15d274f9e6/types/bcryptjs/index.d.ts
+// MIT license.
+
+/** Called with an error on failure or a value of type `T` upon success. */
+type Callback<T> = (err: Error | null, result?: T) => void;
+/** Called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. */
+type ProgressCallback = (percentage: number) => void;
+/** Called to obtain random bytes when both Web Crypto API and Node.js crypto are not available. */
+type RandomFallback = (length: number) => number[];
+
+/**
+ * Sets the pseudo random number generator to use as a fallback if neither node's crypto module nor the Web Crypto API is available.
+ * Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly!
+ * @param  random Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values.
+ */
+export declare function setRandomFallback(random: RandomFallback): void;
+
+/**
+ * Synchronously generates a salt.
+ * @param  rounds Number of rounds to use, defaults to 10 if omitted
+ * @return Resulting salt
+ * @throws If a random fallback is required but not set
+ */
+export declare function genSaltSync(rounds?: number): string;
+
+/**
+ * Asynchronously generates a salt.
+ * @param  rounds  Number of rounds to use, defaults to 10 if omitted
+ * @return Promise with resulting salt, if callback has been omitted
+ */
+export declare function genSalt(rounds?: number): Promise<string>;
+
+/**
+ * Asynchronously generates a salt.
+ * @param callback Callback receiving the error, if any, and the resulting salt
+ */
+export declare function genSalt(callback: Callback<string>): void;
+
+/**
+ * Asynchronously generates a salt.
+ * @param  rounds   Number of rounds to use, defaults to 10 if omitted
+ * @param  callback Callback receiving the error, if any, and the resulting salt
+ */
+export declare function genSalt(
+  rounds: number,
+  callback: Callback<string>,
+): void;
+
+/**
+ * Synchronously generates a hash for the given password.
+ * @param  password Password to hash
+ * @param  salt Salt length to generate or salt to use, default to 10
+ * @return Resulting hash
+ */
+export declare function hashSync(
+  password: string,
+  salt?: number | string,
+): string;
+
+/**
+ * Asynchronously generates a hash for the given password.
+ * @param password Password to hash
+ * @param salt     Salt length to generate or salt to use
+ * @return Promise with resulting hash, if callback has been omitted
+ */
+export declare function hash(
+  password: string,
+  salt: number | string,
+): Promise<string>;
+
+/**
+ * Asynchronously generates a hash for the given password.
+ * @param password         Password to hash
+ * @param salt             Salt length to generate or salt to use
+ * @param callback         Callback receiving the error, if any, and the resulting hash
+ * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms.
+ */
+export declare function hash(
+  password: string,
+  salt: number | string,
+  callback?: Callback<string>,
+  progressCallback?: ProgressCallback,
+): void;
+
+/**
+ * Synchronously tests a password against a hash.
+ * @param  password Password to test
+ * @param  hash     Hash to test against
+ * @return true if matching, otherwise false
+ */
+export declare function compareSync(password: string, hash: string): boolean;
+
+/**
+ * Asynchronously tests a password against a hash.
+ * @param  password Password to test
+ * @param  hash     Hash to test against
+ * @return Promise, if callback has been omitted
+ */
+export declare function compare(
+  password: string,
+  hash: string,
+): Promise<boolean>;
+
+/**
+ * Asynchronously tests a password against a hash.
+ * @param  password         Password to test
+ * @param  hash             Hash to test against
+ * @param  callback         Callback receiving the error, if any, otherwise the result
+ * @param  progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms.
+ */
+export declare function compare(
+  password: string,
+  hash: string,
+  callback?: Callback<boolean>,
+  progressCallback?: ProgressCallback,
+): void;
+
+/**
+ * Gets the number of rounds used to encrypt the specified hash.
+ * @param  hash Hash to extract the used number of rounds from
+ * @return Number of rounds used
+ */
+export declare function getRounds(hash: string): number;
+
+/**
+ * Gets the salt portion from a hash. Does not validate the hash.
+ * @param  hash Hash to extract the salt from
+ * @return Extracted salt part
+ */
+export declare function getSalt(hash: string): string;
+
+/**
+ * Tests if a password will be truncated when hashed, that is its length is
+ * greater than 72 bytes when converted to UTF-8.
+ * @param password The password to test
+ * @returns `true` if truncated, otherwise `false`
+ */
+export declare function truncates(password: string): boolean;
+
+/**
+ * Encodes a byte array to base64 with up to len bytes of input, using the custom bcrypt alphabet.
+ * @function
+ * @param b Byte array
+ * @param len Maximum input length
+ */
+export declare function encodeBase64(
+  b: Readonly<ArrayLike<number>>,
+  len: number,
+): string;
+
+/**
+ * Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet.
+ * @function
+ * @param s String to decode
+ * @param len Maximum output length
+ */
+export declare function decodeBase64(s: string, len: number): number[];

+ 3 - 0
node_modules/bcryptjs/umd/index.d.ts

@@ -0,0 +1,3 @@
+import * as bcrypt from "./types.js";
+export = bcrypt;
+export as namespace bcrypt;

+ 1220 - 0
node_modules/bcryptjs/umd/index.js

@@ -0,0 +1,1220 @@
+// GENERATED FILE. DO NOT EDIT.
+(function (global, factory) {
+  function preferDefault(exports) {
+    return exports.default || exports;
+  }
+  if (typeof define === "function" && define.amd) {
+    define(["crypto"], function (_crypto) {
+      var exports = {};
+      factory(exports, _crypto);
+      return preferDefault(exports);
+    });
+  } else if (typeof exports === "object") {
+    factory(exports, require("crypto"));
+    if (typeof module === "object") module.exports = preferDefault(exports);
+  } else {
+    (function () {
+      var exports = {};
+      factory(exports, global.crypto);
+      global.bcrypt = preferDefault(exports);
+    })();
+  }
+})(
+  typeof globalThis !== "undefined"
+    ? globalThis
+    : typeof self !== "undefined"
+      ? self
+      : this,
+  function (_exports, _crypto) {
+    "use strict";
+
+    Object.defineProperty(_exports, "__esModule", {
+      value: true,
+    });
+    _exports.compare = compare;
+    _exports.compareSync = compareSync;
+    _exports.decodeBase64 = decodeBase64;
+    _exports.default = void 0;
+    _exports.encodeBase64 = encodeBase64;
+    _exports.genSalt = genSalt;
+    _exports.genSaltSync = genSaltSync;
+    _exports.getRounds = getRounds;
+    _exports.getSalt = getSalt;
+    _exports.hash = hash;
+    _exports.hashSync = hashSync;
+    _exports.setRandomFallback = setRandomFallback;
+    _exports.truncates = truncates;
+    _crypto = _interopRequireDefault(_crypto);
+    function _interopRequireDefault(e) {
+      return e && e.__esModule ? e : { default: e };
+    }
+    /*
+   Copyright (c) 2012 Nevins Bartolomeo <nevins.bartolomeo@gmail.com>
+   Copyright (c) 2012 Shane Girish <shaneGirish@gmail.com>
+   Copyright (c) 2025 Daniel Wirtz <dcode@dcode.io>
+  
+   Redistribution and use in source and binary forms, with or without
+   modification, are permitted provided that the following conditions
+   are met:
+   1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+   2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+   3. The name of the author may not be used to endorse or promote products
+   derived from this software without specific prior written permission.
+  
+   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+   */
+
+    // The Node.js crypto module is used as a fallback for the Web Crypto API. When
+    // building for the browser, inclusion of the crypto module should be disabled,
+    // which the package hints at in its package.json for bundlers that support it.
+
+    /**
+     * The random implementation to use as a fallback.
+     * @type {?function(number):!Array.<number>}
+     * @inner
+     */
+    var randomFallback = null;
+
+    /**
+     * Generates cryptographically secure random bytes.
+     * @function
+     * @param {number} len Bytes length
+     * @returns {!Array.<number>} Random bytes
+     * @throws {Error} If no random implementation is available
+     * @inner
+     */
+    function randomBytes(len) {
+      // Web Crypto API. Globally available in the browser and in Node.js >=23.
+      try {
+        return crypto.getRandomValues(new Uint8Array(len));
+      } catch {}
+      // Node.js crypto module for non-browser environments.
+      try {
+        return _crypto.default.randomBytes(len);
+      } catch {}
+      // Custom fallback specified with `setRandomFallback`.
+      if (!randomFallback) {
+        throw Error(
+          "Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative",
+        );
+      }
+      return randomFallback(len);
+    }
+
+    /**
+     * Sets the pseudo random number generator to use as a fallback if neither node's `crypto` module nor the Web Crypto
+     *  API is available. Please note: It is highly important that the PRNG used is cryptographically secure and that it
+     *  is seeded properly!
+     * @param {?function(number):!Array.<number>} random Function taking the number of bytes to generate as its
+     *  sole argument, returning the corresponding array of cryptographically secure random byte values.
+     * @see http://nodejs.org/api/crypto.html
+     * @see http://www.w3.org/TR/WebCryptoAPI/
+     */
+    function setRandomFallback(random) {
+      randomFallback = random;
+    }
+
+    /**
+     * Synchronously generates a salt.
+     * @param {number=} rounds Number of rounds to use, defaults to 10 if omitted
+     * @param {number=} seed_length Not supported.
+     * @returns {string} Resulting salt
+     * @throws {Error} If a random fallback is required but not set
+     */
+    function genSaltSync(rounds, seed_length) {
+      rounds = rounds || GENSALT_DEFAULT_LOG2_ROUNDS;
+      if (typeof rounds !== "number")
+        throw Error(
+          "Illegal arguments: " + typeof rounds + ", " + typeof seed_length,
+        );
+      if (rounds < 4) rounds = 4;
+      else if (rounds > 31) rounds = 31;
+      var salt = [];
+      salt.push("$2b$");
+      if (rounds < 10) salt.push("0");
+      salt.push(rounds.toString());
+      salt.push("$");
+      salt.push(base64_encode(randomBytes(BCRYPT_SALT_LEN), BCRYPT_SALT_LEN)); // May throw
+      return salt.join("");
+    }
+
+    /**
+     * Asynchronously generates a salt.
+     * @param {(number|function(Error, string=))=} rounds Number of rounds to use, defaults to 10 if omitted
+     * @param {(number|function(Error, string=))=} seed_length Not supported.
+     * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting salt
+     * @returns {!Promise} If `callback` has been omitted
+     * @throws {Error} If `callback` is present but not a function
+     */
+    function genSalt(rounds, seed_length, callback) {
+      if (typeof seed_length === "function")
+        (callback = seed_length), (seed_length = undefined); // Not supported.
+      if (typeof rounds === "function")
+        (callback = rounds), (rounds = undefined);
+      if (typeof rounds === "undefined") rounds = GENSALT_DEFAULT_LOG2_ROUNDS;
+      else if (typeof rounds !== "number")
+        throw Error("illegal arguments: " + typeof rounds);
+      function _async(callback) {
+        nextTick(function () {
+          // Pretty thin, but salting is fast enough
+          try {
+            callback(null, genSaltSync(rounds));
+          } catch (err) {
+            callback(err);
+          }
+        });
+      }
+      if (callback) {
+        if (typeof callback !== "function")
+          throw Error("Illegal callback: " + typeof callback);
+        _async(callback);
+      } else
+        return new Promise(function (resolve, reject) {
+          _async(function (err, res) {
+            if (err) {
+              reject(err);
+              return;
+            }
+            resolve(res);
+          });
+        });
+    }
+
+    /**
+     * Synchronously generates a hash for the given password.
+     * @param {string} password Password to hash
+     * @param {(number|string)=} salt Salt length to generate or salt to use, default to 10
+     * @returns {string} Resulting hash
+     */
+    function hashSync(password, salt) {
+      if (typeof salt === "undefined") salt = GENSALT_DEFAULT_LOG2_ROUNDS;
+      if (typeof salt === "number") salt = genSaltSync(salt);
+      if (typeof password !== "string" || typeof salt !== "string")
+        throw Error(
+          "Illegal arguments: " + typeof password + ", " + typeof salt,
+        );
+      return _hash(password, salt);
+    }
+
+    /**
+     * Asynchronously generates a hash for the given password.
+     * @param {string} password Password to hash
+     * @param {number|string} salt Salt length to generate or salt to use
+     * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash
+     * @param {function(number)=} progressCallback Callback successively called with the percentage of rounds completed
+     *  (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
+     * @returns {!Promise} If `callback` has been omitted
+     * @throws {Error} If `callback` is present but not a function
+     */
+    function hash(password, salt, callback, progressCallback) {
+      function _async(callback) {
+        if (typeof password === "string" && typeof salt === "number")
+          genSalt(salt, function (err, salt) {
+            _hash(password, salt, callback, progressCallback);
+          });
+        else if (typeof password === "string" && typeof salt === "string")
+          _hash(password, salt, callback, progressCallback);
+        else
+          nextTick(
+            callback.bind(
+              this,
+              Error(
+                "Illegal arguments: " + typeof password + ", " + typeof salt,
+              ),
+            ),
+          );
+      }
+      if (callback) {
+        if (typeof callback !== "function")
+          throw Error("Illegal callback: " + typeof callback);
+        _async(callback);
+      } else
+        return new Promise(function (resolve, reject) {
+          _async(function (err, res) {
+            if (err) {
+              reject(err);
+              return;
+            }
+            resolve(res);
+          });
+        });
+    }
+
+    /**
+     * Compares two strings of the same length in constant time.
+     * @param {string} known Must be of the correct length
+     * @param {string} unknown Must be the same length as `known`
+     * @returns {boolean}
+     * @inner
+     */
+    function safeStringCompare(known, unknown) {
+      var diff = known.length ^ unknown.length;
+      for (var i = 0; i < known.length; ++i) {
+        diff |= known.charCodeAt(i) ^ unknown.charCodeAt(i);
+      }
+      return diff === 0;
+    }
+
+    /**
+     * Synchronously tests a password against a hash.
+     * @param {string} password Password to compare
+     * @param {string} hash Hash to test against
+     * @returns {boolean} true if matching, otherwise false
+     * @throws {Error} If an argument is illegal
+     */
+    function compareSync(password, hash) {
+      if (typeof password !== "string" || typeof hash !== "string")
+        throw Error(
+          "Illegal arguments: " + typeof password + ", " + typeof hash,
+        );
+      if (hash.length !== 60) return false;
+      return safeStringCompare(
+        hashSync(password, hash.substring(0, hash.length - 31)),
+        hash,
+      );
+    }
+
+    /**
+     * Asynchronously tests a password against a hash.
+     * @param {string} password Password to compare
+     * @param {string} hashValue Hash to test against
+     * @param {function(Error, boolean)=} callback Callback receiving the error, if any, otherwise the result
+     * @param {function(number)=} progressCallback Callback successively called with the percentage of rounds completed
+     *  (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
+     * @returns {!Promise} If `callback` has been omitted
+     * @throws {Error} If `callback` is present but not a function
+     */
+    function compare(password, hashValue, callback, progressCallback) {
+      function _async(callback) {
+        if (typeof password !== "string" || typeof hashValue !== "string") {
+          nextTick(
+            callback.bind(
+              this,
+              Error(
+                "Illegal arguments: " +
+                  typeof password +
+                  ", " +
+                  typeof hashValue,
+              ),
+            ),
+          );
+          return;
+        }
+        if (hashValue.length !== 60) {
+          nextTick(callback.bind(this, null, false));
+          return;
+        }
+        hash(
+          password,
+          hashValue.substring(0, 29),
+          function (err, comp) {
+            if (err) callback(err);
+            else callback(null, safeStringCompare(comp, hashValue));
+          },
+          progressCallback,
+        );
+      }
+      if (callback) {
+        if (typeof callback !== "function")
+          throw Error("Illegal callback: " + typeof callback);
+        _async(callback);
+      } else
+        return new Promise(function (resolve, reject) {
+          _async(function (err, res) {
+            if (err) {
+              reject(err);
+              return;
+            }
+            resolve(res);
+          });
+        });
+    }
+
+    /**
+     * Gets the number of rounds used to encrypt the specified hash.
+     * @param {string} hash Hash to extract the used number of rounds from
+     * @returns {number} Number of rounds used
+     * @throws {Error} If `hash` is not a string
+     */
+    function getRounds(hash) {
+      if (typeof hash !== "string")
+        throw Error("Illegal arguments: " + typeof hash);
+      return parseInt(hash.split("$")[2], 10);
+    }
+
+    /**
+     * Gets the salt portion from a hash. Does not validate the hash.
+     * @param {string} hash Hash to extract the salt from
+     * @returns {string} Extracted salt part
+     * @throws {Error} If `hash` is not a string or otherwise invalid
+     */
+    function getSalt(hash) {
+      if (typeof hash !== "string")
+        throw Error("Illegal arguments: " + typeof hash);
+      if (hash.length !== 60)
+        throw Error("Illegal hash length: " + hash.length + " != 60");
+      return hash.substring(0, 29);
+    }
+
+    /**
+     * Tests if a password will be truncated when hashed, that is its length is
+     * greater than 72 bytes when converted to UTF-8.
+     * @param {string} password The password to test
+     * @returns {boolean} `true` if truncated, otherwise `false`
+     */
+    function truncates(password) {
+      if (typeof password !== "string")
+        throw Error("Illegal arguments: " + typeof password);
+      return utf8Length(password) > 72;
+    }
+
+    /**
+     * Continues with the callback after yielding to the event loop.
+     * @function
+     * @param {function(...[*])} callback Callback to execute
+     * @inner
+     */
+    var nextTick =
+      typeof setImmediate === "function"
+        ? setImmediate
+        : typeof scheduler === "object" &&
+            typeof scheduler.postTask === "function"
+          ? scheduler.postTask.bind(scheduler)
+          : setTimeout;
+
+    /** Calculates the byte length of a string encoded as UTF8. */
+    function utf8Length(string) {
+      var len = 0,
+        c = 0;
+      for (var i = 0; i < string.length; ++i) {
+        c = string.charCodeAt(i);
+        if (c < 128) len += 1;
+        else if (c < 2048) len += 2;
+        else if (
+          (c & 0xfc00) === 0xd800 &&
+          (string.charCodeAt(i + 1) & 0xfc00) === 0xdc00
+        ) {
+          ++i;
+          len += 4;
+        } else len += 3;
+      }
+      return len;
+    }
+
+    /** Converts a string to an array of UTF8 bytes. */
+    function utf8Array(string) {
+      var offset = 0,
+        c1,
+        c2;
+      var buffer = new Array(utf8Length(string));
+      for (var i = 0, k = string.length; i < k; ++i) {
+        c1 = string.charCodeAt(i);
+        if (c1 < 128) {
+          buffer[offset++] = c1;
+        } else if (c1 < 2048) {
+          buffer[offset++] = (c1 >> 6) | 192;
+          buffer[offset++] = (c1 & 63) | 128;
+        } else if (
+          (c1 & 0xfc00) === 0xd800 &&
+          ((c2 = string.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
+        ) {
+          c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
+          ++i;
+          buffer[offset++] = (c1 >> 18) | 240;
+          buffer[offset++] = ((c1 >> 12) & 63) | 128;
+          buffer[offset++] = ((c1 >> 6) & 63) | 128;
+          buffer[offset++] = (c1 & 63) | 128;
+        } else {
+          buffer[offset++] = (c1 >> 12) | 224;
+          buffer[offset++] = ((c1 >> 6) & 63) | 128;
+          buffer[offset++] = (c1 & 63) | 128;
+        }
+      }
+      return buffer;
+    }
+
+    // A base64 implementation for the bcrypt algorithm. This is partly non-standard.
+
+    /**
+     * bcrypt's own non-standard base64 dictionary.
+     * @type {!Array.<string>}
+     * @const
+     * @inner
+     **/
+    var BASE64_CODE =
+      "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(
+        "",
+      );
+
+    /**
+     * @type {!Array.<number>}
+     * @const
+     * @inner
+     **/
+    var BASE64_INDEX = [
+      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, 56, 57, 58, 59, 60,
+      61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
+      12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1,
+      -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
+      42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1,
+    ];
+
+    /**
+     * Encodes a byte array to base64 with up to len bytes of input.
+     * @param {!Array.<number>} b Byte array
+     * @param {number} len Maximum input length
+     * @returns {string}
+     * @inner
+     */
+    function base64_encode(b, len) {
+      var off = 0,
+        rs = [],
+        c1,
+        c2;
+      if (len <= 0 || len > b.length) throw Error("Illegal len: " + len);
+      while (off < len) {
+        c1 = b[off++] & 0xff;
+        rs.push(BASE64_CODE[(c1 >> 2) & 0x3f]);
+        c1 = (c1 & 0x03) << 4;
+        if (off >= len) {
+          rs.push(BASE64_CODE[c1 & 0x3f]);
+          break;
+        }
+        c2 = b[off++] & 0xff;
+        c1 |= (c2 >> 4) & 0x0f;
+        rs.push(BASE64_CODE[c1 & 0x3f]);
+        c1 = (c2 & 0x0f) << 2;
+        if (off >= len) {
+          rs.push(BASE64_CODE[c1 & 0x3f]);
+          break;
+        }
+        c2 = b[off++] & 0xff;
+        c1 |= (c2 >> 6) & 0x03;
+        rs.push(BASE64_CODE[c1 & 0x3f]);
+        rs.push(BASE64_CODE[c2 & 0x3f]);
+      }
+      return rs.join("");
+    }
+
+    /**
+     * Decodes a base64 encoded string to up to len bytes of output.
+     * @param {string} s String to decode
+     * @param {number} len Maximum output length
+     * @returns {!Array.<number>}
+     * @inner
+     */
+    function base64_decode(s, len) {
+      var off = 0,
+        slen = s.length,
+        olen = 0,
+        rs = [],
+        c1,
+        c2,
+        c3,
+        c4,
+        o,
+        code;
+      if (len <= 0) throw Error("Illegal len: " + len);
+      while (off < slen - 1 && olen < len) {
+        code = s.charCodeAt(off++);
+        c1 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
+        code = s.charCodeAt(off++);
+        c2 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
+        if (c1 == -1 || c2 == -1) break;
+        o = (c1 << 2) >>> 0;
+        o |= (c2 & 0x30) >> 4;
+        rs.push(String.fromCharCode(o));
+        if (++olen >= len || off >= slen) break;
+        code = s.charCodeAt(off++);
+        c3 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
+        if (c3 == -1) break;
+        o = ((c2 & 0x0f) << 4) >>> 0;
+        o |= (c3 & 0x3c) >> 2;
+        rs.push(String.fromCharCode(o));
+        if (++olen >= len || off >= slen) break;
+        code = s.charCodeAt(off++);
+        c4 = code < BASE64_INDEX.length ? BASE64_INDEX[code] : -1;
+        o = ((c3 & 0x03) << 6) >>> 0;
+        o |= c4;
+        rs.push(String.fromCharCode(o));
+        ++olen;
+      }
+      var res = [];
+      for (off = 0; off < olen; off++) res.push(rs[off].charCodeAt(0));
+      return res;
+    }
+
+    /**
+     * @type {number}
+     * @const
+     * @inner
+     */
+    var BCRYPT_SALT_LEN = 16;
+
+    /**
+     * @type {number}
+     * @const
+     * @inner
+     */
+    var GENSALT_DEFAULT_LOG2_ROUNDS = 10;
+
+    /**
+     * @type {number}
+     * @const
+     * @inner
+     */
+    var BLOWFISH_NUM_ROUNDS = 16;
+
+    /**
+     * @type {number}
+     * @const
+     * @inner
+     */
+    var MAX_EXECUTION_TIME = 100;
+
+    /**
+     * @type {Array.<number>}
+     * @const
+     * @inner
+     */
+    var P_ORIG = [
+      0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
+      0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
+      0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b,
+    ];
+
+    /**
+     * @type {Array.<number>}
+     * @const
+     * @inner
+     */
+    var S_ORIG = [
+      0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
+      0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
+      0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
+      0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
+      0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
+      0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
+      0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
+      0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
+      0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
+      0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
+      0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
+      0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
+      0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
+      0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
+      0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
+      0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
+      0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
+      0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
+      0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
+      0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
+      0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
+      0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
+      0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
+      0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
+      0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
+      0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
+      0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
+      0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
+      0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
+      0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
+      0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
+      0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
+      0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
+      0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
+      0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
+      0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
+      0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
+      0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
+      0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
+      0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
+      0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
+      0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
+      0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, 0x4b7a70e9, 0xb5b32944,
+      0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
+      0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29,
+      0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
+      0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26,
+      0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
+      0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c,
+      0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
+      0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6,
+      0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
+      0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f,
+      0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
+      0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810,
+      0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
+      0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa,
+      0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
+      0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55,
+      0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
+      0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1,
+      0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
+      0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78,
+      0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
+      0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883,
+      0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
+      0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170,
+      0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
+      0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7,
+      0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
+      0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099,
+      0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
+      0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263,
+      0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
+      0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3,
+      0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
+      0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7,
+      0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
+      0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d,
+      0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
+      0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460,
+      0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
+      0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484,
+      0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
+      0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a,
+      0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
+      0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a,
+      0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
+      0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785,
+      0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
+      0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900,
+      0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
+      0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9,
+      0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
+      0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397,
+      0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
+      0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9,
+      0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
+      0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f,
+      0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
+      0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e,
+      0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
+      0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd,
+      0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
+      0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8,
+      0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
+      0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c,
+      0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
+      0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b,
+      0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
+      0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386,
+      0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
+      0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0,
+      0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
+      0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2,
+      0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
+      0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770,
+      0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
+      0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c,
+      0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
+      0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa,
+      0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
+      0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63,
+      0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
+      0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9,
+      0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
+      0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4,
+      0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
+      0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
+      0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
+      0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
+      0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
+      0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
+      0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
+      0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
+      0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
+      0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
+      0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
+      0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
+      0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
+      0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
+      0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
+      0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
+      0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
+      0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
+      0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
+      0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
+      0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
+      0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
+      0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
+      0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
+      0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
+      0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
+      0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
+      0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
+      0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
+      0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
+      0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
+      0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
+      0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
+      0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
+      0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
+      0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
+      0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
+      0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
+      0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
+      0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
+      0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
+      0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
+      0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
+      0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6,
+    ];
+
+    /**
+     * @type {Array.<number>}
+     * @const
+     * @inner
+     */
+    var C_ORIG = [
+      0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274,
+    ];
+
+    /**
+     * @param {Array.<number>} lr
+     * @param {number} off
+     * @param {Array.<number>} P
+     * @param {Array.<number>} S
+     * @returns {Array.<number>}
+     * @inner
+     */
+    function _encipher(lr, off, P, S) {
+      // This is our bottleneck: 1714/1905 ticks / 90% - see profile.txt
+      var n,
+        l = lr[off],
+        r = lr[off + 1];
+      l ^= P[0];
+
+      /*
+      for (var i=0, k=BLOWFISH_NUM_ROUNDS-2; i<=k;)
+          // Feistel substitution on left word
+          n  = S[l >>> 24],
+          n += S[0x100 | ((l >> 16) & 0xff)],
+          n ^= S[0x200 | ((l >> 8) & 0xff)],
+          n += S[0x300 | (l & 0xff)],
+          r ^= n ^ P[++i],
+          // Feistel substitution on right word
+          n  = S[r >>> 24],
+          n += S[0x100 | ((r >> 16) & 0xff)],
+          n ^= S[0x200 | ((r >> 8) & 0xff)],
+          n += S[0x300 | (r & 0xff)],
+          l ^= n ^ P[++i];
+      */
+
+      //The following is an unrolled version of the above loop.
+      //Iteration 0
+      n = S[l >>> 24];
+      n += S[0x100 | ((l >> 16) & 0xff)];
+      n ^= S[0x200 | ((l >> 8) & 0xff)];
+      n += S[0x300 | (l & 0xff)];
+      r ^= n ^ P[1];
+      n = S[r >>> 24];
+      n += S[0x100 | ((r >> 16) & 0xff)];
+      n ^= S[0x200 | ((r >> 8) & 0xff)];
+      n += S[0x300 | (r & 0xff)];
+      l ^= n ^ P[2];
+      //Iteration 1
+      n = S[l >>> 24];
+      n += S[0x100 | ((l >> 16) & 0xff)];
+      n ^= S[0x200 | ((l >> 8) & 0xff)];
+      n += S[0x300 | (l & 0xff)];
+      r ^= n ^ P[3];
+      n = S[r >>> 24];
+      n += S[0x100 | ((r >> 16) & 0xff)];
+      n ^= S[0x200 | ((r >> 8) & 0xff)];
+      n += S[0x300 | (r & 0xff)];
+      l ^= n ^ P[4];
+      //Iteration 2
+      n = S[l >>> 24];
+      n += S[0x100 | ((l >> 16) & 0xff)];
+      n ^= S[0x200 | ((l >> 8) & 0xff)];
+      n += S[0x300 | (l & 0xff)];
+      r ^= n ^ P[5];
+      n = S[r >>> 24];
+      n += S[0x100 | ((r >> 16) & 0xff)];
+      n ^= S[0x200 | ((r >> 8) & 0xff)];
+      n += S[0x300 | (r & 0xff)];
+      l ^= n ^ P[6];
+      //Iteration 3
+      n = S[l >>> 24];
+      n += S[0x100 | ((l >> 16) & 0xff)];
+      n ^= S[0x200 | ((l >> 8) & 0xff)];
+      n += S[0x300 | (l & 0xff)];
+      r ^= n ^ P[7];
+      n = S[r >>> 24];
+      n += S[0x100 | ((r >> 16) & 0xff)];
+      n ^= S[0x200 | ((r >> 8) & 0xff)];
+      n += S[0x300 | (r & 0xff)];
+      l ^= n ^ P[8];
+      //Iteration 4
+      n = S[l >>> 24];
+      n += S[0x100 | ((l >> 16) & 0xff)];
+      n ^= S[0x200 | ((l >> 8) & 0xff)];
+      n += S[0x300 | (l & 0xff)];
+      r ^= n ^ P[9];
+      n = S[r >>> 24];
+      n += S[0x100 | ((r >> 16) & 0xff)];
+      n ^= S[0x200 | ((r >> 8) & 0xff)];
+      n += S[0x300 | (r & 0xff)];
+      l ^= n ^ P[10];
+      //Iteration 5
+      n = S[l >>> 24];
+      n += S[0x100 | ((l >> 16) & 0xff)];
+      n ^= S[0x200 | ((l >> 8) & 0xff)];
+      n += S[0x300 | (l & 0xff)];
+      r ^= n ^ P[11];
+      n = S[r >>> 24];
+      n += S[0x100 | ((r >> 16) & 0xff)];
+      n ^= S[0x200 | ((r >> 8) & 0xff)];
+      n += S[0x300 | (r & 0xff)];
+      l ^= n ^ P[12];
+      //Iteration 6
+      n = S[l >>> 24];
+      n += S[0x100 | ((l >> 16) & 0xff)];
+      n ^= S[0x200 | ((l >> 8) & 0xff)];
+      n += S[0x300 | (l & 0xff)];
+      r ^= n ^ P[13];
+      n = S[r >>> 24];
+      n += S[0x100 | ((r >> 16) & 0xff)];
+      n ^= S[0x200 | ((r >> 8) & 0xff)];
+      n += S[0x300 | (r & 0xff)];
+      l ^= n ^ P[14];
+      //Iteration 7
+      n = S[l >>> 24];
+      n += S[0x100 | ((l >> 16) & 0xff)];
+      n ^= S[0x200 | ((l >> 8) & 0xff)];
+      n += S[0x300 | (l & 0xff)];
+      r ^= n ^ P[15];
+      n = S[r >>> 24];
+      n += S[0x100 | ((r >> 16) & 0xff)];
+      n ^= S[0x200 | ((r >> 8) & 0xff)];
+      n += S[0x300 | (r & 0xff)];
+      l ^= n ^ P[16];
+      lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1];
+      lr[off + 1] = l;
+      return lr;
+    }
+
+    /**
+     * @param {Array.<number>} data
+     * @param {number} offp
+     * @returns {{key: number, offp: number}}
+     * @inner
+     */
+    function _streamtoword(data, offp) {
+      for (var i = 0, word = 0; i < 4; ++i)
+        (word = (word << 8) | (data[offp] & 0xff)),
+          (offp = (offp + 1) % data.length);
+      return {
+        key: word,
+        offp: offp,
+      };
+    }
+
+    /**
+     * @param {Array.<number>} key
+     * @param {Array.<number>} P
+     * @param {Array.<number>} S
+     * @inner
+     */
+    function _key(key, P, S) {
+      var offset = 0,
+        lr = [0, 0],
+        plen = P.length,
+        slen = S.length,
+        sw;
+      for (var i = 0; i < plen; i++)
+        (sw = _streamtoword(key, offset)),
+          (offset = sw.offp),
+          (P[i] = P[i] ^ sw.key);
+      for (i = 0; i < plen; i += 2)
+        (lr = _encipher(lr, 0, P, S)), (P[i] = lr[0]), (P[i + 1] = lr[1]);
+      for (i = 0; i < slen; i += 2)
+        (lr = _encipher(lr, 0, P, S)), (S[i] = lr[0]), (S[i + 1] = lr[1]);
+    }
+
+    /**
+     * Expensive key schedule Blowfish.
+     * @param {Array.<number>} data
+     * @param {Array.<number>} key
+     * @param {Array.<number>} P
+     * @param {Array.<number>} S
+     * @inner
+     */
+    function _ekskey(data, key, P, S) {
+      var offp = 0,
+        lr = [0, 0],
+        plen = P.length,
+        slen = S.length,
+        sw;
+      for (var i = 0; i < plen; i++)
+        (sw = _streamtoword(key, offp)),
+          (offp = sw.offp),
+          (P[i] = P[i] ^ sw.key);
+      offp = 0;
+      for (i = 0; i < plen; i += 2)
+        (sw = _streamtoword(data, offp)),
+          (offp = sw.offp),
+          (lr[0] ^= sw.key),
+          (sw = _streamtoword(data, offp)),
+          (offp = sw.offp),
+          (lr[1] ^= sw.key),
+          (lr = _encipher(lr, 0, P, S)),
+          (P[i] = lr[0]),
+          (P[i + 1] = lr[1]);
+      for (i = 0; i < slen; i += 2)
+        (sw = _streamtoword(data, offp)),
+          (offp = sw.offp),
+          (lr[0] ^= sw.key),
+          (sw = _streamtoword(data, offp)),
+          (offp = sw.offp),
+          (lr[1] ^= sw.key),
+          (lr = _encipher(lr, 0, P, S)),
+          (S[i] = lr[0]),
+          (S[i + 1] = lr[1]);
+    }
+
+    /**
+     * Internaly crypts a string.
+     * @param {Array.<number>} b Bytes to crypt
+     * @param {Array.<number>} salt Salt bytes to use
+     * @param {number} rounds Number of rounds
+     * @param {function(Error, Array.<number>=)=} callback Callback receiving the error, if any, and the resulting bytes. If
+     *  omitted, the operation will be performed synchronously.
+     *  @param {function(number)=} progressCallback Callback called with the current progress
+     * @returns {!Array.<number>|undefined} Resulting bytes if callback has been omitted, otherwise `undefined`
+     * @inner
+     */
+    function _crypt(b, salt, rounds, callback, progressCallback) {
+      var cdata = C_ORIG.slice(),
+        clen = cdata.length,
+        err;
+
+      // Validate
+      if (rounds < 4 || rounds > 31) {
+        err = Error("Illegal number of rounds (4-31): " + rounds);
+        if (callback) {
+          nextTick(callback.bind(this, err));
+          return;
+        } else throw err;
+      }
+      if (salt.length !== BCRYPT_SALT_LEN) {
+        err = Error(
+          "Illegal salt length: " + salt.length + " != " + BCRYPT_SALT_LEN,
+        );
+        if (callback) {
+          nextTick(callback.bind(this, err));
+          return;
+        } else throw err;
+      }
+      rounds = (1 << rounds) >>> 0;
+      var P,
+        S,
+        i = 0,
+        j;
+
+      //Use typed arrays when available - huge speedup!
+      if (typeof Int32Array === "function") {
+        P = new Int32Array(P_ORIG);
+        S = new Int32Array(S_ORIG);
+      } else {
+        P = P_ORIG.slice();
+        S = S_ORIG.slice();
+      }
+      _ekskey(salt, b, P, S);
+
+      /**
+       * Calcualtes the next round.
+       * @returns {Array.<number>|undefined} Resulting array if callback has been omitted, otherwise `undefined`
+       * @inner
+       */
+      function next() {
+        if (progressCallback) progressCallback(i / rounds);
+        if (i < rounds) {
+          var start = Date.now();
+          for (; i < rounds; ) {
+            i = i + 1;
+            _key(b, P, S);
+            _key(salt, P, S);
+            if (Date.now() - start > MAX_EXECUTION_TIME) break;
+          }
+        } else {
+          for (i = 0; i < 64; i++)
+            for (j = 0; j < clen >> 1; j++) _encipher(cdata, j << 1, P, S);
+          var ret = [];
+          for (i = 0; i < clen; i++)
+            ret.push(((cdata[i] >> 24) & 0xff) >>> 0),
+              ret.push(((cdata[i] >> 16) & 0xff) >>> 0),
+              ret.push(((cdata[i] >> 8) & 0xff) >>> 0),
+              ret.push((cdata[i] & 0xff) >>> 0);
+          if (callback) {
+            callback(null, ret);
+            return;
+          } else return ret;
+        }
+        if (callback) nextTick(next);
+      }
+
+      // Async
+      if (typeof callback !== "undefined") {
+        next();
+
+        // Sync
+      } else {
+        var res;
+        while (true)
+          if (typeof (res = next()) !== "undefined") return res || [];
+      }
+    }
+
+    /**
+     * Internally hashes a password.
+     * @param {string} password Password to hash
+     * @param {?string} salt Salt to use, actually never null
+     * @param {function(Error, string=)=} callback Callback receiving the error, if any, and the resulting hash. If omitted,
+     *  hashing is performed synchronously.
+     *  @param {function(number)=} progressCallback Callback called with the current progress
+     * @returns {string|undefined} Resulting hash if callback has been omitted, otherwise `undefined`
+     * @inner
+     */
+    function _hash(password, salt, callback, progressCallback) {
+      var err;
+      if (typeof password !== "string" || typeof salt !== "string") {
+        err = Error("Invalid string / salt: Not a string");
+        if (callback) {
+          nextTick(callback.bind(this, err));
+          return;
+        } else throw err;
+      }
+
+      // Validate the salt
+      var minor, offset;
+      if (salt.charAt(0) !== "$" || salt.charAt(1) !== "2") {
+        err = Error("Invalid salt version: " + salt.substring(0, 2));
+        if (callback) {
+          nextTick(callback.bind(this, err));
+          return;
+        } else throw err;
+      }
+      if (salt.charAt(2) === "$")
+        (minor = String.fromCharCode(0)), (offset = 3);
+      else {
+        minor = salt.charAt(2);
+        if (
+          (minor !== "a" && minor !== "b" && minor !== "y") ||
+          salt.charAt(3) !== "$"
+        ) {
+          err = Error("Invalid salt revision: " + salt.substring(2, 4));
+          if (callback) {
+            nextTick(callback.bind(this, err));
+            return;
+          } else throw err;
+        }
+        offset = 4;
+      }
+
+      // Extract number of rounds
+      if (salt.charAt(offset + 2) > "$") {
+        err = Error("Missing salt rounds");
+        if (callback) {
+          nextTick(callback.bind(this, err));
+          return;
+        } else throw err;
+      }
+      var r1 = parseInt(salt.substring(offset, offset + 1), 10) * 10,
+        r2 = parseInt(salt.substring(offset + 1, offset + 2), 10),
+        rounds = r1 + r2,
+        real_salt = salt.substring(offset + 3, offset + 25);
+      password += minor >= "a" ? "\x00" : "";
+      var passwordb = utf8Array(password),
+        saltb = base64_decode(real_salt, BCRYPT_SALT_LEN);
+
+      /**
+       * Finishes hashing.
+       * @param {Array.<number>} bytes Byte array
+       * @returns {string}
+       * @inner
+       */
+      function finish(bytes) {
+        var res = [];
+        res.push("$2");
+        if (minor >= "a") res.push(minor);
+        res.push("$");
+        if (rounds < 10) res.push("0");
+        res.push(rounds.toString());
+        res.push("$");
+        res.push(base64_encode(saltb, saltb.length));
+        res.push(base64_encode(bytes, C_ORIG.length * 4 - 1));
+        return res.join("");
+      }
+
+      // Sync
+      if (typeof callback == "undefined")
+        return finish(_crypt(passwordb, saltb, rounds));
+      // Async
+      else {
+        _crypt(
+          passwordb,
+          saltb,
+          rounds,
+          function (err, bytes) {
+            if (err) callback(err, null);
+            else callback(null, finish(bytes));
+          },
+          progressCallback,
+        );
+      }
+    }
+
+    /**
+     * Encodes a byte array to base64 with up to len bytes of input, using the custom bcrypt alphabet.
+     * @function
+     * @param {!Array.<number>} bytes Byte array
+     * @param {number} length Maximum input length
+     * @returns {string}
+     */
+    function encodeBase64(bytes, length) {
+      return base64_encode(bytes, length);
+    }
+
+    /**
+     * Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet.
+     * @function
+     * @param {string} string String to decode
+     * @param {number} length Maximum output length
+     * @returns {!Array.<number>}
+     */
+    function decodeBase64(string, length) {
+      return base64_decode(string, length);
+    }
+    var _default = (_exports.default = {
+      setRandomFallback,
+      genSaltSync,
+      genSalt,
+      hashSync,
+      hash,
+      compareSync,
+      compare,
+      getRounds,
+      getSalt,
+      truncates,
+      encodeBase64,
+      decodeBase64,
+    });
+  },
+);

+ 3 - 0
node_modules/bcryptjs/umd/package.json

@@ -0,0 +1,3 @@
+{
+  "type": "commonjs"
+}

+ 157 - 0
node_modules/bcryptjs/umd/types.d.ts

@@ -0,0 +1,157 @@
+// Originally imported from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/8b36dbdf95b624b8a7cd7f8416f06c15d274f9e6/types/bcryptjs/index.d.ts
+// MIT license.
+
+/** Called with an error on failure or a value of type `T` upon success. */
+type Callback<T> = (err: Error | null, result?: T) => void;
+/** Called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms. */
+type ProgressCallback = (percentage: number) => void;
+/** Called to obtain random bytes when both Web Crypto API and Node.js crypto are not available. */
+type RandomFallback = (length: number) => number[];
+
+/**
+ * Sets the pseudo random number generator to use as a fallback if neither node's crypto module nor the Web Crypto API is available.
+ * Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly!
+ * @param  random Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values.
+ */
+export declare function setRandomFallback(random: RandomFallback): void;
+
+/**
+ * Synchronously generates a salt.
+ * @param  rounds Number of rounds to use, defaults to 10 if omitted
+ * @return Resulting salt
+ * @throws If a random fallback is required but not set
+ */
+export declare function genSaltSync(rounds?: number): string;
+
+/**
+ * Asynchronously generates a salt.
+ * @param  rounds  Number of rounds to use, defaults to 10 if omitted
+ * @return Promise with resulting salt, if callback has been omitted
+ */
+export declare function genSalt(rounds?: number): Promise<string>;
+
+/**
+ * Asynchronously generates a salt.
+ * @param callback Callback receiving the error, if any, and the resulting salt
+ */
+export declare function genSalt(callback: Callback<string>): void;
+
+/**
+ * Asynchronously generates a salt.
+ * @param  rounds   Number of rounds to use, defaults to 10 if omitted
+ * @param  callback Callback receiving the error, if any, and the resulting salt
+ */
+export declare function genSalt(
+  rounds: number,
+  callback: Callback<string>,
+): void;
+
+/**
+ * Synchronously generates a hash for the given password.
+ * @param  password Password to hash
+ * @param  salt Salt length to generate or salt to use, default to 10
+ * @return Resulting hash
+ */
+export declare function hashSync(
+  password: string,
+  salt?: number | string,
+): string;
+
+/**
+ * Asynchronously generates a hash for the given password.
+ * @param password Password to hash
+ * @param salt     Salt length to generate or salt to use
+ * @return Promise with resulting hash, if callback has been omitted
+ */
+export declare function hash(
+  password: string,
+  salt: number | string,
+): Promise<string>;
+
+/**
+ * Asynchronously generates a hash for the given password.
+ * @param password         Password to hash
+ * @param salt             Salt length to generate or salt to use
+ * @param callback         Callback receiving the error, if any, and the resulting hash
+ * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms.
+ */
+export declare function hash(
+  password: string,
+  salt: number | string,
+  callback?: Callback<string>,
+  progressCallback?: ProgressCallback,
+): void;
+
+/**
+ * Synchronously tests a password against a hash.
+ * @param  password Password to test
+ * @param  hash     Hash to test against
+ * @return true if matching, otherwise false
+ */
+export declare function compareSync(password: string, hash: string): boolean;
+
+/**
+ * Asynchronously tests a password against a hash.
+ * @param  password Password to test
+ * @param  hash     Hash to test against
+ * @return Promise, if callback has been omitted
+ */
+export declare function compare(
+  password: string,
+  hash: string,
+): Promise<boolean>;
+
+/**
+ * Asynchronously tests a password against a hash.
+ * @param  password         Password to test
+ * @param  hash             Hash to test against
+ * @param  callback         Callback receiving the error, if any, otherwise the result
+ * @param  progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms.
+ */
+export declare function compare(
+  password: string,
+  hash: string,
+  callback?: Callback<boolean>,
+  progressCallback?: ProgressCallback,
+): void;
+
+/**
+ * Gets the number of rounds used to encrypt the specified hash.
+ * @param  hash Hash to extract the used number of rounds from
+ * @return Number of rounds used
+ */
+export declare function getRounds(hash: string): number;
+
+/**
+ * Gets the salt portion from a hash. Does not validate the hash.
+ * @param  hash Hash to extract the salt from
+ * @return Extracted salt part
+ */
+export declare function getSalt(hash: string): string;
+
+/**
+ * Tests if a password will be truncated when hashed, that is its length is
+ * greater than 72 bytes when converted to UTF-8.
+ * @param password The password to test
+ * @returns `true` if truncated, otherwise `false`
+ */
+export declare function truncates(password: string): boolean;
+
+/**
+ * Encodes a byte array to base64 with up to len bytes of input, using the custom bcrypt alphabet.
+ * @function
+ * @param b Byte array
+ * @param len Maximum input length
+ */
+export declare function encodeBase64(
+  b: Readonly<ArrayLike<number>>,
+  len: number,
+): string;
+
+/**
+ * Decodes a base64 encoded string to up to len bytes of output, using the custom bcrypt alphabet.
+ * @function
+ * @param s String to decode
+ * @param len Maximum output length
+ */
+export declare function decodeBase64(s: string, len: number): number[];

+ 23 - 0
node_modules/body-parser/LICENSE

@@ -0,0 +1,23 @@
+(The MIT License)
+
+Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
+Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.com>
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 494 - 0
node_modules/body-parser/README.md

@@ -0,0 +1,494 @@
+# body-parser
+
+[![NPM Version][npm-version-image]][npm-url]
+[![NPM Downloads][npm-downloads-image]][npm-url]
+[![Build Status][ci-image]][ci-url]
+[![Test Coverage][coveralls-image]][coveralls-url]
+[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
+
+Node.js body parsing middleware.
+
+Parse incoming request bodies in a middleware before your handlers, available
+under the `req.body` property.
+
+**Note** As `req.body`'s shape is based on user-controlled input, all
+properties and values in this object are untrusted and should be validated
+before trusting. For example, `req.body.foo.toString()` may fail in multiple
+ways, for example the `foo` property may not be there or may not be a string,
+and `toString` may not be a function and instead a string or other user input.
+
+[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).
+
+_This does not handle multipart bodies_, due to their complex and typically
+large nature. For multipart bodies, you may be interested in the following
+modules:
+
+  * [busboy](https://www.npmjs.org/package/busboy#readme) and
+    [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)
+  * [multiparty](https://www.npmjs.org/package/multiparty#readme) and
+    [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme)
+  * [formidable](https://www.npmjs.org/package/formidable#readme)
+  * [multer](https://www.npmjs.org/package/multer#readme)
+
+This module provides the following parsers:
+
+  * [JSON body parser](#bodyparserjsonoptions)
+  * [Raw body parser](#bodyparserrawoptions)
+  * [Text body parser](#bodyparsertextoptions)
+  * [URL-encoded form body parser](#bodyparserurlencodedoptions)
+
+Other body parsers you might be interested in:
+
+- [body](https://www.npmjs.org/package/body#readme)
+- [co-body](https://www.npmjs.org/package/co-body#readme)
+
+## Installation
+
+```sh
+$ npm install body-parser
+```
+
+## API
+
+```js
+const bodyParser = require('body-parser')
+```
+
+The `bodyParser` object exposes various factories to create middlewares. All
+middlewares will populate the `req.body` property with the parsed body when
+the `Content-Type` request header matches the `type` option.
+
+The various errors returned by this module are described in the
+[errors section](#errors).
+
+### bodyParser.json([options])
+
+Returns middleware that only parses `json` and only looks at requests where
+the `Content-Type` header matches the `type` option. This parser accepts any
+Unicode encoding of the body and supports automatic inflation of `gzip`,
+`br` (brotli) and `deflate` encodings.
+
+A new `body` object containing the parsed data is populated on the `request`
+object after the middleware (i.e. `req.body`).
+
+#### Options
+
+The `json` function takes an optional `options` object that may contain any of
+the following keys:
+
+##### defaultCharset
+
+Specify the default character set for the json content if the charset is not
+specified in the `Content-Type` header of the request. Defaults to `utf-8`.
+
+##### inflate
+
+When set to `true`, then deflated (compressed) bodies will be inflated; when
+`false`, deflated bodies are rejected. Defaults to `true`.
+
+##### limit
+
+Controls the maximum request body size. If this is a number, then the value
+specifies the number of bytes; if it is a string, the value is passed to the
+[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
+to `'100kb'`.
+
+##### reviver
+
+The `reviver` option is passed directly to `JSON.parse` as the second
+argument. You can find more information on this argument
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+
+##### strict
+
+When set to `true`, will only accept arrays and objects; when `false` will
+accept anything `JSON.parse` accepts. Defaults to `true`.
+
+##### type
+
+The `type` option is used to determine what media type the middleware will
+parse. This option can be a string, array of strings, or a function. If not a
+function, `type` option is passed directly to the
+[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
+be an extension name (like `json`), a mime type (like `application/json`), or
+a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`
+option is called as `fn(req)` and the request is parsed if it returns a truthy
+value. Defaults to `application/json`.
+
+##### verify
+
+The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
+where `buf` is a `Buffer` of the raw request body and `encoding` is the
+encoding of the request. The parsing can be aborted by throwing an error.
+
+### bodyParser.raw([options])
+
+Returns middleware that parses all bodies as a `Buffer` and only looks at
+requests where the `Content-Type` header matches the `type` option. This
+parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate`
+encodings.
+
+A new `body` object containing the parsed data is populated on the `request`
+object after the middleware (i.e. `req.body`). This will be a `Buffer` object
+of the body.
+
+#### Options
+
+The `raw` function takes an optional `options` object that may contain any of
+the following keys:
+
+##### inflate
+
+When set to `true`, then deflated (compressed) bodies will be inflated; when
+`false`, deflated bodies are rejected. Defaults to `true`.
+
+##### limit
+
+Controls the maximum request body size. If this is a number, then the value
+specifies the number of bytes; if it is a string, the value is passed to the
+[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
+to `'100kb'`.
+
+##### type
+
+The `type` option is used to determine what media type the middleware will
+parse. This option can be a string, array of strings, or a function.
+If not a function, `type` option is passed directly to the
+[type-is](https://www.npmjs.org/package/type-is#readme) library and this
+can be an extension name (like `bin`), a mime type (like
+`application/octet-stream`), or a mime type with a wildcard (like `*/*` or
+`application/*`). If a function, the `type` option is called as `fn(req)`
+and the request is parsed if it returns a truthy value. Defaults to
+`application/octet-stream`.
+
+##### verify
+
+The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
+where `buf` is a `Buffer` of the raw request body and `encoding` is the
+encoding of the request. The parsing can be aborted by throwing an error.
+
+### bodyParser.text([options])
+
+Returns middleware that parses all bodies as a string and only looks at
+requests where the `Content-Type` header matches the `type` option. This
+parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate`
+encodings.
+
+A new `body` string containing the parsed data is populated on the `request`
+object after the middleware (i.e. `req.body`). This will be a string of the
+body.
+
+#### Options
+
+The `text` function takes an optional `options` object that may contain any of
+the following keys:
+
+##### defaultCharset
+
+Specify the default character set for the text content if the charset is not
+specified in the `Content-Type` header of the request. Defaults to `utf-8`.
+
+##### inflate
+
+When set to `true`, then deflated (compressed) bodies will be inflated; when
+`false`, deflated bodies are rejected. Defaults to `true`.
+
+##### limit
+
+Controls the maximum request body size. If this is a number, then the value
+specifies the number of bytes; if it is a string, the value is passed to the
+[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
+to `'100kb'`.
+
+##### type
+
+The `type` option is used to determine what media type the middleware will
+parse. This option can be a string, array of strings, or a function. If not
+a function, `type` option is passed directly to the
+[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
+be an extension name (like `txt`), a mime type (like `text/plain`), or a mime
+type with a wildcard (like `*/*` or `text/*`). If a function, the `type`
+option is called as `fn(req)` and the request is parsed if it returns a
+truthy value. Defaults to `text/plain`.
+
+##### verify
+
+The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
+where `buf` is a `Buffer` of the raw request body and `encoding` is the
+encoding of the request. The parsing can be aborted by throwing an error.
+
+### bodyParser.urlencoded([options])
+
+Returns middleware that only parses `urlencoded` bodies and only looks at
+requests where the `Content-Type` header matches the `type` option. This
+parser accepts only UTF-8 encoding of the body and supports automatic
+inflation of `gzip`, `br` (brotli) and `deflate` encodings.
+
+A new `body` object containing the parsed data is populated on the `request`
+object after the middleware (i.e. `req.body`). This object will contain
+key-value pairs, where the value can be a string or array (when `extended` is
+`false`), or any type (when `extended` is `true`).
+
+#### Options
+
+The `urlencoded` function takes an optional `options` object that may contain
+any of the following keys:
+
+##### extended
+
+The "extended" syntax allows for rich objects and arrays to be encoded into the
+URL-encoded format, allowing for a JSON-like experience with URL-encoded. For
+more information, please [see the qs
+library](https://www.npmjs.org/package/qs#readme).
+
+Defaults to `false`.
+
+##### inflate
+
+When set to `true`, then deflated (compressed) bodies will be inflated; when
+`false`, deflated bodies are rejected. Defaults to `true`.
+
+##### limit
+
+Controls the maximum request body size. If this is a number, then the value
+specifies the number of bytes; if it is a string, the value is passed to the
+[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
+to `'100kb'`.
+
+##### parameterLimit
+
+The `parameterLimit` option controls the maximum number of parameters that
+are allowed in the URL-encoded data. If a request contains more parameters
+than this value, a 413 will be returned to the client. Defaults to `1000`.
+
+##### type
+
+The `type` option is used to determine what media type the middleware will
+parse. This option can be a string, array of strings, or a function. If not
+a function, `type` option is passed directly to the
+[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
+be an extension name (like `urlencoded`), a mime type (like
+`application/x-www-form-urlencoded`), or a mime type with a wildcard (like
+`*/x-www-form-urlencoded`). If a function, the `type` option is called as
+`fn(req)` and the request is parsed if it returns a truthy value. Defaults
+to `application/x-www-form-urlencoded`.
+
+##### verify
+
+The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
+where `buf` is a `Buffer` of the raw request body and `encoding` is the
+encoding of the request. The parsing can be aborted by throwing an error.
+
+##### defaultCharset
+
+The default charset to parse as, if not specified in content-type. Must be
+either `utf-8` or `iso-8859-1`. Defaults to `utf-8`.
+
+##### charsetSentinel
+
+Whether to let the value of the `utf8` parameter take precedence as the charset
+selector. It requires the form to contain a parameter named `utf8` with a value
+of `✓`. Defaults to `false`.
+
+##### interpretNumericEntities
+
+Whether to decode numeric entities such as `&#9786;` when parsing an iso-8859-1
+form. Defaults to `false`.
+
+
+##### depth
+
+The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible.
+
+## Errors
+
+The middlewares provided by this module create errors using the
+[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors
+will typically have a `status`/`statusCode` property that contains the suggested
+HTTP response code, an `expose` property to determine if the `message` property
+should be displayed to the client, a `type` property to determine the type of
+error without matching against the `message`, and a `body` property containing
+the read body, if available.
+
+The following are the common errors created, though any error can come through
+for various reasons.
+
+### content encoding unsupported
+
+This error will occur when the request had a `Content-Encoding` header that
+contained an encoding but the "inflation" option was set to `false`. The
+`status` property is set to `415`, the `type` property is set to
+`'encoding.unsupported'`, and the `charset` property will be set to the
+encoding that is unsupported.
+
+### entity parse failed
+
+This error will occur when the request contained an entity that could not be
+parsed by the middleware. The `status` property is set to `400`, the `type`
+property is set to `'entity.parse.failed'`, and the `body` property is set to
+the entity value that failed parsing.
+
+### entity verify failed
+
+This error will occur when the request contained an entity that could not be
+failed verification by the defined `verify` option. The `status` property is
+set to `403`, the `type` property is set to `'entity.verify.failed'`, and the
+`body` property is set to the entity value that failed verification.
+
+### request aborted
+
+This error will occur when the request is aborted by the client before reading
+the body has finished. The `received` property will be set to the number of
+bytes received before the request was aborted and the `expected` property is
+set to the number of expected bytes. The `status` property is set to `400`
+and `type` property is set to `'request.aborted'`.
+
+### request entity too large
+
+This error will occur when the request body's size is larger than the "limit"
+option. The `limit` property will be set to the byte limit and the `length`
+property will be set to the request body's length. The `status` property is
+set to `413` and the `type` property is set to `'entity.too.large'`.
+
+### request size did not match content length
+
+This error will occur when the request's length did not match the length from
+the `Content-Length` header. This typically occurs when the request is malformed,
+typically when the `Content-Length` header was calculated based on characters
+instead of bytes. The `status` property is set to `400` and the `type` property
+is set to `'request.size.invalid'`.
+
+### stream encoding should not be set
+
+This error will occur when something called the `req.setEncoding` method prior
+to this middleware. This module operates directly on bytes only and you cannot
+call `req.setEncoding` when using this module. The `status` property is set to
+`500` and the `type` property is set to `'stream.encoding.set'`.
+
+### stream is not readable
+
+This error will occur when the request is no longer readable when this middleware
+attempts to read it. This typically means something other than a middleware from
+this module read the request body already and the middleware was also configured to
+read the same request. The `status` property is set to `500` and the `type`
+property is set to `'stream.not.readable'`.
+
+### too many parameters
+
+This error will occur when the content of the request exceeds the configured
+`parameterLimit` for the `urlencoded` parser. The `status` property is set to
+`413` and the `type` property is set to `'parameters.too.many'`.
+
+### unsupported charset "BOGUS"
+
+This error will occur when the request had a charset parameter in the
+`Content-Type` header, but the `iconv-lite` module does not support it OR the
+parser does not support it. The charset is contained in the message as well
+as in the `charset` property. The `status` property is set to `415`, the
+`type` property is set to `'charset.unsupported'`, and the `charset` property
+is set to the charset that is unsupported.
+
+### unsupported content encoding "bogus"
+
+This error will occur when the request had a `Content-Encoding` header that
+contained an unsupported encoding. The encoding is contained in the message
+as well as in the `encoding` property. The `status` property is set to `415`,
+the `type` property is set to `'encoding.unsupported'`, and the `encoding`
+property is set to the encoding that is unsupported.
+
+### The input exceeded the depth
+
+This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown.
+
+## Examples
+
+### Express/Connect top-level generic
+
+This example demonstrates adding a generic JSON and URL-encoded parser as a
+top-level middleware, which will parse the bodies of all incoming requests.
+This is the simplest setup.
+
+```js
+const express = require('express')
+const bodyParser = require('body-parser')
+
+const app = express()
+
+// parse application/x-www-form-urlencoded
+app.use(bodyParser.urlencoded())
+
+// parse application/json
+app.use(bodyParser.json())
+
+app.use(function (req, res) {
+  res.setHeader('Content-Type', 'text/plain')
+  res.write('you posted:\n')
+  res.end(String(JSON.stringify(req.body, null, 2)))
+})
+```
+
+### Express route-specific
+
+This example demonstrates adding body parsers specifically to the routes that
+need them. In general, this is the most recommended way to use body-parser with
+Express.
+
+```js
+const express = require('express')
+const bodyParser = require('body-parser')
+
+const app = express()
+
+// create application/json parser
+const jsonParser = bodyParser.json()
+
+// create application/x-www-form-urlencoded parser
+const urlencodedParser = bodyParser.urlencoded()
+
+// POST /login gets urlencoded bodies
+app.post('/login', urlencodedParser, function (req, res) {
+  if (!req.body || !req.body.username) res.sendStatus(400)
+  res.send('welcome, ' + req.body.username)
+})
+
+// POST /api/users gets JSON bodies
+app.post('/api/users', jsonParser, function (req, res) {
+  if (!req.body) res.sendStatus(400)
+  // create user in req.body
+})
+```
+
+### Change accepted type for parsers
+
+All the parsers accept a `type` option which allows you to change the
+`Content-Type` that the middleware will parse.
+
+```js
+const express = require('express')
+const bodyParser = require('body-parser')
+
+const app = express()
+
+// parse various different custom JSON types as JSON
+app.use(bodyParser.json({ type: 'application/*+json' }))
+
+// parse some custom thing into a Buffer
+app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
+
+// parse an HTML body into a string
+app.use(bodyParser.text({ type: 'text/html' }))
+```
+
+## License
+
+[MIT](LICENSE)
+
+[ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/body-parser/ci.yml?branch=master&label=ci
+[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
+[coveralls-image]: https://img.shields.io/coverallsCoverage/github/expressjs/body-parser?branch=master
+[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
+[npm-downloads-image]: https://img.shields.io/npm/dm/body-parser
+[npm-url]: https://npmjs.org/package/body-parser
+[npm-version-image]: https://img.shields.io/npm/v/body-parser
+[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge
+[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser

+ 80 - 0
node_modules/body-parser/index.js

@@ -0,0 +1,80 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * @typedef Parsers
+ * @type {function}
+ * @property {function} json
+ * @property {function} raw
+ * @property {function} text
+ * @property {function} urlencoded
+ */
+
+/**
+ * Module exports.
+ * @type {Parsers}
+ */
+
+exports = module.exports = bodyParser
+
+/**
+ * JSON parser.
+ * @public
+ */
+
+Object.defineProperty(exports, 'json', {
+  configurable: true,
+  enumerable: true,
+  get: () => require('./lib/types/json')
+})
+
+/**
+ * Raw parser.
+ * @public
+ */
+
+Object.defineProperty(exports, 'raw', {
+  configurable: true,
+  enumerable: true,
+  get: () => require('./lib/types/raw')
+})
+
+/**
+ * Text parser.
+ * @public
+ */
+
+Object.defineProperty(exports, 'text', {
+  configurable: true,
+  enumerable: true,
+  get: () => require('./lib/types/text')
+})
+
+/**
+ * URL-encoded parser.
+ * @public
+ */
+
+Object.defineProperty(exports, 'urlencoded', {
+  configurable: true,
+  enumerable: true,
+  get: () => require('./lib/types/urlencoded')
+})
+
+/**
+ * Create a middleware to parse json and urlencoded bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @deprecated
+ * @public
+ */
+
+function bodyParser () {
+  throw new Error('The bodyParser() generic has been split into individual middleware to use instead.')
+}

+ 250 - 0
node_modules/body-parser/lib/read.js

@@ -0,0 +1,250 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var createError = require('http-errors')
+var getBody = require('raw-body')
+var iconv = require('iconv-lite')
+var onFinished = require('on-finished')
+var zlib = require('node:zlib')
+var hasBody = require('type-is').hasBody
+var { getCharset } = require('./utils')
+
+/**
+ * Module exports.
+ */
+
+module.exports = read
+
+/**
+ * Read a request into a buffer and parse.
+ *
+ * @param {object} req
+ * @param {object} res
+ * @param {function} next
+ * @param {function} parse
+ * @param {function} debug
+ * @param {object} options
+ * @private
+ */
+
+function read (req, res, next, parse, debug, options) {
+  if (onFinished.isFinished(req)) {
+    debug('body already parsed')
+    next()
+    return
+  }
+
+  if (!('body' in req)) {
+    req.body = undefined
+  }
+
+  // skip requests without bodies
+  if (!hasBody(req)) {
+    debug('skip empty body')
+    next()
+    return
+  }
+
+  debug('content-type %j', req.headers['content-type'])
+
+  // determine if request should be parsed
+  if (!options.shouldParse(req)) {
+    debug('skip parsing')
+    next()
+    return
+  }
+
+  var encoding = null
+  if (options?.skipCharset !== true) {
+    encoding = getCharset(req) || options.defaultCharset
+
+    // validate charset
+    if (!!options?.isValidCharset && !options.isValidCharset(encoding)) {
+      debug('invalid charset')
+      next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
+        charset: encoding,
+        type: 'charset.unsupported'
+      }))
+      return
+    }
+  }
+
+  var length
+  var opts = options
+  var stream
+
+  // read options
+  var verify = opts.verify
+
+  try {
+    // get the content stream
+    stream = contentstream(req, debug, opts.inflate)
+    length = stream.length
+    stream.length = undefined
+  } catch (err) {
+    return next(err)
+  }
+
+  // set raw-body options
+  opts.length = length
+  opts.encoding = verify
+    ? null
+    : encoding
+
+  // assert charset is supported
+  if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
+    return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
+      charset: encoding.toLowerCase(),
+      type: 'charset.unsupported'
+    }))
+  }
+
+  // read body
+  debug('read body')
+  getBody(stream, opts, function (error, body) {
+    if (error) {
+      var _error
+
+      if (error.type === 'encoding.unsupported') {
+        // echo back charset
+        _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
+          charset: encoding.toLowerCase(),
+          type: 'charset.unsupported'
+        })
+      } else {
+        // set status code on error
+        _error = createError(400, error)
+      }
+
+      // unpipe from stream and destroy
+      if (stream !== req) {
+        req.unpipe()
+        stream.destroy()
+      }
+
+      // read off entire request
+      dump(req, function onfinished () {
+        next(createError(400, _error))
+      })
+      return
+    }
+
+    // verify
+    if (verify) {
+      try {
+        debug('verify body')
+        verify(req, res, body, encoding)
+      } catch (err) {
+        next(createError(403, err, {
+          body: body,
+          type: err.type || 'entity.verify.failed'
+        }))
+        return
+      }
+    }
+
+    // parse
+    var str = body
+    try {
+      debug('parse body')
+      str = typeof body !== 'string' && encoding !== null
+        ? iconv.decode(body, encoding)
+        : body
+      req.body = parse(str, encoding)
+    } catch (err) {
+      next(createError(400, err, {
+        body: str,
+        type: err.type || 'entity.parse.failed'
+      }))
+      return
+    }
+
+    next()
+  })
+}
+
+/**
+ * Get the content stream of the request.
+ *
+ * @param {object} req
+ * @param {function} debug
+ * @param {boolean} [inflate=true]
+ * @return {object}
+ * @api private
+ */
+
+function contentstream (req, debug, inflate) {
+  var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
+  var length = req.headers['content-length']
+
+  debug('content-encoding "%s"', encoding)
+
+  if (inflate === false && encoding !== 'identity') {
+    throw createError(415, 'content encoding unsupported', {
+      encoding: encoding,
+      type: 'encoding.unsupported'
+    })
+  }
+
+  if (encoding === 'identity') {
+    req.length = length
+    return req
+  }
+
+  var stream = createDecompressionStream(encoding, debug)
+  req.pipe(stream)
+  return stream
+}
+
+/**
+ * Create a decompression stream for the given encoding.
+ * @param {string} encoding
+ * @param {function} debug
+ * @return {object}
+ * @api private
+ */
+function createDecompressionStream (encoding, debug) {
+  switch (encoding) {
+    case 'deflate':
+      debug('inflate body')
+      return zlib.createInflate()
+    case 'gzip':
+      debug('gunzip body')
+      return zlib.createGunzip()
+    case 'br':
+      debug('brotli decompress body')
+      return zlib.createBrotliDecompress()
+    default:
+      throw createError(415, 'unsupported content encoding "' + encoding + '"', {
+        encoding: encoding,
+        type: 'encoding.unsupported'
+      })
+  }
+}
+
+/**
+ * Dump the contents of a request.
+ *
+ * @param {object} req
+ * @param {function} callback
+ * @api private
+ */
+
+function dump (req, callback) {
+  if (onFinished.isFinished(req)) {
+    callback(null)
+  } else {
+    onFinished(req, callback)
+    req.resume()
+  }
+}

+ 166 - 0
node_modules/body-parser/lib/types/json.js

@@ -0,0 +1,166 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var debug = require('debug')('body-parser:json')
+var read = require('../read')
+var { normalizeOptions } = require('../utils')
+
+/**
+ * Module exports.
+ */
+
+module.exports = json
+
+/**
+ * RegExp to match the first non-space in a string.
+ *
+ * Allowed whitespace is defined in RFC 7159:
+ *
+ *    ws = *(
+ *            %x20 /              ; Space
+ *            %x09 /              ; Horizontal tab
+ *            %x0A /              ; Line feed or New line
+ *            %x0D )              ; Carriage return
+ */
+
+var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex
+
+var JSON_SYNTAX_CHAR = '#'
+var JSON_SYNTAX_REGEXP = /#+/g
+
+/**
+ * Create a middleware to parse JSON bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @public
+ */
+
+function json (options) {
+  const normalizedOptions = normalizeOptions(options, 'application/json')
+
+  var reviver = options?.reviver
+  var strict = options?.strict !== false
+
+  function parse (body) {
+    if (body.length === 0) {
+      // special-case empty json body, as it's a common client-side mistake
+      // TODO: maybe make this configurable or part of "strict" option
+      return {}
+    }
+
+    if (strict) {
+      var first = firstchar(body)
+
+      if (first !== '{' && first !== '[') {
+        debug('strict violation')
+        throw createStrictSyntaxError(body, first)
+      }
+    }
+
+    try {
+      debug('parse json')
+      return JSON.parse(body, reviver)
+    } catch (e) {
+      throw normalizeJsonSyntaxError(e, {
+        message: e.message,
+        stack: e.stack
+      })
+    }
+  }
+
+  const readOptions = {
+    ...normalizedOptions,
+    // assert charset per RFC 7159 sec 8.1
+    isValidCharset: (charset) => charset.slice(0, 4) === 'utf-'
+  }
+
+  return function jsonParser (req, res, next) {
+    read(req, res, next, parse, debug, readOptions)
+  }
+}
+
+/**
+ * Create strict violation syntax error matching native error.
+ *
+ * @param {string} str
+ * @param {string} char
+ * @return {Error}
+ * @private
+ */
+
+function createStrictSyntaxError (str, char) {
+  var index = str.indexOf(char)
+  var partial = ''
+
+  if (index !== -1) {
+    partial = str.substring(0, index) + JSON_SYNTAX_CHAR
+
+    for (var i = index + 1; i < str.length; i++) {
+      partial += JSON_SYNTAX_CHAR
+    }
+  }
+
+  try {
+    JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
+  } catch (e) {
+    return normalizeJsonSyntaxError(e, {
+      message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) {
+        return str.substring(index, index + placeholder.length)
+      }),
+      stack: e.stack
+    })
+  }
+}
+
+/**
+ * Get the first non-whitespace character in a string.
+ *
+ * @param {string} str
+ * @return {function}
+ * @private
+ */
+
+function firstchar (str) {
+  var match = FIRST_CHAR_REGEXP.exec(str)
+
+  return match
+    ? match[1]
+    : undefined
+}
+
+/**
+ * Normalize a SyntaxError for JSON.parse.
+ *
+ * @param {SyntaxError} error
+ * @param {object} obj
+ * @return {SyntaxError}
+ */
+
+function normalizeJsonSyntaxError (error, obj) {
+  var keys = Object.getOwnPropertyNames(error)
+
+  for (var i = 0; i < keys.length; i++) {
+    var key = keys[i]
+    if (key !== 'stack' && key !== 'message') {
+      delete error[key]
+    }
+  }
+
+  // replace stack before message for Node.js 0.10 and below
+  error.stack = obj.stack.replace(error.message, obj.message)
+  error.message = obj.message
+
+  return error
+}

+ 43 - 0
node_modules/body-parser/lib/types/raw.js

@@ -0,0 +1,43 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ */
+
+var debug = require('debug')('body-parser:raw')
+var read = require('../read')
+var { normalizeOptions, passthrough } = require('../utils')
+
+/**
+ * Module exports.
+ */
+
+module.exports = raw
+
+/**
+ * Create a middleware to parse raw bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @api public
+ */
+
+function raw (options) {
+  const normalizedOptions = normalizeOptions(options, 'application/octet-stream')
+
+  const readOptions = {
+    ...normalizedOptions,
+    // Skip charset validation and parse the body as is
+    skipCharset: true
+  }
+
+  return function rawParser (req, res, next) {
+    read(req, res, next, passthrough, debug, readOptions)
+  }
+}

+ 37 - 0
node_modules/body-parser/lib/types/text.js

@@ -0,0 +1,37 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ */
+
+var debug = require('debug')('body-parser:text')
+var read = require('../read')
+var { normalizeOptions, passthrough } = require('../utils')
+
+/**
+ * Module exports.
+ */
+
+module.exports = text
+
+/**
+ * Create a middleware to parse text bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @api public
+ */
+
+function text (options) {
+  const normalizedOptions = normalizeOptions(options, 'text/plain')
+
+  return function textParser (req, res, next) {
+    read(req, res, next, passthrough, debug, normalizedOptions)
+  }
+}

+ 142 - 0
node_modules/body-parser/lib/types/urlencoded.js

@@ -0,0 +1,142 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var createError = require('http-errors')
+var debug = require('debug')('body-parser:urlencoded')
+var read = require('../read')
+var qs = require('qs')
+var { normalizeOptions } = require('../utils')
+
+/**
+ * Module exports.
+ */
+
+module.exports = urlencoded
+
+/**
+ * Create a middleware to parse urlencoded bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @public
+ */
+
+function urlencoded (options) {
+  const normalizedOptions = normalizeOptions(options, 'application/x-www-form-urlencoded')
+
+  if (normalizedOptions.defaultCharset !== 'utf-8' && normalizedOptions.defaultCharset !== 'iso-8859-1') {
+    throw new TypeError('option defaultCharset must be either utf-8 or iso-8859-1')
+  }
+
+  // create the appropriate query parser
+  var queryparse = createQueryParser(options)
+
+  function parse (body, encoding) {
+    return body.length
+      ? queryparse(body, encoding)
+      : {}
+  }
+
+  const readOptions = {
+    ...normalizedOptions,
+    // assert charset
+    isValidCharset: (charset) => charset === 'utf-8' || charset === 'iso-8859-1'
+  }
+
+  return function urlencodedParser (req, res, next) {
+    read(req, res, next, parse, debug, readOptions)
+  }
+}
+
+/**
+ * Get the extended query parser.
+ *
+ * @param {object} options
+ */
+
+function createQueryParser (options) {
+  var extended = Boolean(options?.extended)
+  var parameterLimit = options?.parameterLimit !== undefined
+    ? options?.parameterLimit
+    : 1000
+  var charsetSentinel = options?.charsetSentinel
+  var interpretNumericEntities = options?.interpretNumericEntities
+  var depth = extended ? (options?.depth !== undefined ? options?.depth : 32) : 0
+
+  if (isNaN(parameterLimit) || parameterLimit < 1) {
+    throw new TypeError('option parameterLimit must be a positive number')
+  }
+
+  if (isNaN(depth) || depth < 0) {
+    throw new TypeError('option depth must be a zero or a positive number')
+  }
+
+  if (isFinite(parameterLimit)) {
+    parameterLimit = parameterLimit | 0
+  }
+
+  return function queryparse (body, encoding) {
+    var paramCount = parameterCount(body, parameterLimit)
+
+    if (paramCount === undefined) {
+      debug('too many parameters')
+      throw createError(413, 'too many parameters', {
+        type: 'parameters.too.many'
+      })
+    }
+
+    var arrayLimit = extended ? Math.max(100, paramCount) : 0
+
+    debug('parse ' + (extended ? 'extended ' : '') + 'urlencoding')
+    try {
+      return qs.parse(body, {
+        allowPrototypes: true,
+        arrayLimit: arrayLimit,
+        depth: depth,
+        charsetSentinel: charsetSentinel,
+        interpretNumericEntities: interpretNumericEntities,
+        charset: encoding,
+        parameterLimit: parameterLimit,
+        strictDepth: true
+      })
+    } catch (err) {
+      if (err instanceof RangeError) {
+        throw createError(400, 'The input exceeded the depth', {
+          type: 'querystring.parse.rangeError'
+        })
+      } else {
+        throw err
+      }
+    }
+  }
+}
+
+/**
+ * Count the number of parameters, stopping once limit reached
+ *
+ * @param {string} body
+ * @param {number} limit
+ * @return {number|undefined} Returns undefined if limit exceeded
+ * @api private
+ */
+function parameterCount (body, limit) {
+  let count = 0
+  let index = -1
+  do {
+    count++
+    if (count > limit) return undefined // Early exit if limit exceeded
+    index = body.indexOf('&', index + 1)
+  } while (index !== -1)
+  return count
+}

+ 96 - 0
node_modules/body-parser/lib/utils.js

@@ -0,0 +1,96 @@
+'use strict'
+
+/**
+ * Module dependencies.
+ */
+
+var bytes = require('bytes')
+var contentType = require('content-type')
+var typeis = require('type-is')
+
+/**
+ * Module exports.
+ */
+module.exports = {
+  getCharset,
+  normalizeOptions,
+  passthrough
+}
+
+/**
+ * Get the charset of a request.
+ *
+ * @param {object} req
+ * @api private
+ */
+
+function getCharset (req) {
+  try {
+    return (contentType.parse(req).parameters.charset || '').toLowerCase()
+  } catch {
+    return undefined
+  }
+}
+
+/**
+ * Get the simple type checker.
+ *
+ * @param {string | string[]} type
+ * @return {function}
+ */
+
+function typeChecker (type) {
+  return function checkType (req) {
+    return Boolean(typeis(req, type))
+  }
+}
+
+/**
+ * Normalizes the common options for all parsers.
+ *
+ * @param {object} options options to normalize
+ * @param {string | string[] | function} defaultType default content type(s) or a function to determine it
+ * @returns {object}
+ */
+function normalizeOptions (options, defaultType) {
+  if (!defaultType) {
+    // Parsers must define a default content type
+    throw new TypeError('defaultType must be provided')
+  }
+
+  var inflate = options?.inflate !== false
+  var limit = typeof options?.limit !== 'number'
+    ? bytes.parse(options?.limit || '100kb')
+    : options?.limit
+  var type = options?.type || defaultType
+  var verify = options?.verify || false
+  var defaultCharset = options?.defaultCharset || 'utf-8'
+
+  if (verify !== false && typeof verify !== 'function') {
+    throw new TypeError('option verify must be function')
+  }
+
+  // create the appropriate type checking function
+  var shouldParse = typeof type !== 'function'
+    ? typeChecker(type)
+    : type
+
+  return {
+    inflate,
+    limit,
+    verify,
+    defaultCharset,
+    shouldParse
+  }
+}
+
+/**
+ * Passthrough function that returns input unchanged.
+ * Used by parsers that don't need to transform the data.
+ *
+ * @param {*} value
+ * @return {*}
+ */
+function passthrough (value) {
+  return value
+}

+ 52 - 0
node_modules/body-parser/package.json

@@ -0,0 +1,52 @@
+{
+  "name": "body-parser",
+  "description": "Node.js body parsing middleware",
+  "version": "2.2.1",
+  "contributors": [
+    "Douglas Christopher Wilson <doug@somethingdoug.com>",
+    "Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
+  ],
+  "license": "MIT",
+  "repository": "expressjs/body-parser",
+  "funding": {
+    "type": "opencollective",
+    "url": "https://opencollective.com/express"
+  },
+  "dependencies": {
+    "bytes": "^3.1.2",
+    "content-type": "^1.0.5",
+    "debug": "^4.4.3",
+    "http-errors": "^2.0.0",
+    "iconv-lite": "^0.7.0",
+    "on-finished": "^2.4.1",
+    "qs": "^6.14.0",
+    "raw-body": "^3.0.1",
+    "type-is": "^2.0.1"
+  },
+  "devDependencies": {
+    "eslint": "^8.57.1",
+    "eslint-config-standard": "^14.1.1",
+    "eslint-plugin-import": "^2.31.0",
+    "eslint-plugin-markdown": "^3.0.1",
+    "eslint-plugin-node": "^11.1.0",
+    "eslint-plugin-promise": "^6.6.0",
+    "eslint-plugin-standard": "^4.1.0",
+    "mocha": "^11.1.0",
+    "nyc": "^17.1.0",
+    "supertest": "^7.0.0"
+  },
+  "files": [
+    "lib/",
+    "LICENSE",
+    "index.js"
+  ],
+  "engines": {
+    "node": ">=18"
+  },
+  "scripts": {
+    "lint": "eslint .",
+    "test": "mocha --reporter spec --check-leaks test/",
+    "test-ci": "nyc --reporter=lcovonly --reporter=text npm test",
+    "test-cov": "nyc --reporter=html --reporter=text npm test"
+  }
+}

+ 201 - 0
node_modules/bson/LICENSE.md

@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 291 - 0
node_modules/bson/README.md

@@ -0,0 +1,291 @@
+# 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).
+
+### Table of Contents
+
+- [Usage](#usage)
+- [Bugs/Feature Requests](#bugs--feature-requests)
+- [Installation](#installation)
+- [Documentation](#documentation)
+- [FAQ](#faq)
+
+
+### Release Integrity
+
+Releases 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:
+
+```shell
+gpg --import node-driver.asc
+```
+
+The GitHub release contains a detached signature file for the NPM package (named
+`bson-X.Y.Z.tgz.sig`).
+
+The following command returns the link npm package. 
+```shell
+npm view bson@vX.Y.Z dist.tarball 
+```
+
+Using the result of the above command, a `curl` command can return the official npm package for the release.
+
+To verify the integrity of the downloaded package, run the following command:
+```shell
+gpg --verify bson-X.Y.Z.tgz.sig bson-X.Y.Z.tgz
+```
+
+>[!Note]
+No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.
+
+## Bugs / Feature Requests
+
+Think you've found a bug? Want to see a new feature in `bson`? Please open a case in our issue management tool, JIRA:
+
+1. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org)
+2. Navigate to the NODE project: [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE)
+3. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it.
+
+Bug reports in JIRA for the NODE driver project are **public**.
+
+## Usage
+
+To build a new version perform the following operations:
+
+```
+npm install
+npm run build
+```
+
+### Node.js or Bundling Usage
+
+When using a bundler or Node.js you can import bson using the package name:
+
+```js
+import { BSON, EJSON, ObjectId } from 'bson';
+// or:
+// const { BSON, EJSON, ObjectId } = require('bson');
+
+const bytes = BSON.serialize({ _id: new ObjectId() });
+console.log(bytes);
+const doc = BSON.deserialize(bytes);
+console.log(EJSON.stringify(doc));
+// {"_id":{"$oid":"..."}}
+```
+
+### Browser Usage
+
+If you are working directly in the browser without a bundler please use the `.mjs` bundle like so:
+
+```html
+<script type="module">
+  import { BSON, EJSON, ObjectId } from './lib/bson.mjs';
+
+  const bytes = BSON.serialize({ _id: new ObjectId() });
+  console.log(bytes);
+  const doc = BSON.deserialize(bytes);
+  console.log(EJSON.stringify(doc));
+  // {"_id":{"$oid":"..."}}
+</script>
+```
+
+## Installation
+
+```sh
+npm install bson
+```
+
+### MongoDB Node.js Driver Version Compatibility
+
+Only the following version combinations with the [MongoDB Node.js Driver](https://github.com/mongodb/node-mongodb-native) are considered stable.
+
+|               | `bson@1.x` | `bson@4.x` | `bson@5.x` | `bson@6.x` | `bson@7.x` |
+| ------------- | ---------- | ---------- | ---------- | ---------- | ---------- |
+| `mongodb@7.x` | N/A        | N/A        | N/A        | N/A        | ✓          |
+| `mongodb@6.x` | N/A        | N/A        | N/A        | ✓          | N/A        |
+| `mongodb@5.x` | N/A        | N/A        | ✓          | N/A        | N/A        |
+| `mongodb@4.x` | N/A        | ✓          | N/A        | N/A        | N/A        |
+| `mongodb@3.x` | ✓          | N/A        | N/A        | N/A        | N/A        |
+
+## Documentation
+
+### BSON
+
+[API documentation](https://mongodb.github.io/node-mongodb-native/Next/modules/BSON.html)
+
+<a name="EJSON"></a>
+
+### EJSON
+
+- [EJSON](#EJSON)
+
+  - [.parse(text, [options])](#EJSON.parse)
+
+  - [.stringify(value, [replacer], [space], [options])](#EJSON.stringify)
+
+  - [.serialize(bson, [options])](#EJSON.serialize)
+
+  - [.deserialize(ejson, [options])](#EJSON.deserialize)
+
+<a name="EJSON.parse"></a>
+
+#### _EJSON_.parse(text, [options])
+
+| Param             | Type                 | Default           | Description                                                                        |
+| ----------------- | -------------------- | ----------------- | ---------------------------------------------------------------------------------- |
+| text              | <code>string</code>  |                   |                                                                                    |
+| [options]         | <code>object</code>  |                   | Optional settings                                                                  |
+| [options.relaxed] | <code>boolean</code> | <code>true</code> | Attempt to return native JS types where possible, rather than BSON types (if true) |
+
+Parse an Extended JSON string, constructing the JavaScript value or object described by that
+string.
+
+**Example**
+
+```js
+const { EJSON } = require('bson');
+const text = '{ "int32": { "$numberInt": "10" } }';
+
+// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
+console.log(EJSON.parse(text, { relaxed: false }));
+
+// prints { int32: 10 }
+console.log(EJSON.parse(text));
+```
+
+<a name="EJSON.stringify"></a>
+
+#### _EJSON_.stringify(value, [replacer], [space], [options])
+
+| Param             | Type                                        | Default           | Description                                                                                                                                                                                                                                                                                                                                        |
+| ----------------- | ------------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| value             | <code>object</code>                         |                   | The value to convert to extended JSON                                                                                                                                                                                                                                                                                                              |
+| [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 |
+| [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.                                                                                                                                                                                                                                  |
+| [options]         | <code>object</code>                         |                   | Optional settings                                                                                                                                                                                                                                                                                                                                  |
+| [options.relaxed] | <code>boolean</code>                        | <code>true</code> | Enabled Extended JSON's `relaxed` mode                                                                                                                                                                                                                                                                                                             |
+| [options.legacy]  | <code>boolean</code>                        | <code>true</code> | Output in Extended JSON v1                                                                                                                                                                                                                                                                                                                         |
+
+Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
+function is specified or optionally including only the specified properties if a replacer array
+is specified.
+
+**Example**
+
+```js
+const { EJSON } = require('bson');
+const Int32 = require('mongodb').Int32;
+const doc = { int32: new Int32(10) };
+
+// prints '{"int32":{"$numberInt":"10"}}'
+console.log(EJSON.stringify(doc, { relaxed: false }));
+
+// prints '{"int32":10}'
+console.log(EJSON.stringify(doc));
+```
+
+<a name="EJSON.serialize"></a>
+
+#### _EJSON_.serialize(bson, [options])
+
+| Param     | Type                | Description                                          |
+| --------- | ------------------- | ---------------------------------------------------- |
+| bson      | <code>object</code> | The object to serialize                              |
+| [options] | <code>object</code> | Optional settings passed to the `stringify` function |
+
+Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
+
+<a name="EJSON.deserialize"></a>
+
+#### _EJSON_.deserialize(ejson, [options])
+
+| Param     | Type                | Description                                  |
+| --------- | ------------------- | -------------------------------------------- |
+| ejson     | <code>object</code> | The Extended JSON object to deserialize      |
+| [options] | <code>object</code> | Optional settings passed to the parse method |
+
+Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
+
+## 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
+
+js-bson requires the `atob`, `btoa` and `TextEncoder` globals.  Older versions of React Native did not support these global objects, and so 
+[js-bson v5.4.0](https://github.com/mongodb/js-bson/releases/tag/v5.4.0) added support for bundled polyfills for these globals.  Newer versions
+of Hermes includes these globals, and so the polyfills for are no longer needed in the js-bson package.
+
+If you find yourself on a version of React Native that does not have these globals, either:
+
+1. polyfill them yourself
+2. upgrade to a later version of hermes
+3. use a version of js-bson `>=5.4.0` and `<7.0.0`
+
+One additional polyfill, `crypto.getRandomValues` is recommended and can be installed with the following command:
+
+```sh
+npm install --save react-native-get-random-values
+```
+
+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 '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.rn.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
+
+#### Why does `undefined` get converted to `null`?
+
+The `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.
+
+#### How do I add custom serialization logic?
+
+This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize.
+
+```javascript
+const BSON = require('bson');
+
+class CustomSerialize {
+  toBSON() {
+    return 42;
+  }
+}
+
+const obj = { answer: new CustomSerialize() };
+// "{ answer: 42 }"
+console.log(BSON.deserialize(BSON.serialize(obj)));
+```

+ 1729 - 0
node_modules/bson/bson.d.ts

@@ -0,0 +1,1729 @@
+/**
+ * A class representation of the BSON Binary type.
+ * @public
+ * @category BSONType
+ */
+export declare class Binary extends BSONValue {
+    get _bsontype(): 'Binary';
+    /* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */
+    /** Initial buffer default size */
+    static readonly BUFFER_SIZE = 256;
+    /** Default BSON type */
+    static readonly SUBTYPE_DEFAULT = 0;
+    /** Function BSON type */
+    static readonly SUBTYPE_FUNCTION = 1;
+    /**
+     * Legacy default BSON Binary type
+     * @deprecated BSON Binary subtype 2 is deprecated in the BSON specification
+     */
+    static readonly SUBTYPE_BYTE_ARRAY = 2;
+    /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
+    static readonly SUBTYPE_UUID_OLD = 3;
+    /** UUID BSON type */
+    static readonly SUBTYPE_UUID = 4;
+    /** MD5 BSON type */
+    static readonly SUBTYPE_MD5 = 5;
+    /** Encrypted BSON type */
+    static readonly SUBTYPE_ENCRYPTED = 6;
+    /** Column BSON type */
+    static readonly SUBTYPE_COLUMN = 7;
+    /** Sensitive BSON type */
+    static readonly SUBTYPE_SENSITIVE = 8;
+    /** Vector BSON type */
+    static readonly SUBTYPE_VECTOR = 9;
+    /** User BSON type */
+    static readonly SUBTYPE_USER_DEFINED = 128;
+    /** datatype of a Binary Vector (subtype: 9) */
+    static readonly VECTOR_TYPE: Readonly<{
+        readonly Int8: 3;
+        readonly Float32: 39;
+        readonly PackedBit: 16;
+    }>;
+    /**
+     * The bytes of the Binary value.
+     *
+     * The format of a Binary value in BSON is defined as:
+     * ```txt
+     * binary	::= int32 subtype (byte*)
+     * ```
+     *
+     * This `buffer` is the "(byte*)" segment.
+     *
+     * Unless the value is subtype 2, then deserialize will read the first 4 bytes as an int32 and set this to the remaining bytes.
+     *
+     * ```txt
+     * binary	::= int32 unsigned_byte(2) int32 (byte*)
+     * ```
+     *
+     * @see https://bsonspec.org/spec.html
+     */
+    buffer: Uint8Array;
+    /**
+     * The binary subtype.
+     *
+     * Current defined values are:
+     *
+     * - `unsigned_byte(0)` Generic binary subtype
+     * - `unsigned_byte(1)` Function
+     * - `unsigned_byte(2)` Binary (Deprecated)
+     * - `unsigned_byte(3)` UUID (Deprecated)
+     * - `unsigned_byte(4)` UUID
+     * - `unsigned_byte(5)` MD5
+     * - `unsigned_byte(6)` Encrypted BSON value
+     * - `unsigned_byte(7)` Compressed BSON column
+     * - `unsigned_byte(8)` Sensitive
+     * - `unsigned_byte(9)` Vector
+     * - `unsigned_byte(128)` - `unsigned_byte(255)` User defined
+     */
+    sub_type: number;
+    /**
+     * The Binary's `buffer` can be larger than the Binary's content.
+     * This property is used to determine where the content ends in the buffer.
+     */
+    position: number;
+    /**
+     * Create a new Binary instance.
+     * @param buffer - a buffer object containing the binary data.
+     * @param subType - the option binary type.
+     */
+    constructor(buffer?: BinarySequence, subType?: number);
+    /**
+     * Updates this binary with byte_value.
+     *
+     * @param byteValue - a single byte we wish to write.
+     */
+    put(byteValue: string | number | Uint8Array | number[]): void;
+    /**
+     * Writes a buffer to the binary.
+     *
+     * @param sequence - a string or buffer to be written to the Binary BSON object.
+     * @param offset - specify the binary of where to write the content.
+     */
+    write(sequence: BinarySequence, offset: number): void;
+    /**
+     * Returns a view of **length** bytes starting at **position**.
+     *
+     * @param position - read from the given position in the Binary.
+     * @param length - the number of bytes to read.
+     */
+    read(position: number, length: number): Uint8Array;
+    /** returns a view of the binary value as a Uint8Array */
+    value(): Uint8Array;
+    /** the length of the binary sequence */
+    length(): number;
+    toJSON(): string;
+    toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string;
+    /* Excluded from this release type: toExtendedJSON */
+    toUUID(): UUID;
+    /** Creates an Binary instance from a hex digit string */
+    static createFromHexString(hex: string, subType?: number): Binary;
+    /** Creates an Binary instance from a base64 string */
+    static createFromBase64(base64: string, subType?: number): Binary;
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+    /**
+     * If this Binary represents a Int8 Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.Int8`),
+     * returns a copy of the bytes in a new Int8Array.
+     *
+     * If the Binary is not a Vector, or the datatype is not Int8, an error is thrown.
+     */
+    toInt8Array(): Int8Array;
+    /**
+     * If this Binary represents a Float32 Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.Float32`),
+     * returns a copy of the bytes in a new Float32Array.
+     *
+     * If the Binary is not a Vector, or the datatype is not Float32, an error is thrown.
+     */
+    toFloat32Array(): Float32Array;
+    /**
+     * If this Binary represents packed bit Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.PackedBit`),
+     * returns a copy of the bytes that are packed bits.
+     *
+     * Use `toBits` to get the unpacked bits.
+     *
+     * If the Binary is not a Vector, or the datatype is not PackedBit, an error is thrown.
+     */
+    toPackedBits(): Uint8Array;
+    /**
+     * If this Binary represents a Packed bit Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.PackedBit`),
+     * returns a copy of the bit unpacked into a new Int8Array.
+     *
+     * Use `toPackedBits` to get the bits still in packed form.
+     *
+     * If the Binary is not a Vector, or the datatype is not PackedBit, an error is thrown.
+     */
+    toBits(): Int8Array;
+    /**
+     * Constructs a Binary representing an Int8 Vector.
+     * @param array - The array to store as a view on the Binary class
+     */
+    static fromInt8Array(array: Int8Array): Binary;
+    /** Constructs a Binary representing an Float32 Vector. */
+    static fromFloat32Array(array: Float32Array): Binary;
+    /**
+     * Constructs a Binary representing a packed bit Vector.
+     *
+     * Use `fromBits` to pack an array of 1s and 0s.
+     */
+    static fromPackedBits(array: Uint8Array, padding?: number): Binary;
+    /**
+     * Constructs a Binary representing an Packed Bit Vector.
+     * @param array - The array of 1s and 0s to pack into the Binary instance
+     */
+    static fromBits(bits: ArrayLike<number>): Binary;
+}
+
+/** @public */
+export declare interface BinaryExtended {
+    $binary: {
+        subType: string;
+        base64: string;
+    };
+}
+
+/** @public */
+export declare interface BinaryExtendedLegacy {
+    $type: string;
+    $binary: string;
+}
+
+/** @public */
+export declare type BinarySequence = Uint8Array | number[];
+
+declare namespace BSON {
+    export {
+        setInternalBufferSize,
+        serialize,
+        serializeWithBufferAndIndex,
+        deserialize,
+        calculateObjectSize,
+        deserializeStream,
+        UUIDExtended,
+        BinaryExtended,
+        BinaryExtendedLegacy,
+        BinarySequence,
+        CodeExtended,
+        DBRefLike,
+        Decimal128Extended,
+        DoubleExtended,
+        EJSONOptions,
+        Int32Extended,
+        LongExtended,
+        MaxKeyExtended,
+        MinKeyExtended,
+        ObjectIdExtended,
+        ObjectIdLike,
+        BSONRegExpExtended,
+        BSONRegExpExtendedLegacy,
+        BSONSymbolExtended,
+        LongWithoutOverrides,
+        TimestampExtended,
+        TimestampOverrides,
+        LongWithoutOverridesClass,
+        SerializeOptions,
+        DeserializeOptions,
+        Code,
+        BSONSymbol,
+        DBRef,
+        Binary,
+        ObjectId,
+        UUID,
+        Long,
+        Timestamp,
+        Double,
+        Int32,
+        MinKey,
+        MaxKey,
+        BSONRegExp,
+        Decimal128,
+        BSONValue,
+        bsonType,
+        BSONTypeTag,
+        BSONError,
+        BSONVersionError,
+        BSONRuntimeError,
+        BSONOffsetError,
+        BSONType,
+        EJSON,
+        onDemand,
+        OnDemand,
+        Document,
+        CalculateObjectSizeOptions
+    }
+}
+export { BSON }
+
+/* Excluded from this release type: BSON_MAJOR_VERSION */
+
+/* Excluded from this release type: BSON_VERSION_SYMBOL */
+
+/**
+ * @public
+ * @experimental
+ */
+declare type BSONElement = [
+type: number,
+nameOffset: number,
+nameLength: number,
+offset: number,
+length: number
+];
+
+/**
+ * @public
+ * @category Error
+ *
+ * `BSONError` objects are thrown when BSON encounters an error.
+ *
+ * This is the parent class for all the other errors thrown by this library.
+ */
+export declare class BSONError extends Error {
+    /* Excluded from this release type: bsonError */
+    get name(): string;
+    constructor(message: string, options?: {
+        cause?: unknown;
+    });
+    /**
+     * @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;
+}
+
+/**
+ * @public
+ * @category Error
+ *
+ * @experimental
+ *
+ * An error generated when BSON bytes are invalid.
+ * Reports the offset the parser was able to reach before encountering the error.
+ */
+export declare class BSONOffsetError extends BSONError {
+    get name(): 'BSONOffsetError';
+    offset: number;
+    constructor(message: string, offset: number, options?: {
+        cause?: unknown;
+    });
+}
+
+/**
+ * A class representation of the BSON RegExp type.
+ * @public
+ * @category BSONType
+ */
+export declare class BSONRegExp extends BSONValue {
+    get _bsontype(): 'BSONRegExp';
+    pattern: string;
+    options: string;
+    /**
+     * @param pattern - The regular expression pattern to match
+     * @param options - The regular expression options
+     */
+    constructor(pattern: string, options?: string);
+    static parseOptions(options?: string): string;
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface BSONRegExpExtended {
+    $regularExpression: {
+        pattern: string;
+        options: string;
+    };
+}
+
+/** @public */
+export declare interface BSONRegExpExtendedLegacy {
+    $regex: string | BSONRegExp;
+    $options: string;
+}
+
+/**
+ * @public
+ * @category Error
+ *
+ * An error generated when BSON functions encounter an unexpected input
+ * or reaches an unexpected/invalid internal state
+ *
+ */
+export declare class BSONRuntimeError extends BSONError {
+    get name(): 'BSONRuntimeError';
+    constructor(message: string);
+}
+
+/**
+ * A class representation of the BSON Symbol type.
+ * @public
+ * @category BSONType
+ */
+export declare class BSONSymbol extends BSONValue {
+    get _bsontype(): 'BSONSymbol';
+    value: string;
+    /**
+     * @param value - the string representing the symbol.
+     */
+    constructor(value: string);
+    /** Access the wrapped string value. */
+    valueOf(): string;
+    toString(): string;
+    toJSON(): string;
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface BSONSymbolExtended {
+    $symbol: string;
+}
+
+/** @public */
+export declare const BSONType: Readonly<{
+    readonly double: 1;
+    readonly string: 2;
+    readonly object: 3;
+    readonly array: 4;
+    readonly binData: 5;
+    readonly undefined: 6;
+    readonly objectId: 7;
+    readonly bool: 8;
+    readonly date: 9;
+    readonly null: 10;
+    readonly regex: 11;
+    readonly dbPointer: 12;
+    readonly javascript: 13;
+    readonly symbol: 14;
+    readonly javascriptWithScope: 15;
+    readonly int: 16;
+    readonly timestamp: 17;
+    readonly long: 18;
+    readonly decimal: 19;
+    readonly minKey: -1;
+    readonly maxKey: 127;
+}>;
+
+/** @public */
+export declare type BSONType = (typeof BSONType)[keyof typeof BSONType];
+
+/** @public */
+export declare const bsonType: unique symbol;
+
+/** @public */
+export declare type BSONTypeTag = 'BSONRegExp' | 'BSONSymbol' | 'ObjectId' | 'Binary' | 'Decimal128' | 'Double' | 'Int32' | 'Long' | 'MaxKey' | 'MinKey' | 'Timestamp' | 'Code' | 'DBRef';
+
+/** @public */
+export declare abstract class BSONValue {
+    /** @public */
+    abstract get _bsontype(): BSONTypeTag;
+    get [bsonType](): this['_bsontype'];
+    /* Excluded from this release type: [BSON_VERSION_SYMBOL] */
+    /**
+     * @public
+     * Prints a human-readable string of BSON value information
+     * If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify
+     */
+    abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+    /* Excluded from this release type: toExtendedJSON */
+}
+
+/**
+ * @public
+ * @category Error
+ */
+export declare class BSONVersionError extends BSONError {
+    get name(): 'BSONVersionError';
+    constructor();
+}
+
+/**
+ * @public
+ * @experimental
+ *
+ * A collection of functions that help work with data in a Uint8Array.
+ * ByteUtils is configured at load time to use Node.js or Web based APIs for the internal implementations.
+ */
+declare type ByteUtils = {
+    /** Transforms the input to an instance of Buffer if running on node, otherwise Uint8Array */
+    toLocalBufferType: (buffer: Uint8Array | ArrayBufferView | ArrayBuffer) => Uint8Array;
+    /** Create empty space of size */
+    allocate: (size: number) => Uint8Array;
+    /** Create empty space of size, use pooled memory when available */
+    allocateUnsafe: (size: number) => Uint8Array;
+    /** Check if two Uint8Arrays are deep equal */
+    equals: (a: Uint8Array, b: Uint8Array) => boolean;
+    /** Check if two Uint8Arrays are deep equal */
+    fromNumberArray: (array: number[]) => Uint8Array;
+    /** Create a Uint8Array from a base64 string */
+    fromBase64: (base64: string) => Uint8Array;
+    /** Create a base64 string from bytes */
+    toBase64: (buffer: Uint8Array) => string;
+    /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */
+    fromISO88591: (codePoints: string) => Uint8Array;
+    /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */
+    toISO88591: (buffer: Uint8Array) => string;
+    /** Create a Uint8Array from a hex string */
+    fromHex: (hex: string) => Uint8Array;
+    /** Create a lowercase hex string from bytes */
+    toHex: (buffer: Uint8Array) => string;
+    /** Create a string from utf8 code units, fatal=true will throw an error if UTF-8 bytes are invalid, fatal=false will insert replacement characters */
+    toUTF8: (buffer: Uint8Array, start: number, end: number, fatal: boolean) => string;
+    /** Get the utf8 code unit count from a string if it were to be transformed to utf8 */
+    utf8ByteLength: (input: string) => number;
+    /** Encode UTF8 bytes generated from `source` string into `destination` at byteOffset. Returns the number of bytes encoded. */
+    encodeUTF8Into: (destination: Uint8Array, source: string, byteOffset: number) => number;
+    /** Generate a Uint8Array filled with random bytes with byteLength */
+    randomBytes: (byteLength: number) => Uint8Array;
+    /** Interprets `buffer` as an array of 32-bit values and swaps the byte order in-place. */
+    swap32: (buffer: Uint8Array) => Uint8Array;
+};
+
+/* Excluded declaration from this release type: ByteUtils */
+
+/**
+ * Calculate the bson size for a passed in Javascript object.
+ *
+ * @param object - the Javascript object to calculate the BSON byte size for
+ * @returns size of BSON object in bytes
+ * @public
+ */
+export declare function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number;
+
+/** @public */
+export declare type CalculateObjectSizeOptions = Pick<SerializeOptions, 'serializeFunctions' | 'ignoreUndefined'>;
+
+/**
+ * A class representation of the BSON Code type.
+ * @public
+ * @category BSONType
+ */
+export declare class Code extends BSONValue {
+    get _bsontype(): 'Code';
+    code: string;
+    scope: Document | null;
+    /**
+     * @param code - a string or function.
+     * @param scope - an optional scope for the function.
+     */
+    constructor(code: string | Function, scope?: Document | null);
+    toJSON(): {
+        code: string;
+        scope?: Document;
+    };
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface CodeExtended {
+    $code: string;
+    $scope?: Document;
+}
+
+/**
+ * A class representation of the BSON DBRef type.
+ * @public
+ * @category BSONType
+ */
+export declare class DBRef extends BSONValue {
+    get _bsontype(): 'DBRef';
+    collection: string;
+    oid: ObjectId;
+    db?: string;
+    fields: Document;
+    /**
+     * @param collection - the collection name.
+     * @param oid - the reference ObjectId.
+     * @param db - optional db name, if omitted the reference is local to the current db.
+     */
+    constructor(collection: string, oid: ObjectId, db?: string, fields?: Document);
+    /* Excluded from this release type: namespace */
+    /* Excluded from this release type: namespace */
+    toJSON(): DBRefLike & Document;
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface DBRefLike {
+    $ref: string;
+    $id: ObjectId;
+    $db?: string;
+}
+
+/**
+ * A class representation of the BSON Decimal128 type.
+ * @public
+ * @category BSONType
+ */
+export declare class Decimal128 extends BSONValue {
+    get _bsontype(): 'Decimal128';
+    readonly bytes: Uint8Array;
+    /**
+     * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order,
+     *                or a string representation as returned by .toString()
+     */
+    constructor(bytes: Uint8Array | string);
+    /**
+     * Create a Decimal128 instance from a string representation
+     *
+     * @param representation - a numeric string representation.
+     */
+    static fromString(representation: string): Decimal128;
+    /**
+     * Create a Decimal128 instance from a string representation, allowing for rounding to 34
+     * significant digits
+     *
+     * @example Example of a number that will be rounded
+     * ```ts
+     * > let d = Decimal128.fromString('37.499999999999999196428571428571375')
+     * Uncaught:
+     * BSONError: "37.499999999999999196428571428571375" is not a valid Decimal128 string - inexact rounding
+     * at invalidErr (/home/wajames/js-bson/lib/bson.cjs:1402:11)
+     * at Decimal128.fromStringInternal (/home/wajames/js-bson/lib/bson.cjs:1633:25)
+     * at Decimal128.fromString (/home/wajames/js-bson/lib/bson.cjs:1424:27)
+     *
+     * > d = Decimal128.fromStringWithRounding('37.499999999999999196428571428571375')
+     * new Decimal128("37.49999999999999919642857142857138")
+     * ```
+     * @param representation - a numeric string representation.
+     */
+    static fromStringWithRounding(representation: string): Decimal128;
+    private static _fromString;
+    /** Create a string representation of the raw Decimal128 value */
+    toString(): string;
+    toJSON(): Decimal128Extended;
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface Decimal128Extended {
+    $numberDecimal: string;
+}
+
+/**
+ * Deserialize data as BSON.
+ *
+ * @param buffer - the buffer containing the serialized set of BSON documents.
+ * @returns returns the deserialized Javascript Object.
+ * @public
+ */
+export declare function deserialize(buffer: Uint8Array, options?: DeserializeOptions): Document;
+
+/** @public */
+export declare interface DeserializeOptions {
+    /**
+     * when deserializing a Long return as a BigInt.
+     * @defaultValue `false`
+     */
+    useBigInt64?: boolean;
+    /**
+     * when deserializing a Long will fit it into a Number if it's smaller than 53 bits.
+     * @defaultValue `true`
+     */
+    promoteLongs?: boolean;
+    /**
+     * when deserializing a Binary will return it as a node.js Buffer instance.
+     * @defaultValue `false`
+     */
+    promoteBuffers?: boolean;
+    /**
+     * when deserializing will promote BSON values to their Node.js closest equivalent types.
+     * @defaultValue `true`
+     */
+    promoteValues?: boolean;
+    /**
+     * allow to specify if there what fields we wish to return as unserialized raw buffer.
+     * @defaultValue `null`
+     */
+    fieldsAsRaw?: Document;
+    /**
+     * return BSON regular expressions as BSONRegExp instances.
+     * @defaultValue `false`
+     */
+    bsonRegExp?: boolean;
+    /**
+     * allows the buffer to be larger than the parsed BSON object.
+     * @defaultValue `false`
+     */
+    allowObjectSmallerThanBufferSize?: boolean;
+    /**
+     * Offset into buffer to begin reading document from
+     * @defaultValue `0`
+     */
+    index?: number;
+    raw?: boolean;
+    /** Allows for opt-out utf-8 validation for all keys or
+     * specified keys. Must be all true or all false.
+     *
+     * @example
+     * ```js
+     * // disables validation on all keys
+     *  validation: { utf8: false }
+     *
+     * // enables validation only on specified keys a, b, and c
+     *  validation: { utf8: { a: true, b: true, c: true } }
+     *
+     *  // disables validation only on specified keys a, b
+     *  validation: { utf8: { a: false, b: false } }
+     * ```
+     */
+    validation?: {
+        utf8: boolean | Record<string, true> | Record<string, false>;
+    };
+}
+
+/**
+ * Deserialize stream data as BSON documents.
+ *
+ * @param data - the buffer containing the serialized set of BSON documents.
+ * @param startIndex - the start index in the data Buffer where the deserialization is to start.
+ * @param numberOfDocuments - number of documents to deserialize.
+ * @param documents - an array where to store the deserialized documents.
+ * @param docStartIndex - the index in the documents array from where to start inserting documents.
+ * @param options - additional options used for the deserialization.
+ * @returns next index in the buffer after deserialization **x** numbers of documents.
+ * @public
+ */
+export declare function deserializeStream(data: Uint8Array | ArrayBuffer, startIndex: number, numberOfDocuments: number, documents: Document[], docStartIndex: number, options: DeserializeOptions): number;
+
+/** @public */
+export declare interface Document {
+    [key: string]: any;
+}
+
+/**
+ * A class representation of the BSON Double type.
+ * @public
+ * @category BSONType
+ */
+export declare class Double extends BSONValue {
+    get _bsontype(): 'Double';
+    value: number;
+    /**
+     * Create a Double type
+     *
+     * @param value - the number we want to represent as a double.
+     */
+    constructor(value: number);
+    /**
+     * Attempt to create an double type from string.
+     *
+     * This method will throw a BSONError on any string input that is not representable as a IEEE-754 64-bit double.
+     * Notably, this method will also throw on the following string formats:
+     * - Strings in non-decimal and non-exponential formats (binary, hex, or octal digits)
+     * - Strings with characters other than numeric, floating point, or leading sign characters (Note: 'Infinity', '-Infinity', and 'NaN' input strings are still allowed)
+     * - Strings with leading and/or trailing whitespace
+     *
+     * Strings with leading zeros, however, are also allowed
+     *
+     * @param value - the string we want to represent as a double.
+     */
+    static fromString(value: string): Double;
+    /**
+     * Access the number value.
+     *
+     * @returns returns the wrapped double number.
+     */
+    valueOf(): number;
+    toJSON(): number;
+    toString(radix?: number): string;
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface DoubleExtended {
+    $numberDouble: string;
+}
+
+/** @public */
+export declare const EJSON: {
+    parse: typeof parse;
+    stringify: typeof stringify;
+    serialize: typeof EJSONserialize;
+    deserialize: typeof EJSONdeserialize;
+};
+
+/**
+ * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
+ *
+ * @param ejson - The Extended JSON object to deserialize
+ * @param options - Optional settings passed to the parse method
+ */
+declare function EJSONdeserialize(ejson: Document, options?: EJSONOptions): any;
+
+/** @public */
+export declare type EJSONOptions = {
+    /**
+     * Output using the Extended JSON v1 spec
+     * @defaultValue `false`
+     */
+    legacy?: boolean;
+    /**
+     * Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types
+     * @defaultValue `false` */
+    relaxed?: boolean;
+    /**
+     * Enable native bigint support
+     * @defaultValue `false`
+     */
+    useBigInt64?: boolean;
+};
+
+/**
+ * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
+ *
+ * @param value - The object to serialize
+ * @param options - Optional settings passed to the `stringify` function
+ */
+declare function EJSONserialize(value: any, options?: EJSONOptions): Document;
+
+declare type InspectFn = (x: unknown, options?: unknown) => string;
+
+/**
+ * A class representation of a BSON Int32 type.
+ * @public
+ * @category BSONType
+ */
+export declare class Int32 extends BSONValue {
+    get _bsontype(): 'Int32';
+    value: number;
+    /**
+     * Create an Int32 type
+     *
+     * @param value - the number we want to represent as an int32.
+     */
+    constructor(value: number | string);
+    /**
+     * Attempt to create an Int32 type from string.
+     *
+     * This method will throw a BSONError on any string input that is not representable as an Int32.
+     * Notably, this method will also throw on the following string formats:
+     * - Strings in non-decimal formats (exponent notation, binary, hex, or octal digits)
+     * - Strings non-numeric and non-leading sign characters (ex: '2.0', '24,000')
+     * - Strings with leading and/or trailing whitespace
+     *
+     * Strings with leading zeros, however, are allowed.
+     *
+     * @param value - the string we want to represent as an int32.
+     */
+    static fromString(value: string): Int32;
+    /**
+     * Access the number value.
+     *
+     * @returns returns the wrapped int32 number.
+     */
+    valueOf(): number;
+    toString(radix?: number): string;
+    toJSON(): number;
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface Int32Extended {
+    $numberInt: string;
+}
+
+/**
+ * A class representing a 64-bit integer
+ * @public
+ * @category BSONType
+ * @remarks
+ * The internal representation of a long is the two given signed, 32-bit values.
+ * We use 32-bit pieces because these are the size of integers on which
+ * Javascript performs bit-operations.  For operations like addition and
+ * multiplication, we split each number into 16 bit pieces, which can easily be
+ * multiplied within Javascript's floating-point representation without overflow
+ * or change in sign.
+ * In the algorithms below, we frequently reduce the negative case to the
+ * positive case by negating the input(s) and then post-processing the result.
+ * Note that we must ALWAYS check specially whether those values are MIN_VALUE
+ * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
+ * a positive number, it overflows back into a negative).  Not handling this
+ * case would often result in infinite recursion.
+ * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
+ */
+export declare class Long extends BSONValue {
+    get _bsontype(): 'Long';
+    /** An indicator used to reliably determine if an object is a Long or not. */
+    get __isLong__(): boolean;
+    /**
+     * The high 32 bits as a signed value.
+     */
+    high: number;
+    /**
+     * The low 32 bits as a signed value.
+     */
+    low: number;
+    /**
+     * Whether unsigned or not.
+     */
+    unsigned: boolean;
+    /**
+     * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
+     *
+     * @param low - The low (signed) 32 bits of the long
+     * @param high - The high (signed) 32 bits of the long
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     */
+    constructor(low: number, high?: number, unsigned?: boolean);
+    /**
+     * Constructs a 64 bit two's-complement integer, given a bigint representation.
+     *
+     * @param value - BigInt representation of the long value
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     */
+    constructor(value: bigint, unsigned?: boolean);
+    /**
+     * Constructs a 64 bit two's-complement integer, given a string representation.
+     *
+     * @param value - String representation of the long value
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     */
+    constructor(value: string, unsigned?: boolean);
+    static TWO_PWR_24: Long;
+    /** Maximum unsigned value. */
+    static MAX_UNSIGNED_VALUE: Long;
+    /** Signed zero */
+    static ZERO: Long;
+    /** Unsigned zero. */
+    static UZERO: Long;
+    /** Signed one. */
+    static ONE: Long;
+    /** Unsigned one. */
+    static UONE: Long;
+    /** Signed negative one. */
+    static NEG_ONE: Long;
+    /** Maximum signed value. */
+    static MAX_VALUE: Long;
+    /** Minimum signed value. */
+    static MIN_VALUE: Long;
+    /**
+     * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.
+     * Each is assumed to use 32 bits.
+     * @param lowBits - The low 32 bits
+     * @param highBits - The high 32 bits
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @returns The corresponding Long value
+     */
+    static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long;
+    /**
+     * Returns a Long representing the given 32 bit integer value.
+     * @param value - The 32 bit integer in question
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @returns The corresponding Long value
+     */
+    static fromInt(value: number, unsigned?: boolean): Long;
+    /**
+     * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
+     * @param value - The number in question
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @returns The corresponding Long value
+     */
+    static fromNumber(value: number, unsigned?: boolean): Long;
+    /**
+     * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
+     * @param value - The number in question
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @returns The corresponding Long value
+     */
+    static fromBigInt(value: bigint, unsigned?: boolean): Long;
+    /* Excluded from this release type: _fromString */
+    /**
+     * Returns a signed Long representation of the given string, written using radix 10.
+     * Will throw an error if the given text is not exactly representable as a Long.
+     * Throws an error if any of the following conditions are true:
+     * - the string contains invalid characters for the radix 10
+     * - the string contains whitespace
+     * - the value the string represents is too large or too small to be a Long
+     * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
+     * @param str - The textual representation of the Long
+     * @returns The corresponding Long value
+     */
+    static fromStringStrict(str: string): Long;
+    /**
+     * Returns a Long representation of the given string, written using the radix 10.
+     * Will throw an error if the given parameters are not exactly representable as a Long.
+     * Throws an error if any of the following conditions are true:
+     * - the string contains invalid characters for the given radix
+     * - the string contains whitespace
+     * - the value the string represents is too large or too small to be a Long
+     * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
+     * @param str - The textual representation of the Long
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @returns The corresponding Long value
+     */
+    static fromStringStrict(str: string, unsigned?: boolean): Long;
+    /**
+     * Returns a signed Long representation of the given string, written using the specified radix.
+     * Will throw an error if the given parameters are not exactly representable as a Long.
+     * Throws an error if any of the following conditions are true:
+     * - the string contains invalid characters for the given radix
+     * - the string contains whitespace
+     * - the value the string represents is too large or too small to be a Long
+     * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
+     * @param str - The textual representation of the Long
+     * @param radix - The radix in which the text is written (2-36), defaults to 10
+     * @returns The corresponding Long value
+     */
+    static fromStringStrict(str: string, radix?: boolean): Long;
+    /**
+     * Returns a Long representation of the given string, written using the specified radix.
+     * Will throw an error if the given parameters are not exactly representable as a Long.
+     * Throws an error if any of the following conditions are true:
+     * - the string contains invalid characters for the given radix
+     * - the string contains whitespace
+     * - the value the string represents is too large or too small to be a Long
+     * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
+     * @param str - The textual representation of the Long
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @param radix - The radix in which the text is written (2-36), defaults to 10
+     * @returns The corresponding Long value
+     */
+    static fromStringStrict(str: string, unsigned?: boolean, radix?: number): Long;
+    /**
+     * Returns a signed Long representation of the given string, written using radix 10.
+     *
+     * If the input string is empty, this function will throw a BSONError.
+     *
+     * If input string does not have valid signed 64-bit Long representation, this method will return a coerced value:
+     * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively
+     * - 'NaN' or '+/-Infinity' are coerced to Long.ZERO
+     * - other invalid characters sequences have variable behavior
+     *
+     * @param str - The textual representation of the Long
+     * @returns The corresponding Long value
+     */
+    static fromString(str: string): Long;
+    /**
+     * Returns a signed Long representation of the given string, written using the provided radix.
+     *
+     * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
+     *
+     * If input parameters do not have valid signed 64-bit Long representation, this method will return a coerced value:
+     * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively
+     * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
+     * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
+     * - other invalid characters sequences have variable behavior
+     * @param str - The textual representation of the Long
+     * @param radix - The radix in which the text is written (2-36), defaults to 10
+     * @returns The corresponding Long value
+     */
+    static fromString(str: string, radix?: number): Long;
+    /**
+     * Returns a Long representation of the given string, written using radix 10.
+     *
+     * If the input string is empty, this function will throw a BSONError.
+     *
+     * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
+     * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values
+     * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
+     * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
+     * - other invalid characters sequences have variable behavior
+     * @param str - The textual representation of the Long
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @returns The corresponding Long value
+     */
+    static fromString(str: string, unsigned?: boolean): Long;
+    /**
+     * Returns a Long representation of the given string, written using the specified radix.
+     *
+     * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
+     *
+     * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
+     * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values
+     * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
+     * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
+     * - other invalid characters sequences have variable behavior
+     * @param str - The textual representation of the Long
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @param radix - The radix in which the text is written (2-36), defaults to 10
+     * @returns The corresponding Long value
+     */
+    static fromString(str: string, unsigned?: boolean, radix?: number): Long;
+    /**
+     * Creates a Long from its byte representation.
+     * @param bytes - Byte representation
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @param le - Whether little or big endian, defaults to big endian
+     * @returns The corresponding Long value
+     */
+    static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long;
+    /**
+     * Creates a Long from its little endian byte representation.
+     * @param bytes - Little endian byte representation
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @returns The corresponding Long value
+     */
+    static fromBytesLE(bytes: number[], unsigned?: boolean): Long;
+    /**
+     * Creates a Long from its big endian byte representation.
+     * @param bytes - Big endian byte representation
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     * @returns The corresponding Long value
+     */
+    static fromBytesBE(bytes: number[], unsigned?: boolean): Long;
+    /**
+     * Tests if the specified object is a Long.
+     */
+    static isLong(value: unknown): value is Long;
+    /**
+     * Converts the specified value to a Long.
+     * @param unsigned - Whether unsigned or not, defaults to signed
+     */
+    static fromValue(val: number | string | {
+        low: number;
+        high: number;
+        unsigned?: boolean;
+    }, unsigned?: boolean): Long;
+    /** Returns the sum of this and the specified Long. */
+    add(addend: string | number | Long | Timestamp): Long;
+    /**
+     * Returns the sum of this and the specified Long.
+     * @returns Sum
+     */
+    and(other: string | number | Long | Timestamp): Long;
+    /**
+     * Compares this Long's value with the specified's.
+     * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
+     */
+    compare(other: string | number | Long | Timestamp): 0 | 1 | -1;
+    /** This is an alias of {@link Long.compare} */
+    comp(other: string | number | Long | Timestamp): 0 | 1 | -1;
+    /**
+     * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.
+     * @returns Quotient
+     */
+    divide(divisor: string | number | Long | Timestamp): Long;
+    /**This is an alias of {@link Long.divide} */
+    div(divisor: string | number | Long | Timestamp): Long;
+    /**
+     * Tests if this Long's value equals the specified's.
+     * @param other - Other value
+     */
+    equals(other: string | number | Long | Timestamp): boolean;
+    /** This is an alias of {@link Long.equals} */
+    eq(other: string | number | Long | Timestamp): boolean;
+    /** Gets the high 32 bits as a signed integer. */
+    getHighBits(): number;
+    /** Gets the high 32 bits as an unsigned integer. */
+    getHighBitsUnsigned(): number;
+    /** Gets the low 32 bits as a signed integer. */
+    getLowBits(): number;
+    /** Gets the low 32 bits as an unsigned integer. */
+    getLowBitsUnsigned(): number;
+    /** Gets the number of bits needed to represent the absolute value of this Long. */
+    getNumBitsAbs(): number;
+    /** Tests if this Long's value is greater than the specified's. */
+    greaterThan(other: string | number | Long | Timestamp): boolean;
+    /** This is an alias of {@link Long.greaterThan} */
+    gt(other: string | number | Long | Timestamp): boolean;
+    /** Tests if this Long's value is greater than or equal the specified's. */
+    greaterThanOrEqual(other: string | number | Long | Timestamp): boolean;
+    /** This is an alias of {@link Long.greaterThanOrEqual} */
+    gte(other: string | number | Long | Timestamp): boolean;
+    /** This is an alias of {@link Long.greaterThanOrEqual} */
+    ge(other: string | number | Long | Timestamp): boolean;
+    /** Tests if this Long's value is even. */
+    isEven(): boolean;
+    /** Tests if this Long's value is negative. */
+    isNegative(): boolean;
+    /** Tests if this Long's value is odd. */
+    isOdd(): boolean;
+    /** Tests if this Long's value is positive. */
+    isPositive(): boolean;
+    /** Tests if this Long's value equals zero. */
+    isZero(): boolean;
+    /** Tests if this Long's value is less than the specified's. */
+    lessThan(other: string | number | Long | Timestamp): boolean;
+    /** This is an alias of {@link Long#lessThan}. */
+    lt(other: string | number | Long | Timestamp): boolean;
+    /** Tests if this Long's value is less than or equal the specified's. */
+    lessThanOrEqual(other: string | number | Long | Timestamp): boolean;
+    /** This is an alias of {@link Long.lessThanOrEqual} */
+    lte(other: string | number | Long | Timestamp): boolean;
+    /** Returns this Long modulo the specified. */
+    modulo(divisor: string | number | Long | Timestamp): Long;
+    /** This is an alias of {@link Long.modulo} */
+    mod(divisor: string | number | Long | Timestamp): Long;
+    /** This is an alias of {@link Long.modulo} */
+    rem(divisor: string | number | Long | Timestamp): Long;
+    /**
+     * Returns the product of this and the specified Long.
+     * @param multiplier - Multiplier
+     * @returns Product
+     */
+    multiply(multiplier: string | number | Long | Timestamp): Long;
+    /** This is an alias of {@link Long.multiply} */
+    mul(multiplier: string | number | Long | Timestamp): Long;
+    /** Returns the Negation of this Long's value. */
+    negate(): Long;
+    /** This is an alias of {@link Long.negate} */
+    neg(): Long;
+    /** Returns the bitwise NOT of this Long. */
+    not(): Long;
+    /** Tests if this Long's value differs from the specified's. */
+    notEquals(other: string | number | Long | Timestamp): boolean;
+    /** This is an alias of {@link Long.notEquals} */
+    neq(other: string | number | Long | Timestamp): boolean;
+    /** This is an alias of {@link Long.notEquals} */
+    ne(other: string | number | Long | Timestamp): boolean;
+    /**
+     * Returns the bitwise OR of this Long and the specified.
+     */
+    or(other: number | string | Long): Long;
+    /**
+     * Returns this Long with bits shifted to the left by the given amount.
+     * @param numBits - Number of bits
+     * @returns Shifted Long
+     */
+    shiftLeft(numBits: number | Long): Long;
+    /** This is an alias of {@link Long.shiftLeft} */
+    shl(numBits: number | Long): Long;
+    /**
+     * Returns this Long with bits arithmetically shifted to the right by the given amount.
+     * @param numBits - Number of bits
+     * @returns Shifted Long
+     */
+    shiftRight(numBits: number | Long): Long;
+    /** This is an alias of {@link Long.shiftRight} */
+    shr(numBits: number | Long): Long;
+    /**
+     * Returns this Long with bits logically shifted to the right by the given amount.
+     * @param numBits - Number of bits
+     * @returns Shifted Long
+     */
+    shiftRightUnsigned(numBits: Long | number): Long;
+    /** This is an alias of {@link Long.shiftRightUnsigned} */
+    shr_u(numBits: number | Long): Long;
+    /** This is an alias of {@link Long.shiftRightUnsigned} */
+    shru(numBits: number | Long): Long;
+    /**
+     * Returns the difference of this and the specified Long.
+     * @param subtrahend - Subtrahend
+     * @returns Difference
+     */
+    subtract(subtrahend: string | number | Long | Timestamp): Long;
+    /** This is an alias of {@link Long.subtract} */
+    sub(subtrahend: string | number | Long | Timestamp): Long;
+    /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */
+    toInt(): number;
+    /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */
+    toNumber(): number;
+    /** Converts the Long to a BigInt (arbitrary precision). */
+    toBigInt(): bigint;
+    /**
+     * Converts this Long to its byte representation.
+     * @param le - Whether little or big endian, defaults to big endian
+     * @returns Byte representation
+     */
+    toBytes(le?: boolean): number[];
+    /**
+     * Converts this Long to its little endian byte representation.
+     * @returns Little endian byte representation
+     */
+    toBytesLE(): number[];
+    /**
+     * Converts this Long to its big endian byte representation.
+     * @returns Big endian byte representation
+     */
+    toBytesBE(): number[];
+    /**
+     * Converts this Long to signed.
+     */
+    toSigned(): Long;
+    /**
+     * Converts the Long to a string written in the specified radix.
+     * @param radix - Radix (2-36), defaults to 10
+     * @throws RangeError If `radix` is out of range
+     */
+    toString(radix?: number): string;
+    /** Converts this Long to unsigned. */
+    toUnsigned(): Long;
+    /** Returns the bitwise XOR of this Long and the given one. */
+    xor(other: Long | number | string): Long;
+    /** This is an alias of {@link Long.isZero} */
+    eqz(): boolean;
+    /** This is an alias of {@link Long.lessThanOrEqual} */
+    le(other: string | number | Long | Timestamp): boolean;
+    toExtendedJSON(options?: EJSONOptions): number | LongExtended;
+    static fromExtendedJSON(doc: {
+        $numberLong: string;
+    }, options?: EJSONOptions): number | Long | bigint;
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface LongExtended {
+    $numberLong: string;
+}
+
+/** @public */
+export declare type LongWithoutOverrides = new (low: unknown, high?: number | boolean, unsigned?: boolean) => {
+    [P in Exclude<keyof Long, TimestampOverrides>]: Long[P];
+};
+
+/** @public */
+export declare const LongWithoutOverridesClass: LongWithoutOverrides;
+
+/**
+ * A class representation of the BSON MaxKey type.
+ * @public
+ * @category BSONType
+ */
+export declare class MaxKey extends BSONValue {
+    get _bsontype(): 'MaxKey';
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(): string;
+}
+
+/** @public */
+export declare interface MaxKeyExtended {
+    $maxKey: 1;
+}
+
+/**
+ * A class representation of the BSON MinKey type.
+ * @public
+ * @category BSONType
+ */
+export declare class MinKey extends BSONValue {
+    get _bsontype(): 'MinKey';
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(): string;
+}
+
+/** @public */
+export declare interface MinKeyExtended {
+    $minKey: 1;
+}
+
+/**
+ * @experimental
+ * @public
+ *
+ * A collection of functions that get or set various numeric types and bit widths from a Uint8Array.
+ */
+declare type NumberUtils = {
+    /** Is true if the current system is big endian. */
+    isBigEndian: boolean;
+    /**
+     * Parses a signed int32 at offset. Throws a `RangeError` if value is negative.
+     */
+    getNonnegativeInt32LE: (source: Uint8Array, offset: number) => number;
+    getInt32LE: (source: Uint8Array, offset: number) => number;
+    getUint32LE: (source: Uint8Array, offset: number) => number;
+    getUint32BE: (source: Uint8Array, offset: number) => number;
+    getBigInt64LE: (source: Uint8Array, offset: number) => bigint;
+    getFloat64LE: (source: Uint8Array, offset: number) => number;
+    setInt32BE: (destination: Uint8Array, offset: number, value: number) => 4;
+    setInt32LE: (destination: Uint8Array, offset: number, value: number) => 4;
+    setBigInt64LE: (destination: Uint8Array, offset: number, value: bigint) => 8;
+    setFloat64LE: (destination: Uint8Array, offset: number, value: number) => 8;
+};
+
+/**
+ * Number parsing and serializing utilities.
+ *
+ * @experimental
+ * @public
+ */
+declare const NumberUtils: NumberUtils;
+
+/**
+ * A class representation of the BSON ObjectId type.
+ * @public
+ * @category BSONType
+ */
+export declare class ObjectId extends BSONValue {
+    get _bsontype(): 'ObjectId';
+    /* Excluded from this release type: index */
+    static cacheHexString: boolean;
+    /* Excluded from this release type: buffer */
+    /** To generate a new ObjectId, use ObjectId() with no argument. */
+    constructor();
+    /**
+     * Create ObjectId from a 24 character hex string.
+     *
+     * @param inputId - A 24 character hex string.
+     */
+    constructor(inputId: string);
+    /**
+     * Create ObjectId from the BSON ObjectId type.
+     *
+     * @param inputId - The BSON ObjectId type.
+     */
+    constructor(inputId: ObjectId);
+    /**
+     * Create ObjectId from the object type that has the toHexString method.
+     *
+     * @param inputId - The ObjectIdLike type.
+     */
+    constructor(inputId: ObjectIdLike);
+    /**
+     * Create ObjectId from a 12 byte binary Buffer.
+     *
+     * @param inputId - A 12 byte binary Buffer.
+     */
+    constructor(inputId: Uint8Array);
+    /**
+     * Implementation overload.
+     *
+     * @param inputId - All input types that are used in the constructor implementation.
+     */
+    constructor(inputId?: string | ObjectId | ObjectIdLike | Uint8Array);
+    /**
+     * The ObjectId bytes
+     * @readonly
+     */
+    get id(): Uint8Array;
+    set id(value: Uint8Array);
+    /* Excluded from this release type: validateHexString */
+    /** Returns the ObjectId id as a 24 lowercase character hex string representation */
+    toHexString(): string;
+    /* Excluded from this release type: getInc */
+    /**
+     * Generate a 12 byte id buffer used in ObjectId's
+     *
+     * @param time - pass in a second based timestamp.
+     */
+    static generate(time?: number): Uint8Array;
+    /**
+     * Converts the id into a 24 character hex string for printing, unless encoding is provided.
+     * @param encoding - hex or base64
+     */
+    toString(encoding?: 'hex' | 'base64'): string;
+    /** Converts to its JSON the 24 character hex string representation. */
+    toJSON(): string;
+    /* Excluded from this release type: is */
+    /**
+     * Compares the equality of this ObjectId with `otherID`.
+     *
+     * @param otherId - ObjectId instance to compare against.
+     */
+    equals(otherId: string | ObjectId | ObjectIdLike | undefined | null): boolean;
+    /** Returns the generation date (accurate up to the second) that this ID was generated. */
+    getTimestamp(): Date;
+    /* Excluded from this release type: createPk */
+    /* Excluded from this release type: serializeInto */
+    /**
+     * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
+     *
+     * @param time - an integer number representing a number of seconds.
+     */
+    static createFromTime(time: number): ObjectId;
+    /**
+     * Creates an ObjectId from a hex string representation of an ObjectId.
+     *
+     * @param hexString - create a ObjectId from a passed in 24 character hexstring.
+     */
+    static createFromHexString(hexString: string): ObjectId;
+    /** Creates an ObjectId instance from a base64 string */
+    static createFromBase64(base64: string): ObjectId;
+    /**
+     * Checks if a value can be used to create a valid bson ObjectId
+     * @param id - any JS value
+     */
+    static isValid(id: string | ObjectId | ObjectIdLike | Uint8Array): boolean;
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    /* Excluded from this release type: isCached */
+    /**
+     * Converts to a string representation of this Id.
+     *
+     * @returns return the 24 character hex string representation.
+     */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface ObjectIdExtended {
+    $oid: string;
+}
+
+/** @public */
+export declare interface ObjectIdLike {
+    id: string | Uint8Array;
+    __id?: string;
+    toHexString(): string;
+}
+
+/**
+ * @experimental
+ * @public
+ *
+ * A new set of BSON APIs that are currently experimental and not intended for production use.
+ */
+export declare type OnDemand = {
+    parseToElements: (this: void, bytes: Uint8Array, startOffset?: number) => Iterable<BSONElement>;
+    BSONElement: BSONElement;
+    ByteUtils: ByteUtils;
+    NumberUtils: NumberUtils;
+};
+
+/**
+ * @experimental
+ * @public
+ */
+export declare const onDemand: OnDemand;
+
+/**
+ * Parse an Extended JSON string, constructing the JavaScript value or object described by that
+ * string.
+ *
+ * @example
+ * ```js
+ * const { EJSON } = require('bson');
+ * const text = '{ "int32": { "$numberInt": "10" } }';
+ *
+ * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
+ * console.log(EJSON.parse(text, { relaxed: false }));
+ *
+ * // prints { int32: 10 }
+ * console.log(EJSON.parse(text));
+ * ```
+ */
+declare function parse(text: string, options?: EJSONOptions): any;
+
+/**
+ * Serialize a Javascript object.
+ *
+ * @param object - the Javascript object to serialize.
+ * @returns Buffer object containing the serialized object.
+ * @public
+ */
+export declare function serialize(object: Document, options?: SerializeOptions): Uint8Array;
+
+/** @public */
+export declare interface SerializeOptions {
+    /**
+     * the serializer will check if keys are valid.
+     * @defaultValue `false`
+     */
+    checkKeys?: boolean;
+    /**
+     * serialize the javascript functions
+     * @defaultValue `false`
+     */
+    serializeFunctions?: boolean;
+    /**
+     * serialize will not emit undefined fields
+     * note that the driver sets this to `false`
+     * @defaultValue `true`
+     */
+    ignoreUndefined?: boolean;
+    /* Excluded from this release type: minInternalBufferSize */
+    /**
+     * the index in the buffer where we wish to start serializing into
+     * @defaultValue `0`
+     */
+    index?: number;
+}
+
+/**
+ * Serialize a Javascript object using a predefined Buffer and index into the buffer,
+ * useful when pre-allocating the space for serialization.
+ *
+ * @param object - the Javascript object to serialize.
+ * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object.
+ * @returns the index pointing to the last written byte in the buffer.
+ * @public
+ */
+export declare function serializeWithBufferAndIndex(object: Document, finalBuffer: Uint8Array, options?: SerializeOptions): number;
+
+/**
+ * Sets the size of the internal serialization buffer.
+ *
+ * @param size - The desired size for the internal serialization buffer in bytes
+ * @public
+ */
+export declare function setInternalBufferSize(size: number): void;
+
+/**
+ * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
+ * function is specified or optionally including only the specified properties if a replacer array
+ * is specified.
+ *
+ * @param value - The value to convert to extended JSON
+ * @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
+ * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
+ * @param options - Optional settings
+ *
+ * @example
+ * ```js
+ * const { EJSON } = require('bson');
+ * const Int32 = require('mongodb').Int32;
+ * const doc = { int32: new Int32(10) };
+ *
+ * // prints '{"int32":{"$numberInt":"10"}}'
+ * console.log(EJSON.stringify(doc, { relaxed: false }));
+ *
+ * // prints '{"int32":10}'
+ * console.log(EJSON.stringify(doc));
+ * ```
+ */
+declare function stringify(value: any, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSONOptions, space?: string | number, options?: EJSONOptions): string;
+
+/**
+ * @public
+ * @category BSONType
+ *
+ * A special type for _internal_ MongoDB use and is **not** associated with the regular Date type.
+ */
+export declare class Timestamp extends LongWithoutOverridesClass {
+    get _bsontype(): 'Timestamp';
+    get [bsonType](): 'Timestamp';
+    static readonly MAX_VALUE: Long;
+    /**
+     * An incrementing ordinal for operations within a given second.
+     */
+    get i(): number;
+    /**
+     * A `time_t` value measuring seconds since the Unix epoch
+     */
+    get t(): number;
+    /**
+     * @param int - A 64-bit bigint representing the Timestamp.
+     */
+    constructor(int: bigint);
+    /**
+     * @param long - A 64-bit Long representing the Timestamp.
+     */
+    constructor(long: Long);
+    /**
+     * @param value - A pair of two values indicating timestamp and increment.
+     */
+    constructor(value: {
+        t: number;
+        i: number;
+    });
+    toJSON(): {
+        $timestamp: string;
+    };
+    /** Returns a Timestamp represented by the given (32-bit) integer value. */
+    static fromInt(value: number): Timestamp;
+    /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */
+    static fromNumber(value: number): Timestamp;
+    /**
+     * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
+     *
+     * @param lowBits - the low 32-bits.
+     * @param highBits - the high 32-bits.
+     */
+    static fromBits(lowBits: number, highBits: number): Timestamp;
+    /**
+     * Returns a Timestamp from the given string, optionally using the given radix.
+     *
+     * @param str - the textual representation of the Timestamp.
+     * @param optRadix - the radix in which the text is written.
+     */
+    static fromString(str: string, optRadix: number): Timestamp;
+    /* Excluded from this release type: toExtendedJSON */
+    /* Excluded from this release type: fromExtendedJSON */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare interface TimestampExtended {
+    $timestamp: {
+        t: number;
+        i: number;
+    };
+}
+
+/** @public */
+export declare type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect' | typeof bsonType;
+
+/**
+ * A class representation of the BSON UUID type.
+ * @public
+ */
+export declare class UUID extends Binary {
+    /**
+     * Create a UUID type
+     *
+     * When the argument to the constructor is omitted a random v4 UUID will be generated.
+     *
+     * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
+     */
+    constructor(input?: string | Uint8Array | UUID);
+    /**
+     * The UUID bytes
+     * @readonly
+     */
+    get id(): Uint8Array;
+    set id(value: Uint8Array);
+    /**
+     * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
+     * @param includeDashes - should the string exclude dash-separators.
+     */
+    toHexString(includeDashes?: boolean): string;
+    /**
+     * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
+     */
+    toString(encoding?: 'hex' | 'base64'): string;
+    /**
+     * Converts the id into its JSON string representation.
+     * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+     */
+    toJSON(): string;
+    /**
+     * Compares the equality of this UUID with `otherID`.
+     *
+     * @param otherId - UUID instance to compare against.
+     */
+    equals(otherId: string | Uint8Array | UUID): boolean;
+    /**
+     * Creates a Binary instance from the current UUID.
+     */
+    toBinary(): Binary;
+    /**
+     * Generates a populated buffer containing a v4 uuid
+     */
+    static generate(): Uint8Array;
+    /**
+     * Checks if a value is a valid bson UUID
+     * @param input - UUID, string or Buffer to validate.
+     */
+    static isValid(input: string | Uint8Array | UUID | Binary): boolean;
+    /**
+     * Creates an UUID from a hex string representation of an UUID.
+     * @param hexString - 32 or 36 character hex string (dashes excluded/included).
+     */
+    static createFromHexString(hexString: string): UUID;
+    /** Creates an UUID from a base64 string representation of an UUID. */
+    static createFromBase64(base64: string): UUID;
+    /* Excluded from this release type: bytesFromString */
+    /* Excluded from this release type: isValidUUIDString */
+    /**
+     * Converts to a string representation of this Id.
+     *
+     * @returns return the 36 character hex string representation.
+     *
+     */
+    inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
+}
+
+/** @public */
+export declare type UUIDExtended = {
+    $uuid: string;
+};
+
+export { }

+ 19 - 0
node_modules/bson/etc/prepare.js

@@ -0,0 +1,19 @@
+#! /usr/bin/env node
+var cp = require('child_process');
+var fs = require('fs');
+
+var nodeMajorVersion = +process.version.match(/^v(\d+)\.\d+/)[1];
+
+if (fs.existsSync('src') && nodeMajorVersion >= 10) {
+  cp.spawnSync('npm', ['run', 'build'], { stdio: 'inherit', shell: true });
+} else {
+  if (!fs.existsSync('lib')) {
+    console.warn('BSON: No compiled javascript present, the library is not installed correctly.');
+    if (nodeMajorVersion < 10) {
+      console.warn(
+        'This library can only be compiled in nodejs version 10 or later, currently running: ' +
+          nodeMajorVersion
+      );
+    }
+  }
+}

+ 4675 - 0
node_modules/bson/lib/bson.bundle.js

@@ -0,0 +1,4675 @@
+var BSON = (function (exports) {
+'use strict';
+
+const TypedArrayPrototypeGetSymbolToStringTag = (() => {
+    const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
+    return (value) => g.call(value);
+})();
+function isUint8Array(value) {
+    return TypedArrayPrototypeGetSymbolToStringTag(value) === 'Uint8Array';
+}
+function isAnyArrayBuffer(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        (value[Symbol.toStringTag] === 'ArrayBuffer' ||
+            value[Symbol.toStringTag] === 'SharedArrayBuffer'));
+}
+function isRegExp(regexp) {
+    return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === '[object RegExp]';
+}
+function isMap(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        value[Symbol.toStringTag] === 'Map');
+}
+function isDate(date) {
+    return date instanceof Date || Object.prototype.toString.call(date) === '[object Date]';
+}
+function defaultInspect(x, _options) {
+    return JSON.stringify(x, (k, v) => {
+        if (typeof v === 'bigint') {
+            return { $numberLong: `${v}` };
+        }
+        else if (isMap(v)) {
+            return Object.fromEntries(v);
+        }
+        return v;
+    });
+}
+function getStylizeFunction(options) {
+    const stylizeExists = options != null &&
+        typeof options === 'object' &&
+        'stylize' in options &&
+        typeof options.stylize === 'function';
+    if (stylizeExists) {
+        return options.stylize;
+    }
+}
+
+const BSON_MAJOR_VERSION = 7;
+const BSON_VERSION_SYMBOL = Symbol.for('@@mdb.bson.version');
+const BSON_INT32_MAX = 0x7fffffff;
+const BSON_INT32_MIN = -2147483648;
+const BSON_INT64_MAX = Math.pow(2, 63) - 1;
+const BSON_INT64_MIN = -Math.pow(2, 63);
+const JS_INT_MAX = Math.pow(2, 53);
+const JS_INT_MIN = -Math.pow(2, 53);
+const BSON_DATA_NUMBER = 1;
+const BSON_DATA_STRING = 2;
+const BSON_DATA_OBJECT = 3;
+const BSON_DATA_ARRAY = 4;
+const BSON_DATA_BINARY = 5;
+const BSON_DATA_UNDEFINED = 6;
+const BSON_DATA_OID = 7;
+const BSON_DATA_BOOLEAN = 8;
+const BSON_DATA_DATE = 9;
+const BSON_DATA_NULL = 10;
+const BSON_DATA_REGEXP = 11;
+const BSON_DATA_DBPOINTER = 12;
+const BSON_DATA_CODE = 13;
+const BSON_DATA_SYMBOL = 14;
+const BSON_DATA_CODE_W_SCOPE = 15;
+const BSON_DATA_INT = 16;
+const BSON_DATA_TIMESTAMP = 17;
+const BSON_DATA_LONG = 18;
+const BSON_DATA_DECIMAL128 = 19;
+const BSON_DATA_MIN_KEY = 0xff;
+const BSON_DATA_MAX_KEY = 0x7f;
+const BSON_BINARY_SUBTYPE_DEFAULT = 0;
+const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
+const BSONType = Object.freeze({
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: -1,
+    maxKey: 127
+});
+
+class BSONError extends Error {
+    get bsonError() {
+        return true;
+    }
+    get name() {
+        return 'BSONError';
+    }
+    constructor(message, options) {
+        super(message, options);
+    }
+    static isBSONError(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            'bsonError' in value &&
+            value.bsonError === true &&
+            'name' in value &&
+            'message' in value &&
+            'stack' in value);
+    }
+}
+class BSONVersionError extends BSONError {
+    get name() {
+        return 'BSONVersionError';
+    }
+    constructor() {
+        super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
+    }
+}
+class BSONRuntimeError extends BSONError {
+    get name() {
+        return 'BSONRuntimeError';
+    }
+    constructor(message) {
+        super(message);
+    }
+}
+class BSONOffsetError extends BSONError {
+    get name() {
+        return 'BSONOffsetError';
+    }
+    offset;
+    constructor(message, offset, options) {
+        super(`${message}. offset: ${offset}`, options);
+        this.offset = offset;
+    }
+}
+
+let TextDecoderFatal;
+let TextDecoderNonFatal;
+function parseUtf8(buffer, start, end, fatal) {
+    if (fatal) {
+        TextDecoderFatal ??= new TextDecoder('utf8', { fatal: true });
+        try {
+            return TextDecoderFatal.decode(buffer.subarray(start, end));
+        }
+        catch (cause) {
+            throw new BSONError('Invalid UTF-8 string in BSON document', { cause });
+        }
+    }
+    TextDecoderNonFatal ??= new TextDecoder('utf8', { fatal: false });
+    return TextDecoderNonFatal.decode(buffer.subarray(start, end));
+}
+
+function tryReadBasicLatin(uint8array, start, end) {
+    if (uint8array.length === 0) {
+        return '';
+    }
+    const stringByteLength = end - start;
+    if (stringByteLength === 0) {
+        return '';
+    }
+    if (stringByteLength > 20) {
+        return null;
+    }
+    if (stringByteLength === 1 && uint8array[start] < 128) {
+        return String.fromCharCode(uint8array[start]);
+    }
+    if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
+        return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
+    }
+    if (stringByteLength === 3 &&
+        uint8array[start] < 128 &&
+        uint8array[start + 1] < 128 &&
+        uint8array[start + 2] < 128) {
+        return (String.fromCharCode(uint8array[start]) +
+            String.fromCharCode(uint8array[start + 1]) +
+            String.fromCharCode(uint8array[start + 2]));
+    }
+    const latinBytes = [];
+    for (let i = start; i < end; i++) {
+        const byte = uint8array[i];
+        if (byte > 127) {
+            return null;
+        }
+        latinBytes.push(byte);
+    }
+    return String.fromCharCode(...latinBytes);
+}
+function tryWriteBasicLatin(destination, source, offset) {
+    if (source.length === 0)
+        return 0;
+    if (source.length > 25)
+        return null;
+    if (destination.length - offset < source.length)
+        return null;
+    for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
+        const char = source.charCodeAt(charOffset);
+        if (char > 127)
+            return null;
+        destination[destinationOffset] = char;
+    }
+    return source.length;
+}
+
+function nodejsMathRandomBytes(byteLength) {
+    return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+function nodejsSecureRandomBytes(byteLength) {
+    return crypto.getRandomValues(nodeJsByteUtils.allocate(byteLength));
+}
+const nodejsRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return nodejsSecureRandomBytes;
+    }
+    else {
+        return nodejsMathRandomBytes;
+    }
+})();
+const nodeJsByteUtils = {
+    toLocalBufferType(potentialBuffer) {
+        if (Buffer.isBuffer(potentialBuffer)) {
+            return potentialBuffer;
+        }
+        if (ArrayBuffer.isView(potentialBuffer)) {
+            return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
+        }
+        const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return Buffer.from(potentialBuffer);
+        }
+        throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);
+    },
+    allocate(size) {
+        return Buffer.alloc(size);
+    },
+    allocateUnsafe(size) {
+        return Buffer.allocUnsafe(size);
+    },
+    equals(a, b) {
+        return nodeJsByteUtils.toLocalBufferType(a).equals(b);
+    },
+    fromNumberArray(array) {
+        return Buffer.from(array);
+    },
+    fromBase64(base64) {
+        return Buffer.from(base64, 'base64');
+    },
+    toBase64(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');
+    },
+    fromISO88591(codePoints) {
+        return Buffer.from(codePoints, 'binary');
+    },
+    toISO88591(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');
+    },
+    fromHex(hex) {
+        return Buffer.from(hex, 'hex');
+    },
+    toHex(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');
+    },
+    toUTF8(buffer, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
+        if (fatal) {
+            for (let i = 0; i < string.length; i++) {
+                if (string.charCodeAt(i) === 0xfffd) {
+                    parseUtf8(buffer, start, end, true);
+                    break;
+                }
+            }
+        }
+        return string;
+    },
+    utf8ByteLength(input) {
+        return Buffer.byteLength(input, 'utf8');
+    },
+    encodeUTF8Into(buffer, source, byteOffset) {
+        const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset);
+        if (latinBytesWritten != null) {
+            return latinBytesWritten;
+        }
+        return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
+    },
+    randomBytes: nodejsRandomBytes,
+    swap32(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).swap32();
+    }
+};
+
+function isReactNative() {
+    const { navigator } = globalThis;
+    return typeof navigator === 'object' && navigator.product === 'ReactNative';
+}
+function webMathRandomBytes(byteLength) {
+    if (byteLength < 0) {
+        throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
+    }
+    return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+const webRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return (byteLength) => {
+            return crypto.getRandomValues(webByteUtils.allocate(byteLength));
+        };
+    }
+    else {
+        if (isReactNative()) {
+            const { console } = globalThis;
+            console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');
+        }
+        return webMathRandomBytes;
+    }
+})();
+const HEX_DIGIT = /(\d|[a-f])/i;
+const webByteUtils = {
+    toLocalBufferType(potentialUint8array) {
+        const stringTag = potentialUint8array?.[Symbol.toStringTag] ??
+            Object.prototype.toString.call(potentialUint8array);
+        if (stringTag === 'Uint8Array') {
+            return potentialUint8array;
+        }
+        if (ArrayBuffer.isView(potentialUint8array)) {
+            return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
+        }
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return new Uint8Array(potentialUint8array);
+        }
+        throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);
+    },
+    allocate(size) {
+        if (typeof size !== 'number') {
+            throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
+        }
+        return new Uint8Array(size);
+    },
+    allocateUnsafe(size) {
+        return webByteUtils.allocate(size);
+    },
+    equals(a, b) {
+        if (a.byteLength !== b.byteLength) {
+            return false;
+        }
+        for (let i = 0; i < a.byteLength; i++) {
+            if (a[i] !== b[i]) {
+                return false;
+            }
+        }
+        return true;
+    },
+    fromNumberArray(array) {
+        return Uint8Array.from(array);
+    },
+    fromBase64(base64) {
+        return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
+    },
+    toBase64(uint8array) {
+        return btoa(webByteUtils.toISO88591(uint8array));
+    },
+    fromISO88591(codePoints) {
+        return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);
+    },
+    toISO88591(uint8array) {
+        return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');
+    },
+    fromHex(hex) {
+        const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
+        const buffer = [];
+        for (let i = 0; i < evenLengthHex.length; i += 2) {
+            const firstDigit = evenLengthHex[i];
+            const secondDigit = evenLengthHex[i + 1];
+            if (!HEX_DIGIT.test(firstDigit)) {
+                break;
+            }
+            if (!HEX_DIGIT.test(secondDigit)) {
+                break;
+            }
+            const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
+            buffer.push(hexDigit);
+        }
+        return Uint8Array.from(buffer);
+    },
+    toHex(uint8array) {
+        return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
+    },
+    toUTF8(uint8array, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        return parseUtf8(uint8array, start, end, fatal);
+    },
+    utf8ByteLength(input) {
+        return new TextEncoder().encode(input).byteLength;
+    },
+    encodeUTF8Into(uint8array, source, byteOffset) {
+        const bytes = new TextEncoder().encode(source);
+        uint8array.set(bytes, byteOffset);
+        return bytes.byteLength;
+    },
+    randomBytes: webRandomBytes,
+    swap32(buffer) {
+        if (buffer.length % 4 !== 0) {
+            throw new RangeError('Buffer size must be a multiple of 32-bits');
+        }
+        for (let i = 0; i < buffer.length; i += 4) {
+            const byte0 = buffer[i];
+            const byte1 = buffer[i + 1];
+            const byte2 = buffer[i + 2];
+            const byte3 = buffer[i + 3];
+            buffer[i] = byte3;
+            buffer[i + 1] = byte2;
+            buffer[i + 2] = byte1;
+            buffer[i + 3] = byte0;
+        }
+        return buffer;
+    }
+};
+
+const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
+const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
+
+const bsonType = Symbol.for('@@mdb.bson.type');
+class BSONValue {
+    get [bsonType]() {
+        return this._bsontype;
+    }
+    get [BSON_VERSION_SYMBOL]() {
+        return BSON_MAJOR_VERSION;
+    }
+    [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) {
+        return this.inspect(depth, options, inspect);
+    }
+}
+
+const FLOAT = new Float64Array(1);
+const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
+FLOAT[0] = -1;
+const isBigEndian = FLOAT_BYTES[7] === 0;
+const NumberUtils = {
+    isBigEndian,
+    getNonnegativeInt32LE(source, offset) {
+        if (source[offset + 3] > 127) {
+            throw new RangeError(`Size cannot be negative at offset: ${offset}`);
+        }
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getInt32LE(source, offset) {
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getUint32LE(source, offset) {
+        return (source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+    },
+    getUint32BE(source, offset) {
+        return (source[offset + 3] +
+            source[offset + 2] * 256 +
+            source[offset + 1] * 65536 +
+            source[offset] * 16777216);
+    },
+    getBigInt64LE(source, offset) {
+        const hi = BigInt(source[offset + 4] +
+            source[offset + 5] * 256 +
+            source[offset + 6] * 65536 +
+            (source[offset + 7] << 24));
+        const lo = BigInt(source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+        return (hi << 32n) + lo;
+    },
+    getFloat64LE: isBigEndian
+        ? (source, offset) => {
+            FLOAT_BYTES[7] = source[offset];
+            FLOAT_BYTES[6] = source[offset + 1];
+            FLOAT_BYTES[5] = source[offset + 2];
+            FLOAT_BYTES[4] = source[offset + 3];
+            FLOAT_BYTES[3] = source[offset + 4];
+            FLOAT_BYTES[2] = source[offset + 5];
+            FLOAT_BYTES[1] = source[offset + 6];
+            FLOAT_BYTES[0] = source[offset + 7];
+            return FLOAT[0];
+        }
+        : (source, offset) => {
+            FLOAT_BYTES[0] = source[offset];
+            FLOAT_BYTES[1] = source[offset + 1];
+            FLOAT_BYTES[2] = source[offset + 2];
+            FLOAT_BYTES[3] = source[offset + 3];
+            FLOAT_BYTES[4] = source[offset + 4];
+            FLOAT_BYTES[5] = source[offset + 5];
+            FLOAT_BYTES[6] = source[offset + 6];
+            FLOAT_BYTES[7] = source[offset + 7];
+            return FLOAT[0];
+        },
+    setInt32BE(destination, offset, value) {
+        destination[offset + 3] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset] = value;
+        return 4;
+    },
+    setInt32LE(destination, offset, value) {
+        destination[offset] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 3] = value;
+        return 4;
+    },
+    setBigInt64LE(destination, offset, value) {
+        const mask32bits = 0xffffffffn;
+        let lo = Number(value & mask32bits);
+        destination[offset] = lo;
+        lo >>= 8;
+        destination[offset + 1] = lo;
+        lo >>= 8;
+        destination[offset + 2] = lo;
+        lo >>= 8;
+        destination[offset + 3] = lo;
+        let hi = Number((value >> 32n) & mask32bits);
+        destination[offset + 4] = hi;
+        hi >>= 8;
+        destination[offset + 5] = hi;
+        hi >>= 8;
+        destination[offset + 6] = hi;
+        hi >>= 8;
+        destination[offset + 7] = hi;
+        return 8;
+    },
+    setFloat64LE: isBigEndian
+        ? (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[7];
+            destination[offset + 1] = FLOAT_BYTES[6];
+            destination[offset + 2] = FLOAT_BYTES[5];
+            destination[offset + 3] = FLOAT_BYTES[4];
+            destination[offset + 4] = FLOAT_BYTES[3];
+            destination[offset + 5] = FLOAT_BYTES[2];
+            destination[offset + 6] = FLOAT_BYTES[1];
+            destination[offset + 7] = FLOAT_BYTES[0];
+            return 8;
+        }
+        : (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[0];
+            destination[offset + 1] = FLOAT_BYTES[1];
+            destination[offset + 2] = FLOAT_BYTES[2];
+            destination[offset + 3] = FLOAT_BYTES[3];
+            destination[offset + 4] = FLOAT_BYTES[4];
+            destination[offset + 5] = FLOAT_BYTES[5];
+            destination[offset + 6] = FLOAT_BYTES[6];
+            destination[offset + 7] = FLOAT_BYTES[7];
+            return 8;
+        }
+};
+
+class Binary extends BSONValue {
+    get _bsontype() {
+        return 'Binary';
+    }
+    static BSON_BINARY_SUBTYPE_DEFAULT = 0;
+    static BUFFER_SIZE = 256;
+    static SUBTYPE_DEFAULT = 0;
+    static SUBTYPE_FUNCTION = 1;
+    static SUBTYPE_BYTE_ARRAY = 2;
+    static SUBTYPE_UUID_OLD = 3;
+    static SUBTYPE_UUID = 4;
+    static SUBTYPE_MD5 = 5;
+    static SUBTYPE_ENCRYPTED = 6;
+    static SUBTYPE_COLUMN = 7;
+    static SUBTYPE_SENSITIVE = 8;
+    static SUBTYPE_VECTOR = 9;
+    static SUBTYPE_USER_DEFINED = 128;
+    static VECTOR_TYPE = Object.freeze({
+        Int8: 0x03,
+        Float32: 0x27,
+        PackedBit: 0x10
+    });
+    buffer;
+    sub_type;
+    position;
+    constructor(buffer, subType) {
+        super();
+        if (!(buffer == null) &&
+            typeof buffer === 'string' &&
+            !ArrayBuffer.isView(buffer) &&
+            !isAnyArrayBuffer(buffer) &&
+            !Array.isArray(buffer)) {
+            throw new BSONError('Binary can only be constructed from Uint8Array or number[]');
+        }
+        this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
+        if (buffer == null) {
+            this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
+            this.position = 0;
+        }
+        else {
+            this.buffer = Array.isArray(buffer)
+                ? ByteUtils.fromNumberArray(buffer)
+                : ByteUtils.toLocalBufferType(buffer);
+            this.position = this.buffer.byteLength;
+        }
+    }
+    put(byteValue) {
+        if (typeof byteValue === 'string' && byteValue.length !== 1) {
+            throw new BSONError('only accepts single character String');
+        }
+        else if (typeof byteValue !== 'number' && byteValue.length !== 1)
+            throw new BSONError('only accepts single character Uint8Array or Array');
+        let decodedByte;
+        if (typeof byteValue === 'string') {
+            decodedByte = byteValue.charCodeAt(0);
+        }
+        else if (typeof byteValue === 'number') {
+            decodedByte = byteValue;
+        }
+        else {
+            decodedByte = byteValue[0];
+        }
+        if (decodedByte < 0 || decodedByte > 255) {
+            throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
+        }
+        if (this.buffer.byteLength > this.position) {
+            this.buffer[this.position++] = decodedByte;
+        }
+        else {
+            const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+            this.buffer[this.position++] = decodedByte;
+        }
+    }
+    write(sequence, offset) {
+        offset = typeof offset === 'number' ? offset : this.position;
+        if (this.buffer.byteLength < offset + sequence.length) {
+            const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+        }
+        if (ArrayBuffer.isView(sequence)) {
+            this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
+            this.position =
+                offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
+        }
+        else if (typeof sequence === 'string') {
+            throw new BSONError('input cannot be string');
+        }
+    }
+    read(position, length) {
+        length = length && length > 0 ? length : this.position;
+        const end = position + length;
+        return this.buffer.subarray(position, end > this.position ? this.position : end);
+    }
+    value() {
+        return this.buffer.length === this.position
+            ? this.buffer
+            : this.buffer.subarray(0, this.position);
+    }
+    length() {
+        return this.position;
+    }
+    toJSON() {
+        return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.buffer.subarray(0, this.position));
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        if (encoding === 'utf8' || encoding === 'utf-8')
+            return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+        return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (this.sub_type === Binary.SUBTYPE_VECTOR) {
+            validateBinaryVector(this);
+        }
+        const base64String = ByteUtils.toBase64(this.buffer);
+        const subType = Number(this.sub_type).toString(16);
+        if (options.legacy) {
+            return {
+                $binary: base64String,
+                $type: subType.length === 1 ? '0' + subType : subType
+            };
+        }
+        return {
+            $binary: {
+                base64: base64String,
+                subType: subType.length === 1 ? '0' + subType : subType
+            }
+        };
+    }
+    toUUID() {
+        if (this.sub_type === Binary.SUBTYPE_UUID) {
+            return new UUID(this.buffer.subarray(0, this.position));
+        }
+        throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
+    }
+    static createFromHexString(hex, subType) {
+        return new Binary(ByteUtils.fromHex(hex), subType);
+    }
+    static createFromBase64(base64, subType) {
+        return new Binary(ByteUtils.fromBase64(base64), subType);
+    }
+    static fromExtendedJSON(doc, options) {
+        options = options || {};
+        let data;
+        let type;
+        if ('$binary' in doc) {
+            if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
+                type = doc.$type ? parseInt(doc.$type, 16) : 0;
+                data = ByteUtils.fromBase64(doc.$binary);
+            }
+            else {
+                if (typeof doc.$binary !== 'string') {
+                    type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
+                    data = ByteUtils.fromBase64(doc.$binary.base64);
+                }
+            }
+        }
+        else if ('$uuid' in doc) {
+            type = 4;
+            data = UUID.bytesFromString(doc.$uuid);
+        }
+        if (!data) {
+            throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
+        }
+        return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        const base64Arg = inspect(base64, options);
+        const subTypeArg = inspect(this.sub_type, options);
+        return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
+    }
+    toInt8Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {
+            throw new BSONError('Binary datatype field is not Int8');
+        }
+        validateBinaryVector(this);
+        return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toFloat32Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {
+            throw new BSONError('Binary datatype field is not Float32');
+        }
+        validateBinaryVector(this);
+        const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(floatBytes);
+        return new Float32Array(floatBytes.buffer);
+    }
+    toPackedBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        const byteCount = this.length() - 2;
+        const bitCount = byteCount * 8 - this.buffer[1];
+        const bits = new Int8Array(bitCount);
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = (bitOffset / 8) | 0;
+            const byte = this.buffer[byteOffset + 2];
+            const shift = 7 - (bitOffset % 8);
+            const bit = (byte >> shift) & 1;
+            bits[bitOffset] = bit;
+        }
+        return bits;
+    }
+    static fromInt8Array(array) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.Int8;
+        buffer[1] = 0;
+        const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        buffer.set(intBytes, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromFloat32Array(array) {
+        const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
+        binaryBytes[0] = Binary.VECTOR_TYPE.Float32;
+        binaryBytes[1] = 0;
+        const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        binaryBytes.set(floatBytes, 2);
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
+        const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromPackedBits(array, padding = 0) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.PackedBit;
+        buffer[1] = padding;
+        buffer.set(array, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromBits(bits) {
+        const byteLength = (bits.length + 7) >>> 3;
+        const bytes = new Uint8Array(byteLength + 2);
+        bytes[0] = Binary.VECTOR_TYPE.PackedBit;
+        const remainder = bits.length % 8;
+        bytes[1] = remainder === 0 ? 0 : 8 - remainder;
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = bitOffset >>> 3;
+            const bit = bits[bitOffset];
+            if (bit !== 0 && bit !== 1) {
+                throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
+            }
+            if (bit === 0)
+                continue;
+            const shift = 7 - (bitOffset % 8);
+            bytes[byteOffset + 2] |= bit << shift;
+        }
+        return new this(bytes, Binary.SUBTYPE_VECTOR);
+    }
+}
+function validateBinaryVector(vector) {
+    if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
+        return;
+    const size = vector.position;
+    const datatype = vector.buffer[0];
+    const padding = vector.buffer[1];
+    if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) &&
+        padding !== 0) {
+        throw new BSONError('Invalid Vector: padding must be zero for int8 and float32 vectors');
+    }
+    if (datatype === Binary.VECTOR_TYPE.Float32) {
+        if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
+            throw new BSONError('Invalid Vector: Float32 vector must contain a multiple of 4 bytes');
+        }
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
+        throw new BSONError('Invalid Vector: padding must be zero for packed bit vectors that are empty');
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
+        throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
+    }
+}
+const UUID_BYTE_LENGTH = 16;
+const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
+const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
+class UUID extends Binary {
+    constructor(input) {
+        let bytes;
+        if (input == null) {
+            bytes = UUID.generate();
+        }
+        else if (input instanceof UUID) {
+            bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
+        }
+        else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
+            bytes = ByteUtils.toLocalBufferType(input);
+        }
+        else if (typeof input === 'string') {
+            bytes = UUID.bytesFromString(input);
+        }
+        else {
+            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).');
+        }
+        super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+    }
+    toHexString(includeDashes = true) {
+        if (includeDashes) {
+            return [
+                ByteUtils.toHex(this.buffer.subarray(0, 4)),
+                ByteUtils.toHex(this.buffer.subarray(4, 6)),
+                ByteUtils.toHex(this.buffer.subarray(6, 8)),
+                ByteUtils.toHex(this.buffer.subarray(8, 10)),
+                ByteUtils.toHex(this.buffer.subarray(10, 16))
+            ].join('-');
+        }
+        return ByteUtils.toHex(this.buffer);
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.id);
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    equals(otherId) {
+        if (!otherId) {
+            return false;
+        }
+        if (otherId instanceof UUID) {
+            return ByteUtils.equals(otherId.id, this.id);
+        }
+        try {
+            return ByteUtils.equals(new UUID(otherId).id, this.id);
+        }
+        catch {
+            return false;
+        }
+    }
+    toBinary() {
+        return new Binary(this.id, Binary.SUBTYPE_UUID);
+    }
+    static generate() {
+        const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
+        bytes[6] = (bytes[6] & 0x0f) | 0x40;
+        bytes[8] = (bytes[8] & 0x3f) | 0x80;
+        return bytes;
+    }
+    static isValid(input) {
+        if (!input) {
+            return false;
+        }
+        if (typeof input === 'string') {
+            return UUID.isValidUUIDString(input);
+        }
+        if (isUint8Array(input)) {
+            return input.byteLength === UUID_BYTE_LENGTH;
+        }
+        return (input._bsontype === 'Binary' &&
+            input.sub_type === this.SUBTYPE_UUID &&
+            input.buffer.byteLength === 16);
+    }
+    static createFromHexString(hexString) {
+        const buffer = UUID.bytesFromString(hexString);
+        return new UUID(buffer);
+    }
+    static createFromBase64(base64) {
+        return new UUID(ByteUtils.fromBase64(base64));
+    }
+    static bytesFromString(representation) {
+        if (!UUID.isValidUUIDString(representation)) {
+            throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
+        }
+        return ByteUtils.fromHex(representation.replace(/-/g, ''));
+    }
+    static isValidUUIDString(representation) {
+        return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new UUID(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+class Code extends BSONValue {
+    get _bsontype() {
+        return 'Code';
+    }
+    code;
+    scope;
+    constructor(code, scope) {
+        super();
+        this.code = code.toString();
+        this.scope = scope ?? null;
+    }
+    toJSON() {
+        if (this.scope != null) {
+            return { code: this.code, scope: this.scope };
+        }
+        return { code: this.code };
+    }
+    toExtendedJSON() {
+        if (this.scope) {
+            return { $code: this.code, $scope: this.scope };
+        }
+        return { $code: this.code };
+    }
+    static fromExtendedJSON(doc) {
+        return new Code(doc.$code, doc.$scope);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        let parametersString = inspect(this.code, options);
+        const multiLineFn = parametersString.includes('\n');
+        if (this.scope != null) {
+            parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
+        }
+        const endingNewline = multiLineFn && this.scope === null;
+        return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
+    }
+}
+
+function isDBRefLike(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '$id' in value &&
+        value.$id != null &&
+        '$ref' in value &&
+        typeof value.$ref === 'string' &&
+        (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));
+}
+class DBRef extends BSONValue {
+    get _bsontype() {
+        return 'DBRef';
+    }
+    collection;
+    oid;
+    db;
+    fields;
+    constructor(collection, oid, db, fields) {
+        super();
+        const parts = collection.split('.');
+        if (parts.length === 2) {
+            db = parts.shift();
+            collection = parts.shift();
+        }
+        this.collection = collection;
+        this.oid = oid;
+        this.db = db;
+        this.fields = fields || {};
+    }
+    get namespace() {
+        return this.collection;
+    }
+    set namespace(value) {
+        this.collection = value;
+    }
+    toJSON() {
+        const o = Object.assign({
+            $ref: this.collection,
+            $id: this.oid
+        }, this.fields);
+        if (this.db != null)
+            o.$db = this.db;
+        return o;
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        let o = {
+            $ref: this.collection,
+            $id: this.oid
+        };
+        if (options.legacy) {
+            return o;
+        }
+        if (this.db)
+            o.$db = this.db;
+        o = Object.assign(o, this.fields);
+        return o;
+    }
+    static fromExtendedJSON(doc) {
+        const copy = Object.assign({}, doc);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const args = [
+            inspect(this.namespace, options),
+            inspect(this.oid, options),
+            ...(this.db ? [inspect(this.db, options)] : []),
+            ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
+        ];
+        args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
+        return `new DBRef(${args.join(', ')})`;
+    }
+}
+
+function removeLeadingZerosAndExplicitPlus(str) {
+    if (str === '') {
+        return str;
+    }
+    let startIndex = 0;
+    const isNegative = str[startIndex] === '-';
+    const isExplicitlyPositive = str[startIndex] === '+';
+    if (isExplicitlyPositive || isNegative) {
+        startIndex += 1;
+    }
+    let foundInsignificantZero = false;
+    for (; startIndex < str.length && str[startIndex] === '0'; ++startIndex) {
+        foundInsignificantZero = true;
+    }
+    if (!foundInsignificantZero) {
+        return isExplicitlyPositive ? str.slice(1) : str;
+    }
+    return `${isNegative ? '-' : ''}${str.length === startIndex ? '0' : str.slice(startIndex)}`;
+}
+function validateStringCharacters(str, radix) {
+    radix = radix ?? 10;
+    const validCharacters = '0123456789abcdefghijklmnopqrstuvwxyz'.slice(0, radix);
+    const regex = new RegExp(`[^-+${validCharacters}]`, 'i');
+    return regex.test(str) ? false : str;
+}
+
+let wasm = undefined;
+try {
+    wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
+}
+catch {
+}
+const TWO_PWR_16_DBL = 1 << 16;
+const TWO_PWR_24_DBL = 1 << 24;
+const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
+const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
+const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
+const INT_CACHE = {};
+const UINT_CACHE = {};
+const MAX_INT64_STRING_LENGTH = 20;
+const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
+class Long extends BSONValue {
+    get _bsontype() {
+        return 'Long';
+    }
+    get __isLong__() {
+        return true;
+    }
+    high;
+    low;
+    unsigned;
+    constructor(lowOrValue = 0, highOrUnsigned, unsigned) {
+        super();
+        const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);
+        const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;
+        const res = typeof lowOrValue === 'string'
+            ? Long.fromString(lowOrValue, unsignedBool)
+            : typeof lowOrValue === 'bigint'
+                ? Long.fromBigInt(lowOrValue, unsignedBool)
+                : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
+        this.low = res.low;
+        this.high = res.high;
+        this.unsigned = res.unsigned;
+    }
+    static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
+    static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
+    static ZERO = Long.fromInt(0);
+    static UZERO = Long.fromInt(0, true);
+    static ONE = Long.fromInt(1);
+    static UONE = Long.fromInt(1, true);
+    static NEG_ONE = Long.fromInt(-1);
+    static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
+    static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
+    static fromBits(lowBits, highBits, unsigned) {
+        return new Long(lowBits, highBits, unsigned);
+    }
+    static fromInt(value, unsigned) {
+        let obj, cachedObj, cache;
+        if (unsigned) {
+            value >>>= 0;
+            if ((cache = 0 <= value && value < 256)) {
+                cachedObj = UINT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
+            if (cache)
+                UINT_CACHE[value] = obj;
+            return obj;
+        }
+        else {
+            value |= 0;
+            if ((cache = -128 <= value && value < 128)) {
+                cachedObj = INT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
+            if (cache)
+                INT_CACHE[value] = obj;
+            return obj;
+        }
+    }
+    static fromNumber(value, unsigned) {
+        if (isNaN(value))
+            return unsigned ? Long.UZERO : Long.ZERO;
+        if (unsigned) {
+            if (value < 0)
+                return Long.UZERO;
+            if (value >= TWO_PWR_64_DBL)
+                return Long.MAX_UNSIGNED_VALUE;
+        }
+        else {
+            if (value <= -TWO_PWR_63_DBL)
+                return Long.MIN_VALUE;
+            if (value + 1 >= TWO_PWR_63_DBL)
+                return Long.MAX_VALUE;
+        }
+        if (value < 0)
+            return Long.fromNumber(-value, unsigned).neg();
+        return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
+    }
+    static fromBigInt(value, unsigned) {
+        const FROM_BIGINT_BIT_MASK = 0xffffffffn;
+        const FROM_BIGINT_BIT_SHIFT = 32n;
+        return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number((value >> FROM_BIGINT_BIT_SHIFT) & FROM_BIGINT_BIT_MASK), unsigned);
+    }
+    static _fromString(str, unsigned, radix) {
+        if (str.length === 0)
+            throw new BSONError('empty string');
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        let p;
+        if ((p = str.indexOf('-')) > 0)
+            throw new BSONError('interior hyphen');
+        else if (p === 0) {
+            return Long._fromString(str.substring(1), unsigned, radix).neg();
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 8));
+        let result = Long.ZERO;
+        for (let i = 0; i < str.length; i += 8) {
+            const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
+            if (size < 8) {
+                const power = Long.fromNumber(Math.pow(radix, size));
+                result = result.mul(power).add(Long.fromNumber(value));
+            }
+            else {
+                result = result.mul(radixToPower);
+                result = result.add(Long.fromNumber(value));
+            }
+        }
+        result.unsigned = unsigned;
+        return result;
+    }
+    static fromStringStrict(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str.trim() !== str) {
+            throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
+        }
+        if (!validateStringCharacters(str, radix)) {
+            throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
+        }
+        const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
+        const result = Long._fromString(cleanedStr, unsigned, radix);
+        if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
+            throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? 'an unsigned' : 'a signed'} 64-bit Long ${radix != null ? `with radix: ${radix}` : ''}`);
+        }
+        return result;
+    }
+    static fromString(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str === 'NaN' && radix < 24) {
+            return Long.ZERO;
+        }
+        else if ((str === 'Infinity' || str === '+Infinity' || str === '-Infinity') && radix < 35) {
+            return Long.ZERO;
+        }
+        return Long._fromString(str, unsigned, radix);
+    }
+    static fromBytes(bytes, unsigned, le) {
+        return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
+    }
+    static fromBytesLE(bytes, unsigned) {
+        return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned);
+    }
+    static fromBytesBE(bytes, unsigned) {
+        return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned);
+    }
+    static isLong(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            '__isLong__' in value &&
+            value.__isLong__ === true);
+    }
+    static fromValue(val, unsigned) {
+        if (typeof val === 'number')
+            return Long.fromNumber(val, unsigned);
+        if (typeof val === 'string')
+            return Long.fromString(val, unsigned);
+        return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
+    }
+    add(addend) {
+        if (!Long.isLong(addend))
+            addend = Long.fromValue(addend);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = addend.high >>> 16;
+        const b32 = addend.high & 0xffff;
+        const b16 = addend.low >>> 16;
+        const b00 = addend.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 + b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 + b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 + b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 + b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    and(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
+    }
+    compare(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.eq(other))
+            return 0;
+        const thisNeg = this.isNegative(), otherNeg = other.isNegative();
+        if (thisNeg && !otherNeg)
+            return -1;
+        if (!thisNeg && otherNeg)
+            return 1;
+        if (!this.unsigned)
+            return this.sub(other).isNegative() ? -1 : 1;
+        return other.high >>> 0 > this.high >>> 0 ||
+            (other.high === this.high && other.low >>> 0 > this.low >>> 0)
+            ? -1
+            : 1;
+    }
+    comp(other) {
+        return this.compare(other);
+    }
+    divide(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (divisor.isZero())
+            throw new BSONError('division by zero');
+        if (wasm) {
+            if (!this.unsigned &&
+                this.high === -2147483648 &&
+                divisor.low === -1 &&
+                divisor.high === -1) {
+                return this;
+            }
+            const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (this.isZero())
+            return this.unsigned ? Long.UZERO : Long.ZERO;
+        let approx, rem, res;
+        if (!this.unsigned) {
+            if (this.eq(Long.MIN_VALUE)) {
+                if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
+                    return Long.MIN_VALUE;
+                else if (divisor.eq(Long.MIN_VALUE))
+                    return Long.ONE;
+                else {
+                    const halfThis = this.shr(1);
+                    approx = halfThis.div(divisor).shl(1);
+                    if (approx.eq(Long.ZERO)) {
+                        return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
+                    }
+                    else {
+                        rem = this.sub(divisor.mul(approx));
+                        res = approx.add(rem.div(divisor));
+                        return res;
+                    }
+                }
+            }
+            else if (divisor.eq(Long.MIN_VALUE))
+                return this.unsigned ? Long.UZERO : Long.ZERO;
+            if (this.isNegative()) {
+                if (divisor.isNegative())
+                    return this.neg().div(divisor.neg());
+                return this.neg().div(divisor).neg();
+            }
+            else if (divisor.isNegative())
+                return this.div(divisor.neg()).neg();
+            res = Long.ZERO;
+        }
+        else {
+            if (!divisor.unsigned)
+                divisor = divisor.toUnsigned();
+            if (divisor.gt(this))
+                return Long.UZERO;
+            if (divisor.gt(this.shru(1)))
+                return Long.UONE;
+            res = Long.UZERO;
+        }
+        rem = this;
+        while (rem.gte(divisor)) {
+            approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
+            const log2 = Math.ceil(Math.log(approx) / Math.LN2);
+            const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
+            let approxRes = Long.fromNumber(approx);
+            let approxRem = approxRes.mul(divisor);
+            while (approxRem.isNegative() || approxRem.gt(rem)) {
+                approx -= delta;
+                approxRes = Long.fromNumber(approx, this.unsigned);
+                approxRem = approxRes.mul(divisor);
+            }
+            if (approxRes.isZero())
+                approxRes = Long.ONE;
+            res = res.add(approxRes);
+            rem = rem.sub(approxRem);
+        }
+        return res;
+    }
+    div(divisor) {
+        return this.divide(divisor);
+    }
+    equals(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
+            return false;
+        return this.high === other.high && this.low === other.low;
+    }
+    eq(other) {
+        return this.equals(other);
+    }
+    getHighBits() {
+        return this.high;
+    }
+    getHighBitsUnsigned() {
+        return this.high >>> 0;
+    }
+    getLowBits() {
+        return this.low;
+    }
+    getLowBitsUnsigned() {
+        return this.low >>> 0;
+    }
+    getNumBitsAbs() {
+        if (this.isNegative()) {
+            return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
+        }
+        const val = this.high !== 0 ? this.high : this.low;
+        let bit;
+        for (bit = 31; bit > 0; bit--)
+            if ((val & (1 << bit)) !== 0)
+                break;
+        return this.high !== 0 ? bit + 33 : bit + 1;
+    }
+    greaterThan(other) {
+        return this.comp(other) > 0;
+    }
+    gt(other) {
+        return this.greaterThan(other);
+    }
+    greaterThanOrEqual(other) {
+        return this.comp(other) >= 0;
+    }
+    gte(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    ge(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    isEven() {
+        return (this.low & 1) === 0;
+    }
+    isNegative() {
+        return !this.unsigned && this.high < 0;
+    }
+    isOdd() {
+        return (this.low & 1) === 1;
+    }
+    isPositive() {
+        return this.unsigned || this.high >= 0;
+    }
+    isZero() {
+        return this.high === 0 && this.low === 0;
+    }
+    lessThan(other) {
+        return this.comp(other) < 0;
+    }
+    lt(other) {
+        return this.lessThan(other);
+    }
+    lessThanOrEqual(other) {
+        return this.comp(other) <= 0;
+    }
+    lte(other) {
+        return this.lessThanOrEqual(other);
+    }
+    modulo(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (wasm) {
+            const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        return this.sub(this.div(divisor).mul(divisor));
+    }
+    mod(divisor) {
+        return this.modulo(divisor);
+    }
+    rem(divisor) {
+        return this.modulo(divisor);
+    }
+    multiply(multiplier) {
+        if (this.isZero())
+            return Long.ZERO;
+        if (!Long.isLong(multiplier))
+            multiplier = Long.fromValue(multiplier);
+        if (wasm) {
+            const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (multiplier.isZero())
+            return Long.ZERO;
+        if (this.eq(Long.MIN_VALUE))
+            return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (multiplier.eq(Long.MIN_VALUE))
+            return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (this.isNegative()) {
+            if (multiplier.isNegative())
+                return this.neg().mul(multiplier.neg());
+            else
+                return this.neg().mul(multiplier).neg();
+        }
+        else if (multiplier.isNegative())
+            return this.mul(multiplier.neg()).neg();
+        if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
+            return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = multiplier.high >>> 16;
+        const b32 = multiplier.high & 0xffff;
+        const b16 = multiplier.low >>> 16;
+        const b00 = multiplier.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 * b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 * b00;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c16 += a00 * b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 * b00;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a16 * b16;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a00 * b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    mul(multiplier) {
+        return this.multiply(multiplier);
+    }
+    negate() {
+        if (!this.unsigned && this.eq(Long.MIN_VALUE))
+            return Long.MIN_VALUE;
+        return this.not().add(Long.ONE);
+    }
+    neg() {
+        return this.negate();
+    }
+    not() {
+        return Long.fromBits(~this.low, ~this.high, this.unsigned);
+    }
+    notEquals(other) {
+        return !this.equals(other);
+    }
+    neq(other) {
+        return this.notEquals(other);
+    }
+    ne(other) {
+        return this.notEquals(other);
+    }
+    or(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
+    }
+    shiftLeft(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
+        else
+            return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
+    }
+    shl(numBits) {
+        return this.shiftLeft(numBits);
+    }
+    shiftRight(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
+        else
+            return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
+    }
+    shr(numBits) {
+        return this.shiftRight(numBits);
+    }
+    shiftRightUnsigned(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        numBits &= 63;
+        if (numBits === 0)
+            return this;
+        else {
+            const high = this.high;
+            if (numBits < 32) {
+                const low = this.low;
+                return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
+            }
+            else if (numBits === 32)
+                return Long.fromBits(high, 0, this.unsigned);
+            else
+                return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
+        }
+    }
+    shr_u(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    shru(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    subtract(subtrahend) {
+        if (!Long.isLong(subtrahend))
+            subtrahend = Long.fromValue(subtrahend);
+        return this.add(subtrahend.neg());
+    }
+    sub(subtrahend) {
+        return this.subtract(subtrahend);
+    }
+    toInt() {
+        return this.unsigned ? this.low >>> 0 : this.low;
+    }
+    toNumber() {
+        if (this.unsigned)
+            return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
+        return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
+    }
+    toBigInt() {
+        return BigInt(this.toString());
+    }
+    toBytes(le) {
+        return le ? this.toBytesLE() : this.toBytesBE();
+    }
+    toBytesLE() {
+        const hi = this.high, lo = this.low;
+        return [
+            lo & 0xff,
+            (lo >>> 8) & 0xff,
+            (lo >>> 16) & 0xff,
+            lo >>> 24,
+            hi & 0xff,
+            (hi >>> 8) & 0xff,
+            (hi >>> 16) & 0xff,
+            hi >>> 24
+        ];
+    }
+    toBytesBE() {
+        const hi = this.high, lo = this.low;
+        return [
+            hi >>> 24,
+            (hi >>> 16) & 0xff,
+            (hi >>> 8) & 0xff,
+            hi & 0xff,
+            lo >>> 24,
+            (lo >>> 16) & 0xff,
+            (lo >>> 8) & 0xff,
+            lo & 0xff
+        ];
+    }
+    toSigned() {
+        if (!this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, false);
+    }
+    toString(radix) {
+        radix = radix || 10;
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        if (this.isZero())
+            return '0';
+        if (this.isNegative()) {
+            if (this.eq(Long.MIN_VALUE)) {
+                const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
+                return div.toString(radix) + rem1.toInt().toString(radix);
+            }
+            else
+                return '-' + this.neg().toString(radix);
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
+        let rem = this;
+        let result = '';
+        while (true) {
+            const remDiv = rem.div(radixToPower);
+            const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
+            let digits = intval.toString(radix);
+            rem = remDiv;
+            if (rem.isZero()) {
+                return digits + result;
+            }
+            else {
+                while (digits.length < 6)
+                    digits = '0' + digits;
+                result = '' + digits + result;
+            }
+        }
+    }
+    toUnsigned() {
+        if (this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, true);
+    }
+    xor(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
+    }
+    eqz() {
+        return this.isZero();
+    }
+    le(other) {
+        return this.lessThanOrEqual(other);
+    }
+    toExtendedJSON(options) {
+        if (options && options.relaxed)
+            return this.toNumber();
+        return { $numberLong: this.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        const { useBigInt64 = false, relaxed = true } = { ...options };
+        if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
+            throw new BSONError('$numberLong string is too long');
+        }
+        if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
+            throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
+        }
+        if (useBigInt64) {
+            const bigIntResult = BigInt(doc.$numberLong);
+            return BigInt.asIntN(64, bigIntResult);
+        }
+        const longResult = Long.fromString(doc.$numberLong);
+        if (relaxed) {
+            return longResult.toNumber();
+        }
+        return longResult;
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const longVal = inspect(this.toString(), options);
+        const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
+        return `new Long(${longVal}${unsignedVal})`;
+    }
+}
+
+const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
+const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
+const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
+const EXPONENT_MAX = 6111;
+const EXPONENT_MIN = -6176;
+const EXPONENT_BIAS = 6176;
+const MAX_DIGITS = 34;
+const NAN_BUFFER = ByteUtils.fromNumberArray([
+    0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
+    0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
+    0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
+const COMBINATION_MASK = 0x1f;
+const EXPONENT_MASK = 0x3fff;
+const COMBINATION_INFINITY = 30;
+const COMBINATION_NAN = 31;
+function isDigit(value) {
+    return !isNaN(parseInt(value, 10));
+}
+function divideu128(value) {
+    const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
+    let _rem = Long.fromNumber(0);
+    if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
+        return { quotient: value, rem: _rem };
+    }
+    for (let i = 0; i <= 3; i++) {
+        _rem = _rem.shiftLeft(32);
+        _rem = _rem.add(new Long(value.parts[i], 0));
+        value.parts[i] = _rem.div(DIVISOR).low;
+        _rem = _rem.modulo(DIVISOR);
+    }
+    return { quotient: value, rem: _rem };
+}
+function multiply64x2(left, right) {
+    if (!left && !right) {
+        return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
+    }
+    const leftHigh = left.shiftRightUnsigned(32);
+    const leftLow = new Long(left.getLowBits(), 0);
+    const rightHigh = right.shiftRightUnsigned(32);
+    const rightLow = new Long(right.getLowBits(), 0);
+    let productHigh = leftHigh.multiply(rightHigh);
+    let productMid = leftHigh.multiply(rightLow);
+    const productMid2 = leftLow.multiply(rightHigh);
+    let productLow = leftLow.multiply(rightLow);
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productMid = new Long(productMid.getLowBits(), 0)
+        .add(productMid2)
+        .add(productLow.shiftRightUnsigned(32));
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
+    return { high: productHigh, low: productLow };
+}
+function lessThan(left, right) {
+    const uhleft = left.high >>> 0;
+    const uhright = right.high >>> 0;
+    if (uhleft < uhright) {
+        return true;
+    }
+    else if (uhleft === uhright) {
+        const ulleft = left.low >>> 0;
+        const ulright = right.low >>> 0;
+        if (ulleft < ulright)
+            return true;
+    }
+    return false;
+}
+function invalidErr(string, message) {
+    throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
+}
+class Decimal128 extends BSONValue {
+    get _bsontype() {
+        return 'Decimal128';
+    }
+    bytes;
+    constructor(bytes) {
+        super();
+        if (typeof bytes === 'string') {
+            this.bytes = Decimal128.fromString(bytes).bytes;
+        }
+        else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
+            if (bytes.byteLength !== 16) {
+                throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
+            }
+            this.bytes = bytes;
+        }
+        else {
+            throw new BSONError('Decimal128 must take a Buffer or string');
+        }
+    }
+    static fromString(representation) {
+        return Decimal128._fromString(representation, { allowRounding: false });
+    }
+    static fromStringWithRounding(representation) {
+        return Decimal128._fromString(representation, { allowRounding: true });
+    }
+    static _fromString(representation, options) {
+        let isNegative = false;
+        let sawSign = false;
+        let sawRadix = false;
+        let foundNonZero = false;
+        let significantDigits = 0;
+        let nDigitsRead = 0;
+        let nDigits = 0;
+        let radixPosition = 0;
+        let firstNonZero = 0;
+        const digits = [0];
+        let nDigitsStored = 0;
+        let digitsInsert = 0;
+        let lastDigit = 0;
+        let exponent = 0;
+        let significandHigh = new Long(0, 0);
+        let significandLow = new Long(0, 0);
+        let biasedExponent = 0;
+        let index = 0;
+        if (representation.length >= 7000) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        const stringMatch = representation.match(PARSE_STRING_REGEXP);
+        const infMatch = representation.match(PARSE_INF_REGEXP);
+        const nanMatch = representation.match(PARSE_NAN_REGEXP);
+        if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        if (stringMatch) {
+            const unsignedNumber = stringMatch[2];
+            const e = stringMatch[4];
+            const expSign = stringMatch[5];
+            const expNumber = stringMatch[6];
+            if (e && expNumber === undefined)
+                invalidErr(representation, 'missing exponent power');
+            if (e && unsignedNumber === undefined)
+                invalidErr(representation, 'missing exponent base');
+            if (e === undefined && (expSign || expNumber)) {
+                invalidErr(representation, 'missing e before exponent');
+            }
+        }
+        if (representation[index] === '+' || representation[index] === '-') {
+            sawSign = true;
+            isNegative = representation[index++] === '-';
+        }
+        if (!isDigit(representation[index]) && representation[index] !== '.') {
+            if (representation[index] === 'i' || representation[index] === 'I') {
+                return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+            }
+            else if (representation[index] === 'N') {
+                return new Decimal128(NAN_BUFFER);
+            }
+        }
+        while (isDigit(representation[index]) || representation[index] === '.') {
+            if (representation[index] === '.') {
+                if (sawRadix)
+                    invalidErr(representation, 'contains multiple periods');
+                sawRadix = true;
+                index = index + 1;
+                continue;
+            }
+            if (nDigitsStored < MAX_DIGITS) {
+                if (representation[index] !== '0' || foundNonZero) {
+                    if (!foundNonZero) {
+                        firstNonZero = nDigitsRead;
+                    }
+                    foundNonZero = true;
+                    digits[digitsInsert++] = parseInt(representation[index], 10);
+                    nDigitsStored = nDigitsStored + 1;
+                }
+            }
+            if (foundNonZero)
+                nDigits = nDigits + 1;
+            if (sawRadix)
+                radixPosition = radixPosition + 1;
+            nDigitsRead = nDigitsRead + 1;
+            index = index + 1;
+        }
+        if (sawRadix && !nDigitsRead)
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        if (representation[index] === 'e' || representation[index] === 'E') {
+            const match = representation.substr(++index).match(EXPONENT_REGEX);
+            if (!match || !match[2])
+                return new Decimal128(NAN_BUFFER);
+            exponent = parseInt(match[0], 10);
+            index = index + match[0].length;
+        }
+        if (representation[index])
+            return new Decimal128(NAN_BUFFER);
+        if (!nDigitsStored) {
+            digits[0] = 0;
+            nDigits = 1;
+            nDigitsStored = 1;
+            significantDigits = 0;
+        }
+        else {
+            lastDigit = nDigitsStored - 1;
+            significantDigits = nDigits;
+            if (significantDigits !== 1) {
+                while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') {
+                    significantDigits = significantDigits - 1;
+                }
+            }
+        }
+        if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
+            exponent = EXPONENT_MIN;
+        }
+        else {
+            exponent = exponent - radixPosition;
+        }
+        while (exponent > EXPONENT_MAX) {
+            lastDigit = lastDigit + 1;
+            if (lastDigit >= MAX_DIGITS) {
+                if (significantDigits === 0) {
+                    exponent = EXPONENT_MAX;
+                    break;
+                }
+                invalidErr(representation, 'overflow');
+            }
+            exponent = exponent - 1;
+        }
+        if (options.allowRounding) {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0 && significantDigits < nDigitsStored) {
+                    exponent = EXPONENT_MIN;
+                    significantDigits = 0;
+                    break;
+                }
+                if (nDigitsStored < nDigits) {
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    const digitsString = digits.join('');
+                    if (digitsString.match(/^0+$/)) {
+                        exponent = EXPONENT_MAX;
+                        break;
+                    }
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                let endOfString = nDigitsRead;
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                let roundBit = 0;
+                if (roundDigit >= 5) {
+                    roundBit = 1;
+                    if (roundDigit === 5) {
+                        roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
+                        for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
+                            if (parseInt(representation[i], 10)) {
+                                roundBit = 1;
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (roundBit) {
+                    let dIdx = lastDigit;
+                    for (; dIdx >= 0; dIdx--) {
+                        if (++digits[dIdx] > 9) {
+                            digits[dIdx] = 0;
+                            if (dIdx === 0) {
+                                if (exponent < EXPONENT_MAX) {
+                                    exponent = exponent + 1;
+                                    digits[dIdx] = 1;
+                                }
+                                else {
+                                    return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+                                }
+                            }
+                        }
+                        else {
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        else {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0) {
+                    if (significantDigits === 0) {
+                        exponent = EXPONENT_MIN;
+                        break;
+                    }
+                    invalidErr(representation, 'exponent underflow');
+                }
+                if (nDigitsStored < nDigits) {
+                    if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
+                        significantDigits !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    if (digits[lastDigit] !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                if (roundDigit !== 0) {
+                    invalidErr(representation, 'inexact rounding');
+                }
+            }
+        }
+        significandHigh = Long.fromNumber(0);
+        significandLow = Long.fromNumber(0);
+        if (significantDigits === 0) {
+            significandHigh = Long.fromNumber(0);
+            significandLow = Long.fromNumber(0);
+        }
+        else if (lastDigit < 17) {
+            let dIdx = 0;
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            significandHigh = new Long(0, 0);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        else {
+            let dIdx = 0;
+            significandHigh = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit - 17; dIdx++) {
+                significandHigh = significandHigh.multiply(Long.fromNumber(10));
+                significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
+            }
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
+        significand.low = significand.low.add(significandLow);
+        if (lessThan(significand.low, significandLow)) {
+            significand.high = significand.high.add(Long.fromNumber(1));
+        }
+        biasedExponent = exponent + EXPONENT_BIAS;
+        const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
+        if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
+            dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
+        }
+        else {
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
+        }
+        dec.low = significand.low;
+        if (isNegative) {
+            dec.high = dec.high.or(Long.fromString('9223372036854775808'));
+        }
+        const buffer = ByteUtils.allocateUnsafe(16);
+        index = 0;
+        buffer[index++] = dec.low.low & 0xff;
+        buffer[index++] = (dec.low.low >> 8) & 0xff;
+        buffer[index++] = (dec.low.low >> 16) & 0xff;
+        buffer[index++] = (dec.low.low >> 24) & 0xff;
+        buffer[index++] = dec.low.high & 0xff;
+        buffer[index++] = (dec.low.high >> 8) & 0xff;
+        buffer[index++] = (dec.low.high >> 16) & 0xff;
+        buffer[index++] = (dec.low.high >> 24) & 0xff;
+        buffer[index++] = dec.high.low & 0xff;
+        buffer[index++] = (dec.high.low >> 8) & 0xff;
+        buffer[index++] = (dec.high.low >> 16) & 0xff;
+        buffer[index++] = (dec.high.low >> 24) & 0xff;
+        buffer[index++] = dec.high.high & 0xff;
+        buffer[index++] = (dec.high.high >> 8) & 0xff;
+        buffer[index++] = (dec.high.high >> 16) & 0xff;
+        buffer[index++] = (dec.high.high >> 24) & 0xff;
+        return new Decimal128(buffer);
+    }
+    toString() {
+        let biased_exponent;
+        let significand_digits = 0;
+        const significand = new Array(36);
+        for (let i = 0; i < significand.length; i++)
+            significand[i] = 0;
+        let index = 0;
+        let is_zero = false;
+        let significand_msb;
+        let significand128 = { parts: [0, 0, 0, 0] };
+        let j, k;
+        const string = [];
+        index = 0;
+        const buffer = this.bytes;
+        const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        index = 0;
+        const dec = {
+            low: new Long(low, midl),
+            high: new Long(midh, high)
+        };
+        if (dec.high.lessThan(Long.ZERO)) {
+            string.push('-');
+        }
+        const combination = (high >> 26) & COMBINATION_MASK;
+        if (combination >> 3 === 3) {
+            if (combination === COMBINATION_INFINITY) {
+                return string.join('') + 'Infinity';
+            }
+            else if (combination === COMBINATION_NAN) {
+                return 'NaN';
+            }
+            else {
+                biased_exponent = (high >> 15) & EXPONENT_MASK;
+                significand_msb = 0x08 + ((high >> 14) & 0x01);
+            }
+        }
+        else {
+            significand_msb = (high >> 14) & 0x07;
+            biased_exponent = (high >> 17) & EXPONENT_MASK;
+        }
+        const exponent = biased_exponent - EXPONENT_BIAS;
+        significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
+        significand128.parts[1] = midh;
+        significand128.parts[2] = midl;
+        significand128.parts[3] = low;
+        if (significand128.parts[0] === 0 &&
+            significand128.parts[1] === 0 &&
+            significand128.parts[2] === 0 &&
+            significand128.parts[3] === 0) {
+            is_zero = true;
+        }
+        else {
+            for (k = 3; k >= 0; k--) {
+                let least_digits = 0;
+                const result = divideu128(significand128);
+                significand128 = result.quotient;
+                least_digits = result.rem.low;
+                if (!least_digits)
+                    continue;
+                for (j = 8; j >= 0; j--) {
+                    significand[k * 9 + j] = least_digits % 10;
+                    least_digits = Math.floor(least_digits / 10);
+                }
+            }
+        }
+        if (is_zero) {
+            significand_digits = 1;
+            significand[index] = 0;
+        }
+        else {
+            significand_digits = 36;
+            while (!significand[index]) {
+                significand_digits = significand_digits - 1;
+                index = index + 1;
+            }
+        }
+        const scientific_exponent = significand_digits - 1 + exponent;
+        if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
+            if (significand_digits > 34) {
+                string.push(`${0}`);
+                if (exponent > 0)
+                    string.push(`E+${exponent}`);
+                else if (exponent < 0)
+                    string.push(`E${exponent}`);
+                return string.join('');
+            }
+            string.push(`${significand[index++]}`);
+            significand_digits = significand_digits - 1;
+            if (significand_digits) {
+                string.push('.');
+            }
+            for (let i = 0; i < significand_digits; i++) {
+                string.push(`${significand[index++]}`);
+            }
+            string.push('E');
+            if (scientific_exponent > 0) {
+                string.push(`+${scientific_exponent}`);
+            }
+            else {
+                string.push(`${scientific_exponent}`);
+            }
+        }
+        else {
+            if (exponent >= 0) {
+                for (let i = 0; i < significand_digits; i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+            else {
+                let radix_position = significand_digits + exponent;
+                if (radix_position > 0) {
+                    for (let i = 0; i < radix_position; i++) {
+                        string.push(`${significand[index++]}`);
+                    }
+                }
+                else {
+                    string.push('0');
+                }
+                string.push('.');
+                while (radix_position++ < 0) {
+                    string.push('0');
+                }
+                for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+        }
+        return string.join('');
+    }
+    toJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    toExtendedJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    static fromExtendedJSON(doc) {
+        return Decimal128.fromString(doc.$numberDecimal);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const d128string = inspect(this.toString(), options);
+        return `new Decimal128(${d128string})`;
+    }
+}
+
+class Double extends BSONValue {
+    get _bsontype() {
+        return 'Double';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value;
+    }
+    static fromString(value) {
+        const coercedValue = Number(value);
+        if (value === 'NaN')
+            return new Double(NaN);
+        if (value === 'Infinity')
+            return new Double(Infinity);
+        if (value === '-Infinity')
+            return new Double(-Infinity);
+        if (!Number.isFinite(coercedValue)) {
+            throw new BSONError(`Input: ${value} is not representable as a Double`);
+        }
+        if (value.trim() !== value) {
+            throw new BSONError(`Input: '${value}' contains whitespace`);
+        }
+        if (value === '') {
+            throw new BSONError(`Input is an empty string`);
+        }
+        if (/[^-0-9.+eE]/.test(value)) {
+            throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
+        }
+        return new Double(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toExtendedJSON(options) {
+        if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
+            return this.value;
+        }
+        if (Object.is(Math.sign(this.value), -0)) {
+            return { $numberDouble: '-0.0' };
+        }
+        return {
+            $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
+        };
+    }
+    static fromExtendedJSON(doc, options) {
+        const doubleValue = parseFloat(doc.$numberDouble);
+        return options && options.relaxed ? doubleValue : new Double(doubleValue);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Double(${inspect(this.value, options)})`;
+    }
+}
+
+class Int32 extends BSONValue {
+    get _bsontype() {
+        return 'Int32';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value | 0;
+    }
+    static fromString(value) {
+        const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
+        const coercedValue = Number(value);
+        if (BSON_INT32_MAX < coercedValue) {
+            throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
+        }
+        else if (BSON_INT32_MIN > coercedValue) {
+            throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
+        }
+        else if (!Number.isSafeInteger(coercedValue)) {
+            throw new BSONError(`Input: '${value}' is not a safe integer`);
+        }
+        else if (coercedValue.toString() !== cleanedValue) {
+            throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
+        }
+        return new Int32(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON(options) {
+        if (options && (options.relaxed || options.legacy))
+            return this.value;
+        return { $numberInt: this.value.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Int32(${inspect(this.value, options)})`;
+    }
+}
+
+class MaxKey extends BSONValue {
+    get _bsontype() {
+        return 'MaxKey';
+    }
+    toExtendedJSON() {
+        return { $maxKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MaxKey();
+    }
+    inspect() {
+        return 'new MaxKey()';
+    }
+}
+
+class MinKey extends BSONValue {
+    get _bsontype() {
+        return 'MinKey';
+    }
+    toExtendedJSON() {
+        return { $minKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MinKey();
+    }
+    inspect() {
+        return 'new MinKey()';
+    }
+}
+
+let PROCESS_UNIQUE = null;
+const __idCache = new WeakMap();
+class ObjectId extends BSONValue {
+    get _bsontype() {
+        return 'ObjectId';
+    }
+    static index = Math.floor(Math.random() * 0xffffff);
+    static cacheHexString;
+    buffer;
+    constructor(inputId) {
+        super();
+        let workingId;
+        if (typeof inputId === 'object' && inputId && 'id' in inputId) {
+            if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
+                throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
+            }
+            if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
+                workingId = ByteUtils.fromHex(inputId.toHexString());
+            }
+            else {
+                workingId = inputId.id;
+            }
+        }
+        else {
+            workingId = inputId;
+        }
+        if (workingId == null) {
+            this.buffer = ObjectId.generate();
+        }
+        else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
+            this.buffer = ByteUtils.toLocalBufferType(workingId);
+        }
+        else if (typeof workingId === 'string') {
+            if (ObjectId.validateHexString(workingId)) {
+                this.buffer = ByteUtils.fromHex(workingId);
+                if (ObjectId.cacheHexString) {
+                    __idCache.set(this, workingId);
+                }
+            }
+            else {
+                throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer');
+            }
+        }
+        else {
+            throw new BSONError('Argument passed in does not match the accepted types');
+        }
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, ByteUtils.toHex(value));
+        }
+    }
+    static validateHexString(string) {
+        if (string?.length !== 24)
+            return false;
+        for (let i = 0; i < 24; i++) {
+            const char = string.charCodeAt(i);
+            if ((char >= 48 && char <= 57) ||
+                (char >= 97 && char <= 102) ||
+                (char >= 65 && char <= 70)) {
+                continue;
+            }
+            return false;
+        }
+        return true;
+    }
+    toHexString() {
+        if (ObjectId.cacheHexString) {
+            const __id = __idCache.get(this);
+            if (__id)
+                return __id;
+        }
+        const hexString = ByteUtils.toHex(this.id);
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, hexString);
+        }
+        return hexString;
+    }
+    static getInc() {
+        return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
+    }
+    static generate(time) {
+        if ('number' !== typeof time) {
+            time = Math.floor(Date.now() / 1000);
+        }
+        const inc = ObjectId.getInc();
+        const buffer = ByteUtils.allocateUnsafe(12);
+        NumberUtils.setInt32BE(buffer, 0, time);
+        if (PROCESS_UNIQUE === null) {
+            PROCESS_UNIQUE = ByteUtils.randomBytes(5);
+        }
+        buffer[4] = PROCESS_UNIQUE[0];
+        buffer[5] = PROCESS_UNIQUE[1];
+        buffer[6] = PROCESS_UNIQUE[2];
+        buffer[7] = PROCESS_UNIQUE[3];
+        buffer[8] = PROCESS_UNIQUE[4];
+        buffer[11] = inc & 0xff;
+        buffer[10] = (inc >> 8) & 0xff;
+        buffer[9] = (inc >> 16) & 0xff;
+        return buffer;
+    }
+    toString(encoding) {
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        if (encoding === 'hex')
+            return this.toHexString();
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    static is(variable) {
+        return (variable != null &&
+            typeof variable === 'object' &&
+            '_bsontype' in variable &&
+            variable._bsontype === 'ObjectId');
+    }
+    equals(otherId) {
+        if (otherId === undefined || otherId === null) {
+            return false;
+        }
+        if (ObjectId.is(otherId)) {
+            return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer));
+        }
+        if (typeof otherId === 'string') {
+            return otherId.toLowerCase() === this.toHexString();
+        }
+        if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') {
+            const otherIdString = otherId.toHexString();
+            const thisIdString = this.toHexString();
+            return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
+        }
+        return false;
+    }
+    getTimestamp() {
+        const timestamp = new Date();
+        const time = NumberUtils.getUint32BE(this.buffer, 0);
+        timestamp.setTime(Math.floor(time) * 1000);
+        return timestamp;
+    }
+    static createPk() {
+        return new ObjectId();
+    }
+    serializeInto(uint8array, index) {
+        uint8array[index] = this.buffer[0];
+        uint8array[index + 1] = this.buffer[1];
+        uint8array[index + 2] = this.buffer[2];
+        uint8array[index + 3] = this.buffer[3];
+        uint8array[index + 4] = this.buffer[4];
+        uint8array[index + 5] = this.buffer[5];
+        uint8array[index + 6] = this.buffer[6];
+        uint8array[index + 7] = this.buffer[7];
+        uint8array[index + 8] = this.buffer[8];
+        uint8array[index + 9] = this.buffer[9];
+        uint8array[index + 10] = this.buffer[10];
+        uint8array[index + 11] = this.buffer[11];
+        return 12;
+    }
+    static createFromTime(time) {
+        const buffer = ByteUtils.allocate(12);
+        for (let i = 11; i >= 4; i--)
+            buffer[i] = 0;
+        NumberUtils.setInt32BE(buffer, 0, time);
+        return new ObjectId(buffer);
+    }
+    static createFromHexString(hexString) {
+        if (hexString?.length !== 24) {
+            throw new BSONError('hex string must be 24 characters');
+        }
+        return new ObjectId(ByteUtils.fromHex(hexString));
+    }
+    static createFromBase64(base64) {
+        if (base64?.length !== 16) {
+            throw new BSONError('base64 string must be 16 characters');
+        }
+        return new ObjectId(ByteUtils.fromBase64(base64));
+    }
+    static isValid(id) {
+        if (id == null)
+            return false;
+        if (typeof id === 'string')
+            return ObjectId.validateHexString(id);
+        try {
+            new ObjectId(id);
+            return true;
+        }
+        catch {
+            return false;
+        }
+    }
+    toExtendedJSON() {
+        if (this.toHexString)
+            return { $oid: this.toHexString() };
+        return { $oid: this.toString('hex') };
+    }
+    static fromExtendedJSON(doc) {
+        return new ObjectId(doc.$oid);
+    }
+    isCached() {
+        return ObjectId.cacheHexString && __idCache.has(this);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new ObjectId(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
+    let totalLength = 4 + 1;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+        }
+        for (const key of Object.keys(object)) {
+            totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
+        }
+    }
+    return totalLength;
+}
+function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
+    if (typeof value?.toBSON === 'function') {
+        value = value.toBSON();
+    }
+    switch (typeof value) {
+        case 'string':
+            return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
+        case 'number':
+            if (Math.floor(value) === value &&
+                value >= JS_INT_MIN &&
+                value <= JS_INT_MAX) {
+                if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
+                }
+                else {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+                }
+            }
+            else {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+        case 'undefined':
+            if (isArray || !ignoreUndefined)
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            return 0;
+        case 'boolean':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
+        case 'object':
+            if (value != null &&
+                typeof value._bsontype === 'string' &&
+                value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                throw new BSONVersionError();
+            }
+            else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            }
+            else if (value._bsontype === 'ObjectId') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
+            }
+            else if (value instanceof Date || isDate(value)) {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (ArrayBuffer.isView(value) ||
+                value instanceof ArrayBuffer ||
+                isAnyArrayBuffer(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength);
+            }
+            else if (value._bsontype === 'Long' ||
+                value._bsontype === 'Double' ||
+                value._bsontype === 'Timestamp') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (value._bsontype === 'Decimal128') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
+            }
+            else if (value._bsontype === 'Code') {
+                if (value.scope != null && Object.keys(value.scope).length > 0) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1 +
+                        internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1);
+                }
+            }
+            else if (value._bsontype === 'Binary') {
+                const binary = value;
+                if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        (binary.position + 1 + 4 + 1 + 4));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1));
+                }
+            }
+            else if (value._bsontype === 'Symbol') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    ByteUtils.utf8ByteLength(value.value) +
+                    4 +
+                    1 +
+                    1);
+            }
+            else if (value._bsontype === 'DBRef') {
+                const ordered_values = Object.assign({
+                    $ref: value.collection,
+                    $id: value.oid
+                }, value.fields);
+                if (value.db != null) {
+                    ordered_values['$db'] = value.db;
+                }
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
+            }
+            else if (value instanceof RegExp || isRegExp(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.source) +
+                    1 +
+                    (value.global ? 1 : 0) +
+                    (value.ignoreCase ? 1 : 0) +
+                    (value.multiline ? 1 : 0) +
+                    1);
+            }
+            else if (value._bsontype === 'BSONRegExp') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.pattern) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.options) +
+                    1);
+            }
+            else {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) +
+                    1);
+            }
+        case 'function':
+            if (serializeFunctions) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    4 +
+                    ByteUtils.utf8ByteLength(value.toString()) +
+                    1);
+            }
+            return 0;
+        case 'bigint':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+        case 'symbol':
+            return 0;
+        default:
+            throw new BSONError(`Unrecognized JS type: ${typeof value}`);
+    }
+}
+
+function alphabetize(str) {
+    return str.split('').sort().join('');
+}
+class BSONRegExp extends BSONValue {
+    get _bsontype() {
+        return 'BSONRegExp';
+    }
+    pattern;
+    options;
+    constructor(pattern, options) {
+        super();
+        this.pattern = pattern;
+        this.options = alphabetize(options ?? '');
+        if (this.pattern.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
+        }
+        if (this.options.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
+        }
+        for (let i = 0; i < this.options.length; i++) {
+            if (!(this.options[i] === 'i' ||
+                this.options[i] === 'm' ||
+                this.options[i] === 'x' ||
+                this.options[i] === 'l' ||
+                this.options[i] === 's' ||
+                this.options[i] === 'u')) {
+                throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
+            }
+        }
+    }
+    static parseOptions(options) {
+        return options ? options.split('').sort().join('') : '';
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (options.legacy) {
+            return { $regex: this.pattern, $options: this.options };
+        }
+        return { $regularExpression: { pattern: this.pattern, options: this.options } };
+    }
+    static fromExtendedJSON(doc) {
+        if ('$regex' in doc) {
+            if (typeof doc.$regex !== 'string') {
+                if (doc.$regex._bsontype === 'BSONRegExp') {
+                    return doc;
+                }
+            }
+            else {
+                return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
+            }
+        }
+        if ('$regularExpression' in doc) {
+            return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
+        }
+        throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
+    }
+    inspect(depth, options, inspect) {
+        const stylize = getStylizeFunction(options) ?? (v => v);
+        inspect ??= defaultInspect;
+        const pattern = stylize(inspect(this.pattern), 'regexp');
+        const flags = stylize(inspect(this.options), 'regexp');
+        return `new BSONRegExp(${pattern}, ${flags})`;
+    }
+}
+
+class BSONSymbol extends BSONValue {
+    get _bsontype() {
+        return 'BSONSymbol';
+    }
+    value;
+    constructor(value) {
+        super();
+        this.value = value;
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON() {
+        return { $symbol: this.value };
+    }
+    static fromExtendedJSON(doc) {
+        return new BSONSymbol(doc.$symbol);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new BSONSymbol(${inspect(this.value, options)})`;
+    }
+}
+
+const LongWithoutOverridesClass = Long;
+class Timestamp extends LongWithoutOverridesClass {
+    get _bsontype() {
+        return 'Timestamp';
+    }
+    get [bsonType]() {
+        return 'Timestamp';
+    }
+    static MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
+    get i() {
+        return this.low >>> 0;
+    }
+    get t() {
+        return this.high >>> 0;
+    }
+    constructor(low) {
+        if (low == null) {
+            super(0, 0, true);
+        }
+        else if (typeof low === 'bigint') {
+            super(low, true);
+        }
+        else if (Long.isLong(low)) {
+            super(low.low, low.high, true);
+        }
+        else if (typeof low === 'object' && 't' in low && 'i' in low) {
+            if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t as a number');
+            }
+            if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
+            }
+            const t = Number(low.t);
+            const i = Number(low.i);
+            if (t < 0 || Number.isNaN(t)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
+            }
+            if (i < 0 || Number.isNaN(i)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
+            }
+            if (t > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max');
+            }
+            if (i > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max');
+            }
+            super(i, t, true);
+        }
+        else {
+            throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }');
+        }
+    }
+    toJSON() {
+        return {
+            $timestamp: this.toString()
+        };
+    }
+    static fromInt(value) {
+        return new Timestamp(Long.fromInt(value, true));
+    }
+    static fromNumber(value) {
+        return new Timestamp(Long.fromNumber(value, true));
+    }
+    static fromBits(lowBits, highBits) {
+        return new Timestamp({ i: lowBits, t: highBits });
+    }
+    static fromString(str, optRadix) {
+        return new Timestamp(Long.fromString(str, true, optRadix));
+    }
+    toExtendedJSON() {
+        return { $timestamp: { t: this.t, i: this.i } };
+    }
+    static fromExtendedJSON(doc) {
+        const i = Long.isLong(doc.$timestamp.i)
+            ? doc.$timestamp.i.getLowBitsUnsigned()
+            : doc.$timestamp.i;
+        const t = Long.isLong(doc.$timestamp.t)
+            ? doc.$timestamp.t.getLowBitsUnsigned()
+            : doc.$timestamp.t;
+        return new Timestamp({ t, i });
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const t = inspect(this.t, options);
+        const i = inspect(this.i, options);
+        return `new Timestamp({ t: ${t}, i: ${i} })`;
+    }
+}
+
+const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
+const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
+function internalDeserialize(buffer, options, isArray) {
+    options = options == null ? {} : options;
+    const index = options && options.index ? options.index : 0;
+    const size = NumberUtils.getInt32LE(buffer, index);
+    if (size < 5) {
+        throw new BSONError(`bson size must be >= 5, is ${size}`);
+    }
+    if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
+        throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
+    }
+    if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
+        throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
+    }
+    if (size + index > buffer.byteLength) {
+        throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`);
+    }
+    if (buffer[index + size - 1] !== 0) {
+        throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
+    }
+    return deserializeObject(buffer, index, options, isArray);
+}
+const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
+function deserializeObject(buffer, index, options, isArray = false) {
+    const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
+    const raw = options['raw'] == null ? false : options['raw'];
+    const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
+    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');
+    }
+    const validation = options.validation == null ? { utf8: true } : options.validation;
+    let globalUTFValidation = true;
+    let validationSetting;
+    let utf8KeysSet;
+    const utf8ValidatedKeys = validation.utf8;
+    if (typeof utf8ValidatedKeys === 'boolean') {
+        validationSetting = utf8ValidatedKeys;
+    }
+    else {
+        globalUTFValidation = false;
+        const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
+            return utf8ValidatedKeys[key];
+        });
+        if (utf8ValidationValues.length === 0) {
+            throw new BSONError('UTF-8 validation setting cannot be empty');
+        }
+        if (typeof utf8ValidationValues[0] !== 'boolean') {
+            throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
+        }
+        validationSetting = utf8ValidationValues[0];
+        if (!utf8ValidationValues.every(item => item === validationSetting)) {
+            throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
+        }
+    }
+    if (!globalUTFValidation) {
+        utf8KeysSet = new Set();
+        for (const key of Object.keys(utf8ValidatedKeys)) {
+            utf8KeysSet.add(key);
+        }
+    }
+    const startIndex = index;
+    if (buffer.length < 5)
+        throw new BSONError('corrupt bson message < 5 bytes long');
+    const size = NumberUtils.getInt32LE(buffer, index);
+    index += 4;
+    if (size < 5 || size > buffer.length)
+        throw new BSONError('corrupt bson message');
+    const object = isArray ? [] : {};
+    let arrayIndex = 0;
+    let isPossibleDBRef = isArray ? false : null;
+    while (true) {
+        const elementType = buffer[index++];
+        if (elementType === 0)
+            break;
+        let i = index;
+        while (buffer[i] !== 0x00 && i < buffer.length) {
+            i++;
+        }
+        if (i >= buffer.byteLength)
+            throw new BSONError('Bad BSON Document: illegal CString');
+        const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false);
+        let shouldValidateKey = true;
+        if (globalUTFValidation || utf8KeysSet?.has(name)) {
+            shouldValidateKey = validationSetting;
+        }
+        else {
+            shouldValidateKey = !validationSetting;
+        }
+        if (isPossibleDBRef !== false && name[0] === '$') {
+            isPossibleDBRef = allowedDBRefKeys.test(name);
+        }
+        let value;
+        index = i + 1;
+        if (elementType === BSON_DATA_STRING) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_OID) {
+            const oid = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oid[i] = buffer[index + i];
+            value = new ObjectId(oid);
+            index = index + 12;
+        }
+        else if (elementType === BSON_DATA_INT && promoteValues === false) {
+            value = new Int32(NumberUtils.getInt32LE(buffer, index));
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_INT) {
+            value = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_NUMBER) {
+            value = NumberUtils.getFloat64LE(buffer, index);
+            index += 8;
+            if (promoteValues === false)
+                value = new Double(value);
+        }
+        else if (elementType === BSON_DATA_DATE) {
+            const lowBits = NumberUtils.getInt32LE(buffer, index);
+            const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+            index += 8;
+            value = new Date(new Long(lowBits, highBits).toNumber());
+        }
+        else if (elementType === BSON_DATA_BOOLEAN) {
+            if (buffer[index] !== 0 && buffer[index] !== 1)
+                throw new BSONError('illegal boolean type value');
+            value = buffer[index++] === 1;
+        }
+        else if (elementType === BSON_DATA_OBJECT) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            if (objectSize <= 0 || objectSize > buffer.length - index)
+                throw new BSONError('bad embedded document length in bson');
+            if (raw) {
+                value = buffer.subarray(index, index + objectSize);
+            }
+            else {
+                let objectOptions = options;
+                if (!globalUTFValidation) {
+                    objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
+                }
+                value = deserializeObject(buffer, _index, objectOptions, false);
+            }
+            index = index + objectSize;
+        }
+        else if (elementType === BSON_DATA_ARRAY) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            let arrayOptions = options;
+            const stopIndex = index + objectSize;
+            if (fieldsAsRaw && fieldsAsRaw[name]) {
+                arrayOptions = { ...options, raw: true };
+            }
+            if (!globalUTFValidation) {
+                arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
+            }
+            value = deserializeObject(buffer, _index, arrayOptions, true);
+            index = index + objectSize;
+            if (buffer[index - 1] !== 0)
+                throw new BSONError('invalid array terminator byte');
+            if (index !== stopIndex)
+                throw new BSONError('corrupted array bson');
+        }
+        else if (elementType === BSON_DATA_UNDEFINED) {
+            value = undefined;
+        }
+        else if (elementType === BSON_DATA_NULL) {
+            value = null;
+        }
+        else if (elementType === BSON_DATA_LONG) {
+            if (useBigInt64) {
+                value = NumberUtils.getBigInt64LE(buffer, index);
+                index += 8;
+            }
+            else {
+                const lowBits = NumberUtils.getInt32LE(buffer, index);
+                const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+                index += 8;
+                const long = new Long(lowBits, highBits);
+                if (promoteLongs && promoteValues === true) {
+                    value =
+                        long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
+                            ? long.toNumber()
+                            : long;
+                }
+                else {
+                    value = long;
+                }
+            }
+        }
+        else if (elementType === BSON_DATA_DECIMAL128) {
+            const bytes = ByteUtils.allocateUnsafe(16);
+            for (let i = 0; i < 16; i++)
+                bytes[i] = buffer[index + i];
+            index = index + 16;
+            value = new Decimal128(bytes);
+        }
+        else if (elementType === BSON_DATA_BINARY) {
+            let binarySize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            const totalBinarySize = binarySize;
+            const subType = buffer[index++];
+            if (binarySize < 0)
+                throw new BSONError('Negative binary type element size found');
+            if (binarySize > buffer.byteLength)
+                throw new BSONError('Binary type size larger than document size');
+            if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
+                binarySize = NumberUtils.getInt32LE(buffer, index);
+                index += 4;
+                if (binarySize < 0)
+                    throw new BSONError('Negative binary type element size found for subtype 0x02');
+                if (binarySize > totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
+                if (binarySize < totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
+            }
+            if (promoteBuffers && promoteValues) {
+                value = ByteUtils.toLocalBufferType(buffer.subarray(index, index + binarySize));
+            }
+            else {
+                value = new Binary(buffer.subarray(index, index + binarySize), subType);
+                if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
+                    value = value.toUUID();
+                }
+            }
+            index = index + binarySize;
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            const optionsArray = new Array(regExpOptions.length);
+            for (i = 0; i < regExpOptions.length; i++) {
+                switch (regExpOptions[i]) {
+                    case 'm':
+                        optionsArray[i] = 'm';
+                        break;
+                    case 's':
+                        optionsArray[i] = 'g';
+                        break;
+                    case 'i':
+                        optionsArray[i] = 'i';
+                        break;
+                }
+            }
+            value = new RegExp(source, optionsArray.join(''));
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            value = new BSONRegExp(source, regExpOptions);
+        }
+        else if (elementType === BSON_DATA_SYMBOL) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = promoteValues ? symbol : new BSONSymbol(symbol);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_TIMESTAMP) {
+            value = new Timestamp({
+                i: NumberUtils.getUint32LE(buffer, index),
+                t: NumberUtils.getUint32LE(buffer, index + 4)
+            });
+            index += 8;
+        }
+        else if (elementType === BSON_DATA_MIN_KEY) {
+            value = new MinKey();
+        }
+        else if (elementType === BSON_DATA_MAX_KEY) {
+            value = new MaxKey();
+        }
+        else if (elementType === BSON_DATA_CODE) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = new Code(functionString);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_CODE_W_SCOPE) {
+            const totalSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (totalSize < 4 + 4 + 4 + 1) {
+                throw new BSONError('code_w_scope total size shorter minimum expected length');
+            }
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            const scopeObject = deserializeObject(buffer, _index, options, false);
+            index = index + objectSize;
+            if (totalSize < 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too short, truncating scope');
+            }
+            if (totalSize > 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too long, clips outer document');
+            }
+            value = new Code(functionString, scopeObject);
+        }
+        else if (elementType === BSON_DATA_DBPOINTER) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0)
+                throw new BSONError('bad string length in bson');
+            const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const oidBuffer = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oidBuffer[i] = buffer[index + i];
+            const oid = new ObjectId(oidBuffer);
+            index = index + 12;
+            value = new DBRef(namespace, oid);
+        }
+        else {
+            throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
+        }
+        if (name === '__proto__') {
+            Object.defineProperty(object, name, {
+                value,
+                writable: true,
+                enumerable: true,
+                configurable: true
+            });
+        }
+        else {
+            object[name] = value;
+        }
+    }
+    if (size !== index - startIndex) {
+        if (isArray)
+            throw new BSONError('corrupt array bson');
+        throw new BSONError('corrupt object bson');
+    }
+    if (!isPossibleDBRef)
+        return object;
+    if (isDBRefLike(object)) {
+        const copy = Object.assign({}, object);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(object.$ref, object.$id, object.$db, copy);
+    }
+    return object;
+}
+
+const regexp = /\x00/;
+const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
+function serializeString(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_STRING;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes + 1;
+    buffer[index - 1] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
+    NumberUtils.setInt32LE(buffer, index, size + 1);
+    index = index + 4 + size;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeNumber(buffer, key, value, index) {
+    const isNegativeZero = Object.is(value, -0);
+    const type = !isNegativeZero &&
+        Number.isSafeInteger(value) &&
+        value <= BSON_INT32_MAX &&
+        value >= BSON_INT32_MIN
+        ? BSON_DATA_INT
+        : BSON_DATA_NUMBER;
+    buffer[index++] = type;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0x00;
+    if (type === BSON_DATA_INT) {
+        index += NumberUtils.setInt32LE(buffer, index, value);
+    }
+    else {
+        index += NumberUtils.setFloat64LE(buffer, index, value);
+    }
+    return index;
+}
+function serializeBigInt(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_LONG;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index += numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setBigInt64LE(buffer, index, value);
+    return index;
+}
+function serializeNull(buffer, key, _, index) {
+    buffer[index++] = BSON_DATA_NULL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeBoolean(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BOOLEAN;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    buffer[index++] = value ? 1 : 0;
+    return index;
+}
+function serializeDate(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DATE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const dateInMilis = Long.fromNumber(value.getTime());
+    const lowBits = dateInMilis.getLowBits();
+    const highBits = dateInMilis.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.source && value.source.match(regexp) != null) {
+        throw new BSONError('value ' + value.source + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
+    buffer[index++] = 0x00;
+    if (value.ignoreCase)
+        buffer[index++] = 0x69;
+    if (value.global)
+        buffer[index++] = 0x73;
+    if (value.multiline)
+        buffer[index++] = 0x6d;
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeBSONRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.pattern.match(regexp) != null) {
+        throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
+    buffer[index++] = 0x00;
+    const sortedOptions = value.options.split('').sort().join('');
+    index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeMinMax(buffer, key, value, index) {
+    if (value === null) {
+        buffer[index++] = BSON_DATA_NULL;
+    }
+    else if (value._bsontype === 'MinKey') {
+        buffer[index++] = BSON_DATA_MIN_KEY;
+    }
+    else {
+        buffer[index++] = BSON_DATA_MAX_KEY;
+    }
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeObjectId(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_OID;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += value.serializeInto(buffer, index);
+    return index;
+}
+function serializeBuffer(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = value.length;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = value[i];
+    }
+    else {
+        buffer.set(value, index);
+    }
+    index = index + size;
+    return index;
+}
+function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path.has(value)) {
+        throw new BSONError('Cannot convert circular structure to BSON');
+    }
+    path.add(value);
+    buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+    path.delete(value);
+    return endIndex;
+}
+function serializeDecimal128(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DECIMAL128;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    for (let i = 0; i < 16; i++)
+        buffer[index + i] = value.bytes[i];
+    return index + 16;
+}
+function serializeLong(buffer, key, value, index) {
+    buffer[index++] =
+        value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const lowBits = value.getLowBits();
+    const highBits = value.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeInt32(buffer, key, value, index) {
+    value = value.valueOf();
+    buffer[index++] = BSON_DATA_INT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setInt32LE(buffer, index, value);
+    return index;
+}
+function serializeDouble(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_NUMBER;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setFloat64LE(buffer, index, value.value);
+    return index;
+}
+function serializeFunction(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_CODE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const functionString = value.toString();
+    const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
+    if (value.scope && typeof value.scope === 'object') {
+        buffer[index++] = BSON_DATA_CODE_W_SCOPE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        let startIndex = index;
+        const functionString = value.code;
+        index = index + 4;
+        const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, codeSize);
+        buffer[index + 4 + codeSize - 1] = 0;
+        index = index + codeSize + 4;
+        const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+        index = endIndex - 1;
+        const totalSize = endIndex - startIndex;
+        startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize);
+        buffer[index++] = 0;
+    }
+    else {
+        buffer[index++] = BSON_DATA_CODE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        const functionString = value.code.toString();
+        const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, size);
+        index = index + 4 + size - 1;
+        buffer[index++] = 0;
+    }
+    return index;
+}
+function serializeBinary(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const data = value.buffer;
+    let size = value.position;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
+        size = size + 4;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = value.sub_type;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+        size = size - 4;
+        index += NumberUtils.setInt32LE(buffer, index, size);
+    }
+    if (value.sub_type === Binary.SUBTYPE_VECTOR) {
+        validateBinaryVector(value);
+    }
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = data[i];
+    }
+    else {
+        buffer.set(data, index);
+    }
+    index = index + value.position;
+    return index;
+}
+function serializeSymbol(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_SYMBOL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) {
+    buffer[index++] = BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    let startIndex = index;
+    let output = {
+        $ref: value.collection || value.namespace,
+        $id: value.oid
+    };
+    if (value.db != null) {
+        output.$db = value.db;
+    }
+    output = Object.assign(output, value.fields);
+    const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path);
+    const size = endIndex - startIndex;
+    startIndex += NumberUtils.setInt32LE(buffer, index, size);
+    return endIndex;
+}
+function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path == null) {
+        if (object == null) {
+            buffer[0] = 0x05;
+            buffer[1] = 0x00;
+            buffer[2] = 0x00;
+            buffer[3] = 0x00;
+            buffer[4] = 0x00;
+            return 5;
+        }
+        if (Array.isArray(object)) {
+            throw new BSONError('serialize does not support an array as the root input');
+        }
+        if (typeof object !== 'object') {
+            throw new BSONError('serialize does not support non-object as the root input');
+        }
+        else if ('_bsontype' in object && typeof object._bsontype === 'string') {
+            throw new BSONError(`BSON types cannot be serialized as a document`);
+        }
+        else if (isDate(object) ||
+            isRegExp(object) ||
+            isUint8Array(object) ||
+            isAnyArrayBuffer(object)) {
+            throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
+        }
+        path = new Set();
+    }
+    path.add(object);
+    let index = startingIndex + 4;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            const key = `${i}`;
+            let value = object[i];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (value === undefined) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else if (object instanceof Map || isMap(object)) {
+        const iterator = object.entries();
+        let done = false;
+        while (!done) {
+            const entry = iterator.next();
+            done = !!entry.done;
+            if (done)
+                continue;
+            const key = entry.value ? entry.value[0] : undefined;
+            let value = entry.value ? entry.value[1] : undefined;
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+            if (object != null && typeof object !== 'object') {
+                throw new BSONError('toBSON function did not return an object');
+            }
+        }
+        for (const key of Object.keys(object)) {
+            let value = object[key];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    path.delete(object);
+    buffer[index++] = 0x00;
+    const size = index - startingIndex;
+    startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size);
+    return index;
+}
+
+function isBSONType(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '_bsontype' in value &&
+        typeof value._bsontype === 'string');
+}
+const keysToCodecs = {
+    $oid: ObjectId,
+    $binary: Binary,
+    $uuid: Binary,
+    $symbol: BSONSymbol,
+    $numberInt: Int32,
+    $numberDecimal: Decimal128,
+    $numberDouble: Double,
+    $numberLong: Long,
+    $minKey: MinKey,
+    $maxKey: MaxKey,
+    $regex: BSONRegExp,
+    $regularExpression: BSONRegExp,
+    $timestamp: Timestamp
+};
+function deserializeValue(value, options = {}) {
+    if (typeof value === 'number') {
+        const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
+        const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
+        if (options.relaxed || options.legacy) {
+            return value;
+        }
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (in32BitRange) {
+                return new Int32(value);
+            }
+            if (in64BitRange) {
+                if (options.useBigInt64) {
+                    return BigInt(value);
+                }
+                return Long.fromNumber(value);
+            }
+        }
+        return new Double(value);
+    }
+    if (value == null || typeof value !== 'object')
+        return value;
+    if (value.$undefined)
+        return null;
+    const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null);
+    for (let i = 0; i < keys.length; i++) {
+        const c = keysToCodecs[keys[i]];
+        if (c)
+            return c.fromExtendedJSON(value, options);
+    }
+    if (value.$date != null) {
+        const d = value.$date;
+        const date = new Date();
+        if (options.legacy) {
+            if (typeof d === 'number')
+                date.setTime(d);
+            else if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        else {
+            if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (Long.isLong(d))
+                date.setTime(d.toNumber());
+            else if (typeof d === 'number' && options.relaxed)
+                date.setTime(d);
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        return date;
+    }
+    if (value.$code != null) {
+        const copy = Object.assign({}, value);
+        if (value.$scope) {
+            copy.$scope = deserializeValue(value.$scope);
+        }
+        return Code.fromExtendedJSON(value);
+    }
+    if (isDBRefLike(value) || value.$dbPointer) {
+        const v = value.$ref ? value : value.$dbPointer;
+        if (v instanceof DBRef)
+            return v;
+        const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
+        let valid = true;
+        dollarKeys.forEach(k => {
+            if (['$ref', '$id', '$db'].indexOf(k) === -1)
+                valid = false;
+        });
+        if (valid)
+            return DBRef.fromExtendedJSON(v);
+    }
+    return value;
+}
+function serializeArray(array, options) {
+    return array.map((v, index) => {
+        options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
+        try {
+            return serializeValue(v, options);
+        }
+        finally {
+            options.seenObjects.pop();
+        }
+    });
+}
+function getISOString(date) {
+    const isoStr = date.toISOString();
+    return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
+}
+function serializeValue(value, options) {
+    if (value instanceof Map || isMap(value)) {
+        const obj = Object.create(null);
+        for (const [k, v] of value) {
+            if (typeof k !== 'string') {
+                throw new BSONError('Can only serialize maps with string keys');
+            }
+            obj[k] = v;
+        }
+        return serializeValue(obj, options);
+    }
+    if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
+        const index = options.seenObjects.findIndex(entry => entry.obj === value);
+        if (index !== -1) {
+            const props = options.seenObjects.map(entry => entry.propertyName);
+            const leadingPart = props
+                .slice(0, index)
+                .map(prop => `${prop} -> `)
+                .join('');
+            const alreadySeen = props[index];
+            const circularPart = ' -> ' +
+                props
+                    .slice(index + 1, props.length - 1)
+                    .map(prop => `${prop} -> `)
+                    .join('');
+            const current = props[props.length - 1];
+            const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
+            const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
+            throw new BSONError('Converting circular structure to EJSON:\n' +
+                `    ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
+                `    ${leadingSpace}\\${dashes}/`);
+        }
+        options.seenObjects[options.seenObjects.length - 1].obj = value;
+    }
+    if (Array.isArray(value))
+        return serializeArray(value, options);
+    if (value === undefined)
+        return null;
+    if (value instanceof Date || isDate(value)) {
+        const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000;
+        if (options.legacy) {
+            return options.relaxed && inRange
+                ? { $date: value.getTime() }
+                : { $date: getISOString(value) };
+        }
+        return options.relaxed && inRange
+            ? { $date: getISOString(value) }
+            : { $date: { $numberLong: value.getTime().toString() } };
+    }
+    if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                return { $numberInt: value.toString() };
+            }
+            if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
+                return { $numberLong: value.toString() };
+            }
+        }
+        return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
+    }
+    if (typeof value === 'bigint') {
+        if (!options.relaxed) {
+            return { $numberLong: BigInt.asIntN(64, value).toString() };
+        }
+        return Number(BigInt.asIntN(64, value));
+    }
+    if (value instanceof RegExp || isRegExp(value)) {
+        let flags = value.flags;
+        if (flags === undefined) {
+            const match = value.toString().match(/[gimuy]*$/);
+            if (match) {
+                flags = match[0];
+            }
+        }
+        const rx = new BSONRegExp(value.source, flags);
+        return rx.toExtendedJSON(options);
+    }
+    if (value != null && typeof value === 'object')
+        return serializeDocument(value, options);
+    return value;
+}
+const BSON_TYPE_MAPPINGS = {
+    Binary: (o) => new Binary(o.value(), o.sub_type),
+    Code: (o) => new Code(o.code, o.scope),
+    DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
+    Decimal128: (o) => new Decimal128(o.bytes),
+    Double: (o) => new Double(o.value),
+    Int32: (o) => new Int32(o.value),
+    Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_),
+    MaxKey: () => new MaxKey(),
+    MinKey: () => new MinKey(),
+    ObjectId: (o) => new ObjectId(o),
+    BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
+    BSONSymbol: (o) => new BSONSymbol(o.value),
+    Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
+};
+function serializeDocument(doc, options) {
+    if (doc == null || typeof doc !== 'object')
+        throw new BSONError('not an object instance');
+    const bsontype = doc._bsontype;
+    if (typeof bsontype === 'undefined') {
+        const _doc = {};
+        for (const name of Object.keys(doc)) {
+            options.seenObjects.push({ propertyName: name, obj: null });
+            try {
+                const value = serializeValue(doc[name], options);
+                if (name === '__proto__') {
+                    Object.defineProperty(_doc, name, {
+                        value,
+                        writable: true,
+                        enumerable: true,
+                        configurable: true
+                    });
+                }
+                else {
+                    _doc[name] = value;
+                }
+            }
+            finally {
+                options.seenObjects.pop();
+            }
+        }
+        return _doc;
+    }
+    else if (doc != null &&
+        typeof doc === 'object' &&
+        typeof doc._bsontype === 'string' &&
+        doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+        throw new BSONVersionError();
+    }
+    else if (isBSONType(doc)) {
+        let outDoc = doc;
+        if (typeof outDoc.toExtendedJSON !== 'function') {
+            const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
+            if (!mapper) {
+                throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
+            }
+            outDoc = mapper(outDoc);
+        }
+        if (bsontype === 'Code' && outDoc.scope) {
+            outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
+        }
+        else if (bsontype === 'DBRef' && outDoc.oid) {
+            outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
+        }
+        return outDoc.toExtendedJSON(options);
+    }
+    else {
+        throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
+    }
+}
+function parse(text, options) {
+    const ejsonOptions = {
+        useBigInt64: options?.useBigInt64 ?? false,
+        relaxed: options?.relaxed ?? true,
+        legacy: options?.legacy ?? false
+    };
+    return JSON.parse(text, (key, value) => {
+        if (key.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
+        }
+        return deserializeValue(value, ejsonOptions);
+    });
+}
+function stringify(value, replacer, space, options) {
+    if (space != null && typeof space === 'object') {
+        options = space;
+        space = 0;
+    }
+    if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
+        options = replacer;
+        replacer = undefined;
+        space = 0;
+    }
+    const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
+        seenObjects: [{ propertyName: '(root)', obj: null }]
+    });
+    const doc = serializeValue(value, serializeOptions);
+    return JSON.stringify(doc, replacer, space);
+}
+function EJSONserialize(value, options) {
+    options = options || {};
+    return JSON.parse(stringify(value, options));
+}
+function EJSONdeserialize(ejson, options) {
+    options = options || {};
+    return parse(JSON.stringify(ejson), options);
+}
+const EJSON = Object.create(null);
+EJSON.parse = parse;
+EJSON.stringify = stringify;
+EJSON.serialize = EJSONserialize;
+EJSON.deserialize = EJSONdeserialize;
+Object.freeze(EJSON);
+
+const BSONElementType = {
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: 255,
+    maxKey: 127
+};
+function getSize(source, offset) {
+    try {
+        return NumberUtils.getNonnegativeInt32LE(source, offset);
+    }
+    catch (cause) {
+        throw new BSONOffsetError('BSON size cannot be negative', offset, { cause });
+    }
+}
+function findNull(bytes, offset) {
+    let nullTerminatorOffset = offset;
+    for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++)
+        ;
+    if (nullTerminatorOffset === bytes.length - 1) {
+        throw new BSONOffsetError('Null terminator not found', offset);
+    }
+    return nullTerminatorOffset;
+}
+function parseToElements(bytes, startOffset = 0) {
+    startOffset ??= 0;
+    if (bytes.length < 5) {
+        throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
+    }
+    const documentSize = getSize(bytes, startOffset);
+    if (documentSize > bytes.length - startOffset) {
+        throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
+    }
+    if (bytes[startOffset + documentSize - 1] !== 0x00) {
+        throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize);
+    }
+    const elements = [];
+    let offset = startOffset + 4;
+    while (offset <= documentSize + startOffset) {
+        const type = bytes[offset];
+        offset += 1;
+        if (type === 0) {
+            if (offset - startOffset !== documentSize) {
+                throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
+            }
+            break;
+        }
+        const nameOffset = offset;
+        const nameLength = findNull(bytes, offset) - nameOffset;
+        offset += nameLength + 1;
+        let length;
+        if (type === BSONElementType.double ||
+            type === BSONElementType.long ||
+            type === BSONElementType.date ||
+            type === BSONElementType.timestamp) {
+            length = 8;
+        }
+        else if (type === BSONElementType.int) {
+            length = 4;
+        }
+        else if (type === BSONElementType.objectId) {
+            length = 12;
+        }
+        else if (type === BSONElementType.decimal) {
+            length = 16;
+        }
+        else if (type === BSONElementType.bool) {
+            length = 1;
+        }
+        else if (type === BSONElementType.null ||
+            type === BSONElementType.undefined ||
+            type === BSONElementType.maxKey ||
+            type === BSONElementType.minKey) {
+            length = 0;
+        }
+        else if (type === BSONElementType.regex) {
+            length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
+        }
+        else if (type === BSONElementType.object ||
+            type === BSONElementType.array ||
+            type === BSONElementType.javascriptWithScope) {
+            length = getSize(bytes, offset);
+        }
+        else if (type === BSONElementType.string ||
+            type === BSONElementType.binData ||
+            type === BSONElementType.dbPointer ||
+            type === BSONElementType.javascript ||
+            type === BSONElementType.symbol) {
+            length = getSize(bytes, offset) + 4;
+            if (type === BSONElementType.binData) {
+                length += 1;
+            }
+            if (type === BSONElementType.dbPointer) {
+                length += 12;
+            }
+        }
+        else {
+            throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset);
+        }
+        if (length > documentSize) {
+            throw new BSONOffsetError('value reports length larger than document', offset);
+        }
+        elements.push([type, nameOffset, nameLength, offset, length]);
+        offset += length;
+    }
+    return elements;
+}
+
+const onDemand = Object.create(null);
+onDemand.parseToElements = parseToElements;
+onDemand.ByteUtils = ByteUtils;
+onDemand.NumberUtils = NumberUtils;
+Object.freeze(onDemand);
+
+const MAXSIZE = 1024 * 1024 * 17;
+let buffer = ByteUtils.allocate(MAXSIZE);
+function setInternalBufferSize(size) {
+    if (buffer.length < size) {
+        buffer = ByteUtils.allocate(size);
+    }
+}
+function serialize(object, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
+    if (buffer.length < minInternalBufferSize) {
+        buffer = ByteUtils.allocate(minInternalBufferSize);
+    }
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex);
+    finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
+    return finishedBuffer;
+}
+function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const startIndex = typeof options.index === 'number' ? options.index : 0;
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
+    return startIndex + serializationIndex - 1;
+}
+function deserialize(buffer, options = {}) {
+    return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
+}
+function calculateObjectSize(object, options = {}) {
+    options = options || {};
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
+}
+function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
+    const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
+    const bufferData = ByteUtils.toLocalBufferType(data);
+    let index = startIndex;
+    for (let i = 0; i < numberOfDocuments; i++) {
+        const size = NumberUtils.getInt32LE(bufferData, index);
+        internalOptions.index = index;
+        documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
+        index = index + size;
+    }
+    return index;
+}
+
+var bson = /*#__PURE__*/Object.freeze({
+__proto__: null,
+BSONError: BSONError,
+BSONOffsetError: BSONOffsetError,
+BSONRegExp: BSONRegExp,
+BSONRuntimeError: BSONRuntimeError,
+BSONSymbol: BSONSymbol,
+BSONType: BSONType,
+BSONValue: BSONValue,
+BSONVersionError: BSONVersionError,
+Binary: Binary,
+Code: Code,
+DBRef: DBRef,
+Decimal128: Decimal128,
+Double: Double,
+EJSON: EJSON,
+Int32: Int32,
+Long: Long,
+MaxKey: MaxKey,
+MinKey: MinKey,
+ObjectId: ObjectId,
+Timestamp: Timestamp,
+UUID: UUID,
+bsonType: bsonType,
+calculateObjectSize: calculateObjectSize,
+deserialize: deserialize,
+deserializeStream: deserializeStream,
+onDemand: onDemand,
+serialize: serialize,
+serializeWithBufferAndIndex: serializeWithBufferAndIndex,
+setInternalBufferSize: setInternalBufferSize
+});
+
+exports.BSON = bson;
+exports.BSONError = BSONError;
+exports.BSONOffsetError = BSONOffsetError;
+exports.BSONRegExp = BSONRegExp;
+exports.BSONRuntimeError = BSONRuntimeError;
+exports.BSONSymbol = BSONSymbol;
+exports.BSONType = BSONType;
+exports.BSONValue = BSONValue;
+exports.BSONVersionError = BSONVersionError;
+exports.Binary = Binary;
+exports.Code = Code;
+exports.DBRef = DBRef;
+exports.Decimal128 = Decimal128;
+exports.Double = Double;
+exports.EJSON = EJSON;
+exports.Int32 = Int32;
+exports.Long = Long;
+exports.MaxKey = MaxKey;
+exports.MinKey = MinKey;
+exports.ObjectId = ObjectId;
+exports.Timestamp = Timestamp;
+exports.UUID = UUID;
+exports.bsonType = bsonType;
+exports.calculateObjectSize = calculateObjectSize;
+exports.deserialize = deserialize;
+exports.deserializeStream = deserializeStream;
+exports.onDemand = onDemand;
+exports.serialize = serialize;
+exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
+exports.setInternalBufferSize = setInternalBufferSize;
+
+return exports;
+
+})({});
+//# sourceMappingURL=bson.bundle.js.map

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
node_modules/bson/lib/bson.bundle.js.map


+ 4670 - 0
node_modules/bson/lib/bson.cjs

@@ -0,0 +1,4670 @@
+'use strict';
+
+const TypedArrayPrototypeGetSymbolToStringTag = (() => {
+    const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
+    return (value) => g.call(value);
+})();
+function isUint8Array(value) {
+    return TypedArrayPrototypeGetSymbolToStringTag(value) === 'Uint8Array';
+}
+function isAnyArrayBuffer(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        (value[Symbol.toStringTag] === 'ArrayBuffer' ||
+            value[Symbol.toStringTag] === 'SharedArrayBuffer'));
+}
+function isRegExp(regexp) {
+    return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === '[object RegExp]';
+}
+function isMap(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        value[Symbol.toStringTag] === 'Map');
+}
+function isDate(date) {
+    return date instanceof Date || Object.prototype.toString.call(date) === '[object Date]';
+}
+function defaultInspect(x, _options) {
+    return JSON.stringify(x, (k, v) => {
+        if (typeof v === 'bigint') {
+            return { $numberLong: `${v}` };
+        }
+        else if (isMap(v)) {
+            return Object.fromEntries(v);
+        }
+        return v;
+    });
+}
+function getStylizeFunction(options) {
+    const stylizeExists = options != null &&
+        typeof options === 'object' &&
+        'stylize' in options &&
+        typeof options.stylize === 'function';
+    if (stylizeExists) {
+        return options.stylize;
+    }
+}
+
+const BSON_MAJOR_VERSION = 7;
+const BSON_VERSION_SYMBOL = Symbol.for('@@mdb.bson.version');
+const BSON_INT32_MAX = 0x7fffffff;
+const BSON_INT32_MIN = -2147483648;
+const BSON_INT64_MAX = Math.pow(2, 63) - 1;
+const BSON_INT64_MIN = -Math.pow(2, 63);
+const JS_INT_MAX = Math.pow(2, 53);
+const JS_INT_MIN = -Math.pow(2, 53);
+const BSON_DATA_NUMBER = 1;
+const BSON_DATA_STRING = 2;
+const BSON_DATA_OBJECT = 3;
+const BSON_DATA_ARRAY = 4;
+const BSON_DATA_BINARY = 5;
+const BSON_DATA_UNDEFINED = 6;
+const BSON_DATA_OID = 7;
+const BSON_DATA_BOOLEAN = 8;
+const BSON_DATA_DATE = 9;
+const BSON_DATA_NULL = 10;
+const BSON_DATA_REGEXP = 11;
+const BSON_DATA_DBPOINTER = 12;
+const BSON_DATA_CODE = 13;
+const BSON_DATA_SYMBOL = 14;
+const BSON_DATA_CODE_W_SCOPE = 15;
+const BSON_DATA_INT = 16;
+const BSON_DATA_TIMESTAMP = 17;
+const BSON_DATA_LONG = 18;
+const BSON_DATA_DECIMAL128 = 19;
+const BSON_DATA_MIN_KEY = 0xff;
+const BSON_DATA_MAX_KEY = 0x7f;
+const BSON_BINARY_SUBTYPE_DEFAULT = 0;
+const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
+const BSONType = Object.freeze({
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: -1,
+    maxKey: 127
+});
+
+class BSONError extends Error {
+    get bsonError() {
+        return true;
+    }
+    get name() {
+        return 'BSONError';
+    }
+    constructor(message, options) {
+        super(message, options);
+    }
+    static isBSONError(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            'bsonError' in value &&
+            value.bsonError === true &&
+            'name' in value &&
+            'message' in value &&
+            'stack' in value);
+    }
+}
+class BSONVersionError extends BSONError {
+    get name() {
+        return 'BSONVersionError';
+    }
+    constructor() {
+        super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
+    }
+}
+class BSONRuntimeError extends BSONError {
+    get name() {
+        return 'BSONRuntimeError';
+    }
+    constructor(message) {
+        super(message);
+    }
+}
+class BSONOffsetError extends BSONError {
+    get name() {
+        return 'BSONOffsetError';
+    }
+    offset;
+    constructor(message, offset, options) {
+        super(`${message}. offset: ${offset}`, options);
+        this.offset = offset;
+    }
+}
+
+let TextDecoderFatal;
+let TextDecoderNonFatal;
+function parseUtf8(buffer, start, end, fatal) {
+    if (fatal) {
+        TextDecoderFatal ??= new TextDecoder('utf8', { fatal: true });
+        try {
+            return TextDecoderFatal.decode(buffer.subarray(start, end));
+        }
+        catch (cause) {
+            throw new BSONError('Invalid UTF-8 string in BSON document', { cause });
+        }
+    }
+    TextDecoderNonFatal ??= new TextDecoder('utf8', { fatal: false });
+    return TextDecoderNonFatal.decode(buffer.subarray(start, end));
+}
+
+function tryReadBasicLatin(uint8array, start, end) {
+    if (uint8array.length === 0) {
+        return '';
+    }
+    const stringByteLength = end - start;
+    if (stringByteLength === 0) {
+        return '';
+    }
+    if (stringByteLength > 20) {
+        return null;
+    }
+    if (stringByteLength === 1 && uint8array[start] < 128) {
+        return String.fromCharCode(uint8array[start]);
+    }
+    if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
+        return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
+    }
+    if (stringByteLength === 3 &&
+        uint8array[start] < 128 &&
+        uint8array[start + 1] < 128 &&
+        uint8array[start + 2] < 128) {
+        return (String.fromCharCode(uint8array[start]) +
+            String.fromCharCode(uint8array[start + 1]) +
+            String.fromCharCode(uint8array[start + 2]));
+    }
+    const latinBytes = [];
+    for (let i = start; i < end; i++) {
+        const byte = uint8array[i];
+        if (byte > 127) {
+            return null;
+        }
+        latinBytes.push(byte);
+    }
+    return String.fromCharCode(...latinBytes);
+}
+function tryWriteBasicLatin(destination, source, offset) {
+    if (source.length === 0)
+        return 0;
+    if (source.length > 25)
+        return null;
+    if (destination.length - offset < source.length)
+        return null;
+    for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
+        const char = source.charCodeAt(charOffset);
+        if (char > 127)
+            return null;
+        destination[destinationOffset] = char;
+    }
+    return source.length;
+}
+
+function nodejsMathRandomBytes(byteLength) {
+    return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+function nodejsSecureRandomBytes(byteLength) {
+    return crypto.getRandomValues(nodeJsByteUtils.allocate(byteLength));
+}
+const nodejsRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return nodejsSecureRandomBytes;
+    }
+    else {
+        return nodejsMathRandomBytes;
+    }
+})();
+const nodeJsByteUtils = {
+    toLocalBufferType(potentialBuffer) {
+        if (Buffer.isBuffer(potentialBuffer)) {
+            return potentialBuffer;
+        }
+        if (ArrayBuffer.isView(potentialBuffer)) {
+            return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
+        }
+        const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return Buffer.from(potentialBuffer);
+        }
+        throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);
+    },
+    allocate(size) {
+        return Buffer.alloc(size);
+    },
+    allocateUnsafe(size) {
+        return Buffer.allocUnsafe(size);
+    },
+    equals(a, b) {
+        return nodeJsByteUtils.toLocalBufferType(a).equals(b);
+    },
+    fromNumberArray(array) {
+        return Buffer.from(array);
+    },
+    fromBase64(base64) {
+        return Buffer.from(base64, 'base64');
+    },
+    toBase64(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');
+    },
+    fromISO88591(codePoints) {
+        return Buffer.from(codePoints, 'binary');
+    },
+    toISO88591(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');
+    },
+    fromHex(hex) {
+        return Buffer.from(hex, 'hex');
+    },
+    toHex(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');
+    },
+    toUTF8(buffer, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
+        if (fatal) {
+            for (let i = 0; i < string.length; i++) {
+                if (string.charCodeAt(i) === 0xfffd) {
+                    parseUtf8(buffer, start, end, true);
+                    break;
+                }
+            }
+        }
+        return string;
+    },
+    utf8ByteLength(input) {
+        return Buffer.byteLength(input, 'utf8');
+    },
+    encodeUTF8Into(buffer, source, byteOffset) {
+        const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset);
+        if (latinBytesWritten != null) {
+            return latinBytesWritten;
+        }
+        return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
+    },
+    randomBytes: nodejsRandomBytes,
+    swap32(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).swap32();
+    }
+};
+
+function isReactNative() {
+    const { navigator } = globalThis;
+    return typeof navigator === 'object' && navigator.product === 'ReactNative';
+}
+function webMathRandomBytes(byteLength) {
+    if (byteLength < 0) {
+        throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
+    }
+    return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+const webRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return (byteLength) => {
+            return crypto.getRandomValues(webByteUtils.allocate(byteLength));
+        };
+    }
+    else {
+        if (isReactNative()) {
+            const { console } = globalThis;
+            console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');
+        }
+        return webMathRandomBytes;
+    }
+})();
+const HEX_DIGIT = /(\d|[a-f])/i;
+const webByteUtils = {
+    toLocalBufferType(potentialUint8array) {
+        const stringTag = potentialUint8array?.[Symbol.toStringTag] ??
+            Object.prototype.toString.call(potentialUint8array);
+        if (stringTag === 'Uint8Array') {
+            return potentialUint8array;
+        }
+        if (ArrayBuffer.isView(potentialUint8array)) {
+            return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
+        }
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return new Uint8Array(potentialUint8array);
+        }
+        throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);
+    },
+    allocate(size) {
+        if (typeof size !== 'number') {
+            throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
+        }
+        return new Uint8Array(size);
+    },
+    allocateUnsafe(size) {
+        return webByteUtils.allocate(size);
+    },
+    equals(a, b) {
+        if (a.byteLength !== b.byteLength) {
+            return false;
+        }
+        for (let i = 0; i < a.byteLength; i++) {
+            if (a[i] !== b[i]) {
+                return false;
+            }
+        }
+        return true;
+    },
+    fromNumberArray(array) {
+        return Uint8Array.from(array);
+    },
+    fromBase64(base64) {
+        return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
+    },
+    toBase64(uint8array) {
+        return btoa(webByteUtils.toISO88591(uint8array));
+    },
+    fromISO88591(codePoints) {
+        return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);
+    },
+    toISO88591(uint8array) {
+        return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');
+    },
+    fromHex(hex) {
+        const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
+        const buffer = [];
+        for (let i = 0; i < evenLengthHex.length; i += 2) {
+            const firstDigit = evenLengthHex[i];
+            const secondDigit = evenLengthHex[i + 1];
+            if (!HEX_DIGIT.test(firstDigit)) {
+                break;
+            }
+            if (!HEX_DIGIT.test(secondDigit)) {
+                break;
+            }
+            const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
+            buffer.push(hexDigit);
+        }
+        return Uint8Array.from(buffer);
+    },
+    toHex(uint8array) {
+        return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
+    },
+    toUTF8(uint8array, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        return parseUtf8(uint8array, start, end, fatal);
+    },
+    utf8ByteLength(input) {
+        return new TextEncoder().encode(input).byteLength;
+    },
+    encodeUTF8Into(uint8array, source, byteOffset) {
+        const bytes = new TextEncoder().encode(source);
+        uint8array.set(bytes, byteOffset);
+        return bytes.byteLength;
+    },
+    randomBytes: webRandomBytes,
+    swap32(buffer) {
+        if (buffer.length % 4 !== 0) {
+            throw new RangeError('Buffer size must be a multiple of 32-bits');
+        }
+        for (let i = 0; i < buffer.length; i += 4) {
+            const byte0 = buffer[i];
+            const byte1 = buffer[i + 1];
+            const byte2 = buffer[i + 2];
+            const byte3 = buffer[i + 3];
+            buffer[i] = byte3;
+            buffer[i + 1] = byte2;
+            buffer[i + 2] = byte1;
+            buffer[i + 3] = byte0;
+        }
+        return buffer;
+    }
+};
+
+const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
+const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
+
+const bsonType = Symbol.for('@@mdb.bson.type');
+class BSONValue {
+    get [bsonType]() {
+        return this._bsontype;
+    }
+    get [BSON_VERSION_SYMBOL]() {
+        return BSON_MAJOR_VERSION;
+    }
+    [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) {
+        return this.inspect(depth, options, inspect);
+    }
+}
+
+const FLOAT = new Float64Array(1);
+const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
+FLOAT[0] = -1;
+const isBigEndian = FLOAT_BYTES[7] === 0;
+const NumberUtils = {
+    isBigEndian,
+    getNonnegativeInt32LE(source, offset) {
+        if (source[offset + 3] > 127) {
+            throw new RangeError(`Size cannot be negative at offset: ${offset}`);
+        }
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getInt32LE(source, offset) {
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getUint32LE(source, offset) {
+        return (source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+    },
+    getUint32BE(source, offset) {
+        return (source[offset + 3] +
+            source[offset + 2] * 256 +
+            source[offset + 1] * 65536 +
+            source[offset] * 16777216);
+    },
+    getBigInt64LE(source, offset) {
+        const hi = BigInt(source[offset + 4] +
+            source[offset + 5] * 256 +
+            source[offset + 6] * 65536 +
+            (source[offset + 7] << 24));
+        const lo = BigInt(source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+        return (hi << 32n) + lo;
+    },
+    getFloat64LE: isBigEndian
+        ? (source, offset) => {
+            FLOAT_BYTES[7] = source[offset];
+            FLOAT_BYTES[6] = source[offset + 1];
+            FLOAT_BYTES[5] = source[offset + 2];
+            FLOAT_BYTES[4] = source[offset + 3];
+            FLOAT_BYTES[3] = source[offset + 4];
+            FLOAT_BYTES[2] = source[offset + 5];
+            FLOAT_BYTES[1] = source[offset + 6];
+            FLOAT_BYTES[0] = source[offset + 7];
+            return FLOAT[0];
+        }
+        : (source, offset) => {
+            FLOAT_BYTES[0] = source[offset];
+            FLOAT_BYTES[1] = source[offset + 1];
+            FLOAT_BYTES[2] = source[offset + 2];
+            FLOAT_BYTES[3] = source[offset + 3];
+            FLOAT_BYTES[4] = source[offset + 4];
+            FLOAT_BYTES[5] = source[offset + 5];
+            FLOAT_BYTES[6] = source[offset + 6];
+            FLOAT_BYTES[7] = source[offset + 7];
+            return FLOAT[0];
+        },
+    setInt32BE(destination, offset, value) {
+        destination[offset + 3] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset] = value;
+        return 4;
+    },
+    setInt32LE(destination, offset, value) {
+        destination[offset] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 3] = value;
+        return 4;
+    },
+    setBigInt64LE(destination, offset, value) {
+        const mask32bits = 0xffffffffn;
+        let lo = Number(value & mask32bits);
+        destination[offset] = lo;
+        lo >>= 8;
+        destination[offset + 1] = lo;
+        lo >>= 8;
+        destination[offset + 2] = lo;
+        lo >>= 8;
+        destination[offset + 3] = lo;
+        let hi = Number((value >> 32n) & mask32bits);
+        destination[offset + 4] = hi;
+        hi >>= 8;
+        destination[offset + 5] = hi;
+        hi >>= 8;
+        destination[offset + 6] = hi;
+        hi >>= 8;
+        destination[offset + 7] = hi;
+        return 8;
+    },
+    setFloat64LE: isBigEndian
+        ? (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[7];
+            destination[offset + 1] = FLOAT_BYTES[6];
+            destination[offset + 2] = FLOAT_BYTES[5];
+            destination[offset + 3] = FLOAT_BYTES[4];
+            destination[offset + 4] = FLOAT_BYTES[3];
+            destination[offset + 5] = FLOAT_BYTES[2];
+            destination[offset + 6] = FLOAT_BYTES[1];
+            destination[offset + 7] = FLOAT_BYTES[0];
+            return 8;
+        }
+        : (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[0];
+            destination[offset + 1] = FLOAT_BYTES[1];
+            destination[offset + 2] = FLOAT_BYTES[2];
+            destination[offset + 3] = FLOAT_BYTES[3];
+            destination[offset + 4] = FLOAT_BYTES[4];
+            destination[offset + 5] = FLOAT_BYTES[5];
+            destination[offset + 6] = FLOAT_BYTES[6];
+            destination[offset + 7] = FLOAT_BYTES[7];
+            return 8;
+        }
+};
+
+class Binary extends BSONValue {
+    get _bsontype() {
+        return 'Binary';
+    }
+    static BSON_BINARY_SUBTYPE_DEFAULT = 0;
+    static BUFFER_SIZE = 256;
+    static SUBTYPE_DEFAULT = 0;
+    static SUBTYPE_FUNCTION = 1;
+    static SUBTYPE_BYTE_ARRAY = 2;
+    static SUBTYPE_UUID_OLD = 3;
+    static SUBTYPE_UUID = 4;
+    static SUBTYPE_MD5 = 5;
+    static SUBTYPE_ENCRYPTED = 6;
+    static SUBTYPE_COLUMN = 7;
+    static SUBTYPE_SENSITIVE = 8;
+    static SUBTYPE_VECTOR = 9;
+    static SUBTYPE_USER_DEFINED = 128;
+    static VECTOR_TYPE = Object.freeze({
+        Int8: 0x03,
+        Float32: 0x27,
+        PackedBit: 0x10
+    });
+    buffer;
+    sub_type;
+    position;
+    constructor(buffer, subType) {
+        super();
+        if (!(buffer == null) &&
+            typeof buffer === 'string' &&
+            !ArrayBuffer.isView(buffer) &&
+            !isAnyArrayBuffer(buffer) &&
+            !Array.isArray(buffer)) {
+            throw new BSONError('Binary can only be constructed from Uint8Array or number[]');
+        }
+        this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
+        if (buffer == null) {
+            this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
+            this.position = 0;
+        }
+        else {
+            this.buffer = Array.isArray(buffer)
+                ? ByteUtils.fromNumberArray(buffer)
+                : ByteUtils.toLocalBufferType(buffer);
+            this.position = this.buffer.byteLength;
+        }
+    }
+    put(byteValue) {
+        if (typeof byteValue === 'string' && byteValue.length !== 1) {
+            throw new BSONError('only accepts single character String');
+        }
+        else if (typeof byteValue !== 'number' && byteValue.length !== 1)
+            throw new BSONError('only accepts single character Uint8Array or Array');
+        let decodedByte;
+        if (typeof byteValue === 'string') {
+            decodedByte = byteValue.charCodeAt(0);
+        }
+        else if (typeof byteValue === 'number') {
+            decodedByte = byteValue;
+        }
+        else {
+            decodedByte = byteValue[0];
+        }
+        if (decodedByte < 0 || decodedByte > 255) {
+            throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
+        }
+        if (this.buffer.byteLength > this.position) {
+            this.buffer[this.position++] = decodedByte;
+        }
+        else {
+            const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+            this.buffer[this.position++] = decodedByte;
+        }
+    }
+    write(sequence, offset) {
+        offset = typeof offset === 'number' ? offset : this.position;
+        if (this.buffer.byteLength < offset + sequence.length) {
+            const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+        }
+        if (ArrayBuffer.isView(sequence)) {
+            this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
+            this.position =
+                offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
+        }
+        else if (typeof sequence === 'string') {
+            throw new BSONError('input cannot be string');
+        }
+    }
+    read(position, length) {
+        length = length && length > 0 ? length : this.position;
+        const end = position + length;
+        return this.buffer.subarray(position, end > this.position ? this.position : end);
+    }
+    value() {
+        return this.buffer.length === this.position
+            ? this.buffer
+            : this.buffer.subarray(0, this.position);
+    }
+    length() {
+        return this.position;
+    }
+    toJSON() {
+        return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.buffer.subarray(0, this.position));
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        if (encoding === 'utf8' || encoding === 'utf-8')
+            return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+        return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (this.sub_type === Binary.SUBTYPE_VECTOR) {
+            validateBinaryVector(this);
+        }
+        const base64String = ByteUtils.toBase64(this.buffer);
+        const subType = Number(this.sub_type).toString(16);
+        if (options.legacy) {
+            return {
+                $binary: base64String,
+                $type: subType.length === 1 ? '0' + subType : subType
+            };
+        }
+        return {
+            $binary: {
+                base64: base64String,
+                subType: subType.length === 1 ? '0' + subType : subType
+            }
+        };
+    }
+    toUUID() {
+        if (this.sub_type === Binary.SUBTYPE_UUID) {
+            return new UUID(this.buffer.subarray(0, this.position));
+        }
+        throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
+    }
+    static createFromHexString(hex, subType) {
+        return new Binary(ByteUtils.fromHex(hex), subType);
+    }
+    static createFromBase64(base64, subType) {
+        return new Binary(ByteUtils.fromBase64(base64), subType);
+    }
+    static fromExtendedJSON(doc, options) {
+        options = options || {};
+        let data;
+        let type;
+        if ('$binary' in doc) {
+            if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
+                type = doc.$type ? parseInt(doc.$type, 16) : 0;
+                data = ByteUtils.fromBase64(doc.$binary);
+            }
+            else {
+                if (typeof doc.$binary !== 'string') {
+                    type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
+                    data = ByteUtils.fromBase64(doc.$binary.base64);
+                }
+            }
+        }
+        else if ('$uuid' in doc) {
+            type = 4;
+            data = UUID.bytesFromString(doc.$uuid);
+        }
+        if (!data) {
+            throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
+        }
+        return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        const base64Arg = inspect(base64, options);
+        const subTypeArg = inspect(this.sub_type, options);
+        return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
+    }
+    toInt8Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {
+            throw new BSONError('Binary datatype field is not Int8');
+        }
+        validateBinaryVector(this);
+        return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toFloat32Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {
+            throw new BSONError('Binary datatype field is not Float32');
+        }
+        validateBinaryVector(this);
+        const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(floatBytes);
+        return new Float32Array(floatBytes.buffer);
+    }
+    toPackedBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        const byteCount = this.length() - 2;
+        const bitCount = byteCount * 8 - this.buffer[1];
+        const bits = new Int8Array(bitCount);
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = (bitOffset / 8) | 0;
+            const byte = this.buffer[byteOffset + 2];
+            const shift = 7 - (bitOffset % 8);
+            const bit = (byte >> shift) & 1;
+            bits[bitOffset] = bit;
+        }
+        return bits;
+    }
+    static fromInt8Array(array) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.Int8;
+        buffer[1] = 0;
+        const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        buffer.set(intBytes, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromFloat32Array(array) {
+        const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
+        binaryBytes[0] = Binary.VECTOR_TYPE.Float32;
+        binaryBytes[1] = 0;
+        const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        binaryBytes.set(floatBytes, 2);
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
+        const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromPackedBits(array, padding = 0) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.PackedBit;
+        buffer[1] = padding;
+        buffer.set(array, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromBits(bits) {
+        const byteLength = (bits.length + 7) >>> 3;
+        const bytes = new Uint8Array(byteLength + 2);
+        bytes[0] = Binary.VECTOR_TYPE.PackedBit;
+        const remainder = bits.length % 8;
+        bytes[1] = remainder === 0 ? 0 : 8 - remainder;
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = bitOffset >>> 3;
+            const bit = bits[bitOffset];
+            if (bit !== 0 && bit !== 1) {
+                throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
+            }
+            if (bit === 0)
+                continue;
+            const shift = 7 - (bitOffset % 8);
+            bytes[byteOffset + 2] |= bit << shift;
+        }
+        return new this(bytes, Binary.SUBTYPE_VECTOR);
+    }
+}
+function validateBinaryVector(vector) {
+    if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
+        return;
+    const size = vector.position;
+    const datatype = vector.buffer[0];
+    const padding = vector.buffer[1];
+    if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) &&
+        padding !== 0) {
+        throw new BSONError('Invalid Vector: padding must be zero for int8 and float32 vectors');
+    }
+    if (datatype === Binary.VECTOR_TYPE.Float32) {
+        if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
+            throw new BSONError('Invalid Vector: Float32 vector must contain a multiple of 4 bytes');
+        }
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
+        throw new BSONError('Invalid Vector: padding must be zero for packed bit vectors that are empty');
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
+        throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
+    }
+}
+const UUID_BYTE_LENGTH = 16;
+const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
+const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
+class UUID extends Binary {
+    constructor(input) {
+        let bytes;
+        if (input == null) {
+            bytes = UUID.generate();
+        }
+        else if (input instanceof UUID) {
+            bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
+        }
+        else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
+            bytes = ByteUtils.toLocalBufferType(input);
+        }
+        else if (typeof input === 'string') {
+            bytes = UUID.bytesFromString(input);
+        }
+        else {
+            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).');
+        }
+        super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+    }
+    toHexString(includeDashes = true) {
+        if (includeDashes) {
+            return [
+                ByteUtils.toHex(this.buffer.subarray(0, 4)),
+                ByteUtils.toHex(this.buffer.subarray(4, 6)),
+                ByteUtils.toHex(this.buffer.subarray(6, 8)),
+                ByteUtils.toHex(this.buffer.subarray(8, 10)),
+                ByteUtils.toHex(this.buffer.subarray(10, 16))
+            ].join('-');
+        }
+        return ByteUtils.toHex(this.buffer);
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.id);
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    equals(otherId) {
+        if (!otherId) {
+            return false;
+        }
+        if (otherId instanceof UUID) {
+            return ByteUtils.equals(otherId.id, this.id);
+        }
+        try {
+            return ByteUtils.equals(new UUID(otherId).id, this.id);
+        }
+        catch {
+            return false;
+        }
+    }
+    toBinary() {
+        return new Binary(this.id, Binary.SUBTYPE_UUID);
+    }
+    static generate() {
+        const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
+        bytes[6] = (bytes[6] & 0x0f) | 0x40;
+        bytes[8] = (bytes[8] & 0x3f) | 0x80;
+        return bytes;
+    }
+    static isValid(input) {
+        if (!input) {
+            return false;
+        }
+        if (typeof input === 'string') {
+            return UUID.isValidUUIDString(input);
+        }
+        if (isUint8Array(input)) {
+            return input.byteLength === UUID_BYTE_LENGTH;
+        }
+        return (input._bsontype === 'Binary' &&
+            input.sub_type === this.SUBTYPE_UUID &&
+            input.buffer.byteLength === 16);
+    }
+    static createFromHexString(hexString) {
+        const buffer = UUID.bytesFromString(hexString);
+        return new UUID(buffer);
+    }
+    static createFromBase64(base64) {
+        return new UUID(ByteUtils.fromBase64(base64));
+    }
+    static bytesFromString(representation) {
+        if (!UUID.isValidUUIDString(representation)) {
+            throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
+        }
+        return ByteUtils.fromHex(representation.replace(/-/g, ''));
+    }
+    static isValidUUIDString(representation) {
+        return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new UUID(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+class Code extends BSONValue {
+    get _bsontype() {
+        return 'Code';
+    }
+    code;
+    scope;
+    constructor(code, scope) {
+        super();
+        this.code = code.toString();
+        this.scope = scope ?? null;
+    }
+    toJSON() {
+        if (this.scope != null) {
+            return { code: this.code, scope: this.scope };
+        }
+        return { code: this.code };
+    }
+    toExtendedJSON() {
+        if (this.scope) {
+            return { $code: this.code, $scope: this.scope };
+        }
+        return { $code: this.code };
+    }
+    static fromExtendedJSON(doc) {
+        return new Code(doc.$code, doc.$scope);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        let parametersString = inspect(this.code, options);
+        const multiLineFn = parametersString.includes('\n');
+        if (this.scope != null) {
+            parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
+        }
+        const endingNewline = multiLineFn && this.scope === null;
+        return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
+    }
+}
+
+function isDBRefLike(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '$id' in value &&
+        value.$id != null &&
+        '$ref' in value &&
+        typeof value.$ref === 'string' &&
+        (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));
+}
+class DBRef extends BSONValue {
+    get _bsontype() {
+        return 'DBRef';
+    }
+    collection;
+    oid;
+    db;
+    fields;
+    constructor(collection, oid, db, fields) {
+        super();
+        const parts = collection.split('.');
+        if (parts.length === 2) {
+            db = parts.shift();
+            collection = parts.shift();
+        }
+        this.collection = collection;
+        this.oid = oid;
+        this.db = db;
+        this.fields = fields || {};
+    }
+    get namespace() {
+        return this.collection;
+    }
+    set namespace(value) {
+        this.collection = value;
+    }
+    toJSON() {
+        const o = Object.assign({
+            $ref: this.collection,
+            $id: this.oid
+        }, this.fields);
+        if (this.db != null)
+            o.$db = this.db;
+        return o;
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        let o = {
+            $ref: this.collection,
+            $id: this.oid
+        };
+        if (options.legacy) {
+            return o;
+        }
+        if (this.db)
+            o.$db = this.db;
+        o = Object.assign(o, this.fields);
+        return o;
+    }
+    static fromExtendedJSON(doc) {
+        const copy = Object.assign({}, doc);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const args = [
+            inspect(this.namespace, options),
+            inspect(this.oid, options),
+            ...(this.db ? [inspect(this.db, options)] : []),
+            ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
+        ];
+        args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
+        return `new DBRef(${args.join(', ')})`;
+    }
+}
+
+function removeLeadingZerosAndExplicitPlus(str) {
+    if (str === '') {
+        return str;
+    }
+    let startIndex = 0;
+    const isNegative = str[startIndex] === '-';
+    const isExplicitlyPositive = str[startIndex] === '+';
+    if (isExplicitlyPositive || isNegative) {
+        startIndex += 1;
+    }
+    let foundInsignificantZero = false;
+    for (; startIndex < str.length && str[startIndex] === '0'; ++startIndex) {
+        foundInsignificantZero = true;
+    }
+    if (!foundInsignificantZero) {
+        return isExplicitlyPositive ? str.slice(1) : str;
+    }
+    return `${isNegative ? '-' : ''}${str.length === startIndex ? '0' : str.slice(startIndex)}`;
+}
+function validateStringCharacters(str, radix) {
+    radix = radix ?? 10;
+    const validCharacters = '0123456789abcdefghijklmnopqrstuvwxyz'.slice(0, radix);
+    const regex = new RegExp(`[^-+${validCharacters}]`, 'i');
+    return regex.test(str) ? false : str;
+}
+
+let wasm = undefined;
+try {
+    wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
+}
+catch {
+}
+const TWO_PWR_16_DBL = 1 << 16;
+const TWO_PWR_24_DBL = 1 << 24;
+const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
+const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
+const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
+const INT_CACHE = {};
+const UINT_CACHE = {};
+const MAX_INT64_STRING_LENGTH = 20;
+const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
+class Long extends BSONValue {
+    get _bsontype() {
+        return 'Long';
+    }
+    get __isLong__() {
+        return true;
+    }
+    high;
+    low;
+    unsigned;
+    constructor(lowOrValue = 0, highOrUnsigned, unsigned) {
+        super();
+        const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);
+        const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;
+        const res = typeof lowOrValue === 'string'
+            ? Long.fromString(lowOrValue, unsignedBool)
+            : typeof lowOrValue === 'bigint'
+                ? Long.fromBigInt(lowOrValue, unsignedBool)
+                : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
+        this.low = res.low;
+        this.high = res.high;
+        this.unsigned = res.unsigned;
+    }
+    static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
+    static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
+    static ZERO = Long.fromInt(0);
+    static UZERO = Long.fromInt(0, true);
+    static ONE = Long.fromInt(1);
+    static UONE = Long.fromInt(1, true);
+    static NEG_ONE = Long.fromInt(-1);
+    static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
+    static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
+    static fromBits(lowBits, highBits, unsigned) {
+        return new Long(lowBits, highBits, unsigned);
+    }
+    static fromInt(value, unsigned) {
+        let obj, cachedObj, cache;
+        if (unsigned) {
+            value >>>= 0;
+            if ((cache = 0 <= value && value < 256)) {
+                cachedObj = UINT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
+            if (cache)
+                UINT_CACHE[value] = obj;
+            return obj;
+        }
+        else {
+            value |= 0;
+            if ((cache = -128 <= value && value < 128)) {
+                cachedObj = INT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
+            if (cache)
+                INT_CACHE[value] = obj;
+            return obj;
+        }
+    }
+    static fromNumber(value, unsigned) {
+        if (isNaN(value))
+            return unsigned ? Long.UZERO : Long.ZERO;
+        if (unsigned) {
+            if (value < 0)
+                return Long.UZERO;
+            if (value >= TWO_PWR_64_DBL)
+                return Long.MAX_UNSIGNED_VALUE;
+        }
+        else {
+            if (value <= -TWO_PWR_63_DBL)
+                return Long.MIN_VALUE;
+            if (value + 1 >= TWO_PWR_63_DBL)
+                return Long.MAX_VALUE;
+        }
+        if (value < 0)
+            return Long.fromNumber(-value, unsigned).neg();
+        return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
+    }
+    static fromBigInt(value, unsigned) {
+        const FROM_BIGINT_BIT_MASK = 0xffffffffn;
+        const FROM_BIGINT_BIT_SHIFT = 32n;
+        return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number((value >> FROM_BIGINT_BIT_SHIFT) & FROM_BIGINT_BIT_MASK), unsigned);
+    }
+    static _fromString(str, unsigned, radix) {
+        if (str.length === 0)
+            throw new BSONError('empty string');
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        let p;
+        if ((p = str.indexOf('-')) > 0)
+            throw new BSONError('interior hyphen');
+        else if (p === 0) {
+            return Long._fromString(str.substring(1), unsigned, radix).neg();
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 8));
+        let result = Long.ZERO;
+        for (let i = 0; i < str.length; i += 8) {
+            const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
+            if (size < 8) {
+                const power = Long.fromNumber(Math.pow(radix, size));
+                result = result.mul(power).add(Long.fromNumber(value));
+            }
+            else {
+                result = result.mul(radixToPower);
+                result = result.add(Long.fromNumber(value));
+            }
+        }
+        result.unsigned = unsigned;
+        return result;
+    }
+    static fromStringStrict(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str.trim() !== str) {
+            throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
+        }
+        if (!validateStringCharacters(str, radix)) {
+            throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
+        }
+        const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
+        const result = Long._fromString(cleanedStr, unsigned, radix);
+        if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
+            throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? 'an unsigned' : 'a signed'} 64-bit Long ${radix != null ? `with radix: ${radix}` : ''}`);
+        }
+        return result;
+    }
+    static fromString(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str === 'NaN' && radix < 24) {
+            return Long.ZERO;
+        }
+        else if ((str === 'Infinity' || str === '+Infinity' || str === '-Infinity') && radix < 35) {
+            return Long.ZERO;
+        }
+        return Long._fromString(str, unsigned, radix);
+    }
+    static fromBytes(bytes, unsigned, le) {
+        return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
+    }
+    static fromBytesLE(bytes, unsigned) {
+        return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned);
+    }
+    static fromBytesBE(bytes, unsigned) {
+        return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned);
+    }
+    static isLong(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            '__isLong__' in value &&
+            value.__isLong__ === true);
+    }
+    static fromValue(val, unsigned) {
+        if (typeof val === 'number')
+            return Long.fromNumber(val, unsigned);
+        if (typeof val === 'string')
+            return Long.fromString(val, unsigned);
+        return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
+    }
+    add(addend) {
+        if (!Long.isLong(addend))
+            addend = Long.fromValue(addend);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = addend.high >>> 16;
+        const b32 = addend.high & 0xffff;
+        const b16 = addend.low >>> 16;
+        const b00 = addend.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 + b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 + b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 + b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 + b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    and(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
+    }
+    compare(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.eq(other))
+            return 0;
+        const thisNeg = this.isNegative(), otherNeg = other.isNegative();
+        if (thisNeg && !otherNeg)
+            return -1;
+        if (!thisNeg && otherNeg)
+            return 1;
+        if (!this.unsigned)
+            return this.sub(other).isNegative() ? -1 : 1;
+        return other.high >>> 0 > this.high >>> 0 ||
+            (other.high === this.high && other.low >>> 0 > this.low >>> 0)
+            ? -1
+            : 1;
+    }
+    comp(other) {
+        return this.compare(other);
+    }
+    divide(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (divisor.isZero())
+            throw new BSONError('division by zero');
+        if (wasm) {
+            if (!this.unsigned &&
+                this.high === -2147483648 &&
+                divisor.low === -1 &&
+                divisor.high === -1) {
+                return this;
+            }
+            const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (this.isZero())
+            return this.unsigned ? Long.UZERO : Long.ZERO;
+        let approx, rem, res;
+        if (!this.unsigned) {
+            if (this.eq(Long.MIN_VALUE)) {
+                if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
+                    return Long.MIN_VALUE;
+                else if (divisor.eq(Long.MIN_VALUE))
+                    return Long.ONE;
+                else {
+                    const halfThis = this.shr(1);
+                    approx = halfThis.div(divisor).shl(1);
+                    if (approx.eq(Long.ZERO)) {
+                        return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
+                    }
+                    else {
+                        rem = this.sub(divisor.mul(approx));
+                        res = approx.add(rem.div(divisor));
+                        return res;
+                    }
+                }
+            }
+            else if (divisor.eq(Long.MIN_VALUE))
+                return this.unsigned ? Long.UZERO : Long.ZERO;
+            if (this.isNegative()) {
+                if (divisor.isNegative())
+                    return this.neg().div(divisor.neg());
+                return this.neg().div(divisor).neg();
+            }
+            else if (divisor.isNegative())
+                return this.div(divisor.neg()).neg();
+            res = Long.ZERO;
+        }
+        else {
+            if (!divisor.unsigned)
+                divisor = divisor.toUnsigned();
+            if (divisor.gt(this))
+                return Long.UZERO;
+            if (divisor.gt(this.shru(1)))
+                return Long.UONE;
+            res = Long.UZERO;
+        }
+        rem = this;
+        while (rem.gte(divisor)) {
+            approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
+            const log2 = Math.ceil(Math.log(approx) / Math.LN2);
+            const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
+            let approxRes = Long.fromNumber(approx);
+            let approxRem = approxRes.mul(divisor);
+            while (approxRem.isNegative() || approxRem.gt(rem)) {
+                approx -= delta;
+                approxRes = Long.fromNumber(approx, this.unsigned);
+                approxRem = approxRes.mul(divisor);
+            }
+            if (approxRes.isZero())
+                approxRes = Long.ONE;
+            res = res.add(approxRes);
+            rem = rem.sub(approxRem);
+        }
+        return res;
+    }
+    div(divisor) {
+        return this.divide(divisor);
+    }
+    equals(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
+            return false;
+        return this.high === other.high && this.low === other.low;
+    }
+    eq(other) {
+        return this.equals(other);
+    }
+    getHighBits() {
+        return this.high;
+    }
+    getHighBitsUnsigned() {
+        return this.high >>> 0;
+    }
+    getLowBits() {
+        return this.low;
+    }
+    getLowBitsUnsigned() {
+        return this.low >>> 0;
+    }
+    getNumBitsAbs() {
+        if (this.isNegative()) {
+            return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
+        }
+        const val = this.high !== 0 ? this.high : this.low;
+        let bit;
+        for (bit = 31; bit > 0; bit--)
+            if ((val & (1 << bit)) !== 0)
+                break;
+        return this.high !== 0 ? bit + 33 : bit + 1;
+    }
+    greaterThan(other) {
+        return this.comp(other) > 0;
+    }
+    gt(other) {
+        return this.greaterThan(other);
+    }
+    greaterThanOrEqual(other) {
+        return this.comp(other) >= 0;
+    }
+    gte(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    ge(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    isEven() {
+        return (this.low & 1) === 0;
+    }
+    isNegative() {
+        return !this.unsigned && this.high < 0;
+    }
+    isOdd() {
+        return (this.low & 1) === 1;
+    }
+    isPositive() {
+        return this.unsigned || this.high >= 0;
+    }
+    isZero() {
+        return this.high === 0 && this.low === 0;
+    }
+    lessThan(other) {
+        return this.comp(other) < 0;
+    }
+    lt(other) {
+        return this.lessThan(other);
+    }
+    lessThanOrEqual(other) {
+        return this.comp(other) <= 0;
+    }
+    lte(other) {
+        return this.lessThanOrEqual(other);
+    }
+    modulo(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (wasm) {
+            const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        return this.sub(this.div(divisor).mul(divisor));
+    }
+    mod(divisor) {
+        return this.modulo(divisor);
+    }
+    rem(divisor) {
+        return this.modulo(divisor);
+    }
+    multiply(multiplier) {
+        if (this.isZero())
+            return Long.ZERO;
+        if (!Long.isLong(multiplier))
+            multiplier = Long.fromValue(multiplier);
+        if (wasm) {
+            const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (multiplier.isZero())
+            return Long.ZERO;
+        if (this.eq(Long.MIN_VALUE))
+            return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (multiplier.eq(Long.MIN_VALUE))
+            return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (this.isNegative()) {
+            if (multiplier.isNegative())
+                return this.neg().mul(multiplier.neg());
+            else
+                return this.neg().mul(multiplier).neg();
+        }
+        else if (multiplier.isNegative())
+            return this.mul(multiplier.neg()).neg();
+        if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
+            return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = multiplier.high >>> 16;
+        const b32 = multiplier.high & 0xffff;
+        const b16 = multiplier.low >>> 16;
+        const b00 = multiplier.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 * b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 * b00;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c16 += a00 * b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 * b00;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a16 * b16;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a00 * b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    mul(multiplier) {
+        return this.multiply(multiplier);
+    }
+    negate() {
+        if (!this.unsigned && this.eq(Long.MIN_VALUE))
+            return Long.MIN_VALUE;
+        return this.not().add(Long.ONE);
+    }
+    neg() {
+        return this.negate();
+    }
+    not() {
+        return Long.fromBits(~this.low, ~this.high, this.unsigned);
+    }
+    notEquals(other) {
+        return !this.equals(other);
+    }
+    neq(other) {
+        return this.notEquals(other);
+    }
+    ne(other) {
+        return this.notEquals(other);
+    }
+    or(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
+    }
+    shiftLeft(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
+        else
+            return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
+    }
+    shl(numBits) {
+        return this.shiftLeft(numBits);
+    }
+    shiftRight(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
+        else
+            return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
+    }
+    shr(numBits) {
+        return this.shiftRight(numBits);
+    }
+    shiftRightUnsigned(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        numBits &= 63;
+        if (numBits === 0)
+            return this;
+        else {
+            const high = this.high;
+            if (numBits < 32) {
+                const low = this.low;
+                return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
+            }
+            else if (numBits === 32)
+                return Long.fromBits(high, 0, this.unsigned);
+            else
+                return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
+        }
+    }
+    shr_u(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    shru(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    subtract(subtrahend) {
+        if (!Long.isLong(subtrahend))
+            subtrahend = Long.fromValue(subtrahend);
+        return this.add(subtrahend.neg());
+    }
+    sub(subtrahend) {
+        return this.subtract(subtrahend);
+    }
+    toInt() {
+        return this.unsigned ? this.low >>> 0 : this.low;
+    }
+    toNumber() {
+        if (this.unsigned)
+            return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
+        return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
+    }
+    toBigInt() {
+        return BigInt(this.toString());
+    }
+    toBytes(le) {
+        return le ? this.toBytesLE() : this.toBytesBE();
+    }
+    toBytesLE() {
+        const hi = this.high, lo = this.low;
+        return [
+            lo & 0xff,
+            (lo >>> 8) & 0xff,
+            (lo >>> 16) & 0xff,
+            lo >>> 24,
+            hi & 0xff,
+            (hi >>> 8) & 0xff,
+            (hi >>> 16) & 0xff,
+            hi >>> 24
+        ];
+    }
+    toBytesBE() {
+        const hi = this.high, lo = this.low;
+        return [
+            hi >>> 24,
+            (hi >>> 16) & 0xff,
+            (hi >>> 8) & 0xff,
+            hi & 0xff,
+            lo >>> 24,
+            (lo >>> 16) & 0xff,
+            (lo >>> 8) & 0xff,
+            lo & 0xff
+        ];
+    }
+    toSigned() {
+        if (!this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, false);
+    }
+    toString(radix) {
+        radix = radix || 10;
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        if (this.isZero())
+            return '0';
+        if (this.isNegative()) {
+            if (this.eq(Long.MIN_VALUE)) {
+                const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
+                return div.toString(radix) + rem1.toInt().toString(radix);
+            }
+            else
+                return '-' + this.neg().toString(radix);
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
+        let rem = this;
+        let result = '';
+        while (true) {
+            const remDiv = rem.div(radixToPower);
+            const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
+            let digits = intval.toString(radix);
+            rem = remDiv;
+            if (rem.isZero()) {
+                return digits + result;
+            }
+            else {
+                while (digits.length < 6)
+                    digits = '0' + digits;
+                result = '' + digits + result;
+            }
+        }
+    }
+    toUnsigned() {
+        if (this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, true);
+    }
+    xor(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
+    }
+    eqz() {
+        return this.isZero();
+    }
+    le(other) {
+        return this.lessThanOrEqual(other);
+    }
+    toExtendedJSON(options) {
+        if (options && options.relaxed)
+            return this.toNumber();
+        return { $numberLong: this.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        const { useBigInt64 = false, relaxed = true } = { ...options };
+        if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
+            throw new BSONError('$numberLong string is too long');
+        }
+        if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
+            throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
+        }
+        if (useBigInt64) {
+            const bigIntResult = BigInt(doc.$numberLong);
+            return BigInt.asIntN(64, bigIntResult);
+        }
+        const longResult = Long.fromString(doc.$numberLong);
+        if (relaxed) {
+            return longResult.toNumber();
+        }
+        return longResult;
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const longVal = inspect(this.toString(), options);
+        const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
+        return `new Long(${longVal}${unsignedVal})`;
+    }
+}
+
+const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
+const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
+const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
+const EXPONENT_MAX = 6111;
+const EXPONENT_MIN = -6176;
+const EXPONENT_BIAS = 6176;
+const MAX_DIGITS = 34;
+const NAN_BUFFER = ByteUtils.fromNumberArray([
+    0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
+    0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
+    0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
+const COMBINATION_MASK = 0x1f;
+const EXPONENT_MASK = 0x3fff;
+const COMBINATION_INFINITY = 30;
+const COMBINATION_NAN = 31;
+function isDigit(value) {
+    return !isNaN(parseInt(value, 10));
+}
+function divideu128(value) {
+    const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
+    let _rem = Long.fromNumber(0);
+    if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
+        return { quotient: value, rem: _rem };
+    }
+    for (let i = 0; i <= 3; i++) {
+        _rem = _rem.shiftLeft(32);
+        _rem = _rem.add(new Long(value.parts[i], 0));
+        value.parts[i] = _rem.div(DIVISOR).low;
+        _rem = _rem.modulo(DIVISOR);
+    }
+    return { quotient: value, rem: _rem };
+}
+function multiply64x2(left, right) {
+    if (!left && !right) {
+        return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
+    }
+    const leftHigh = left.shiftRightUnsigned(32);
+    const leftLow = new Long(left.getLowBits(), 0);
+    const rightHigh = right.shiftRightUnsigned(32);
+    const rightLow = new Long(right.getLowBits(), 0);
+    let productHigh = leftHigh.multiply(rightHigh);
+    let productMid = leftHigh.multiply(rightLow);
+    const productMid2 = leftLow.multiply(rightHigh);
+    let productLow = leftLow.multiply(rightLow);
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productMid = new Long(productMid.getLowBits(), 0)
+        .add(productMid2)
+        .add(productLow.shiftRightUnsigned(32));
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
+    return { high: productHigh, low: productLow };
+}
+function lessThan(left, right) {
+    const uhleft = left.high >>> 0;
+    const uhright = right.high >>> 0;
+    if (uhleft < uhright) {
+        return true;
+    }
+    else if (uhleft === uhright) {
+        const ulleft = left.low >>> 0;
+        const ulright = right.low >>> 0;
+        if (ulleft < ulright)
+            return true;
+    }
+    return false;
+}
+function invalidErr(string, message) {
+    throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
+}
+class Decimal128 extends BSONValue {
+    get _bsontype() {
+        return 'Decimal128';
+    }
+    bytes;
+    constructor(bytes) {
+        super();
+        if (typeof bytes === 'string') {
+            this.bytes = Decimal128.fromString(bytes).bytes;
+        }
+        else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
+            if (bytes.byteLength !== 16) {
+                throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
+            }
+            this.bytes = bytes;
+        }
+        else {
+            throw new BSONError('Decimal128 must take a Buffer or string');
+        }
+    }
+    static fromString(representation) {
+        return Decimal128._fromString(representation, { allowRounding: false });
+    }
+    static fromStringWithRounding(representation) {
+        return Decimal128._fromString(representation, { allowRounding: true });
+    }
+    static _fromString(representation, options) {
+        let isNegative = false;
+        let sawSign = false;
+        let sawRadix = false;
+        let foundNonZero = false;
+        let significantDigits = 0;
+        let nDigitsRead = 0;
+        let nDigits = 0;
+        let radixPosition = 0;
+        let firstNonZero = 0;
+        const digits = [0];
+        let nDigitsStored = 0;
+        let digitsInsert = 0;
+        let lastDigit = 0;
+        let exponent = 0;
+        let significandHigh = new Long(0, 0);
+        let significandLow = new Long(0, 0);
+        let biasedExponent = 0;
+        let index = 0;
+        if (representation.length >= 7000) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        const stringMatch = representation.match(PARSE_STRING_REGEXP);
+        const infMatch = representation.match(PARSE_INF_REGEXP);
+        const nanMatch = representation.match(PARSE_NAN_REGEXP);
+        if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        if (stringMatch) {
+            const unsignedNumber = stringMatch[2];
+            const e = stringMatch[4];
+            const expSign = stringMatch[5];
+            const expNumber = stringMatch[6];
+            if (e && expNumber === undefined)
+                invalidErr(representation, 'missing exponent power');
+            if (e && unsignedNumber === undefined)
+                invalidErr(representation, 'missing exponent base');
+            if (e === undefined && (expSign || expNumber)) {
+                invalidErr(representation, 'missing e before exponent');
+            }
+        }
+        if (representation[index] === '+' || representation[index] === '-') {
+            sawSign = true;
+            isNegative = representation[index++] === '-';
+        }
+        if (!isDigit(representation[index]) && representation[index] !== '.') {
+            if (representation[index] === 'i' || representation[index] === 'I') {
+                return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+            }
+            else if (representation[index] === 'N') {
+                return new Decimal128(NAN_BUFFER);
+            }
+        }
+        while (isDigit(representation[index]) || representation[index] === '.') {
+            if (representation[index] === '.') {
+                if (sawRadix)
+                    invalidErr(representation, 'contains multiple periods');
+                sawRadix = true;
+                index = index + 1;
+                continue;
+            }
+            if (nDigitsStored < MAX_DIGITS) {
+                if (representation[index] !== '0' || foundNonZero) {
+                    if (!foundNonZero) {
+                        firstNonZero = nDigitsRead;
+                    }
+                    foundNonZero = true;
+                    digits[digitsInsert++] = parseInt(representation[index], 10);
+                    nDigitsStored = nDigitsStored + 1;
+                }
+            }
+            if (foundNonZero)
+                nDigits = nDigits + 1;
+            if (sawRadix)
+                radixPosition = radixPosition + 1;
+            nDigitsRead = nDigitsRead + 1;
+            index = index + 1;
+        }
+        if (sawRadix && !nDigitsRead)
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        if (representation[index] === 'e' || representation[index] === 'E') {
+            const match = representation.substr(++index).match(EXPONENT_REGEX);
+            if (!match || !match[2])
+                return new Decimal128(NAN_BUFFER);
+            exponent = parseInt(match[0], 10);
+            index = index + match[0].length;
+        }
+        if (representation[index])
+            return new Decimal128(NAN_BUFFER);
+        if (!nDigitsStored) {
+            digits[0] = 0;
+            nDigits = 1;
+            nDigitsStored = 1;
+            significantDigits = 0;
+        }
+        else {
+            lastDigit = nDigitsStored - 1;
+            significantDigits = nDigits;
+            if (significantDigits !== 1) {
+                while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') {
+                    significantDigits = significantDigits - 1;
+                }
+            }
+        }
+        if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
+            exponent = EXPONENT_MIN;
+        }
+        else {
+            exponent = exponent - radixPosition;
+        }
+        while (exponent > EXPONENT_MAX) {
+            lastDigit = lastDigit + 1;
+            if (lastDigit >= MAX_DIGITS) {
+                if (significantDigits === 0) {
+                    exponent = EXPONENT_MAX;
+                    break;
+                }
+                invalidErr(representation, 'overflow');
+            }
+            exponent = exponent - 1;
+        }
+        if (options.allowRounding) {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0 && significantDigits < nDigitsStored) {
+                    exponent = EXPONENT_MIN;
+                    significantDigits = 0;
+                    break;
+                }
+                if (nDigitsStored < nDigits) {
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    const digitsString = digits.join('');
+                    if (digitsString.match(/^0+$/)) {
+                        exponent = EXPONENT_MAX;
+                        break;
+                    }
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                let endOfString = nDigitsRead;
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                let roundBit = 0;
+                if (roundDigit >= 5) {
+                    roundBit = 1;
+                    if (roundDigit === 5) {
+                        roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
+                        for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
+                            if (parseInt(representation[i], 10)) {
+                                roundBit = 1;
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (roundBit) {
+                    let dIdx = lastDigit;
+                    for (; dIdx >= 0; dIdx--) {
+                        if (++digits[dIdx] > 9) {
+                            digits[dIdx] = 0;
+                            if (dIdx === 0) {
+                                if (exponent < EXPONENT_MAX) {
+                                    exponent = exponent + 1;
+                                    digits[dIdx] = 1;
+                                }
+                                else {
+                                    return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+                                }
+                            }
+                        }
+                        else {
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        else {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0) {
+                    if (significantDigits === 0) {
+                        exponent = EXPONENT_MIN;
+                        break;
+                    }
+                    invalidErr(representation, 'exponent underflow');
+                }
+                if (nDigitsStored < nDigits) {
+                    if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
+                        significantDigits !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    if (digits[lastDigit] !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                if (roundDigit !== 0) {
+                    invalidErr(representation, 'inexact rounding');
+                }
+            }
+        }
+        significandHigh = Long.fromNumber(0);
+        significandLow = Long.fromNumber(0);
+        if (significantDigits === 0) {
+            significandHigh = Long.fromNumber(0);
+            significandLow = Long.fromNumber(0);
+        }
+        else if (lastDigit < 17) {
+            let dIdx = 0;
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            significandHigh = new Long(0, 0);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        else {
+            let dIdx = 0;
+            significandHigh = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit - 17; dIdx++) {
+                significandHigh = significandHigh.multiply(Long.fromNumber(10));
+                significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
+            }
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
+        significand.low = significand.low.add(significandLow);
+        if (lessThan(significand.low, significandLow)) {
+            significand.high = significand.high.add(Long.fromNumber(1));
+        }
+        biasedExponent = exponent + EXPONENT_BIAS;
+        const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
+        if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
+            dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
+        }
+        else {
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
+        }
+        dec.low = significand.low;
+        if (isNegative) {
+            dec.high = dec.high.or(Long.fromString('9223372036854775808'));
+        }
+        const buffer = ByteUtils.allocateUnsafe(16);
+        index = 0;
+        buffer[index++] = dec.low.low & 0xff;
+        buffer[index++] = (dec.low.low >> 8) & 0xff;
+        buffer[index++] = (dec.low.low >> 16) & 0xff;
+        buffer[index++] = (dec.low.low >> 24) & 0xff;
+        buffer[index++] = dec.low.high & 0xff;
+        buffer[index++] = (dec.low.high >> 8) & 0xff;
+        buffer[index++] = (dec.low.high >> 16) & 0xff;
+        buffer[index++] = (dec.low.high >> 24) & 0xff;
+        buffer[index++] = dec.high.low & 0xff;
+        buffer[index++] = (dec.high.low >> 8) & 0xff;
+        buffer[index++] = (dec.high.low >> 16) & 0xff;
+        buffer[index++] = (dec.high.low >> 24) & 0xff;
+        buffer[index++] = dec.high.high & 0xff;
+        buffer[index++] = (dec.high.high >> 8) & 0xff;
+        buffer[index++] = (dec.high.high >> 16) & 0xff;
+        buffer[index++] = (dec.high.high >> 24) & 0xff;
+        return new Decimal128(buffer);
+    }
+    toString() {
+        let biased_exponent;
+        let significand_digits = 0;
+        const significand = new Array(36);
+        for (let i = 0; i < significand.length; i++)
+            significand[i] = 0;
+        let index = 0;
+        let is_zero = false;
+        let significand_msb;
+        let significand128 = { parts: [0, 0, 0, 0] };
+        let j, k;
+        const string = [];
+        index = 0;
+        const buffer = this.bytes;
+        const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        index = 0;
+        const dec = {
+            low: new Long(low, midl),
+            high: new Long(midh, high)
+        };
+        if (dec.high.lessThan(Long.ZERO)) {
+            string.push('-');
+        }
+        const combination = (high >> 26) & COMBINATION_MASK;
+        if (combination >> 3 === 3) {
+            if (combination === COMBINATION_INFINITY) {
+                return string.join('') + 'Infinity';
+            }
+            else if (combination === COMBINATION_NAN) {
+                return 'NaN';
+            }
+            else {
+                biased_exponent = (high >> 15) & EXPONENT_MASK;
+                significand_msb = 0x08 + ((high >> 14) & 0x01);
+            }
+        }
+        else {
+            significand_msb = (high >> 14) & 0x07;
+            biased_exponent = (high >> 17) & EXPONENT_MASK;
+        }
+        const exponent = biased_exponent - EXPONENT_BIAS;
+        significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
+        significand128.parts[1] = midh;
+        significand128.parts[2] = midl;
+        significand128.parts[3] = low;
+        if (significand128.parts[0] === 0 &&
+            significand128.parts[1] === 0 &&
+            significand128.parts[2] === 0 &&
+            significand128.parts[3] === 0) {
+            is_zero = true;
+        }
+        else {
+            for (k = 3; k >= 0; k--) {
+                let least_digits = 0;
+                const result = divideu128(significand128);
+                significand128 = result.quotient;
+                least_digits = result.rem.low;
+                if (!least_digits)
+                    continue;
+                for (j = 8; j >= 0; j--) {
+                    significand[k * 9 + j] = least_digits % 10;
+                    least_digits = Math.floor(least_digits / 10);
+                }
+            }
+        }
+        if (is_zero) {
+            significand_digits = 1;
+            significand[index] = 0;
+        }
+        else {
+            significand_digits = 36;
+            while (!significand[index]) {
+                significand_digits = significand_digits - 1;
+                index = index + 1;
+            }
+        }
+        const scientific_exponent = significand_digits - 1 + exponent;
+        if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
+            if (significand_digits > 34) {
+                string.push(`${0}`);
+                if (exponent > 0)
+                    string.push(`E+${exponent}`);
+                else if (exponent < 0)
+                    string.push(`E${exponent}`);
+                return string.join('');
+            }
+            string.push(`${significand[index++]}`);
+            significand_digits = significand_digits - 1;
+            if (significand_digits) {
+                string.push('.');
+            }
+            for (let i = 0; i < significand_digits; i++) {
+                string.push(`${significand[index++]}`);
+            }
+            string.push('E');
+            if (scientific_exponent > 0) {
+                string.push(`+${scientific_exponent}`);
+            }
+            else {
+                string.push(`${scientific_exponent}`);
+            }
+        }
+        else {
+            if (exponent >= 0) {
+                for (let i = 0; i < significand_digits; i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+            else {
+                let radix_position = significand_digits + exponent;
+                if (radix_position > 0) {
+                    for (let i = 0; i < radix_position; i++) {
+                        string.push(`${significand[index++]}`);
+                    }
+                }
+                else {
+                    string.push('0');
+                }
+                string.push('.');
+                while (radix_position++ < 0) {
+                    string.push('0');
+                }
+                for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+        }
+        return string.join('');
+    }
+    toJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    toExtendedJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    static fromExtendedJSON(doc) {
+        return Decimal128.fromString(doc.$numberDecimal);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const d128string = inspect(this.toString(), options);
+        return `new Decimal128(${d128string})`;
+    }
+}
+
+class Double extends BSONValue {
+    get _bsontype() {
+        return 'Double';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value;
+    }
+    static fromString(value) {
+        const coercedValue = Number(value);
+        if (value === 'NaN')
+            return new Double(NaN);
+        if (value === 'Infinity')
+            return new Double(Infinity);
+        if (value === '-Infinity')
+            return new Double(-Infinity);
+        if (!Number.isFinite(coercedValue)) {
+            throw new BSONError(`Input: ${value} is not representable as a Double`);
+        }
+        if (value.trim() !== value) {
+            throw new BSONError(`Input: '${value}' contains whitespace`);
+        }
+        if (value === '') {
+            throw new BSONError(`Input is an empty string`);
+        }
+        if (/[^-0-9.+eE]/.test(value)) {
+            throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
+        }
+        return new Double(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toExtendedJSON(options) {
+        if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
+            return this.value;
+        }
+        if (Object.is(Math.sign(this.value), -0)) {
+            return { $numberDouble: '-0.0' };
+        }
+        return {
+            $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
+        };
+    }
+    static fromExtendedJSON(doc, options) {
+        const doubleValue = parseFloat(doc.$numberDouble);
+        return options && options.relaxed ? doubleValue : new Double(doubleValue);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Double(${inspect(this.value, options)})`;
+    }
+}
+
+class Int32 extends BSONValue {
+    get _bsontype() {
+        return 'Int32';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value | 0;
+    }
+    static fromString(value) {
+        const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
+        const coercedValue = Number(value);
+        if (BSON_INT32_MAX < coercedValue) {
+            throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
+        }
+        else if (BSON_INT32_MIN > coercedValue) {
+            throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
+        }
+        else if (!Number.isSafeInteger(coercedValue)) {
+            throw new BSONError(`Input: '${value}' is not a safe integer`);
+        }
+        else if (coercedValue.toString() !== cleanedValue) {
+            throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
+        }
+        return new Int32(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON(options) {
+        if (options && (options.relaxed || options.legacy))
+            return this.value;
+        return { $numberInt: this.value.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Int32(${inspect(this.value, options)})`;
+    }
+}
+
+class MaxKey extends BSONValue {
+    get _bsontype() {
+        return 'MaxKey';
+    }
+    toExtendedJSON() {
+        return { $maxKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MaxKey();
+    }
+    inspect() {
+        return 'new MaxKey()';
+    }
+}
+
+class MinKey extends BSONValue {
+    get _bsontype() {
+        return 'MinKey';
+    }
+    toExtendedJSON() {
+        return { $minKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MinKey();
+    }
+    inspect() {
+        return 'new MinKey()';
+    }
+}
+
+let PROCESS_UNIQUE = null;
+const __idCache = new WeakMap();
+class ObjectId extends BSONValue {
+    get _bsontype() {
+        return 'ObjectId';
+    }
+    static index = Math.floor(Math.random() * 0xffffff);
+    static cacheHexString;
+    buffer;
+    constructor(inputId) {
+        super();
+        let workingId;
+        if (typeof inputId === 'object' && inputId && 'id' in inputId) {
+            if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
+                throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
+            }
+            if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
+                workingId = ByteUtils.fromHex(inputId.toHexString());
+            }
+            else {
+                workingId = inputId.id;
+            }
+        }
+        else {
+            workingId = inputId;
+        }
+        if (workingId == null) {
+            this.buffer = ObjectId.generate();
+        }
+        else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
+            this.buffer = ByteUtils.toLocalBufferType(workingId);
+        }
+        else if (typeof workingId === 'string') {
+            if (ObjectId.validateHexString(workingId)) {
+                this.buffer = ByteUtils.fromHex(workingId);
+                if (ObjectId.cacheHexString) {
+                    __idCache.set(this, workingId);
+                }
+            }
+            else {
+                throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer');
+            }
+        }
+        else {
+            throw new BSONError('Argument passed in does not match the accepted types');
+        }
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, ByteUtils.toHex(value));
+        }
+    }
+    static validateHexString(string) {
+        if (string?.length !== 24)
+            return false;
+        for (let i = 0; i < 24; i++) {
+            const char = string.charCodeAt(i);
+            if ((char >= 48 && char <= 57) ||
+                (char >= 97 && char <= 102) ||
+                (char >= 65 && char <= 70)) {
+                continue;
+            }
+            return false;
+        }
+        return true;
+    }
+    toHexString() {
+        if (ObjectId.cacheHexString) {
+            const __id = __idCache.get(this);
+            if (__id)
+                return __id;
+        }
+        const hexString = ByteUtils.toHex(this.id);
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, hexString);
+        }
+        return hexString;
+    }
+    static getInc() {
+        return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
+    }
+    static generate(time) {
+        if ('number' !== typeof time) {
+            time = Math.floor(Date.now() / 1000);
+        }
+        const inc = ObjectId.getInc();
+        const buffer = ByteUtils.allocateUnsafe(12);
+        NumberUtils.setInt32BE(buffer, 0, time);
+        if (PROCESS_UNIQUE === null) {
+            PROCESS_UNIQUE = ByteUtils.randomBytes(5);
+        }
+        buffer[4] = PROCESS_UNIQUE[0];
+        buffer[5] = PROCESS_UNIQUE[1];
+        buffer[6] = PROCESS_UNIQUE[2];
+        buffer[7] = PROCESS_UNIQUE[3];
+        buffer[8] = PROCESS_UNIQUE[4];
+        buffer[11] = inc & 0xff;
+        buffer[10] = (inc >> 8) & 0xff;
+        buffer[9] = (inc >> 16) & 0xff;
+        return buffer;
+    }
+    toString(encoding) {
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        if (encoding === 'hex')
+            return this.toHexString();
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    static is(variable) {
+        return (variable != null &&
+            typeof variable === 'object' &&
+            '_bsontype' in variable &&
+            variable._bsontype === 'ObjectId');
+    }
+    equals(otherId) {
+        if (otherId === undefined || otherId === null) {
+            return false;
+        }
+        if (ObjectId.is(otherId)) {
+            return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer));
+        }
+        if (typeof otherId === 'string') {
+            return otherId.toLowerCase() === this.toHexString();
+        }
+        if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') {
+            const otherIdString = otherId.toHexString();
+            const thisIdString = this.toHexString();
+            return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
+        }
+        return false;
+    }
+    getTimestamp() {
+        const timestamp = new Date();
+        const time = NumberUtils.getUint32BE(this.buffer, 0);
+        timestamp.setTime(Math.floor(time) * 1000);
+        return timestamp;
+    }
+    static createPk() {
+        return new ObjectId();
+    }
+    serializeInto(uint8array, index) {
+        uint8array[index] = this.buffer[0];
+        uint8array[index + 1] = this.buffer[1];
+        uint8array[index + 2] = this.buffer[2];
+        uint8array[index + 3] = this.buffer[3];
+        uint8array[index + 4] = this.buffer[4];
+        uint8array[index + 5] = this.buffer[5];
+        uint8array[index + 6] = this.buffer[6];
+        uint8array[index + 7] = this.buffer[7];
+        uint8array[index + 8] = this.buffer[8];
+        uint8array[index + 9] = this.buffer[9];
+        uint8array[index + 10] = this.buffer[10];
+        uint8array[index + 11] = this.buffer[11];
+        return 12;
+    }
+    static createFromTime(time) {
+        const buffer = ByteUtils.allocate(12);
+        for (let i = 11; i >= 4; i--)
+            buffer[i] = 0;
+        NumberUtils.setInt32BE(buffer, 0, time);
+        return new ObjectId(buffer);
+    }
+    static createFromHexString(hexString) {
+        if (hexString?.length !== 24) {
+            throw new BSONError('hex string must be 24 characters');
+        }
+        return new ObjectId(ByteUtils.fromHex(hexString));
+    }
+    static createFromBase64(base64) {
+        if (base64?.length !== 16) {
+            throw new BSONError('base64 string must be 16 characters');
+        }
+        return new ObjectId(ByteUtils.fromBase64(base64));
+    }
+    static isValid(id) {
+        if (id == null)
+            return false;
+        if (typeof id === 'string')
+            return ObjectId.validateHexString(id);
+        try {
+            new ObjectId(id);
+            return true;
+        }
+        catch {
+            return false;
+        }
+    }
+    toExtendedJSON() {
+        if (this.toHexString)
+            return { $oid: this.toHexString() };
+        return { $oid: this.toString('hex') };
+    }
+    static fromExtendedJSON(doc) {
+        return new ObjectId(doc.$oid);
+    }
+    isCached() {
+        return ObjectId.cacheHexString && __idCache.has(this);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new ObjectId(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
+    let totalLength = 4 + 1;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+        }
+        for (const key of Object.keys(object)) {
+            totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
+        }
+    }
+    return totalLength;
+}
+function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
+    if (typeof value?.toBSON === 'function') {
+        value = value.toBSON();
+    }
+    switch (typeof value) {
+        case 'string':
+            return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
+        case 'number':
+            if (Math.floor(value) === value &&
+                value >= JS_INT_MIN &&
+                value <= JS_INT_MAX) {
+                if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
+                }
+                else {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+                }
+            }
+            else {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+        case 'undefined':
+            if (isArray || !ignoreUndefined)
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            return 0;
+        case 'boolean':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
+        case 'object':
+            if (value != null &&
+                typeof value._bsontype === 'string' &&
+                value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                throw new BSONVersionError();
+            }
+            else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            }
+            else if (value._bsontype === 'ObjectId') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
+            }
+            else if (value instanceof Date || isDate(value)) {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (ArrayBuffer.isView(value) ||
+                value instanceof ArrayBuffer ||
+                isAnyArrayBuffer(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength);
+            }
+            else if (value._bsontype === 'Long' ||
+                value._bsontype === 'Double' ||
+                value._bsontype === 'Timestamp') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (value._bsontype === 'Decimal128') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
+            }
+            else if (value._bsontype === 'Code') {
+                if (value.scope != null && Object.keys(value.scope).length > 0) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1 +
+                        internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1);
+                }
+            }
+            else if (value._bsontype === 'Binary') {
+                const binary = value;
+                if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        (binary.position + 1 + 4 + 1 + 4));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1));
+                }
+            }
+            else if (value._bsontype === 'Symbol') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    ByteUtils.utf8ByteLength(value.value) +
+                    4 +
+                    1 +
+                    1);
+            }
+            else if (value._bsontype === 'DBRef') {
+                const ordered_values = Object.assign({
+                    $ref: value.collection,
+                    $id: value.oid
+                }, value.fields);
+                if (value.db != null) {
+                    ordered_values['$db'] = value.db;
+                }
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
+            }
+            else if (value instanceof RegExp || isRegExp(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.source) +
+                    1 +
+                    (value.global ? 1 : 0) +
+                    (value.ignoreCase ? 1 : 0) +
+                    (value.multiline ? 1 : 0) +
+                    1);
+            }
+            else if (value._bsontype === 'BSONRegExp') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.pattern) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.options) +
+                    1);
+            }
+            else {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) +
+                    1);
+            }
+        case 'function':
+            if (serializeFunctions) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    4 +
+                    ByteUtils.utf8ByteLength(value.toString()) +
+                    1);
+            }
+            return 0;
+        case 'bigint':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+        case 'symbol':
+            return 0;
+        default:
+            throw new BSONError(`Unrecognized JS type: ${typeof value}`);
+    }
+}
+
+function alphabetize(str) {
+    return str.split('').sort().join('');
+}
+class BSONRegExp extends BSONValue {
+    get _bsontype() {
+        return 'BSONRegExp';
+    }
+    pattern;
+    options;
+    constructor(pattern, options) {
+        super();
+        this.pattern = pattern;
+        this.options = alphabetize(options ?? '');
+        if (this.pattern.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
+        }
+        if (this.options.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
+        }
+        for (let i = 0; i < this.options.length; i++) {
+            if (!(this.options[i] === 'i' ||
+                this.options[i] === 'm' ||
+                this.options[i] === 'x' ||
+                this.options[i] === 'l' ||
+                this.options[i] === 's' ||
+                this.options[i] === 'u')) {
+                throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
+            }
+        }
+    }
+    static parseOptions(options) {
+        return options ? options.split('').sort().join('') : '';
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (options.legacy) {
+            return { $regex: this.pattern, $options: this.options };
+        }
+        return { $regularExpression: { pattern: this.pattern, options: this.options } };
+    }
+    static fromExtendedJSON(doc) {
+        if ('$regex' in doc) {
+            if (typeof doc.$regex !== 'string') {
+                if (doc.$regex._bsontype === 'BSONRegExp') {
+                    return doc;
+                }
+            }
+            else {
+                return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
+            }
+        }
+        if ('$regularExpression' in doc) {
+            return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
+        }
+        throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
+    }
+    inspect(depth, options, inspect) {
+        const stylize = getStylizeFunction(options) ?? (v => v);
+        inspect ??= defaultInspect;
+        const pattern = stylize(inspect(this.pattern), 'regexp');
+        const flags = stylize(inspect(this.options), 'regexp');
+        return `new BSONRegExp(${pattern}, ${flags})`;
+    }
+}
+
+class BSONSymbol extends BSONValue {
+    get _bsontype() {
+        return 'BSONSymbol';
+    }
+    value;
+    constructor(value) {
+        super();
+        this.value = value;
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON() {
+        return { $symbol: this.value };
+    }
+    static fromExtendedJSON(doc) {
+        return new BSONSymbol(doc.$symbol);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new BSONSymbol(${inspect(this.value, options)})`;
+    }
+}
+
+const LongWithoutOverridesClass = Long;
+class Timestamp extends LongWithoutOverridesClass {
+    get _bsontype() {
+        return 'Timestamp';
+    }
+    get [bsonType]() {
+        return 'Timestamp';
+    }
+    static MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
+    get i() {
+        return this.low >>> 0;
+    }
+    get t() {
+        return this.high >>> 0;
+    }
+    constructor(low) {
+        if (low == null) {
+            super(0, 0, true);
+        }
+        else if (typeof low === 'bigint') {
+            super(low, true);
+        }
+        else if (Long.isLong(low)) {
+            super(low.low, low.high, true);
+        }
+        else if (typeof low === 'object' && 't' in low && 'i' in low) {
+            if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t as a number');
+            }
+            if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
+            }
+            const t = Number(low.t);
+            const i = Number(low.i);
+            if (t < 0 || Number.isNaN(t)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
+            }
+            if (i < 0 || Number.isNaN(i)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
+            }
+            if (t > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max');
+            }
+            if (i > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max');
+            }
+            super(i, t, true);
+        }
+        else {
+            throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }');
+        }
+    }
+    toJSON() {
+        return {
+            $timestamp: this.toString()
+        };
+    }
+    static fromInt(value) {
+        return new Timestamp(Long.fromInt(value, true));
+    }
+    static fromNumber(value) {
+        return new Timestamp(Long.fromNumber(value, true));
+    }
+    static fromBits(lowBits, highBits) {
+        return new Timestamp({ i: lowBits, t: highBits });
+    }
+    static fromString(str, optRadix) {
+        return new Timestamp(Long.fromString(str, true, optRadix));
+    }
+    toExtendedJSON() {
+        return { $timestamp: { t: this.t, i: this.i } };
+    }
+    static fromExtendedJSON(doc) {
+        const i = Long.isLong(doc.$timestamp.i)
+            ? doc.$timestamp.i.getLowBitsUnsigned()
+            : doc.$timestamp.i;
+        const t = Long.isLong(doc.$timestamp.t)
+            ? doc.$timestamp.t.getLowBitsUnsigned()
+            : doc.$timestamp.t;
+        return new Timestamp({ t, i });
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const t = inspect(this.t, options);
+        const i = inspect(this.i, options);
+        return `new Timestamp({ t: ${t}, i: ${i} })`;
+    }
+}
+
+const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
+const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
+function internalDeserialize(buffer, options, isArray) {
+    options = options == null ? {} : options;
+    const index = options && options.index ? options.index : 0;
+    const size = NumberUtils.getInt32LE(buffer, index);
+    if (size < 5) {
+        throw new BSONError(`bson size must be >= 5, is ${size}`);
+    }
+    if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
+        throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
+    }
+    if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
+        throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
+    }
+    if (size + index > buffer.byteLength) {
+        throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`);
+    }
+    if (buffer[index + size - 1] !== 0) {
+        throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
+    }
+    return deserializeObject(buffer, index, options, isArray);
+}
+const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
+function deserializeObject(buffer, index, options, isArray = false) {
+    const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
+    const raw = options['raw'] == null ? false : options['raw'];
+    const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
+    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');
+    }
+    const validation = options.validation == null ? { utf8: true } : options.validation;
+    let globalUTFValidation = true;
+    let validationSetting;
+    let utf8KeysSet;
+    const utf8ValidatedKeys = validation.utf8;
+    if (typeof utf8ValidatedKeys === 'boolean') {
+        validationSetting = utf8ValidatedKeys;
+    }
+    else {
+        globalUTFValidation = false;
+        const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
+            return utf8ValidatedKeys[key];
+        });
+        if (utf8ValidationValues.length === 0) {
+            throw new BSONError('UTF-8 validation setting cannot be empty');
+        }
+        if (typeof utf8ValidationValues[0] !== 'boolean') {
+            throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
+        }
+        validationSetting = utf8ValidationValues[0];
+        if (!utf8ValidationValues.every(item => item === validationSetting)) {
+            throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
+        }
+    }
+    if (!globalUTFValidation) {
+        utf8KeysSet = new Set();
+        for (const key of Object.keys(utf8ValidatedKeys)) {
+            utf8KeysSet.add(key);
+        }
+    }
+    const startIndex = index;
+    if (buffer.length < 5)
+        throw new BSONError('corrupt bson message < 5 bytes long');
+    const size = NumberUtils.getInt32LE(buffer, index);
+    index += 4;
+    if (size < 5 || size > buffer.length)
+        throw new BSONError('corrupt bson message');
+    const object = isArray ? [] : {};
+    let arrayIndex = 0;
+    let isPossibleDBRef = isArray ? false : null;
+    while (true) {
+        const elementType = buffer[index++];
+        if (elementType === 0)
+            break;
+        let i = index;
+        while (buffer[i] !== 0x00 && i < buffer.length) {
+            i++;
+        }
+        if (i >= buffer.byteLength)
+            throw new BSONError('Bad BSON Document: illegal CString');
+        const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false);
+        let shouldValidateKey = true;
+        if (globalUTFValidation || utf8KeysSet?.has(name)) {
+            shouldValidateKey = validationSetting;
+        }
+        else {
+            shouldValidateKey = !validationSetting;
+        }
+        if (isPossibleDBRef !== false && name[0] === '$') {
+            isPossibleDBRef = allowedDBRefKeys.test(name);
+        }
+        let value;
+        index = i + 1;
+        if (elementType === BSON_DATA_STRING) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_OID) {
+            const oid = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oid[i] = buffer[index + i];
+            value = new ObjectId(oid);
+            index = index + 12;
+        }
+        else if (elementType === BSON_DATA_INT && promoteValues === false) {
+            value = new Int32(NumberUtils.getInt32LE(buffer, index));
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_INT) {
+            value = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_NUMBER) {
+            value = NumberUtils.getFloat64LE(buffer, index);
+            index += 8;
+            if (promoteValues === false)
+                value = new Double(value);
+        }
+        else if (elementType === BSON_DATA_DATE) {
+            const lowBits = NumberUtils.getInt32LE(buffer, index);
+            const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+            index += 8;
+            value = new Date(new Long(lowBits, highBits).toNumber());
+        }
+        else if (elementType === BSON_DATA_BOOLEAN) {
+            if (buffer[index] !== 0 && buffer[index] !== 1)
+                throw new BSONError('illegal boolean type value');
+            value = buffer[index++] === 1;
+        }
+        else if (elementType === BSON_DATA_OBJECT) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            if (objectSize <= 0 || objectSize > buffer.length - index)
+                throw new BSONError('bad embedded document length in bson');
+            if (raw) {
+                value = buffer.subarray(index, index + objectSize);
+            }
+            else {
+                let objectOptions = options;
+                if (!globalUTFValidation) {
+                    objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
+                }
+                value = deserializeObject(buffer, _index, objectOptions, false);
+            }
+            index = index + objectSize;
+        }
+        else if (elementType === BSON_DATA_ARRAY) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            let arrayOptions = options;
+            const stopIndex = index + objectSize;
+            if (fieldsAsRaw && fieldsAsRaw[name]) {
+                arrayOptions = { ...options, raw: true };
+            }
+            if (!globalUTFValidation) {
+                arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
+            }
+            value = deserializeObject(buffer, _index, arrayOptions, true);
+            index = index + objectSize;
+            if (buffer[index - 1] !== 0)
+                throw new BSONError('invalid array terminator byte');
+            if (index !== stopIndex)
+                throw new BSONError('corrupted array bson');
+        }
+        else if (elementType === BSON_DATA_UNDEFINED) {
+            value = undefined;
+        }
+        else if (elementType === BSON_DATA_NULL) {
+            value = null;
+        }
+        else if (elementType === BSON_DATA_LONG) {
+            if (useBigInt64) {
+                value = NumberUtils.getBigInt64LE(buffer, index);
+                index += 8;
+            }
+            else {
+                const lowBits = NumberUtils.getInt32LE(buffer, index);
+                const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+                index += 8;
+                const long = new Long(lowBits, highBits);
+                if (promoteLongs && promoteValues === true) {
+                    value =
+                        long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
+                            ? long.toNumber()
+                            : long;
+                }
+                else {
+                    value = long;
+                }
+            }
+        }
+        else if (elementType === BSON_DATA_DECIMAL128) {
+            const bytes = ByteUtils.allocateUnsafe(16);
+            for (let i = 0; i < 16; i++)
+                bytes[i] = buffer[index + i];
+            index = index + 16;
+            value = new Decimal128(bytes);
+        }
+        else if (elementType === BSON_DATA_BINARY) {
+            let binarySize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            const totalBinarySize = binarySize;
+            const subType = buffer[index++];
+            if (binarySize < 0)
+                throw new BSONError('Negative binary type element size found');
+            if (binarySize > buffer.byteLength)
+                throw new BSONError('Binary type size larger than document size');
+            if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
+                binarySize = NumberUtils.getInt32LE(buffer, index);
+                index += 4;
+                if (binarySize < 0)
+                    throw new BSONError('Negative binary type element size found for subtype 0x02');
+                if (binarySize > totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
+                if (binarySize < totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
+            }
+            if (promoteBuffers && promoteValues) {
+                value = ByteUtils.toLocalBufferType(buffer.subarray(index, index + binarySize));
+            }
+            else {
+                value = new Binary(buffer.subarray(index, index + binarySize), subType);
+                if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
+                    value = value.toUUID();
+                }
+            }
+            index = index + binarySize;
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            const optionsArray = new Array(regExpOptions.length);
+            for (i = 0; i < regExpOptions.length; i++) {
+                switch (regExpOptions[i]) {
+                    case 'm':
+                        optionsArray[i] = 'm';
+                        break;
+                    case 's':
+                        optionsArray[i] = 'g';
+                        break;
+                    case 'i':
+                        optionsArray[i] = 'i';
+                        break;
+                }
+            }
+            value = new RegExp(source, optionsArray.join(''));
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            value = new BSONRegExp(source, regExpOptions);
+        }
+        else if (elementType === BSON_DATA_SYMBOL) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = promoteValues ? symbol : new BSONSymbol(symbol);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_TIMESTAMP) {
+            value = new Timestamp({
+                i: NumberUtils.getUint32LE(buffer, index),
+                t: NumberUtils.getUint32LE(buffer, index + 4)
+            });
+            index += 8;
+        }
+        else if (elementType === BSON_DATA_MIN_KEY) {
+            value = new MinKey();
+        }
+        else if (elementType === BSON_DATA_MAX_KEY) {
+            value = new MaxKey();
+        }
+        else if (elementType === BSON_DATA_CODE) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = new Code(functionString);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_CODE_W_SCOPE) {
+            const totalSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (totalSize < 4 + 4 + 4 + 1) {
+                throw new BSONError('code_w_scope total size shorter minimum expected length');
+            }
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            const scopeObject = deserializeObject(buffer, _index, options, false);
+            index = index + objectSize;
+            if (totalSize < 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too short, truncating scope');
+            }
+            if (totalSize > 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too long, clips outer document');
+            }
+            value = new Code(functionString, scopeObject);
+        }
+        else if (elementType === BSON_DATA_DBPOINTER) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0)
+                throw new BSONError('bad string length in bson');
+            const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const oidBuffer = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oidBuffer[i] = buffer[index + i];
+            const oid = new ObjectId(oidBuffer);
+            index = index + 12;
+            value = new DBRef(namespace, oid);
+        }
+        else {
+            throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
+        }
+        if (name === '__proto__') {
+            Object.defineProperty(object, name, {
+                value,
+                writable: true,
+                enumerable: true,
+                configurable: true
+            });
+        }
+        else {
+            object[name] = value;
+        }
+    }
+    if (size !== index - startIndex) {
+        if (isArray)
+            throw new BSONError('corrupt array bson');
+        throw new BSONError('corrupt object bson');
+    }
+    if (!isPossibleDBRef)
+        return object;
+    if (isDBRefLike(object)) {
+        const copy = Object.assign({}, object);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(object.$ref, object.$id, object.$db, copy);
+    }
+    return object;
+}
+
+const regexp = /\x00/;
+const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
+function serializeString(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_STRING;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes + 1;
+    buffer[index - 1] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
+    NumberUtils.setInt32LE(buffer, index, size + 1);
+    index = index + 4 + size;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeNumber(buffer, key, value, index) {
+    const isNegativeZero = Object.is(value, -0);
+    const type = !isNegativeZero &&
+        Number.isSafeInteger(value) &&
+        value <= BSON_INT32_MAX &&
+        value >= BSON_INT32_MIN
+        ? BSON_DATA_INT
+        : BSON_DATA_NUMBER;
+    buffer[index++] = type;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0x00;
+    if (type === BSON_DATA_INT) {
+        index += NumberUtils.setInt32LE(buffer, index, value);
+    }
+    else {
+        index += NumberUtils.setFloat64LE(buffer, index, value);
+    }
+    return index;
+}
+function serializeBigInt(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_LONG;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index += numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setBigInt64LE(buffer, index, value);
+    return index;
+}
+function serializeNull(buffer, key, _, index) {
+    buffer[index++] = BSON_DATA_NULL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeBoolean(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BOOLEAN;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    buffer[index++] = value ? 1 : 0;
+    return index;
+}
+function serializeDate(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DATE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const dateInMilis = Long.fromNumber(value.getTime());
+    const lowBits = dateInMilis.getLowBits();
+    const highBits = dateInMilis.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.source && value.source.match(regexp) != null) {
+        throw new BSONError('value ' + value.source + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
+    buffer[index++] = 0x00;
+    if (value.ignoreCase)
+        buffer[index++] = 0x69;
+    if (value.global)
+        buffer[index++] = 0x73;
+    if (value.multiline)
+        buffer[index++] = 0x6d;
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeBSONRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.pattern.match(regexp) != null) {
+        throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
+    buffer[index++] = 0x00;
+    const sortedOptions = value.options.split('').sort().join('');
+    index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeMinMax(buffer, key, value, index) {
+    if (value === null) {
+        buffer[index++] = BSON_DATA_NULL;
+    }
+    else if (value._bsontype === 'MinKey') {
+        buffer[index++] = BSON_DATA_MIN_KEY;
+    }
+    else {
+        buffer[index++] = BSON_DATA_MAX_KEY;
+    }
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeObjectId(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_OID;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += value.serializeInto(buffer, index);
+    return index;
+}
+function serializeBuffer(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = value.length;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = value[i];
+    }
+    else {
+        buffer.set(value, index);
+    }
+    index = index + size;
+    return index;
+}
+function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path.has(value)) {
+        throw new BSONError('Cannot convert circular structure to BSON');
+    }
+    path.add(value);
+    buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+    path.delete(value);
+    return endIndex;
+}
+function serializeDecimal128(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DECIMAL128;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    for (let i = 0; i < 16; i++)
+        buffer[index + i] = value.bytes[i];
+    return index + 16;
+}
+function serializeLong(buffer, key, value, index) {
+    buffer[index++] =
+        value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const lowBits = value.getLowBits();
+    const highBits = value.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeInt32(buffer, key, value, index) {
+    value = value.valueOf();
+    buffer[index++] = BSON_DATA_INT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setInt32LE(buffer, index, value);
+    return index;
+}
+function serializeDouble(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_NUMBER;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setFloat64LE(buffer, index, value.value);
+    return index;
+}
+function serializeFunction(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_CODE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const functionString = value.toString();
+    const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
+    if (value.scope && typeof value.scope === 'object') {
+        buffer[index++] = BSON_DATA_CODE_W_SCOPE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        let startIndex = index;
+        const functionString = value.code;
+        index = index + 4;
+        const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, codeSize);
+        buffer[index + 4 + codeSize - 1] = 0;
+        index = index + codeSize + 4;
+        const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+        index = endIndex - 1;
+        const totalSize = endIndex - startIndex;
+        startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize);
+        buffer[index++] = 0;
+    }
+    else {
+        buffer[index++] = BSON_DATA_CODE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        const functionString = value.code.toString();
+        const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, size);
+        index = index + 4 + size - 1;
+        buffer[index++] = 0;
+    }
+    return index;
+}
+function serializeBinary(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const data = value.buffer;
+    let size = value.position;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
+        size = size + 4;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = value.sub_type;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+        size = size - 4;
+        index += NumberUtils.setInt32LE(buffer, index, size);
+    }
+    if (value.sub_type === Binary.SUBTYPE_VECTOR) {
+        validateBinaryVector(value);
+    }
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = data[i];
+    }
+    else {
+        buffer.set(data, index);
+    }
+    index = index + value.position;
+    return index;
+}
+function serializeSymbol(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_SYMBOL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) {
+    buffer[index++] = BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    let startIndex = index;
+    let output = {
+        $ref: value.collection || value.namespace,
+        $id: value.oid
+    };
+    if (value.db != null) {
+        output.$db = value.db;
+    }
+    output = Object.assign(output, value.fields);
+    const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path);
+    const size = endIndex - startIndex;
+    startIndex += NumberUtils.setInt32LE(buffer, index, size);
+    return endIndex;
+}
+function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path == null) {
+        if (object == null) {
+            buffer[0] = 0x05;
+            buffer[1] = 0x00;
+            buffer[2] = 0x00;
+            buffer[3] = 0x00;
+            buffer[4] = 0x00;
+            return 5;
+        }
+        if (Array.isArray(object)) {
+            throw new BSONError('serialize does not support an array as the root input');
+        }
+        if (typeof object !== 'object') {
+            throw new BSONError('serialize does not support non-object as the root input');
+        }
+        else if ('_bsontype' in object && typeof object._bsontype === 'string') {
+            throw new BSONError(`BSON types cannot be serialized as a document`);
+        }
+        else if (isDate(object) ||
+            isRegExp(object) ||
+            isUint8Array(object) ||
+            isAnyArrayBuffer(object)) {
+            throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
+        }
+        path = new Set();
+    }
+    path.add(object);
+    let index = startingIndex + 4;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            const key = `${i}`;
+            let value = object[i];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (value === undefined) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else if (object instanceof Map || isMap(object)) {
+        const iterator = object.entries();
+        let done = false;
+        while (!done) {
+            const entry = iterator.next();
+            done = !!entry.done;
+            if (done)
+                continue;
+            const key = entry.value ? entry.value[0] : undefined;
+            let value = entry.value ? entry.value[1] : undefined;
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+            if (object != null && typeof object !== 'object') {
+                throw new BSONError('toBSON function did not return an object');
+            }
+        }
+        for (const key of Object.keys(object)) {
+            let value = object[key];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    path.delete(object);
+    buffer[index++] = 0x00;
+    const size = index - startingIndex;
+    startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size);
+    return index;
+}
+
+function isBSONType(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '_bsontype' in value &&
+        typeof value._bsontype === 'string');
+}
+const keysToCodecs = {
+    $oid: ObjectId,
+    $binary: Binary,
+    $uuid: Binary,
+    $symbol: BSONSymbol,
+    $numberInt: Int32,
+    $numberDecimal: Decimal128,
+    $numberDouble: Double,
+    $numberLong: Long,
+    $minKey: MinKey,
+    $maxKey: MaxKey,
+    $regex: BSONRegExp,
+    $regularExpression: BSONRegExp,
+    $timestamp: Timestamp
+};
+function deserializeValue(value, options = {}) {
+    if (typeof value === 'number') {
+        const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
+        const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
+        if (options.relaxed || options.legacy) {
+            return value;
+        }
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (in32BitRange) {
+                return new Int32(value);
+            }
+            if (in64BitRange) {
+                if (options.useBigInt64) {
+                    return BigInt(value);
+                }
+                return Long.fromNumber(value);
+            }
+        }
+        return new Double(value);
+    }
+    if (value == null || typeof value !== 'object')
+        return value;
+    if (value.$undefined)
+        return null;
+    const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null);
+    for (let i = 0; i < keys.length; i++) {
+        const c = keysToCodecs[keys[i]];
+        if (c)
+            return c.fromExtendedJSON(value, options);
+    }
+    if (value.$date != null) {
+        const d = value.$date;
+        const date = new Date();
+        if (options.legacy) {
+            if (typeof d === 'number')
+                date.setTime(d);
+            else if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        else {
+            if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (Long.isLong(d))
+                date.setTime(d.toNumber());
+            else if (typeof d === 'number' && options.relaxed)
+                date.setTime(d);
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        return date;
+    }
+    if (value.$code != null) {
+        const copy = Object.assign({}, value);
+        if (value.$scope) {
+            copy.$scope = deserializeValue(value.$scope);
+        }
+        return Code.fromExtendedJSON(value);
+    }
+    if (isDBRefLike(value) || value.$dbPointer) {
+        const v = value.$ref ? value : value.$dbPointer;
+        if (v instanceof DBRef)
+            return v;
+        const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
+        let valid = true;
+        dollarKeys.forEach(k => {
+            if (['$ref', '$id', '$db'].indexOf(k) === -1)
+                valid = false;
+        });
+        if (valid)
+            return DBRef.fromExtendedJSON(v);
+    }
+    return value;
+}
+function serializeArray(array, options) {
+    return array.map((v, index) => {
+        options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
+        try {
+            return serializeValue(v, options);
+        }
+        finally {
+            options.seenObjects.pop();
+        }
+    });
+}
+function getISOString(date) {
+    const isoStr = date.toISOString();
+    return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
+}
+function serializeValue(value, options) {
+    if (value instanceof Map || isMap(value)) {
+        const obj = Object.create(null);
+        for (const [k, v] of value) {
+            if (typeof k !== 'string') {
+                throw new BSONError('Can only serialize maps with string keys');
+            }
+            obj[k] = v;
+        }
+        return serializeValue(obj, options);
+    }
+    if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
+        const index = options.seenObjects.findIndex(entry => entry.obj === value);
+        if (index !== -1) {
+            const props = options.seenObjects.map(entry => entry.propertyName);
+            const leadingPart = props
+                .slice(0, index)
+                .map(prop => `${prop} -> `)
+                .join('');
+            const alreadySeen = props[index];
+            const circularPart = ' -> ' +
+                props
+                    .slice(index + 1, props.length - 1)
+                    .map(prop => `${prop} -> `)
+                    .join('');
+            const current = props[props.length - 1];
+            const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
+            const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
+            throw new BSONError('Converting circular structure to EJSON:\n' +
+                `    ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
+                `    ${leadingSpace}\\${dashes}/`);
+        }
+        options.seenObjects[options.seenObjects.length - 1].obj = value;
+    }
+    if (Array.isArray(value))
+        return serializeArray(value, options);
+    if (value === undefined)
+        return null;
+    if (value instanceof Date || isDate(value)) {
+        const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000;
+        if (options.legacy) {
+            return options.relaxed && inRange
+                ? { $date: value.getTime() }
+                : { $date: getISOString(value) };
+        }
+        return options.relaxed && inRange
+            ? { $date: getISOString(value) }
+            : { $date: { $numberLong: value.getTime().toString() } };
+    }
+    if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                return { $numberInt: value.toString() };
+            }
+            if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
+                return { $numberLong: value.toString() };
+            }
+        }
+        return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
+    }
+    if (typeof value === 'bigint') {
+        if (!options.relaxed) {
+            return { $numberLong: BigInt.asIntN(64, value).toString() };
+        }
+        return Number(BigInt.asIntN(64, value));
+    }
+    if (value instanceof RegExp || isRegExp(value)) {
+        let flags = value.flags;
+        if (flags === undefined) {
+            const match = value.toString().match(/[gimuy]*$/);
+            if (match) {
+                flags = match[0];
+            }
+        }
+        const rx = new BSONRegExp(value.source, flags);
+        return rx.toExtendedJSON(options);
+    }
+    if (value != null && typeof value === 'object')
+        return serializeDocument(value, options);
+    return value;
+}
+const BSON_TYPE_MAPPINGS = {
+    Binary: (o) => new Binary(o.value(), o.sub_type),
+    Code: (o) => new Code(o.code, o.scope),
+    DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
+    Decimal128: (o) => new Decimal128(o.bytes),
+    Double: (o) => new Double(o.value),
+    Int32: (o) => new Int32(o.value),
+    Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_),
+    MaxKey: () => new MaxKey(),
+    MinKey: () => new MinKey(),
+    ObjectId: (o) => new ObjectId(o),
+    BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
+    BSONSymbol: (o) => new BSONSymbol(o.value),
+    Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
+};
+function serializeDocument(doc, options) {
+    if (doc == null || typeof doc !== 'object')
+        throw new BSONError('not an object instance');
+    const bsontype = doc._bsontype;
+    if (typeof bsontype === 'undefined') {
+        const _doc = {};
+        for (const name of Object.keys(doc)) {
+            options.seenObjects.push({ propertyName: name, obj: null });
+            try {
+                const value = serializeValue(doc[name], options);
+                if (name === '__proto__') {
+                    Object.defineProperty(_doc, name, {
+                        value,
+                        writable: true,
+                        enumerable: true,
+                        configurable: true
+                    });
+                }
+                else {
+                    _doc[name] = value;
+                }
+            }
+            finally {
+                options.seenObjects.pop();
+            }
+        }
+        return _doc;
+    }
+    else if (doc != null &&
+        typeof doc === 'object' &&
+        typeof doc._bsontype === 'string' &&
+        doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+        throw new BSONVersionError();
+    }
+    else if (isBSONType(doc)) {
+        let outDoc = doc;
+        if (typeof outDoc.toExtendedJSON !== 'function') {
+            const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
+            if (!mapper) {
+                throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
+            }
+            outDoc = mapper(outDoc);
+        }
+        if (bsontype === 'Code' && outDoc.scope) {
+            outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
+        }
+        else if (bsontype === 'DBRef' && outDoc.oid) {
+            outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
+        }
+        return outDoc.toExtendedJSON(options);
+    }
+    else {
+        throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
+    }
+}
+function parse(text, options) {
+    const ejsonOptions = {
+        useBigInt64: options?.useBigInt64 ?? false,
+        relaxed: options?.relaxed ?? true,
+        legacy: options?.legacy ?? false
+    };
+    return JSON.parse(text, (key, value) => {
+        if (key.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
+        }
+        return deserializeValue(value, ejsonOptions);
+    });
+}
+function stringify(value, replacer, space, options) {
+    if (space != null && typeof space === 'object') {
+        options = space;
+        space = 0;
+    }
+    if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
+        options = replacer;
+        replacer = undefined;
+        space = 0;
+    }
+    const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
+        seenObjects: [{ propertyName: '(root)', obj: null }]
+    });
+    const doc = serializeValue(value, serializeOptions);
+    return JSON.stringify(doc, replacer, space);
+}
+function EJSONserialize(value, options) {
+    options = options || {};
+    return JSON.parse(stringify(value, options));
+}
+function EJSONdeserialize(ejson, options) {
+    options = options || {};
+    return parse(JSON.stringify(ejson), options);
+}
+const EJSON = Object.create(null);
+EJSON.parse = parse;
+EJSON.stringify = stringify;
+EJSON.serialize = EJSONserialize;
+EJSON.deserialize = EJSONdeserialize;
+Object.freeze(EJSON);
+
+const BSONElementType = {
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: 255,
+    maxKey: 127
+};
+function getSize(source, offset) {
+    try {
+        return NumberUtils.getNonnegativeInt32LE(source, offset);
+    }
+    catch (cause) {
+        throw new BSONOffsetError('BSON size cannot be negative', offset, { cause });
+    }
+}
+function findNull(bytes, offset) {
+    let nullTerminatorOffset = offset;
+    for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++)
+        ;
+    if (nullTerminatorOffset === bytes.length - 1) {
+        throw new BSONOffsetError('Null terminator not found', offset);
+    }
+    return nullTerminatorOffset;
+}
+function parseToElements(bytes, startOffset = 0) {
+    startOffset ??= 0;
+    if (bytes.length < 5) {
+        throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
+    }
+    const documentSize = getSize(bytes, startOffset);
+    if (documentSize > bytes.length - startOffset) {
+        throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
+    }
+    if (bytes[startOffset + documentSize - 1] !== 0x00) {
+        throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize);
+    }
+    const elements = [];
+    let offset = startOffset + 4;
+    while (offset <= documentSize + startOffset) {
+        const type = bytes[offset];
+        offset += 1;
+        if (type === 0) {
+            if (offset - startOffset !== documentSize) {
+                throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
+            }
+            break;
+        }
+        const nameOffset = offset;
+        const nameLength = findNull(bytes, offset) - nameOffset;
+        offset += nameLength + 1;
+        let length;
+        if (type === BSONElementType.double ||
+            type === BSONElementType.long ||
+            type === BSONElementType.date ||
+            type === BSONElementType.timestamp) {
+            length = 8;
+        }
+        else if (type === BSONElementType.int) {
+            length = 4;
+        }
+        else if (type === BSONElementType.objectId) {
+            length = 12;
+        }
+        else if (type === BSONElementType.decimal) {
+            length = 16;
+        }
+        else if (type === BSONElementType.bool) {
+            length = 1;
+        }
+        else if (type === BSONElementType.null ||
+            type === BSONElementType.undefined ||
+            type === BSONElementType.maxKey ||
+            type === BSONElementType.minKey) {
+            length = 0;
+        }
+        else if (type === BSONElementType.regex) {
+            length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
+        }
+        else if (type === BSONElementType.object ||
+            type === BSONElementType.array ||
+            type === BSONElementType.javascriptWithScope) {
+            length = getSize(bytes, offset);
+        }
+        else if (type === BSONElementType.string ||
+            type === BSONElementType.binData ||
+            type === BSONElementType.dbPointer ||
+            type === BSONElementType.javascript ||
+            type === BSONElementType.symbol) {
+            length = getSize(bytes, offset) + 4;
+            if (type === BSONElementType.binData) {
+                length += 1;
+            }
+            if (type === BSONElementType.dbPointer) {
+                length += 12;
+            }
+        }
+        else {
+            throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset);
+        }
+        if (length > documentSize) {
+            throw new BSONOffsetError('value reports length larger than document', offset);
+        }
+        elements.push([type, nameOffset, nameLength, offset, length]);
+        offset += length;
+    }
+    return elements;
+}
+
+const onDemand = Object.create(null);
+onDemand.parseToElements = parseToElements;
+onDemand.ByteUtils = ByteUtils;
+onDemand.NumberUtils = NumberUtils;
+Object.freeze(onDemand);
+
+const MAXSIZE = 1024 * 1024 * 17;
+let buffer = ByteUtils.allocate(MAXSIZE);
+function setInternalBufferSize(size) {
+    if (buffer.length < size) {
+        buffer = ByteUtils.allocate(size);
+    }
+}
+function serialize(object, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
+    if (buffer.length < minInternalBufferSize) {
+        buffer = ByteUtils.allocate(minInternalBufferSize);
+    }
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex);
+    finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
+    return finishedBuffer;
+}
+function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const startIndex = typeof options.index === 'number' ? options.index : 0;
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
+    return startIndex + serializationIndex - 1;
+}
+function deserialize(buffer, options = {}) {
+    return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
+}
+function calculateObjectSize(object, options = {}) {
+    options = options || {};
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
+}
+function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
+    const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
+    const bufferData = ByteUtils.toLocalBufferType(data);
+    let index = startIndex;
+    for (let i = 0; i < numberOfDocuments; i++) {
+        const size = NumberUtils.getInt32LE(bufferData, index);
+        internalOptions.index = index;
+        documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
+        index = index + size;
+    }
+    return index;
+}
+
+var bson = /*#__PURE__*/Object.freeze({
+    __proto__: null,
+    BSONError: BSONError,
+    BSONOffsetError: BSONOffsetError,
+    BSONRegExp: BSONRegExp,
+    BSONRuntimeError: BSONRuntimeError,
+    BSONSymbol: BSONSymbol,
+    BSONType: BSONType,
+    BSONValue: BSONValue,
+    BSONVersionError: BSONVersionError,
+    Binary: Binary,
+    Code: Code,
+    DBRef: DBRef,
+    Decimal128: Decimal128,
+    Double: Double,
+    EJSON: EJSON,
+    Int32: Int32,
+    Long: Long,
+    MaxKey: MaxKey,
+    MinKey: MinKey,
+    ObjectId: ObjectId,
+    Timestamp: Timestamp,
+    UUID: UUID,
+    bsonType: bsonType,
+    calculateObjectSize: calculateObjectSize,
+    deserialize: deserialize,
+    deserializeStream: deserializeStream,
+    onDemand: onDemand,
+    serialize: serialize,
+    serializeWithBufferAndIndex: serializeWithBufferAndIndex,
+    setInternalBufferSize: setInternalBufferSize
+});
+
+exports.BSON = bson;
+exports.BSONError = BSONError;
+exports.BSONOffsetError = BSONOffsetError;
+exports.BSONRegExp = BSONRegExp;
+exports.BSONRuntimeError = BSONRuntimeError;
+exports.BSONSymbol = BSONSymbol;
+exports.BSONType = BSONType;
+exports.BSONValue = BSONValue;
+exports.BSONVersionError = BSONVersionError;
+exports.Binary = Binary;
+exports.Code = Code;
+exports.DBRef = DBRef;
+exports.Decimal128 = Decimal128;
+exports.Double = Double;
+exports.EJSON = EJSON;
+exports.Int32 = Int32;
+exports.Long = Long;
+exports.MaxKey = MaxKey;
+exports.MinKey = MinKey;
+exports.ObjectId = ObjectId;
+exports.Timestamp = Timestamp;
+exports.UUID = UUID;
+exports.bsonType = bsonType;
+exports.calculateObjectSize = calculateObjectSize;
+exports.deserialize = deserialize;
+exports.deserializeStream = deserializeStream;
+exports.onDemand = onDemand;
+exports.serialize = serialize;
+exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
+exports.setInternalBufferSize = setInternalBufferSize;
+//# sourceMappingURL=bson.cjs.map

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
node_modules/bson/lib/bson.cjs.map


+ 4639 - 0
node_modules/bson/lib/bson.mjs

@@ -0,0 +1,4639 @@
+const TypedArrayPrototypeGetSymbolToStringTag = (() => {
+    const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
+    return (value) => g.call(value);
+})();
+function isUint8Array(value) {
+    return TypedArrayPrototypeGetSymbolToStringTag(value) === 'Uint8Array';
+}
+function isAnyArrayBuffer(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        (value[Symbol.toStringTag] === 'ArrayBuffer' ||
+            value[Symbol.toStringTag] === 'SharedArrayBuffer'));
+}
+function isRegExp(regexp) {
+    return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === '[object RegExp]';
+}
+function isMap(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        value[Symbol.toStringTag] === 'Map');
+}
+function isDate(date) {
+    return date instanceof Date || Object.prototype.toString.call(date) === '[object Date]';
+}
+function defaultInspect(x, _options) {
+    return JSON.stringify(x, (k, v) => {
+        if (typeof v === 'bigint') {
+            return { $numberLong: `${v}` };
+        }
+        else if (isMap(v)) {
+            return Object.fromEntries(v);
+        }
+        return v;
+    });
+}
+function getStylizeFunction(options) {
+    const stylizeExists = options != null &&
+        typeof options === 'object' &&
+        'stylize' in options &&
+        typeof options.stylize === 'function';
+    if (stylizeExists) {
+        return options.stylize;
+    }
+}
+
+const BSON_MAJOR_VERSION = 7;
+const BSON_VERSION_SYMBOL = Symbol.for('@@mdb.bson.version');
+const BSON_INT32_MAX = 0x7fffffff;
+const BSON_INT32_MIN = -2147483648;
+const BSON_INT64_MAX = Math.pow(2, 63) - 1;
+const BSON_INT64_MIN = -Math.pow(2, 63);
+const JS_INT_MAX = Math.pow(2, 53);
+const JS_INT_MIN = -Math.pow(2, 53);
+const BSON_DATA_NUMBER = 1;
+const BSON_DATA_STRING = 2;
+const BSON_DATA_OBJECT = 3;
+const BSON_DATA_ARRAY = 4;
+const BSON_DATA_BINARY = 5;
+const BSON_DATA_UNDEFINED = 6;
+const BSON_DATA_OID = 7;
+const BSON_DATA_BOOLEAN = 8;
+const BSON_DATA_DATE = 9;
+const BSON_DATA_NULL = 10;
+const BSON_DATA_REGEXP = 11;
+const BSON_DATA_DBPOINTER = 12;
+const BSON_DATA_CODE = 13;
+const BSON_DATA_SYMBOL = 14;
+const BSON_DATA_CODE_W_SCOPE = 15;
+const BSON_DATA_INT = 16;
+const BSON_DATA_TIMESTAMP = 17;
+const BSON_DATA_LONG = 18;
+const BSON_DATA_DECIMAL128 = 19;
+const BSON_DATA_MIN_KEY = 0xff;
+const BSON_DATA_MAX_KEY = 0x7f;
+const BSON_BINARY_SUBTYPE_DEFAULT = 0;
+const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
+const BSONType = Object.freeze({
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: -1,
+    maxKey: 127
+});
+
+class BSONError extends Error {
+    get bsonError() {
+        return true;
+    }
+    get name() {
+        return 'BSONError';
+    }
+    constructor(message, options) {
+        super(message, options);
+    }
+    static isBSONError(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            'bsonError' in value &&
+            value.bsonError === true &&
+            'name' in value &&
+            'message' in value &&
+            'stack' in value);
+    }
+}
+class BSONVersionError extends BSONError {
+    get name() {
+        return 'BSONVersionError';
+    }
+    constructor() {
+        super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
+    }
+}
+class BSONRuntimeError extends BSONError {
+    get name() {
+        return 'BSONRuntimeError';
+    }
+    constructor(message) {
+        super(message);
+    }
+}
+class BSONOffsetError extends BSONError {
+    get name() {
+        return 'BSONOffsetError';
+    }
+    offset;
+    constructor(message, offset, options) {
+        super(`${message}. offset: ${offset}`, options);
+        this.offset = offset;
+    }
+}
+
+let TextDecoderFatal;
+let TextDecoderNonFatal;
+function parseUtf8(buffer, start, end, fatal) {
+    if (fatal) {
+        TextDecoderFatal ??= new TextDecoder('utf8', { fatal: true });
+        try {
+            return TextDecoderFatal.decode(buffer.subarray(start, end));
+        }
+        catch (cause) {
+            throw new BSONError('Invalid UTF-8 string in BSON document', { cause });
+        }
+    }
+    TextDecoderNonFatal ??= new TextDecoder('utf8', { fatal: false });
+    return TextDecoderNonFatal.decode(buffer.subarray(start, end));
+}
+
+function tryReadBasicLatin(uint8array, start, end) {
+    if (uint8array.length === 0) {
+        return '';
+    }
+    const stringByteLength = end - start;
+    if (stringByteLength === 0) {
+        return '';
+    }
+    if (stringByteLength > 20) {
+        return null;
+    }
+    if (stringByteLength === 1 && uint8array[start] < 128) {
+        return String.fromCharCode(uint8array[start]);
+    }
+    if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
+        return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
+    }
+    if (stringByteLength === 3 &&
+        uint8array[start] < 128 &&
+        uint8array[start + 1] < 128 &&
+        uint8array[start + 2] < 128) {
+        return (String.fromCharCode(uint8array[start]) +
+            String.fromCharCode(uint8array[start + 1]) +
+            String.fromCharCode(uint8array[start + 2]));
+    }
+    const latinBytes = [];
+    for (let i = start; i < end; i++) {
+        const byte = uint8array[i];
+        if (byte > 127) {
+            return null;
+        }
+        latinBytes.push(byte);
+    }
+    return String.fromCharCode(...latinBytes);
+}
+function tryWriteBasicLatin(destination, source, offset) {
+    if (source.length === 0)
+        return 0;
+    if (source.length > 25)
+        return null;
+    if (destination.length - offset < source.length)
+        return null;
+    for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
+        const char = source.charCodeAt(charOffset);
+        if (char > 127)
+            return null;
+        destination[destinationOffset] = char;
+    }
+    return source.length;
+}
+
+function nodejsMathRandomBytes(byteLength) {
+    return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+function nodejsSecureRandomBytes(byteLength) {
+    return crypto.getRandomValues(nodeJsByteUtils.allocate(byteLength));
+}
+const nodejsRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return nodejsSecureRandomBytes;
+    }
+    else {
+        return nodejsMathRandomBytes;
+    }
+})();
+const nodeJsByteUtils = {
+    toLocalBufferType(potentialBuffer) {
+        if (Buffer.isBuffer(potentialBuffer)) {
+            return potentialBuffer;
+        }
+        if (ArrayBuffer.isView(potentialBuffer)) {
+            return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
+        }
+        const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return Buffer.from(potentialBuffer);
+        }
+        throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);
+    },
+    allocate(size) {
+        return Buffer.alloc(size);
+    },
+    allocateUnsafe(size) {
+        return Buffer.allocUnsafe(size);
+    },
+    equals(a, b) {
+        return nodeJsByteUtils.toLocalBufferType(a).equals(b);
+    },
+    fromNumberArray(array) {
+        return Buffer.from(array);
+    },
+    fromBase64(base64) {
+        return Buffer.from(base64, 'base64');
+    },
+    toBase64(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');
+    },
+    fromISO88591(codePoints) {
+        return Buffer.from(codePoints, 'binary');
+    },
+    toISO88591(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');
+    },
+    fromHex(hex) {
+        return Buffer.from(hex, 'hex');
+    },
+    toHex(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');
+    },
+    toUTF8(buffer, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
+        if (fatal) {
+            for (let i = 0; i < string.length; i++) {
+                if (string.charCodeAt(i) === 0xfffd) {
+                    parseUtf8(buffer, start, end, true);
+                    break;
+                }
+            }
+        }
+        return string;
+    },
+    utf8ByteLength(input) {
+        return Buffer.byteLength(input, 'utf8');
+    },
+    encodeUTF8Into(buffer, source, byteOffset) {
+        const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset);
+        if (latinBytesWritten != null) {
+            return latinBytesWritten;
+        }
+        return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
+    },
+    randomBytes: nodejsRandomBytes,
+    swap32(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).swap32();
+    }
+};
+
+function isReactNative() {
+    const { navigator } = globalThis;
+    return typeof navigator === 'object' && navigator.product === 'ReactNative';
+}
+function webMathRandomBytes(byteLength) {
+    if (byteLength < 0) {
+        throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
+    }
+    return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+const webRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return (byteLength) => {
+            return crypto.getRandomValues(webByteUtils.allocate(byteLength));
+        };
+    }
+    else {
+        if (isReactNative()) {
+            const { console } = globalThis;
+            console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');
+        }
+        return webMathRandomBytes;
+    }
+})();
+const HEX_DIGIT = /(\d|[a-f])/i;
+const webByteUtils = {
+    toLocalBufferType(potentialUint8array) {
+        const stringTag = potentialUint8array?.[Symbol.toStringTag] ??
+            Object.prototype.toString.call(potentialUint8array);
+        if (stringTag === 'Uint8Array') {
+            return potentialUint8array;
+        }
+        if (ArrayBuffer.isView(potentialUint8array)) {
+            return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
+        }
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return new Uint8Array(potentialUint8array);
+        }
+        throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);
+    },
+    allocate(size) {
+        if (typeof size !== 'number') {
+            throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
+        }
+        return new Uint8Array(size);
+    },
+    allocateUnsafe(size) {
+        return webByteUtils.allocate(size);
+    },
+    equals(a, b) {
+        if (a.byteLength !== b.byteLength) {
+            return false;
+        }
+        for (let i = 0; i < a.byteLength; i++) {
+            if (a[i] !== b[i]) {
+                return false;
+            }
+        }
+        return true;
+    },
+    fromNumberArray(array) {
+        return Uint8Array.from(array);
+    },
+    fromBase64(base64) {
+        return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
+    },
+    toBase64(uint8array) {
+        return btoa(webByteUtils.toISO88591(uint8array));
+    },
+    fromISO88591(codePoints) {
+        return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);
+    },
+    toISO88591(uint8array) {
+        return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');
+    },
+    fromHex(hex) {
+        const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
+        const buffer = [];
+        for (let i = 0; i < evenLengthHex.length; i += 2) {
+            const firstDigit = evenLengthHex[i];
+            const secondDigit = evenLengthHex[i + 1];
+            if (!HEX_DIGIT.test(firstDigit)) {
+                break;
+            }
+            if (!HEX_DIGIT.test(secondDigit)) {
+                break;
+            }
+            const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
+            buffer.push(hexDigit);
+        }
+        return Uint8Array.from(buffer);
+    },
+    toHex(uint8array) {
+        return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
+    },
+    toUTF8(uint8array, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        return parseUtf8(uint8array, start, end, fatal);
+    },
+    utf8ByteLength(input) {
+        return new TextEncoder().encode(input).byteLength;
+    },
+    encodeUTF8Into(uint8array, source, byteOffset) {
+        const bytes = new TextEncoder().encode(source);
+        uint8array.set(bytes, byteOffset);
+        return bytes.byteLength;
+    },
+    randomBytes: webRandomBytes,
+    swap32(buffer) {
+        if (buffer.length % 4 !== 0) {
+            throw new RangeError('Buffer size must be a multiple of 32-bits');
+        }
+        for (let i = 0; i < buffer.length; i += 4) {
+            const byte0 = buffer[i];
+            const byte1 = buffer[i + 1];
+            const byte2 = buffer[i + 2];
+            const byte3 = buffer[i + 3];
+            buffer[i] = byte3;
+            buffer[i + 1] = byte2;
+            buffer[i + 2] = byte1;
+            buffer[i + 3] = byte0;
+        }
+        return buffer;
+    }
+};
+
+const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
+const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
+
+const bsonType = Symbol.for('@@mdb.bson.type');
+class BSONValue {
+    get [bsonType]() {
+        return this._bsontype;
+    }
+    get [BSON_VERSION_SYMBOL]() {
+        return BSON_MAJOR_VERSION;
+    }
+    [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) {
+        return this.inspect(depth, options, inspect);
+    }
+}
+
+const FLOAT = new Float64Array(1);
+const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
+FLOAT[0] = -1;
+const isBigEndian = FLOAT_BYTES[7] === 0;
+const NumberUtils = {
+    isBigEndian,
+    getNonnegativeInt32LE(source, offset) {
+        if (source[offset + 3] > 127) {
+            throw new RangeError(`Size cannot be negative at offset: ${offset}`);
+        }
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getInt32LE(source, offset) {
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getUint32LE(source, offset) {
+        return (source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+    },
+    getUint32BE(source, offset) {
+        return (source[offset + 3] +
+            source[offset + 2] * 256 +
+            source[offset + 1] * 65536 +
+            source[offset] * 16777216);
+    },
+    getBigInt64LE(source, offset) {
+        const hi = BigInt(source[offset + 4] +
+            source[offset + 5] * 256 +
+            source[offset + 6] * 65536 +
+            (source[offset + 7] << 24));
+        const lo = BigInt(source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+        return (hi << 32n) + lo;
+    },
+    getFloat64LE: isBigEndian
+        ? (source, offset) => {
+            FLOAT_BYTES[7] = source[offset];
+            FLOAT_BYTES[6] = source[offset + 1];
+            FLOAT_BYTES[5] = source[offset + 2];
+            FLOAT_BYTES[4] = source[offset + 3];
+            FLOAT_BYTES[3] = source[offset + 4];
+            FLOAT_BYTES[2] = source[offset + 5];
+            FLOAT_BYTES[1] = source[offset + 6];
+            FLOAT_BYTES[0] = source[offset + 7];
+            return FLOAT[0];
+        }
+        : (source, offset) => {
+            FLOAT_BYTES[0] = source[offset];
+            FLOAT_BYTES[1] = source[offset + 1];
+            FLOAT_BYTES[2] = source[offset + 2];
+            FLOAT_BYTES[3] = source[offset + 3];
+            FLOAT_BYTES[4] = source[offset + 4];
+            FLOAT_BYTES[5] = source[offset + 5];
+            FLOAT_BYTES[6] = source[offset + 6];
+            FLOAT_BYTES[7] = source[offset + 7];
+            return FLOAT[0];
+        },
+    setInt32BE(destination, offset, value) {
+        destination[offset + 3] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset] = value;
+        return 4;
+    },
+    setInt32LE(destination, offset, value) {
+        destination[offset] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 3] = value;
+        return 4;
+    },
+    setBigInt64LE(destination, offset, value) {
+        const mask32bits = 0xffffffffn;
+        let lo = Number(value & mask32bits);
+        destination[offset] = lo;
+        lo >>= 8;
+        destination[offset + 1] = lo;
+        lo >>= 8;
+        destination[offset + 2] = lo;
+        lo >>= 8;
+        destination[offset + 3] = lo;
+        let hi = Number((value >> 32n) & mask32bits);
+        destination[offset + 4] = hi;
+        hi >>= 8;
+        destination[offset + 5] = hi;
+        hi >>= 8;
+        destination[offset + 6] = hi;
+        hi >>= 8;
+        destination[offset + 7] = hi;
+        return 8;
+    },
+    setFloat64LE: isBigEndian
+        ? (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[7];
+            destination[offset + 1] = FLOAT_BYTES[6];
+            destination[offset + 2] = FLOAT_BYTES[5];
+            destination[offset + 3] = FLOAT_BYTES[4];
+            destination[offset + 4] = FLOAT_BYTES[3];
+            destination[offset + 5] = FLOAT_BYTES[2];
+            destination[offset + 6] = FLOAT_BYTES[1];
+            destination[offset + 7] = FLOAT_BYTES[0];
+            return 8;
+        }
+        : (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[0];
+            destination[offset + 1] = FLOAT_BYTES[1];
+            destination[offset + 2] = FLOAT_BYTES[2];
+            destination[offset + 3] = FLOAT_BYTES[3];
+            destination[offset + 4] = FLOAT_BYTES[4];
+            destination[offset + 5] = FLOAT_BYTES[5];
+            destination[offset + 6] = FLOAT_BYTES[6];
+            destination[offset + 7] = FLOAT_BYTES[7];
+            return 8;
+        }
+};
+
+class Binary extends BSONValue {
+    get _bsontype() {
+        return 'Binary';
+    }
+    static BSON_BINARY_SUBTYPE_DEFAULT = 0;
+    static BUFFER_SIZE = 256;
+    static SUBTYPE_DEFAULT = 0;
+    static SUBTYPE_FUNCTION = 1;
+    static SUBTYPE_BYTE_ARRAY = 2;
+    static SUBTYPE_UUID_OLD = 3;
+    static SUBTYPE_UUID = 4;
+    static SUBTYPE_MD5 = 5;
+    static SUBTYPE_ENCRYPTED = 6;
+    static SUBTYPE_COLUMN = 7;
+    static SUBTYPE_SENSITIVE = 8;
+    static SUBTYPE_VECTOR = 9;
+    static SUBTYPE_USER_DEFINED = 128;
+    static VECTOR_TYPE = Object.freeze({
+        Int8: 0x03,
+        Float32: 0x27,
+        PackedBit: 0x10
+    });
+    buffer;
+    sub_type;
+    position;
+    constructor(buffer, subType) {
+        super();
+        if (!(buffer == null) &&
+            typeof buffer === 'string' &&
+            !ArrayBuffer.isView(buffer) &&
+            !isAnyArrayBuffer(buffer) &&
+            !Array.isArray(buffer)) {
+            throw new BSONError('Binary can only be constructed from Uint8Array or number[]');
+        }
+        this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
+        if (buffer == null) {
+            this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
+            this.position = 0;
+        }
+        else {
+            this.buffer = Array.isArray(buffer)
+                ? ByteUtils.fromNumberArray(buffer)
+                : ByteUtils.toLocalBufferType(buffer);
+            this.position = this.buffer.byteLength;
+        }
+    }
+    put(byteValue) {
+        if (typeof byteValue === 'string' && byteValue.length !== 1) {
+            throw new BSONError('only accepts single character String');
+        }
+        else if (typeof byteValue !== 'number' && byteValue.length !== 1)
+            throw new BSONError('only accepts single character Uint8Array or Array');
+        let decodedByte;
+        if (typeof byteValue === 'string') {
+            decodedByte = byteValue.charCodeAt(0);
+        }
+        else if (typeof byteValue === 'number') {
+            decodedByte = byteValue;
+        }
+        else {
+            decodedByte = byteValue[0];
+        }
+        if (decodedByte < 0 || decodedByte > 255) {
+            throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
+        }
+        if (this.buffer.byteLength > this.position) {
+            this.buffer[this.position++] = decodedByte;
+        }
+        else {
+            const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+            this.buffer[this.position++] = decodedByte;
+        }
+    }
+    write(sequence, offset) {
+        offset = typeof offset === 'number' ? offset : this.position;
+        if (this.buffer.byteLength < offset + sequence.length) {
+            const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+        }
+        if (ArrayBuffer.isView(sequence)) {
+            this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
+            this.position =
+                offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
+        }
+        else if (typeof sequence === 'string') {
+            throw new BSONError('input cannot be string');
+        }
+    }
+    read(position, length) {
+        length = length && length > 0 ? length : this.position;
+        const end = position + length;
+        return this.buffer.subarray(position, end > this.position ? this.position : end);
+    }
+    value() {
+        return this.buffer.length === this.position
+            ? this.buffer
+            : this.buffer.subarray(0, this.position);
+    }
+    length() {
+        return this.position;
+    }
+    toJSON() {
+        return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.buffer.subarray(0, this.position));
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        if (encoding === 'utf8' || encoding === 'utf-8')
+            return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+        return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (this.sub_type === Binary.SUBTYPE_VECTOR) {
+            validateBinaryVector(this);
+        }
+        const base64String = ByteUtils.toBase64(this.buffer);
+        const subType = Number(this.sub_type).toString(16);
+        if (options.legacy) {
+            return {
+                $binary: base64String,
+                $type: subType.length === 1 ? '0' + subType : subType
+            };
+        }
+        return {
+            $binary: {
+                base64: base64String,
+                subType: subType.length === 1 ? '0' + subType : subType
+            }
+        };
+    }
+    toUUID() {
+        if (this.sub_type === Binary.SUBTYPE_UUID) {
+            return new UUID(this.buffer.subarray(0, this.position));
+        }
+        throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
+    }
+    static createFromHexString(hex, subType) {
+        return new Binary(ByteUtils.fromHex(hex), subType);
+    }
+    static createFromBase64(base64, subType) {
+        return new Binary(ByteUtils.fromBase64(base64), subType);
+    }
+    static fromExtendedJSON(doc, options) {
+        options = options || {};
+        let data;
+        let type;
+        if ('$binary' in doc) {
+            if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
+                type = doc.$type ? parseInt(doc.$type, 16) : 0;
+                data = ByteUtils.fromBase64(doc.$binary);
+            }
+            else {
+                if (typeof doc.$binary !== 'string') {
+                    type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
+                    data = ByteUtils.fromBase64(doc.$binary.base64);
+                }
+            }
+        }
+        else if ('$uuid' in doc) {
+            type = 4;
+            data = UUID.bytesFromString(doc.$uuid);
+        }
+        if (!data) {
+            throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
+        }
+        return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        const base64Arg = inspect(base64, options);
+        const subTypeArg = inspect(this.sub_type, options);
+        return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
+    }
+    toInt8Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {
+            throw new BSONError('Binary datatype field is not Int8');
+        }
+        validateBinaryVector(this);
+        return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toFloat32Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {
+            throw new BSONError('Binary datatype field is not Float32');
+        }
+        validateBinaryVector(this);
+        const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(floatBytes);
+        return new Float32Array(floatBytes.buffer);
+    }
+    toPackedBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        const byteCount = this.length() - 2;
+        const bitCount = byteCount * 8 - this.buffer[1];
+        const bits = new Int8Array(bitCount);
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = (bitOffset / 8) | 0;
+            const byte = this.buffer[byteOffset + 2];
+            const shift = 7 - (bitOffset % 8);
+            const bit = (byte >> shift) & 1;
+            bits[bitOffset] = bit;
+        }
+        return bits;
+    }
+    static fromInt8Array(array) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.Int8;
+        buffer[1] = 0;
+        const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        buffer.set(intBytes, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromFloat32Array(array) {
+        const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
+        binaryBytes[0] = Binary.VECTOR_TYPE.Float32;
+        binaryBytes[1] = 0;
+        const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        binaryBytes.set(floatBytes, 2);
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
+        const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromPackedBits(array, padding = 0) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.PackedBit;
+        buffer[1] = padding;
+        buffer.set(array, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromBits(bits) {
+        const byteLength = (bits.length + 7) >>> 3;
+        const bytes = new Uint8Array(byteLength + 2);
+        bytes[0] = Binary.VECTOR_TYPE.PackedBit;
+        const remainder = bits.length % 8;
+        bytes[1] = remainder === 0 ? 0 : 8 - remainder;
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = bitOffset >>> 3;
+            const bit = bits[bitOffset];
+            if (bit !== 0 && bit !== 1) {
+                throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
+            }
+            if (bit === 0)
+                continue;
+            const shift = 7 - (bitOffset % 8);
+            bytes[byteOffset + 2] |= bit << shift;
+        }
+        return new this(bytes, Binary.SUBTYPE_VECTOR);
+    }
+}
+function validateBinaryVector(vector) {
+    if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
+        return;
+    const size = vector.position;
+    const datatype = vector.buffer[0];
+    const padding = vector.buffer[1];
+    if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) &&
+        padding !== 0) {
+        throw new BSONError('Invalid Vector: padding must be zero for int8 and float32 vectors');
+    }
+    if (datatype === Binary.VECTOR_TYPE.Float32) {
+        if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
+            throw new BSONError('Invalid Vector: Float32 vector must contain a multiple of 4 bytes');
+        }
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
+        throw new BSONError('Invalid Vector: padding must be zero for packed bit vectors that are empty');
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
+        throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
+    }
+}
+const UUID_BYTE_LENGTH = 16;
+const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
+const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
+class UUID extends Binary {
+    constructor(input) {
+        let bytes;
+        if (input == null) {
+            bytes = UUID.generate();
+        }
+        else if (input instanceof UUID) {
+            bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
+        }
+        else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
+            bytes = ByteUtils.toLocalBufferType(input);
+        }
+        else if (typeof input === 'string') {
+            bytes = UUID.bytesFromString(input);
+        }
+        else {
+            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).');
+        }
+        super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+    }
+    toHexString(includeDashes = true) {
+        if (includeDashes) {
+            return [
+                ByteUtils.toHex(this.buffer.subarray(0, 4)),
+                ByteUtils.toHex(this.buffer.subarray(4, 6)),
+                ByteUtils.toHex(this.buffer.subarray(6, 8)),
+                ByteUtils.toHex(this.buffer.subarray(8, 10)),
+                ByteUtils.toHex(this.buffer.subarray(10, 16))
+            ].join('-');
+        }
+        return ByteUtils.toHex(this.buffer);
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.id);
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    equals(otherId) {
+        if (!otherId) {
+            return false;
+        }
+        if (otherId instanceof UUID) {
+            return ByteUtils.equals(otherId.id, this.id);
+        }
+        try {
+            return ByteUtils.equals(new UUID(otherId).id, this.id);
+        }
+        catch {
+            return false;
+        }
+    }
+    toBinary() {
+        return new Binary(this.id, Binary.SUBTYPE_UUID);
+    }
+    static generate() {
+        const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
+        bytes[6] = (bytes[6] & 0x0f) | 0x40;
+        bytes[8] = (bytes[8] & 0x3f) | 0x80;
+        return bytes;
+    }
+    static isValid(input) {
+        if (!input) {
+            return false;
+        }
+        if (typeof input === 'string') {
+            return UUID.isValidUUIDString(input);
+        }
+        if (isUint8Array(input)) {
+            return input.byteLength === UUID_BYTE_LENGTH;
+        }
+        return (input._bsontype === 'Binary' &&
+            input.sub_type === this.SUBTYPE_UUID &&
+            input.buffer.byteLength === 16);
+    }
+    static createFromHexString(hexString) {
+        const buffer = UUID.bytesFromString(hexString);
+        return new UUID(buffer);
+    }
+    static createFromBase64(base64) {
+        return new UUID(ByteUtils.fromBase64(base64));
+    }
+    static bytesFromString(representation) {
+        if (!UUID.isValidUUIDString(representation)) {
+            throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
+        }
+        return ByteUtils.fromHex(representation.replace(/-/g, ''));
+    }
+    static isValidUUIDString(representation) {
+        return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new UUID(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+class Code extends BSONValue {
+    get _bsontype() {
+        return 'Code';
+    }
+    code;
+    scope;
+    constructor(code, scope) {
+        super();
+        this.code = code.toString();
+        this.scope = scope ?? null;
+    }
+    toJSON() {
+        if (this.scope != null) {
+            return { code: this.code, scope: this.scope };
+        }
+        return { code: this.code };
+    }
+    toExtendedJSON() {
+        if (this.scope) {
+            return { $code: this.code, $scope: this.scope };
+        }
+        return { $code: this.code };
+    }
+    static fromExtendedJSON(doc) {
+        return new Code(doc.$code, doc.$scope);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        let parametersString = inspect(this.code, options);
+        const multiLineFn = parametersString.includes('\n');
+        if (this.scope != null) {
+            parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
+        }
+        const endingNewline = multiLineFn && this.scope === null;
+        return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
+    }
+}
+
+function isDBRefLike(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '$id' in value &&
+        value.$id != null &&
+        '$ref' in value &&
+        typeof value.$ref === 'string' &&
+        (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));
+}
+class DBRef extends BSONValue {
+    get _bsontype() {
+        return 'DBRef';
+    }
+    collection;
+    oid;
+    db;
+    fields;
+    constructor(collection, oid, db, fields) {
+        super();
+        const parts = collection.split('.');
+        if (parts.length === 2) {
+            db = parts.shift();
+            collection = parts.shift();
+        }
+        this.collection = collection;
+        this.oid = oid;
+        this.db = db;
+        this.fields = fields || {};
+    }
+    get namespace() {
+        return this.collection;
+    }
+    set namespace(value) {
+        this.collection = value;
+    }
+    toJSON() {
+        const o = Object.assign({
+            $ref: this.collection,
+            $id: this.oid
+        }, this.fields);
+        if (this.db != null)
+            o.$db = this.db;
+        return o;
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        let o = {
+            $ref: this.collection,
+            $id: this.oid
+        };
+        if (options.legacy) {
+            return o;
+        }
+        if (this.db)
+            o.$db = this.db;
+        o = Object.assign(o, this.fields);
+        return o;
+    }
+    static fromExtendedJSON(doc) {
+        const copy = Object.assign({}, doc);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const args = [
+            inspect(this.namespace, options),
+            inspect(this.oid, options),
+            ...(this.db ? [inspect(this.db, options)] : []),
+            ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
+        ];
+        args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
+        return `new DBRef(${args.join(', ')})`;
+    }
+}
+
+function removeLeadingZerosAndExplicitPlus(str) {
+    if (str === '') {
+        return str;
+    }
+    let startIndex = 0;
+    const isNegative = str[startIndex] === '-';
+    const isExplicitlyPositive = str[startIndex] === '+';
+    if (isExplicitlyPositive || isNegative) {
+        startIndex += 1;
+    }
+    let foundInsignificantZero = false;
+    for (; startIndex < str.length && str[startIndex] === '0'; ++startIndex) {
+        foundInsignificantZero = true;
+    }
+    if (!foundInsignificantZero) {
+        return isExplicitlyPositive ? str.slice(1) : str;
+    }
+    return `${isNegative ? '-' : ''}${str.length === startIndex ? '0' : str.slice(startIndex)}`;
+}
+function validateStringCharacters(str, radix) {
+    radix = radix ?? 10;
+    const validCharacters = '0123456789abcdefghijklmnopqrstuvwxyz'.slice(0, radix);
+    const regex = new RegExp(`[^-+${validCharacters}]`, 'i');
+    return regex.test(str) ? false : str;
+}
+
+let wasm = undefined;
+try {
+    wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
+}
+catch {
+}
+const TWO_PWR_16_DBL = 1 << 16;
+const TWO_PWR_24_DBL = 1 << 24;
+const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
+const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
+const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
+const INT_CACHE = {};
+const UINT_CACHE = {};
+const MAX_INT64_STRING_LENGTH = 20;
+const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
+class Long extends BSONValue {
+    get _bsontype() {
+        return 'Long';
+    }
+    get __isLong__() {
+        return true;
+    }
+    high;
+    low;
+    unsigned;
+    constructor(lowOrValue = 0, highOrUnsigned, unsigned) {
+        super();
+        const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);
+        const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;
+        const res = typeof lowOrValue === 'string'
+            ? Long.fromString(lowOrValue, unsignedBool)
+            : typeof lowOrValue === 'bigint'
+                ? Long.fromBigInt(lowOrValue, unsignedBool)
+                : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
+        this.low = res.low;
+        this.high = res.high;
+        this.unsigned = res.unsigned;
+    }
+    static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
+    static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
+    static ZERO = Long.fromInt(0);
+    static UZERO = Long.fromInt(0, true);
+    static ONE = Long.fromInt(1);
+    static UONE = Long.fromInt(1, true);
+    static NEG_ONE = Long.fromInt(-1);
+    static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
+    static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
+    static fromBits(lowBits, highBits, unsigned) {
+        return new Long(lowBits, highBits, unsigned);
+    }
+    static fromInt(value, unsigned) {
+        let obj, cachedObj, cache;
+        if (unsigned) {
+            value >>>= 0;
+            if ((cache = 0 <= value && value < 256)) {
+                cachedObj = UINT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
+            if (cache)
+                UINT_CACHE[value] = obj;
+            return obj;
+        }
+        else {
+            value |= 0;
+            if ((cache = -128 <= value && value < 128)) {
+                cachedObj = INT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
+            if (cache)
+                INT_CACHE[value] = obj;
+            return obj;
+        }
+    }
+    static fromNumber(value, unsigned) {
+        if (isNaN(value))
+            return unsigned ? Long.UZERO : Long.ZERO;
+        if (unsigned) {
+            if (value < 0)
+                return Long.UZERO;
+            if (value >= TWO_PWR_64_DBL)
+                return Long.MAX_UNSIGNED_VALUE;
+        }
+        else {
+            if (value <= -TWO_PWR_63_DBL)
+                return Long.MIN_VALUE;
+            if (value + 1 >= TWO_PWR_63_DBL)
+                return Long.MAX_VALUE;
+        }
+        if (value < 0)
+            return Long.fromNumber(-value, unsigned).neg();
+        return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
+    }
+    static fromBigInt(value, unsigned) {
+        const FROM_BIGINT_BIT_MASK = 0xffffffffn;
+        const FROM_BIGINT_BIT_SHIFT = 32n;
+        return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number((value >> FROM_BIGINT_BIT_SHIFT) & FROM_BIGINT_BIT_MASK), unsigned);
+    }
+    static _fromString(str, unsigned, radix) {
+        if (str.length === 0)
+            throw new BSONError('empty string');
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        let p;
+        if ((p = str.indexOf('-')) > 0)
+            throw new BSONError('interior hyphen');
+        else if (p === 0) {
+            return Long._fromString(str.substring(1), unsigned, radix).neg();
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 8));
+        let result = Long.ZERO;
+        for (let i = 0; i < str.length; i += 8) {
+            const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
+            if (size < 8) {
+                const power = Long.fromNumber(Math.pow(radix, size));
+                result = result.mul(power).add(Long.fromNumber(value));
+            }
+            else {
+                result = result.mul(radixToPower);
+                result = result.add(Long.fromNumber(value));
+            }
+        }
+        result.unsigned = unsigned;
+        return result;
+    }
+    static fromStringStrict(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str.trim() !== str) {
+            throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
+        }
+        if (!validateStringCharacters(str, radix)) {
+            throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
+        }
+        const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
+        const result = Long._fromString(cleanedStr, unsigned, radix);
+        if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
+            throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? 'an unsigned' : 'a signed'} 64-bit Long ${radix != null ? `with radix: ${radix}` : ''}`);
+        }
+        return result;
+    }
+    static fromString(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str === 'NaN' && radix < 24) {
+            return Long.ZERO;
+        }
+        else if ((str === 'Infinity' || str === '+Infinity' || str === '-Infinity') && radix < 35) {
+            return Long.ZERO;
+        }
+        return Long._fromString(str, unsigned, radix);
+    }
+    static fromBytes(bytes, unsigned, le) {
+        return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
+    }
+    static fromBytesLE(bytes, unsigned) {
+        return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned);
+    }
+    static fromBytesBE(bytes, unsigned) {
+        return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned);
+    }
+    static isLong(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            '__isLong__' in value &&
+            value.__isLong__ === true);
+    }
+    static fromValue(val, unsigned) {
+        if (typeof val === 'number')
+            return Long.fromNumber(val, unsigned);
+        if (typeof val === 'string')
+            return Long.fromString(val, unsigned);
+        return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
+    }
+    add(addend) {
+        if (!Long.isLong(addend))
+            addend = Long.fromValue(addend);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = addend.high >>> 16;
+        const b32 = addend.high & 0xffff;
+        const b16 = addend.low >>> 16;
+        const b00 = addend.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 + b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 + b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 + b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 + b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    and(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
+    }
+    compare(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.eq(other))
+            return 0;
+        const thisNeg = this.isNegative(), otherNeg = other.isNegative();
+        if (thisNeg && !otherNeg)
+            return -1;
+        if (!thisNeg && otherNeg)
+            return 1;
+        if (!this.unsigned)
+            return this.sub(other).isNegative() ? -1 : 1;
+        return other.high >>> 0 > this.high >>> 0 ||
+            (other.high === this.high && other.low >>> 0 > this.low >>> 0)
+            ? -1
+            : 1;
+    }
+    comp(other) {
+        return this.compare(other);
+    }
+    divide(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (divisor.isZero())
+            throw new BSONError('division by zero');
+        if (wasm) {
+            if (!this.unsigned &&
+                this.high === -2147483648 &&
+                divisor.low === -1 &&
+                divisor.high === -1) {
+                return this;
+            }
+            const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (this.isZero())
+            return this.unsigned ? Long.UZERO : Long.ZERO;
+        let approx, rem, res;
+        if (!this.unsigned) {
+            if (this.eq(Long.MIN_VALUE)) {
+                if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
+                    return Long.MIN_VALUE;
+                else if (divisor.eq(Long.MIN_VALUE))
+                    return Long.ONE;
+                else {
+                    const halfThis = this.shr(1);
+                    approx = halfThis.div(divisor).shl(1);
+                    if (approx.eq(Long.ZERO)) {
+                        return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
+                    }
+                    else {
+                        rem = this.sub(divisor.mul(approx));
+                        res = approx.add(rem.div(divisor));
+                        return res;
+                    }
+                }
+            }
+            else if (divisor.eq(Long.MIN_VALUE))
+                return this.unsigned ? Long.UZERO : Long.ZERO;
+            if (this.isNegative()) {
+                if (divisor.isNegative())
+                    return this.neg().div(divisor.neg());
+                return this.neg().div(divisor).neg();
+            }
+            else if (divisor.isNegative())
+                return this.div(divisor.neg()).neg();
+            res = Long.ZERO;
+        }
+        else {
+            if (!divisor.unsigned)
+                divisor = divisor.toUnsigned();
+            if (divisor.gt(this))
+                return Long.UZERO;
+            if (divisor.gt(this.shru(1)))
+                return Long.UONE;
+            res = Long.UZERO;
+        }
+        rem = this;
+        while (rem.gte(divisor)) {
+            approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
+            const log2 = Math.ceil(Math.log(approx) / Math.LN2);
+            const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
+            let approxRes = Long.fromNumber(approx);
+            let approxRem = approxRes.mul(divisor);
+            while (approxRem.isNegative() || approxRem.gt(rem)) {
+                approx -= delta;
+                approxRes = Long.fromNumber(approx, this.unsigned);
+                approxRem = approxRes.mul(divisor);
+            }
+            if (approxRes.isZero())
+                approxRes = Long.ONE;
+            res = res.add(approxRes);
+            rem = rem.sub(approxRem);
+        }
+        return res;
+    }
+    div(divisor) {
+        return this.divide(divisor);
+    }
+    equals(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
+            return false;
+        return this.high === other.high && this.low === other.low;
+    }
+    eq(other) {
+        return this.equals(other);
+    }
+    getHighBits() {
+        return this.high;
+    }
+    getHighBitsUnsigned() {
+        return this.high >>> 0;
+    }
+    getLowBits() {
+        return this.low;
+    }
+    getLowBitsUnsigned() {
+        return this.low >>> 0;
+    }
+    getNumBitsAbs() {
+        if (this.isNegative()) {
+            return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
+        }
+        const val = this.high !== 0 ? this.high : this.low;
+        let bit;
+        for (bit = 31; bit > 0; bit--)
+            if ((val & (1 << bit)) !== 0)
+                break;
+        return this.high !== 0 ? bit + 33 : bit + 1;
+    }
+    greaterThan(other) {
+        return this.comp(other) > 0;
+    }
+    gt(other) {
+        return this.greaterThan(other);
+    }
+    greaterThanOrEqual(other) {
+        return this.comp(other) >= 0;
+    }
+    gte(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    ge(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    isEven() {
+        return (this.low & 1) === 0;
+    }
+    isNegative() {
+        return !this.unsigned && this.high < 0;
+    }
+    isOdd() {
+        return (this.low & 1) === 1;
+    }
+    isPositive() {
+        return this.unsigned || this.high >= 0;
+    }
+    isZero() {
+        return this.high === 0 && this.low === 0;
+    }
+    lessThan(other) {
+        return this.comp(other) < 0;
+    }
+    lt(other) {
+        return this.lessThan(other);
+    }
+    lessThanOrEqual(other) {
+        return this.comp(other) <= 0;
+    }
+    lte(other) {
+        return this.lessThanOrEqual(other);
+    }
+    modulo(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (wasm) {
+            const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        return this.sub(this.div(divisor).mul(divisor));
+    }
+    mod(divisor) {
+        return this.modulo(divisor);
+    }
+    rem(divisor) {
+        return this.modulo(divisor);
+    }
+    multiply(multiplier) {
+        if (this.isZero())
+            return Long.ZERO;
+        if (!Long.isLong(multiplier))
+            multiplier = Long.fromValue(multiplier);
+        if (wasm) {
+            const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (multiplier.isZero())
+            return Long.ZERO;
+        if (this.eq(Long.MIN_VALUE))
+            return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (multiplier.eq(Long.MIN_VALUE))
+            return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (this.isNegative()) {
+            if (multiplier.isNegative())
+                return this.neg().mul(multiplier.neg());
+            else
+                return this.neg().mul(multiplier).neg();
+        }
+        else if (multiplier.isNegative())
+            return this.mul(multiplier.neg()).neg();
+        if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
+            return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = multiplier.high >>> 16;
+        const b32 = multiplier.high & 0xffff;
+        const b16 = multiplier.low >>> 16;
+        const b00 = multiplier.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 * b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 * b00;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c16 += a00 * b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 * b00;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a16 * b16;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a00 * b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    mul(multiplier) {
+        return this.multiply(multiplier);
+    }
+    negate() {
+        if (!this.unsigned && this.eq(Long.MIN_VALUE))
+            return Long.MIN_VALUE;
+        return this.not().add(Long.ONE);
+    }
+    neg() {
+        return this.negate();
+    }
+    not() {
+        return Long.fromBits(~this.low, ~this.high, this.unsigned);
+    }
+    notEquals(other) {
+        return !this.equals(other);
+    }
+    neq(other) {
+        return this.notEquals(other);
+    }
+    ne(other) {
+        return this.notEquals(other);
+    }
+    or(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
+    }
+    shiftLeft(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
+        else
+            return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
+    }
+    shl(numBits) {
+        return this.shiftLeft(numBits);
+    }
+    shiftRight(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
+        else
+            return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
+    }
+    shr(numBits) {
+        return this.shiftRight(numBits);
+    }
+    shiftRightUnsigned(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        numBits &= 63;
+        if (numBits === 0)
+            return this;
+        else {
+            const high = this.high;
+            if (numBits < 32) {
+                const low = this.low;
+                return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
+            }
+            else if (numBits === 32)
+                return Long.fromBits(high, 0, this.unsigned);
+            else
+                return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
+        }
+    }
+    shr_u(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    shru(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    subtract(subtrahend) {
+        if (!Long.isLong(subtrahend))
+            subtrahend = Long.fromValue(subtrahend);
+        return this.add(subtrahend.neg());
+    }
+    sub(subtrahend) {
+        return this.subtract(subtrahend);
+    }
+    toInt() {
+        return this.unsigned ? this.low >>> 0 : this.low;
+    }
+    toNumber() {
+        if (this.unsigned)
+            return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
+        return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
+    }
+    toBigInt() {
+        return BigInt(this.toString());
+    }
+    toBytes(le) {
+        return le ? this.toBytesLE() : this.toBytesBE();
+    }
+    toBytesLE() {
+        const hi = this.high, lo = this.low;
+        return [
+            lo & 0xff,
+            (lo >>> 8) & 0xff,
+            (lo >>> 16) & 0xff,
+            lo >>> 24,
+            hi & 0xff,
+            (hi >>> 8) & 0xff,
+            (hi >>> 16) & 0xff,
+            hi >>> 24
+        ];
+    }
+    toBytesBE() {
+        const hi = this.high, lo = this.low;
+        return [
+            hi >>> 24,
+            (hi >>> 16) & 0xff,
+            (hi >>> 8) & 0xff,
+            hi & 0xff,
+            lo >>> 24,
+            (lo >>> 16) & 0xff,
+            (lo >>> 8) & 0xff,
+            lo & 0xff
+        ];
+    }
+    toSigned() {
+        if (!this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, false);
+    }
+    toString(radix) {
+        radix = radix || 10;
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        if (this.isZero())
+            return '0';
+        if (this.isNegative()) {
+            if (this.eq(Long.MIN_VALUE)) {
+                const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
+                return div.toString(radix) + rem1.toInt().toString(radix);
+            }
+            else
+                return '-' + this.neg().toString(radix);
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
+        let rem = this;
+        let result = '';
+        while (true) {
+            const remDiv = rem.div(radixToPower);
+            const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
+            let digits = intval.toString(radix);
+            rem = remDiv;
+            if (rem.isZero()) {
+                return digits + result;
+            }
+            else {
+                while (digits.length < 6)
+                    digits = '0' + digits;
+                result = '' + digits + result;
+            }
+        }
+    }
+    toUnsigned() {
+        if (this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, true);
+    }
+    xor(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
+    }
+    eqz() {
+        return this.isZero();
+    }
+    le(other) {
+        return this.lessThanOrEqual(other);
+    }
+    toExtendedJSON(options) {
+        if (options && options.relaxed)
+            return this.toNumber();
+        return { $numberLong: this.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        const { useBigInt64 = false, relaxed = true } = { ...options };
+        if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
+            throw new BSONError('$numberLong string is too long');
+        }
+        if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
+            throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
+        }
+        if (useBigInt64) {
+            const bigIntResult = BigInt(doc.$numberLong);
+            return BigInt.asIntN(64, bigIntResult);
+        }
+        const longResult = Long.fromString(doc.$numberLong);
+        if (relaxed) {
+            return longResult.toNumber();
+        }
+        return longResult;
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const longVal = inspect(this.toString(), options);
+        const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
+        return `new Long(${longVal}${unsignedVal})`;
+    }
+}
+
+const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
+const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
+const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
+const EXPONENT_MAX = 6111;
+const EXPONENT_MIN = -6176;
+const EXPONENT_BIAS = 6176;
+const MAX_DIGITS = 34;
+const NAN_BUFFER = ByteUtils.fromNumberArray([
+    0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
+    0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
+    0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
+const COMBINATION_MASK = 0x1f;
+const EXPONENT_MASK = 0x3fff;
+const COMBINATION_INFINITY = 30;
+const COMBINATION_NAN = 31;
+function isDigit(value) {
+    return !isNaN(parseInt(value, 10));
+}
+function divideu128(value) {
+    const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
+    let _rem = Long.fromNumber(0);
+    if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
+        return { quotient: value, rem: _rem };
+    }
+    for (let i = 0; i <= 3; i++) {
+        _rem = _rem.shiftLeft(32);
+        _rem = _rem.add(new Long(value.parts[i], 0));
+        value.parts[i] = _rem.div(DIVISOR).low;
+        _rem = _rem.modulo(DIVISOR);
+    }
+    return { quotient: value, rem: _rem };
+}
+function multiply64x2(left, right) {
+    if (!left && !right) {
+        return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
+    }
+    const leftHigh = left.shiftRightUnsigned(32);
+    const leftLow = new Long(left.getLowBits(), 0);
+    const rightHigh = right.shiftRightUnsigned(32);
+    const rightLow = new Long(right.getLowBits(), 0);
+    let productHigh = leftHigh.multiply(rightHigh);
+    let productMid = leftHigh.multiply(rightLow);
+    const productMid2 = leftLow.multiply(rightHigh);
+    let productLow = leftLow.multiply(rightLow);
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productMid = new Long(productMid.getLowBits(), 0)
+        .add(productMid2)
+        .add(productLow.shiftRightUnsigned(32));
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
+    return { high: productHigh, low: productLow };
+}
+function lessThan(left, right) {
+    const uhleft = left.high >>> 0;
+    const uhright = right.high >>> 0;
+    if (uhleft < uhright) {
+        return true;
+    }
+    else if (uhleft === uhright) {
+        const ulleft = left.low >>> 0;
+        const ulright = right.low >>> 0;
+        if (ulleft < ulright)
+            return true;
+    }
+    return false;
+}
+function invalidErr(string, message) {
+    throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
+}
+class Decimal128 extends BSONValue {
+    get _bsontype() {
+        return 'Decimal128';
+    }
+    bytes;
+    constructor(bytes) {
+        super();
+        if (typeof bytes === 'string') {
+            this.bytes = Decimal128.fromString(bytes).bytes;
+        }
+        else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
+            if (bytes.byteLength !== 16) {
+                throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
+            }
+            this.bytes = bytes;
+        }
+        else {
+            throw new BSONError('Decimal128 must take a Buffer or string');
+        }
+    }
+    static fromString(representation) {
+        return Decimal128._fromString(representation, { allowRounding: false });
+    }
+    static fromStringWithRounding(representation) {
+        return Decimal128._fromString(representation, { allowRounding: true });
+    }
+    static _fromString(representation, options) {
+        let isNegative = false;
+        let sawSign = false;
+        let sawRadix = false;
+        let foundNonZero = false;
+        let significantDigits = 0;
+        let nDigitsRead = 0;
+        let nDigits = 0;
+        let radixPosition = 0;
+        let firstNonZero = 0;
+        const digits = [0];
+        let nDigitsStored = 0;
+        let digitsInsert = 0;
+        let lastDigit = 0;
+        let exponent = 0;
+        let significandHigh = new Long(0, 0);
+        let significandLow = new Long(0, 0);
+        let biasedExponent = 0;
+        let index = 0;
+        if (representation.length >= 7000) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        const stringMatch = representation.match(PARSE_STRING_REGEXP);
+        const infMatch = representation.match(PARSE_INF_REGEXP);
+        const nanMatch = representation.match(PARSE_NAN_REGEXP);
+        if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        if (stringMatch) {
+            const unsignedNumber = stringMatch[2];
+            const e = stringMatch[4];
+            const expSign = stringMatch[5];
+            const expNumber = stringMatch[6];
+            if (e && expNumber === undefined)
+                invalidErr(representation, 'missing exponent power');
+            if (e && unsignedNumber === undefined)
+                invalidErr(representation, 'missing exponent base');
+            if (e === undefined && (expSign || expNumber)) {
+                invalidErr(representation, 'missing e before exponent');
+            }
+        }
+        if (representation[index] === '+' || representation[index] === '-') {
+            sawSign = true;
+            isNegative = representation[index++] === '-';
+        }
+        if (!isDigit(representation[index]) && representation[index] !== '.') {
+            if (representation[index] === 'i' || representation[index] === 'I') {
+                return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+            }
+            else if (representation[index] === 'N') {
+                return new Decimal128(NAN_BUFFER);
+            }
+        }
+        while (isDigit(representation[index]) || representation[index] === '.') {
+            if (representation[index] === '.') {
+                if (sawRadix)
+                    invalidErr(representation, 'contains multiple periods');
+                sawRadix = true;
+                index = index + 1;
+                continue;
+            }
+            if (nDigitsStored < MAX_DIGITS) {
+                if (representation[index] !== '0' || foundNonZero) {
+                    if (!foundNonZero) {
+                        firstNonZero = nDigitsRead;
+                    }
+                    foundNonZero = true;
+                    digits[digitsInsert++] = parseInt(representation[index], 10);
+                    nDigitsStored = nDigitsStored + 1;
+                }
+            }
+            if (foundNonZero)
+                nDigits = nDigits + 1;
+            if (sawRadix)
+                radixPosition = radixPosition + 1;
+            nDigitsRead = nDigitsRead + 1;
+            index = index + 1;
+        }
+        if (sawRadix && !nDigitsRead)
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        if (representation[index] === 'e' || representation[index] === 'E') {
+            const match = representation.substr(++index).match(EXPONENT_REGEX);
+            if (!match || !match[2])
+                return new Decimal128(NAN_BUFFER);
+            exponent = parseInt(match[0], 10);
+            index = index + match[0].length;
+        }
+        if (representation[index])
+            return new Decimal128(NAN_BUFFER);
+        if (!nDigitsStored) {
+            digits[0] = 0;
+            nDigits = 1;
+            nDigitsStored = 1;
+            significantDigits = 0;
+        }
+        else {
+            lastDigit = nDigitsStored - 1;
+            significantDigits = nDigits;
+            if (significantDigits !== 1) {
+                while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') {
+                    significantDigits = significantDigits - 1;
+                }
+            }
+        }
+        if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
+            exponent = EXPONENT_MIN;
+        }
+        else {
+            exponent = exponent - radixPosition;
+        }
+        while (exponent > EXPONENT_MAX) {
+            lastDigit = lastDigit + 1;
+            if (lastDigit >= MAX_DIGITS) {
+                if (significantDigits === 0) {
+                    exponent = EXPONENT_MAX;
+                    break;
+                }
+                invalidErr(representation, 'overflow');
+            }
+            exponent = exponent - 1;
+        }
+        if (options.allowRounding) {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0 && significantDigits < nDigitsStored) {
+                    exponent = EXPONENT_MIN;
+                    significantDigits = 0;
+                    break;
+                }
+                if (nDigitsStored < nDigits) {
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    const digitsString = digits.join('');
+                    if (digitsString.match(/^0+$/)) {
+                        exponent = EXPONENT_MAX;
+                        break;
+                    }
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                let endOfString = nDigitsRead;
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                let roundBit = 0;
+                if (roundDigit >= 5) {
+                    roundBit = 1;
+                    if (roundDigit === 5) {
+                        roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
+                        for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
+                            if (parseInt(representation[i], 10)) {
+                                roundBit = 1;
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (roundBit) {
+                    let dIdx = lastDigit;
+                    for (; dIdx >= 0; dIdx--) {
+                        if (++digits[dIdx] > 9) {
+                            digits[dIdx] = 0;
+                            if (dIdx === 0) {
+                                if (exponent < EXPONENT_MAX) {
+                                    exponent = exponent + 1;
+                                    digits[dIdx] = 1;
+                                }
+                                else {
+                                    return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+                                }
+                            }
+                        }
+                        else {
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        else {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0) {
+                    if (significantDigits === 0) {
+                        exponent = EXPONENT_MIN;
+                        break;
+                    }
+                    invalidErr(representation, 'exponent underflow');
+                }
+                if (nDigitsStored < nDigits) {
+                    if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
+                        significantDigits !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    if (digits[lastDigit] !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                if (roundDigit !== 0) {
+                    invalidErr(representation, 'inexact rounding');
+                }
+            }
+        }
+        significandHigh = Long.fromNumber(0);
+        significandLow = Long.fromNumber(0);
+        if (significantDigits === 0) {
+            significandHigh = Long.fromNumber(0);
+            significandLow = Long.fromNumber(0);
+        }
+        else if (lastDigit < 17) {
+            let dIdx = 0;
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            significandHigh = new Long(0, 0);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        else {
+            let dIdx = 0;
+            significandHigh = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit - 17; dIdx++) {
+                significandHigh = significandHigh.multiply(Long.fromNumber(10));
+                significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
+            }
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
+        significand.low = significand.low.add(significandLow);
+        if (lessThan(significand.low, significandLow)) {
+            significand.high = significand.high.add(Long.fromNumber(1));
+        }
+        biasedExponent = exponent + EXPONENT_BIAS;
+        const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
+        if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
+            dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
+        }
+        else {
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
+        }
+        dec.low = significand.low;
+        if (isNegative) {
+            dec.high = dec.high.or(Long.fromString('9223372036854775808'));
+        }
+        const buffer = ByteUtils.allocateUnsafe(16);
+        index = 0;
+        buffer[index++] = dec.low.low & 0xff;
+        buffer[index++] = (dec.low.low >> 8) & 0xff;
+        buffer[index++] = (dec.low.low >> 16) & 0xff;
+        buffer[index++] = (dec.low.low >> 24) & 0xff;
+        buffer[index++] = dec.low.high & 0xff;
+        buffer[index++] = (dec.low.high >> 8) & 0xff;
+        buffer[index++] = (dec.low.high >> 16) & 0xff;
+        buffer[index++] = (dec.low.high >> 24) & 0xff;
+        buffer[index++] = dec.high.low & 0xff;
+        buffer[index++] = (dec.high.low >> 8) & 0xff;
+        buffer[index++] = (dec.high.low >> 16) & 0xff;
+        buffer[index++] = (dec.high.low >> 24) & 0xff;
+        buffer[index++] = dec.high.high & 0xff;
+        buffer[index++] = (dec.high.high >> 8) & 0xff;
+        buffer[index++] = (dec.high.high >> 16) & 0xff;
+        buffer[index++] = (dec.high.high >> 24) & 0xff;
+        return new Decimal128(buffer);
+    }
+    toString() {
+        let biased_exponent;
+        let significand_digits = 0;
+        const significand = new Array(36);
+        for (let i = 0; i < significand.length; i++)
+            significand[i] = 0;
+        let index = 0;
+        let is_zero = false;
+        let significand_msb;
+        let significand128 = { parts: [0, 0, 0, 0] };
+        let j, k;
+        const string = [];
+        index = 0;
+        const buffer = this.bytes;
+        const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        index = 0;
+        const dec = {
+            low: new Long(low, midl),
+            high: new Long(midh, high)
+        };
+        if (dec.high.lessThan(Long.ZERO)) {
+            string.push('-');
+        }
+        const combination = (high >> 26) & COMBINATION_MASK;
+        if (combination >> 3 === 3) {
+            if (combination === COMBINATION_INFINITY) {
+                return string.join('') + 'Infinity';
+            }
+            else if (combination === COMBINATION_NAN) {
+                return 'NaN';
+            }
+            else {
+                biased_exponent = (high >> 15) & EXPONENT_MASK;
+                significand_msb = 0x08 + ((high >> 14) & 0x01);
+            }
+        }
+        else {
+            significand_msb = (high >> 14) & 0x07;
+            biased_exponent = (high >> 17) & EXPONENT_MASK;
+        }
+        const exponent = biased_exponent - EXPONENT_BIAS;
+        significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
+        significand128.parts[1] = midh;
+        significand128.parts[2] = midl;
+        significand128.parts[3] = low;
+        if (significand128.parts[0] === 0 &&
+            significand128.parts[1] === 0 &&
+            significand128.parts[2] === 0 &&
+            significand128.parts[3] === 0) {
+            is_zero = true;
+        }
+        else {
+            for (k = 3; k >= 0; k--) {
+                let least_digits = 0;
+                const result = divideu128(significand128);
+                significand128 = result.quotient;
+                least_digits = result.rem.low;
+                if (!least_digits)
+                    continue;
+                for (j = 8; j >= 0; j--) {
+                    significand[k * 9 + j] = least_digits % 10;
+                    least_digits = Math.floor(least_digits / 10);
+                }
+            }
+        }
+        if (is_zero) {
+            significand_digits = 1;
+            significand[index] = 0;
+        }
+        else {
+            significand_digits = 36;
+            while (!significand[index]) {
+                significand_digits = significand_digits - 1;
+                index = index + 1;
+            }
+        }
+        const scientific_exponent = significand_digits - 1 + exponent;
+        if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
+            if (significand_digits > 34) {
+                string.push(`${0}`);
+                if (exponent > 0)
+                    string.push(`E+${exponent}`);
+                else if (exponent < 0)
+                    string.push(`E${exponent}`);
+                return string.join('');
+            }
+            string.push(`${significand[index++]}`);
+            significand_digits = significand_digits - 1;
+            if (significand_digits) {
+                string.push('.');
+            }
+            for (let i = 0; i < significand_digits; i++) {
+                string.push(`${significand[index++]}`);
+            }
+            string.push('E');
+            if (scientific_exponent > 0) {
+                string.push(`+${scientific_exponent}`);
+            }
+            else {
+                string.push(`${scientific_exponent}`);
+            }
+        }
+        else {
+            if (exponent >= 0) {
+                for (let i = 0; i < significand_digits; i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+            else {
+                let radix_position = significand_digits + exponent;
+                if (radix_position > 0) {
+                    for (let i = 0; i < radix_position; i++) {
+                        string.push(`${significand[index++]}`);
+                    }
+                }
+                else {
+                    string.push('0');
+                }
+                string.push('.');
+                while (radix_position++ < 0) {
+                    string.push('0');
+                }
+                for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+        }
+        return string.join('');
+    }
+    toJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    toExtendedJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    static fromExtendedJSON(doc) {
+        return Decimal128.fromString(doc.$numberDecimal);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const d128string = inspect(this.toString(), options);
+        return `new Decimal128(${d128string})`;
+    }
+}
+
+class Double extends BSONValue {
+    get _bsontype() {
+        return 'Double';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value;
+    }
+    static fromString(value) {
+        const coercedValue = Number(value);
+        if (value === 'NaN')
+            return new Double(NaN);
+        if (value === 'Infinity')
+            return new Double(Infinity);
+        if (value === '-Infinity')
+            return new Double(-Infinity);
+        if (!Number.isFinite(coercedValue)) {
+            throw new BSONError(`Input: ${value} is not representable as a Double`);
+        }
+        if (value.trim() !== value) {
+            throw new BSONError(`Input: '${value}' contains whitespace`);
+        }
+        if (value === '') {
+            throw new BSONError(`Input is an empty string`);
+        }
+        if (/[^-0-9.+eE]/.test(value)) {
+            throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
+        }
+        return new Double(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toExtendedJSON(options) {
+        if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
+            return this.value;
+        }
+        if (Object.is(Math.sign(this.value), -0)) {
+            return { $numberDouble: '-0.0' };
+        }
+        return {
+            $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
+        };
+    }
+    static fromExtendedJSON(doc, options) {
+        const doubleValue = parseFloat(doc.$numberDouble);
+        return options && options.relaxed ? doubleValue : new Double(doubleValue);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Double(${inspect(this.value, options)})`;
+    }
+}
+
+class Int32 extends BSONValue {
+    get _bsontype() {
+        return 'Int32';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value | 0;
+    }
+    static fromString(value) {
+        const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
+        const coercedValue = Number(value);
+        if (BSON_INT32_MAX < coercedValue) {
+            throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
+        }
+        else if (BSON_INT32_MIN > coercedValue) {
+            throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
+        }
+        else if (!Number.isSafeInteger(coercedValue)) {
+            throw new BSONError(`Input: '${value}' is not a safe integer`);
+        }
+        else if (coercedValue.toString() !== cleanedValue) {
+            throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
+        }
+        return new Int32(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON(options) {
+        if (options && (options.relaxed || options.legacy))
+            return this.value;
+        return { $numberInt: this.value.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Int32(${inspect(this.value, options)})`;
+    }
+}
+
+class MaxKey extends BSONValue {
+    get _bsontype() {
+        return 'MaxKey';
+    }
+    toExtendedJSON() {
+        return { $maxKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MaxKey();
+    }
+    inspect() {
+        return 'new MaxKey()';
+    }
+}
+
+class MinKey extends BSONValue {
+    get _bsontype() {
+        return 'MinKey';
+    }
+    toExtendedJSON() {
+        return { $minKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MinKey();
+    }
+    inspect() {
+        return 'new MinKey()';
+    }
+}
+
+let PROCESS_UNIQUE = null;
+const __idCache = new WeakMap();
+class ObjectId extends BSONValue {
+    get _bsontype() {
+        return 'ObjectId';
+    }
+    static index = Math.floor(Math.random() * 0xffffff);
+    static cacheHexString;
+    buffer;
+    constructor(inputId) {
+        super();
+        let workingId;
+        if (typeof inputId === 'object' && inputId && 'id' in inputId) {
+            if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
+                throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
+            }
+            if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
+                workingId = ByteUtils.fromHex(inputId.toHexString());
+            }
+            else {
+                workingId = inputId.id;
+            }
+        }
+        else {
+            workingId = inputId;
+        }
+        if (workingId == null) {
+            this.buffer = ObjectId.generate();
+        }
+        else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
+            this.buffer = ByteUtils.toLocalBufferType(workingId);
+        }
+        else if (typeof workingId === 'string') {
+            if (ObjectId.validateHexString(workingId)) {
+                this.buffer = ByteUtils.fromHex(workingId);
+                if (ObjectId.cacheHexString) {
+                    __idCache.set(this, workingId);
+                }
+            }
+            else {
+                throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer');
+            }
+        }
+        else {
+            throw new BSONError('Argument passed in does not match the accepted types');
+        }
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, ByteUtils.toHex(value));
+        }
+    }
+    static validateHexString(string) {
+        if (string?.length !== 24)
+            return false;
+        for (let i = 0; i < 24; i++) {
+            const char = string.charCodeAt(i);
+            if ((char >= 48 && char <= 57) ||
+                (char >= 97 && char <= 102) ||
+                (char >= 65 && char <= 70)) {
+                continue;
+            }
+            return false;
+        }
+        return true;
+    }
+    toHexString() {
+        if (ObjectId.cacheHexString) {
+            const __id = __idCache.get(this);
+            if (__id)
+                return __id;
+        }
+        const hexString = ByteUtils.toHex(this.id);
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, hexString);
+        }
+        return hexString;
+    }
+    static getInc() {
+        return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
+    }
+    static generate(time) {
+        if ('number' !== typeof time) {
+            time = Math.floor(Date.now() / 1000);
+        }
+        const inc = ObjectId.getInc();
+        const buffer = ByteUtils.allocateUnsafe(12);
+        NumberUtils.setInt32BE(buffer, 0, time);
+        if (PROCESS_UNIQUE === null) {
+            PROCESS_UNIQUE = ByteUtils.randomBytes(5);
+        }
+        buffer[4] = PROCESS_UNIQUE[0];
+        buffer[5] = PROCESS_UNIQUE[1];
+        buffer[6] = PROCESS_UNIQUE[2];
+        buffer[7] = PROCESS_UNIQUE[3];
+        buffer[8] = PROCESS_UNIQUE[4];
+        buffer[11] = inc & 0xff;
+        buffer[10] = (inc >> 8) & 0xff;
+        buffer[9] = (inc >> 16) & 0xff;
+        return buffer;
+    }
+    toString(encoding) {
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        if (encoding === 'hex')
+            return this.toHexString();
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    static is(variable) {
+        return (variable != null &&
+            typeof variable === 'object' &&
+            '_bsontype' in variable &&
+            variable._bsontype === 'ObjectId');
+    }
+    equals(otherId) {
+        if (otherId === undefined || otherId === null) {
+            return false;
+        }
+        if (ObjectId.is(otherId)) {
+            return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer));
+        }
+        if (typeof otherId === 'string') {
+            return otherId.toLowerCase() === this.toHexString();
+        }
+        if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') {
+            const otherIdString = otherId.toHexString();
+            const thisIdString = this.toHexString();
+            return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
+        }
+        return false;
+    }
+    getTimestamp() {
+        const timestamp = new Date();
+        const time = NumberUtils.getUint32BE(this.buffer, 0);
+        timestamp.setTime(Math.floor(time) * 1000);
+        return timestamp;
+    }
+    static createPk() {
+        return new ObjectId();
+    }
+    serializeInto(uint8array, index) {
+        uint8array[index] = this.buffer[0];
+        uint8array[index + 1] = this.buffer[1];
+        uint8array[index + 2] = this.buffer[2];
+        uint8array[index + 3] = this.buffer[3];
+        uint8array[index + 4] = this.buffer[4];
+        uint8array[index + 5] = this.buffer[5];
+        uint8array[index + 6] = this.buffer[6];
+        uint8array[index + 7] = this.buffer[7];
+        uint8array[index + 8] = this.buffer[8];
+        uint8array[index + 9] = this.buffer[9];
+        uint8array[index + 10] = this.buffer[10];
+        uint8array[index + 11] = this.buffer[11];
+        return 12;
+    }
+    static createFromTime(time) {
+        const buffer = ByteUtils.allocate(12);
+        for (let i = 11; i >= 4; i--)
+            buffer[i] = 0;
+        NumberUtils.setInt32BE(buffer, 0, time);
+        return new ObjectId(buffer);
+    }
+    static createFromHexString(hexString) {
+        if (hexString?.length !== 24) {
+            throw new BSONError('hex string must be 24 characters');
+        }
+        return new ObjectId(ByteUtils.fromHex(hexString));
+    }
+    static createFromBase64(base64) {
+        if (base64?.length !== 16) {
+            throw new BSONError('base64 string must be 16 characters');
+        }
+        return new ObjectId(ByteUtils.fromBase64(base64));
+    }
+    static isValid(id) {
+        if (id == null)
+            return false;
+        if (typeof id === 'string')
+            return ObjectId.validateHexString(id);
+        try {
+            new ObjectId(id);
+            return true;
+        }
+        catch {
+            return false;
+        }
+    }
+    toExtendedJSON() {
+        if (this.toHexString)
+            return { $oid: this.toHexString() };
+        return { $oid: this.toString('hex') };
+    }
+    static fromExtendedJSON(doc) {
+        return new ObjectId(doc.$oid);
+    }
+    isCached() {
+        return ObjectId.cacheHexString && __idCache.has(this);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new ObjectId(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
+    let totalLength = 4 + 1;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+        }
+        for (const key of Object.keys(object)) {
+            totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
+        }
+    }
+    return totalLength;
+}
+function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
+    if (typeof value?.toBSON === 'function') {
+        value = value.toBSON();
+    }
+    switch (typeof value) {
+        case 'string':
+            return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
+        case 'number':
+            if (Math.floor(value) === value &&
+                value >= JS_INT_MIN &&
+                value <= JS_INT_MAX) {
+                if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
+                }
+                else {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+                }
+            }
+            else {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+        case 'undefined':
+            if (isArray || !ignoreUndefined)
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            return 0;
+        case 'boolean':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
+        case 'object':
+            if (value != null &&
+                typeof value._bsontype === 'string' &&
+                value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                throw new BSONVersionError();
+            }
+            else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            }
+            else if (value._bsontype === 'ObjectId') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
+            }
+            else if (value instanceof Date || isDate(value)) {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (ArrayBuffer.isView(value) ||
+                value instanceof ArrayBuffer ||
+                isAnyArrayBuffer(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength);
+            }
+            else if (value._bsontype === 'Long' ||
+                value._bsontype === 'Double' ||
+                value._bsontype === 'Timestamp') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (value._bsontype === 'Decimal128') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
+            }
+            else if (value._bsontype === 'Code') {
+                if (value.scope != null && Object.keys(value.scope).length > 0) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1 +
+                        internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1);
+                }
+            }
+            else if (value._bsontype === 'Binary') {
+                const binary = value;
+                if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        (binary.position + 1 + 4 + 1 + 4));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1));
+                }
+            }
+            else if (value._bsontype === 'Symbol') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    ByteUtils.utf8ByteLength(value.value) +
+                    4 +
+                    1 +
+                    1);
+            }
+            else if (value._bsontype === 'DBRef') {
+                const ordered_values = Object.assign({
+                    $ref: value.collection,
+                    $id: value.oid
+                }, value.fields);
+                if (value.db != null) {
+                    ordered_values['$db'] = value.db;
+                }
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
+            }
+            else if (value instanceof RegExp || isRegExp(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.source) +
+                    1 +
+                    (value.global ? 1 : 0) +
+                    (value.ignoreCase ? 1 : 0) +
+                    (value.multiline ? 1 : 0) +
+                    1);
+            }
+            else if (value._bsontype === 'BSONRegExp') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.pattern) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.options) +
+                    1);
+            }
+            else {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) +
+                    1);
+            }
+        case 'function':
+            if (serializeFunctions) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    4 +
+                    ByteUtils.utf8ByteLength(value.toString()) +
+                    1);
+            }
+            return 0;
+        case 'bigint':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+        case 'symbol':
+            return 0;
+        default:
+            throw new BSONError(`Unrecognized JS type: ${typeof value}`);
+    }
+}
+
+function alphabetize(str) {
+    return str.split('').sort().join('');
+}
+class BSONRegExp extends BSONValue {
+    get _bsontype() {
+        return 'BSONRegExp';
+    }
+    pattern;
+    options;
+    constructor(pattern, options) {
+        super();
+        this.pattern = pattern;
+        this.options = alphabetize(options ?? '');
+        if (this.pattern.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
+        }
+        if (this.options.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
+        }
+        for (let i = 0; i < this.options.length; i++) {
+            if (!(this.options[i] === 'i' ||
+                this.options[i] === 'm' ||
+                this.options[i] === 'x' ||
+                this.options[i] === 'l' ||
+                this.options[i] === 's' ||
+                this.options[i] === 'u')) {
+                throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
+            }
+        }
+    }
+    static parseOptions(options) {
+        return options ? options.split('').sort().join('') : '';
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (options.legacy) {
+            return { $regex: this.pattern, $options: this.options };
+        }
+        return { $regularExpression: { pattern: this.pattern, options: this.options } };
+    }
+    static fromExtendedJSON(doc) {
+        if ('$regex' in doc) {
+            if (typeof doc.$regex !== 'string') {
+                if (doc.$regex._bsontype === 'BSONRegExp') {
+                    return doc;
+                }
+            }
+            else {
+                return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
+            }
+        }
+        if ('$regularExpression' in doc) {
+            return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
+        }
+        throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
+    }
+    inspect(depth, options, inspect) {
+        const stylize = getStylizeFunction(options) ?? (v => v);
+        inspect ??= defaultInspect;
+        const pattern = stylize(inspect(this.pattern), 'regexp');
+        const flags = stylize(inspect(this.options), 'regexp');
+        return `new BSONRegExp(${pattern}, ${flags})`;
+    }
+}
+
+class BSONSymbol extends BSONValue {
+    get _bsontype() {
+        return 'BSONSymbol';
+    }
+    value;
+    constructor(value) {
+        super();
+        this.value = value;
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON() {
+        return { $symbol: this.value };
+    }
+    static fromExtendedJSON(doc) {
+        return new BSONSymbol(doc.$symbol);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new BSONSymbol(${inspect(this.value, options)})`;
+    }
+}
+
+const LongWithoutOverridesClass = Long;
+class Timestamp extends LongWithoutOverridesClass {
+    get _bsontype() {
+        return 'Timestamp';
+    }
+    get [bsonType]() {
+        return 'Timestamp';
+    }
+    static MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
+    get i() {
+        return this.low >>> 0;
+    }
+    get t() {
+        return this.high >>> 0;
+    }
+    constructor(low) {
+        if (low == null) {
+            super(0, 0, true);
+        }
+        else if (typeof low === 'bigint') {
+            super(low, true);
+        }
+        else if (Long.isLong(low)) {
+            super(low.low, low.high, true);
+        }
+        else if (typeof low === 'object' && 't' in low && 'i' in low) {
+            if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t as a number');
+            }
+            if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
+            }
+            const t = Number(low.t);
+            const i = Number(low.i);
+            if (t < 0 || Number.isNaN(t)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
+            }
+            if (i < 0 || Number.isNaN(i)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
+            }
+            if (t > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max');
+            }
+            if (i > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max');
+            }
+            super(i, t, true);
+        }
+        else {
+            throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }');
+        }
+    }
+    toJSON() {
+        return {
+            $timestamp: this.toString()
+        };
+    }
+    static fromInt(value) {
+        return new Timestamp(Long.fromInt(value, true));
+    }
+    static fromNumber(value) {
+        return new Timestamp(Long.fromNumber(value, true));
+    }
+    static fromBits(lowBits, highBits) {
+        return new Timestamp({ i: lowBits, t: highBits });
+    }
+    static fromString(str, optRadix) {
+        return new Timestamp(Long.fromString(str, true, optRadix));
+    }
+    toExtendedJSON() {
+        return { $timestamp: { t: this.t, i: this.i } };
+    }
+    static fromExtendedJSON(doc) {
+        const i = Long.isLong(doc.$timestamp.i)
+            ? doc.$timestamp.i.getLowBitsUnsigned()
+            : doc.$timestamp.i;
+        const t = Long.isLong(doc.$timestamp.t)
+            ? doc.$timestamp.t.getLowBitsUnsigned()
+            : doc.$timestamp.t;
+        return new Timestamp({ t, i });
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const t = inspect(this.t, options);
+        const i = inspect(this.i, options);
+        return `new Timestamp({ t: ${t}, i: ${i} })`;
+    }
+}
+
+const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
+const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
+function internalDeserialize(buffer, options, isArray) {
+    options = options == null ? {} : options;
+    const index = options && options.index ? options.index : 0;
+    const size = NumberUtils.getInt32LE(buffer, index);
+    if (size < 5) {
+        throw new BSONError(`bson size must be >= 5, is ${size}`);
+    }
+    if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
+        throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
+    }
+    if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
+        throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
+    }
+    if (size + index > buffer.byteLength) {
+        throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`);
+    }
+    if (buffer[index + size - 1] !== 0) {
+        throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
+    }
+    return deserializeObject(buffer, index, options, isArray);
+}
+const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
+function deserializeObject(buffer, index, options, isArray = false) {
+    const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
+    const raw = options['raw'] == null ? false : options['raw'];
+    const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
+    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');
+    }
+    const validation = options.validation == null ? { utf8: true } : options.validation;
+    let globalUTFValidation = true;
+    let validationSetting;
+    let utf8KeysSet;
+    const utf8ValidatedKeys = validation.utf8;
+    if (typeof utf8ValidatedKeys === 'boolean') {
+        validationSetting = utf8ValidatedKeys;
+    }
+    else {
+        globalUTFValidation = false;
+        const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
+            return utf8ValidatedKeys[key];
+        });
+        if (utf8ValidationValues.length === 0) {
+            throw new BSONError('UTF-8 validation setting cannot be empty');
+        }
+        if (typeof utf8ValidationValues[0] !== 'boolean') {
+            throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
+        }
+        validationSetting = utf8ValidationValues[0];
+        if (!utf8ValidationValues.every(item => item === validationSetting)) {
+            throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
+        }
+    }
+    if (!globalUTFValidation) {
+        utf8KeysSet = new Set();
+        for (const key of Object.keys(utf8ValidatedKeys)) {
+            utf8KeysSet.add(key);
+        }
+    }
+    const startIndex = index;
+    if (buffer.length < 5)
+        throw new BSONError('corrupt bson message < 5 bytes long');
+    const size = NumberUtils.getInt32LE(buffer, index);
+    index += 4;
+    if (size < 5 || size > buffer.length)
+        throw new BSONError('corrupt bson message');
+    const object = isArray ? [] : {};
+    let arrayIndex = 0;
+    let isPossibleDBRef = isArray ? false : null;
+    while (true) {
+        const elementType = buffer[index++];
+        if (elementType === 0)
+            break;
+        let i = index;
+        while (buffer[i] !== 0x00 && i < buffer.length) {
+            i++;
+        }
+        if (i >= buffer.byteLength)
+            throw new BSONError('Bad BSON Document: illegal CString');
+        const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false);
+        let shouldValidateKey = true;
+        if (globalUTFValidation || utf8KeysSet?.has(name)) {
+            shouldValidateKey = validationSetting;
+        }
+        else {
+            shouldValidateKey = !validationSetting;
+        }
+        if (isPossibleDBRef !== false && name[0] === '$') {
+            isPossibleDBRef = allowedDBRefKeys.test(name);
+        }
+        let value;
+        index = i + 1;
+        if (elementType === BSON_DATA_STRING) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_OID) {
+            const oid = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oid[i] = buffer[index + i];
+            value = new ObjectId(oid);
+            index = index + 12;
+        }
+        else if (elementType === BSON_DATA_INT && promoteValues === false) {
+            value = new Int32(NumberUtils.getInt32LE(buffer, index));
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_INT) {
+            value = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_NUMBER) {
+            value = NumberUtils.getFloat64LE(buffer, index);
+            index += 8;
+            if (promoteValues === false)
+                value = new Double(value);
+        }
+        else if (elementType === BSON_DATA_DATE) {
+            const lowBits = NumberUtils.getInt32LE(buffer, index);
+            const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+            index += 8;
+            value = new Date(new Long(lowBits, highBits).toNumber());
+        }
+        else if (elementType === BSON_DATA_BOOLEAN) {
+            if (buffer[index] !== 0 && buffer[index] !== 1)
+                throw new BSONError('illegal boolean type value');
+            value = buffer[index++] === 1;
+        }
+        else if (elementType === BSON_DATA_OBJECT) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            if (objectSize <= 0 || objectSize > buffer.length - index)
+                throw new BSONError('bad embedded document length in bson');
+            if (raw) {
+                value = buffer.subarray(index, index + objectSize);
+            }
+            else {
+                let objectOptions = options;
+                if (!globalUTFValidation) {
+                    objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
+                }
+                value = deserializeObject(buffer, _index, objectOptions, false);
+            }
+            index = index + objectSize;
+        }
+        else if (elementType === BSON_DATA_ARRAY) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            let arrayOptions = options;
+            const stopIndex = index + objectSize;
+            if (fieldsAsRaw && fieldsAsRaw[name]) {
+                arrayOptions = { ...options, raw: true };
+            }
+            if (!globalUTFValidation) {
+                arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
+            }
+            value = deserializeObject(buffer, _index, arrayOptions, true);
+            index = index + objectSize;
+            if (buffer[index - 1] !== 0)
+                throw new BSONError('invalid array terminator byte');
+            if (index !== stopIndex)
+                throw new BSONError('corrupted array bson');
+        }
+        else if (elementType === BSON_DATA_UNDEFINED) {
+            value = undefined;
+        }
+        else if (elementType === BSON_DATA_NULL) {
+            value = null;
+        }
+        else if (elementType === BSON_DATA_LONG) {
+            if (useBigInt64) {
+                value = NumberUtils.getBigInt64LE(buffer, index);
+                index += 8;
+            }
+            else {
+                const lowBits = NumberUtils.getInt32LE(buffer, index);
+                const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+                index += 8;
+                const long = new Long(lowBits, highBits);
+                if (promoteLongs && promoteValues === true) {
+                    value =
+                        long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
+                            ? long.toNumber()
+                            : long;
+                }
+                else {
+                    value = long;
+                }
+            }
+        }
+        else if (elementType === BSON_DATA_DECIMAL128) {
+            const bytes = ByteUtils.allocateUnsafe(16);
+            for (let i = 0; i < 16; i++)
+                bytes[i] = buffer[index + i];
+            index = index + 16;
+            value = new Decimal128(bytes);
+        }
+        else if (elementType === BSON_DATA_BINARY) {
+            let binarySize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            const totalBinarySize = binarySize;
+            const subType = buffer[index++];
+            if (binarySize < 0)
+                throw new BSONError('Negative binary type element size found');
+            if (binarySize > buffer.byteLength)
+                throw new BSONError('Binary type size larger than document size');
+            if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
+                binarySize = NumberUtils.getInt32LE(buffer, index);
+                index += 4;
+                if (binarySize < 0)
+                    throw new BSONError('Negative binary type element size found for subtype 0x02');
+                if (binarySize > totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
+                if (binarySize < totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
+            }
+            if (promoteBuffers && promoteValues) {
+                value = ByteUtils.toLocalBufferType(buffer.subarray(index, index + binarySize));
+            }
+            else {
+                value = new Binary(buffer.subarray(index, index + binarySize), subType);
+                if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
+                    value = value.toUUID();
+                }
+            }
+            index = index + binarySize;
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            const optionsArray = new Array(regExpOptions.length);
+            for (i = 0; i < regExpOptions.length; i++) {
+                switch (regExpOptions[i]) {
+                    case 'm':
+                        optionsArray[i] = 'm';
+                        break;
+                    case 's':
+                        optionsArray[i] = 'g';
+                        break;
+                    case 'i':
+                        optionsArray[i] = 'i';
+                        break;
+                }
+            }
+            value = new RegExp(source, optionsArray.join(''));
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            value = new BSONRegExp(source, regExpOptions);
+        }
+        else if (elementType === BSON_DATA_SYMBOL) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = promoteValues ? symbol : new BSONSymbol(symbol);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_TIMESTAMP) {
+            value = new Timestamp({
+                i: NumberUtils.getUint32LE(buffer, index),
+                t: NumberUtils.getUint32LE(buffer, index + 4)
+            });
+            index += 8;
+        }
+        else if (elementType === BSON_DATA_MIN_KEY) {
+            value = new MinKey();
+        }
+        else if (elementType === BSON_DATA_MAX_KEY) {
+            value = new MaxKey();
+        }
+        else if (elementType === BSON_DATA_CODE) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = new Code(functionString);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_CODE_W_SCOPE) {
+            const totalSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (totalSize < 4 + 4 + 4 + 1) {
+                throw new BSONError('code_w_scope total size shorter minimum expected length');
+            }
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            const scopeObject = deserializeObject(buffer, _index, options, false);
+            index = index + objectSize;
+            if (totalSize < 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too short, truncating scope');
+            }
+            if (totalSize > 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too long, clips outer document');
+            }
+            value = new Code(functionString, scopeObject);
+        }
+        else if (elementType === BSON_DATA_DBPOINTER) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0)
+                throw new BSONError('bad string length in bson');
+            const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const oidBuffer = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oidBuffer[i] = buffer[index + i];
+            const oid = new ObjectId(oidBuffer);
+            index = index + 12;
+            value = new DBRef(namespace, oid);
+        }
+        else {
+            throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
+        }
+        if (name === '__proto__') {
+            Object.defineProperty(object, name, {
+                value,
+                writable: true,
+                enumerable: true,
+                configurable: true
+            });
+        }
+        else {
+            object[name] = value;
+        }
+    }
+    if (size !== index - startIndex) {
+        if (isArray)
+            throw new BSONError('corrupt array bson');
+        throw new BSONError('corrupt object bson');
+    }
+    if (!isPossibleDBRef)
+        return object;
+    if (isDBRefLike(object)) {
+        const copy = Object.assign({}, object);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(object.$ref, object.$id, object.$db, copy);
+    }
+    return object;
+}
+
+const regexp = /\x00/;
+const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
+function serializeString(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_STRING;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes + 1;
+    buffer[index - 1] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
+    NumberUtils.setInt32LE(buffer, index, size + 1);
+    index = index + 4 + size;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeNumber(buffer, key, value, index) {
+    const isNegativeZero = Object.is(value, -0);
+    const type = !isNegativeZero &&
+        Number.isSafeInteger(value) &&
+        value <= BSON_INT32_MAX &&
+        value >= BSON_INT32_MIN
+        ? BSON_DATA_INT
+        : BSON_DATA_NUMBER;
+    buffer[index++] = type;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0x00;
+    if (type === BSON_DATA_INT) {
+        index += NumberUtils.setInt32LE(buffer, index, value);
+    }
+    else {
+        index += NumberUtils.setFloat64LE(buffer, index, value);
+    }
+    return index;
+}
+function serializeBigInt(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_LONG;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index += numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setBigInt64LE(buffer, index, value);
+    return index;
+}
+function serializeNull(buffer, key, _, index) {
+    buffer[index++] = BSON_DATA_NULL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeBoolean(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BOOLEAN;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    buffer[index++] = value ? 1 : 0;
+    return index;
+}
+function serializeDate(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DATE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const dateInMilis = Long.fromNumber(value.getTime());
+    const lowBits = dateInMilis.getLowBits();
+    const highBits = dateInMilis.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.source && value.source.match(regexp) != null) {
+        throw new BSONError('value ' + value.source + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
+    buffer[index++] = 0x00;
+    if (value.ignoreCase)
+        buffer[index++] = 0x69;
+    if (value.global)
+        buffer[index++] = 0x73;
+    if (value.multiline)
+        buffer[index++] = 0x6d;
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeBSONRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.pattern.match(regexp) != null) {
+        throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
+    buffer[index++] = 0x00;
+    const sortedOptions = value.options.split('').sort().join('');
+    index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeMinMax(buffer, key, value, index) {
+    if (value === null) {
+        buffer[index++] = BSON_DATA_NULL;
+    }
+    else if (value._bsontype === 'MinKey') {
+        buffer[index++] = BSON_DATA_MIN_KEY;
+    }
+    else {
+        buffer[index++] = BSON_DATA_MAX_KEY;
+    }
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeObjectId(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_OID;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += value.serializeInto(buffer, index);
+    return index;
+}
+function serializeBuffer(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = value.length;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = value[i];
+    }
+    else {
+        buffer.set(value, index);
+    }
+    index = index + size;
+    return index;
+}
+function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path.has(value)) {
+        throw new BSONError('Cannot convert circular structure to BSON');
+    }
+    path.add(value);
+    buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+    path.delete(value);
+    return endIndex;
+}
+function serializeDecimal128(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DECIMAL128;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    for (let i = 0; i < 16; i++)
+        buffer[index + i] = value.bytes[i];
+    return index + 16;
+}
+function serializeLong(buffer, key, value, index) {
+    buffer[index++] =
+        value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const lowBits = value.getLowBits();
+    const highBits = value.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeInt32(buffer, key, value, index) {
+    value = value.valueOf();
+    buffer[index++] = BSON_DATA_INT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setInt32LE(buffer, index, value);
+    return index;
+}
+function serializeDouble(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_NUMBER;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setFloat64LE(buffer, index, value.value);
+    return index;
+}
+function serializeFunction(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_CODE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const functionString = value.toString();
+    const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
+    if (value.scope && typeof value.scope === 'object') {
+        buffer[index++] = BSON_DATA_CODE_W_SCOPE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        let startIndex = index;
+        const functionString = value.code;
+        index = index + 4;
+        const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, codeSize);
+        buffer[index + 4 + codeSize - 1] = 0;
+        index = index + codeSize + 4;
+        const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+        index = endIndex - 1;
+        const totalSize = endIndex - startIndex;
+        startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize);
+        buffer[index++] = 0;
+    }
+    else {
+        buffer[index++] = BSON_DATA_CODE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        const functionString = value.code.toString();
+        const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, size);
+        index = index + 4 + size - 1;
+        buffer[index++] = 0;
+    }
+    return index;
+}
+function serializeBinary(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const data = value.buffer;
+    let size = value.position;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
+        size = size + 4;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = value.sub_type;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+        size = size - 4;
+        index += NumberUtils.setInt32LE(buffer, index, size);
+    }
+    if (value.sub_type === Binary.SUBTYPE_VECTOR) {
+        validateBinaryVector(value);
+    }
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = data[i];
+    }
+    else {
+        buffer.set(data, index);
+    }
+    index = index + value.position;
+    return index;
+}
+function serializeSymbol(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_SYMBOL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) {
+    buffer[index++] = BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    let startIndex = index;
+    let output = {
+        $ref: value.collection || value.namespace,
+        $id: value.oid
+    };
+    if (value.db != null) {
+        output.$db = value.db;
+    }
+    output = Object.assign(output, value.fields);
+    const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path);
+    const size = endIndex - startIndex;
+    startIndex += NumberUtils.setInt32LE(buffer, index, size);
+    return endIndex;
+}
+function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path == null) {
+        if (object == null) {
+            buffer[0] = 0x05;
+            buffer[1] = 0x00;
+            buffer[2] = 0x00;
+            buffer[3] = 0x00;
+            buffer[4] = 0x00;
+            return 5;
+        }
+        if (Array.isArray(object)) {
+            throw new BSONError('serialize does not support an array as the root input');
+        }
+        if (typeof object !== 'object') {
+            throw new BSONError('serialize does not support non-object as the root input');
+        }
+        else if ('_bsontype' in object && typeof object._bsontype === 'string') {
+            throw new BSONError(`BSON types cannot be serialized as a document`);
+        }
+        else if (isDate(object) ||
+            isRegExp(object) ||
+            isUint8Array(object) ||
+            isAnyArrayBuffer(object)) {
+            throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
+        }
+        path = new Set();
+    }
+    path.add(object);
+    let index = startingIndex + 4;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            const key = `${i}`;
+            let value = object[i];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (value === undefined) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else if (object instanceof Map || isMap(object)) {
+        const iterator = object.entries();
+        let done = false;
+        while (!done) {
+            const entry = iterator.next();
+            done = !!entry.done;
+            if (done)
+                continue;
+            const key = entry.value ? entry.value[0] : undefined;
+            let value = entry.value ? entry.value[1] : undefined;
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+            if (object != null && typeof object !== 'object') {
+                throw new BSONError('toBSON function did not return an object');
+            }
+        }
+        for (const key of Object.keys(object)) {
+            let value = object[key];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    path.delete(object);
+    buffer[index++] = 0x00;
+    const size = index - startingIndex;
+    startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size);
+    return index;
+}
+
+function isBSONType(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '_bsontype' in value &&
+        typeof value._bsontype === 'string');
+}
+const keysToCodecs = {
+    $oid: ObjectId,
+    $binary: Binary,
+    $uuid: Binary,
+    $symbol: BSONSymbol,
+    $numberInt: Int32,
+    $numberDecimal: Decimal128,
+    $numberDouble: Double,
+    $numberLong: Long,
+    $minKey: MinKey,
+    $maxKey: MaxKey,
+    $regex: BSONRegExp,
+    $regularExpression: BSONRegExp,
+    $timestamp: Timestamp
+};
+function deserializeValue(value, options = {}) {
+    if (typeof value === 'number') {
+        const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
+        const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
+        if (options.relaxed || options.legacy) {
+            return value;
+        }
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (in32BitRange) {
+                return new Int32(value);
+            }
+            if (in64BitRange) {
+                if (options.useBigInt64) {
+                    return BigInt(value);
+                }
+                return Long.fromNumber(value);
+            }
+        }
+        return new Double(value);
+    }
+    if (value == null || typeof value !== 'object')
+        return value;
+    if (value.$undefined)
+        return null;
+    const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null);
+    for (let i = 0; i < keys.length; i++) {
+        const c = keysToCodecs[keys[i]];
+        if (c)
+            return c.fromExtendedJSON(value, options);
+    }
+    if (value.$date != null) {
+        const d = value.$date;
+        const date = new Date();
+        if (options.legacy) {
+            if (typeof d === 'number')
+                date.setTime(d);
+            else if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        else {
+            if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (Long.isLong(d))
+                date.setTime(d.toNumber());
+            else if (typeof d === 'number' && options.relaxed)
+                date.setTime(d);
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        return date;
+    }
+    if (value.$code != null) {
+        const copy = Object.assign({}, value);
+        if (value.$scope) {
+            copy.$scope = deserializeValue(value.$scope);
+        }
+        return Code.fromExtendedJSON(value);
+    }
+    if (isDBRefLike(value) || value.$dbPointer) {
+        const v = value.$ref ? value : value.$dbPointer;
+        if (v instanceof DBRef)
+            return v;
+        const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
+        let valid = true;
+        dollarKeys.forEach(k => {
+            if (['$ref', '$id', '$db'].indexOf(k) === -1)
+                valid = false;
+        });
+        if (valid)
+            return DBRef.fromExtendedJSON(v);
+    }
+    return value;
+}
+function serializeArray(array, options) {
+    return array.map((v, index) => {
+        options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
+        try {
+            return serializeValue(v, options);
+        }
+        finally {
+            options.seenObjects.pop();
+        }
+    });
+}
+function getISOString(date) {
+    const isoStr = date.toISOString();
+    return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
+}
+function serializeValue(value, options) {
+    if (value instanceof Map || isMap(value)) {
+        const obj = Object.create(null);
+        for (const [k, v] of value) {
+            if (typeof k !== 'string') {
+                throw new BSONError('Can only serialize maps with string keys');
+            }
+            obj[k] = v;
+        }
+        return serializeValue(obj, options);
+    }
+    if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
+        const index = options.seenObjects.findIndex(entry => entry.obj === value);
+        if (index !== -1) {
+            const props = options.seenObjects.map(entry => entry.propertyName);
+            const leadingPart = props
+                .slice(0, index)
+                .map(prop => `${prop} -> `)
+                .join('');
+            const alreadySeen = props[index];
+            const circularPart = ' -> ' +
+                props
+                    .slice(index + 1, props.length - 1)
+                    .map(prop => `${prop} -> `)
+                    .join('');
+            const current = props[props.length - 1];
+            const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
+            const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
+            throw new BSONError('Converting circular structure to EJSON:\n' +
+                `    ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
+                `    ${leadingSpace}\\${dashes}/`);
+        }
+        options.seenObjects[options.seenObjects.length - 1].obj = value;
+    }
+    if (Array.isArray(value))
+        return serializeArray(value, options);
+    if (value === undefined)
+        return null;
+    if (value instanceof Date || isDate(value)) {
+        const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000;
+        if (options.legacy) {
+            return options.relaxed && inRange
+                ? { $date: value.getTime() }
+                : { $date: getISOString(value) };
+        }
+        return options.relaxed && inRange
+            ? { $date: getISOString(value) }
+            : { $date: { $numberLong: value.getTime().toString() } };
+    }
+    if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                return { $numberInt: value.toString() };
+            }
+            if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
+                return { $numberLong: value.toString() };
+            }
+        }
+        return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
+    }
+    if (typeof value === 'bigint') {
+        if (!options.relaxed) {
+            return { $numberLong: BigInt.asIntN(64, value).toString() };
+        }
+        return Number(BigInt.asIntN(64, value));
+    }
+    if (value instanceof RegExp || isRegExp(value)) {
+        let flags = value.flags;
+        if (flags === undefined) {
+            const match = value.toString().match(/[gimuy]*$/);
+            if (match) {
+                flags = match[0];
+            }
+        }
+        const rx = new BSONRegExp(value.source, flags);
+        return rx.toExtendedJSON(options);
+    }
+    if (value != null && typeof value === 'object')
+        return serializeDocument(value, options);
+    return value;
+}
+const BSON_TYPE_MAPPINGS = {
+    Binary: (o) => new Binary(o.value(), o.sub_type),
+    Code: (o) => new Code(o.code, o.scope),
+    DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
+    Decimal128: (o) => new Decimal128(o.bytes),
+    Double: (o) => new Double(o.value),
+    Int32: (o) => new Int32(o.value),
+    Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_),
+    MaxKey: () => new MaxKey(),
+    MinKey: () => new MinKey(),
+    ObjectId: (o) => new ObjectId(o),
+    BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
+    BSONSymbol: (o) => new BSONSymbol(o.value),
+    Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
+};
+function serializeDocument(doc, options) {
+    if (doc == null || typeof doc !== 'object')
+        throw new BSONError('not an object instance');
+    const bsontype = doc._bsontype;
+    if (typeof bsontype === 'undefined') {
+        const _doc = {};
+        for (const name of Object.keys(doc)) {
+            options.seenObjects.push({ propertyName: name, obj: null });
+            try {
+                const value = serializeValue(doc[name], options);
+                if (name === '__proto__') {
+                    Object.defineProperty(_doc, name, {
+                        value,
+                        writable: true,
+                        enumerable: true,
+                        configurable: true
+                    });
+                }
+                else {
+                    _doc[name] = value;
+                }
+            }
+            finally {
+                options.seenObjects.pop();
+            }
+        }
+        return _doc;
+    }
+    else if (doc != null &&
+        typeof doc === 'object' &&
+        typeof doc._bsontype === 'string' &&
+        doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+        throw new BSONVersionError();
+    }
+    else if (isBSONType(doc)) {
+        let outDoc = doc;
+        if (typeof outDoc.toExtendedJSON !== 'function') {
+            const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
+            if (!mapper) {
+                throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
+            }
+            outDoc = mapper(outDoc);
+        }
+        if (bsontype === 'Code' && outDoc.scope) {
+            outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
+        }
+        else if (bsontype === 'DBRef' && outDoc.oid) {
+            outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
+        }
+        return outDoc.toExtendedJSON(options);
+    }
+    else {
+        throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
+    }
+}
+function parse(text, options) {
+    const ejsonOptions = {
+        useBigInt64: options?.useBigInt64 ?? false,
+        relaxed: options?.relaxed ?? true,
+        legacy: options?.legacy ?? false
+    };
+    return JSON.parse(text, (key, value) => {
+        if (key.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
+        }
+        return deserializeValue(value, ejsonOptions);
+    });
+}
+function stringify(value, replacer, space, options) {
+    if (space != null && typeof space === 'object') {
+        options = space;
+        space = 0;
+    }
+    if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
+        options = replacer;
+        replacer = undefined;
+        space = 0;
+    }
+    const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
+        seenObjects: [{ propertyName: '(root)', obj: null }]
+    });
+    const doc = serializeValue(value, serializeOptions);
+    return JSON.stringify(doc, replacer, space);
+}
+function EJSONserialize(value, options) {
+    options = options || {};
+    return JSON.parse(stringify(value, options));
+}
+function EJSONdeserialize(ejson, options) {
+    options = options || {};
+    return parse(JSON.stringify(ejson), options);
+}
+const EJSON = Object.create(null);
+EJSON.parse = parse;
+EJSON.stringify = stringify;
+EJSON.serialize = EJSONserialize;
+EJSON.deserialize = EJSONdeserialize;
+Object.freeze(EJSON);
+
+const BSONElementType = {
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: 255,
+    maxKey: 127
+};
+function getSize(source, offset) {
+    try {
+        return NumberUtils.getNonnegativeInt32LE(source, offset);
+    }
+    catch (cause) {
+        throw new BSONOffsetError('BSON size cannot be negative', offset, { cause });
+    }
+}
+function findNull(bytes, offset) {
+    let nullTerminatorOffset = offset;
+    for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++)
+        ;
+    if (nullTerminatorOffset === bytes.length - 1) {
+        throw new BSONOffsetError('Null terminator not found', offset);
+    }
+    return nullTerminatorOffset;
+}
+function parseToElements(bytes, startOffset = 0) {
+    startOffset ??= 0;
+    if (bytes.length < 5) {
+        throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
+    }
+    const documentSize = getSize(bytes, startOffset);
+    if (documentSize > bytes.length - startOffset) {
+        throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
+    }
+    if (bytes[startOffset + documentSize - 1] !== 0x00) {
+        throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize);
+    }
+    const elements = [];
+    let offset = startOffset + 4;
+    while (offset <= documentSize + startOffset) {
+        const type = bytes[offset];
+        offset += 1;
+        if (type === 0) {
+            if (offset - startOffset !== documentSize) {
+                throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
+            }
+            break;
+        }
+        const nameOffset = offset;
+        const nameLength = findNull(bytes, offset) - nameOffset;
+        offset += nameLength + 1;
+        let length;
+        if (type === BSONElementType.double ||
+            type === BSONElementType.long ||
+            type === BSONElementType.date ||
+            type === BSONElementType.timestamp) {
+            length = 8;
+        }
+        else if (type === BSONElementType.int) {
+            length = 4;
+        }
+        else if (type === BSONElementType.objectId) {
+            length = 12;
+        }
+        else if (type === BSONElementType.decimal) {
+            length = 16;
+        }
+        else if (type === BSONElementType.bool) {
+            length = 1;
+        }
+        else if (type === BSONElementType.null ||
+            type === BSONElementType.undefined ||
+            type === BSONElementType.maxKey ||
+            type === BSONElementType.minKey) {
+            length = 0;
+        }
+        else if (type === BSONElementType.regex) {
+            length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
+        }
+        else if (type === BSONElementType.object ||
+            type === BSONElementType.array ||
+            type === BSONElementType.javascriptWithScope) {
+            length = getSize(bytes, offset);
+        }
+        else if (type === BSONElementType.string ||
+            type === BSONElementType.binData ||
+            type === BSONElementType.dbPointer ||
+            type === BSONElementType.javascript ||
+            type === BSONElementType.symbol) {
+            length = getSize(bytes, offset) + 4;
+            if (type === BSONElementType.binData) {
+                length += 1;
+            }
+            if (type === BSONElementType.dbPointer) {
+                length += 12;
+            }
+        }
+        else {
+            throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset);
+        }
+        if (length > documentSize) {
+            throw new BSONOffsetError('value reports length larger than document', offset);
+        }
+        elements.push([type, nameOffset, nameLength, offset, length]);
+        offset += length;
+    }
+    return elements;
+}
+
+const onDemand = Object.create(null);
+onDemand.parseToElements = parseToElements;
+onDemand.ByteUtils = ByteUtils;
+onDemand.NumberUtils = NumberUtils;
+Object.freeze(onDemand);
+
+const MAXSIZE = 1024 * 1024 * 17;
+let buffer = ByteUtils.allocate(MAXSIZE);
+function setInternalBufferSize(size) {
+    if (buffer.length < size) {
+        buffer = ByteUtils.allocate(size);
+    }
+}
+function serialize(object, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
+    if (buffer.length < minInternalBufferSize) {
+        buffer = ByteUtils.allocate(minInternalBufferSize);
+    }
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex);
+    finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
+    return finishedBuffer;
+}
+function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const startIndex = typeof options.index === 'number' ? options.index : 0;
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
+    return startIndex + serializationIndex - 1;
+}
+function deserialize(buffer, options = {}) {
+    return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
+}
+function calculateObjectSize(object, options = {}) {
+    options = options || {};
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
+}
+function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
+    const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
+    const bufferData = ByteUtils.toLocalBufferType(data);
+    let index = startIndex;
+    for (let i = 0; i < numberOfDocuments; i++) {
+        const size = NumberUtils.getInt32LE(bufferData, index);
+        internalOptions.index = index;
+        documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
+        index = index + size;
+    }
+    return index;
+}
+
+var bson = /*#__PURE__*/Object.freeze({
+    __proto__: null,
+    BSONError: BSONError,
+    BSONOffsetError: BSONOffsetError,
+    BSONRegExp: BSONRegExp,
+    BSONRuntimeError: BSONRuntimeError,
+    BSONSymbol: BSONSymbol,
+    BSONType: BSONType,
+    BSONValue: BSONValue,
+    BSONVersionError: BSONVersionError,
+    Binary: Binary,
+    Code: Code,
+    DBRef: DBRef,
+    Decimal128: Decimal128,
+    Double: Double,
+    EJSON: EJSON,
+    Int32: Int32,
+    Long: Long,
+    MaxKey: MaxKey,
+    MinKey: MinKey,
+    ObjectId: ObjectId,
+    Timestamp: Timestamp,
+    UUID: UUID,
+    bsonType: bsonType,
+    calculateObjectSize: calculateObjectSize,
+    deserialize: deserialize,
+    deserializeStream: deserializeStream,
+    onDemand: onDemand,
+    serialize: serialize,
+    serializeWithBufferAndIndex: serializeWithBufferAndIndex,
+    setInternalBufferSize: setInternalBufferSize
+});
+
+export { bson as BSON, BSONError, BSONOffsetError, BSONRegExp, BSONRuntimeError, BSONSymbol, BSONType, BSONValue, BSONVersionError, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, MaxKey, MinKey, ObjectId, Timestamp, UUID, bsonType, calculateObjectSize, deserialize, deserializeStream, onDemand, serialize, serializeWithBufferAndIndex, setInternalBufferSize };
+//# sourceMappingURL=bson.mjs.map

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
node_modules/bson/lib/bson.mjs.map


+ 4639 - 0
node_modules/bson/lib/bson.node.mjs

@@ -0,0 +1,4639 @@
+const TypedArrayPrototypeGetSymbolToStringTag = (() => {
+    const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
+    return (value) => g.call(value);
+})();
+function isUint8Array(value) {
+    return TypedArrayPrototypeGetSymbolToStringTag(value) === 'Uint8Array';
+}
+function isAnyArrayBuffer(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        (value[Symbol.toStringTag] === 'ArrayBuffer' ||
+            value[Symbol.toStringTag] === 'SharedArrayBuffer'));
+}
+function isRegExp(regexp) {
+    return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === '[object RegExp]';
+}
+function isMap(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        value[Symbol.toStringTag] === 'Map');
+}
+function isDate(date) {
+    return date instanceof Date || Object.prototype.toString.call(date) === '[object Date]';
+}
+function defaultInspect(x, _options) {
+    return JSON.stringify(x, (k, v) => {
+        if (typeof v === 'bigint') {
+            return { $numberLong: `${v}` };
+        }
+        else if (isMap(v)) {
+            return Object.fromEntries(v);
+        }
+        return v;
+    });
+}
+function getStylizeFunction(options) {
+    const stylizeExists = options != null &&
+        typeof options === 'object' &&
+        'stylize' in options &&
+        typeof options.stylize === 'function';
+    if (stylizeExists) {
+        return options.stylize;
+    }
+}
+
+const BSON_MAJOR_VERSION = 7;
+const BSON_VERSION_SYMBOL = Symbol.for('@@mdb.bson.version');
+const BSON_INT32_MAX = 0x7fffffff;
+const BSON_INT32_MIN = -2147483648;
+const BSON_INT64_MAX = Math.pow(2, 63) - 1;
+const BSON_INT64_MIN = -Math.pow(2, 63);
+const JS_INT_MAX = Math.pow(2, 53);
+const JS_INT_MIN = -Math.pow(2, 53);
+const BSON_DATA_NUMBER = 1;
+const BSON_DATA_STRING = 2;
+const BSON_DATA_OBJECT = 3;
+const BSON_DATA_ARRAY = 4;
+const BSON_DATA_BINARY = 5;
+const BSON_DATA_UNDEFINED = 6;
+const BSON_DATA_OID = 7;
+const BSON_DATA_BOOLEAN = 8;
+const BSON_DATA_DATE = 9;
+const BSON_DATA_NULL = 10;
+const BSON_DATA_REGEXP = 11;
+const BSON_DATA_DBPOINTER = 12;
+const BSON_DATA_CODE = 13;
+const BSON_DATA_SYMBOL = 14;
+const BSON_DATA_CODE_W_SCOPE = 15;
+const BSON_DATA_INT = 16;
+const BSON_DATA_TIMESTAMP = 17;
+const BSON_DATA_LONG = 18;
+const BSON_DATA_DECIMAL128 = 19;
+const BSON_DATA_MIN_KEY = 0xff;
+const BSON_DATA_MAX_KEY = 0x7f;
+const BSON_BINARY_SUBTYPE_DEFAULT = 0;
+const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
+const BSONType = Object.freeze({
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: -1,
+    maxKey: 127
+});
+
+class BSONError extends Error {
+    get bsonError() {
+        return true;
+    }
+    get name() {
+        return 'BSONError';
+    }
+    constructor(message, options) {
+        super(message, options);
+    }
+    static isBSONError(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            'bsonError' in value &&
+            value.bsonError === true &&
+            'name' in value &&
+            'message' in value &&
+            'stack' in value);
+    }
+}
+class BSONVersionError extends BSONError {
+    get name() {
+        return 'BSONVersionError';
+    }
+    constructor() {
+        super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
+    }
+}
+class BSONRuntimeError extends BSONError {
+    get name() {
+        return 'BSONRuntimeError';
+    }
+    constructor(message) {
+        super(message);
+    }
+}
+class BSONOffsetError extends BSONError {
+    get name() {
+        return 'BSONOffsetError';
+    }
+    offset;
+    constructor(message, offset, options) {
+        super(`${message}. offset: ${offset}`, options);
+        this.offset = offset;
+    }
+}
+
+let TextDecoderFatal;
+let TextDecoderNonFatal;
+function parseUtf8(buffer, start, end, fatal) {
+    if (fatal) {
+        TextDecoderFatal ??= new TextDecoder('utf8', { fatal: true });
+        try {
+            return TextDecoderFatal.decode(buffer.subarray(start, end));
+        }
+        catch (cause) {
+            throw new BSONError('Invalid UTF-8 string in BSON document', { cause });
+        }
+    }
+    TextDecoderNonFatal ??= new TextDecoder('utf8', { fatal: false });
+    return TextDecoderNonFatal.decode(buffer.subarray(start, end));
+}
+
+function tryReadBasicLatin(uint8array, start, end) {
+    if (uint8array.length === 0) {
+        return '';
+    }
+    const stringByteLength = end - start;
+    if (stringByteLength === 0) {
+        return '';
+    }
+    if (stringByteLength > 20) {
+        return null;
+    }
+    if (stringByteLength === 1 && uint8array[start] < 128) {
+        return String.fromCharCode(uint8array[start]);
+    }
+    if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
+        return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
+    }
+    if (stringByteLength === 3 &&
+        uint8array[start] < 128 &&
+        uint8array[start + 1] < 128 &&
+        uint8array[start + 2] < 128) {
+        return (String.fromCharCode(uint8array[start]) +
+            String.fromCharCode(uint8array[start + 1]) +
+            String.fromCharCode(uint8array[start + 2]));
+    }
+    const latinBytes = [];
+    for (let i = start; i < end; i++) {
+        const byte = uint8array[i];
+        if (byte > 127) {
+            return null;
+        }
+        latinBytes.push(byte);
+    }
+    return String.fromCharCode(...latinBytes);
+}
+function tryWriteBasicLatin(destination, source, offset) {
+    if (source.length === 0)
+        return 0;
+    if (source.length > 25)
+        return null;
+    if (destination.length - offset < source.length)
+        return null;
+    for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
+        const char = source.charCodeAt(charOffset);
+        if (char > 127)
+            return null;
+        destination[destinationOffset] = char;
+    }
+    return source.length;
+}
+
+function nodejsMathRandomBytes(byteLength) {
+    return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+function nodejsSecureRandomBytes(byteLength) {
+    return crypto.getRandomValues(nodeJsByteUtils.allocate(byteLength));
+}
+const nodejsRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return nodejsSecureRandomBytes;
+    }
+    else {
+        return nodejsMathRandomBytes;
+    }
+})();
+const nodeJsByteUtils = {
+    toLocalBufferType(potentialBuffer) {
+        if (Buffer.isBuffer(potentialBuffer)) {
+            return potentialBuffer;
+        }
+        if (ArrayBuffer.isView(potentialBuffer)) {
+            return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
+        }
+        const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return Buffer.from(potentialBuffer);
+        }
+        throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);
+    },
+    allocate(size) {
+        return Buffer.alloc(size);
+    },
+    allocateUnsafe(size) {
+        return Buffer.allocUnsafe(size);
+    },
+    equals(a, b) {
+        return nodeJsByteUtils.toLocalBufferType(a).equals(b);
+    },
+    fromNumberArray(array) {
+        return Buffer.from(array);
+    },
+    fromBase64(base64) {
+        return Buffer.from(base64, 'base64');
+    },
+    toBase64(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');
+    },
+    fromISO88591(codePoints) {
+        return Buffer.from(codePoints, 'binary');
+    },
+    toISO88591(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');
+    },
+    fromHex(hex) {
+        return Buffer.from(hex, 'hex');
+    },
+    toHex(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');
+    },
+    toUTF8(buffer, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
+        if (fatal) {
+            for (let i = 0; i < string.length; i++) {
+                if (string.charCodeAt(i) === 0xfffd) {
+                    parseUtf8(buffer, start, end, true);
+                    break;
+                }
+            }
+        }
+        return string;
+    },
+    utf8ByteLength(input) {
+        return Buffer.byteLength(input, 'utf8');
+    },
+    encodeUTF8Into(buffer, source, byteOffset) {
+        const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset);
+        if (latinBytesWritten != null) {
+            return latinBytesWritten;
+        }
+        return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
+    },
+    randomBytes: nodejsRandomBytes,
+    swap32(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).swap32();
+    }
+};
+
+function isReactNative() {
+    const { navigator } = globalThis;
+    return typeof navigator === 'object' && navigator.product === 'ReactNative';
+}
+function webMathRandomBytes(byteLength) {
+    if (byteLength < 0) {
+        throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
+    }
+    return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+const webRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return (byteLength) => {
+            return crypto.getRandomValues(webByteUtils.allocate(byteLength));
+        };
+    }
+    else {
+        if (isReactNative()) {
+            const { console } = globalThis;
+            console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');
+        }
+        return webMathRandomBytes;
+    }
+})();
+const HEX_DIGIT = /(\d|[a-f])/i;
+const webByteUtils = {
+    toLocalBufferType(potentialUint8array) {
+        const stringTag = potentialUint8array?.[Symbol.toStringTag] ??
+            Object.prototype.toString.call(potentialUint8array);
+        if (stringTag === 'Uint8Array') {
+            return potentialUint8array;
+        }
+        if (ArrayBuffer.isView(potentialUint8array)) {
+            return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
+        }
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return new Uint8Array(potentialUint8array);
+        }
+        throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);
+    },
+    allocate(size) {
+        if (typeof size !== 'number') {
+            throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
+        }
+        return new Uint8Array(size);
+    },
+    allocateUnsafe(size) {
+        return webByteUtils.allocate(size);
+    },
+    equals(a, b) {
+        if (a.byteLength !== b.byteLength) {
+            return false;
+        }
+        for (let i = 0; i < a.byteLength; i++) {
+            if (a[i] !== b[i]) {
+                return false;
+            }
+        }
+        return true;
+    },
+    fromNumberArray(array) {
+        return Uint8Array.from(array);
+    },
+    fromBase64(base64) {
+        return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
+    },
+    toBase64(uint8array) {
+        return btoa(webByteUtils.toISO88591(uint8array));
+    },
+    fromISO88591(codePoints) {
+        return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);
+    },
+    toISO88591(uint8array) {
+        return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');
+    },
+    fromHex(hex) {
+        const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
+        const buffer = [];
+        for (let i = 0; i < evenLengthHex.length; i += 2) {
+            const firstDigit = evenLengthHex[i];
+            const secondDigit = evenLengthHex[i + 1];
+            if (!HEX_DIGIT.test(firstDigit)) {
+                break;
+            }
+            if (!HEX_DIGIT.test(secondDigit)) {
+                break;
+            }
+            const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
+            buffer.push(hexDigit);
+        }
+        return Uint8Array.from(buffer);
+    },
+    toHex(uint8array) {
+        return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
+    },
+    toUTF8(uint8array, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        return parseUtf8(uint8array, start, end, fatal);
+    },
+    utf8ByteLength(input) {
+        return new TextEncoder().encode(input).byteLength;
+    },
+    encodeUTF8Into(uint8array, source, byteOffset) {
+        const bytes = new TextEncoder().encode(source);
+        uint8array.set(bytes, byteOffset);
+        return bytes.byteLength;
+    },
+    randomBytes: webRandomBytes,
+    swap32(buffer) {
+        if (buffer.length % 4 !== 0) {
+            throw new RangeError('Buffer size must be a multiple of 32-bits');
+        }
+        for (let i = 0; i < buffer.length; i += 4) {
+            const byte0 = buffer[i];
+            const byte1 = buffer[i + 1];
+            const byte2 = buffer[i + 2];
+            const byte3 = buffer[i + 3];
+            buffer[i] = byte3;
+            buffer[i + 1] = byte2;
+            buffer[i + 2] = byte1;
+            buffer[i + 3] = byte0;
+        }
+        return buffer;
+    }
+};
+
+const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
+const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
+
+const bsonType = Symbol.for('@@mdb.bson.type');
+class BSONValue {
+    get [bsonType]() {
+        return this._bsontype;
+    }
+    get [BSON_VERSION_SYMBOL]() {
+        return BSON_MAJOR_VERSION;
+    }
+    [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) {
+        return this.inspect(depth, options, inspect);
+    }
+}
+
+const FLOAT = new Float64Array(1);
+const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
+FLOAT[0] = -1;
+const isBigEndian = FLOAT_BYTES[7] === 0;
+const NumberUtils = {
+    isBigEndian,
+    getNonnegativeInt32LE(source, offset) {
+        if (source[offset + 3] > 127) {
+            throw new RangeError(`Size cannot be negative at offset: ${offset}`);
+        }
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getInt32LE(source, offset) {
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getUint32LE(source, offset) {
+        return (source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+    },
+    getUint32BE(source, offset) {
+        return (source[offset + 3] +
+            source[offset + 2] * 256 +
+            source[offset + 1] * 65536 +
+            source[offset] * 16777216);
+    },
+    getBigInt64LE(source, offset) {
+        const hi = BigInt(source[offset + 4] +
+            source[offset + 5] * 256 +
+            source[offset + 6] * 65536 +
+            (source[offset + 7] << 24));
+        const lo = BigInt(source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+        return (hi << 32n) + lo;
+    },
+    getFloat64LE: isBigEndian
+        ? (source, offset) => {
+            FLOAT_BYTES[7] = source[offset];
+            FLOAT_BYTES[6] = source[offset + 1];
+            FLOAT_BYTES[5] = source[offset + 2];
+            FLOAT_BYTES[4] = source[offset + 3];
+            FLOAT_BYTES[3] = source[offset + 4];
+            FLOAT_BYTES[2] = source[offset + 5];
+            FLOAT_BYTES[1] = source[offset + 6];
+            FLOAT_BYTES[0] = source[offset + 7];
+            return FLOAT[0];
+        }
+        : (source, offset) => {
+            FLOAT_BYTES[0] = source[offset];
+            FLOAT_BYTES[1] = source[offset + 1];
+            FLOAT_BYTES[2] = source[offset + 2];
+            FLOAT_BYTES[3] = source[offset + 3];
+            FLOAT_BYTES[4] = source[offset + 4];
+            FLOAT_BYTES[5] = source[offset + 5];
+            FLOAT_BYTES[6] = source[offset + 6];
+            FLOAT_BYTES[7] = source[offset + 7];
+            return FLOAT[0];
+        },
+    setInt32BE(destination, offset, value) {
+        destination[offset + 3] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset] = value;
+        return 4;
+    },
+    setInt32LE(destination, offset, value) {
+        destination[offset] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 3] = value;
+        return 4;
+    },
+    setBigInt64LE(destination, offset, value) {
+        const mask32bits = 0xffffffffn;
+        let lo = Number(value & mask32bits);
+        destination[offset] = lo;
+        lo >>= 8;
+        destination[offset + 1] = lo;
+        lo >>= 8;
+        destination[offset + 2] = lo;
+        lo >>= 8;
+        destination[offset + 3] = lo;
+        let hi = Number((value >> 32n) & mask32bits);
+        destination[offset + 4] = hi;
+        hi >>= 8;
+        destination[offset + 5] = hi;
+        hi >>= 8;
+        destination[offset + 6] = hi;
+        hi >>= 8;
+        destination[offset + 7] = hi;
+        return 8;
+    },
+    setFloat64LE: isBigEndian
+        ? (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[7];
+            destination[offset + 1] = FLOAT_BYTES[6];
+            destination[offset + 2] = FLOAT_BYTES[5];
+            destination[offset + 3] = FLOAT_BYTES[4];
+            destination[offset + 4] = FLOAT_BYTES[3];
+            destination[offset + 5] = FLOAT_BYTES[2];
+            destination[offset + 6] = FLOAT_BYTES[1];
+            destination[offset + 7] = FLOAT_BYTES[0];
+            return 8;
+        }
+        : (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[0];
+            destination[offset + 1] = FLOAT_BYTES[1];
+            destination[offset + 2] = FLOAT_BYTES[2];
+            destination[offset + 3] = FLOAT_BYTES[3];
+            destination[offset + 4] = FLOAT_BYTES[4];
+            destination[offset + 5] = FLOAT_BYTES[5];
+            destination[offset + 6] = FLOAT_BYTES[6];
+            destination[offset + 7] = FLOAT_BYTES[7];
+            return 8;
+        }
+};
+
+class Binary extends BSONValue {
+    get _bsontype() {
+        return 'Binary';
+    }
+    static BSON_BINARY_SUBTYPE_DEFAULT = 0;
+    static BUFFER_SIZE = 256;
+    static SUBTYPE_DEFAULT = 0;
+    static SUBTYPE_FUNCTION = 1;
+    static SUBTYPE_BYTE_ARRAY = 2;
+    static SUBTYPE_UUID_OLD = 3;
+    static SUBTYPE_UUID = 4;
+    static SUBTYPE_MD5 = 5;
+    static SUBTYPE_ENCRYPTED = 6;
+    static SUBTYPE_COLUMN = 7;
+    static SUBTYPE_SENSITIVE = 8;
+    static SUBTYPE_VECTOR = 9;
+    static SUBTYPE_USER_DEFINED = 128;
+    static VECTOR_TYPE = Object.freeze({
+        Int8: 0x03,
+        Float32: 0x27,
+        PackedBit: 0x10
+    });
+    buffer;
+    sub_type;
+    position;
+    constructor(buffer, subType) {
+        super();
+        if (!(buffer == null) &&
+            typeof buffer === 'string' &&
+            !ArrayBuffer.isView(buffer) &&
+            !isAnyArrayBuffer(buffer) &&
+            !Array.isArray(buffer)) {
+            throw new BSONError('Binary can only be constructed from Uint8Array or number[]');
+        }
+        this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
+        if (buffer == null) {
+            this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
+            this.position = 0;
+        }
+        else {
+            this.buffer = Array.isArray(buffer)
+                ? ByteUtils.fromNumberArray(buffer)
+                : ByteUtils.toLocalBufferType(buffer);
+            this.position = this.buffer.byteLength;
+        }
+    }
+    put(byteValue) {
+        if (typeof byteValue === 'string' && byteValue.length !== 1) {
+            throw new BSONError('only accepts single character String');
+        }
+        else if (typeof byteValue !== 'number' && byteValue.length !== 1)
+            throw new BSONError('only accepts single character Uint8Array or Array');
+        let decodedByte;
+        if (typeof byteValue === 'string') {
+            decodedByte = byteValue.charCodeAt(0);
+        }
+        else if (typeof byteValue === 'number') {
+            decodedByte = byteValue;
+        }
+        else {
+            decodedByte = byteValue[0];
+        }
+        if (decodedByte < 0 || decodedByte > 255) {
+            throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
+        }
+        if (this.buffer.byteLength > this.position) {
+            this.buffer[this.position++] = decodedByte;
+        }
+        else {
+            const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+            this.buffer[this.position++] = decodedByte;
+        }
+    }
+    write(sequence, offset) {
+        offset = typeof offset === 'number' ? offset : this.position;
+        if (this.buffer.byteLength < offset + sequence.length) {
+            const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+        }
+        if (ArrayBuffer.isView(sequence)) {
+            this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
+            this.position =
+                offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
+        }
+        else if (typeof sequence === 'string') {
+            throw new BSONError('input cannot be string');
+        }
+    }
+    read(position, length) {
+        length = length && length > 0 ? length : this.position;
+        const end = position + length;
+        return this.buffer.subarray(position, end > this.position ? this.position : end);
+    }
+    value() {
+        return this.buffer.length === this.position
+            ? this.buffer
+            : this.buffer.subarray(0, this.position);
+    }
+    length() {
+        return this.position;
+    }
+    toJSON() {
+        return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.buffer.subarray(0, this.position));
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        if (encoding === 'utf8' || encoding === 'utf-8')
+            return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+        return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (this.sub_type === Binary.SUBTYPE_VECTOR) {
+            validateBinaryVector(this);
+        }
+        const base64String = ByteUtils.toBase64(this.buffer);
+        const subType = Number(this.sub_type).toString(16);
+        if (options.legacy) {
+            return {
+                $binary: base64String,
+                $type: subType.length === 1 ? '0' + subType : subType
+            };
+        }
+        return {
+            $binary: {
+                base64: base64String,
+                subType: subType.length === 1 ? '0' + subType : subType
+            }
+        };
+    }
+    toUUID() {
+        if (this.sub_type === Binary.SUBTYPE_UUID) {
+            return new UUID(this.buffer.subarray(0, this.position));
+        }
+        throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
+    }
+    static createFromHexString(hex, subType) {
+        return new Binary(ByteUtils.fromHex(hex), subType);
+    }
+    static createFromBase64(base64, subType) {
+        return new Binary(ByteUtils.fromBase64(base64), subType);
+    }
+    static fromExtendedJSON(doc, options) {
+        options = options || {};
+        let data;
+        let type;
+        if ('$binary' in doc) {
+            if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
+                type = doc.$type ? parseInt(doc.$type, 16) : 0;
+                data = ByteUtils.fromBase64(doc.$binary);
+            }
+            else {
+                if (typeof doc.$binary !== 'string') {
+                    type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
+                    data = ByteUtils.fromBase64(doc.$binary.base64);
+                }
+            }
+        }
+        else if ('$uuid' in doc) {
+            type = 4;
+            data = UUID.bytesFromString(doc.$uuid);
+        }
+        if (!data) {
+            throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
+        }
+        return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        const base64Arg = inspect(base64, options);
+        const subTypeArg = inspect(this.sub_type, options);
+        return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
+    }
+    toInt8Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {
+            throw new BSONError('Binary datatype field is not Int8');
+        }
+        validateBinaryVector(this);
+        return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toFloat32Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {
+            throw new BSONError('Binary datatype field is not Float32');
+        }
+        validateBinaryVector(this);
+        const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(floatBytes);
+        return new Float32Array(floatBytes.buffer);
+    }
+    toPackedBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        const byteCount = this.length() - 2;
+        const bitCount = byteCount * 8 - this.buffer[1];
+        const bits = new Int8Array(bitCount);
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = (bitOffset / 8) | 0;
+            const byte = this.buffer[byteOffset + 2];
+            const shift = 7 - (bitOffset % 8);
+            const bit = (byte >> shift) & 1;
+            bits[bitOffset] = bit;
+        }
+        return bits;
+    }
+    static fromInt8Array(array) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.Int8;
+        buffer[1] = 0;
+        const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        buffer.set(intBytes, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromFloat32Array(array) {
+        const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
+        binaryBytes[0] = Binary.VECTOR_TYPE.Float32;
+        binaryBytes[1] = 0;
+        const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        binaryBytes.set(floatBytes, 2);
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
+        const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromPackedBits(array, padding = 0) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.PackedBit;
+        buffer[1] = padding;
+        buffer.set(array, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromBits(bits) {
+        const byteLength = (bits.length + 7) >>> 3;
+        const bytes = new Uint8Array(byteLength + 2);
+        bytes[0] = Binary.VECTOR_TYPE.PackedBit;
+        const remainder = bits.length % 8;
+        bytes[1] = remainder === 0 ? 0 : 8 - remainder;
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = bitOffset >>> 3;
+            const bit = bits[bitOffset];
+            if (bit !== 0 && bit !== 1) {
+                throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
+            }
+            if (bit === 0)
+                continue;
+            const shift = 7 - (bitOffset % 8);
+            bytes[byteOffset + 2] |= bit << shift;
+        }
+        return new this(bytes, Binary.SUBTYPE_VECTOR);
+    }
+}
+function validateBinaryVector(vector) {
+    if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
+        return;
+    const size = vector.position;
+    const datatype = vector.buffer[0];
+    const padding = vector.buffer[1];
+    if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) &&
+        padding !== 0) {
+        throw new BSONError('Invalid Vector: padding must be zero for int8 and float32 vectors');
+    }
+    if (datatype === Binary.VECTOR_TYPE.Float32) {
+        if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
+            throw new BSONError('Invalid Vector: Float32 vector must contain a multiple of 4 bytes');
+        }
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
+        throw new BSONError('Invalid Vector: padding must be zero for packed bit vectors that are empty');
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
+        throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
+    }
+}
+const UUID_BYTE_LENGTH = 16;
+const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
+const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
+class UUID extends Binary {
+    constructor(input) {
+        let bytes;
+        if (input == null) {
+            bytes = UUID.generate();
+        }
+        else if (input instanceof UUID) {
+            bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
+        }
+        else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
+            bytes = ByteUtils.toLocalBufferType(input);
+        }
+        else if (typeof input === 'string') {
+            bytes = UUID.bytesFromString(input);
+        }
+        else {
+            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).');
+        }
+        super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+    }
+    toHexString(includeDashes = true) {
+        if (includeDashes) {
+            return [
+                ByteUtils.toHex(this.buffer.subarray(0, 4)),
+                ByteUtils.toHex(this.buffer.subarray(4, 6)),
+                ByteUtils.toHex(this.buffer.subarray(6, 8)),
+                ByteUtils.toHex(this.buffer.subarray(8, 10)),
+                ByteUtils.toHex(this.buffer.subarray(10, 16))
+            ].join('-');
+        }
+        return ByteUtils.toHex(this.buffer);
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.id);
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    equals(otherId) {
+        if (!otherId) {
+            return false;
+        }
+        if (otherId instanceof UUID) {
+            return ByteUtils.equals(otherId.id, this.id);
+        }
+        try {
+            return ByteUtils.equals(new UUID(otherId).id, this.id);
+        }
+        catch {
+            return false;
+        }
+    }
+    toBinary() {
+        return new Binary(this.id, Binary.SUBTYPE_UUID);
+    }
+    static generate() {
+        const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
+        bytes[6] = (bytes[6] & 0x0f) | 0x40;
+        bytes[8] = (bytes[8] & 0x3f) | 0x80;
+        return bytes;
+    }
+    static isValid(input) {
+        if (!input) {
+            return false;
+        }
+        if (typeof input === 'string') {
+            return UUID.isValidUUIDString(input);
+        }
+        if (isUint8Array(input)) {
+            return input.byteLength === UUID_BYTE_LENGTH;
+        }
+        return (input._bsontype === 'Binary' &&
+            input.sub_type === this.SUBTYPE_UUID &&
+            input.buffer.byteLength === 16);
+    }
+    static createFromHexString(hexString) {
+        const buffer = UUID.bytesFromString(hexString);
+        return new UUID(buffer);
+    }
+    static createFromBase64(base64) {
+        return new UUID(ByteUtils.fromBase64(base64));
+    }
+    static bytesFromString(representation) {
+        if (!UUID.isValidUUIDString(representation)) {
+            throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
+        }
+        return ByteUtils.fromHex(representation.replace(/-/g, ''));
+    }
+    static isValidUUIDString(representation) {
+        return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new UUID(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+class Code extends BSONValue {
+    get _bsontype() {
+        return 'Code';
+    }
+    code;
+    scope;
+    constructor(code, scope) {
+        super();
+        this.code = code.toString();
+        this.scope = scope ?? null;
+    }
+    toJSON() {
+        if (this.scope != null) {
+            return { code: this.code, scope: this.scope };
+        }
+        return { code: this.code };
+    }
+    toExtendedJSON() {
+        if (this.scope) {
+            return { $code: this.code, $scope: this.scope };
+        }
+        return { $code: this.code };
+    }
+    static fromExtendedJSON(doc) {
+        return new Code(doc.$code, doc.$scope);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        let parametersString = inspect(this.code, options);
+        const multiLineFn = parametersString.includes('\n');
+        if (this.scope != null) {
+            parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
+        }
+        const endingNewline = multiLineFn && this.scope === null;
+        return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
+    }
+}
+
+function isDBRefLike(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '$id' in value &&
+        value.$id != null &&
+        '$ref' in value &&
+        typeof value.$ref === 'string' &&
+        (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));
+}
+class DBRef extends BSONValue {
+    get _bsontype() {
+        return 'DBRef';
+    }
+    collection;
+    oid;
+    db;
+    fields;
+    constructor(collection, oid, db, fields) {
+        super();
+        const parts = collection.split('.');
+        if (parts.length === 2) {
+            db = parts.shift();
+            collection = parts.shift();
+        }
+        this.collection = collection;
+        this.oid = oid;
+        this.db = db;
+        this.fields = fields || {};
+    }
+    get namespace() {
+        return this.collection;
+    }
+    set namespace(value) {
+        this.collection = value;
+    }
+    toJSON() {
+        const o = Object.assign({
+            $ref: this.collection,
+            $id: this.oid
+        }, this.fields);
+        if (this.db != null)
+            o.$db = this.db;
+        return o;
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        let o = {
+            $ref: this.collection,
+            $id: this.oid
+        };
+        if (options.legacy) {
+            return o;
+        }
+        if (this.db)
+            o.$db = this.db;
+        o = Object.assign(o, this.fields);
+        return o;
+    }
+    static fromExtendedJSON(doc) {
+        const copy = Object.assign({}, doc);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const args = [
+            inspect(this.namespace, options),
+            inspect(this.oid, options),
+            ...(this.db ? [inspect(this.db, options)] : []),
+            ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
+        ];
+        args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
+        return `new DBRef(${args.join(', ')})`;
+    }
+}
+
+function removeLeadingZerosAndExplicitPlus(str) {
+    if (str === '') {
+        return str;
+    }
+    let startIndex = 0;
+    const isNegative = str[startIndex] === '-';
+    const isExplicitlyPositive = str[startIndex] === '+';
+    if (isExplicitlyPositive || isNegative) {
+        startIndex += 1;
+    }
+    let foundInsignificantZero = false;
+    for (; startIndex < str.length && str[startIndex] === '0'; ++startIndex) {
+        foundInsignificantZero = true;
+    }
+    if (!foundInsignificantZero) {
+        return isExplicitlyPositive ? str.slice(1) : str;
+    }
+    return `${isNegative ? '-' : ''}${str.length === startIndex ? '0' : str.slice(startIndex)}`;
+}
+function validateStringCharacters(str, radix) {
+    radix = radix ?? 10;
+    const validCharacters = '0123456789abcdefghijklmnopqrstuvwxyz'.slice(0, radix);
+    const regex = new RegExp(`[^-+${validCharacters}]`, 'i');
+    return regex.test(str) ? false : str;
+}
+
+let wasm = undefined;
+try {
+    wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
+}
+catch {
+}
+const TWO_PWR_16_DBL = 1 << 16;
+const TWO_PWR_24_DBL = 1 << 24;
+const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
+const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
+const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
+const INT_CACHE = {};
+const UINT_CACHE = {};
+const MAX_INT64_STRING_LENGTH = 20;
+const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
+class Long extends BSONValue {
+    get _bsontype() {
+        return 'Long';
+    }
+    get __isLong__() {
+        return true;
+    }
+    high;
+    low;
+    unsigned;
+    constructor(lowOrValue = 0, highOrUnsigned, unsigned) {
+        super();
+        const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);
+        const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;
+        const res = typeof lowOrValue === 'string'
+            ? Long.fromString(lowOrValue, unsignedBool)
+            : typeof lowOrValue === 'bigint'
+                ? Long.fromBigInt(lowOrValue, unsignedBool)
+                : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
+        this.low = res.low;
+        this.high = res.high;
+        this.unsigned = res.unsigned;
+    }
+    static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
+    static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
+    static ZERO = Long.fromInt(0);
+    static UZERO = Long.fromInt(0, true);
+    static ONE = Long.fromInt(1);
+    static UONE = Long.fromInt(1, true);
+    static NEG_ONE = Long.fromInt(-1);
+    static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
+    static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
+    static fromBits(lowBits, highBits, unsigned) {
+        return new Long(lowBits, highBits, unsigned);
+    }
+    static fromInt(value, unsigned) {
+        let obj, cachedObj, cache;
+        if (unsigned) {
+            value >>>= 0;
+            if ((cache = 0 <= value && value < 256)) {
+                cachedObj = UINT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
+            if (cache)
+                UINT_CACHE[value] = obj;
+            return obj;
+        }
+        else {
+            value |= 0;
+            if ((cache = -128 <= value && value < 128)) {
+                cachedObj = INT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
+            if (cache)
+                INT_CACHE[value] = obj;
+            return obj;
+        }
+    }
+    static fromNumber(value, unsigned) {
+        if (isNaN(value))
+            return unsigned ? Long.UZERO : Long.ZERO;
+        if (unsigned) {
+            if (value < 0)
+                return Long.UZERO;
+            if (value >= TWO_PWR_64_DBL)
+                return Long.MAX_UNSIGNED_VALUE;
+        }
+        else {
+            if (value <= -TWO_PWR_63_DBL)
+                return Long.MIN_VALUE;
+            if (value + 1 >= TWO_PWR_63_DBL)
+                return Long.MAX_VALUE;
+        }
+        if (value < 0)
+            return Long.fromNumber(-value, unsigned).neg();
+        return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
+    }
+    static fromBigInt(value, unsigned) {
+        const FROM_BIGINT_BIT_MASK = 0xffffffffn;
+        const FROM_BIGINT_BIT_SHIFT = 32n;
+        return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number((value >> FROM_BIGINT_BIT_SHIFT) & FROM_BIGINT_BIT_MASK), unsigned);
+    }
+    static _fromString(str, unsigned, radix) {
+        if (str.length === 0)
+            throw new BSONError('empty string');
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        let p;
+        if ((p = str.indexOf('-')) > 0)
+            throw new BSONError('interior hyphen');
+        else if (p === 0) {
+            return Long._fromString(str.substring(1), unsigned, radix).neg();
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 8));
+        let result = Long.ZERO;
+        for (let i = 0; i < str.length; i += 8) {
+            const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
+            if (size < 8) {
+                const power = Long.fromNumber(Math.pow(radix, size));
+                result = result.mul(power).add(Long.fromNumber(value));
+            }
+            else {
+                result = result.mul(radixToPower);
+                result = result.add(Long.fromNumber(value));
+            }
+        }
+        result.unsigned = unsigned;
+        return result;
+    }
+    static fromStringStrict(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str.trim() !== str) {
+            throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
+        }
+        if (!validateStringCharacters(str, radix)) {
+            throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
+        }
+        const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
+        const result = Long._fromString(cleanedStr, unsigned, radix);
+        if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
+            throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? 'an unsigned' : 'a signed'} 64-bit Long ${radix != null ? `with radix: ${radix}` : ''}`);
+        }
+        return result;
+    }
+    static fromString(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str === 'NaN' && radix < 24) {
+            return Long.ZERO;
+        }
+        else if ((str === 'Infinity' || str === '+Infinity' || str === '-Infinity') && radix < 35) {
+            return Long.ZERO;
+        }
+        return Long._fromString(str, unsigned, radix);
+    }
+    static fromBytes(bytes, unsigned, le) {
+        return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
+    }
+    static fromBytesLE(bytes, unsigned) {
+        return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned);
+    }
+    static fromBytesBE(bytes, unsigned) {
+        return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned);
+    }
+    static isLong(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            '__isLong__' in value &&
+            value.__isLong__ === true);
+    }
+    static fromValue(val, unsigned) {
+        if (typeof val === 'number')
+            return Long.fromNumber(val, unsigned);
+        if (typeof val === 'string')
+            return Long.fromString(val, unsigned);
+        return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
+    }
+    add(addend) {
+        if (!Long.isLong(addend))
+            addend = Long.fromValue(addend);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = addend.high >>> 16;
+        const b32 = addend.high & 0xffff;
+        const b16 = addend.low >>> 16;
+        const b00 = addend.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 + b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 + b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 + b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 + b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    and(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
+    }
+    compare(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.eq(other))
+            return 0;
+        const thisNeg = this.isNegative(), otherNeg = other.isNegative();
+        if (thisNeg && !otherNeg)
+            return -1;
+        if (!thisNeg && otherNeg)
+            return 1;
+        if (!this.unsigned)
+            return this.sub(other).isNegative() ? -1 : 1;
+        return other.high >>> 0 > this.high >>> 0 ||
+            (other.high === this.high && other.low >>> 0 > this.low >>> 0)
+            ? -1
+            : 1;
+    }
+    comp(other) {
+        return this.compare(other);
+    }
+    divide(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (divisor.isZero())
+            throw new BSONError('division by zero');
+        if (wasm) {
+            if (!this.unsigned &&
+                this.high === -2147483648 &&
+                divisor.low === -1 &&
+                divisor.high === -1) {
+                return this;
+            }
+            const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (this.isZero())
+            return this.unsigned ? Long.UZERO : Long.ZERO;
+        let approx, rem, res;
+        if (!this.unsigned) {
+            if (this.eq(Long.MIN_VALUE)) {
+                if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
+                    return Long.MIN_VALUE;
+                else if (divisor.eq(Long.MIN_VALUE))
+                    return Long.ONE;
+                else {
+                    const halfThis = this.shr(1);
+                    approx = halfThis.div(divisor).shl(1);
+                    if (approx.eq(Long.ZERO)) {
+                        return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
+                    }
+                    else {
+                        rem = this.sub(divisor.mul(approx));
+                        res = approx.add(rem.div(divisor));
+                        return res;
+                    }
+                }
+            }
+            else if (divisor.eq(Long.MIN_VALUE))
+                return this.unsigned ? Long.UZERO : Long.ZERO;
+            if (this.isNegative()) {
+                if (divisor.isNegative())
+                    return this.neg().div(divisor.neg());
+                return this.neg().div(divisor).neg();
+            }
+            else if (divisor.isNegative())
+                return this.div(divisor.neg()).neg();
+            res = Long.ZERO;
+        }
+        else {
+            if (!divisor.unsigned)
+                divisor = divisor.toUnsigned();
+            if (divisor.gt(this))
+                return Long.UZERO;
+            if (divisor.gt(this.shru(1)))
+                return Long.UONE;
+            res = Long.UZERO;
+        }
+        rem = this;
+        while (rem.gte(divisor)) {
+            approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
+            const log2 = Math.ceil(Math.log(approx) / Math.LN2);
+            const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
+            let approxRes = Long.fromNumber(approx);
+            let approxRem = approxRes.mul(divisor);
+            while (approxRem.isNegative() || approxRem.gt(rem)) {
+                approx -= delta;
+                approxRes = Long.fromNumber(approx, this.unsigned);
+                approxRem = approxRes.mul(divisor);
+            }
+            if (approxRes.isZero())
+                approxRes = Long.ONE;
+            res = res.add(approxRes);
+            rem = rem.sub(approxRem);
+        }
+        return res;
+    }
+    div(divisor) {
+        return this.divide(divisor);
+    }
+    equals(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
+            return false;
+        return this.high === other.high && this.low === other.low;
+    }
+    eq(other) {
+        return this.equals(other);
+    }
+    getHighBits() {
+        return this.high;
+    }
+    getHighBitsUnsigned() {
+        return this.high >>> 0;
+    }
+    getLowBits() {
+        return this.low;
+    }
+    getLowBitsUnsigned() {
+        return this.low >>> 0;
+    }
+    getNumBitsAbs() {
+        if (this.isNegative()) {
+            return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
+        }
+        const val = this.high !== 0 ? this.high : this.low;
+        let bit;
+        for (bit = 31; bit > 0; bit--)
+            if ((val & (1 << bit)) !== 0)
+                break;
+        return this.high !== 0 ? bit + 33 : bit + 1;
+    }
+    greaterThan(other) {
+        return this.comp(other) > 0;
+    }
+    gt(other) {
+        return this.greaterThan(other);
+    }
+    greaterThanOrEqual(other) {
+        return this.comp(other) >= 0;
+    }
+    gte(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    ge(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    isEven() {
+        return (this.low & 1) === 0;
+    }
+    isNegative() {
+        return !this.unsigned && this.high < 0;
+    }
+    isOdd() {
+        return (this.low & 1) === 1;
+    }
+    isPositive() {
+        return this.unsigned || this.high >= 0;
+    }
+    isZero() {
+        return this.high === 0 && this.low === 0;
+    }
+    lessThan(other) {
+        return this.comp(other) < 0;
+    }
+    lt(other) {
+        return this.lessThan(other);
+    }
+    lessThanOrEqual(other) {
+        return this.comp(other) <= 0;
+    }
+    lte(other) {
+        return this.lessThanOrEqual(other);
+    }
+    modulo(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (wasm) {
+            const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        return this.sub(this.div(divisor).mul(divisor));
+    }
+    mod(divisor) {
+        return this.modulo(divisor);
+    }
+    rem(divisor) {
+        return this.modulo(divisor);
+    }
+    multiply(multiplier) {
+        if (this.isZero())
+            return Long.ZERO;
+        if (!Long.isLong(multiplier))
+            multiplier = Long.fromValue(multiplier);
+        if (wasm) {
+            const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (multiplier.isZero())
+            return Long.ZERO;
+        if (this.eq(Long.MIN_VALUE))
+            return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (multiplier.eq(Long.MIN_VALUE))
+            return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (this.isNegative()) {
+            if (multiplier.isNegative())
+                return this.neg().mul(multiplier.neg());
+            else
+                return this.neg().mul(multiplier).neg();
+        }
+        else if (multiplier.isNegative())
+            return this.mul(multiplier.neg()).neg();
+        if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
+            return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = multiplier.high >>> 16;
+        const b32 = multiplier.high & 0xffff;
+        const b16 = multiplier.low >>> 16;
+        const b00 = multiplier.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 * b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 * b00;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c16 += a00 * b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 * b00;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a16 * b16;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a00 * b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    mul(multiplier) {
+        return this.multiply(multiplier);
+    }
+    negate() {
+        if (!this.unsigned && this.eq(Long.MIN_VALUE))
+            return Long.MIN_VALUE;
+        return this.not().add(Long.ONE);
+    }
+    neg() {
+        return this.negate();
+    }
+    not() {
+        return Long.fromBits(~this.low, ~this.high, this.unsigned);
+    }
+    notEquals(other) {
+        return !this.equals(other);
+    }
+    neq(other) {
+        return this.notEquals(other);
+    }
+    ne(other) {
+        return this.notEquals(other);
+    }
+    or(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
+    }
+    shiftLeft(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
+        else
+            return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
+    }
+    shl(numBits) {
+        return this.shiftLeft(numBits);
+    }
+    shiftRight(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
+        else
+            return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
+    }
+    shr(numBits) {
+        return this.shiftRight(numBits);
+    }
+    shiftRightUnsigned(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        numBits &= 63;
+        if (numBits === 0)
+            return this;
+        else {
+            const high = this.high;
+            if (numBits < 32) {
+                const low = this.low;
+                return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
+            }
+            else if (numBits === 32)
+                return Long.fromBits(high, 0, this.unsigned);
+            else
+                return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
+        }
+    }
+    shr_u(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    shru(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    subtract(subtrahend) {
+        if (!Long.isLong(subtrahend))
+            subtrahend = Long.fromValue(subtrahend);
+        return this.add(subtrahend.neg());
+    }
+    sub(subtrahend) {
+        return this.subtract(subtrahend);
+    }
+    toInt() {
+        return this.unsigned ? this.low >>> 0 : this.low;
+    }
+    toNumber() {
+        if (this.unsigned)
+            return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
+        return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
+    }
+    toBigInt() {
+        return BigInt(this.toString());
+    }
+    toBytes(le) {
+        return le ? this.toBytesLE() : this.toBytesBE();
+    }
+    toBytesLE() {
+        const hi = this.high, lo = this.low;
+        return [
+            lo & 0xff,
+            (lo >>> 8) & 0xff,
+            (lo >>> 16) & 0xff,
+            lo >>> 24,
+            hi & 0xff,
+            (hi >>> 8) & 0xff,
+            (hi >>> 16) & 0xff,
+            hi >>> 24
+        ];
+    }
+    toBytesBE() {
+        const hi = this.high, lo = this.low;
+        return [
+            hi >>> 24,
+            (hi >>> 16) & 0xff,
+            (hi >>> 8) & 0xff,
+            hi & 0xff,
+            lo >>> 24,
+            (lo >>> 16) & 0xff,
+            (lo >>> 8) & 0xff,
+            lo & 0xff
+        ];
+    }
+    toSigned() {
+        if (!this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, false);
+    }
+    toString(radix) {
+        radix = radix || 10;
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        if (this.isZero())
+            return '0';
+        if (this.isNegative()) {
+            if (this.eq(Long.MIN_VALUE)) {
+                const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
+                return div.toString(radix) + rem1.toInt().toString(radix);
+            }
+            else
+                return '-' + this.neg().toString(radix);
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
+        let rem = this;
+        let result = '';
+        while (true) {
+            const remDiv = rem.div(radixToPower);
+            const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
+            let digits = intval.toString(radix);
+            rem = remDiv;
+            if (rem.isZero()) {
+                return digits + result;
+            }
+            else {
+                while (digits.length < 6)
+                    digits = '0' + digits;
+                result = '' + digits + result;
+            }
+        }
+    }
+    toUnsigned() {
+        if (this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, true);
+    }
+    xor(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
+    }
+    eqz() {
+        return this.isZero();
+    }
+    le(other) {
+        return this.lessThanOrEqual(other);
+    }
+    toExtendedJSON(options) {
+        if (options && options.relaxed)
+            return this.toNumber();
+        return { $numberLong: this.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        const { useBigInt64 = false, relaxed = true } = { ...options };
+        if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
+            throw new BSONError('$numberLong string is too long');
+        }
+        if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
+            throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
+        }
+        if (useBigInt64) {
+            const bigIntResult = BigInt(doc.$numberLong);
+            return BigInt.asIntN(64, bigIntResult);
+        }
+        const longResult = Long.fromString(doc.$numberLong);
+        if (relaxed) {
+            return longResult.toNumber();
+        }
+        return longResult;
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const longVal = inspect(this.toString(), options);
+        const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
+        return `new Long(${longVal}${unsignedVal})`;
+    }
+}
+
+const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
+const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
+const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
+const EXPONENT_MAX = 6111;
+const EXPONENT_MIN = -6176;
+const EXPONENT_BIAS = 6176;
+const MAX_DIGITS = 34;
+const NAN_BUFFER = ByteUtils.fromNumberArray([
+    0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
+    0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
+    0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
+const COMBINATION_MASK = 0x1f;
+const EXPONENT_MASK = 0x3fff;
+const COMBINATION_INFINITY = 30;
+const COMBINATION_NAN = 31;
+function isDigit(value) {
+    return !isNaN(parseInt(value, 10));
+}
+function divideu128(value) {
+    const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
+    let _rem = Long.fromNumber(0);
+    if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
+        return { quotient: value, rem: _rem };
+    }
+    for (let i = 0; i <= 3; i++) {
+        _rem = _rem.shiftLeft(32);
+        _rem = _rem.add(new Long(value.parts[i], 0));
+        value.parts[i] = _rem.div(DIVISOR).low;
+        _rem = _rem.modulo(DIVISOR);
+    }
+    return { quotient: value, rem: _rem };
+}
+function multiply64x2(left, right) {
+    if (!left && !right) {
+        return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
+    }
+    const leftHigh = left.shiftRightUnsigned(32);
+    const leftLow = new Long(left.getLowBits(), 0);
+    const rightHigh = right.shiftRightUnsigned(32);
+    const rightLow = new Long(right.getLowBits(), 0);
+    let productHigh = leftHigh.multiply(rightHigh);
+    let productMid = leftHigh.multiply(rightLow);
+    const productMid2 = leftLow.multiply(rightHigh);
+    let productLow = leftLow.multiply(rightLow);
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productMid = new Long(productMid.getLowBits(), 0)
+        .add(productMid2)
+        .add(productLow.shiftRightUnsigned(32));
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
+    return { high: productHigh, low: productLow };
+}
+function lessThan(left, right) {
+    const uhleft = left.high >>> 0;
+    const uhright = right.high >>> 0;
+    if (uhleft < uhright) {
+        return true;
+    }
+    else if (uhleft === uhright) {
+        const ulleft = left.low >>> 0;
+        const ulright = right.low >>> 0;
+        if (ulleft < ulright)
+            return true;
+    }
+    return false;
+}
+function invalidErr(string, message) {
+    throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
+}
+class Decimal128 extends BSONValue {
+    get _bsontype() {
+        return 'Decimal128';
+    }
+    bytes;
+    constructor(bytes) {
+        super();
+        if (typeof bytes === 'string') {
+            this.bytes = Decimal128.fromString(bytes).bytes;
+        }
+        else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
+            if (bytes.byteLength !== 16) {
+                throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
+            }
+            this.bytes = bytes;
+        }
+        else {
+            throw new BSONError('Decimal128 must take a Buffer or string');
+        }
+    }
+    static fromString(representation) {
+        return Decimal128._fromString(representation, { allowRounding: false });
+    }
+    static fromStringWithRounding(representation) {
+        return Decimal128._fromString(representation, { allowRounding: true });
+    }
+    static _fromString(representation, options) {
+        let isNegative = false;
+        let sawSign = false;
+        let sawRadix = false;
+        let foundNonZero = false;
+        let significantDigits = 0;
+        let nDigitsRead = 0;
+        let nDigits = 0;
+        let radixPosition = 0;
+        let firstNonZero = 0;
+        const digits = [0];
+        let nDigitsStored = 0;
+        let digitsInsert = 0;
+        let lastDigit = 0;
+        let exponent = 0;
+        let significandHigh = new Long(0, 0);
+        let significandLow = new Long(0, 0);
+        let biasedExponent = 0;
+        let index = 0;
+        if (representation.length >= 7000) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        const stringMatch = representation.match(PARSE_STRING_REGEXP);
+        const infMatch = representation.match(PARSE_INF_REGEXP);
+        const nanMatch = representation.match(PARSE_NAN_REGEXP);
+        if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        if (stringMatch) {
+            const unsignedNumber = stringMatch[2];
+            const e = stringMatch[4];
+            const expSign = stringMatch[5];
+            const expNumber = stringMatch[6];
+            if (e && expNumber === undefined)
+                invalidErr(representation, 'missing exponent power');
+            if (e && unsignedNumber === undefined)
+                invalidErr(representation, 'missing exponent base');
+            if (e === undefined && (expSign || expNumber)) {
+                invalidErr(representation, 'missing e before exponent');
+            }
+        }
+        if (representation[index] === '+' || representation[index] === '-') {
+            sawSign = true;
+            isNegative = representation[index++] === '-';
+        }
+        if (!isDigit(representation[index]) && representation[index] !== '.') {
+            if (representation[index] === 'i' || representation[index] === 'I') {
+                return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+            }
+            else if (representation[index] === 'N') {
+                return new Decimal128(NAN_BUFFER);
+            }
+        }
+        while (isDigit(representation[index]) || representation[index] === '.') {
+            if (representation[index] === '.') {
+                if (sawRadix)
+                    invalidErr(representation, 'contains multiple periods');
+                sawRadix = true;
+                index = index + 1;
+                continue;
+            }
+            if (nDigitsStored < MAX_DIGITS) {
+                if (representation[index] !== '0' || foundNonZero) {
+                    if (!foundNonZero) {
+                        firstNonZero = nDigitsRead;
+                    }
+                    foundNonZero = true;
+                    digits[digitsInsert++] = parseInt(representation[index], 10);
+                    nDigitsStored = nDigitsStored + 1;
+                }
+            }
+            if (foundNonZero)
+                nDigits = nDigits + 1;
+            if (sawRadix)
+                radixPosition = radixPosition + 1;
+            nDigitsRead = nDigitsRead + 1;
+            index = index + 1;
+        }
+        if (sawRadix && !nDigitsRead)
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        if (representation[index] === 'e' || representation[index] === 'E') {
+            const match = representation.substr(++index).match(EXPONENT_REGEX);
+            if (!match || !match[2])
+                return new Decimal128(NAN_BUFFER);
+            exponent = parseInt(match[0], 10);
+            index = index + match[0].length;
+        }
+        if (representation[index])
+            return new Decimal128(NAN_BUFFER);
+        if (!nDigitsStored) {
+            digits[0] = 0;
+            nDigits = 1;
+            nDigitsStored = 1;
+            significantDigits = 0;
+        }
+        else {
+            lastDigit = nDigitsStored - 1;
+            significantDigits = nDigits;
+            if (significantDigits !== 1) {
+                while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') {
+                    significantDigits = significantDigits - 1;
+                }
+            }
+        }
+        if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
+            exponent = EXPONENT_MIN;
+        }
+        else {
+            exponent = exponent - radixPosition;
+        }
+        while (exponent > EXPONENT_MAX) {
+            lastDigit = lastDigit + 1;
+            if (lastDigit >= MAX_DIGITS) {
+                if (significantDigits === 0) {
+                    exponent = EXPONENT_MAX;
+                    break;
+                }
+                invalidErr(representation, 'overflow');
+            }
+            exponent = exponent - 1;
+        }
+        if (options.allowRounding) {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0 && significantDigits < nDigitsStored) {
+                    exponent = EXPONENT_MIN;
+                    significantDigits = 0;
+                    break;
+                }
+                if (nDigitsStored < nDigits) {
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    const digitsString = digits.join('');
+                    if (digitsString.match(/^0+$/)) {
+                        exponent = EXPONENT_MAX;
+                        break;
+                    }
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                let endOfString = nDigitsRead;
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                let roundBit = 0;
+                if (roundDigit >= 5) {
+                    roundBit = 1;
+                    if (roundDigit === 5) {
+                        roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
+                        for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
+                            if (parseInt(representation[i], 10)) {
+                                roundBit = 1;
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (roundBit) {
+                    let dIdx = lastDigit;
+                    for (; dIdx >= 0; dIdx--) {
+                        if (++digits[dIdx] > 9) {
+                            digits[dIdx] = 0;
+                            if (dIdx === 0) {
+                                if (exponent < EXPONENT_MAX) {
+                                    exponent = exponent + 1;
+                                    digits[dIdx] = 1;
+                                }
+                                else {
+                                    return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+                                }
+                            }
+                        }
+                        else {
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        else {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0) {
+                    if (significantDigits === 0) {
+                        exponent = EXPONENT_MIN;
+                        break;
+                    }
+                    invalidErr(representation, 'exponent underflow');
+                }
+                if (nDigitsStored < nDigits) {
+                    if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
+                        significantDigits !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    if (digits[lastDigit] !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                if (roundDigit !== 0) {
+                    invalidErr(representation, 'inexact rounding');
+                }
+            }
+        }
+        significandHigh = Long.fromNumber(0);
+        significandLow = Long.fromNumber(0);
+        if (significantDigits === 0) {
+            significandHigh = Long.fromNumber(0);
+            significandLow = Long.fromNumber(0);
+        }
+        else if (lastDigit < 17) {
+            let dIdx = 0;
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            significandHigh = new Long(0, 0);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        else {
+            let dIdx = 0;
+            significandHigh = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit - 17; dIdx++) {
+                significandHigh = significandHigh.multiply(Long.fromNumber(10));
+                significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
+            }
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
+        significand.low = significand.low.add(significandLow);
+        if (lessThan(significand.low, significandLow)) {
+            significand.high = significand.high.add(Long.fromNumber(1));
+        }
+        biasedExponent = exponent + EXPONENT_BIAS;
+        const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
+        if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
+            dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
+        }
+        else {
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
+        }
+        dec.low = significand.low;
+        if (isNegative) {
+            dec.high = dec.high.or(Long.fromString('9223372036854775808'));
+        }
+        const buffer = ByteUtils.allocateUnsafe(16);
+        index = 0;
+        buffer[index++] = dec.low.low & 0xff;
+        buffer[index++] = (dec.low.low >> 8) & 0xff;
+        buffer[index++] = (dec.low.low >> 16) & 0xff;
+        buffer[index++] = (dec.low.low >> 24) & 0xff;
+        buffer[index++] = dec.low.high & 0xff;
+        buffer[index++] = (dec.low.high >> 8) & 0xff;
+        buffer[index++] = (dec.low.high >> 16) & 0xff;
+        buffer[index++] = (dec.low.high >> 24) & 0xff;
+        buffer[index++] = dec.high.low & 0xff;
+        buffer[index++] = (dec.high.low >> 8) & 0xff;
+        buffer[index++] = (dec.high.low >> 16) & 0xff;
+        buffer[index++] = (dec.high.low >> 24) & 0xff;
+        buffer[index++] = dec.high.high & 0xff;
+        buffer[index++] = (dec.high.high >> 8) & 0xff;
+        buffer[index++] = (dec.high.high >> 16) & 0xff;
+        buffer[index++] = (dec.high.high >> 24) & 0xff;
+        return new Decimal128(buffer);
+    }
+    toString() {
+        let biased_exponent;
+        let significand_digits = 0;
+        const significand = new Array(36);
+        for (let i = 0; i < significand.length; i++)
+            significand[i] = 0;
+        let index = 0;
+        let is_zero = false;
+        let significand_msb;
+        let significand128 = { parts: [0, 0, 0, 0] };
+        let j, k;
+        const string = [];
+        index = 0;
+        const buffer = this.bytes;
+        const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        index = 0;
+        const dec = {
+            low: new Long(low, midl),
+            high: new Long(midh, high)
+        };
+        if (dec.high.lessThan(Long.ZERO)) {
+            string.push('-');
+        }
+        const combination = (high >> 26) & COMBINATION_MASK;
+        if (combination >> 3 === 3) {
+            if (combination === COMBINATION_INFINITY) {
+                return string.join('') + 'Infinity';
+            }
+            else if (combination === COMBINATION_NAN) {
+                return 'NaN';
+            }
+            else {
+                biased_exponent = (high >> 15) & EXPONENT_MASK;
+                significand_msb = 0x08 + ((high >> 14) & 0x01);
+            }
+        }
+        else {
+            significand_msb = (high >> 14) & 0x07;
+            biased_exponent = (high >> 17) & EXPONENT_MASK;
+        }
+        const exponent = biased_exponent - EXPONENT_BIAS;
+        significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
+        significand128.parts[1] = midh;
+        significand128.parts[2] = midl;
+        significand128.parts[3] = low;
+        if (significand128.parts[0] === 0 &&
+            significand128.parts[1] === 0 &&
+            significand128.parts[2] === 0 &&
+            significand128.parts[3] === 0) {
+            is_zero = true;
+        }
+        else {
+            for (k = 3; k >= 0; k--) {
+                let least_digits = 0;
+                const result = divideu128(significand128);
+                significand128 = result.quotient;
+                least_digits = result.rem.low;
+                if (!least_digits)
+                    continue;
+                for (j = 8; j >= 0; j--) {
+                    significand[k * 9 + j] = least_digits % 10;
+                    least_digits = Math.floor(least_digits / 10);
+                }
+            }
+        }
+        if (is_zero) {
+            significand_digits = 1;
+            significand[index] = 0;
+        }
+        else {
+            significand_digits = 36;
+            while (!significand[index]) {
+                significand_digits = significand_digits - 1;
+                index = index + 1;
+            }
+        }
+        const scientific_exponent = significand_digits - 1 + exponent;
+        if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
+            if (significand_digits > 34) {
+                string.push(`${0}`);
+                if (exponent > 0)
+                    string.push(`E+${exponent}`);
+                else if (exponent < 0)
+                    string.push(`E${exponent}`);
+                return string.join('');
+            }
+            string.push(`${significand[index++]}`);
+            significand_digits = significand_digits - 1;
+            if (significand_digits) {
+                string.push('.');
+            }
+            for (let i = 0; i < significand_digits; i++) {
+                string.push(`${significand[index++]}`);
+            }
+            string.push('E');
+            if (scientific_exponent > 0) {
+                string.push(`+${scientific_exponent}`);
+            }
+            else {
+                string.push(`${scientific_exponent}`);
+            }
+        }
+        else {
+            if (exponent >= 0) {
+                for (let i = 0; i < significand_digits; i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+            else {
+                let radix_position = significand_digits + exponent;
+                if (radix_position > 0) {
+                    for (let i = 0; i < radix_position; i++) {
+                        string.push(`${significand[index++]}`);
+                    }
+                }
+                else {
+                    string.push('0');
+                }
+                string.push('.');
+                while (radix_position++ < 0) {
+                    string.push('0');
+                }
+                for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+        }
+        return string.join('');
+    }
+    toJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    toExtendedJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    static fromExtendedJSON(doc) {
+        return Decimal128.fromString(doc.$numberDecimal);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const d128string = inspect(this.toString(), options);
+        return `new Decimal128(${d128string})`;
+    }
+}
+
+class Double extends BSONValue {
+    get _bsontype() {
+        return 'Double';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value;
+    }
+    static fromString(value) {
+        const coercedValue = Number(value);
+        if (value === 'NaN')
+            return new Double(NaN);
+        if (value === 'Infinity')
+            return new Double(Infinity);
+        if (value === '-Infinity')
+            return new Double(-Infinity);
+        if (!Number.isFinite(coercedValue)) {
+            throw new BSONError(`Input: ${value} is not representable as a Double`);
+        }
+        if (value.trim() !== value) {
+            throw new BSONError(`Input: '${value}' contains whitespace`);
+        }
+        if (value === '') {
+            throw new BSONError(`Input is an empty string`);
+        }
+        if (/[^-0-9.+eE]/.test(value)) {
+            throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
+        }
+        return new Double(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toExtendedJSON(options) {
+        if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
+            return this.value;
+        }
+        if (Object.is(Math.sign(this.value), -0)) {
+            return { $numberDouble: '-0.0' };
+        }
+        return {
+            $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
+        };
+    }
+    static fromExtendedJSON(doc, options) {
+        const doubleValue = parseFloat(doc.$numberDouble);
+        return options && options.relaxed ? doubleValue : new Double(doubleValue);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Double(${inspect(this.value, options)})`;
+    }
+}
+
+class Int32 extends BSONValue {
+    get _bsontype() {
+        return 'Int32';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value | 0;
+    }
+    static fromString(value) {
+        const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
+        const coercedValue = Number(value);
+        if (BSON_INT32_MAX < coercedValue) {
+            throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
+        }
+        else if (BSON_INT32_MIN > coercedValue) {
+            throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
+        }
+        else if (!Number.isSafeInteger(coercedValue)) {
+            throw new BSONError(`Input: '${value}' is not a safe integer`);
+        }
+        else if (coercedValue.toString() !== cleanedValue) {
+            throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
+        }
+        return new Int32(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON(options) {
+        if (options && (options.relaxed || options.legacy))
+            return this.value;
+        return { $numberInt: this.value.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Int32(${inspect(this.value, options)})`;
+    }
+}
+
+class MaxKey extends BSONValue {
+    get _bsontype() {
+        return 'MaxKey';
+    }
+    toExtendedJSON() {
+        return { $maxKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MaxKey();
+    }
+    inspect() {
+        return 'new MaxKey()';
+    }
+}
+
+class MinKey extends BSONValue {
+    get _bsontype() {
+        return 'MinKey';
+    }
+    toExtendedJSON() {
+        return { $minKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MinKey();
+    }
+    inspect() {
+        return 'new MinKey()';
+    }
+}
+
+let PROCESS_UNIQUE = null;
+const __idCache = new WeakMap();
+class ObjectId extends BSONValue {
+    get _bsontype() {
+        return 'ObjectId';
+    }
+    static index = Math.floor(Math.random() * 0xffffff);
+    static cacheHexString;
+    buffer;
+    constructor(inputId) {
+        super();
+        let workingId;
+        if (typeof inputId === 'object' && inputId && 'id' in inputId) {
+            if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
+                throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
+            }
+            if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
+                workingId = ByteUtils.fromHex(inputId.toHexString());
+            }
+            else {
+                workingId = inputId.id;
+            }
+        }
+        else {
+            workingId = inputId;
+        }
+        if (workingId == null) {
+            this.buffer = ObjectId.generate();
+        }
+        else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
+            this.buffer = ByteUtils.toLocalBufferType(workingId);
+        }
+        else if (typeof workingId === 'string') {
+            if (ObjectId.validateHexString(workingId)) {
+                this.buffer = ByteUtils.fromHex(workingId);
+                if (ObjectId.cacheHexString) {
+                    __idCache.set(this, workingId);
+                }
+            }
+            else {
+                throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer');
+            }
+        }
+        else {
+            throw new BSONError('Argument passed in does not match the accepted types');
+        }
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, ByteUtils.toHex(value));
+        }
+    }
+    static validateHexString(string) {
+        if (string?.length !== 24)
+            return false;
+        for (let i = 0; i < 24; i++) {
+            const char = string.charCodeAt(i);
+            if ((char >= 48 && char <= 57) ||
+                (char >= 97 && char <= 102) ||
+                (char >= 65 && char <= 70)) {
+                continue;
+            }
+            return false;
+        }
+        return true;
+    }
+    toHexString() {
+        if (ObjectId.cacheHexString) {
+            const __id = __idCache.get(this);
+            if (__id)
+                return __id;
+        }
+        const hexString = ByteUtils.toHex(this.id);
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, hexString);
+        }
+        return hexString;
+    }
+    static getInc() {
+        return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
+    }
+    static generate(time) {
+        if ('number' !== typeof time) {
+            time = Math.floor(Date.now() / 1000);
+        }
+        const inc = ObjectId.getInc();
+        const buffer = ByteUtils.allocateUnsafe(12);
+        NumberUtils.setInt32BE(buffer, 0, time);
+        if (PROCESS_UNIQUE === null) {
+            PROCESS_UNIQUE = ByteUtils.randomBytes(5);
+        }
+        buffer[4] = PROCESS_UNIQUE[0];
+        buffer[5] = PROCESS_UNIQUE[1];
+        buffer[6] = PROCESS_UNIQUE[2];
+        buffer[7] = PROCESS_UNIQUE[3];
+        buffer[8] = PROCESS_UNIQUE[4];
+        buffer[11] = inc & 0xff;
+        buffer[10] = (inc >> 8) & 0xff;
+        buffer[9] = (inc >> 16) & 0xff;
+        return buffer;
+    }
+    toString(encoding) {
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        if (encoding === 'hex')
+            return this.toHexString();
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    static is(variable) {
+        return (variable != null &&
+            typeof variable === 'object' &&
+            '_bsontype' in variable &&
+            variable._bsontype === 'ObjectId');
+    }
+    equals(otherId) {
+        if (otherId === undefined || otherId === null) {
+            return false;
+        }
+        if (ObjectId.is(otherId)) {
+            return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer));
+        }
+        if (typeof otherId === 'string') {
+            return otherId.toLowerCase() === this.toHexString();
+        }
+        if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') {
+            const otherIdString = otherId.toHexString();
+            const thisIdString = this.toHexString();
+            return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
+        }
+        return false;
+    }
+    getTimestamp() {
+        const timestamp = new Date();
+        const time = NumberUtils.getUint32BE(this.buffer, 0);
+        timestamp.setTime(Math.floor(time) * 1000);
+        return timestamp;
+    }
+    static createPk() {
+        return new ObjectId();
+    }
+    serializeInto(uint8array, index) {
+        uint8array[index] = this.buffer[0];
+        uint8array[index + 1] = this.buffer[1];
+        uint8array[index + 2] = this.buffer[2];
+        uint8array[index + 3] = this.buffer[3];
+        uint8array[index + 4] = this.buffer[4];
+        uint8array[index + 5] = this.buffer[5];
+        uint8array[index + 6] = this.buffer[6];
+        uint8array[index + 7] = this.buffer[7];
+        uint8array[index + 8] = this.buffer[8];
+        uint8array[index + 9] = this.buffer[9];
+        uint8array[index + 10] = this.buffer[10];
+        uint8array[index + 11] = this.buffer[11];
+        return 12;
+    }
+    static createFromTime(time) {
+        const buffer = ByteUtils.allocate(12);
+        for (let i = 11; i >= 4; i--)
+            buffer[i] = 0;
+        NumberUtils.setInt32BE(buffer, 0, time);
+        return new ObjectId(buffer);
+    }
+    static createFromHexString(hexString) {
+        if (hexString?.length !== 24) {
+            throw new BSONError('hex string must be 24 characters');
+        }
+        return new ObjectId(ByteUtils.fromHex(hexString));
+    }
+    static createFromBase64(base64) {
+        if (base64?.length !== 16) {
+            throw new BSONError('base64 string must be 16 characters');
+        }
+        return new ObjectId(ByteUtils.fromBase64(base64));
+    }
+    static isValid(id) {
+        if (id == null)
+            return false;
+        if (typeof id === 'string')
+            return ObjectId.validateHexString(id);
+        try {
+            new ObjectId(id);
+            return true;
+        }
+        catch {
+            return false;
+        }
+    }
+    toExtendedJSON() {
+        if (this.toHexString)
+            return { $oid: this.toHexString() };
+        return { $oid: this.toString('hex') };
+    }
+    static fromExtendedJSON(doc) {
+        return new ObjectId(doc.$oid);
+    }
+    isCached() {
+        return ObjectId.cacheHexString && __idCache.has(this);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new ObjectId(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
+    let totalLength = 4 + 1;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+        }
+        for (const key of Object.keys(object)) {
+            totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
+        }
+    }
+    return totalLength;
+}
+function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
+    if (typeof value?.toBSON === 'function') {
+        value = value.toBSON();
+    }
+    switch (typeof value) {
+        case 'string':
+            return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
+        case 'number':
+            if (Math.floor(value) === value &&
+                value >= JS_INT_MIN &&
+                value <= JS_INT_MAX) {
+                if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
+                }
+                else {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+                }
+            }
+            else {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+        case 'undefined':
+            if (isArray || !ignoreUndefined)
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            return 0;
+        case 'boolean':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
+        case 'object':
+            if (value != null &&
+                typeof value._bsontype === 'string' &&
+                value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                throw new BSONVersionError();
+            }
+            else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            }
+            else if (value._bsontype === 'ObjectId') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
+            }
+            else if (value instanceof Date || isDate(value)) {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (ArrayBuffer.isView(value) ||
+                value instanceof ArrayBuffer ||
+                isAnyArrayBuffer(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength);
+            }
+            else if (value._bsontype === 'Long' ||
+                value._bsontype === 'Double' ||
+                value._bsontype === 'Timestamp') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (value._bsontype === 'Decimal128') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
+            }
+            else if (value._bsontype === 'Code') {
+                if (value.scope != null && Object.keys(value.scope).length > 0) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1 +
+                        internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1);
+                }
+            }
+            else if (value._bsontype === 'Binary') {
+                const binary = value;
+                if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        (binary.position + 1 + 4 + 1 + 4));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1));
+                }
+            }
+            else if (value._bsontype === 'Symbol') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    ByteUtils.utf8ByteLength(value.value) +
+                    4 +
+                    1 +
+                    1);
+            }
+            else if (value._bsontype === 'DBRef') {
+                const ordered_values = Object.assign({
+                    $ref: value.collection,
+                    $id: value.oid
+                }, value.fields);
+                if (value.db != null) {
+                    ordered_values['$db'] = value.db;
+                }
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
+            }
+            else if (value instanceof RegExp || isRegExp(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.source) +
+                    1 +
+                    (value.global ? 1 : 0) +
+                    (value.ignoreCase ? 1 : 0) +
+                    (value.multiline ? 1 : 0) +
+                    1);
+            }
+            else if (value._bsontype === 'BSONRegExp') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.pattern) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.options) +
+                    1);
+            }
+            else {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) +
+                    1);
+            }
+        case 'function':
+            if (serializeFunctions) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    4 +
+                    ByteUtils.utf8ByteLength(value.toString()) +
+                    1);
+            }
+            return 0;
+        case 'bigint':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+        case 'symbol':
+            return 0;
+        default:
+            throw new BSONError(`Unrecognized JS type: ${typeof value}`);
+    }
+}
+
+function alphabetize(str) {
+    return str.split('').sort().join('');
+}
+class BSONRegExp extends BSONValue {
+    get _bsontype() {
+        return 'BSONRegExp';
+    }
+    pattern;
+    options;
+    constructor(pattern, options) {
+        super();
+        this.pattern = pattern;
+        this.options = alphabetize(options ?? '');
+        if (this.pattern.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
+        }
+        if (this.options.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
+        }
+        for (let i = 0; i < this.options.length; i++) {
+            if (!(this.options[i] === 'i' ||
+                this.options[i] === 'm' ||
+                this.options[i] === 'x' ||
+                this.options[i] === 'l' ||
+                this.options[i] === 's' ||
+                this.options[i] === 'u')) {
+                throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
+            }
+        }
+    }
+    static parseOptions(options) {
+        return options ? options.split('').sort().join('') : '';
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (options.legacy) {
+            return { $regex: this.pattern, $options: this.options };
+        }
+        return { $regularExpression: { pattern: this.pattern, options: this.options } };
+    }
+    static fromExtendedJSON(doc) {
+        if ('$regex' in doc) {
+            if (typeof doc.$regex !== 'string') {
+                if (doc.$regex._bsontype === 'BSONRegExp') {
+                    return doc;
+                }
+            }
+            else {
+                return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
+            }
+        }
+        if ('$regularExpression' in doc) {
+            return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
+        }
+        throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
+    }
+    inspect(depth, options, inspect) {
+        const stylize = getStylizeFunction(options) ?? (v => v);
+        inspect ??= defaultInspect;
+        const pattern = stylize(inspect(this.pattern), 'regexp');
+        const flags = stylize(inspect(this.options), 'regexp');
+        return `new BSONRegExp(${pattern}, ${flags})`;
+    }
+}
+
+class BSONSymbol extends BSONValue {
+    get _bsontype() {
+        return 'BSONSymbol';
+    }
+    value;
+    constructor(value) {
+        super();
+        this.value = value;
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON() {
+        return { $symbol: this.value };
+    }
+    static fromExtendedJSON(doc) {
+        return new BSONSymbol(doc.$symbol);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new BSONSymbol(${inspect(this.value, options)})`;
+    }
+}
+
+const LongWithoutOverridesClass = Long;
+class Timestamp extends LongWithoutOverridesClass {
+    get _bsontype() {
+        return 'Timestamp';
+    }
+    get [bsonType]() {
+        return 'Timestamp';
+    }
+    static MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
+    get i() {
+        return this.low >>> 0;
+    }
+    get t() {
+        return this.high >>> 0;
+    }
+    constructor(low) {
+        if (low == null) {
+            super(0, 0, true);
+        }
+        else if (typeof low === 'bigint') {
+            super(low, true);
+        }
+        else if (Long.isLong(low)) {
+            super(low.low, low.high, true);
+        }
+        else if (typeof low === 'object' && 't' in low && 'i' in low) {
+            if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t as a number');
+            }
+            if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
+            }
+            const t = Number(low.t);
+            const i = Number(low.i);
+            if (t < 0 || Number.isNaN(t)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
+            }
+            if (i < 0 || Number.isNaN(i)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
+            }
+            if (t > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max');
+            }
+            if (i > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max');
+            }
+            super(i, t, true);
+        }
+        else {
+            throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }');
+        }
+    }
+    toJSON() {
+        return {
+            $timestamp: this.toString()
+        };
+    }
+    static fromInt(value) {
+        return new Timestamp(Long.fromInt(value, true));
+    }
+    static fromNumber(value) {
+        return new Timestamp(Long.fromNumber(value, true));
+    }
+    static fromBits(lowBits, highBits) {
+        return new Timestamp({ i: lowBits, t: highBits });
+    }
+    static fromString(str, optRadix) {
+        return new Timestamp(Long.fromString(str, true, optRadix));
+    }
+    toExtendedJSON() {
+        return { $timestamp: { t: this.t, i: this.i } };
+    }
+    static fromExtendedJSON(doc) {
+        const i = Long.isLong(doc.$timestamp.i)
+            ? doc.$timestamp.i.getLowBitsUnsigned()
+            : doc.$timestamp.i;
+        const t = Long.isLong(doc.$timestamp.t)
+            ? doc.$timestamp.t.getLowBitsUnsigned()
+            : doc.$timestamp.t;
+        return new Timestamp({ t, i });
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const t = inspect(this.t, options);
+        const i = inspect(this.i, options);
+        return `new Timestamp({ t: ${t}, i: ${i} })`;
+    }
+}
+
+const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
+const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
+function internalDeserialize(buffer, options, isArray) {
+    options = options == null ? {} : options;
+    const index = options && options.index ? options.index : 0;
+    const size = NumberUtils.getInt32LE(buffer, index);
+    if (size < 5) {
+        throw new BSONError(`bson size must be >= 5, is ${size}`);
+    }
+    if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
+        throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
+    }
+    if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
+        throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
+    }
+    if (size + index > buffer.byteLength) {
+        throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`);
+    }
+    if (buffer[index + size - 1] !== 0) {
+        throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
+    }
+    return deserializeObject(buffer, index, options, isArray);
+}
+const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
+function deserializeObject(buffer, index, options, isArray = false) {
+    const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
+    const raw = options['raw'] == null ? false : options['raw'];
+    const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
+    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');
+    }
+    const validation = options.validation == null ? { utf8: true } : options.validation;
+    let globalUTFValidation = true;
+    let validationSetting;
+    let utf8KeysSet;
+    const utf8ValidatedKeys = validation.utf8;
+    if (typeof utf8ValidatedKeys === 'boolean') {
+        validationSetting = utf8ValidatedKeys;
+    }
+    else {
+        globalUTFValidation = false;
+        const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
+            return utf8ValidatedKeys[key];
+        });
+        if (utf8ValidationValues.length === 0) {
+            throw new BSONError('UTF-8 validation setting cannot be empty');
+        }
+        if (typeof utf8ValidationValues[0] !== 'boolean') {
+            throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
+        }
+        validationSetting = utf8ValidationValues[0];
+        if (!utf8ValidationValues.every(item => item === validationSetting)) {
+            throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
+        }
+    }
+    if (!globalUTFValidation) {
+        utf8KeysSet = new Set();
+        for (const key of Object.keys(utf8ValidatedKeys)) {
+            utf8KeysSet.add(key);
+        }
+    }
+    const startIndex = index;
+    if (buffer.length < 5)
+        throw new BSONError('corrupt bson message < 5 bytes long');
+    const size = NumberUtils.getInt32LE(buffer, index);
+    index += 4;
+    if (size < 5 || size > buffer.length)
+        throw new BSONError('corrupt bson message');
+    const object = isArray ? [] : {};
+    let arrayIndex = 0;
+    let isPossibleDBRef = isArray ? false : null;
+    while (true) {
+        const elementType = buffer[index++];
+        if (elementType === 0)
+            break;
+        let i = index;
+        while (buffer[i] !== 0x00 && i < buffer.length) {
+            i++;
+        }
+        if (i >= buffer.byteLength)
+            throw new BSONError('Bad BSON Document: illegal CString');
+        const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false);
+        let shouldValidateKey = true;
+        if (globalUTFValidation || utf8KeysSet?.has(name)) {
+            shouldValidateKey = validationSetting;
+        }
+        else {
+            shouldValidateKey = !validationSetting;
+        }
+        if (isPossibleDBRef !== false && name[0] === '$') {
+            isPossibleDBRef = allowedDBRefKeys.test(name);
+        }
+        let value;
+        index = i + 1;
+        if (elementType === BSON_DATA_STRING) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_OID) {
+            const oid = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oid[i] = buffer[index + i];
+            value = new ObjectId(oid);
+            index = index + 12;
+        }
+        else if (elementType === BSON_DATA_INT && promoteValues === false) {
+            value = new Int32(NumberUtils.getInt32LE(buffer, index));
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_INT) {
+            value = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_NUMBER) {
+            value = NumberUtils.getFloat64LE(buffer, index);
+            index += 8;
+            if (promoteValues === false)
+                value = new Double(value);
+        }
+        else if (elementType === BSON_DATA_DATE) {
+            const lowBits = NumberUtils.getInt32LE(buffer, index);
+            const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+            index += 8;
+            value = new Date(new Long(lowBits, highBits).toNumber());
+        }
+        else if (elementType === BSON_DATA_BOOLEAN) {
+            if (buffer[index] !== 0 && buffer[index] !== 1)
+                throw new BSONError('illegal boolean type value');
+            value = buffer[index++] === 1;
+        }
+        else if (elementType === BSON_DATA_OBJECT) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            if (objectSize <= 0 || objectSize > buffer.length - index)
+                throw new BSONError('bad embedded document length in bson');
+            if (raw) {
+                value = buffer.subarray(index, index + objectSize);
+            }
+            else {
+                let objectOptions = options;
+                if (!globalUTFValidation) {
+                    objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
+                }
+                value = deserializeObject(buffer, _index, objectOptions, false);
+            }
+            index = index + objectSize;
+        }
+        else if (elementType === BSON_DATA_ARRAY) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            let arrayOptions = options;
+            const stopIndex = index + objectSize;
+            if (fieldsAsRaw && fieldsAsRaw[name]) {
+                arrayOptions = { ...options, raw: true };
+            }
+            if (!globalUTFValidation) {
+                arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
+            }
+            value = deserializeObject(buffer, _index, arrayOptions, true);
+            index = index + objectSize;
+            if (buffer[index - 1] !== 0)
+                throw new BSONError('invalid array terminator byte');
+            if (index !== stopIndex)
+                throw new BSONError('corrupted array bson');
+        }
+        else if (elementType === BSON_DATA_UNDEFINED) {
+            value = undefined;
+        }
+        else if (elementType === BSON_DATA_NULL) {
+            value = null;
+        }
+        else if (elementType === BSON_DATA_LONG) {
+            if (useBigInt64) {
+                value = NumberUtils.getBigInt64LE(buffer, index);
+                index += 8;
+            }
+            else {
+                const lowBits = NumberUtils.getInt32LE(buffer, index);
+                const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+                index += 8;
+                const long = new Long(lowBits, highBits);
+                if (promoteLongs && promoteValues === true) {
+                    value =
+                        long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
+                            ? long.toNumber()
+                            : long;
+                }
+                else {
+                    value = long;
+                }
+            }
+        }
+        else if (elementType === BSON_DATA_DECIMAL128) {
+            const bytes = ByteUtils.allocateUnsafe(16);
+            for (let i = 0; i < 16; i++)
+                bytes[i] = buffer[index + i];
+            index = index + 16;
+            value = new Decimal128(bytes);
+        }
+        else if (elementType === BSON_DATA_BINARY) {
+            let binarySize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            const totalBinarySize = binarySize;
+            const subType = buffer[index++];
+            if (binarySize < 0)
+                throw new BSONError('Negative binary type element size found');
+            if (binarySize > buffer.byteLength)
+                throw new BSONError('Binary type size larger than document size');
+            if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
+                binarySize = NumberUtils.getInt32LE(buffer, index);
+                index += 4;
+                if (binarySize < 0)
+                    throw new BSONError('Negative binary type element size found for subtype 0x02');
+                if (binarySize > totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
+                if (binarySize < totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
+            }
+            if (promoteBuffers && promoteValues) {
+                value = ByteUtils.toLocalBufferType(buffer.subarray(index, index + binarySize));
+            }
+            else {
+                value = new Binary(buffer.subarray(index, index + binarySize), subType);
+                if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
+                    value = value.toUUID();
+                }
+            }
+            index = index + binarySize;
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            const optionsArray = new Array(regExpOptions.length);
+            for (i = 0; i < regExpOptions.length; i++) {
+                switch (regExpOptions[i]) {
+                    case 'm':
+                        optionsArray[i] = 'm';
+                        break;
+                    case 's':
+                        optionsArray[i] = 'g';
+                        break;
+                    case 'i':
+                        optionsArray[i] = 'i';
+                        break;
+                }
+            }
+            value = new RegExp(source, optionsArray.join(''));
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            value = new BSONRegExp(source, regExpOptions);
+        }
+        else if (elementType === BSON_DATA_SYMBOL) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = promoteValues ? symbol : new BSONSymbol(symbol);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_TIMESTAMP) {
+            value = new Timestamp({
+                i: NumberUtils.getUint32LE(buffer, index),
+                t: NumberUtils.getUint32LE(buffer, index + 4)
+            });
+            index += 8;
+        }
+        else if (elementType === BSON_DATA_MIN_KEY) {
+            value = new MinKey();
+        }
+        else if (elementType === BSON_DATA_MAX_KEY) {
+            value = new MaxKey();
+        }
+        else if (elementType === BSON_DATA_CODE) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = new Code(functionString);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_CODE_W_SCOPE) {
+            const totalSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (totalSize < 4 + 4 + 4 + 1) {
+                throw new BSONError('code_w_scope total size shorter minimum expected length');
+            }
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            const scopeObject = deserializeObject(buffer, _index, options, false);
+            index = index + objectSize;
+            if (totalSize < 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too short, truncating scope');
+            }
+            if (totalSize > 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too long, clips outer document');
+            }
+            value = new Code(functionString, scopeObject);
+        }
+        else if (elementType === BSON_DATA_DBPOINTER) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0)
+                throw new BSONError('bad string length in bson');
+            const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const oidBuffer = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oidBuffer[i] = buffer[index + i];
+            const oid = new ObjectId(oidBuffer);
+            index = index + 12;
+            value = new DBRef(namespace, oid);
+        }
+        else {
+            throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
+        }
+        if (name === '__proto__') {
+            Object.defineProperty(object, name, {
+                value,
+                writable: true,
+                enumerable: true,
+                configurable: true
+            });
+        }
+        else {
+            object[name] = value;
+        }
+    }
+    if (size !== index - startIndex) {
+        if (isArray)
+            throw new BSONError('corrupt array bson');
+        throw new BSONError('corrupt object bson');
+    }
+    if (!isPossibleDBRef)
+        return object;
+    if (isDBRefLike(object)) {
+        const copy = Object.assign({}, object);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(object.$ref, object.$id, object.$db, copy);
+    }
+    return object;
+}
+
+const regexp = /\x00/;
+const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
+function serializeString(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_STRING;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes + 1;
+    buffer[index - 1] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
+    NumberUtils.setInt32LE(buffer, index, size + 1);
+    index = index + 4 + size;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeNumber(buffer, key, value, index) {
+    const isNegativeZero = Object.is(value, -0);
+    const type = !isNegativeZero &&
+        Number.isSafeInteger(value) &&
+        value <= BSON_INT32_MAX &&
+        value >= BSON_INT32_MIN
+        ? BSON_DATA_INT
+        : BSON_DATA_NUMBER;
+    buffer[index++] = type;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0x00;
+    if (type === BSON_DATA_INT) {
+        index += NumberUtils.setInt32LE(buffer, index, value);
+    }
+    else {
+        index += NumberUtils.setFloat64LE(buffer, index, value);
+    }
+    return index;
+}
+function serializeBigInt(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_LONG;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index += numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setBigInt64LE(buffer, index, value);
+    return index;
+}
+function serializeNull(buffer, key, _, index) {
+    buffer[index++] = BSON_DATA_NULL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeBoolean(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BOOLEAN;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    buffer[index++] = value ? 1 : 0;
+    return index;
+}
+function serializeDate(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DATE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const dateInMilis = Long.fromNumber(value.getTime());
+    const lowBits = dateInMilis.getLowBits();
+    const highBits = dateInMilis.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.source && value.source.match(regexp) != null) {
+        throw new BSONError('value ' + value.source + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
+    buffer[index++] = 0x00;
+    if (value.ignoreCase)
+        buffer[index++] = 0x69;
+    if (value.global)
+        buffer[index++] = 0x73;
+    if (value.multiline)
+        buffer[index++] = 0x6d;
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeBSONRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.pattern.match(regexp) != null) {
+        throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
+    buffer[index++] = 0x00;
+    const sortedOptions = value.options.split('').sort().join('');
+    index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeMinMax(buffer, key, value, index) {
+    if (value === null) {
+        buffer[index++] = BSON_DATA_NULL;
+    }
+    else if (value._bsontype === 'MinKey') {
+        buffer[index++] = BSON_DATA_MIN_KEY;
+    }
+    else {
+        buffer[index++] = BSON_DATA_MAX_KEY;
+    }
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeObjectId(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_OID;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += value.serializeInto(buffer, index);
+    return index;
+}
+function serializeBuffer(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = value.length;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = value[i];
+    }
+    else {
+        buffer.set(value, index);
+    }
+    index = index + size;
+    return index;
+}
+function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path.has(value)) {
+        throw new BSONError('Cannot convert circular structure to BSON');
+    }
+    path.add(value);
+    buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+    path.delete(value);
+    return endIndex;
+}
+function serializeDecimal128(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DECIMAL128;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    for (let i = 0; i < 16; i++)
+        buffer[index + i] = value.bytes[i];
+    return index + 16;
+}
+function serializeLong(buffer, key, value, index) {
+    buffer[index++] =
+        value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const lowBits = value.getLowBits();
+    const highBits = value.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeInt32(buffer, key, value, index) {
+    value = value.valueOf();
+    buffer[index++] = BSON_DATA_INT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setInt32LE(buffer, index, value);
+    return index;
+}
+function serializeDouble(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_NUMBER;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setFloat64LE(buffer, index, value.value);
+    return index;
+}
+function serializeFunction(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_CODE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const functionString = value.toString();
+    const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
+    if (value.scope && typeof value.scope === 'object') {
+        buffer[index++] = BSON_DATA_CODE_W_SCOPE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        let startIndex = index;
+        const functionString = value.code;
+        index = index + 4;
+        const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, codeSize);
+        buffer[index + 4 + codeSize - 1] = 0;
+        index = index + codeSize + 4;
+        const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+        index = endIndex - 1;
+        const totalSize = endIndex - startIndex;
+        startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize);
+        buffer[index++] = 0;
+    }
+    else {
+        buffer[index++] = BSON_DATA_CODE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        const functionString = value.code.toString();
+        const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, size);
+        index = index + 4 + size - 1;
+        buffer[index++] = 0;
+    }
+    return index;
+}
+function serializeBinary(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const data = value.buffer;
+    let size = value.position;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
+        size = size + 4;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = value.sub_type;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+        size = size - 4;
+        index += NumberUtils.setInt32LE(buffer, index, size);
+    }
+    if (value.sub_type === Binary.SUBTYPE_VECTOR) {
+        validateBinaryVector(value);
+    }
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = data[i];
+    }
+    else {
+        buffer.set(data, index);
+    }
+    index = index + value.position;
+    return index;
+}
+function serializeSymbol(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_SYMBOL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) {
+    buffer[index++] = BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    let startIndex = index;
+    let output = {
+        $ref: value.collection || value.namespace,
+        $id: value.oid
+    };
+    if (value.db != null) {
+        output.$db = value.db;
+    }
+    output = Object.assign(output, value.fields);
+    const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path);
+    const size = endIndex - startIndex;
+    startIndex += NumberUtils.setInt32LE(buffer, index, size);
+    return endIndex;
+}
+function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path == null) {
+        if (object == null) {
+            buffer[0] = 0x05;
+            buffer[1] = 0x00;
+            buffer[2] = 0x00;
+            buffer[3] = 0x00;
+            buffer[4] = 0x00;
+            return 5;
+        }
+        if (Array.isArray(object)) {
+            throw new BSONError('serialize does not support an array as the root input');
+        }
+        if (typeof object !== 'object') {
+            throw new BSONError('serialize does not support non-object as the root input');
+        }
+        else if ('_bsontype' in object && typeof object._bsontype === 'string') {
+            throw new BSONError(`BSON types cannot be serialized as a document`);
+        }
+        else if (isDate(object) ||
+            isRegExp(object) ||
+            isUint8Array(object) ||
+            isAnyArrayBuffer(object)) {
+            throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
+        }
+        path = new Set();
+    }
+    path.add(object);
+    let index = startingIndex + 4;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            const key = `${i}`;
+            let value = object[i];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (value === undefined) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else if (object instanceof Map || isMap(object)) {
+        const iterator = object.entries();
+        let done = false;
+        while (!done) {
+            const entry = iterator.next();
+            done = !!entry.done;
+            if (done)
+                continue;
+            const key = entry.value ? entry.value[0] : undefined;
+            let value = entry.value ? entry.value[1] : undefined;
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+            if (object != null && typeof object !== 'object') {
+                throw new BSONError('toBSON function did not return an object');
+            }
+        }
+        for (const key of Object.keys(object)) {
+            let value = object[key];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    path.delete(object);
+    buffer[index++] = 0x00;
+    const size = index - startingIndex;
+    startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size);
+    return index;
+}
+
+function isBSONType(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '_bsontype' in value &&
+        typeof value._bsontype === 'string');
+}
+const keysToCodecs = {
+    $oid: ObjectId,
+    $binary: Binary,
+    $uuid: Binary,
+    $symbol: BSONSymbol,
+    $numberInt: Int32,
+    $numberDecimal: Decimal128,
+    $numberDouble: Double,
+    $numberLong: Long,
+    $minKey: MinKey,
+    $maxKey: MaxKey,
+    $regex: BSONRegExp,
+    $regularExpression: BSONRegExp,
+    $timestamp: Timestamp
+};
+function deserializeValue(value, options = {}) {
+    if (typeof value === 'number') {
+        const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
+        const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
+        if (options.relaxed || options.legacy) {
+            return value;
+        }
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (in32BitRange) {
+                return new Int32(value);
+            }
+            if (in64BitRange) {
+                if (options.useBigInt64) {
+                    return BigInt(value);
+                }
+                return Long.fromNumber(value);
+            }
+        }
+        return new Double(value);
+    }
+    if (value == null || typeof value !== 'object')
+        return value;
+    if (value.$undefined)
+        return null;
+    const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null);
+    for (let i = 0; i < keys.length; i++) {
+        const c = keysToCodecs[keys[i]];
+        if (c)
+            return c.fromExtendedJSON(value, options);
+    }
+    if (value.$date != null) {
+        const d = value.$date;
+        const date = new Date();
+        if (options.legacy) {
+            if (typeof d === 'number')
+                date.setTime(d);
+            else if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        else {
+            if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (Long.isLong(d))
+                date.setTime(d.toNumber());
+            else if (typeof d === 'number' && options.relaxed)
+                date.setTime(d);
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        return date;
+    }
+    if (value.$code != null) {
+        const copy = Object.assign({}, value);
+        if (value.$scope) {
+            copy.$scope = deserializeValue(value.$scope);
+        }
+        return Code.fromExtendedJSON(value);
+    }
+    if (isDBRefLike(value) || value.$dbPointer) {
+        const v = value.$ref ? value : value.$dbPointer;
+        if (v instanceof DBRef)
+            return v;
+        const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
+        let valid = true;
+        dollarKeys.forEach(k => {
+            if (['$ref', '$id', '$db'].indexOf(k) === -1)
+                valid = false;
+        });
+        if (valid)
+            return DBRef.fromExtendedJSON(v);
+    }
+    return value;
+}
+function serializeArray(array, options) {
+    return array.map((v, index) => {
+        options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
+        try {
+            return serializeValue(v, options);
+        }
+        finally {
+            options.seenObjects.pop();
+        }
+    });
+}
+function getISOString(date) {
+    const isoStr = date.toISOString();
+    return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
+}
+function serializeValue(value, options) {
+    if (value instanceof Map || isMap(value)) {
+        const obj = Object.create(null);
+        for (const [k, v] of value) {
+            if (typeof k !== 'string') {
+                throw new BSONError('Can only serialize maps with string keys');
+            }
+            obj[k] = v;
+        }
+        return serializeValue(obj, options);
+    }
+    if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
+        const index = options.seenObjects.findIndex(entry => entry.obj === value);
+        if (index !== -1) {
+            const props = options.seenObjects.map(entry => entry.propertyName);
+            const leadingPart = props
+                .slice(0, index)
+                .map(prop => `${prop} -> `)
+                .join('');
+            const alreadySeen = props[index];
+            const circularPart = ' -> ' +
+                props
+                    .slice(index + 1, props.length - 1)
+                    .map(prop => `${prop} -> `)
+                    .join('');
+            const current = props[props.length - 1];
+            const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
+            const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
+            throw new BSONError('Converting circular structure to EJSON:\n' +
+                `    ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
+                `    ${leadingSpace}\\${dashes}/`);
+        }
+        options.seenObjects[options.seenObjects.length - 1].obj = value;
+    }
+    if (Array.isArray(value))
+        return serializeArray(value, options);
+    if (value === undefined)
+        return null;
+    if (value instanceof Date || isDate(value)) {
+        const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000;
+        if (options.legacy) {
+            return options.relaxed && inRange
+                ? { $date: value.getTime() }
+                : { $date: getISOString(value) };
+        }
+        return options.relaxed && inRange
+            ? { $date: getISOString(value) }
+            : { $date: { $numberLong: value.getTime().toString() } };
+    }
+    if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                return { $numberInt: value.toString() };
+            }
+            if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
+                return { $numberLong: value.toString() };
+            }
+        }
+        return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
+    }
+    if (typeof value === 'bigint') {
+        if (!options.relaxed) {
+            return { $numberLong: BigInt.asIntN(64, value).toString() };
+        }
+        return Number(BigInt.asIntN(64, value));
+    }
+    if (value instanceof RegExp || isRegExp(value)) {
+        let flags = value.flags;
+        if (flags === undefined) {
+            const match = value.toString().match(/[gimuy]*$/);
+            if (match) {
+                flags = match[0];
+            }
+        }
+        const rx = new BSONRegExp(value.source, flags);
+        return rx.toExtendedJSON(options);
+    }
+    if (value != null && typeof value === 'object')
+        return serializeDocument(value, options);
+    return value;
+}
+const BSON_TYPE_MAPPINGS = {
+    Binary: (o) => new Binary(o.value(), o.sub_type),
+    Code: (o) => new Code(o.code, o.scope),
+    DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
+    Decimal128: (o) => new Decimal128(o.bytes),
+    Double: (o) => new Double(o.value),
+    Int32: (o) => new Int32(o.value),
+    Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_),
+    MaxKey: () => new MaxKey(),
+    MinKey: () => new MinKey(),
+    ObjectId: (o) => new ObjectId(o),
+    BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
+    BSONSymbol: (o) => new BSONSymbol(o.value),
+    Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
+};
+function serializeDocument(doc, options) {
+    if (doc == null || typeof doc !== 'object')
+        throw new BSONError('not an object instance');
+    const bsontype = doc._bsontype;
+    if (typeof bsontype === 'undefined') {
+        const _doc = {};
+        for (const name of Object.keys(doc)) {
+            options.seenObjects.push({ propertyName: name, obj: null });
+            try {
+                const value = serializeValue(doc[name], options);
+                if (name === '__proto__') {
+                    Object.defineProperty(_doc, name, {
+                        value,
+                        writable: true,
+                        enumerable: true,
+                        configurable: true
+                    });
+                }
+                else {
+                    _doc[name] = value;
+                }
+            }
+            finally {
+                options.seenObjects.pop();
+            }
+        }
+        return _doc;
+    }
+    else if (doc != null &&
+        typeof doc === 'object' &&
+        typeof doc._bsontype === 'string' &&
+        doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+        throw new BSONVersionError();
+    }
+    else if (isBSONType(doc)) {
+        let outDoc = doc;
+        if (typeof outDoc.toExtendedJSON !== 'function') {
+            const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
+            if (!mapper) {
+                throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
+            }
+            outDoc = mapper(outDoc);
+        }
+        if (bsontype === 'Code' && outDoc.scope) {
+            outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
+        }
+        else if (bsontype === 'DBRef' && outDoc.oid) {
+            outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
+        }
+        return outDoc.toExtendedJSON(options);
+    }
+    else {
+        throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
+    }
+}
+function parse(text, options) {
+    const ejsonOptions = {
+        useBigInt64: options?.useBigInt64 ?? false,
+        relaxed: options?.relaxed ?? true,
+        legacy: options?.legacy ?? false
+    };
+    return JSON.parse(text, (key, value) => {
+        if (key.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
+        }
+        return deserializeValue(value, ejsonOptions);
+    });
+}
+function stringify(value, replacer, space, options) {
+    if (space != null && typeof space === 'object') {
+        options = space;
+        space = 0;
+    }
+    if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
+        options = replacer;
+        replacer = undefined;
+        space = 0;
+    }
+    const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
+        seenObjects: [{ propertyName: '(root)', obj: null }]
+    });
+    const doc = serializeValue(value, serializeOptions);
+    return JSON.stringify(doc, replacer, space);
+}
+function EJSONserialize(value, options) {
+    options = options || {};
+    return JSON.parse(stringify(value, options));
+}
+function EJSONdeserialize(ejson, options) {
+    options = options || {};
+    return parse(JSON.stringify(ejson), options);
+}
+const EJSON = Object.create(null);
+EJSON.parse = parse;
+EJSON.stringify = stringify;
+EJSON.serialize = EJSONserialize;
+EJSON.deserialize = EJSONdeserialize;
+Object.freeze(EJSON);
+
+const BSONElementType = {
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: 255,
+    maxKey: 127
+};
+function getSize(source, offset) {
+    try {
+        return NumberUtils.getNonnegativeInt32LE(source, offset);
+    }
+    catch (cause) {
+        throw new BSONOffsetError('BSON size cannot be negative', offset, { cause });
+    }
+}
+function findNull(bytes, offset) {
+    let nullTerminatorOffset = offset;
+    for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++)
+        ;
+    if (nullTerminatorOffset === bytes.length - 1) {
+        throw new BSONOffsetError('Null terminator not found', offset);
+    }
+    return nullTerminatorOffset;
+}
+function parseToElements(bytes, startOffset = 0) {
+    startOffset ??= 0;
+    if (bytes.length < 5) {
+        throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
+    }
+    const documentSize = getSize(bytes, startOffset);
+    if (documentSize > bytes.length - startOffset) {
+        throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
+    }
+    if (bytes[startOffset + documentSize - 1] !== 0x00) {
+        throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize);
+    }
+    const elements = [];
+    let offset = startOffset + 4;
+    while (offset <= documentSize + startOffset) {
+        const type = bytes[offset];
+        offset += 1;
+        if (type === 0) {
+            if (offset - startOffset !== documentSize) {
+                throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
+            }
+            break;
+        }
+        const nameOffset = offset;
+        const nameLength = findNull(bytes, offset) - nameOffset;
+        offset += nameLength + 1;
+        let length;
+        if (type === BSONElementType.double ||
+            type === BSONElementType.long ||
+            type === BSONElementType.date ||
+            type === BSONElementType.timestamp) {
+            length = 8;
+        }
+        else if (type === BSONElementType.int) {
+            length = 4;
+        }
+        else if (type === BSONElementType.objectId) {
+            length = 12;
+        }
+        else if (type === BSONElementType.decimal) {
+            length = 16;
+        }
+        else if (type === BSONElementType.bool) {
+            length = 1;
+        }
+        else if (type === BSONElementType.null ||
+            type === BSONElementType.undefined ||
+            type === BSONElementType.maxKey ||
+            type === BSONElementType.minKey) {
+            length = 0;
+        }
+        else if (type === BSONElementType.regex) {
+            length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
+        }
+        else if (type === BSONElementType.object ||
+            type === BSONElementType.array ||
+            type === BSONElementType.javascriptWithScope) {
+            length = getSize(bytes, offset);
+        }
+        else if (type === BSONElementType.string ||
+            type === BSONElementType.binData ||
+            type === BSONElementType.dbPointer ||
+            type === BSONElementType.javascript ||
+            type === BSONElementType.symbol) {
+            length = getSize(bytes, offset) + 4;
+            if (type === BSONElementType.binData) {
+                length += 1;
+            }
+            if (type === BSONElementType.dbPointer) {
+                length += 12;
+            }
+        }
+        else {
+            throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset);
+        }
+        if (length > documentSize) {
+            throw new BSONOffsetError('value reports length larger than document', offset);
+        }
+        elements.push([type, nameOffset, nameLength, offset, length]);
+        offset += length;
+    }
+    return elements;
+}
+
+const onDemand = Object.create(null);
+onDemand.parseToElements = parseToElements;
+onDemand.ByteUtils = ByteUtils;
+onDemand.NumberUtils = NumberUtils;
+Object.freeze(onDemand);
+
+const MAXSIZE = 1024 * 1024 * 17;
+let buffer = ByteUtils.allocate(MAXSIZE);
+function setInternalBufferSize(size) {
+    if (buffer.length < size) {
+        buffer = ByteUtils.allocate(size);
+    }
+}
+function serialize(object, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
+    if (buffer.length < minInternalBufferSize) {
+        buffer = ByteUtils.allocate(minInternalBufferSize);
+    }
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex);
+    finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
+    return finishedBuffer;
+}
+function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const startIndex = typeof options.index === 'number' ? options.index : 0;
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
+    return startIndex + serializationIndex - 1;
+}
+function deserialize(buffer, options = {}) {
+    return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
+}
+function calculateObjectSize(object, options = {}) {
+    options = options || {};
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
+}
+function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
+    const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
+    const bufferData = ByteUtils.toLocalBufferType(data);
+    let index = startIndex;
+    for (let i = 0; i < numberOfDocuments; i++) {
+        const size = NumberUtils.getInt32LE(bufferData, index);
+        internalOptions.index = index;
+        documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
+        index = index + size;
+    }
+    return index;
+}
+
+var bson = /*#__PURE__*/Object.freeze({
+    __proto__: null,
+    BSONError: BSONError,
+    BSONOffsetError: BSONOffsetError,
+    BSONRegExp: BSONRegExp,
+    BSONRuntimeError: BSONRuntimeError,
+    BSONSymbol: BSONSymbol,
+    BSONType: BSONType,
+    BSONValue: BSONValue,
+    BSONVersionError: BSONVersionError,
+    Binary: Binary,
+    Code: Code,
+    DBRef: DBRef,
+    Decimal128: Decimal128,
+    Double: Double,
+    EJSON: EJSON,
+    Int32: Int32,
+    Long: Long,
+    MaxKey: MaxKey,
+    MinKey: MinKey,
+    ObjectId: ObjectId,
+    Timestamp: Timestamp,
+    UUID: UUID,
+    bsonType: bsonType,
+    calculateObjectSize: calculateObjectSize,
+    deserialize: deserialize,
+    deserializeStream: deserializeStream,
+    onDemand: onDemand,
+    serialize: serialize,
+    serializeWithBufferAndIndex: serializeWithBufferAndIndex,
+    setInternalBufferSize: setInternalBufferSize
+});
+
+export { bson as BSON, BSONError, BSONOffsetError, BSONRegExp, BSONRuntimeError, BSONSymbol, BSONType, BSONValue, BSONVersionError, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, MaxKey, MinKey, ObjectId, Timestamp, UUID, bsonType, calculateObjectSize, deserialize, deserializeStream, onDemand, serialize, serializeWithBufferAndIndex, setInternalBufferSize };
+//# sourceMappingURL=bson.node.mjs.map

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
node_modules/bson/lib/bson.node.mjs.map


+ 4680 - 0
node_modules/bson/lib/bson.rn.cjs

@@ -0,0 +1,4680 @@
+'use strict';
+
+const TypedArrayPrototypeGetSymbolToStringTag = (() => {
+    const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
+    return (value) => g.call(value);
+})();
+function isUint8Array(value) {
+    return TypedArrayPrototypeGetSymbolToStringTag(value) === 'Uint8Array';
+}
+function isAnyArrayBuffer(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        (value[Symbol.toStringTag] === 'ArrayBuffer' ||
+            value[Symbol.toStringTag] === 'SharedArrayBuffer'));
+}
+function isRegExp(regexp) {
+    return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === '[object RegExp]';
+}
+function isMap(value) {
+    return (typeof value === 'object' &&
+        value != null &&
+        Symbol.toStringTag in value &&
+        value[Symbol.toStringTag] === 'Map');
+}
+function isDate(date) {
+    return date instanceof Date || Object.prototype.toString.call(date) === '[object Date]';
+}
+function defaultInspect(x, _options) {
+    return JSON.stringify(x, (k, v) => {
+        if (typeof v === 'bigint') {
+            return { $numberLong: `${v}` };
+        }
+        else if (isMap(v)) {
+            return Object.fromEntries(v);
+        }
+        return v;
+    });
+}
+function getStylizeFunction(options) {
+    const stylizeExists = options != null &&
+        typeof options === 'object' &&
+        'stylize' in options &&
+        typeof options.stylize === 'function';
+    if (stylizeExists) {
+        return options.stylize;
+    }
+}
+
+const BSON_MAJOR_VERSION = 7;
+const BSON_VERSION_SYMBOL = Symbol.for('@@mdb.bson.version');
+const BSON_INT32_MAX = 0x7fffffff;
+const BSON_INT32_MIN = -0x80000000;
+const BSON_INT64_MAX = Math.pow(2, 63) - 1;
+const BSON_INT64_MIN = -Math.pow(2, 63);
+const JS_INT_MAX = Math.pow(2, 53);
+const JS_INT_MIN = -Math.pow(2, 53);
+const BSON_DATA_NUMBER = 1;
+const BSON_DATA_STRING = 2;
+const BSON_DATA_OBJECT = 3;
+const BSON_DATA_ARRAY = 4;
+const BSON_DATA_BINARY = 5;
+const BSON_DATA_UNDEFINED = 6;
+const BSON_DATA_OID = 7;
+const BSON_DATA_BOOLEAN = 8;
+const BSON_DATA_DATE = 9;
+const BSON_DATA_NULL = 10;
+const BSON_DATA_REGEXP = 11;
+const BSON_DATA_DBPOINTER = 12;
+const BSON_DATA_CODE = 13;
+const BSON_DATA_SYMBOL = 14;
+const BSON_DATA_CODE_W_SCOPE = 15;
+const BSON_DATA_INT = 16;
+const BSON_DATA_TIMESTAMP = 17;
+const BSON_DATA_LONG = 18;
+const BSON_DATA_DECIMAL128 = 19;
+const BSON_DATA_MIN_KEY = 0xff;
+const BSON_DATA_MAX_KEY = 0x7f;
+const BSON_BINARY_SUBTYPE_DEFAULT = 0;
+const BSON_BINARY_SUBTYPE_FUNCTION = 1;
+const BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
+const BSON_BINARY_SUBTYPE_UUID = 3;
+const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
+const BSON_BINARY_SUBTYPE_MD5 = 5;
+const BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
+const BSON_BINARY_SUBTYPE_COLUMN = 7;
+const BSON_BINARY_SUBTYPE_SENSITIVE = 8;
+const BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
+const BSONType = Object.freeze({
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: -1,
+    maxKey: 127
+});
+
+class BSONError extends Error {
+    get bsonError() {
+        return true;
+    }
+    get name() {
+        return 'BSONError';
+    }
+    constructor(message, options) {
+        super(message, options);
+    }
+    static isBSONError(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            'bsonError' in value &&
+            value.bsonError === true &&
+            'name' in value &&
+            'message' in value &&
+            'stack' in value);
+    }
+}
+class BSONVersionError extends BSONError {
+    get name() {
+        return 'BSONVersionError';
+    }
+    constructor() {
+        super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
+    }
+}
+class BSONRuntimeError extends BSONError {
+    get name() {
+        return 'BSONRuntimeError';
+    }
+    constructor(message) {
+        super(message);
+    }
+}
+class BSONOffsetError extends BSONError {
+    get name() {
+        return 'BSONOffsetError';
+    }
+    offset;
+    constructor(message, offset, options) {
+        super(`${message}. offset: ${offset}`, options);
+        this.offset = offset;
+    }
+}
+
+let TextDecoderFatal;
+let TextDecoderNonFatal;
+function parseUtf8(buffer, start, end, fatal) {
+    if (fatal) {
+        TextDecoderFatal ??= new TextDecoder('utf8', { fatal: true });
+        try {
+            return TextDecoderFatal.decode(buffer.subarray(start, end));
+        }
+        catch (cause) {
+            throw new BSONError('Invalid UTF-8 string in BSON document', { cause });
+        }
+    }
+    TextDecoderNonFatal ??= new TextDecoder('utf8', { fatal: false });
+    return TextDecoderNonFatal.decode(buffer.subarray(start, end));
+}
+
+function tryReadBasicLatin(uint8array, start, end) {
+    if (uint8array.length === 0) {
+        return '';
+    }
+    const stringByteLength = end - start;
+    if (stringByteLength === 0) {
+        return '';
+    }
+    if (stringByteLength > 20) {
+        return null;
+    }
+    if (stringByteLength === 1 && uint8array[start] < 128) {
+        return String.fromCharCode(uint8array[start]);
+    }
+    if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
+        return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
+    }
+    if (stringByteLength === 3 &&
+        uint8array[start] < 128 &&
+        uint8array[start + 1] < 128 &&
+        uint8array[start + 2] < 128) {
+        return (String.fromCharCode(uint8array[start]) +
+            String.fromCharCode(uint8array[start + 1]) +
+            String.fromCharCode(uint8array[start + 2]));
+    }
+    const latinBytes = [];
+    for (let i = start; i < end; i++) {
+        const byte = uint8array[i];
+        if (byte > 127) {
+            return null;
+        }
+        latinBytes.push(byte);
+    }
+    return String.fromCharCode(...latinBytes);
+}
+function tryWriteBasicLatin(destination, source, offset) {
+    if (source.length === 0)
+        return 0;
+    if (source.length > 25)
+        return null;
+    if (destination.length - offset < source.length)
+        return null;
+    for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
+        const char = source.charCodeAt(charOffset);
+        if (char > 127)
+            return null;
+        destination[destinationOffset] = char;
+    }
+    return source.length;
+}
+
+function nodejsMathRandomBytes(byteLength) {
+    return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+function nodejsSecureRandomBytes(byteLength) {
+    return crypto.getRandomValues(nodeJsByteUtils.allocate(byteLength));
+}
+const nodejsRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return nodejsSecureRandomBytes;
+    }
+    else {
+        return nodejsMathRandomBytes;
+    }
+})();
+const nodeJsByteUtils = {
+    toLocalBufferType(potentialBuffer) {
+        if (Buffer.isBuffer(potentialBuffer)) {
+            return potentialBuffer;
+        }
+        if (ArrayBuffer.isView(potentialBuffer)) {
+            return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
+        }
+        const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return Buffer.from(potentialBuffer);
+        }
+        throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);
+    },
+    allocate(size) {
+        return Buffer.alloc(size);
+    },
+    allocateUnsafe(size) {
+        return Buffer.allocUnsafe(size);
+    },
+    equals(a, b) {
+        return nodeJsByteUtils.toLocalBufferType(a).equals(b);
+    },
+    fromNumberArray(array) {
+        return Buffer.from(array);
+    },
+    fromBase64(base64) {
+        return Buffer.from(base64, 'base64');
+    },
+    toBase64(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');
+    },
+    fromISO88591(codePoints) {
+        return Buffer.from(codePoints, 'binary');
+    },
+    toISO88591(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');
+    },
+    fromHex(hex) {
+        return Buffer.from(hex, 'hex');
+    },
+    toHex(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');
+    },
+    toUTF8(buffer, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
+        if (fatal) {
+            for (let i = 0; i < string.length; i++) {
+                if (string.charCodeAt(i) === 0xfffd) {
+                    parseUtf8(buffer, start, end, true);
+                    break;
+                }
+            }
+        }
+        return string;
+    },
+    utf8ByteLength(input) {
+        return Buffer.byteLength(input, 'utf8');
+    },
+    encodeUTF8Into(buffer, source, byteOffset) {
+        const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset);
+        if (latinBytesWritten != null) {
+            return latinBytesWritten;
+        }
+        return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
+    },
+    randomBytes: nodejsRandomBytes,
+    swap32(buffer) {
+        return nodeJsByteUtils.toLocalBufferType(buffer).swap32();
+    }
+};
+
+function isReactNative() {
+    const { navigator } = globalThis;
+    return typeof navigator === 'object' && navigator.product === 'ReactNative';
+}
+function webMathRandomBytes(byteLength) {
+    if (byteLength < 0) {
+        throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
+    }
+    return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
+}
+const webRandomBytes = (() => {
+    const { crypto } = globalThis;
+    if (crypto != null && typeof crypto.getRandomValues === 'function') {
+        return (byteLength) => {
+            return crypto.getRandomValues(webByteUtils.allocate(byteLength));
+        };
+    }
+    else {
+        if (isReactNative()) {
+            const { console } = globalThis;
+            console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');
+        }
+        return webMathRandomBytes;
+    }
+})();
+const HEX_DIGIT = /(\d|[a-f])/i;
+const webByteUtils = {
+    toLocalBufferType(potentialUint8array) {
+        const stringTag = potentialUint8array?.[Symbol.toStringTag] ??
+            Object.prototype.toString.call(potentialUint8array);
+        if (stringTag === 'Uint8Array') {
+            return potentialUint8array;
+        }
+        if (ArrayBuffer.isView(potentialUint8array)) {
+            return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
+        }
+        if (stringTag === 'ArrayBuffer' ||
+            stringTag === 'SharedArrayBuffer' ||
+            stringTag === '[object ArrayBuffer]' ||
+            stringTag === '[object SharedArrayBuffer]') {
+            return new Uint8Array(potentialUint8array);
+        }
+        throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);
+    },
+    allocate(size) {
+        if (typeof size !== 'number') {
+            throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
+        }
+        return new Uint8Array(size);
+    },
+    allocateUnsafe(size) {
+        return webByteUtils.allocate(size);
+    },
+    equals(a, b) {
+        if (a.byteLength !== b.byteLength) {
+            return false;
+        }
+        for (let i = 0; i < a.byteLength; i++) {
+            if (a[i] !== b[i]) {
+                return false;
+            }
+        }
+        return true;
+    },
+    fromNumberArray(array) {
+        return Uint8Array.from(array);
+    },
+    fromBase64(base64) {
+        return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
+    },
+    toBase64(uint8array) {
+        return btoa(webByteUtils.toISO88591(uint8array));
+    },
+    fromISO88591(codePoints) {
+        return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);
+    },
+    toISO88591(uint8array) {
+        return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');
+    },
+    fromHex(hex) {
+        const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
+        const buffer = [];
+        for (let i = 0; i < evenLengthHex.length; i += 2) {
+            const firstDigit = evenLengthHex[i];
+            const secondDigit = evenLengthHex[i + 1];
+            if (!HEX_DIGIT.test(firstDigit)) {
+                break;
+            }
+            if (!HEX_DIGIT.test(secondDigit)) {
+                break;
+            }
+            const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
+            buffer.push(hexDigit);
+        }
+        return Uint8Array.from(buffer);
+    },
+    toHex(uint8array) {
+        return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
+    },
+    toUTF8(uint8array, start, end, fatal) {
+        const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
+        if (basicLatin != null) {
+            return basicLatin;
+        }
+        return parseUtf8(uint8array, start, end, fatal);
+    },
+    utf8ByteLength(input) {
+        return new TextEncoder().encode(input).byteLength;
+    },
+    encodeUTF8Into(uint8array, source, byteOffset) {
+        const bytes = new TextEncoder().encode(source);
+        uint8array.set(bytes, byteOffset);
+        return bytes.byteLength;
+    },
+    randomBytes: webRandomBytes,
+    swap32(buffer) {
+        if (buffer.length % 4 !== 0) {
+            throw new RangeError('Buffer size must be a multiple of 32-bits');
+        }
+        for (let i = 0; i < buffer.length; i += 4) {
+            const byte0 = buffer[i];
+            const byte1 = buffer[i + 1];
+            const byte2 = buffer[i + 2];
+            const byte3 = buffer[i + 3];
+            buffer[i] = byte3;
+            buffer[i + 1] = byte2;
+            buffer[i + 2] = byte1;
+            buffer[i + 3] = byte0;
+        }
+        return buffer;
+    }
+};
+
+const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
+const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
+
+const bsonType = Symbol.for('@@mdb.bson.type');
+class BSONValue {
+    get [bsonType]() {
+        return this._bsontype;
+    }
+    get [BSON_VERSION_SYMBOL]() {
+        return BSON_MAJOR_VERSION;
+    }
+    [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) {
+        return this.inspect(depth, options, inspect);
+    }
+}
+
+const FLOAT = new Float64Array(1);
+const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
+FLOAT[0] = -1;
+const isBigEndian = FLOAT_BYTES[7] === 0;
+const NumberUtils = {
+    isBigEndian,
+    getNonnegativeInt32LE(source, offset) {
+        if (source[offset + 3] > 127) {
+            throw new RangeError(`Size cannot be negative at offset: ${offset}`);
+        }
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getInt32LE(source, offset) {
+        return (source[offset] |
+            (source[offset + 1] << 8) |
+            (source[offset + 2] << 16) |
+            (source[offset + 3] << 24));
+    },
+    getUint32LE(source, offset) {
+        return (source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+    },
+    getUint32BE(source, offset) {
+        return (source[offset + 3] +
+            source[offset + 2] * 256 +
+            source[offset + 1] * 65536 +
+            source[offset] * 16777216);
+    },
+    getBigInt64LE(source, offset) {
+        const hi = BigInt(source[offset + 4] +
+            source[offset + 5] * 256 +
+            source[offset + 6] * 65536 +
+            (source[offset + 7] << 24));
+        const lo = BigInt(source[offset] +
+            source[offset + 1] * 256 +
+            source[offset + 2] * 65536 +
+            source[offset + 3] * 16777216);
+        return (hi << 32n) + lo;
+    },
+    getFloat64LE: isBigEndian
+        ? (source, offset) => {
+            FLOAT_BYTES[7] = source[offset];
+            FLOAT_BYTES[6] = source[offset + 1];
+            FLOAT_BYTES[5] = source[offset + 2];
+            FLOAT_BYTES[4] = source[offset + 3];
+            FLOAT_BYTES[3] = source[offset + 4];
+            FLOAT_BYTES[2] = source[offset + 5];
+            FLOAT_BYTES[1] = source[offset + 6];
+            FLOAT_BYTES[0] = source[offset + 7];
+            return FLOAT[0];
+        }
+        : (source, offset) => {
+            FLOAT_BYTES[0] = source[offset];
+            FLOAT_BYTES[1] = source[offset + 1];
+            FLOAT_BYTES[2] = source[offset + 2];
+            FLOAT_BYTES[3] = source[offset + 3];
+            FLOAT_BYTES[4] = source[offset + 4];
+            FLOAT_BYTES[5] = source[offset + 5];
+            FLOAT_BYTES[6] = source[offset + 6];
+            FLOAT_BYTES[7] = source[offset + 7];
+            return FLOAT[0];
+        },
+    setInt32BE(destination, offset, value) {
+        destination[offset + 3] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset] = value;
+        return 4;
+    },
+    setInt32LE(destination, offset, value) {
+        destination[offset] = value;
+        value >>>= 8;
+        destination[offset + 1] = value;
+        value >>>= 8;
+        destination[offset + 2] = value;
+        value >>>= 8;
+        destination[offset + 3] = value;
+        return 4;
+    },
+    setBigInt64LE(destination, offset, value) {
+        const mask32bits = 0xffffffffn;
+        let lo = Number(value & mask32bits);
+        destination[offset] = lo;
+        lo >>= 8;
+        destination[offset + 1] = lo;
+        lo >>= 8;
+        destination[offset + 2] = lo;
+        lo >>= 8;
+        destination[offset + 3] = lo;
+        let hi = Number((value >> 32n) & mask32bits);
+        destination[offset + 4] = hi;
+        hi >>= 8;
+        destination[offset + 5] = hi;
+        hi >>= 8;
+        destination[offset + 6] = hi;
+        hi >>= 8;
+        destination[offset + 7] = hi;
+        return 8;
+    },
+    setFloat64LE: isBigEndian
+        ? (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[7];
+            destination[offset + 1] = FLOAT_BYTES[6];
+            destination[offset + 2] = FLOAT_BYTES[5];
+            destination[offset + 3] = FLOAT_BYTES[4];
+            destination[offset + 4] = FLOAT_BYTES[3];
+            destination[offset + 5] = FLOAT_BYTES[2];
+            destination[offset + 6] = FLOAT_BYTES[1];
+            destination[offset + 7] = FLOAT_BYTES[0];
+            return 8;
+        }
+        : (destination, offset, value) => {
+            FLOAT[0] = value;
+            destination[offset] = FLOAT_BYTES[0];
+            destination[offset + 1] = FLOAT_BYTES[1];
+            destination[offset + 2] = FLOAT_BYTES[2];
+            destination[offset + 3] = FLOAT_BYTES[3];
+            destination[offset + 4] = FLOAT_BYTES[4];
+            destination[offset + 5] = FLOAT_BYTES[5];
+            destination[offset + 6] = FLOAT_BYTES[6];
+            destination[offset + 7] = FLOAT_BYTES[7];
+            return 8;
+        }
+};
+
+class Binary extends BSONValue {
+    get _bsontype() {
+        return 'Binary';
+    }
+    static BSON_BINARY_SUBTYPE_DEFAULT = 0;
+    static BUFFER_SIZE = 256;
+    static SUBTYPE_DEFAULT = 0;
+    static SUBTYPE_FUNCTION = 1;
+    static SUBTYPE_BYTE_ARRAY = 2;
+    static SUBTYPE_UUID_OLD = 3;
+    static SUBTYPE_UUID = 4;
+    static SUBTYPE_MD5 = 5;
+    static SUBTYPE_ENCRYPTED = 6;
+    static SUBTYPE_COLUMN = 7;
+    static SUBTYPE_SENSITIVE = 8;
+    static SUBTYPE_VECTOR = 9;
+    static SUBTYPE_USER_DEFINED = 128;
+    static VECTOR_TYPE = Object.freeze({
+        Int8: 0x03,
+        Float32: 0x27,
+        PackedBit: 0x10
+    });
+    buffer;
+    sub_type;
+    position;
+    constructor(buffer, subType) {
+        super();
+        if (!(buffer == null) &&
+            typeof buffer === 'string' &&
+            !ArrayBuffer.isView(buffer) &&
+            !isAnyArrayBuffer(buffer) &&
+            !Array.isArray(buffer)) {
+            throw new BSONError('Binary can only be constructed from Uint8Array or number[]');
+        }
+        this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
+        if (buffer == null) {
+            this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
+            this.position = 0;
+        }
+        else {
+            this.buffer = Array.isArray(buffer)
+                ? ByteUtils.fromNumberArray(buffer)
+                : ByteUtils.toLocalBufferType(buffer);
+            this.position = this.buffer.byteLength;
+        }
+    }
+    put(byteValue) {
+        if (typeof byteValue === 'string' && byteValue.length !== 1) {
+            throw new BSONError('only accepts single character String');
+        }
+        else if (typeof byteValue !== 'number' && byteValue.length !== 1)
+            throw new BSONError('only accepts single character Uint8Array or Array');
+        let decodedByte;
+        if (typeof byteValue === 'string') {
+            decodedByte = byteValue.charCodeAt(0);
+        }
+        else if (typeof byteValue === 'number') {
+            decodedByte = byteValue;
+        }
+        else {
+            decodedByte = byteValue[0];
+        }
+        if (decodedByte < 0 || decodedByte > 255) {
+            throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
+        }
+        if (this.buffer.byteLength > this.position) {
+            this.buffer[this.position++] = decodedByte;
+        }
+        else {
+            const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+            this.buffer[this.position++] = decodedByte;
+        }
+    }
+    write(sequence, offset) {
+        offset = typeof offset === 'number' ? offset : this.position;
+        if (this.buffer.byteLength < offset + sequence.length) {
+            const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
+            newSpace.set(this.buffer, 0);
+            this.buffer = newSpace;
+        }
+        if (ArrayBuffer.isView(sequence)) {
+            this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
+            this.position =
+                offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
+        }
+        else if (typeof sequence === 'string') {
+            throw new BSONError('input cannot be string');
+        }
+    }
+    read(position, length) {
+        length = length && length > 0 ? length : this.position;
+        const end = position + length;
+        return this.buffer.subarray(position, end > this.position ? this.position : end);
+    }
+    value() {
+        return this.buffer.length === this.position
+            ? this.buffer
+            : this.buffer.subarray(0, this.position);
+    }
+    length() {
+        return this.position;
+    }
+    toJSON() {
+        return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.buffer.subarray(0, this.position));
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        if (encoding === 'utf8' || encoding === 'utf-8')
+            return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+        return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (this.sub_type === Binary.SUBTYPE_VECTOR) {
+            validateBinaryVector(this);
+        }
+        const base64String = ByteUtils.toBase64(this.buffer);
+        const subType = Number(this.sub_type).toString(16);
+        if (options.legacy) {
+            return {
+                $binary: base64String,
+                $type: subType.length === 1 ? '0' + subType : subType
+            };
+        }
+        return {
+            $binary: {
+                base64: base64String,
+                subType: subType.length === 1 ? '0' + subType : subType
+            }
+        };
+    }
+    toUUID() {
+        if (this.sub_type === Binary.SUBTYPE_UUID) {
+            return new UUID(this.buffer.subarray(0, this.position));
+        }
+        throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
+    }
+    static createFromHexString(hex, subType) {
+        return new Binary(ByteUtils.fromHex(hex), subType);
+    }
+    static createFromBase64(base64, subType) {
+        return new Binary(ByteUtils.fromBase64(base64), subType);
+    }
+    static fromExtendedJSON(doc, options) {
+        options = options || {};
+        let data;
+        let type;
+        if ('$binary' in doc) {
+            if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
+                type = doc.$type ? parseInt(doc.$type, 16) : 0;
+                data = ByteUtils.fromBase64(doc.$binary);
+            }
+            else {
+                if (typeof doc.$binary !== 'string') {
+                    type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
+                    data = ByteUtils.fromBase64(doc.$binary.base64);
+                }
+            }
+        }
+        else if ('$uuid' in doc) {
+            type = 4;
+            data = UUID.bytesFromString(doc.$uuid);
+        }
+        if (!data) {
+            throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
+        }
+        return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
+        const base64Arg = inspect(base64, options);
+        const subTypeArg = inspect(this.sub_type, options);
+        return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
+    }
+    toInt8Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {
+            throw new BSONError('Binary datatype field is not Int8');
+        }
+        validateBinaryVector(this);
+        return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toFloat32Array() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {
+            throw new BSONError('Binary datatype field is not Float32');
+        }
+        validateBinaryVector(this);
+        const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(floatBytes);
+        return new Float32Array(floatBytes.buffer);
+    }
+    toPackedBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
+    }
+    toBits() {
+        if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
+            throw new BSONError('Binary sub_type is not Vector');
+        }
+        if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
+            throw new BSONError('Binary datatype field is not packed bit');
+        }
+        validateBinaryVector(this);
+        const byteCount = this.length() - 2;
+        const bitCount = byteCount * 8 - this.buffer[1];
+        const bits = new Int8Array(bitCount);
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = (bitOffset / 8) | 0;
+            const byte = this.buffer[byteOffset + 2];
+            const shift = 7 - (bitOffset % 8);
+            const bit = (byte >> shift) & 1;
+            bits[bitOffset] = bit;
+        }
+        return bits;
+    }
+    static fromInt8Array(array) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.Int8;
+        buffer[1] = 0;
+        const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        buffer.set(intBytes, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromFloat32Array(array) {
+        const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
+        binaryBytes[0] = Binary.VECTOR_TYPE.Float32;
+        binaryBytes[1] = 0;
+        const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+        binaryBytes.set(floatBytes, 2);
+        if (NumberUtils.isBigEndian)
+            ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
+        const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromPackedBits(array, padding = 0) {
+        const buffer = ByteUtils.allocate(array.byteLength + 2);
+        buffer[0] = Binary.VECTOR_TYPE.PackedBit;
+        buffer[1] = padding;
+        buffer.set(array, 2);
+        const bin = new this(buffer, this.SUBTYPE_VECTOR);
+        validateBinaryVector(bin);
+        return bin;
+    }
+    static fromBits(bits) {
+        const byteLength = (bits.length + 7) >>> 3;
+        const bytes = new Uint8Array(byteLength + 2);
+        bytes[0] = Binary.VECTOR_TYPE.PackedBit;
+        const remainder = bits.length % 8;
+        bytes[1] = remainder === 0 ? 0 : 8 - remainder;
+        for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
+            const byteOffset = bitOffset >>> 3;
+            const bit = bits[bitOffset];
+            if (bit !== 0 && bit !== 1) {
+                throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
+            }
+            if (bit === 0)
+                continue;
+            const shift = 7 - (bitOffset % 8);
+            bytes[byteOffset + 2] |= bit << shift;
+        }
+        return new this(bytes, Binary.SUBTYPE_VECTOR);
+    }
+}
+function validateBinaryVector(vector) {
+    if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
+        return;
+    const size = vector.position;
+    const datatype = vector.buffer[0];
+    const padding = vector.buffer[1];
+    if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) &&
+        padding !== 0) {
+        throw new BSONError('Invalid Vector: padding must be zero for int8 and float32 vectors');
+    }
+    if (datatype === Binary.VECTOR_TYPE.Float32) {
+        if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
+            throw new BSONError('Invalid Vector: Float32 vector must contain a multiple of 4 bytes');
+        }
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
+        throw new BSONError('Invalid Vector: padding must be zero for packed bit vectors that are empty');
+    }
+    if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
+        throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
+    }
+}
+const UUID_BYTE_LENGTH = 16;
+const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
+const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
+class UUID extends Binary {
+    constructor(input) {
+        let bytes;
+        if (input == null) {
+            bytes = UUID.generate();
+        }
+        else if (input instanceof UUID) {
+            bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
+        }
+        else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
+            bytes = ByteUtils.toLocalBufferType(input);
+        }
+        else if (typeof input === 'string') {
+            bytes = UUID.bytesFromString(input);
+        }
+        else {
+            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).');
+        }
+        super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+    }
+    toHexString(includeDashes = true) {
+        if (includeDashes) {
+            return [
+                ByteUtils.toHex(this.buffer.subarray(0, 4)),
+                ByteUtils.toHex(this.buffer.subarray(4, 6)),
+                ByteUtils.toHex(this.buffer.subarray(6, 8)),
+                ByteUtils.toHex(this.buffer.subarray(8, 10)),
+                ByteUtils.toHex(this.buffer.subarray(10, 16))
+            ].join('-');
+        }
+        return ByteUtils.toHex(this.buffer);
+    }
+    toString(encoding) {
+        if (encoding === 'hex')
+            return ByteUtils.toHex(this.id);
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    equals(otherId) {
+        if (!otherId) {
+            return false;
+        }
+        if (otherId instanceof UUID) {
+            return ByteUtils.equals(otherId.id, this.id);
+        }
+        try {
+            return ByteUtils.equals(new UUID(otherId).id, this.id);
+        }
+        catch {
+            return false;
+        }
+    }
+    toBinary() {
+        return new Binary(this.id, Binary.SUBTYPE_UUID);
+    }
+    static generate() {
+        const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
+        bytes[6] = (bytes[6] & 0x0f) | 0x40;
+        bytes[8] = (bytes[8] & 0x3f) | 0x80;
+        return bytes;
+    }
+    static isValid(input) {
+        if (!input) {
+            return false;
+        }
+        if (typeof input === 'string') {
+            return UUID.isValidUUIDString(input);
+        }
+        if (isUint8Array(input)) {
+            return input.byteLength === UUID_BYTE_LENGTH;
+        }
+        return (input._bsontype === 'Binary' &&
+            input.sub_type === this.SUBTYPE_UUID &&
+            input.buffer.byteLength === 16);
+    }
+    static createFromHexString(hexString) {
+        const buffer = UUID.bytesFromString(hexString);
+        return new UUID(buffer);
+    }
+    static createFromBase64(base64) {
+        return new UUID(ByteUtils.fromBase64(base64));
+    }
+    static bytesFromString(representation) {
+        if (!UUID.isValidUUIDString(representation)) {
+            throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
+        }
+        return ByteUtils.fromHex(representation.replace(/-/g, ''));
+    }
+    static isValidUUIDString(representation) {
+        return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new UUID(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+class Code extends BSONValue {
+    get _bsontype() {
+        return 'Code';
+    }
+    code;
+    scope;
+    constructor(code, scope) {
+        super();
+        this.code = code.toString();
+        this.scope = scope ?? null;
+    }
+    toJSON() {
+        if (this.scope != null) {
+            return { code: this.code, scope: this.scope };
+        }
+        return { code: this.code };
+    }
+    toExtendedJSON() {
+        if (this.scope) {
+            return { $code: this.code, $scope: this.scope };
+        }
+        return { $code: this.code };
+    }
+    static fromExtendedJSON(doc) {
+        return new Code(doc.$code, doc.$scope);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        let parametersString = inspect(this.code, options);
+        const multiLineFn = parametersString.includes('\n');
+        if (this.scope != null) {
+            parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
+        }
+        const endingNewline = multiLineFn && this.scope === null;
+        return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
+    }
+}
+
+function isDBRefLike(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '$id' in value &&
+        value.$id != null &&
+        '$ref' in value &&
+        typeof value.$ref === 'string' &&
+        (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));
+}
+class DBRef extends BSONValue {
+    get _bsontype() {
+        return 'DBRef';
+    }
+    collection;
+    oid;
+    db;
+    fields;
+    constructor(collection, oid, db, fields) {
+        super();
+        const parts = collection.split('.');
+        if (parts.length === 2) {
+            db = parts.shift();
+            collection = parts.shift();
+        }
+        this.collection = collection;
+        this.oid = oid;
+        this.db = db;
+        this.fields = fields || {};
+    }
+    get namespace() {
+        return this.collection;
+    }
+    set namespace(value) {
+        this.collection = value;
+    }
+    toJSON() {
+        const o = Object.assign({
+            $ref: this.collection,
+            $id: this.oid
+        }, this.fields);
+        if (this.db != null)
+            o.$db = this.db;
+        return o;
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        let o = {
+            $ref: this.collection,
+            $id: this.oid
+        };
+        if (options.legacy) {
+            return o;
+        }
+        if (this.db)
+            o.$db = this.db;
+        o = Object.assign(o, this.fields);
+        return o;
+    }
+    static fromExtendedJSON(doc) {
+        const copy = Object.assign({}, doc);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const args = [
+            inspect(this.namespace, options),
+            inspect(this.oid, options),
+            ...(this.db ? [inspect(this.db, options)] : []),
+            ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
+        ];
+        args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
+        return `new DBRef(${args.join(', ')})`;
+    }
+}
+
+function removeLeadingZerosAndExplicitPlus(str) {
+    if (str === '') {
+        return str;
+    }
+    let startIndex = 0;
+    const isNegative = str[startIndex] === '-';
+    const isExplicitlyPositive = str[startIndex] === '+';
+    if (isExplicitlyPositive || isNegative) {
+        startIndex += 1;
+    }
+    let foundInsignificantZero = false;
+    for (; startIndex < str.length && str[startIndex] === '0'; ++startIndex) {
+        foundInsignificantZero = true;
+    }
+    if (!foundInsignificantZero) {
+        return isExplicitlyPositive ? str.slice(1) : str;
+    }
+    return `${isNegative ? '-' : ''}${str.length === startIndex ? '0' : str.slice(startIndex)}`;
+}
+function validateStringCharacters(str, radix) {
+    radix = radix ?? 10;
+    const validCharacters = '0123456789abcdefghijklmnopqrstuvwxyz'.slice(0, radix);
+    const regex = new RegExp(`[^-+${validCharacters}]`, 'i');
+    return regex.test(str) ? false : str;
+}
+
+let wasm = undefined;
+try {
+    wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
+}
+catch {
+}
+const TWO_PWR_16_DBL = 1 << 16;
+const TWO_PWR_24_DBL = 1 << 24;
+const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
+const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
+const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
+const INT_CACHE = {};
+const UINT_CACHE = {};
+const MAX_INT64_STRING_LENGTH = 20;
+const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
+class Long extends BSONValue {
+    get _bsontype() {
+        return 'Long';
+    }
+    get __isLong__() {
+        return true;
+    }
+    high;
+    low;
+    unsigned;
+    constructor(lowOrValue = 0, highOrUnsigned, unsigned) {
+        super();
+        const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);
+        const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;
+        const res = typeof lowOrValue === 'string'
+            ? Long.fromString(lowOrValue, unsignedBool)
+            : typeof lowOrValue === 'bigint'
+                ? Long.fromBigInt(lowOrValue, unsignedBool)
+                : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
+        this.low = res.low;
+        this.high = res.high;
+        this.unsigned = res.unsigned;
+    }
+    static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
+    static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
+    static ZERO = Long.fromInt(0);
+    static UZERO = Long.fromInt(0, true);
+    static ONE = Long.fromInt(1);
+    static UONE = Long.fromInt(1, true);
+    static NEG_ONE = Long.fromInt(-1);
+    static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
+    static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
+    static fromBits(lowBits, highBits, unsigned) {
+        return new Long(lowBits, highBits, unsigned);
+    }
+    static fromInt(value, unsigned) {
+        let obj, cachedObj, cache;
+        if (unsigned) {
+            value >>>= 0;
+            if ((cache = 0 <= value && value < 256)) {
+                cachedObj = UINT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
+            if (cache)
+                UINT_CACHE[value] = obj;
+            return obj;
+        }
+        else {
+            value |= 0;
+            if ((cache = -128 <= value && value < 128)) {
+                cachedObj = INT_CACHE[value];
+                if (cachedObj)
+                    return cachedObj;
+            }
+            obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
+            if (cache)
+                INT_CACHE[value] = obj;
+            return obj;
+        }
+    }
+    static fromNumber(value, unsigned) {
+        if (isNaN(value))
+            return unsigned ? Long.UZERO : Long.ZERO;
+        if (unsigned) {
+            if (value < 0)
+                return Long.UZERO;
+            if (value >= TWO_PWR_64_DBL)
+                return Long.MAX_UNSIGNED_VALUE;
+        }
+        else {
+            if (value <= -TWO_PWR_63_DBL)
+                return Long.MIN_VALUE;
+            if (value + 1 >= TWO_PWR_63_DBL)
+                return Long.MAX_VALUE;
+        }
+        if (value < 0)
+            return Long.fromNumber(-value, unsigned).neg();
+        return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
+    }
+    static fromBigInt(value, unsigned) {
+        const FROM_BIGINT_BIT_MASK = 0xffffffffn;
+        const FROM_BIGINT_BIT_SHIFT = 32n;
+        return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number((value >> FROM_BIGINT_BIT_SHIFT) & FROM_BIGINT_BIT_MASK), unsigned);
+    }
+    static _fromString(str, unsigned, radix) {
+        if (str.length === 0)
+            throw new BSONError('empty string');
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        let p;
+        if ((p = str.indexOf('-')) > 0)
+            throw new BSONError('interior hyphen');
+        else if (p === 0) {
+            return Long._fromString(str.substring(1), unsigned, radix).neg();
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 8));
+        let result = Long.ZERO;
+        for (let i = 0; i < str.length; i += 8) {
+            const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
+            if (size < 8) {
+                const power = Long.fromNumber(Math.pow(radix, size));
+                result = result.mul(power).add(Long.fromNumber(value));
+            }
+            else {
+                result = result.mul(radixToPower);
+                result = result.add(Long.fromNumber(value));
+            }
+        }
+        result.unsigned = unsigned;
+        return result;
+    }
+    static fromStringStrict(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str.trim() !== str) {
+            throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
+        }
+        if (!validateStringCharacters(str, radix)) {
+            throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
+        }
+        const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
+        const result = Long._fromString(cleanedStr, unsigned, radix);
+        if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
+            throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? 'an unsigned' : 'a signed'} 64-bit Long ${radix != null ? `with radix: ${radix}` : ''}`);
+        }
+        return result;
+    }
+    static fromString(str, unsignedOrRadix, radix) {
+        let unsigned = false;
+        if (typeof unsignedOrRadix === 'number') {
+            ((radix = unsignedOrRadix), (unsignedOrRadix = false));
+        }
+        else {
+            unsigned = !!unsignedOrRadix;
+        }
+        radix ??= 10;
+        if (str === 'NaN' && radix < 24) {
+            return Long.ZERO;
+        }
+        else if ((str === 'Infinity' || str === '+Infinity' || str === '-Infinity') && radix < 35) {
+            return Long.ZERO;
+        }
+        return Long._fromString(str, unsigned, radix);
+    }
+    static fromBytes(bytes, unsigned, le) {
+        return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
+    }
+    static fromBytesLE(bytes, unsigned) {
+        return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned);
+    }
+    static fromBytesBE(bytes, unsigned) {
+        return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned);
+    }
+    static isLong(value) {
+        return (value != null &&
+            typeof value === 'object' &&
+            '__isLong__' in value &&
+            value.__isLong__ === true);
+    }
+    static fromValue(val, unsigned) {
+        if (typeof val === 'number')
+            return Long.fromNumber(val, unsigned);
+        if (typeof val === 'string')
+            return Long.fromString(val, unsigned);
+        return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
+    }
+    add(addend) {
+        if (!Long.isLong(addend))
+            addend = Long.fromValue(addend);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = addend.high >>> 16;
+        const b32 = addend.high & 0xffff;
+        const b16 = addend.low >>> 16;
+        const b00 = addend.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 + b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 + b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 + b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 + b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    and(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
+    }
+    compare(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.eq(other))
+            return 0;
+        const thisNeg = this.isNegative(), otherNeg = other.isNegative();
+        if (thisNeg && !otherNeg)
+            return -1;
+        if (!thisNeg && otherNeg)
+            return 1;
+        if (!this.unsigned)
+            return this.sub(other).isNegative() ? -1 : 1;
+        return other.high >>> 0 > this.high >>> 0 ||
+            (other.high === this.high && other.low >>> 0 > this.low >>> 0)
+            ? -1
+            : 1;
+    }
+    comp(other) {
+        return this.compare(other);
+    }
+    divide(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (divisor.isZero())
+            throw new BSONError('division by zero');
+        if (wasm) {
+            if (!this.unsigned &&
+                this.high === -0x80000000 &&
+                divisor.low === -1 &&
+                divisor.high === -1) {
+                return this;
+            }
+            const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (this.isZero())
+            return this.unsigned ? Long.UZERO : Long.ZERO;
+        let approx, rem, res;
+        if (!this.unsigned) {
+            if (this.eq(Long.MIN_VALUE)) {
+                if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
+                    return Long.MIN_VALUE;
+                else if (divisor.eq(Long.MIN_VALUE))
+                    return Long.ONE;
+                else {
+                    const halfThis = this.shr(1);
+                    approx = halfThis.div(divisor).shl(1);
+                    if (approx.eq(Long.ZERO)) {
+                        return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
+                    }
+                    else {
+                        rem = this.sub(divisor.mul(approx));
+                        res = approx.add(rem.div(divisor));
+                        return res;
+                    }
+                }
+            }
+            else if (divisor.eq(Long.MIN_VALUE))
+                return this.unsigned ? Long.UZERO : Long.ZERO;
+            if (this.isNegative()) {
+                if (divisor.isNegative())
+                    return this.neg().div(divisor.neg());
+                return this.neg().div(divisor).neg();
+            }
+            else if (divisor.isNegative())
+                return this.div(divisor.neg()).neg();
+            res = Long.ZERO;
+        }
+        else {
+            if (!divisor.unsigned)
+                divisor = divisor.toUnsigned();
+            if (divisor.gt(this))
+                return Long.UZERO;
+            if (divisor.gt(this.shru(1)))
+                return Long.UONE;
+            res = Long.UZERO;
+        }
+        rem = this;
+        while (rem.gte(divisor)) {
+            approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
+            const log2 = Math.ceil(Math.log(approx) / Math.LN2);
+            const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
+            let approxRes = Long.fromNumber(approx);
+            let approxRem = approxRes.mul(divisor);
+            while (approxRem.isNegative() || approxRem.gt(rem)) {
+                approx -= delta;
+                approxRes = Long.fromNumber(approx, this.unsigned);
+                approxRem = approxRes.mul(divisor);
+            }
+            if (approxRes.isZero())
+                approxRes = Long.ONE;
+            res = res.add(approxRes);
+            rem = rem.sub(approxRem);
+        }
+        return res;
+    }
+    div(divisor) {
+        return this.divide(divisor);
+    }
+    equals(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
+            return false;
+        return this.high === other.high && this.low === other.low;
+    }
+    eq(other) {
+        return this.equals(other);
+    }
+    getHighBits() {
+        return this.high;
+    }
+    getHighBitsUnsigned() {
+        return this.high >>> 0;
+    }
+    getLowBits() {
+        return this.low;
+    }
+    getLowBitsUnsigned() {
+        return this.low >>> 0;
+    }
+    getNumBitsAbs() {
+        if (this.isNegative()) {
+            return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
+        }
+        const val = this.high !== 0 ? this.high : this.low;
+        let bit;
+        for (bit = 31; bit > 0; bit--)
+            if ((val & (1 << bit)) !== 0)
+                break;
+        return this.high !== 0 ? bit + 33 : bit + 1;
+    }
+    greaterThan(other) {
+        return this.comp(other) > 0;
+    }
+    gt(other) {
+        return this.greaterThan(other);
+    }
+    greaterThanOrEqual(other) {
+        return this.comp(other) >= 0;
+    }
+    gte(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    ge(other) {
+        return this.greaterThanOrEqual(other);
+    }
+    isEven() {
+        return (this.low & 1) === 0;
+    }
+    isNegative() {
+        return !this.unsigned && this.high < 0;
+    }
+    isOdd() {
+        return (this.low & 1) === 1;
+    }
+    isPositive() {
+        return this.unsigned || this.high >= 0;
+    }
+    isZero() {
+        return this.high === 0 && this.low === 0;
+    }
+    lessThan(other) {
+        return this.comp(other) < 0;
+    }
+    lt(other) {
+        return this.lessThan(other);
+    }
+    lessThanOrEqual(other) {
+        return this.comp(other) <= 0;
+    }
+    lte(other) {
+        return this.lessThanOrEqual(other);
+    }
+    modulo(divisor) {
+        if (!Long.isLong(divisor))
+            divisor = Long.fromValue(divisor);
+        if (wasm) {
+            const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        return this.sub(this.div(divisor).mul(divisor));
+    }
+    mod(divisor) {
+        return this.modulo(divisor);
+    }
+    rem(divisor) {
+        return this.modulo(divisor);
+    }
+    multiply(multiplier) {
+        if (this.isZero())
+            return Long.ZERO;
+        if (!Long.isLong(multiplier))
+            multiplier = Long.fromValue(multiplier);
+        if (wasm) {
+            const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
+            return Long.fromBits(low, wasm.get_high(), this.unsigned);
+        }
+        if (multiplier.isZero())
+            return Long.ZERO;
+        if (this.eq(Long.MIN_VALUE))
+            return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (multiplier.eq(Long.MIN_VALUE))
+            return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
+        if (this.isNegative()) {
+            if (multiplier.isNegative())
+                return this.neg().mul(multiplier.neg());
+            else
+                return this.neg().mul(multiplier).neg();
+        }
+        else if (multiplier.isNegative())
+            return this.mul(multiplier.neg()).neg();
+        if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
+            return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
+        const a48 = this.high >>> 16;
+        const a32 = this.high & 0xffff;
+        const a16 = this.low >>> 16;
+        const a00 = this.low & 0xffff;
+        const b48 = multiplier.high >>> 16;
+        const b32 = multiplier.high & 0xffff;
+        const b16 = multiplier.low >>> 16;
+        const b00 = multiplier.low & 0xffff;
+        let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
+        c00 += a00 * b00;
+        c16 += c00 >>> 16;
+        c00 &= 0xffff;
+        c16 += a16 * b00;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c16 += a00 * b16;
+        c32 += c16 >>> 16;
+        c16 &= 0xffff;
+        c32 += a32 * b00;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a16 * b16;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c32 += a00 * b32;
+        c48 += c32 >>> 16;
+        c32 &= 0xffff;
+        c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
+        c48 &= 0xffff;
+        return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
+    }
+    mul(multiplier) {
+        return this.multiply(multiplier);
+    }
+    negate() {
+        if (!this.unsigned && this.eq(Long.MIN_VALUE))
+            return Long.MIN_VALUE;
+        return this.not().add(Long.ONE);
+    }
+    neg() {
+        return this.negate();
+    }
+    not() {
+        return Long.fromBits(~this.low, ~this.high, this.unsigned);
+    }
+    notEquals(other) {
+        return !this.equals(other);
+    }
+    neq(other) {
+        return this.notEquals(other);
+    }
+    ne(other) {
+        return this.notEquals(other);
+    }
+    or(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
+    }
+    shiftLeft(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
+        else
+            return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
+    }
+    shl(numBits) {
+        return this.shiftLeft(numBits);
+    }
+    shiftRight(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        if ((numBits &= 63) === 0)
+            return this;
+        else if (numBits < 32)
+            return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
+        else
+            return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
+    }
+    shr(numBits) {
+        return this.shiftRight(numBits);
+    }
+    shiftRightUnsigned(numBits) {
+        if (Long.isLong(numBits))
+            numBits = numBits.toInt();
+        numBits &= 63;
+        if (numBits === 0)
+            return this;
+        else {
+            const high = this.high;
+            if (numBits < 32) {
+                const low = this.low;
+                return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
+            }
+            else if (numBits === 32)
+                return Long.fromBits(high, 0, this.unsigned);
+            else
+                return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
+        }
+    }
+    shr_u(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    shru(numBits) {
+        return this.shiftRightUnsigned(numBits);
+    }
+    subtract(subtrahend) {
+        if (!Long.isLong(subtrahend))
+            subtrahend = Long.fromValue(subtrahend);
+        return this.add(subtrahend.neg());
+    }
+    sub(subtrahend) {
+        return this.subtract(subtrahend);
+    }
+    toInt() {
+        return this.unsigned ? this.low >>> 0 : this.low;
+    }
+    toNumber() {
+        if (this.unsigned)
+            return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
+        return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
+    }
+    toBigInt() {
+        return BigInt(this.toString());
+    }
+    toBytes(le) {
+        return le ? this.toBytesLE() : this.toBytesBE();
+    }
+    toBytesLE() {
+        const hi = this.high, lo = this.low;
+        return [
+            lo & 0xff,
+            (lo >>> 8) & 0xff,
+            (lo >>> 16) & 0xff,
+            lo >>> 24,
+            hi & 0xff,
+            (hi >>> 8) & 0xff,
+            (hi >>> 16) & 0xff,
+            hi >>> 24
+        ];
+    }
+    toBytesBE() {
+        const hi = this.high, lo = this.low;
+        return [
+            hi >>> 24,
+            (hi >>> 16) & 0xff,
+            (hi >>> 8) & 0xff,
+            hi & 0xff,
+            lo >>> 24,
+            (lo >>> 16) & 0xff,
+            (lo >>> 8) & 0xff,
+            lo & 0xff
+        ];
+    }
+    toSigned() {
+        if (!this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, false);
+    }
+    toString(radix) {
+        radix = radix || 10;
+        if (radix < 2 || 36 < radix)
+            throw new BSONError('radix');
+        if (this.isZero())
+            return '0';
+        if (this.isNegative()) {
+            if (this.eq(Long.MIN_VALUE)) {
+                const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
+                return div.toString(radix) + rem1.toInt().toString(radix);
+            }
+            else
+                return '-' + this.neg().toString(radix);
+        }
+        const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
+        let rem = this;
+        let result = '';
+        while (true) {
+            const remDiv = rem.div(radixToPower);
+            const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
+            let digits = intval.toString(radix);
+            rem = remDiv;
+            if (rem.isZero()) {
+                return digits + result;
+            }
+            else {
+                while (digits.length < 6)
+                    digits = '0' + digits;
+                result = '' + digits + result;
+            }
+        }
+    }
+    toUnsigned() {
+        if (this.unsigned)
+            return this;
+        return Long.fromBits(this.low, this.high, true);
+    }
+    xor(other) {
+        if (!Long.isLong(other))
+            other = Long.fromValue(other);
+        return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
+    }
+    eqz() {
+        return this.isZero();
+    }
+    le(other) {
+        return this.lessThanOrEqual(other);
+    }
+    toExtendedJSON(options) {
+        if (options && options.relaxed)
+            return this.toNumber();
+        return { $numberLong: this.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        const { useBigInt64 = false, relaxed = true } = { ...options };
+        if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
+            throw new BSONError('$numberLong string is too long');
+        }
+        if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
+            throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
+        }
+        if (useBigInt64) {
+            const bigIntResult = BigInt(doc.$numberLong);
+            return BigInt.asIntN(64, bigIntResult);
+        }
+        const longResult = Long.fromString(doc.$numberLong);
+        if (relaxed) {
+            return longResult.toNumber();
+        }
+        return longResult;
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const longVal = inspect(this.toString(), options);
+        const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
+        return `new Long(${longVal}${unsignedVal})`;
+    }
+}
+
+const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
+const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
+const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
+const EXPONENT_MAX = 6111;
+const EXPONENT_MIN = -6176;
+const EXPONENT_BIAS = 6176;
+const MAX_DIGITS = 34;
+const NAN_BUFFER = ByteUtils.fromNumberArray([
+    0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
+    0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
+    0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+].reverse());
+const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
+const COMBINATION_MASK = 0x1f;
+const EXPONENT_MASK = 0x3fff;
+const COMBINATION_INFINITY = 30;
+const COMBINATION_NAN = 31;
+function isDigit(value) {
+    return !isNaN(parseInt(value, 10));
+}
+function divideu128(value) {
+    const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
+    let _rem = Long.fromNumber(0);
+    if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
+        return { quotient: value, rem: _rem };
+    }
+    for (let i = 0; i <= 3; i++) {
+        _rem = _rem.shiftLeft(32);
+        _rem = _rem.add(new Long(value.parts[i], 0));
+        value.parts[i] = _rem.div(DIVISOR).low;
+        _rem = _rem.modulo(DIVISOR);
+    }
+    return { quotient: value, rem: _rem };
+}
+function multiply64x2(left, right) {
+    if (!left && !right) {
+        return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
+    }
+    const leftHigh = left.shiftRightUnsigned(32);
+    const leftLow = new Long(left.getLowBits(), 0);
+    const rightHigh = right.shiftRightUnsigned(32);
+    const rightLow = new Long(right.getLowBits(), 0);
+    let productHigh = leftHigh.multiply(rightHigh);
+    let productMid = leftHigh.multiply(rightLow);
+    const productMid2 = leftLow.multiply(rightHigh);
+    let productLow = leftLow.multiply(rightLow);
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productMid = new Long(productMid.getLowBits(), 0)
+        .add(productMid2)
+        .add(productLow.shiftRightUnsigned(32));
+    productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
+    productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
+    return { high: productHigh, low: productLow };
+}
+function lessThan(left, right) {
+    const uhleft = left.high >>> 0;
+    const uhright = right.high >>> 0;
+    if (uhleft < uhright) {
+        return true;
+    }
+    else if (uhleft === uhright) {
+        const ulleft = left.low >>> 0;
+        const ulright = right.low >>> 0;
+        if (ulleft < ulright)
+            return true;
+    }
+    return false;
+}
+function invalidErr(string, message) {
+    throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
+}
+class Decimal128 extends BSONValue {
+    get _bsontype() {
+        return 'Decimal128';
+    }
+    bytes;
+    constructor(bytes) {
+        super();
+        if (typeof bytes === 'string') {
+            this.bytes = Decimal128.fromString(bytes).bytes;
+        }
+        else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
+            if (bytes.byteLength !== 16) {
+                throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
+            }
+            this.bytes = bytes;
+        }
+        else {
+            throw new BSONError('Decimal128 must take a Buffer or string');
+        }
+    }
+    static fromString(representation) {
+        return Decimal128._fromString(representation, { allowRounding: false });
+    }
+    static fromStringWithRounding(representation) {
+        return Decimal128._fromString(representation, { allowRounding: true });
+    }
+    static _fromString(representation, options) {
+        let isNegative = false;
+        let sawSign = false;
+        let sawRadix = false;
+        let foundNonZero = false;
+        let significantDigits = 0;
+        let nDigitsRead = 0;
+        let nDigits = 0;
+        let radixPosition = 0;
+        let firstNonZero = 0;
+        const digits = [0];
+        let nDigitsStored = 0;
+        let digitsInsert = 0;
+        let lastDigit = 0;
+        let exponent = 0;
+        let significandHigh = new Long(0, 0);
+        let significandLow = new Long(0, 0);
+        let biasedExponent = 0;
+        let index = 0;
+        if (representation.length >= 7000) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        const stringMatch = representation.match(PARSE_STRING_REGEXP);
+        const infMatch = representation.match(PARSE_INF_REGEXP);
+        const nanMatch = representation.match(PARSE_NAN_REGEXP);
+        if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        }
+        if (stringMatch) {
+            const unsignedNumber = stringMatch[2];
+            const e = stringMatch[4];
+            const expSign = stringMatch[5];
+            const expNumber = stringMatch[6];
+            if (e && expNumber === undefined)
+                invalidErr(representation, 'missing exponent power');
+            if (e && unsignedNumber === undefined)
+                invalidErr(representation, 'missing exponent base');
+            if (e === undefined && (expSign || expNumber)) {
+                invalidErr(representation, 'missing e before exponent');
+            }
+        }
+        if (representation[index] === '+' || representation[index] === '-') {
+            sawSign = true;
+            isNegative = representation[index++] === '-';
+        }
+        if (!isDigit(representation[index]) && representation[index] !== '.') {
+            if (representation[index] === 'i' || representation[index] === 'I') {
+                return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+            }
+            else if (representation[index] === 'N') {
+                return new Decimal128(NAN_BUFFER);
+            }
+        }
+        while (isDigit(representation[index]) || representation[index] === '.') {
+            if (representation[index] === '.') {
+                if (sawRadix)
+                    invalidErr(representation, 'contains multiple periods');
+                sawRadix = true;
+                index = index + 1;
+                continue;
+            }
+            if (nDigitsStored < MAX_DIGITS) {
+                if (representation[index] !== '0' || foundNonZero) {
+                    if (!foundNonZero) {
+                        firstNonZero = nDigitsRead;
+                    }
+                    foundNonZero = true;
+                    digits[digitsInsert++] = parseInt(representation[index], 10);
+                    nDigitsStored = nDigitsStored + 1;
+                }
+            }
+            if (foundNonZero)
+                nDigits = nDigits + 1;
+            if (sawRadix)
+                radixPosition = radixPosition + 1;
+            nDigitsRead = nDigitsRead + 1;
+            index = index + 1;
+        }
+        if (sawRadix && !nDigitsRead)
+            throw new BSONError('' + representation + ' not a valid Decimal128 string');
+        if (representation[index] === 'e' || representation[index] === 'E') {
+            const match = representation.substr(++index).match(EXPONENT_REGEX);
+            if (!match || !match[2])
+                return new Decimal128(NAN_BUFFER);
+            exponent = parseInt(match[0], 10);
+            index = index + match[0].length;
+        }
+        if (representation[index])
+            return new Decimal128(NAN_BUFFER);
+        if (!nDigitsStored) {
+            digits[0] = 0;
+            nDigits = 1;
+            nDigitsStored = 1;
+            significantDigits = 0;
+        }
+        else {
+            lastDigit = nDigitsStored - 1;
+            significantDigits = nDigits;
+            if (significantDigits !== 1) {
+                while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') {
+                    significantDigits = significantDigits - 1;
+                }
+            }
+        }
+        if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
+            exponent = EXPONENT_MIN;
+        }
+        else {
+            exponent = exponent - radixPosition;
+        }
+        while (exponent > EXPONENT_MAX) {
+            lastDigit = lastDigit + 1;
+            if (lastDigit >= MAX_DIGITS) {
+                if (significantDigits === 0) {
+                    exponent = EXPONENT_MAX;
+                    break;
+                }
+                invalidErr(representation, 'overflow');
+            }
+            exponent = exponent - 1;
+        }
+        if (options.allowRounding) {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0 && significantDigits < nDigitsStored) {
+                    exponent = EXPONENT_MIN;
+                    significantDigits = 0;
+                    break;
+                }
+                if (nDigitsStored < nDigits) {
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    const digitsString = digits.join('');
+                    if (digitsString.match(/^0+$/)) {
+                        exponent = EXPONENT_MAX;
+                        break;
+                    }
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                let endOfString = nDigitsRead;
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                    endOfString = endOfString + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                let roundBit = 0;
+                if (roundDigit >= 5) {
+                    roundBit = 1;
+                    if (roundDigit === 5) {
+                        roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
+                        for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
+                            if (parseInt(representation[i], 10)) {
+                                roundBit = 1;
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (roundBit) {
+                    let dIdx = lastDigit;
+                    for (; dIdx >= 0; dIdx--) {
+                        if (++digits[dIdx] > 9) {
+                            digits[dIdx] = 0;
+                            if (dIdx === 0) {
+                                if (exponent < EXPONENT_MAX) {
+                                    exponent = exponent + 1;
+                                    digits[dIdx] = 1;
+                                }
+                                else {
+                                    return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
+                                }
+                            }
+                        }
+                        else {
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        else {
+            while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
+                if (lastDigit === 0) {
+                    if (significantDigits === 0) {
+                        exponent = EXPONENT_MIN;
+                        break;
+                    }
+                    invalidErr(representation, 'exponent underflow');
+                }
+                if (nDigitsStored < nDigits) {
+                    if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
+                        significantDigits !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    nDigits = nDigits - 1;
+                }
+                else {
+                    if (digits[lastDigit] !== 0) {
+                        invalidErr(representation, 'inexact rounding');
+                    }
+                    lastDigit = lastDigit - 1;
+                }
+                if (exponent < EXPONENT_MAX) {
+                    exponent = exponent + 1;
+                }
+                else {
+                    invalidErr(representation, 'overflow');
+                }
+            }
+            if (lastDigit + 1 < significantDigits) {
+                if (sawRadix) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                if (sawSign) {
+                    firstNonZero = firstNonZero + 1;
+                }
+                const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
+                if (roundDigit !== 0) {
+                    invalidErr(representation, 'inexact rounding');
+                }
+            }
+        }
+        significandHigh = Long.fromNumber(0);
+        significandLow = Long.fromNumber(0);
+        if (significantDigits === 0) {
+            significandHigh = Long.fromNumber(0);
+            significandLow = Long.fromNumber(0);
+        }
+        else if (lastDigit < 17) {
+            let dIdx = 0;
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            significandHigh = new Long(0, 0);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        else {
+            let dIdx = 0;
+            significandHigh = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit - 17; dIdx++) {
+                significandHigh = significandHigh.multiply(Long.fromNumber(10));
+                significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
+            }
+            significandLow = Long.fromNumber(digits[dIdx++]);
+            for (; dIdx <= lastDigit; dIdx++) {
+                significandLow = significandLow.multiply(Long.fromNumber(10));
+                significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
+            }
+        }
+        const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
+        significand.low = significand.low.add(significandLow);
+        if (lessThan(significand.low, significandLow)) {
+            significand.high = significand.high.add(Long.fromNumber(1));
+        }
+        biasedExponent = exponent + EXPONENT_BIAS;
+        const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
+        if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
+            dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
+        }
+        else {
+            dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
+            dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
+        }
+        dec.low = significand.low;
+        if (isNegative) {
+            dec.high = dec.high.or(Long.fromString('9223372036854775808'));
+        }
+        const buffer = ByteUtils.allocateUnsafe(16);
+        index = 0;
+        buffer[index++] = dec.low.low & 0xff;
+        buffer[index++] = (dec.low.low >> 8) & 0xff;
+        buffer[index++] = (dec.low.low >> 16) & 0xff;
+        buffer[index++] = (dec.low.low >> 24) & 0xff;
+        buffer[index++] = dec.low.high & 0xff;
+        buffer[index++] = (dec.low.high >> 8) & 0xff;
+        buffer[index++] = (dec.low.high >> 16) & 0xff;
+        buffer[index++] = (dec.low.high >> 24) & 0xff;
+        buffer[index++] = dec.high.low & 0xff;
+        buffer[index++] = (dec.high.low >> 8) & 0xff;
+        buffer[index++] = (dec.high.low >> 16) & 0xff;
+        buffer[index++] = (dec.high.low >> 24) & 0xff;
+        buffer[index++] = dec.high.high & 0xff;
+        buffer[index++] = (dec.high.high >> 8) & 0xff;
+        buffer[index++] = (dec.high.high >> 16) & 0xff;
+        buffer[index++] = (dec.high.high >> 24) & 0xff;
+        return new Decimal128(buffer);
+    }
+    toString() {
+        let biased_exponent;
+        let significand_digits = 0;
+        const significand = new Array(36);
+        for (let i = 0; i < significand.length; i++)
+            significand[i] = 0;
+        let index = 0;
+        let is_zero = false;
+        let significand_msb;
+        let significand128 = { parts: [0, 0, 0, 0] };
+        let j, k;
+        const string = [];
+        index = 0;
+        const buffer = this.bytes;
+        const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
+        index = 0;
+        const dec = {
+            low: new Long(low, midl),
+            high: new Long(midh, high)
+        };
+        if (dec.high.lessThan(Long.ZERO)) {
+            string.push('-');
+        }
+        const combination = (high >> 26) & COMBINATION_MASK;
+        if (combination >> 3 === 3) {
+            if (combination === COMBINATION_INFINITY) {
+                return string.join('') + 'Infinity';
+            }
+            else if (combination === COMBINATION_NAN) {
+                return 'NaN';
+            }
+            else {
+                biased_exponent = (high >> 15) & EXPONENT_MASK;
+                significand_msb = 0x08 + ((high >> 14) & 0x01);
+            }
+        }
+        else {
+            significand_msb = (high >> 14) & 0x07;
+            biased_exponent = (high >> 17) & EXPONENT_MASK;
+        }
+        const exponent = biased_exponent - EXPONENT_BIAS;
+        significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
+        significand128.parts[1] = midh;
+        significand128.parts[2] = midl;
+        significand128.parts[3] = low;
+        if (significand128.parts[0] === 0 &&
+            significand128.parts[1] === 0 &&
+            significand128.parts[2] === 0 &&
+            significand128.parts[3] === 0) {
+            is_zero = true;
+        }
+        else {
+            for (k = 3; k >= 0; k--) {
+                let least_digits = 0;
+                const result = divideu128(significand128);
+                significand128 = result.quotient;
+                least_digits = result.rem.low;
+                if (!least_digits)
+                    continue;
+                for (j = 8; j >= 0; j--) {
+                    significand[k * 9 + j] = least_digits % 10;
+                    least_digits = Math.floor(least_digits / 10);
+                }
+            }
+        }
+        if (is_zero) {
+            significand_digits = 1;
+            significand[index] = 0;
+        }
+        else {
+            significand_digits = 36;
+            while (!significand[index]) {
+                significand_digits = significand_digits - 1;
+                index = index + 1;
+            }
+        }
+        const scientific_exponent = significand_digits - 1 + exponent;
+        if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
+            if (significand_digits > 34) {
+                string.push(`${0}`);
+                if (exponent > 0)
+                    string.push(`E+${exponent}`);
+                else if (exponent < 0)
+                    string.push(`E${exponent}`);
+                return string.join('');
+            }
+            string.push(`${significand[index++]}`);
+            significand_digits = significand_digits - 1;
+            if (significand_digits) {
+                string.push('.');
+            }
+            for (let i = 0; i < significand_digits; i++) {
+                string.push(`${significand[index++]}`);
+            }
+            string.push('E');
+            if (scientific_exponent > 0) {
+                string.push(`+${scientific_exponent}`);
+            }
+            else {
+                string.push(`${scientific_exponent}`);
+            }
+        }
+        else {
+            if (exponent >= 0) {
+                for (let i = 0; i < significand_digits; i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+            else {
+                let radix_position = significand_digits + exponent;
+                if (radix_position > 0) {
+                    for (let i = 0; i < radix_position; i++) {
+                        string.push(`${significand[index++]}`);
+                    }
+                }
+                else {
+                    string.push('0');
+                }
+                string.push('.');
+                while (radix_position++ < 0) {
+                    string.push('0');
+                }
+                for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
+                    string.push(`${significand[index++]}`);
+                }
+            }
+        }
+        return string.join('');
+    }
+    toJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    toExtendedJSON() {
+        return { $numberDecimal: this.toString() };
+    }
+    static fromExtendedJSON(doc) {
+        return Decimal128.fromString(doc.$numberDecimal);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const d128string = inspect(this.toString(), options);
+        return `new Decimal128(${d128string})`;
+    }
+}
+
+class Double extends BSONValue {
+    get _bsontype() {
+        return 'Double';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value;
+    }
+    static fromString(value) {
+        const coercedValue = Number(value);
+        if (value === 'NaN')
+            return new Double(NaN);
+        if (value === 'Infinity')
+            return new Double(Infinity);
+        if (value === '-Infinity')
+            return new Double(-Infinity);
+        if (!Number.isFinite(coercedValue)) {
+            throw new BSONError(`Input: ${value} is not representable as a Double`);
+        }
+        if (value.trim() !== value) {
+            throw new BSONError(`Input: '${value}' contains whitespace`);
+        }
+        if (value === '') {
+            throw new BSONError(`Input is an empty string`);
+        }
+        if (/[^-0-9.+eE]/.test(value)) {
+            throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
+        }
+        return new Double(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toExtendedJSON(options) {
+        if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
+            return this.value;
+        }
+        if (Object.is(Math.sign(this.value), -0)) {
+            return { $numberDouble: '-0.0' };
+        }
+        return {
+            $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
+        };
+    }
+    static fromExtendedJSON(doc, options) {
+        const doubleValue = parseFloat(doc.$numberDouble);
+        return options && options.relaxed ? doubleValue : new Double(doubleValue);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Double(${inspect(this.value, options)})`;
+    }
+}
+
+class Int32 extends BSONValue {
+    get _bsontype() {
+        return 'Int32';
+    }
+    value;
+    constructor(value) {
+        super();
+        if (value instanceof Number) {
+            value = value.valueOf();
+        }
+        this.value = +value | 0;
+    }
+    static fromString(value) {
+        const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
+        const coercedValue = Number(value);
+        if (BSON_INT32_MAX < coercedValue) {
+            throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
+        }
+        else if (BSON_INT32_MIN > coercedValue) {
+            throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
+        }
+        else if (!Number.isSafeInteger(coercedValue)) {
+            throw new BSONError(`Input: '${value}' is not a safe integer`);
+        }
+        else if (coercedValue.toString() !== cleanedValue) {
+            throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
+        }
+        return new Int32(coercedValue);
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString(radix) {
+        return this.value.toString(radix);
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON(options) {
+        if (options && (options.relaxed || options.legacy))
+            return this.value;
+        return { $numberInt: this.value.toString() };
+    }
+    static fromExtendedJSON(doc, options) {
+        return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new Int32(${inspect(this.value, options)})`;
+    }
+}
+
+class MaxKey extends BSONValue {
+    get _bsontype() {
+        return 'MaxKey';
+    }
+    toExtendedJSON() {
+        return { $maxKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MaxKey();
+    }
+    inspect() {
+        return 'new MaxKey()';
+    }
+}
+
+class MinKey extends BSONValue {
+    get _bsontype() {
+        return 'MinKey';
+    }
+    toExtendedJSON() {
+        return { $minKey: 1 };
+    }
+    static fromExtendedJSON() {
+        return new MinKey();
+    }
+    inspect() {
+        return 'new MinKey()';
+    }
+}
+
+let PROCESS_UNIQUE = null;
+const __idCache = new WeakMap();
+class ObjectId extends BSONValue {
+    get _bsontype() {
+        return 'ObjectId';
+    }
+    static index = Math.floor(Math.random() * 0xffffff);
+    static cacheHexString;
+    buffer;
+    constructor(inputId) {
+        super();
+        let workingId;
+        if (typeof inputId === 'object' && inputId && 'id' in inputId) {
+            if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
+                throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
+            }
+            if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
+                workingId = ByteUtils.fromHex(inputId.toHexString());
+            }
+            else {
+                workingId = inputId.id;
+            }
+        }
+        else {
+            workingId = inputId;
+        }
+        if (workingId == null) {
+            this.buffer = ObjectId.generate();
+        }
+        else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
+            this.buffer = ByteUtils.toLocalBufferType(workingId);
+        }
+        else if (typeof workingId === 'string') {
+            if (ObjectId.validateHexString(workingId)) {
+                this.buffer = ByteUtils.fromHex(workingId);
+                if (ObjectId.cacheHexString) {
+                    __idCache.set(this, workingId);
+                }
+            }
+            else {
+                throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer');
+            }
+        }
+        else {
+            throw new BSONError('Argument passed in does not match the accepted types');
+        }
+    }
+    get id() {
+        return this.buffer;
+    }
+    set id(value) {
+        this.buffer = value;
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, ByteUtils.toHex(value));
+        }
+    }
+    static validateHexString(string) {
+        if (string?.length !== 24)
+            return false;
+        for (let i = 0; i < 24; i++) {
+            const char = string.charCodeAt(i);
+            if ((char >= 48 && char <= 57) ||
+                (char >= 97 && char <= 102) ||
+                (char >= 65 && char <= 70)) {
+                continue;
+            }
+            return false;
+        }
+        return true;
+    }
+    toHexString() {
+        if (ObjectId.cacheHexString) {
+            const __id = __idCache.get(this);
+            if (__id)
+                return __id;
+        }
+        const hexString = ByteUtils.toHex(this.id);
+        if (ObjectId.cacheHexString) {
+            __idCache.set(this, hexString);
+        }
+        return hexString;
+    }
+    static getInc() {
+        return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
+    }
+    static generate(time) {
+        if ('number' !== typeof time) {
+            time = Math.floor(Date.now() / 1000);
+        }
+        const inc = ObjectId.getInc();
+        const buffer = ByteUtils.allocateUnsafe(12);
+        NumberUtils.setInt32BE(buffer, 0, time);
+        if (PROCESS_UNIQUE === null) {
+            PROCESS_UNIQUE = ByteUtils.randomBytes(5);
+        }
+        buffer[4] = PROCESS_UNIQUE[0];
+        buffer[5] = PROCESS_UNIQUE[1];
+        buffer[6] = PROCESS_UNIQUE[2];
+        buffer[7] = PROCESS_UNIQUE[3];
+        buffer[8] = PROCESS_UNIQUE[4];
+        buffer[11] = inc & 0xff;
+        buffer[10] = (inc >> 8) & 0xff;
+        buffer[9] = (inc >> 16) & 0xff;
+        return buffer;
+    }
+    toString(encoding) {
+        if (encoding === 'base64')
+            return ByteUtils.toBase64(this.id);
+        if (encoding === 'hex')
+            return this.toHexString();
+        return this.toHexString();
+    }
+    toJSON() {
+        return this.toHexString();
+    }
+    static is(variable) {
+        return (variable != null &&
+            typeof variable === 'object' &&
+            '_bsontype' in variable &&
+            variable._bsontype === 'ObjectId');
+    }
+    equals(otherId) {
+        if (otherId === undefined || otherId === null) {
+            return false;
+        }
+        if (ObjectId.is(otherId)) {
+            return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer));
+        }
+        if (typeof otherId === 'string') {
+            return otherId.toLowerCase() === this.toHexString();
+        }
+        if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') {
+            const otherIdString = otherId.toHexString();
+            const thisIdString = this.toHexString();
+            return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
+        }
+        return false;
+    }
+    getTimestamp() {
+        const timestamp = new Date();
+        const time = NumberUtils.getUint32BE(this.buffer, 0);
+        timestamp.setTime(Math.floor(time) * 1000);
+        return timestamp;
+    }
+    static createPk() {
+        return new ObjectId();
+    }
+    serializeInto(uint8array, index) {
+        uint8array[index] = this.buffer[0];
+        uint8array[index + 1] = this.buffer[1];
+        uint8array[index + 2] = this.buffer[2];
+        uint8array[index + 3] = this.buffer[3];
+        uint8array[index + 4] = this.buffer[4];
+        uint8array[index + 5] = this.buffer[5];
+        uint8array[index + 6] = this.buffer[6];
+        uint8array[index + 7] = this.buffer[7];
+        uint8array[index + 8] = this.buffer[8];
+        uint8array[index + 9] = this.buffer[9];
+        uint8array[index + 10] = this.buffer[10];
+        uint8array[index + 11] = this.buffer[11];
+        return 12;
+    }
+    static createFromTime(time) {
+        const buffer = ByteUtils.allocate(12);
+        for (let i = 11; i >= 4; i--)
+            buffer[i] = 0;
+        NumberUtils.setInt32BE(buffer, 0, time);
+        return new ObjectId(buffer);
+    }
+    static createFromHexString(hexString) {
+        if (hexString?.length !== 24) {
+            throw new BSONError('hex string must be 24 characters');
+        }
+        return new ObjectId(ByteUtils.fromHex(hexString));
+    }
+    static createFromBase64(base64) {
+        if (base64?.length !== 16) {
+            throw new BSONError('base64 string must be 16 characters');
+        }
+        return new ObjectId(ByteUtils.fromBase64(base64));
+    }
+    static isValid(id) {
+        if (id == null)
+            return false;
+        if (typeof id === 'string')
+            return ObjectId.validateHexString(id);
+        try {
+            new ObjectId(id);
+            return true;
+        }
+        catch {
+            return false;
+        }
+    }
+    toExtendedJSON() {
+        if (this.toHexString)
+            return { $oid: this.toHexString() };
+        return { $oid: this.toString('hex') };
+    }
+    static fromExtendedJSON(doc) {
+        return new ObjectId(doc.$oid);
+    }
+    isCached() {
+        return ObjectId.cacheHexString && __idCache.has(this);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new ObjectId(${inspect(this.toHexString(), options)})`;
+    }
+}
+
+function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
+    let totalLength = 4 + 1;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+        }
+        for (const key of Object.keys(object)) {
+            totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
+        }
+    }
+    return totalLength;
+}
+function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
+    if (typeof value?.toBSON === 'function') {
+        value = value.toBSON();
+    }
+    switch (typeof value) {
+        case 'string':
+            return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
+        case 'number':
+            if (Math.floor(value) === value &&
+                value >= JS_INT_MIN &&
+                value <= JS_INT_MAX) {
+                if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
+                }
+                else {
+                    return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+                }
+            }
+            else {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+        case 'undefined':
+            if (isArray || !ignoreUndefined)
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            return 0;
+        case 'boolean':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
+        case 'object':
+            if (value != null &&
+                typeof value._bsontype === 'string' &&
+                value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                throw new BSONVersionError();
+            }
+            else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
+            }
+            else if (value._bsontype === 'ObjectId') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
+            }
+            else if (value instanceof Date || isDate(value)) {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (ArrayBuffer.isView(value) ||
+                value instanceof ArrayBuffer ||
+                isAnyArrayBuffer(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength);
+            }
+            else if (value._bsontype === 'Long' ||
+                value._bsontype === 'Double' ||
+                value._bsontype === 'Timestamp') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+            }
+            else if (value._bsontype === 'Decimal128') {
+                return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
+            }
+            else if (value._bsontype === 'Code') {
+                if (value.scope != null && Object.keys(value.scope).length > 0) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1 +
+                        internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        1 +
+                        4 +
+                        ByteUtils.utf8ByteLength(value.code.toString()) +
+                        1);
+                }
+            }
+            else if (value._bsontype === 'Binary') {
+                const binary = value;
+                if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                        (binary.position + 1 + 4 + 1 + 4));
+                }
+                else {
+                    return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1));
+                }
+            }
+            else if (value._bsontype === 'Symbol') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    ByteUtils.utf8ByteLength(value.value) +
+                    4 +
+                    1 +
+                    1);
+            }
+            else if (value._bsontype === 'DBRef') {
+                const ordered_values = Object.assign({
+                    $ref: value.collection,
+                    $id: value.oid
+                }, value.fields);
+                if (value.db != null) {
+                    ordered_values['$db'] = value.db;
+                }
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
+            }
+            else if (value instanceof RegExp || isRegExp(value)) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.source) +
+                    1 +
+                    (value.global ? 1 : 0) +
+                    (value.ignoreCase ? 1 : 0) +
+                    (value.multiline ? 1 : 0) +
+                    1);
+            }
+            else if (value._bsontype === 'BSONRegExp') {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.pattern) +
+                    1 +
+                    ByteUtils.utf8ByteLength(value.options) +
+                    1);
+            }
+            else {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) +
+                    1);
+            }
+        case 'function':
+            if (serializeFunctions) {
+                return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
+                    1 +
+                    4 +
+                    ByteUtils.utf8ByteLength(value.toString()) +
+                    1);
+            }
+            return 0;
+        case 'bigint':
+            return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
+        case 'symbol':
+            return 0;
+        default:
+            throw new BSONError(`Unrecognized JS type: ${typeof value}`);
+    }
+    return 0;
+}
+
+function alphabetize(str) {
+    return str.split('').sort().join('');
+}
+class BSONRegExp extends BSONValue {
+    get _bsontype() {
+        return 'BSONRegExp';
+    }
+    pattern;
+    options;
+    constructor(pattern, options) {
+        super();
+        this.pattern = pattern;
+        this.options = alphabetize(options ?? '');
+        if (this.pattern.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
+        }
+        if (this.options.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
+        }
+        for (let i = 0; i < this.options.length; i++) {
+            if (!(this.options[i] === 'i' ||
+                this.options[i] === 'm' ||
+                this.options[i] === 'x' ||
+                this.options[i] === 'l' ||
+                this.options[i] === 's' ||
+                this.options[i] === 'u')) {
+                throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
+            }
+        }
+    }
+    static parseOptions(options) {
+        return options ? options.split('').sort().join('') : '';
+    }
+    toExtendedJSON(options) {
+        options = options || {};
+        if (options.legacy) {
+            return { $regex: this.pattern, $options: this.options };
+        }
+        return { $regularExpression: { pattern: this.pattern, options: this.options } };
+    }
+    static fromExtendedJSON(doc) {
+        if ('$regex' in doc) {
+            if (typeof doc.$regex !== 'string') {
+                if (doc.$regex._bsontype === 'BSONRegExp') {
+                    return doc;
+                }
+            }
+            else {
+                return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
+            }
+        }
+        if ('$regularExpression' in doc) {
+            return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
+        }
+        throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
+    }
+    inspect(depth, options, inspect) {
+        const stylize = getStylizeFunction(options) ?? (v => v);
+        inspect ??= defaultInspect;
+        const pattern = stylize(inspect(this.pattern), 'regexp');
+        const flags = stylize(inspect(this.options), 'regexp');
+        return `new BSONRegExp(${pattern}, ${flags})`;
+    }
+}
+
+class BSONSymbol extends BSONValue {
+    get _bsontype() {
+        return 'BSONSymbol';
+    }
+    value;
+    constructor(value) {
+        super();
+        this.value = value;
+    }
+    valueOf() {
+        return this.value;
+    }
+    toString() {
+        return this.value;
+    }
+    toJSON() {
+        return this.value;
+    }
+    toExtendedJSON() {
+        return { $symbol: this.value };
+    }
+    static fromExtendedJSON(doc) {
+        return new BSONSymbol(doc.$symbol);
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        return `new BSONSymbol(${inspect(this.value, options)})`;
+    }
+}
+
+const LongWithoutOverridesClass = Long;
+class Timestamp extends LongWithoutOverridesClass {
+    get _bsontype() {
+        return 'Timestamp';
+    }
+    get [bsonType]() {
+        return 'Timestamp';
+    }
+    static MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
+    get i() {
+        return this.low >>> 0;
+    }
+    get t() {
+        return this.high >>> 0;
+    }
+    constructor(low) {
+        if (low == null) {
+            super(0, 0, true);
+        }
+        else if (typeof low === 'bigint') {
+            super(low, true);
+        }
+        else if (Long.isLong(low)) {
+            super(low.low, low.high, true);
+        }
+        else if (typeof low === 'object' && 't' in low && 'i' in low) {
+            if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t as a number');
+            }
+            if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
+            }
+            const t = Number(low.t);
+            const i = Number(low.i);
+            if (t < 0 || Number.isNaN(t)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
+            }
+            if (i < 0 || Number.isNaN(i)) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
+            }
+            if (t > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max');
+            }
+            if (i > 0xffff_ffff) {
+                throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max');
+            }
+            super(i, t, true);
+        }
+        else {
+            throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }');
+        }
+    }
+    toJSON() {
+        return {
+            $timestamp: this.toString()
+        };
+    }
+    static fromInt(value) {
+        return new Timestamp(Long.fromInt(value, true));
+    }
+    static fromNumber(value) {
+        return new Timestamp(Long.fromNumber(value, true));
+    }
+    static fromBits(lowBits, highBits) {
+        return new Timestamp({ i: lowBits, t: highBits });
+    }
+    static fromString(str, optRadix) {
+        return new Timestamp(Long.fromString(str, true, optRadix));
+    }
+    toExtendedJSON() {
+        return { $timestamp: { t: this.t, i: this.i } };
+    }
+    static fromExtendedJSON(doc) {
+        const i = Long.isLong(doc.$timestamp.i)
+            ? doc.$timestamp.i.getLowBitsUnsigned()
+            : doc.$timestamp.i;
+        const t = Long.isLong(doc.$timestamp.t)
+            ? doc.$timestamp.t.getLowBitsUnsigned()
+            : doc.$timestamp.t;
+        return new Timestamp({ t, i });
+    }
+    inspect(depth, options, inspect) {
+        inspect ??= defaultInspect;
+        const t = inspect(this.t, options);
+        const i = inspect(this.i, options);
+        return `new Timestamp({ t: ${t}, i: ${i} })`;
+    }
+}
+
+const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
+const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
+function internalDeserialize(buffer, options, isArray) {
+    options = options == null ? {} : options;
+    const index = options && options.index ? options.index : 0;
+    const size = NumberUtils.getInt32LE(buffer, index);
+    if (size < 5) {
+        throw new BSONError(`bson size must be >= 5, is ${size}`);
+    }
+    if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
+        throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
+    }
+    if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
+        throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
+    }
+    if (size + index > buffer.byteLength) {
+        throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`);
+    }
+    if (buffer[index + size - 1] !== 0) {
+        throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
+    }
+    return deserializeObject(buffer, index, options, isArray);
+}
+const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
+function deserializeObject(buffer, index, options, isArray = false) {
+    const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
+    const raw = options['raw'] == null ? false : options['raw'];
+    const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
+    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');
+    }
+    const validation = options.validation == null ? { utf8: true } : options.validation;
+    let globalUTFValidation = true;
+    let validationSetting;
+    let utf8KeysSet;
+    const utf8ValidatedKeys = validation.utf8;
+    if (typeof utf8ValidatedKeys === 'boolean') {
+        validationSetting = utf8ValidatedKeys;
+    }
+    else {
+        globalUTFValidation = false;
+        const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
+            return utf8ValidatedKeys[key];
+        });
+        if (utf8ValidationValues.length === 0) {
+            throw new BSONError('UTF-8 validation setting cannot be empty');
+        }
+        if (typeof utf8ValidationValues[0] !== 'boolean') {
+            throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
+        }
+        validationSetting = utf8ValidationValues[0];
+        if (!utf8ValidationValues.every(item => item === validationSetting)) {
+            throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
+        }
+    }
+    if (!globalUTFValidation) {
+        utf8KeysSet = new Set();
+        for (const key of Object.keys(utf8ValidatedKeys)) {
+            utf8KeysSet.add(key);
+        }
+    }
+    const startIndex = index;
+    if (buffer.length < 5)
+        throw new BSONError('corrupt bson message < 5 bytes long');
+    const size = NumberUtils.getInt32LE(buffer, index);
+    index += 4;
+    if (size < 5 || size > buffer.length)
+        throw new BSONError('corrupt bson message');
+    const object = isArray ? [] : {};
+    let arrayIndex = 0;
+    const done = false;
+    let isPossibleDBRef = isArray ? false : null;
+    while (!done) {
+        const elementType = buffer[index++];
+        if (elementType === 0)
+            break;
+        let i = index;
+        while (buffer[i] !== 0x00 && i < buffer.length) {
+            i++;
+        }
+        if (i >= buffer.byteLength)
+            throw new BSONError('Bad BSON Document: illegal CString');
+        const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false);
+        let shouldValidateKey = true;
+        if (globalUTFValidation || utf8KeysSet?.has(name)) {
+            shouldValidateKey = validationSetting;
+        }
+        else {
+            shouldValidateKey = !validationSetting;
+        }
+        if (isPossibleDBRef !== false && name[0] === '$') {
+            isPossibleDBRef = allowedDBRefKeys.test(name);
+        }
+        let value;
+        index = i + 1;
+        if (elementType === BSON_DATA_STRING) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_OID) {
+            const oid = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oid[i] = buffer[index + i];
+            value = new ObjectId(oid);
+            index = index + 12;
+        }
+        else if (elementType === BSON_DATA_INT && promoteValues === false) {
+            value = new Int32(NumberUtils.getInt32LE(buffer, index));
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_INT) {
+            value = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+        }
+        else if (elementType === BSON_DATA_NUMBER) {
+            value = NumberUtils.getFloat64LE(buffer, index);
+            index += 8;
+            if (promoteValues === false)
+                value = new Double(value);
+        }
+        else if (elementType === BSON_DATA_DATE) {
+            const lowBits = NumberUtils.getInt32LE(buffer, index);
+            const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+            index += 8;
+            value = new Date(new Long(lowBits, highBits).toNumber());
+        }
+        else if (elementType === BSON_DATA_BOOLEAN) {
+            if (buffer[index] !== 0 && buffer[index] !== 1)
+                throw new BSONError('illegal boolean type value');
+            value = buffer[index++] === 1;
+        }
+        else if (elementType === BSON_DATA_OBJECT) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            if (objectSize <= 0 || objectSize > buffer.length - index)
+                throw new BSONError('bad embedded document length in bson');
+            if (raw) {
+                value = buffer.subarray(index, index + objectSize);
+            }
+            else {
+                let objectOptions = options;
+                if (!globalUTFValidation) {
+                    objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
+                }
+                value = deserializeObject(buffer, _index, objectOptions, false);
+            }
+            index = index + objectSize;
+        }
+        else if (elementType === BSON_DATA_ARRAY) {
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            let arrayOptions = options;
+            const stopIndex = index + objectSize;
+            if (fieldsAsRaw && fieldsAsRaw[name]) {
+                arrayOptions = { ...options, raw: true };
+            }
+            if (!globalUTFValidation) {
+                arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
+            }
+            value = deserializeObject(buffer, _index, arrayOptions, true);
+            index = index + objectSize;
+            if (buffer[index - 1] !== 0)
+                throw new BSONError('invalid array terminator byte');
+            if (index !== stopIndex)
+                throw new BSONError('corrupted array bson');
+        }
+        else if (elementType === BSON_DATA_UNDEFINED) {
+            value = undefined;
+        }
+        else if (elementType === BSON_DATA_NULL) {
+            value = null;
+        }
+        else if (elementType === BSON_DATA_LONG) {
+            if (useBigInt64) {
+                value = NumberUtils.getBigInt64LE(buffer, index);
+                index += 8;
+            }
+            else {
+                const lowBits = NumberUtils.getInt32LE(buffer, index);
+                const highBits = NumberUtils.getInt32LE(buffer, index + 4);
+                index += 8;
+                const long = new Long(lowBits, highBits);
+                if (promoteLongs && promoteValues === true) {
+                    value =
+                        long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
+                            ? long.toNumber()
+                            : long;
+                }
+                else {
+                    value = long;
+                }
+            }
+        }
+        else if (elementType === BSON_DATA_DECIMAL128) {
+            const bytes = ByteUtils.allocateUnsafe(16);
+            for (let i = 0; i < 16; i++)
+                bytes[i] = buffer[index + i];
+            index = index + 16;
+            value = new Decimal128(bytes);
+        }
+        else if (elementType === BSON_DATA_BINARY) {
+            let binarySize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            const totalBinarySize = binarySize;
+            const subType = buffer[index++];
+            if (binarySize < 0)
+                throw new BSONError('Negative binary type element size found');
+            if (binarySize > buffer.byteLength)
+                throw new BSONError('Binary type size larger than document size');
+            if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
+                binarySize = NumberUtils.getInt32LE(buffer, index);
+                index += 4;
+                if (binarySize < 0)
+                    throw new BSONError('Negative binary type element size found for subtype 0x02');
+                if (binarySize > totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
+                if (binarySize < totalBinarySize - 4)
+                    throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
+            }
+            if (promoteBuffers && promoteValues) {
+                value = ByteUtils.toLocalBufferType(buffer.subarray(index, index + binarySize));
+            }
+            else {
+                value = new Binary(buffer.subarray(index, index + binarySize), subType);
+                if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
+                    value = value.toUUID();
+                }
+            }
+            index = index + binarySize;
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            const optionsArray = new Array(regExpOptions.length);
+            for (i = 0; i < regExpOptions.length; i++) {
+                switch (regExpOptions[i]) {
+                    case 'm':
+                        optionsArray[i] = 'm';
+                        break;
+                    case 's':
+                        optionsArray[i] = 'g';
+                        break;
+                    case 'i':
+                        optionsArray[i] = 'i';
+                        break;
+                }
+            }
+            value = new RegExp(source, optionsArray.join(''));
+        }
+        else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const source = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            i = index;
+            while (buffer[i] !== 0x00 && i < buffer.length) {
+                i++;
+            }
+            if (i >= buffer.length)
+                throw new BSONError('Bad BSON Document: illegal CString');
+            const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
+            index = i + 1;
+            value = new BSONRegExp(source, regExpOptions);
+        }
+        else if (elementType === BSON_DATA_SYMBOL) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = promoteValues ? symbol : new BSONSymbol(symbol);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_TIMESTAMP) {
+            value = new Timestamp({
+                i: NumberUtils.getUint32LE(buffer, index),
+                t: NumberUtils.getUint32LE(buffer, index + 4)
+            });
+            index += 8;
+        }
+        else if (elementType === BSON_DATA_MIN_KEY) {
+            value = new MinKey();
+        }
+        else if (elementType === BSON_DATA_MAX_KEY) {
+            value = new MaxKey();
+        }
+        else if (elementType === BSON_DATA_CODE) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            value = new Code(functionString);
+            index = index + stringSize;
+        }
+        else if (elementType === BSON_DATA_CODE_W_SCOPE) {
+            const totalSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (totalSize < 4 + 4 + 4 + 1) {
+                throw new BSONError('code_w_scope total size shorter minimum expected length');
+            }
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0) {
+                throw new BSONError('bad string length in bson');
+            }
+            const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const _index = index;
+            const objectSize = NumberUtils.getInt32LE(buffer, index);
+            const scopeObject = deserializeObject(buffer, _index, options, false);
+            index = index + objectSize;
+            if (totalSize < 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too short, truncating scope');
+            }
+            if (totalSize > 4 + 4 + objectSize + stringSize) {
+                throw new BSONError('code_w_scope total size is too long, clips outer document');
+            }
+            value = new Code(functionString, scopeObject);
+        }
+        else if (elementType === BSON_DATA_DBPOINTER) {
+            const stringSize = NumberUtils.getInt32LE(buffer, index);
+            index += 4;
+            if (stringSize <= 0 ||
+                stringSize > buffer.length - index ||
+                buffer[index + stringSize - 1] !== 0)
+                throw new BSONError('bad string length in bson');
+            const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
+            index = index + stringSize;
+            const oidBuffer = ByteUtils.allocateUnsafe(12);
+            for (let i = 0; i < 12; i++)
+                oidBuffer[i] = buffer[index + i];
+            const oid = new ObjectId(oidBuffer);
+            index = index + 12;
+            value = new DBRef(namespace, oid);
+        }
+        else {
+            throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
+        }
+        if (name === '__proto__') {
+            Object.defineProperty(object, name, {
+                value,
+                writable: true,
+                enumerable: true,
+                configurable: true
+            });
+        }
+        else {
+            object[name] = value;
+        }
+    }
+    if (size !== index - startIndex) {
+        if (isArray)
+            throw new BSONError('corrupt array bson');
+        throw new BSONError('corrupt object bson');
+    }
+    if (!isPossibleDBRef)
+        return object;
+    if (isDBRefLike(object)) {
+        const copy = Object.assign({}, object);
+        delete copy.$ref;
+        delete copy.$id;
+        delete copy.$db;
+        return new DBRef(object.$ref, object.$id, object.$db, copy);
+    }
+    return object;
+}
+
+const regexp = /\x00/;
+const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
+function serializeString(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_STRING;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes + 1;
+    buffer[index - 1] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
+    NumberUtils.setInt32LE(buffer, index, size + 1);
+    index = index + 4 + size;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeNumber(buffer, key, value, index) {
+    const isNegativeZero = Object.is(value, -0);
+    const type = !isNegativeZero &&
+        Number.isSafeInteger(value) &&
+        value <= BSON_INT32_MAX &&
+        value >= BSON_INT32_MIN
+        ? BSON_DATA_INT
+        : BSON_DATA_NUMBER;
+    buffer[index++] = type;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0x00;
+    if (type === BSON_DATA_INT) {
+        index += NumberUtils.setInt32LE(buffer, index, value);
+    }
+    else {
+        index += NumberUtils.setFloat64LE(buffer, index, value);
+    }
+    return index;
+}
+function serializeBigInt(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_LONG;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index += numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setBigInt64LE(buffer, index, value);
+    return index;
+}
+function serializeNull(buffer, key, _, index) {
+    buffer[index++] = BSON_DATA_NULL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeBoolean(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BOOLEAN;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    buffer[index++] = value ? 1 : 0;
+    return index;
+}
+function serializeDate(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DATE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const dateInMilis = Long.fromNumber(value.getTime());
+    const lowBits = dateInMilis.getLowBits();
+    const highBits = dateInMilis.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.source && value.source.match(regexp) != null) {
+        throw new BSONError('value ' + value.source + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
+    buffer[index++] = 0x00;
+    if (value.ignoreCase)
+        buffer[index++] = 0x69;
+    if (value.global)
+        buffer[index++] = 0x73;
+    if (value.multiline)
+        buffer[index++] = 0x6d;
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeBSONRegExp(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_REGEXP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    if (value.pattern.match(regexp) != null) {
+        throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
+    }
+    index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
+    buffer[index++] = 0x00;
+    const sortedOptions = value.options.split('').sort().join('');
+    index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
+    buffer[index++] = 0x00;
+    return index;
+}
+function serializeMinMax(buffer, key, value, index) {
+    if (value === null) {
+        buffer[index++] = BSON_DATA_NULL;
+    }
+    else if (value._bsontype === 'MinKey') {
+        buffer[index++] = BSON_DATA_MIN_KEY;
+    }
+    else {
+        buffer[index++] = BSON_DATA_MAX_KEY;
+    }
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeObjectId(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_OID;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += value.serializeInto(buffer, index);
+    return index;
+}
+function serializeBuffer(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = value.length;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = value[i];
+    }
+    else {
+        buffer.set(value, index);
+    }
+    index = index + size;
+    return index;
+}
+function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path.has(value)) {
+        throw new BSONError('Cannot convert circular structure to BSON');
+    }
+    path.add(value);
+    buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+    path.delete(value);
+    return endIndex;
+}
+function serializeDecimal128(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_DECIMAL128;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    for (let i = 0; i < 16; i++)
+        buffer[index + i] = value.bytes[i];
+    return index + 16;
+}
+function serializeLong(buffer, key, value, index) {
+    buffer[index++] =
+        value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const lowBits = value.getLowBits();
+    const highBits = value.getHighBits();
+    index += NumberUtils.setInt32LE(buffer, index, lowBits);
+    index += NumberUtils.setInt32LE(buffer, index, highBits);
+    return index;
+}
+function serializeInt32(buffer, key, value, index) {
+    value = value.valueOf();
+    buffer[index++] = BSON_DATA_INT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setInt32LE(buffer, index, value);
+    return index;
+}
+function serializeDouble(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_NUMBER;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    index += NumberUtils.setFloat64LE(buffer, index, value.value);
+    return index;
+}
+function serializeFunction(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_CODE;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const functionString = value.toString();
+    const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
+    if (value.scope && typeof value.scope === 'object') {
+        buffer[index++] = BSON_DATA_CODE_W_SCOPE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        let startIndex = index;
+        const functionString = value.code;
+        index = index + 4;
+        const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, codeSize);
+        buffer[index + 4 + codeSize - 1] = 0;
+        index = index + codeSize + 4;
+        const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
+        index = endIndex - 1;
+        const totalSize = endIndex - startIndex;
+        startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize);
+        buffer[index++] = 0;
+    }
+    else {
+        buffer[index++] = BSON_DATA_CODE;
+        const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+        index = index + numberOfWrittenBytes;
+        buffer[index++] = 0;
+        const functionString = value.code.toString();
+        const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
+        NumberUtils.setInt32LE(buffer, index, size);
+        index = index + 4 + size - 1;
+        buffer[index++] = 0;
+    }
+    return index;
+}
+function serializeBinary(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_BINARY;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const data = value.buffer;
+    let size = value.position;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
+        size = size + 4;
+    index += NumberUtils.setInt32LE(buffer, index, size);
+    buffer[index++] = value.sub_type;
+    if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
+        size = size - 4;
+        index += NumberUtils.setInt32LE(buffer, index, size);
+    }
+    if (value.sub_type === Binary.SUBTYPE_VECTOR) {
+        validateBinaryVector(value);
+    }
+    if (size <= 16) {
+        for (let i = 0; i < size; i++)
+            buffer[index + i] = data[i];
+    }
+    else {
+        buffer.set(data, index);
+    }
+    index = index + value.position;
+    return index;
+}
+function serializeSymbol(buffer, key, value, index) {
+    buffer[index++] = BSON_DATA_SYMBOL;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
+    NumberUtils.setInt32LE(buffer, index, size);
+    index = index + 4 + size - 1;
+    buffer[index++] = 0;
+    return index;
+}
+function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) {
+    buffer[index++] = BSON_DATA_OBJECT;
+    const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
+    index = index + numberOfWrittenBytes;
+    buffer[index++] = 0;
+    let startIndex = index;
+    let output = {
+        $ref: value.collection || value.namespace,
+        $id: value.oid
+    };
+    if (value.db != null) {
+        output.$db = value.db;
+    }
+    output = Object.assign(output, value.fields);
+    const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path);
+    const size = endIndex - startIndex;
+    startIndex += NumberUtils.setInt32LE(buffer, index, size);
+    return endIndex;
+}
+function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
+    if (path == null) {
+        if (object == null) {
+            buffer[0] = 0x05;
+            buffer[1] = 0x00;
+            buffer[2] = 0x00;
+            buffer[3] = 0x00;
+            buffer[4] = 0x00;
+            return 5;
+        }
+        if (Array.isArray(object)) {
+            throw new BSONError('serialize does not support an array as the root input');
+        }
+        if (typeof object !== 'object') {
+            throw new BSONError('serialize does not support non-object as the root input');
+        }
+        else if ('_bsontype' in object && typeof object._bsontype === 'string') {
+            throw new BSONError(`BSON types cannot be serialized as a document`);
+        }
+        else if (isDate(object) ||
+            isRegExp(object) ||
+            isUint8Array(object) ||
+            isAnyArrayBuffer(object)) {
+            throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
+        }
+        path = new Set();
+    }
+    path.add(object);
+    let index = startingIndex + 4;
+    if (Array.isArray(object)) {
+        for (let i = 0; i < object.length; i++) {
+            const key = `${i}`;
+            let value = object[i];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (value === undefined) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else if (object instanceof Map || isMap(object)) {
+        const iterator = object.entries();
+        let done = false;
+        while (!done) {
+            const entry = iterator.next();
+            done = !!entry.done;
+            if (done)
+                continue;
+            const key = entry.value ? entry.value[0] : undefined;
+            let value = entry.value ? entry.value[1] : undefined;
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    else {
+        if (typeof object?.toBSON === 'function') {
+            object = object.toBSON();
+            if (object != null && typeof object !== 'object') {
+                throw new BSONError('toBSON function did not return an object');
+            }
+        }
+        for (const key of Object.keys(object)) {
+            let value = object[key];
+            if (typeof value?.toBSON === 'function') {
+                value = value.toBSON();
+            }
+            const type = typeof value;
+            if (typeof key === 'string' && !ignoreKeys.has(key)) {
+                if (key.match(regexp) != null) {
+                    throw new BSONError('key ' + key + ' must not contain null bytes');
+                }
+                if (checkKeys) {
+                    if ('$' === key[0]) {
+                        throw new BSONError('key ' + key + " must not start with '$'");
+                    }
+                    else if (key.includes('.')) {
+                        throw new BSONError('key ' + key + " must not contain '.'");
+                    }
+                }
+            }
+            if (value === undefined) {
+                if (ignoreUndefined === false)
+                    index = serializeNull(buffer, key, value, index);
+            }
+            else if (value === null) {
+                index = serializeNull(buffer, key, value, index);
+            }
+            else if (type === 'string') {
+                index = serializeString(buffer, key, value, index);
+            }
+            else if (type === 'number') {
+                index = serializeNumber(buffer, key, value, index);
+            }
+            else if (type === 'bigint') {
+                index = serializeBigInt(buffer, key, value, index);
+            }
+            else if (type === 'boolean') {
+                index = serializeBoolean(buffer, key, value, index);
+            }
+            else if (type === 'object' && value._bsontype == null) {
+                if (value instanceof Date || isDate(value)) {
+                    index = serializeDate(buffer, key, value, index);
+                }
+                else if (value instanceof Uint8Array || isUint8Array(value)) {
+                    index = serializeBuffer(buffer, key, value, index);
+                }
+                else if (value instanceof RegExp || isRegExp(value)) {
+                    index = serializeRegExp(buffer, key, value, index);
+                }
+                else {
+                    index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+            }
+            else if (type === 'object') {
+                if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+                    throw new BSONVersionError();
+                }
+                else if (value._bsontype === 'ObjectId') {
+                    index = serializeObjectId(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Decimal128') {
+                    index = serializeDecimal128(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
+                    index = serializeLong(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Double') {
+                    index = serializeDouble(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Code') {
+                    index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
+                }
+                else if (value._bsontype === 'Binary') {
+                    index = serializeBinary(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'BSONSymbol') {
+                    index = serializeSymbol(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'DBRef') {
+                    index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
+                }
+                else if (value._bsontype === 'BSONRegExp') {
+                    index = serializeBSONRegExp(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'Int32') {
+                    index = serializeInt32(buffer, key, value, index);
+                }
+                else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
+                    index = serializeMinMax(buffer, key, value, index);
+                }
+                else if (typeof value._bsontype !== 'undefined') {
+                    throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
+                }
+            }
+            else if (type === 'function' && serializeFunctions) {
+                index = serializeFunction(buffer, key, value, index);
+            }
+        }
+    }
+    path.delete(object);
+    buffer[index++] = 0x00;
+    const size = index - startingIndex;
+    startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size);
+    return index;
+}
+
+function isBSONType(value) {
+    return (value != null &&
+        typeof value === 'object' &&
+        '_bsontype' in value &&
+        typeof value._bsontype === 'string');
+}
+const keysToCodecs = {
+    $oid: ObjectId,
+    $binary: Binary,
+    $uuid: Binary,
+    $symbol: BSONSymbol,
+    $numberInt: Int32,
+    $numberDecimal: Decimal128,
+    $numberDouble: Double,
+    $numberLong: Long,
+    $minKey: MinKey,
+    $maxKey: MaxKey,
+    $regex: BSONRegExp,
+    $regularExpression: BSONRegExp,
+    $timestamp: Timestamp
+};
+function deserializeValue(value, options = {}) {
+    if (typeof value === 'number') {
+        const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
+        const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
+        if (options.relaxed || options.legacy) {
+            return value;
+        }
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (in32BitRange) {
+                return new Int32(value);
+            }
+            if (in64BitRange) {
+                if (options.useBigInt64) {
+                    return BigInt(value);
+                }
+                return Long.fromNumber(value);
+            }
+        }
+        return new Double(value);
+    }
+    if (value == null || typeof value !== 'object')
+        return value;
+    if (value.$undefined)
+        return null;
+    const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null);
+    for (let i = 0; i < keys.length; i++) {
+        const c = keysToCodecs[keys[i]];
+        if (c)
+            return c.fromExtendedJSON(value, options);
+    }
+    if (value.$date != null) {
+        const d = value.$date;
+        const date = new Date();
+        if (options.legacy) {
+            if (typeof d === 'number')
+                date.setTime(d);
+            else if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        else {
+            if (typeof d === 'string')
+                date.setTime(Date.parse(d));
+            else if (Long.isLong(d))
+                date.setTime(d.toNumber());
+            else if (typeof d === 'number' && options.relaxed)
+                date.setTime(d);
+            else if (typeof d === 'bigint')
+                date.setTime(Number(d));
+            else
+                throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
+        }
+        return date;
+    }
+    if (value.$code != null) {
+        const copy = Object.assign({}, value);
+        if (value.$scope) {
+            copy.$scope = deserializeValue(value.$scope);
+        }
+        return Code.fromExtendedJSON(value);
+    }
+    if (isDBRefLike(value) || value.$dbPointer) {
+        const v = value.$ref ? value : value.$dbPointer;
+        if (v instanceof DBRef)
+            return v;
+        const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
+        let valid = true;
+        dollarKeys.forEach(k => {
+            if (['$ref', '$id', '$db'].indexOf(k) === -1)
+                valid = false;
+        });
+        if (valid)
+            return DBRef.fromExtendedJSON(v);
+    }
+    return value;
+}
+function serializeArray(array, options) {
+    return array.map((v, index) => {
+        options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
+        try {
+            return serializeValue(v, options);
+        }
+        finally {
+            options.seenObjects.pop();
+        }
+    });
+}
+function getISOString(date) {
+    const isoStr = date.toISOString();
+    return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
+}
+function serializeValue(value, options) {
+    if (value instanceof Map || isMap(value)) {
+        const obj = Object.create(null);
+        for (const [k, v] of value) {
+            if (typeof k !== 'string') {
+                throw new BSONError('Can only serialize maps with string keys');
+            }
+            obj[k] = v;
+        }
+        return serializeValue(obj, options);
+    }
+    if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
+        const index = options.seenObjects.findIndex(entry => entry.obj === value);
+        if (index !== -1) {
+            const props = options.seenObjects.map(entry => entry.propertyName);
+            const leadingPart = props
+                .slice(0, index)
+                .map(prop => `${prop} -> `)
+                .join('');
+            const alreadySeen = props[index];
+            const circularPart = ' -> ' +
+                props
+                    .slice(index + 1, props.length - 1)
+                    .map(prop => `${prop} -> `)
+                    .join('');
+            const current = props[props.length - 1];
+            const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
+            const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
+            throw new BSONError('Converting circular structure to EJSON:\n' +
+                `    ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
+                `    ${leadingSpace}\\${dashes}/`);
+        }
+        options.seenObjects[options.seenObjects.length - 1].obj = value;
+    }
+    if (Array.isArray(value))
+        return serializeArray(value, options);
+    if (value === undefined)
+        return null;
+    if (value instanceof Date || isDate(value)) {
+        const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000;
+        if (options.legacy) {
+            return options.relaxed && inRange
+                ? { $date: value.getTime() }
+                : { $date: getISOString(value) };
+        }
+        return options.relaxed && inRange
+            ? { $date: getISOString(value) }
+            : { $date: { $numberLong: value.getTime().toString() } };
+    }
+    if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
+        if (Number.isInteger(value) && !Object.is(value, -0)) {
+            if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
+                return { $numberInt: value.toString() };
+            }
+            if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
+                return { $numberLong: value.toString() };
+            }
+        }
+        return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
+    }
+    if (typeof value === 'bigint') {
+        if (!options.relaxed) {
+            return { $numberLong: BigInt.asIntN(64, value).toString() };
+        }
+        return Number(BigInt.asIntN(64, value));
+    }
+    if (value instanceof RegExp || isRegExp(value)) {
+        let flags = value.flags;
+        if (flags === undefined) {
+            const match = value.toString().match(/[gimuy]*$/);
+            if (match) {
+                flags = match[0];
+            }
+        }
+        const rx = new BSONRegExp(value.source, flags);
+        return rx.toExtendedJSON(options);
+    }
+    if (value != null && typeof value === 'object')
+        return serializeDocument(value, options);
+    return value;
+}
+const BSON_TYPE_MAPPINGS = {
+    Binary: (o) => new Binary(o.value(), o.sub_type),
+    Code: (o) => new Code(o.code, o.scope),
+    DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
+    Decimal128: (o) => new Decimal128(o.bytes),
+    Double: (o) => new Double(o.value),
+    Int32: (o) => new Int32(o.value),
+    Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_),
+    MaxKey: () => new MaxKey(),
+    MinKey: () => new MinKey(),
+    ObjectId: (o) => new ObjectId(o),
+    BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
+    BSONSymbol: (o) => new BSONSymbol(o.value),
+    Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
+};
+function serializeDocument(doc, options) {
+    if (doc == null || typeof doc !== 'object')
+        throw new BSONError('not an object instance');
+    const bsontype = doc._bsontype;
+    if (typeof bsontype === 'undefined') {
+        const _doc = {};
+        for (const name of Object.keys(doc)) {
+            options.seenObjects.push({ propertyName: name, obj: null });
+            try {
+                const value = serializeValue(doc[name], options);
+                if (name === '__proto__') {
+                    Object.defineProperty(_doc, name, {
+                        value,
+                        writable: true,
+                        enumerable: true,
+                        configurable: true
+                    });
+                }
+                else {
+                    _doc[name] = value;
+                }
+            }
+            finally {
+                options.seenObjects.pop();
+            }
+        }
+        return _doc;
+    }
+    else if (doc != null &&
+        typeof doc === 'object' &&
+        typeof doc._bsontype === 'string' &&
+        doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
+        throw new BSONVersionError();
+    }
+    else if (isBSONType(doc)) {
+        let outDoc = doc;
+        if (typeof outDoc.toExtendedJSON !== 'function') {
+            const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
+            if (!mapper) {
+                throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
+            }
+            outDoc = mapper(outDoc);
+        }
+        if (bsontype === 'Code' && outDoc.scope) {
+            outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
+        }
+        else if (bsontype === 'DBRef' && outDoc.oid) {
+            outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
+        }
+        return outDoc.toExtendedJSON(options);
+    }
+    else {
+        throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
+    }
+}
+function parse(text, options) {
+    const ejsonOptions = {
+        useBigInt64: options?.useBigInt64 ?? false,
+        relaxed: options?.relaxed ?? true,
+        legacy: options?.legacy ?? false
+    };
+    return JSON.parse(text, (key, value) => {
+        if (key.indexOf('\x00') !== -1) {
+            throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
+        }
+        return deserializeValue(value, ejsonOptions);
+    });
+}
+function stringify(value, replacer, space, options) {
+    if (space != null && typeof space === 'object') {
+        options = space;
+        space = 0;
+    }
+    if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
+        options = replacer;
+        replacer = undefined;
+        space = 0;
+    }
+    const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
+        seenObjects: [{ propertyName: '(root)', obj: null }]
+    });
+    const doc = serializeValue(value, serializeOptions);
+    return JSON.stringify(doc, replacer, space);
+}
+function EJSONserialize(value, options) {
+    options = options || {};
+    return JSON.parse(stringify(value, options));
+}
+function EJSONdeserialize(ejson, options) {
+    options = options || {};
+    return parse(JSON.stringify(ejson), options);
+}
+const EJSON = Object.create(null);
+EJSON.parse = parse;
+EJSON.stringify = stringify;
+EJSON.serialize = EJSONserialize;
+EJSON.deserialize = EJSONdeserialize;
+Object.freeze(EJSON);
+
+const BSONElementType = {
+    double: 1,
+    string: 2,
+    object: 3,
+    array: 4,
+    binData: 5,
+    undefined: 6,
+    objectId: 7,
+    bool: 8,
+    date: 9,
+    null: 10,
+    regex: 11,
+    dbPointer: 12,
+    javascript: 13,
+    symbol: 14,
+    javascriptWithScope: 15,
+    int: 16,
+    timestamp: 17,
+    long: 18,
+    decimal: 19,
+    minKey: 255,
+    maxKey: 127
+};
+function getSize(source, offset) {
+    try {
+        return NumberUtils.getNonnegativeInt32LE(source, offset);
+    }
+    catch (cause) {
+        throw new BSONOffsetError('BSON size cannot be negative', offset, { cause });
+    }
+}
+function findNull(bytes, offset) {
+    let nullTerminatorOffset = offset;
+    for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++)
+        ;
+    if (nullTerminatorOffset === bytes.length - 1) {
+        throw new BSONOffsetError('Null terminator not found', offset);
+    }
+    return nullTerminatorOffset;
+}
+function parseToElements(bytes, startOffset = 0) {
+    startOffset ??= 0;
+    if (bytes.length < 5) {
+        throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
+    }
+    const documentSize = getSize(bytes, startOffset);
+    if (documentSize > bytes.length - startOffset) {
+        throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
+    }
+    if (bytes[startOffset + documentSize - 1] !== 0x00) {
+        throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize);
+    }
+    const elements = [];
+    let offset = startOffset + 4;
+    while (offset <= documentSize + startOffset) {
+        const type = bytes[offset];
+        offset += 1;
+        if (type === 0) {
+            if (offset - startOffset !== documentSize) {
+                throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
+            }
+            break;
+        }
+        const nameOffset = offset;
+        const nameLength = findNull(bytes, offset) - nameOffset;
+        offset += nameLength + 1;
+        let length;
+        if (type === BSONElementType.double ||
+            type === BSONElementType.long ||
+            type === BSONElementType.date ||
+            type === BSONElementType.timestamp) {
+            length = 8;
+        }
+        else if (type === BSONElementType.int) {
+            length = 4;
+        }
+        else if (type === BSONElementType.objectId) {
+            length = 12;
+        }
+        else if (type === BSONElementType.decimal) {
+            length = 16;
+        }
+        else if (type === BSONElementType.bool) {
+            length = 1;
+        }
+        else if (type === BSONElementType.null ||
+            type === BSONElementType.undefined ||
+            type === BSONElementType.maxKey ||
+            type === BSONElementType.minKey) {
+            length = 0;
+        }
+        else if (type === BSONElementType.regex) {
+            length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
+        }
+        else if (type === BSONElementType.object ||
+            type === BSONElementType.array ||
+            type === BSONElementType.javascriptWithScope) {
+            length = getSize(bytes, offset);
+        }
+        else if (type === BSONElementType.string ||
+            type === BSONElementType.binData ||
+            type === BSONElementType.dbPointer ||
+            type === BSONElementType.javascript ||
+            type === BSONElementType.symbol) {
+            length = getSize(bytes, offset) + 4;
+            if (type === BSONElementType.binData) {
+                length += 1;
+            }
+            if (type === BSONElementType.dbPointer) {
+                length += 12;
+            }
+        }
+        else {
+            throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset);
+        }
+        if (length > documentSize) {
+            throw new BSONOffsetError('value reports length larger than document', offset);
+        }
+        elements.push([type, nameOffset, nameLength, offset, length]);
+        offset += length;
+    }
+    return elements;
+}
+
+const onDemand = Object.create(null);
+onDemand.parseToElements = parseToElements;
+onDemand.ByteUtils = ByteUtils;
+onDemand.NumberUtils = NumberUtils;
+Object.freeze(onDemand);
+
+const MAXSIZE = 1024 * 1024 * 17;
+let buffer = ByteUtils.allocate(MAXSIZE);
+function setInternalBufferSize(size) {
+    if (buffer.length < size) {
+        buffer = ByteUtils.allocate(size);
+    }
+}
+function serialize(object, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
+    if (buffer.length < minInternalBufferSize) {
+        buffer = ByteUtils.allocate(minInternalBufferSize);
+    }
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex);
+    finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
+    return finishedBuffer;
+}
+function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
+    const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    const startIndex = typeof options.index === 'number' ? options.index : 0;
+    const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
+    finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
+    return startIndex + serializationIndex - 1;
+}
+function deserialize(buffer, options = {}) {
+    return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
+}
+function calculateObjectSize(object, options = {}) {
+    options = options || {};
+    const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
+    const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
+    return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
+}
+function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
+    const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
+    const bufferData = ByteUtils.toLocalBufferType(data);
+    let index = startIndex;
+    for (let i = 0; i < numberOfDocuments; i++) {
+        const size = NumberUtils.getInt32LE(bufferData, index);
+        internalOptions.index = index;
+        documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
+        index = index + size;
+    }
+    return index;
+}
+
+var bson = /*#__PURE__*/Object.freeze({
+    __proto__: null,
+    BSONError: BSONError,
+    BSONOffsetError: BSONOffsetError,
+    BSONRegExp: BSONRegExp,
+    BSONRuntimeError: BSONRuntimeError,
+    BSONSymbol: BSONSymbol,
+    BSONType: BSONType,
+    BSONValue: BSONValue,
+    BSONVersionError: BSONVersionError,
+    Binary: Binary,
+    Code: Code,
+    DBRef: DBRef,
+    Decimal128: Decimal128,
+    Double: Double,
+    EJSON: EJSON,
+    Int32: Int32,
+    Long: Long,
+    MaxKey: MaxKey,
+    MinKey: MinKey,
+    ObjectId: ObjectId,
+    Timestamp: Timestamp,
+    UUID: UUID,
+    bsonType: bsonType,
+    calculateObjectSize: calculateObjectSize,
+    deserialize: deserialize,
+    deserializeStream: deserializeStream,
+    onDemand: onDemand,
+    serialize: serialize,
+    serializeWithBufferAndIndex: serializeWithBufferAndIndex,
+    setInternalBufferSize: setInternalBufferSize
+});
+
+exports.BSON = bson;
+exports.BSONError = BSONError;
+exports.BSONOffsetError = BSONOffsetError;
+exports.BSONRegExp = BSONRegExp;
+exports.BSONRuntimeError = BSONRuntimeError;
+exports.BSONSymbol = BSONSymbol;
+exports.BSONType = BSONType;
+exports.BSONValue = BSONValue;
+exports.BSONVersionError = BSONVersionError;
+exports.Binary = Binary;
+exports.Code = Code;
+exports.DBRef = DBRef;
+exports.Decimal128 = Decimal128;
+exports.Double = Double;
+exports.EJSON = EJSON;
+exports.Int32 = Int32;
+exports.Long = Long;
+exports.MaxKey = MaxKey;
+exports.MinKey = MinKey;
+exports.ObjectId = ObjectId;
+exports.Timestamp = Timestamp;
+exports.UUID = UUID;
+exports.bsonType = bsonType;
+exports.calculateObjectSize = calculateObjectSize;
+exports.deserialize = deserialize;
+exports.deserializeStream = deserializeStream;
+exports.onDemand = onDemand;
+exports.serialize = serialize;
+exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
+exports.setInternalBufferSize = setInternalBufferSize;
+//# sourceMappingURL=bson.rn.cjs.map

Неке датотеке нису приказане због велике количине промена