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