opusdev/vector-similarity-api
1
1var BSON = (function (exports) {2'use strict';3 4const TypedArrayPrototypeGetSymbolToStringTag = (() => {5 const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;6 return (value) => g.call(value);7})();8function isUint8Array(value) {9 return TypedArrayPrototypeGetSymbolToStringTag(value) === 'Uint8Array';10}11function isAnyArrayBuffer(value) {12 return (typeof value === 'object' &&13 value != null &&14 Symbol.toStringTag in value &&15 (value[Symbol.toStringTag] === 'ArrayBuffer' ||16 value[Symbol.toStringTag] === 'SharedArrayBuffer'));17}18function isRegExp(regexp) {19 return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === '[object RegExp]';20}21function isMap(value) {22 return (typeof value === 'object' &&23 value != null &&24 Symbol.toStringTag in value &&25 value[Symbol.toStringTag] === 'Map');26}27function isDate(date) {28 return date instanceof Date || Object.prototype.toString.call(date) === '[object Date]';29}30function defaultInspect(x, _options) {31 return JSON.stringify(x, (k, v) => {32 if (typeof v === 'bigint') {33 return { $numberLong: `${v}` };34 }35 else if (isMap(v)) {36 return Object.fromEntries(v);37 }38 return v;39 });40}41function getStylizeFunction(options) {42 const stylizeExists = options != null &&43 typeof options === 'object' &&44 'stylize' in options &&45 typeof options.stylize === 'function';46 if (stylizeExists) {47 return options.stylize;48 }49}50 51const BSON_MAJOR_VERSION = 6;52const BSON_VERSION_SYMBOL = Symbol.for('@@mdb.bson.version');53const BSON_INT32_MAX = 0x7fffffff;54const BSON_INT32_MIN = -2147483648;55const BSON_INT64_MAX = Math.pow(2, 63) - 1;56const BSON_INT64_MIN = -Math.pow(2, 63);57const JS_INT_MAX = Math.pow(2, 53);58const JS_INT_MIN = -Math.pow(2, 53);59const BSON_DATA_NUMBER = 1;60const BSON_DATA_STRING = 2;61const BSON_DATA_OBJECT = 3;62const BSON_DATA_ARRAY = 4;63const BSON_DATA_BINARY = 5;64const BSON_DATA_UNDEFINED = 6;65const BSON_DATA_OID = 7;66const BSON_DATA_BOOLEAN = 8;67const BSON_DATA_DATE = 9;68const BSON_DATA_NULL = 10;69const BSON_DATA_REGEXP = 11;70const BSON_DATA_DBPOINTER = 12;71const BSON_DATA_CODE = 13;72const BSON_DATA_SYMBOL = 14;73const BSON_DATA_CODE_W_SCOPE = 15;74const BSON_DATA_INT = 16;75const BSON_DATA_TIMESTAMP = 17;76const BSON_DATA_LONG = 18;77const BSON_DATA_DECIMAL128 = 19;78const BSON_DATA_MIN_KEY = 0xff;79const BSON_DATA_MAX_KEY = 0x7f;80const BSON_BINARY_SUBTYPE_DEFAULT = 0;81const BSON_BINARY_SUBTYPE_UUID_NEW = 4;82const BSONType = Object.freeze({83 double: 1,84 string: 2,85 object: 3,86 array: 4,87 binData: 5,88 undefined: 6,89 objectId: 7,90 bool: 8,91 date: 9,92 null: 10,93 regex: 11,94 dbPointer: 12,95 javascript: 13,96 symbol: 14,97 javascriptWithScope: 15,98 int: 16,99 timestamp: 17,100 long: 18,101 decimal: 19,102 minKey: -1,103 maxKey: 127104});105 106class BSONError extends Error {107 get bsonError() {108 return true;109 }110 get name() {111 return 'BSONError';112 }113 constructor(message, options) {114 super(message, options);115 }116 static isBSONError(value) {117 return (value != null &&118 typeof value === 'object' &&119 'bsonError' in value &&120 value.bsonError === true &&121 'name' in value &&122 'message' in value &&123 'stack' in value);124 }125}126class BSONVersionError extends BSONError {127 get name() {128 return 'BSONVersionError';129 }130 constructor() {131 super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);132 }133}134class BSONRuntimeError extends BSONError {135 get name() {136 return 'BSONRuntimeError';137 }138 constructor(message) {139 super(message);140 }141}142class BSONOffsetError extends BSONError {143 get name() {144 return 'BSONOffsetError';145 }146 constructor(message, offset, options) {147 super(`${message}. offset: ${offset}`, options);148 this.offset = offset;149 }150}151 152let TextDecoderFatal;153let TextDecoderNonFatal;154function parseUtf8(buffer, start, end, fatal) {155 if (fatal) {156 TextDecoderFatal ??= new TextDecoder('utf8', { fatal: true });157 try {158 return TextDecoderFatal.decode(buffer.subarray(start, end));159 }160 catch (cause) {161 throw new BSONError('Invalid UTF-8 string in BSON document', { cause });162 }163 }164 TextDecoderNonFatal ??= new TextDecoder('utf8', { fatal: false });165 return TextDecoderNonFatal.decode(buffer.subarray(start, end));166}167 168function tryReadBasicLatin(uint8array, start, end) {169 if (uint8array.length === 0) {170 return '';171 }172 const stringByteLength = end - start;173 if (stringByteLength === 0) {174 return '';175 }176 if (stringByteLength > 20) {177 return null;178 }179 if (stringByteLength === 1 && uint8array[start] < 128) {180 return String.fromCharCode(uint8array[start]);181 }182 if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {183 return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);184 }185 if (stringByteLength === 3 &&186 uint8array[start] < 128 &&187 uint8array[start + 1] < 128 &&188 uint8array[start + 2] < 128) {189 return (String.fromCharCode(uint8array[start]) +190 String.fromCharCode(uint8array[start + 1]) +191 String.fromCharCode(uint8array[start + 2]));192 }193 const latinBytes = [];194 for (let i = start; i < end; i++) {195 const byte = uint8array[i];196 if (byte > 127) {197 return null;198 }199 latinBytes.push(byte);200 }201 return String.fromCharCode(...latinBytes);202}203function tryWriteBasicLatin(destination, source, offset) {204 if (source.length === 0)205 return 0;206 if (source.length > 25)207 return null;208 if (destination.length - offset < source.length)209 return null;210 for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {211 const char = source.charCodeAt(charOffset);212 if (char > 127)213 return null;214 destination[destinationOffset] = char;215 }216 return source.length;217}218 219function nodejsMathRandomBytes(byteLength) {220 return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));221}222const nodejsRandomBytes = (() => {223 try {224 return require('crypto').randomBytes;225 }226 catch {227 return nodejsMathRandomBytes;228 }229})();230const nodeJsByteUtils = {231 toLocalBufferType(potentialBuffer) {232 if (Buffer.isBuffer(potentialBuffer)) {233 return potentialBuffer;234 }235 if (ArrayBuffer.isView(potentialBuffer)) {236 return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);237 }238 const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);239 if (stringTag === 'ArrayBuffer' ||240 stringTag === 'SharedArrayBuffer' ||241 stringTag === '[object ArrayBuffer]' ||242 stringTag === '[object SharedArrayBuffer]') {243 return Buffer.from(potentialBuffer);244 }245 throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);246 },247 allocate(size) {248 return Buffer.alloc(size);249 },250 allocateUnsafe(size) {251 return Buffer.allocUnsafe(size);252 },253 equals(a, b) {254 return nodeJsByteUtils.toLocalBufferType(a).equals(b);255 },256 fromNumberArray(array) {257 return Buffer.from(array);258 },259 fromBase64(base64) {260 return Buffer.from(base64, 'base64');261 },262 toBase64(buffer) {263 return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');264 },265 fromISO88591(codePoints) {266 return Buffer.from(codePoints, 'binary');267 },268 toISO88591(buffer) {269 return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');270 },271 fromHex(hex) {272 return Buffer.from(hex, 'hex');273 },274 toHex(buffer) {275 return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');276 },277 toUTF8(buffer, start, end, fatal) {278 const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null;279 if (basicLatin != null) {280 return basicLatin;281 }282 const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);283 if (fatal) {284 for (let i = 0; i < string.length; i++) {285 if (string.charCodeAt(i) === 0xfffd) {286 parseUtf8(buffer, start, end, true);287 break;288 }289 }290 }291 return string;292 },293 utf8ByteLength(input) {294 return Buffer.byteLength(input, 'utf8');295 },296 encodeUTF8Into(buffer, source, byteOffset) {297 const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset);298 if (latinBytesWritten != null) {299 return latinBytesWritten;300 }301 return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');302 },303 randomBytes: nodejsRandomBytes,304 swap32(buffer) {305 return nodeJsByteUtils.toLocalBufferType(buffer).swap32();306 }307};308 309function isReactNative() {310 const { navigator } = globalThis;311 return typeof navigator === 'object' && navigator.product === 'ReactNative';312}313function webMathRandomBytes(byteLength) {314 if (byteLength < 0) {315 throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);316 }317 return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));318}319const webRandomBytes = (() => {320 const { crypto } = globalThis;321 if (crypto != null && typeof crypto.getRandomValues === 'function') {322 return (byteLength) => {323 return crypto.getRandomValues(webByteUtils.allocate(byteLength));324 };325 }326 else {327 if (isReactNative()) {328 const { console } = globalThis;329 console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');330 }331 return webMathRandomBytes;332 }333})();334const HEX_DIGIT = /(\d|[a-f])/i;335const webByteUtils = {336 toLocalBufferType(potentialUint8array) {337 const stringTag = potentialUint8array?.[Symbol.toStringTag] ??338 Object.prototype.toString.call(potentialUint8array);339 if (stringTag === 'Uint8Array') {340 return potentialUint8array;341 }342 if (ArrayBuffer.isView(potentialUint8array)) {343 return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));344 }345 if (stringTag === 'ArrayBuffer' ||346 stringTag === 'SharedArrayBuffer' ||347 stringTag === '[object ArrayBuffer]' ||348 stringTag === '[object SharedArrayBuffer]') {349 return new Uint8Array(potentialUint8array);350 }351 throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);352 },353 allocate(size) {354 if (typeof size !== 'number') {355 throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);356 }357 return new Uint8Array(size);358 },359 allocateUnsafe(size) {360 return webByteUtils.allocate(size);361 },362 equals(a, b) {363 if (a.byteLength !== b.byteLength) {364 return false;365 }366 for (let i = 0; i < a.byteLength; i++) {367 if (a[i] !== b[i]) {368 return false;369 }370 }371 return true;372 },373 fromNumberArray(array) {374 return Uint8Array.from(array);375 },376 fromBase64(base64) {377 return Uint8Array.from(atob(base64), c => c.charCodeAt(0));378 },379 toBase64(uint8array) {380 return btoa(webByteUtils.toISO88591(uint8array));381 },382 fromISO88591(codePoints) {383 return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);384 },385 toISO88591(uint8array) {386 return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');387 },388 fromHex(hex) {389 const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);390 const buffer = [];391 for (let i = 0; i < evenLengthHex.length; i += 2) {392 const firstDigit = evenLengthHex[i];393 const secondDigit = evenLengthHex[i + 1];394 if (!HEX_DIGIT.test(firstDigit)) {395 break;396 }397 if (!HEX_DIGIT.test(secondDigit)) {398 break;399 }400 const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);401 buffer.push(hexDigit);402 }403 return Uint8Array.from(buffer);404 },405 toHex(uint8array) {406 return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');407 },408 toUTF8(uint8array, start, end, fatal) {409 const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;410 if (basicLatin != null) {411 return basicLatin;412 }413 return parseUtf8(uint8array, start, end, fatal);414 },415 utf8ByteLength(input) {416 return new TextEncoder().encode(input).byteLength;417 },418 encodeUTF8Into(uint8array, source, byteOffset) {419 const bytes = new TextEncoder().encode(source);420 uint8array.set(bytes, byteOffset);421 return bytes.byteLength;422 },423 randomBytes: webRandomBytes,424 swap32(buffer) {425 if (buffer.length % 4 !== 0) {426 throw new RangeError('Buffer size must be a multiple of 32-bits');427 }428 for (let i = 0; i < buffer.length; i += 4) {429 const byte0 = buffer[i];430 const byte1 = buffer[i + 1];431 const byte2 = buffer[i + 2];432 const byte3 = buffer[i + 3];433 buffer[i] = byte3;434 buffer[i + 1] = byte2;435 buffer[i + 2] = byte1;436 buffer[i + 3] = byte0;437 }438 return buffer;439 }440};441 442const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;443const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;444 445class BSONValue {446 get [BSON_VERSION_SYMBOL]() {447 return BSON_MAJOR_VERSION;448 }449 [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) {450 return this.inspect(depth, options, inspect);451 }452}453 454const FLOAT = new Float64Array(1);455const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);456FLOAT[0] = -1;457const isBigEndian = FLOAT_BYTES[7] === 0;458const NumberUtils = {459 isBigEndian,460 getNonnegativeInt32LE(source, offset) {461 if (source[offset + 3] > 127) {462 throw new RangeError(`Size cannot be negative at offset: ${offset}`);463 }464 return (source[offset] |465 (source[offset + 1] << 8) |466 (source[offset + 2] << 16) |467 (source[offset + 3] << 24));468 },469 getInt32LE(source, offset) {470 return (source[offset] |471 (source[offset + 1] << 8) |472 (source[offset + 2] << 16) |473 (source[offset + 3] << 24));474 },475 getUint32LE(source, offset) {476 return (source[offset] +477 source[offset + 1] * 256 +478 source[offset + 2] * 65536 +479 source[offset + 3] * 16777216);480 },481 getUint32BE(source, offset) {482 return (source[offset + 3] +483 source[offset + 2] * 256 +484 source[offset + 1] * 65536 +485 source[offset] * 16777216);486 },487 getBigInt64LE(source, offset) {488 const hi = BigInt(source[offset + 4] +489 source[offset + 5] * 256 +490 source[offset + 6] * 65536 +491 (source[offset + 7] << 24));492 const lo = BigInt(source[offset] +493 source[offset + 1] * 256 +494 source[offset + 2] * 65536 +495 source[offset + 3] * 16777216);496 return (hi << BigInt(32)) + lo;497 },498 getFloat64LE: isBigEndian499 ? (source, offset) => {500 FLOAT_BYTES[7] = source[offset];501 FLOAT_BYTES[6] = source[offset + 1];502 FLOAT_BYTES[5] = source[offset + 2];503 FLOAT_BYTES[4] = source[offset + 3];504 FLOAT_BYTES[3] = source[offset + 4];505 FLOAT_BYTES[2] = source[offset + 5];506 FLOAT_BYTES[1] = source[offset + 6];507 FLOAT_BYTES[0] = source[offset + 7];508 return FLOAT[0];509 }510 : (source, offset) => {511 FLOAT_BYTES[0] = source[offset];512 FLOAT_BYTES[1] = source[offset + 1];513 FLOAT_BYTES[2] = source[offset + 2];514 FLOAT_BYTES[3] = source[offset + 3];515 FLOAT_BYTES[4] = source[offset + 4];516 FLOAT_BYTES[5] = source[offset + 5];517 FLOAT_BYTES[6] = source[offset + 6];518 FLOAT_BYTES[7] = source[offset + 7];519 return FLOAT[0];520 },521 setInt32BE(destination, offset, value) {522 destination[offset + 3] = value;523 value >>>= 8;524 destination[offset + 2] = value;525 value >>>= 8;526 destination[offset + 1] = value;527 value >>>= 8;528 destination[offset] = value;529 return 4;530 },531 setInt32LE(destination, offset, value) {532 destination[offset] = value;533 value >>>= 8;534 destination[offset + 1] = value;535 value >>>= 8;536 destination[offset + 2] = value;537 value >>>= 8;538 destination[offset + 3] = value;539 return 4;540 },541 setBigInt64LE(destination, offset, value) {542 const mask32bits = BigInt(0xffff_ffff);543 let lo = Number(value & mask32bits);544 destination[offset] = lo;545 lo >>= 8;546 destination[offset + 1] = lo;547 lo >>= 8;548 destination[offset + 2] = lo;549 lo >>= 8;550 destination[offset + 3] = lo;551 let hi = Number((value >> BigInt(32)) & mask32bits);552 destination[offset + 4] = hi;553 hi >>= 8;554 destination[offset + 5] = hi;555 hi >>= 8;556 destination[offset + 6] = hi;557 hi >>= 8;558 destination[offset + 7] = hi;559 return 8;560 },561 setFloat64LE: isBigEndian562 ? (destination, offset, value) => {563 FLOAT[0] = value;564 destination[offset] = FLOAT_BYTES[7];565 destination[offset + 1] = FLOAT_BYTES[6];566 destination[offset + 2] = FLOAT_BYTES[5];567 destination[offset + 3] = FLOAT_BYTES[4];568 destination[offset + 4] = FLOAT_BYTES[3];569 destination[offset + 5] = FLOAT_BYTES[2];570 destination[offset + 6] = FLOAT_BYTES[1];571 destination[offset + 7] = FLOAT_BYTES[0];572 return 8;573 }574 : (destination, offset, value) => {575 FLOAT[0] = value;576 destination[offset] = FLOAT_BYTES[0];577 destination[offset + 1] = FLOAT_BYTES[1];578 destination[offset + 2] = FLOAT_BYTES[2];579 destination[offset + 3] = FLOAT_BYTES[3];580 destination[offset + 4] = FLOAT_BYTES[4];581 destination[offset + 5] = FLOAT_BYTES[5];582 destination[offset + 6] = FLOAT_BYTES[6];583 destination[offset + 7] = FLOAT_BYTES[7];584 return 8;585 }586};587 588class Binary extends BSONValue {589 get _bsontype() {590 return 'Binary';591 }592 constructor(buffer, subType) {593 super();594 if (!(buffer == null) &&595 typeof buffer === 'string' &&596 !ArrayBuffer.isView(buffer) &&597 !isAnyArrayBuffer(buffer) &&598 !Array.isArray(buffer)) {599 throw new BSONError('Binary can only be constructed from Uint8Array or number[]');600 }601 this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;602 if (buffer == null) {603 this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);604 this.position = 0;605 }606 else {607 this.buffer = Array.isArray(buffer)608 ? ByteUtils.fromNumberArray(buffer)609 : ByteUtils.toLocalBufferType(buffer);610 this.position = this.buffer.byteLength;611 }612 }613 put(byteValue) {614 if (typeof byteValue === 'string' && byteValue.length !== 1) {615 throw new BSONError('only accepts single character String');616 }617 else if (typeof byteValue !== 'number' && byteValue.length !== 1)618 throw new BSONError('only accepts single character Uint8Array or Array');619 let decodedByte;620 if (typeof byteValue === 'string') {621 decodedByte = byteValue.charCodeAt(0);622 }623 else if (typeof byteValue === 'number') {624 decodedByte = byteValue;625 }626 else {627 decodedByte = byteValue[0];628 }629 if (decodedByte < 0 || decodedByte > 255) {630 throw new BSONError('only accepts number in a valid unsigned byte range 0-255');631 }632 if (this.buffer.byteLength > this.position) {633 this.buffer[this.position++] = decodedByte;634 }635 else {636 const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);637 newSpace.set(this.buffer, 0);638 this.buffer = newSpace;639 this.buffer[this.position++] = decodedByte;640 }641 }642 write(sequence, offset) {643 offset = typeof offset === 'number' ? offset : this.position;644 if (this.buffer.byteLength < offset + sequence.length) {645 const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);646 newSpace.set(this.buffer, 0);647 this.buffer = newSpace;648 }649 if (ArrayBuffer.isView(sequence)) {650 this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);651 this.position =652 offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;653 }654 else if (typeof sequence === 'string') {655 throw new BSONError('input cannot be string');656 }657 }658 read(position, length) {659 length = length && length > 0 ? length : this.position;660 const end = position + length;661 return this.buffer.subarray(position, end > this.position ? this.position : end);662 }663 value() {664 return this.buffer.length === this.position665 ? this.buffer666 : this.buffer.subarray(0, this.position);667 }668 length() {669 return this.position;670 }671 toJSON() {672 return ByteUtils.toBase64(this.buffer.subarray(0, this.position));673 }674 toString(encoding) {675 if (encoding === 'hex')676 return ByteUtils.toHex(this.buffer.subarray(0, this.position));677 if (encoding === 'base64')678 return ByteUtils.toBase64(this.buffer.subarray(0, this.position));679 if (encoding === 'utf8' || encoding === 'utf-8')680 return ByteUtils.toUTF8(this.buffer, 0, this.position, false);681 return ByteUtils.toUTF8(this.buffer, 0, this.position, false);682 }683 toExtendedJSON(options) {684 options = options || {};685 if (this.sub_type === Binary.SUBTYPE_VECTOR) {686 validateBinaryVector(this);687 }688 const base64String = ByteUtils.toBase64(this.buffer);689 const subType = Number(this.sub_type).toString(16);690 if (options.legacy) {691 return {692 $binary: base64String,693 $type: subType.length === 1 ? '0' + subType : subType694 };695 }696 return {697 $binary: {698 base64: base64String,699 subType: subType.length === 1 ? '0' + subType : subType700 }701 };702 }703 toUUID() {704 if (this.sub_type === Binary.SUBTYPE_UUID) {705 return new UUID(this.buffer.subarray(0, this.position));706 }707 throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);708 }709 static createFromHexString(hex, subType) {710 return new Binary(ByteUtils.fromHex(hex), subType);711 }712 static createFromBase64(base64, subType) {713 return new Binary(ByteUtils.fromBase64(base64), subType);714 }715 static fromExtendedJSON(doc, options) {716 options = options || {};717 let data;718 let type;719 if ('$binary' in doc) {720 if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {721 type = doc.$type ? parseInt(doc.$type, 16) : 0;722 data = ByteUtils.fromBase64(doc.$binary);723 }724 else {725 if (typeof doc.$binary !== 'string') {726 type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;727 data = ByteUtils.fromBase64(doc.$binary.base64);728 }729 }730 }731 else if ('$uuid' in doc) {732 type = 4;733 data = UUID.bytesFromString(doc.$uuid);734 }735 if (!data) {736 throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);737 }738 return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);739 }740 inspect(depth, options, inspect) {741 inspect ??= defaultInspect;742 const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));743 const base64Arg = inspect(base64, options);744 const subTypeArg = inspect(this.sub_type, options);745 return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;746 }747 toInt8Array() {748 if (this.sub_type !== Binary.SUBTYPE_VECTOR) {749 throw new BSONError('Binary sub_type is not Vector');750 }751 if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {752 throw new BSONError('Binary datatype field is not Int8');753 }754 validateBinaryVector(this);755 return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));756 }757 toFloat32Array() {758 if (this.sub_type !== Binary.SUBTYPE_VECTOR) {759 throw new BSONError('Binary sub_type is not Vector');760 }761 if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {762 throw new BSONError('Binary datatype field is not Float32');763 }764 validateBinaryVector(this);765 const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));766 if (NumberUtils.isBigEndian)767 ByteUtils.swap32(floatBytes);768 return new Float32Array(floatBytes.buffer);769 }770 toPackedBits() {771 if (this.sub_type !== Binary.SUBTYPE_VECTOR) {772 throw new BSONError('Binary sub_type is not Vector');773 }774 if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {775 throw new BSONError('Binary datatype field is not packed bit');776 }777 validateBinaryVector(this);778 return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));779 }780 toBits() {781 if (this.sub_type !== Binary.SUBTYPE_VECTOR) {782 throw new BSONError('Binary sub_type is not Vector');783 }784 if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {785 throw new BSONError('Binary datatype field is not packed bit');786 }787 validateBinaryVector(this);788 const byteCount = this.length() - 2;789 const bitCount = byteCount * 8 - this.buffer[1];790 const bits = new Int8Array(bitCount);791 for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {792 const byteOffset = (bitOffset / 8) | 0;793 const byte = this.buffer[byteOffset + 2];794 const shift = 7 - (bitOffset % 8);795 const bit = (byte >> shift) & 1;796 bits[bitOffset] = bit;797 }798 return bits;799 }800 static fromInt8Array(array) {801 const buffer = ByteUtils.allocate(array.byteLength + 2);802 buffer[0] = Binary.VECTOR_TYPE.Int8;803 buffer[1] = 0;804 const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);805 buffer.set(intBytes, 2);806 const bin = new this(buffer, this.SUBTYPE_VECTOR);807 validateBinaryVector(bin);808 return bin;809 }810 static fromFloat32Array(array) {811 const binaryBytes = ByteUtils.allocate(array.byteLength + 2);812 binaryBytes[0] = Binary.VECTOR_TYPE.Float32;813 binaryBytes[1] = 0;814 const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);815 binaryBytes.set(floatBytes, 2);816 if (NumberUtils.isBigEndian)817 ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));818 const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);819 validateBinaryVector(bin);820 return bin;821 }822 static fromPackedBits(array, padding = 0) {823 const buffer = ByteUtils.allocate(array.byteLength + 2);824 buffer[0] = Binary.VECTOR_TYPE.PackedBit;825 buffer[1] = padding;826 buffer.set(array, 2);827 const bin = new this(buffer, this.SUBTYPE_VECTOR);828 validateBinaryVector(bin);829 return bin;830 }831 static fromBits(bits) {832 const byteLength = (bits.length + 7) >>> 3;833 const bytes = new Uint8Array(byteLength + 2);834 bytes[0] = Binary.VECTOR_TYPE.PackedBit;835 const remainder = bits.length % 8;836 bytes[1] = remainder === 0 ? 0 : 8 - remainder;837 for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {838 const byteOffset = bitOffset >>> 3;839 const bit = bits[bitOffset];840 if (bit !== 0 && bit !== 1) {841 throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);842 }843 if (bit === 0)844 continue;845 const shift = 7 - (bitOffset % 8);846 bytes[byteOffset + 2] |= bit << shift;847 }848 return new this(bytes, Binary.SUBTYPE_VECTOR);849 }850}851Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;852Binary.BUFFER_SIZE = 256;853Binary.SUBTYPE_DEFAULT = 0;854Binary.SUBTYPE_FUNCTION = 1;855Binary.SUBTYPE_BYTE_ARRAY = 2;856Binary.SUBTYPE_UUID_OLD = 3;857Binary.SUBTYPE_UUID = 4;858Binary.SUBTYPE_MD5 = 5;859Binary.SUBTYPE_ENCRYPTED = 6;860Binary.SUBTYPE_COLUMN = 7;861Binary.SUBTYPE_SENSITIVE = 8;862Binary.SUBTYPE_VECTOR = 9;863Binary.SUBTYPE_USER_DEFINED = 128;864Binary.VECTOR_TYPE = Object.freeze({865 Int8: 0x03,866 Float32: 0x27,867 PackedBit: 0x10868});869function validateBinaryVector(vector) {870 if (vector.sub_type !== Binary.SUBTYPE_VECTOR)871 return;872 const size = vector.position;873 const datatype = vector.buffer[0];874 const padding = vector.buffer[1];875 if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) &&876 padding !== 0) {877 throw new BSONError('Invalid Vector: padding must be zero for int8 and float32 vectors');878 }879 if (datatype === Binary.VECTOR_TYPE.Float32) {880 if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {881 throw new BSONError('Invalid Vector: Float32 vector must contain a multiple of 4 bytes');882 }883 }884 if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {885 throw new BSONError('Invalid Vector: padding must be zero for packed bit vectors that are empty');886 }887 if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {888 throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);889 }890}891const UUID_BYTE_LENGTH = 16;892const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;893const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;894class UUID extends Binary {895 constructor(input) {896 let bytes;897 if (input == null) {898 bytes = UUID.generate();899 }900 else if (input instanceof UUID) {901 bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));902 }903 else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {904 bytes = ByteUtils.toLocalBufferType(input);905 }906 else if (typeof input === 'string') {907 bytes = UUID.bytesFromString(input);908 }909 else {910 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).');911 }912 super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);913 }914 get id() {915 return this.buffer;916 }917 set id(value) {918 this.buffer = value;919 }920 toHexString(includeDashes = true) {921 if (includeDashes) {922 return [923 ByteUtils.toHex(this.buffer.subarray(0, 4)),924 ByteUtils.toHex(this.buffer.subarray(4, 6)),925 ByteUtils.toHex(this.buffer.subarray(6, 8)),926 ByteUtils.toHex(this.buffer.subarray(8, 10)),927 ByteUtils.toHex(this.buffer.subarray(10, 16))928 ].join('-');929 }930 return ByteUtils.toHex(this.buffer);931 }932 toString(encoding) {933 if (encoding === 'hex')934 return ByteUtils.toHex(this.id);935 if (encoding === 'base64')936 return ByteUtils.toBase64(this.id);937 return this.toHexString();938 }939 toJSON() {940 return this.toHexString();941 }942 equals(otherId) {943 if (!otherId) {944 return false;945 }946 if (otherId instanceof UUID) {947 return ByteUtils.equals(otherId.id, this.id);948 }949 try {950 return ByteUtils.equals(new UUID(otherId).id, this.id);951 }952 catch {953 return false;954 }955 }956 toBinary() {957 return new Binary(this.id, Binary.SUBTYPE_UUID);958 }959 static generate() {960 const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);961 bytes[6] = (bytes[6] & 0x0f) | 0x40;962 bytes[8] = (bytes[8] & 0x3f) | 0x80;963 return bytes;964 }965 static isValid(input) {966 if (!input) {967 return false;968 }969 if (typeof input === 'string') {970 return UUID.isValidUUIDString(input);971 }972 if (isUint8Array(input)) {973 return input.byteLength === UUID_BYTE_LENGTH;974 }975 return (input._bsontype === 'Binary' &&976 input.sub_type === this.SUBTYPE_UUID &&977 input.buffer.byteLength === 16);978 }979 static createFromHexString(hexString) {980 const buffer = UUID.bytesFromString(hexString);981 return new UUID(buffer);982 }983 static createFromBase64(base64) {984 return new UUID(ByteUtils.fromBase64(base64));985 }986 static bytesFromString(representation) {987 if (!UUID.isValidUUIDString(representation)) {988 throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');989 }990 return ByteUtils.fromHex(representation.replace(/-/g, ''));991 }992 static isValidUUIDString(representation) {993 return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);994 }995 inspect(depth, options, inspect) {996 inspect ??= defaultInspect;997 return `new UUID(${inspect(this.toHexString(), options)})`;998 }999}1000 1001class Code extends BSONValue {1002 get _bsontype() {1003 return 'Code';1004 }1005 constructor(code, scope) {1006 super();1007 this.code = code.toString();1008 this.scope = scope ?? null;1009 }1010 toJSON() {1011 if (this.scope != null) {1012 return { code: this.code, scope: this.scope };1013 }1014 return { code: this.code };1015 }1016 toExtendedJSON() {1017 if (this.scope) {1018 return { $code: this.code, $scope: this.scope };1019 }1020 return { $code: this.code };1021 }1022 static fromExtendedJSON(doc) {1023 return new Code(doc.$code, doc.$scope);1024 }1025 inspect(depth, options, inspect) {1026 inspect ??= defaultInspect;1027 let parametersString = inspect(this.code, options);1028 const multiLineFn = parametersString.includes('\n');1029 if (this.scope != null) {1030 parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;1031 }1032 const endingNewline = multiLineFn && this.scope === null;1033 return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;1034 }1035}1036 1037function isDBRefLike(value) {1038 return (value != null &&1039 typeof value === 'object' &&1040 '$id' in value &&1041 value.$id != null &&1042 '$ref' in value &&1043 typeof value.$ref === 'string' &&1044 (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));1045}1046class DBRef extends BSONValue {1047 get _bsontype() {1048 return 'DBRef';1049 }1050 constructor(collection, oid, db, fields) {1051 super();1052 const parts = collection.split('.');1053 if (parts.length === 2) {1054 db = parts.shift();1055 collection = parts.shift();1056 }1057 this.collection = collection;1058 this.oid = oid;1059 this.db = db;1060 this.fields = fields || {};1061 }1062 get namespace() {1063 return this.collection;1064 }1065 set namespace(value) {1066 this.collection = value;1067 }1068 toJSON() {1069 const o = Object.assign({1070 $ref: this.collection,1071 $id: this.oid1072 }, this.fields);1073 if (this.db != null)1074 o.$db = this.db;1075 return o;1076 }1077 toExtendedJSON(options) {1078 options = options || {};1079 let o = {1080 $ref: this.collection,1081 $id: this.oid1082 };1083 if (options.legacy) {1084 return o;1085 }1086 if (this.db)1087 o.$db = this.db;1088 o = Object.assign(o, this.fields);1089 return o;1090 }1091 static fromExtendedJSON(doc) {1092 const copy = Object.assign({}, doc);1093 delete copy.$ref;1094 delete copy.$id;1095 delete copy.$db;1096 return new DBRef(doc.$ref, doc.$id, doc.$db, copy);1097 }1098 inspect(depth, options, inspect) {1099 inspect ??= defaultInspect;1100 const args = [1101 inspect(this.namespace, options),1102 inspect(this.oid, options),1103 ...(this.db ? [inspect(this.db, options)] : []),1104 ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])1105 ];1106 args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];1107 return `new DBRef(${args.join(', ')})`;1108 }1109}1110 1111function removeLeadingZerosAndExplicitPlus(str) {1112 if (str === '') {1113 return str;1114 }1115 let startIndex = 0;1116 const isNegative = str[startIndex] === '-';1117 const isExplicitlyPositive = str[startIndex] === '+';1118 if (isExplicitlyPositive || isNegative) {1119 startIndex += 1;1120 }1121 let foundInsignificantZero = false;1122 for (; startIndex < str.length && str[startIndex] === '0'; ++startIndex) {1123 foundInsignificantZero = true;1124 }1125 if (!foundInsignificantZero) {1126 return isExplicitlyPositive ? str.slice(1) : str;1127 }1128 return `${isNegative ? '-' : ''}${str.length === startIndex ? '0' : str.slice(startIndex)}`;1129}1130function validateStringCharacters(str, radix) {1131 radix = radix ?? 10;1132 const validCharacters = '0123456789abcdefghijklmnopqrstuvwxyz'.slice(0, radix);1133 const regex = new RegExp(`[^-+${validCharacters}]`, 'i');1134 return regex.test(str) ? false : str;1135}1136 1137let wasm = undefined;1138try {1139 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;1140}1141catch {1142}1143const TWO_PWR_16_DBL = 1 << 16;1144const TWO_PWR_24_DBL = 1 << 24;1145const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;1146const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;1147const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;1148const INT_CACHE = {};1149const UINT_CACHE = {};1150const MAX_INT64_STRING_LENGTH = 20;1151const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;1152class Long extends BSONValue {1153 get _bsontype() {1154 return 'Long';1155 }1156 get __isLong__() {1157 return true;1158 }1159 constructor(lowOrValue = 0, highOrUnsigned, unsigned) {1160 super();1161 const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);1162 const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;1163 const res = typeof lowOrValue === 'string'1164 ? Long.fromString(lowOrValue, unsignedBool)1165 : typeof lowOrValue === 'bigint'1166 ? Long.fromBigInt(lowOrValue, unsignedBool)1167 : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };1168 this.low = res.low;1169 this.high = res.high;1170 this.unsigned = res.unsigned;1171 }1172 static fromBits(lowBits, highBits, unsigned) {1173 return new Long(lowBits, highBits, unsigned);1174 }1175 static fromInt(value, unsigned) {1176 let obj, cachedObj, cache;1177 if (unsigned) {1178 value >>>= 0;1179 if ((cache = 0 <= value && value < 256)) {1180 cachedObj = UINT_CACHE[value];1181 if (cachedObj)1182 return cachedObj;1183 }1184 obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);1185 if (cache)1186 UINT_CACHE[value] = obj;1187 return obj;1188 }1189 else {1190 value |= 0;1191 if ((cache = -128 <= value && value < 128)) {1192 cachedObj = INT_CACHE[value];1193 if (cachedObj)1194 return cachedObj;1195 }1196 obj = Long.fromBits(value, value < 0 ? -1 : 0, false);1197 if (cache)1198 INT_CACHE[value] = obj;1199 return obj;1200 }