bson.rn.cjs 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680
  1. 'use strict';
  2. const TypedArrayPrototypeGetSymbolToStringTag = (() => {
  3. const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
  4. return (value) => g.call(value);
  5. })();
  6. function isUint8Array(value) {
  7. return TypedArrayPrototypeGetSymbolToStringTag(value) === 'Uint8Array';
  8. }
  9. function isAnyArrayBuffer(value) {
  10. return (typeof value === 'object' &&
  11. value != null &&
  12. Symbol.toStringTag in value &&
  13. (value[Symbol.toStringTag] === 'ArrayBuffer' ||
  14. value[Symbol.toStringTag] === 'SharedArrayBuffer'));
  15. }
  16. function isRegExp(regexp) {
  17. return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === '[object RegExp]';
  18. }
  19. function isMap(value) {
  20. return (typeof value === 'object' &&
  21. value != null &&
  22. Symbol.toStringTag in value &&
  23. value[Symbol.toStringTag] === 'Map');
  24. }
  25. function isDate(date) {
  26. return date instanceof Date || Object.prototype.toString.call(date) === '[object Date]';
  27. }
  28. function defaultInspect(x, _options) {
  29. return JSON.stringify(x, (k, v) => {
  30. if (typeof v === 'bigint') {
  31. return { $numberLong: `${v}` };
  32. }
  33. else if (isMap(v)) {
  34. return Object.fromEntries(v);
  35. }
  36. return v;
  37. });
  38. }
  39. function getStylizeFunction(options) {
  40. const stylizeExists = options != null &&
  41. typeof options === 'object' &&
  42. 'stylize' in options &&
  43. typeof options.stylize === 'function';
  44. if (stylizeExists) {
  45. return options.stylize;
  46. }
  47. }
  48. const BSON_MAJOR_VERSION = 7;
  49. const BSON_VERSION_SYMBOL = Symbol.for('@@mdb.bson.version');
  50. const BSON_INT32_MAX = 0x7fffffff;
  51. const BSON_INT32_MIN = -0x80000000;
  52. const BSON_INT64_MAX = Math.pow(2, 63) - 1;
  53. const BSON_INT64_MIN = -Math.pow(2, 63);
  54. const JS_INT_MAX = Math.pow(2, 53);
  55. const JS_INT_MIN = -Math.pow(2, 53);
  56. const BSON_DATA_NUMBER = 1;
  57. const BSON_DATA_STRING = 2;
  58. const BSON_DATA_OBJECT = 3;
  59. const BSON_DATA_ARRAY = 4;
  60. const BSON_DATA_BINARY = 5;
  61. const BSON_DATA_UNDEFINED = 6;
  62. const BSON_DATA_OID = 7;
  63. const BSON_DATA_BOOLEAN = 8;
  64. const BSON_DATA_DATE = 9;
  65. const BSON_DATA_NULL = 10;
  66. const BSON_DATA_REGEXP = 11;
  67. const BSON_DATA_DBPOINTER = 12;
  68. const BSON_DATA_CODE = 13;
  69. const BSON_DATA_SYMBOL = 14;
  70. const BSON_DATA_CODE_W_SCOPE = 15;
  71. const BSON_DATA_INT = 16;
  72. const BSON_DATA_TIMESTAMP = 17;
  73. const BSON_DATA_LONG = 18;
  74. const BSON_DATA_DECIMAL128 = 19;
  75. const BSON_DATA_MIN_KEY = 0xff;
  76. const BSON_DATA_MAX_KEY = 0x7f;
  77. const BSON_BINARY_SUBTYPE_DEFAULT = 0;
  78. const BSON_BINARY_SUBTYPE_FUNCTION = 1;
  79. const BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
  80. const BSON_BINARY_SUBTYPE_UUID = 3;
  81. const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
  82. const BSON_BINARY_SUBTYPE_MD5 = 5;
  83. const BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
  84. const BSON_BINARY_SUBTYPE_COLUMN = 7;
  85. const BSON_BINARY_SUBTYPE_SENSITIVE = 8;
  86. const BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
  87. const BSONType = Object.freeze({
  88. double: 1,
  89. string: 2,
  90. object: 3,
  91. array: 4,
  92. binData: 5,
  93. undefined: 6,
  94. objectId: 7,
  95. bool: 8,
  96. date: 9,
  97. null: 10,
  98. regex: 11,
  99. dbPointer: 12,
  100. javascript: 13,
  101. symbol: 14,
  102. javascriptWithScope: 15,
  103. int: 16,
  104. timestamp: 17,
  105. long: 18,
  106. decimal: 19,
  107. minKey: -1,
  108. maxKey: 127
  109. });
  110. class BSONError extends Error {
  111. get bsonError() {
  112. return true;
  113. }
  114. get name() {
  115. return 'BSONError';
  116. }
  117. constructor(message, options) {
  118. super(message, options);
  119. }
  120. static isBSONError(value) {
  121. return (value != null &&
  122. typeof value === 'object' &&
  123. 'bsonError' in value &&
  124. value.bsonError === true &&
  125. 'name' in value &&
  126. 'message' in value &&
  127. 'stack' in value);
  128. }
  129. }
  130. class BSONVersionError extends BSONError {
  131. get name() {
  132. return 'BSONVersionError';
  133. }
  134. constructor() {
  135. super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
  136. }
  137. }
  138. class BSONRuntimeError extends BSONError {
  139. get name() {
  140. return 'BSONRuntimeError';
  141. }
  142. constructor(message) {
  143. super(message);
  144. }
  145. }
  146. class BSONOffsetError extends BSONError {
  147. get name() {
  148. return 'BSONOffsetError';
  149. }
  150. offset;
  151. constructor(message, offset, options) {
  152. super(`${message}. offset: ${offset}`, options);
  153. this.offset = offset;
  154. }
  155. }
  156. let TextDecoderFatal;
  157. let TextDecoderNonFatal;
  158. function parseUtf8(buffer, start, end, fatal) {
  159. if (fatal) {
  160. TextDecoderFatal ??= new TextDecoder('utf8', { fatal: true });
  161. try {
  162. return TextDecoderFatal.decode(buffer.subarray(start, end));
  163. }
  164. catch (cause) {
  165. throw new BSONError('Invalid UTF-8 string in BSON document', { cause });
  166. }
  167. }
  168. TextDecoderNonFatal ??= new TextDecoder('utf8', { fatal: false });
  169. return TextDecoderNonFatal.decode(buffer.subarray(start, end));
  170. }
  171. function tryReadBasicLatin(uint8array, start, end) {
  172. if (uint8array.length === 0) {
  173. return '';
  174. }
  175. const stringByteLength = end - start;
  176. if (stringByteLength === 0) {
  177. return '';
  178. }
  179. if (stringByteLength > 20) {
  180. return null;
  181. }
  182. if (stringByteLength === 1 && uint8array[start] < 128) {
  183. return String.fromCharCode(uint8array[start]);
  184. }
  185. if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
  186. return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
  187. }
  188. if (stringByteLength === 3 &&
  189. uint8array[start] < 128 &&
  190. uint8array[start + 1] < 128 &&
  191. uint8array[start + 2] < 128) {
  192. return (String.fromCharCode(uint8array[start]) +
  193. String.fromCharCode(uint8array[start + 1]) +
  194. String.fromCharCode(uint8array[start + 2]));
  195. }
  196. const latinBytes = [];
  197. for (let i = start; i < end; i++) {
  198. const byte = uint8array[i];
  199. if (byte > 127) {
  200. return null;
  201. }
  202. latinBytes.push(byte);
  203. }
  204. return String.fromCharCode(...latinBytes);
  205. }
  206. function tryWriteBasicLatin(destination, source, offset) {
  207. if (source.length === 0)
  208. return 0;
  209. if (source.length > 25)
  210. return null;
  211. if (destination.length - offset < source.length)
  212. return null;
  213. for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
  214. const char = source.charCodeAt(charOffset);
  215. if (char > 127)
  216. return null;
  217. destination[destinationOffset] = char;
  218. }
  219. return source.length;
  220. }
  221. function nodejsMathRandomBytes(byteLength) {
  222. return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
  223. }
  224. function nodejsSecureRandomBytes(byteLength) {
  225. return crypto.getRandomValues(nodeJsByteUtils.allocate(byteLength));
  226. }
  227. const nodejsRandomBytes = (() => {
  228. const { crypto } = globalThis;
  229. if (crypto != null && typeof crypto.getRandomValues === 'function') {
  230. return nodejsSecureRandomBytes;
  231. }
  232. else {
  233. return nodejsMathRandomBytes;
  234. }
  235. })();
  236. const nodeJsByteUtils = {
  237. toLocalBufferType(potentialBuffer) {
  238. if (Buffer.isBuffer(potentialBuffer)) {
  239. return potentialBuffer;
  240. }
  241. if (ArrayBuffer.isView(potentialBuffer)) {
  242. return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
  243. }
  244. const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
  245. if (stringTag === 'ArrayBuffer' ||
  246. stringTag === 'SharedArrayBuffer' ||
  247. stringTag === '[object ArrayBuffer]' ||
  248. stringTag === '[object SharedArrayBuffer]') {
  249. return Buffer.from(potentialBuffer);
  250. }
  251. throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);
  252. },
  253. allocate(size) {
  254. return Buffer.alloc(size);
  255. },
  256. allocateUnsafe(size) {
  257. return Buffer.allocUnsafe(size);
  258. },
  259. equals(a, b) {
  260. return nodeJsByteUtils.toLocalBufferType(a).equals(b);
  261. },
  262. fromNumberArray(array) {
  263. return Buffer.from(array);
  264. },
  265. fromBase64(base64) {
  266. return Buffer.from(base64, 'base64');
  267. },
  268. toBase64(buffer) {
  269. return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');
  270. },
  271. fromISO88591(codePoints) {
  272. return Buffer.from(codePoints, 'binary');
  273. },
  274. toISO88591(buffer) {
  275. return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');
  276. },
  277. fromHex(hex) {
  278. return Buffer.from(hex, 'hex');
  279. },
  280. toHex(buffer) {
  281. return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');
  282. },
  283. toUTF8(buffer, start, end, fatal) {
  284. const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer, start, end) : null;
  285. if (basicLatin != null) {
  286. return basicLatin;
  287. }
  288. const string = nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
  289. if (fatal) {
  290. for (let i = 0; i < string.length; i++) {
  291. if (string.charCodeAt(i) === 0xfffd) {
  292. parseUtf8(buffer, start, end, true);
  293. break;
  294. }
  295. }
  296. }
  297. return string;
  298. },
  299. utf8ByteLength(input) {
  300. return Buffer.byteLength(input, 'utf8');
  301. },
  302. encodeUTF8Into(buffer, source, byteOffset) {
  303. const latinBytesWritten = tryWriteBasicLatin(buffer, source, byteOffset);
  304. if (latinBytesWritten != null) {
  305. return latinBytesWritten;
  306. }
  307. return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
  308. },
  309. randomBytes: nodejsRandomBytes,
  310. swap32(buffer) {
  311. return nodeJsByteUtils.toLocalBufferType(buffer).swap32();
  312. }
  313. };
  314. function isReactNative() {
  315. const { navigator } = globalThis;
  316. return typeof navigator === 'object' && navigator.product === 'ReactNative';
  317. }
  318. function webMathRandomBytes(byteLength) {
  319. if (byteLength < 0) {
  320. throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
  321. }
  322. return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
  323. }
  324. const webRandomBytes = (() => {
  325. const { crypto } = globalThis;
  326. if (crypto != null && typeof crypto.getRandomValues === 'function') {
  327. return (byteLength) => {
  328. return crypto.getRandomValues(webByteUtils.allocate(byteLength));
  329. };
  330. }
  331. else {
  332. if (isReactNative()) {
  333. const { console } = globalThis;
  334. console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');
  335. }
  336. return webMathRandomBytes;
  337. }
  338. })();
  339. const HEX_DIGIT = /(\d|[a-f])/i;
  340. const webByteUtils = {
  341. toLocalBufferType(potentialUint8array) {
  342. const stringTag = potentialUint8array?.[Symbol.toStringTag] ??
  343. Object.prototype.toString.call(potentialUint8array);
  344. if (stringTag === 'Uint8Array') {
  345. return potentialUint8array;
  346. }
  347. if (ArrayBuffer.isView(potentialUint8array)) {
  348. return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
  349. }
  350. if (stringTag === 'ArrayBuffer' ||
  351. stringTag === 'SharedArrayBuffer' ||
  352. stringTag === '[object ArrayBuffer]' ||
  353. stringTag === '[object SharedArrayBuffer]') {
  354. return new Uint8Array(potentialUint8array);
  355. }
  356. throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);
  357. },
  358. allocate(size) {
  359. if (typeof size !== 'number') {
  360. throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
  361. }
  362. return new Uint8Array(size);
  363. },
  364. allocateUnsafe(size) {
  365. return webByteUtils.allocate(size);
  366. },
  367. equals(a, b) {
  368. if (a.byteLength !== b.byteLength) {
  369. return false;
  370. }
  371. for (let i = 0; i < a.byteLength; i++) {
  372. if (a[i] !== b[i]) {
  373. return false;
  374. }
  375. }
  376. return true;
  377. },
  378. fromNumberArray(array) {
  379. return Uint8Array.from(array);
  380. },
  381. fromBase64(base64) {
  382. return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
  383. },
  384. toBase64(uint8array) {
  385. return btoa(webByteUtils.toISO88591(uint8array));
  386. },
  387. fromISO88591(codePoints) {
  388. return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);
  389. },
  390. toISO88591(uint8array) {
  391. return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');
  392. },
  393. fromHex(hex) {
  394. const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
  395. const buffer = [];
  396. for (let i = 0; i < evenLengthHex.length; i += 2) {
  397. const firstDigit = evenLengthHex[i];
  398. const secondDigit = evenLengthHex[i + 1];
  399. if (!HEX_DIGIT.test(firstDigit)) {
  400. break;
  401. }
  402. if (!HEX_DIGIT.test(secondDigit)) {
  403. break;
  404. }
  405. const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
  406. buffer.push(hexDigit);
  407. }
  408. return Uint8Array.from(buffer);
  409. },
  410. toHex(uint8array) {
  411. return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
  412. },
  413. toUTF8(uint8array, start, end, fatal) {
  414. const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
  415. if (basicLatin != null) {
  416. return basicLatin;
  417. }
  418. return parseUtf8(uint8array, start, end, fatal);
  419. },
  420. utf8ByteLength(input) {
  421. return new TextEncoder().encode(input).byteLength;
  422. },
  423. encodeUTF8Into(uint8array, source, byteOffset) {
  424. const bytes = new TextEncoder().encode(source);
  425. uint8array.set(bytes, byteOffset);
  426. return bytes.byteLength;
  427. },
  428. randomBytes: webRandomBytes,
  429. swap32(buffer) {
  430. if (buffer.length % 4 !== 0) {
  431. throw new RangeError('Buffer size must be a multiple of 32-bits');
  432. }
  433. for (let i = 0; i < buffer.length; i += 4) {
  434. const byte0 = buffer[i];
  435. const byte1 = buffer[i + 1];
  436. const byte2 = buffer[i + 2];
  437. const byte3 = buffer[i + 3];
  438. buffer[i] = byte3;
  439. buffer[i + 1] = byte2;
  440. buffer[i + 2] = byte1;
  441. buffer[i + 3] = byte0;
  442. }
  443. return buffer;
  444. }
  445. };
  446. const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
  447. const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
  448. const bsonType = Symbol.for('@@mdb.bson.type');
  449. class BSONValue {
  450. get [bsonType]() {
  451. return this._bsontype;
  452. }
  453. get [BSON_VERSION_SYMBOL]() {
  454. return BSON_MAJOR_VERSION;
  455. }
  456. [Symbol.for('nodejs.util.inspect.custom')](depth, options, inspect) {
  457. return this.inspect(depth, options, inspect);
  458. }
  459. }
  460. const FLOAT = new Float64Array(1);
  461. const FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
  462. FLOAT[0] = -1;
  463. const isBigEndian = FLOAT_BYTES[7] === 0;
  464. const NumberUtils = {
  465. isBigEndian,
  466. getNonnegativeInt32LE(source, offset) {
  467. if (source[offset + 3] > 127) {
  468. throw new RangeError(`Size cannot be negative at offset: ${offset}`);
  469. }
  470. return (source[offset] |
  471. (source[offset + 1] << 8) |
  472. (source[offset + 2] << 16) |
  473. (source[offset + 3] << 24));
  474. },
  475. getInt32LE(source, offset) {
  476. return (source[offset] |
  477. (source[offset + 1] << 8) |
  478. (source[offset + 2] << 16) |
  479. (source[offset + 3] << 24));
  480. },
  481. getUint32LE(source, offset) {
  482. return (source[offset] +
  483. source[offset + 1] * 256 +
  484. source[offset + 2] * 65536 +
  485. source[offset + 3] * 16777216);
  486. },
  487. getUint32BE(source, offset) {
  488. return (source[offset + 3] +
  489. source[offset + 2] * 256 +
  490. source[offset + 1] * 65536 +
  491. source[offset] * 16777216);
  492. },
  493. getBigInt64LE(source, offset) {
  494. const hi = BigInt(source[offset + 4] +
  495. source[offset + 5] * 256 +
  496. source[offset + 6] * 65536 +
  497. (source[offset + 7] << 24));
  498. const lo = BigInt(source[offset] +
  499. source[offset + 1] * 256 +
  500. source[offset + 2] * 65536 +
  501. source[offset + 3] * 16777216);
  502. return (hi << 32n) + lo;
  503. },
  504. getFloat64LE: isBigEndian
  505. ? (source, offset) => {
  506. FLOAT_BYTES[7] = source[offset];
  507. FLOAT_BYTES[6] = source[offset + 1];
  508. FLOAT_BYTES[5] = source[offset + 2];
  509. FLOAT_BYTES[4] = source[offset + 3];
  510. FLOAT_BYTES[3] = source[offset + 4];
  511. FLOAT_BYTES[2] = source[offset + 5];
  512. FLOAT_BYTES[1] = source[offset + 6];
  513. FLOAT_BYTES[0] = source[offset + 7];
  514. return FLOAT[0];
  515. }
  516. : (source, offset) => {
  517. FLOAT_BYTES[0] = source[offset];
  518. FLOAT_BYTES[1] = source[offset + 1];
  519. FLOAT_BYTES[2] = source[offset + 2];
  520. FLOAT_BYTES[3] = source[offset + 3];
  521. FLOAT_BYTES[4] = source[offset + 4];
  522. FLOAT_BYTES[5] = source[offset + 5];
  523. FLOAT_BYTES[6] = source[offset + 6];
  524. FLOAT_BYTES[7] = source[offset + 7];
  525. return FLOAT[0];
  526. },
  527. setInt32BE(destination, offset, value) {
  528. destination[offset + 3] = value;
  529. value >>>= 8;
  530. destination[offset + 2] = value;
  531. value >>>= 8;
  532. destination[offset + 1] = value;
  533. value >>>= 8;
  534. destination[offset] = value;
  535. return 4;
  536. },
  537. setInt32LE(destination, offset, value) {
  538. destination[offset] = value;
  539. value >>>= 8;
  540. destination[offset + 1] = value;
  541. value >>>= 8;
  542. destination[offset + 2] = value;
  543. value >>>= 8;
  544. destination[offset + 3] = value;
  545. return 4;
  546. },
  547. setBigInt64LE(destination, offset, value) {
  548. const mask32bits = 0xffffffffn;
  549. let lo = Number(value & mask32bits);
  550. destination[offset] = lo;
  551. lo >>= 8;
  552. destination[offset + 1] = lo;
  553. lo >>= 8;
  554. destination[offset + 2] = lo;
  555. lo >>= 8;
  556. destination[offset + 3] = lo;
  557. let hi = Number((value >> 32n) & mask32bits);
  558. destination[offset + 4] = hi;
  559. hi >>= 8;
  560. destination[offset + 5] = hi;
  561. hi >>= 8;
  562. destination[offset + 6] = hi;
  563. hi >>= 8;
  564. destination[offset + 7] = hi;
  565. return 8;
  566. },
  567. setFloat64LE: isBigEndian
  568. ? (destination, offset, value) => {
  569. FLOAT[0] = value;
  570. destination[offset] = FLOAT_BYTES[7];
  571. destination[offset + 1] = FLOAT_BYTES[6];
  572. destination[offset + 2] = FLOAT_BYTES[5];
  573. destination[offset + 3] = FLOAT_BYTES[4];
  574. destination[offset + 4] = FLOAT_BYTES[3];
  575. destination[offset + 5] = FLOAT_BYTES[2];
  576. destination[offset + 6] = FLOAT_BYTES[1];
  577. destination[offset + 7] = FLOAT_BYTES[0];
  578. return 8;
  579. }
  580. : (destination, offset, value) => {
  581. FLOAT[0] = value;
  582. destination[offset] = FLOAT_BYTES[0];
  583. destination[offset + 1] = FLOAT_BYTES[1];
  584. destination[offset + 2] = FLOAT_BYTES[2];
  585. destination[offset + 3] = FLOAT_BYTES[3];
  586. destination[offset + 4] = FLOAT_BYTES[4];
  587. destination[offset + 5] = FLOAT_BYTES[5];
  588. destination[offset + 6] = FLOAT_BYTES[6];
  589. destination[offset + 7] = FLOAT_BYTES[7];
  590. return 8;
  591. }
  592. };
  593. class Binary extends BSONValue {
  594. get _bsontype() {
  595. return 'Binary';
  596. }
  597. static BSON_BINARY_SUBTYPE_DEFAULT = 0;
  598. static BUFFER_SIZE = 256;
  599. static SUBTYPE_DEFAULT = 0;
  600. static SUBTYPE_FUNCTION = 1;
  601. static SUBTYPE_BYTE_ARRAY = 2;
  602. static SUBTYPE_UUID_OLD = 3;
  603. static SUBTYPE_UUID = 4;
  604. static SUBTYPE_MD5 = 5;
  605. static SUBTYPE_ENCRYPTED = 6;
  606. static SUBTYPE_COLUMN = 7;
  607. static SUBTYPE_SENSITIVE = 8;
  608. static SUBTYPE_VECTOR = 9;
  609. static SUBTYPE_USER_DEFINED = 128;
  610. static VECTOR_TYPE = Object.freeze({
  611. Int8: 0x03,
  612. Float32: 0x27,
  613. PackedBit: 0x10
  614. });
  615. buffer;
  616. sub_type;
  617. position;
  618. constructor(buffer, subType) {
  619. super();
  620. if (!(buffer == null) &&
  621. typeof buffer === 'string' &&
  622. !ArrayBuffer.isView(buffer) &&
  623. !isAnyArrayBuffer(buffer) &&
  624. !Array.isArray(buffer)) {
  625. throw new BSONError('Binary can only be constructed from Uint8Array or number[]');
  626. }
  627. this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
  628. if (buffer == null) {
  629. this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
  630. this.position = 0;
  631. }
  632. else {
  633. this.buffer = Array.isArray(buffer)
  634. ? ByteUtils.fromNumberArray(buffer)
  635. : ByteUtils.toLocalBufferType(buffer);
  636. this.position = this.buffer.byteLength;
  637. }
  638. }
  639. put(byteValue) {
  640. if (typeof byteValue === 'string' && byteValue.length !== 1) {
  641. throw new BSONError('only accepts single character String');
  642. }
  643. else if (typeof byteValue !== 'number' && byteValue.length !== 1)
  644. throw new BSONError('only accepts single character Uint8Array or Array');
  645. let decodedByte;
  646. if (typeof byteValue === 'string') {
  647. decodedByte = byteValue.charCodeAt(0);
  648. }
  649. else if (typeof byteValue === 'number') {
  650. decodedByte = byteValue;
  651. }
  652. else {
  653. decodedByte = byteValue[0];
  654. }
  655. if (decodedByte < 0 || decodedByte > 255) {
  656. throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
  657. }
  658. if (this.buffer.byteLength > this.position) {
  659. this.buffer[this.position++] = decodedByte;
  660. }
  661. else {
  662. const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
  663. newSpace.set(this.buffer, 0);
  664. this.buffer = newSpace;
  665. this.buffer[this.position++] = decodedByte;
  666. }
  667. }
  668. write(sequence, offset) {
  669. offset = typeof offset === 'number' ? offset : this.position;
  670. if (this.buffer.byteLength < offset + sequence.length) {
  671. const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
  672. newSpace.set(this.buffer, 0);
  673. this.buffer = newSpace;
  674. }
  675. if (ArrayBuffer.isView(sequence)) {
  676. this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
  677. this.position =
  678. offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
  679. }
  680. else if (typeof sequence === 'string') {
  681. throw new BSONError('input cannot be string');
  682. }
  683. }
  684. read(position, length) {
  685. length = length && length > 0 ? length : this.position;
  686. const end = position + length;
  687. return this.buffer.subarray(position, end > this.position ? this.position : end);
  688. }
  689. value() {
  690. return this.buffer.length === this.position
  691. ? this.buffer
  692. : this.buffer.subarray(0, this.position);
  693. }
  694. length() {
  695. return this.position;
  696. }
  697. toJSON() {
  698. return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
  699. }
  700. toString(encoding) {
  701. if (encoding === 'hex')
  702. return ByteUtils.toHex(this.buffer.subarray(0, this.position));
  703. if (encoding === 'base64')
  704. return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
  705. if (encoding === 'utf8' || encoding === 'utf-8')
  706. return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
  707. return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
  708. }
  709. toExtendedJSON(options) {
  710. options = options || {};
  711. if (this.sub_type === Binary.SUBTYPE_VECTOR) {
  712. validateBinaryVector(this);
  713. }
  714. const base64String = ByteUtils.toBase64(this.buffer);
  715. const subType = Number(this.sub_type).toString(16);
  716. if (options.legacy) {
  717. return {
  718. $binary: base64String,
  719. $type: subType.length === 1 ? '0' + subType : subType
  720. };
  721. }
  722. return {
  723. $binary: {
  724. base64: base64String,
  725. subType: subType.length === 1 ? '0' + subType : subType
  726. }
  727. };
  728. }
  729. toUUID() {
  730. if (this.sub_type === Binary.SUBTYPE_UUID) {
  731. return new UUID(this.buffer.subarray(0, this.position));
  732. }
  733. throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
  734. }
  735. static createFromHexString(hex, subType) {
  736. return new Binary(ByteUtils.fromHex(hex), subType);
  737. }
  738. static createFromBase64(base64, subType) {
  739. return new Binary(ByteUtils.fromBase64(base64), subType);
  740. }
  741. static fromExtendedJSON(doc, options) {
  742. options = options || {};
  743. let data;
  744. let type;
  745. if ('$binary' in doc) {
  746. if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
  747. type = doc.$type ? parseInt(doc.$type, 16) : 0;
  748. data = ByteUtils.fromBase64(doc.$binary);
  749. }
  750. else {
  751. if (typeof doc.$binary !== 'string') {
  752. type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  753. data = ByteUtils.fromBase64(doc.$binary.base64);
  754. }
  755. }
  756. }
  757. else if ('$uuid' in doc) {
  758. type = 4;
  759. data = UUID.bytesFromString(doc.$uuid);
  760. }
  761. if (!data) {
  762. throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
  763. }
  764. return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
  765. }
  766. inspect(depth, options, inspect) {
  767. inspect ??= defaultInspect;
  768. const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
  769. const base64Arg = inspect(base64, options);
  770. const subTypeArg = inspect(this.sub_type, options);
  771. return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
  772. }
  773. toInt8Array() {
  774. if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
  775. throw new BSONError('Binary sub_type is not Vector');
  776. }
  777. if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {
  778. throw new BSONError('Binary datatype field is not Int8');
  779. }
  780. validateBinaryVector(this);
  781. return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
  782. }
  783. toFloat32Array() {
  784. if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
  785. throw new BSONError('Binary sub_type is not Vector');
  786. }
  787. if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {
  788. throw new BSONError('Binary datatype field is not Float32');
  789. }
  790. validateBinaryVector(this);
  791. const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
  792. if (NumberUtils.isBigEndian)
  793. ByteUtils.swap32(floatBytes);
  794. return new Float32Array(floatBytes.buffer);
  795. }
  796. toPackedBits() {
  797. if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
  798. throw new BSONError('Binary sub_type is not Vector');
  799. }
  800. if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
  801. throw new BSONError('Binary datatype field is not packed bit');
  802. }
  803. validateBinaryVector(this);
  804. return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
  805. }
  806. toBits() {
  807. if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
  808. throw new BSONError('Binary sub_type is not Vector');
  809. }
  810. if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
  811. throw new BSONError('Binary datatype field is not packed bit');
  812. }
  813. validateBinaryVector(this);
  814. const byteCount = this.length() - 2;
  815. const bitCount = byteCount * 8 - this.buffer[1];
  816. const bits = new Int8Array(bitCount);
  817. for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
  818. const byteOffset = (bitOffset / 8) | 0;
  819. const byte = this.buffer[byteOffset + 2];
  820. const shift = 7 - (bitOffset % 8);
  821. const bit = (byte >> shift) & 1;
  822. bits[bitOffset] = bit;
  823. }
  824. return bits;
  825. }
  826. static fromInt8Array(array) {
  827. const buffer = ByteUtils.allocate(array.byteLength + 2);
  828. buffer[0] = Binary.VECTOR_TYPE.Int8;
  829. buffer[1] = 0;
  830. const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
  831. buffer.set(intBytes, 2);
  832. const bin = new this(buffer, this.SUBTYPE_VECTOR);
  833. validateBinaryVector(bin);
  834. return bin;
  835. }
  836. static fromFloat32Array(array) {
  837. const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
  838. binaryBytes[0] = Binary.VECTOR_TYPE.Float32;
  839. binaryBytes[1] = 0;
  840. const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
  841. binaryBytes.set(floatBytes, 2);
  842. if (NumberUtils.isBigEndian)
  843. ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
  844. const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
  845. validateBinaryVector(bin);
  846. return bin;
  847. }
  848. static fromPackedBits(array, padding = 0) {
  849. const buffer = ByteUtils.allocate(array.byteLength + 2);
  850. buffer[0] = Binary.VECTOR_TYPE.PackedBit;
  851. buffer[1] = padding;
  852. buffer.set(array, 2);
  853. const bin = new this(buffer, this.SUBTYPE_VECTOR);
  854. validateBinaryVector(bin);
  855. return bin;
  856. }
  857. static fromBits(bits) {
  858. const byteLength = (bits.length + 7) >>> 3;
  859. const bytes = new Uint8Array(byteLength + 2);
  860. bytes[0] = Binary.VECTOR_TYPE.PackedBit;
  861. const remainder = bits.length % 8;
  862. bytes[1] = remainder === 0 ? 0 : 8 - remainder;
  863. for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
  864. const byteOffset = bitOffset >>> 3;
  865. const bit = bits[bitOffset];
  866. if (bit !== 0 && bit !== 1) {
  867. throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
  868. }
  869. if (bit === 0)
  870. continue;
  871. const shift = 7 - (bitOffset % 8);
  872. bytes[byteOffset + 2] |= bit << shift;
  873. }
  874. return new this(bytes, Binary.SUBTYPE_VECTOR);
  875. }
  876. }
  877. function validateBinaryVector(vector) {
  878. if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
  879. return;
  880. const size = vector.position;
  881. const datatype = vector.buffer[0];
  882. const padding = vector.buffer[1];
  883. if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) &&
  884. padding !== 0) {
  885. throw new BSONError('Invalid Vector: padding must be zero for int8 and float32 vectors');
  886. }
  887. if (datatype === Binary.VECTOR_TYPE.Float32) {
  888. if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
  889. throw new BSONError('Invalid Vector: Float32 vector must contain a multiple of 4 bytes');
  890. }
  891. }
  892. if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
  893. throw new BSONError('Invalid Vector: padding must be zero for packed bit vectors that are empty');
  894. }
  895. if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
  896. throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
  897. }
  898. }
  899. const UUID_BYTE_LENGTH = 16;
  900. const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
  901. 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;
  902. class UUID extends Binary {
  903. constructor(input) {
  904. let bytes;
  905. if (input == null) {
  906. bytes = UUID.generate();
  907. }
  908. else if (input instanceof UUID) {
  909. bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
  910. }
  911. else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
  912. bytes = ByteUtils.toLocalBufferType(input);
  913. }
  914. else if (typeof input === 'string') {
  915. bytes = UUID.bytesFromString(input);
  916. }
  917. else {
  918. 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).');
  919. }
  920. super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
  921. }
  922. get id() {
  923. return this.buffer;
  924. }
  925. set id(value) {
  926. this.buffer = value;
  927. }
  928. toHexString(includeDashes = true) {
  929. if (includeDashes) {
  930. return [
  931. ByteUtils.toHex(this.buffer.subarray(0, 4)),
  932. ByteUtils.toHex(this.buffer.subarray(4, 6)),
  933. ByteUtils.toHex(this.buffer.subarray(6, 8)),
  934. ByteUtils.toHex(this.buffer.subarray(8, 10)),
  935. ByteUtils.toHex(this.buffer.subarray(10, 16))
  936. ].join('-');
  937. }
  938. return ByteUtils.toHex(this.buffer);
  939. }
  940. toString(encoding) {
  941. if (encoding === 'hex')
  942. return ByteUtils.toHex(this.id);
  943. if (encoding === 'base64')
  944. return ByteUtils.toBase64(this.id);
  945. return this.toHexString();
  946. }
  947. toJSON() {
  948. return this.toHexString();
  949. }
  950. equals(otherId) {
  951. if (!otherId) {
  952. return false;
  953. }
  954. if (otherId instanceof UUID) {
  955. return ByteUtils.equals(otherId.id, this.id);
  956. }
  957. try {
  958. return ByteUtils.equals(new UUID(otherId).id, this.id);
  959. }
  960. catch {
  961. return false;
  962. }
  963. }
  964. toBinary() {
  965. return new Binary(this.id, Binary.SUBTYPE_UUID);
  966. }
  967. static generate() {
  968. const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
  969. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  970. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  971. return bytes;
  972. }
  973. static isValid(input) {
  974. if (!input) {
  975. return false;
  976. }
  977. if (typeof input === 'string') {
  978. return UUID.isValidUUIDString(input);
  979. }
  980. if (isUint8Array(input)) {
  981. return input.byteLength === UUID_BYTE_LENGTH;
  982. }
  983. return (input._bsontype === 'Binary' &&
  984. input.sub_type === this.SUBTYPE_UUID &&
  985. input.buffer.byteLength === 16);
  986. }
  987. static createFromHexString(hexString) {
  988. const buffer = UUID.bytesFromString(hexString);
  989. return new UUID(buffer);
  990. }
  991. static createFromBase64(base64) {
  992. return new UUID(ByteUtils.fromBase64(base64));
  993. }
  994. static bytesFromString(representation) {
  995. if (!UUID.isValidUUIDString(representation)) {
  996. throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
  997. }
  998. return ByteUtils.fromHex(representation.replace(/-/g, ''));
  999. }
  1000. static isValidUUIDString(representation) {
  1001. return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
  1002. }
  1003. inspect(depth, options, inspect) {
  1004. inspect ??= defaultInspect;
  1005. return `new UUID(${inspect(this.toHexString(), options)})`;
  1006. }
  1007. }
  1008. class Code extends BSONValue {
  1009. get _bsontype() {
  1010. return 'Code';
  1011. }
  1012. code;
  1013. scope;
  1014. constructor(code, scope) {
  1015. super();
  1016. this.code = code.toString();
  1017. this.scope = scope ?? null;
  1018. }
  1019. toJSON() {
  1020. if (this.scope != null) {
  1021. return { code: this.code, scope: this.scope };
  1022. }
  1023. return { code: this.code };
  1024. }
  1025. toExtendedJSON() {
  1026. if (this.scope) {
  1027. return { $code: this.code, $scope: this.scope };
  1028. }
  1029. return { $code: this.code };
  1030. }
  1031. static fromExtendedJSON(doc) {
  1032. return new Code(doc.$code, doc.$scope);
  1033. }
  1034. inspect(depth, options, inspect) {
  1035. inspect ??= defaultInspect;
  1036. let parametersString = inspect(this.code, options);
  1037. const multiLineFn = parametersString.includes('\n');
  1038. if (this.scope != null) {
  1039. parametersString += `,${multiLineFn ? '\n' : ' '}${inspect(this.scope, options)}`;
  1040. }
  1041. const endingNewline = multiLineFn && this.scope === null;
  1042. return `new Code(${multiLineFn ? '\n' : ''}${parametersString}${endingNewline ? '\n' : ''})`;
  1043. }
  1044. }
  1045. function isDBRefLike(value) {
  1046. return (value != null &&
  1047. typeof value === 'object' &&
  1048. '$id' in value &&
  1049. value.$id != null &&
  1050. '$ref' in value &&
  1051. typeof value.$ref === 'string' &&
  1052. (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));
  1053. }
  1054. class DBRef extends BSONValue {
  1055. get _bsontype() {
  1056. return 'DBRef';
  1057. }
  1058. collection;
  1059. oid;
  1060. db;
  1061. fields;
  1062. constructor(collection, oid, db, fields) {
  1063. super();
  1064. const parts = collection.split('.');
  1065. if (parts.length === 2) {
  1066. db = parts.shift();
  1067. collection = parts.shift();
  1068. }
  1069. this.collection = collection;
  1070. this.oid = oid;
  1071. this.db = db;
  1072. this.fields = fields || {};
  1073. }
  1074. get namespace() {
  1075. return this.collection;
  1076. }
  1077. set namespace(value) {
  1078. this.collection = value;
  1079. }
  1080. toJSON() {
  1081. const o = Object.assign({
  1082. $ref: this.collection,
  1083. $id: this.oid
  1084. }, this.fields);
  1085. if (this.db != null)
  1086. o.$db = this.db;
  1087. return o;
  1088. }
  1089. toExtendedJSON(options) {
  1090. options = options || {};
  1091. let o = {
  1092. $ref: this.collection,
  1093. $id: this.oid
  1094. };
  1095. if (options.legacy) {
  1096. return o;
  1097. }
  1098. if (this.db)
  1099. o.$db = this.db;
  1100. o = Object.assign(o, this.fields);
  1101. return o;
  1102. }
  1103. static fromExtendedJSON(doc) {
  1104. const copy = Object.assign({}, doc);
  1105. delete copy.$ref;
  1106. delete copy.$id;
  1107. delete copy.$db;
  1108. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  1109. }
  1110. inspect(depth, options, inspect) {
  1111. inspect ??= defaultInspect;
  1112. const args = [
  1113. inspect(this.namespace, options),
  1114. inspect(this.oid, options),
  1115. ...(this.db ? [inspect(this.db, options)] : []),
  1116. ...(Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [])
  1117. ];
  1118. args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
  1119. return `new DBRef(${args.join(', ')})`;
  1120. }
  1121. }
  1122. function removeLeadingZerosAndExplicitPlus(str) {
  1123. if (str === '') {
  1124. return str;
  1125. }
  1126. let startIndex = 0;
  1127. const isNegative = str[startIndex] === '-';
  1128. const isExplicitlyPositive = str[startIndex] === '+';
  1129. if (isExplicitlyPositive || isNegative) {
  1130. startIndex += 1;
  1131. }
  1132. let foundInsignificantZero = false;
  1133. for (; startIndex < str.length && str[startIndex] === '0'; ++startIndex) {
  1134. foundInsignificantZero = true;
  1135. }
  1136. if (!foundInsignificantZero) {
  1137. return isExplicitlyPositive ? str.slice(1) : str;
  1138. }
  1139. return `${isNegative ? '-' : ''}${str.length === startIndex ? '0' : str.slice(startIndex)}`;
  1140. }
  1141. function validateStringCharacters(str, radix) {
  1142. radix = radix ?? 10;
  1143. const validCharacters = '0123456789abcdefghijklmnopqrstuvwxyz'.slice(0, radix);
  1144. const regex = new RegExp(`[^-+${validCharacters}]`, 'i');
  1145. return regex.test(str) ? false : str;
  1146. }
  1147. let wasm = undefined;
  1148. try {
  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. }
  1151. catch {
  1152. }
  1153. const TWO_PWR_16_DBL = 1 << 16;
  1154. const TWO_PWR_24_DBL = 1 << 24;
  1155. const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  1156. const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  1157. const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  1158. const INT_CACHE = {};
  1159. const UINT_CACHE = {};
  1160. const MAX_INT64_STRING_LENGTH = 20;
  1161. const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
  1162. class Long extends BSONValue {
  1163. get _bsontype() {
  1164. return 'Long';
  1165. }
  1166. get __isLong__() {
  1167. return true;
  1168. }
  1169. high;
  1170. low;
  1171. unsigned;
  1172. constructor(lowOrValue = 0, highOrUnsigned, unsigned) {
  1173. super();
  1174. const unsignedBool = typeof highOrUnsigned === 'boolean' ? highOrUnsigned : Boolean(unsigned);
  1175. const high = typeof highOrUnsigned === 'number' ? highOrUnsigned : 0;
  1176. const res = typeof lowOrValue === 'string'
  1177. ? Long.fromString(lowOrValue, unsignedBool)
  1178. : typeof lowOrValue === 'bigint'
  1179. ? Long.fromBigInt(lowOrValue, unsignedBool)
  1180. : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
  1181. this.low = res.low;
  1182. this.high = res.high;
  1183. this.unsigned = res.unsigned;
  1184. }
  1185. static TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
  1186. static MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
  1187. static ZERO = Long.fromInt(0);
  1188. static UZERO = Long.fromInt(0, true);
  1189. static ONE = Long.fromInt(1);
  1190. static UONE = Long.fromInt(1, true);
  1191. static NEG_ONE = Long.fromInt(-1);
  1192. static MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
  1193. static MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
  1194. static fromBits(lowBits, highBits, unsigned) {
  1195. return new Long(lowBits, highBits, unsigned);
  1196. }
  1197. static fromInt(value, unsigned) {
  1198. let obj, cachedObj, cache;
  1199. if (unsigned) {
  1200. value >>>= 0;
  1201. if ((cache = 0 <= value && value < 256)) {
  1202. cachedObj = UINT_CACHE[value];
  1203. if (cachedObj)
  1204. return cachedObj;
  1205. }
  1206. obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  1207. if (cache)
  1208. UINT_CACHE[value] = obj;
  1209. return obj;
  1210. }
  1211. else {
  1212. value |= 0;
  1213. if ((cache = -128 <= value && value < 128)) {
  1214. cachedObj = INT_CACHE[value];
  1215. if (cachedObj)
  1216. return cachedObj;
  1217. }
  1218. obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
  1219. if (cache)
  1220. INT_CACHE[value] = obj;
  1221. return obj;
  1222. }
  1223. }
  1224. static fromNumber(value, unsigned) {
  1225. if (isNaN(value))
  1226. return unsigned ? Long.UZERO : Long.ZERO;
  1227. if (unsigned) {
  1228. if (value < 0)
  1229. return Long.UZERO;
  1230. if (value >= TWO_PWR_64_DBL)
  1231. return Long.MAX_UNSIGNED_VALUE;
  1232. }
  1233. else {
  1234. if (value <= -TWO_PWR_63_DBL)
  1235. return Long.MIN_VALUE;
  1236. if (value + 1 >= TWO_PWR_63_DBL)
  1237. return Long.MAX_VALUE;
  1238. }
  1239. if (value < 0)
  1240. return Long.fromNumber(-value, unsigned).neg();
  1241. return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  1242. }
  1243. static fromBigInt(value, unsigned) {
  1244. const FROM_BIGINT_BIT_MASK = 0xffffffffn;
  1245. const FROM_BIGINT_BIT_SHIFT = 32n;
  1246. return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number((value >> FROM_BIGINT_BIT_SHIFT) & FROM_BIGINT_BIT_MASK), unsigned);
  1247. }
  1248. static _fromString(str, unsigned, radix) {
  1249. if (str.length === 0)
  1250. throw new BSONError('empty string');
  1251. if (radix < 2 || 36 < radix)
  1252. throw new BSONError('radix');
  1253. let p;
  1254. if ((p = str.indexOf('-')) > 0)
  1255. throw new BSONError('interior hyphen');
  1256. else if (p === 0) {
  1257. return Long._fromString(str.substring(1), unsigned, radix).neg();
  1258. }
  1259. const radixToPower = Long.fromNumber(Math.pow(radix, 8));
  1260. let result = Long.ZERO;
  1261. for (let i = 0; i < str.length; i += 8) {
  1262. const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
  1263. if (size < 8) {
  1264. const power = Long.fromNumber(Math.pow(radix, size));
  1265. result = result.mul(power).add(Long.fromNumber(value));
  1266. }
  1267. else {
  1268. result = result.mul(radixToPower);
  1269. result = result.add(Long.fromNumber(value));
  1270. }
  1271. }
  1272. result.unsigned = unsigned;
  1273. return result;
  1274. }
  1275. static fromStringStrict(str, unsignedOrRadix, radix) {
  1276. let unsigned = false;
  1277. if (typeof unsignedOrRadix === 'number') {
  1278. ((radix = unsignedOrRadix), (unsignedOrRadix = false));
  1279. }
  1280. else {
  1281. unsigned = !!unsignedOrRadix;
  1282. }
  1283. radix ??= 10;
  1284. if (str.trim() !== str) {
  1285. throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
  1286. }
  1287. if (!validateStringCharacters(str, radix)) {
  1288. throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
  1289. }
  1290. const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
  1291. const result = Long._fromString(cleanedStr, unsigned, radix);
  1292. if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
  1293. throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? 'an unsigned' : 'a signed'} 64-bit Long ${radix != null ? `with radix: ${radix}` : ''}`);
  1294. }
  1295. return result;
  1296. }
  1297. static fromString(str, unsignedOrRadix, radix) {
  1298. let unsigned = false;
  1299. if (typeof unsignedOrRadix === 'number') {
  1300. ((radix = unsignedOrRadix), (unsignedOrRadix = false));
  1301. }
  1302. else {
  1303. unsigned = !!unsignedOrRadix;
  1304. }
  1305. radix ??= 10;
  1306. if (str === 'NaN' && radix < 24) {
  1307. return Long.ZERO;
  1308. }
  1309. else if ((str === 'Infinity' || str === '+Infinity' || str === '-Infinity') && radix < 35) {
  1310. return Long.ZERO;
  1311. }
  1312. return Long._fromString(str, unsigned, radix);
  1313. }
  1314. static fromBytes(bytes, unsigned, le) {
  1315. return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
  1316. }
  1317. static fromBytesLE(bytes, unsigned) {
  1318. 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);
  1319. }
  1320. static fromBytesBE(bytes, unsigned) {
  1321. 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);
  1322. }
  1323. static isLong(value) {
  1324. return (value != null &&
  1325. typeof value === 'object' &&
  1326. '__isLong__' in value &&
  1327. value.__isLong__ === true);
  1328. }
  1329. static fromValue(val, unsigned) {
  1330. if (typeof val === 'number')
  1331. return Long.fromNumber(val, unsigned);
  1332. if (typeof val === 'string')
  1333. return Long.fromString(val, unsigned);
  1334. return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
  1335. }
  1336. add(addend) {
  1337. if (!Long.isLong(addend))
  1338. addend = Long.fromValue(addend);
  1339. const a48 = this.high >>> 16;
  1340. const a32 = this.high & 0xffff;
  1341. const a16 = this.low >>> 16;
  1342. const a00 = this.low & 0xffff;
  1343. const b48 = addend.high >>> 16;
  1344. const b32 = addend.high & 0xffff;
  1345. const b16 = addend.low >>> 16;
  1346. const b00 = addend.low & 0xffff;
  1347. let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1348. c00 += a00 + b00;
  1349. c16 += c00 >>> 16;
  1350. c00 &= 0xffff;
  1351. c16 += a16 + b16;
  1352. c32 += c16 >>> 16;
  1353. c16 &= 0xffff;
  1354. c32 += a32 + b32;
  1355. c48 += c32 >>> 16;
  1356. c32 &= 0xffff;
  1357. c48 += a48 + b48;
  1358. c48 &= 0xffff;
  1359. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  1360. }
  1361. and(other) {
  1362. if (!Long.isLong(other))
  1363. other = Long.fromValue(other);
  1364. return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  1365. }
  1366. compare(other) {
  1367. if (!Long.isLong(other))
  1368. other = Long.fromValue(other);
  1369. if (this.eq(other))
  1370. return 0;
  1371. const thisNeg = this.isNegative(), otherNeg = other.isNegative();
  1372. if (thisNeg && !otherNeg)
  1373. return -1;
  1374. if (!thisNeg && otherNeg)
  1375. return 1;
  1376. if (!this.unsigned)
  1377. return this.sub(other).isNegative() ? -1 : 1;
  1378. return other.high >>> 0 > this.high >>> 0 ||
  1379. (other.high === this.high && other.low >>> 0 > this.low >>> 0)
  1380. ? -1
  1381. : 1;
  1382. }
  1383. comp(other) {
  1384. return this.compare(other);
  1385. }
  1386. divide(divisor) {
  1387. if (!Long.isLong(divisor))
  1388. divisor = Long.fromValue(divisor);
  1389. if (divisor.isZero())
  1390. throw new BSONError('division by zero');
  1391. if (wasm) {
  1392. if (!this.unsigned &&
  1393. this.high === -0x80000000 &&
  1394. divisor.low === -1 &&
  1395. divisor.high === -1) {
  1396. return this;
  1397. }
  1398. const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
  1399. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1400. }
  1401. if (this.isZero())
  1402. return this.unsigned ? Long.UZERO : Long.ZERO;
  1403. let approx, rem, res;
  1404. if (!this.unsigned) {
  1405. if (this.eq(Long.MIN_VALUE)) {
  1406. if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
  1407. return Long.MIN_VALUE;
  1408. else if (divisor.eq(Long.MIN_VALUE))
  1409. return Long.ONE;
  1410. else {
  1411. const halfThis = this.shr(1);
  1412. approx = halfThis.div(divisor).shl(1);
  1413. if (approx.eq(Long.ZERO)) {
  1414. return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
  1415. }
  1416. else {
  1417. rem = this.sub(divisor.mul(approx));
  1418. res = approx.add(rem.div(divisor));
  1419. return res;
  1420. }
  1421. }
  1422. }
  1423. else if (divisor.eq(Long.MIN_VALUE))
  1424. return this.unsigned ? Long.UZERO : Long.ZERO;
  1425. if (this.isNegative()) {
  1426. if (divisor.isNegative())
  1427. return this.neg().div(divisor.neg());
  1428. return this.neg().div(divisor).neg();
  1429. }
  1430. else if (divisor.isNegative())
  1431. return this.div(divisor.neg()).neg();
  1432. res = Long.ZERO;
  1433. }
  1434. else {
  1435. if (!divisor.unsigned)
  1436. divisor = divisor.toUnsigned();
  1437. if (divisor.gt(this))
  1438. return Long.UZERO;
  1439. if (divisor.gt(this.shru(1)))
  1440. return Long.UONE;
  1441. res = Long.UZERO;
  1442. }
  1443. rem = this;
  1444. while (rem.gte(divisor)) {
  1445. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  1446. const log2 = Math.ceil(Math.log(approx) / Math.LN2);
  1447. const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
  1448. let approxRes = Long.fromNumber(approx);
  1449. let approxRem = approxRes.mul(divisor);
  1450. while (approxRem.isNegative() || approxRem.gt(rem)) {
  1451. approx -= delta;
  1452. approxRes = Long.fromNumber(approx, this.unsigned);
  1453. approxRem = approxRes.mul(divisor);
  1454. }
  1455. if (approxRes.isZero())
  1456. approxRes = Long.ONE;
  1457. res = res.add(approxRes);
  1458. rem = rem.sub(approxRem);
  1459. }
  1460. return res;
  1461. }
  1462. div(divisor) {
  1463. return this.divide(divisor);
  1464. }
  1465. equals(other) {
  1466. if (!Long.isLong(other))
  1467. other = Long.fromValue(other);
  1468. if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
  1469. return false;
  1470. return this.high === other.high && this.low === other.low;
  1471. }
  1472. eq(other) {
  1473. return this.equals(other);
  1474. }
  1475. getHighBits() {
  1476. return this.high;
  1477. }
  1478. getHighBitsUnsigned() {
  1479. return this.high >>> 0;
  1480. }
  1481. getLowBits() {
  1482. return this.low;
  1483. }
  1484. getLowBitsUnsigned() {
  1485. return this.low >>> 0;
  1486. }
  1487. getNumBitsAbs() {
  1488. if (this.isNegative()) {
  1489. return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  1490. }
  1491. const val = this.high !== 0 ? this.high : this.low;
  1492. let bit;
  1493. for (bit = 31; bit > 0; bit--)
  1494. if ((val & (1 << bit)) !== 0)
  1495. break;
  1496. return this.high !== 0 ? bit + 33 : bit + 1;
  1497. }
  1498. greaterThan(other) {
  1499. return this.comp(other) > 0;
  1500. }
  1501. gt(other) {
  1502. return this.greaterThan(other);
  1503. }
  1504. greaterThanOrEqual(other) {
  1505. return this.comp(other) >= 0;
  1506. }
  1507. gte(other) {
  1508. return this.greaterThanOrEqual(other);
  1509. }
  1510. ge(other) {
  1511. return this.greaterThanOrEqual(other);
  1512. }
  1513. isEven() {
  1514. return (this.low & 1) === 0;
  1515. }
  1516. isNegative() {
  1517. return !this.unsigned && this.high < 0;
  1518. }
  1519. isOdd() {
  1520. return (this.low & 1) === 1;
  1521. }
  1522. isPositive() {
  1523. return this.unsigned || this.high >= 0;
  1524. }
  1525. isZero() {
  1526. return this.high === 0 && this.low === 0;
  1527. }
  1528. lessThan(other) {
  1529. return this.comp(other) < 0;
  1530. }
  1531. lt(other) {
  1532. return this.lessThan(other);
  1533. }
  1534. lessThanOrEqual(other) {
  1535. return this.comp(other) <= 0;
  1536. }
  1537. lte(other) {
  1538. return this.lessThanOrEqual(other);
  1539. }
  1540. modulo(divisor) {
  1541. if (!Long.isLong(divisor))
  1542. divisor = Long.fromValue(divisor);
  1543. if (wasm) {
  1544. const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
  1545. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1546. }
  1547. return this.sub(this.div(divisor).mul(divisor));
  1548. }
  1549. mod(divisor) {
  1550. return this.modulo(divisor);
  1551. }
  1552. rem(divisor) {
  1553. return this.modulo(divisor);
  1554. }
  1555. multiply(multiplier) {
  1556. if (this.isZero())
  1557. return Long.ZERO;
  1558. if (!Long.isLong(multiplier))
  1559. multiplier = Long.fromValue(multiplier);
  1560. if (wasm) {
  1561. const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
  1562. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1563. }
  1564. if (multiplier.isZero())
  1565. return Long.ZERO;
  1566. if (this.eq(Long.MIN_VALUE))
  1567. return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  1568. if (multiplier.eq(Long.MIN_VALUE))
  1569. return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  1570. if (this.isNegative()) {
  1571. if (multiplier.isNegative())
  1572. return this.neg().mul(multiplier.neg());
  1573. else
  1574. return this.neg().mul(multiplier).neg();
  1575. }
  1576. else if (multiplier.isNegative())
  1577. return this.mul(multiplier.neg()).neg();
  1578. if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
  1579. return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  1580. const a48 = this.high >>> 16;
  1581. const a32 = this.high & 0xffff;
  1582. const a16 = this.low >>> 16;
  1583. const a00 = this.low & 0xffff;
  1584. const b48 = multiplier.high >>> 16;
  1585. const b32 = multiplier.high & 0xffff;
  1586. const b16 = multiplier.low >>> 16;
  1587. const b00 = multiplier.low & 0xffff;
  1588. let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1589. c00 += a00 * b00;
  1590. c16 += c00 >>> 16;
  1591. c00 &= 0xffff;
  1592. c16 += a16 * b00;
  1593. c32 += c16 >>> 16;
  1594. c16 &= 0xffff;
  1595. c16 += a00 * b16;
  1596. c32 += c16 >>> 16;
  1597. c16 &= 0xffff;
  1598. c32 += a32 * b00;
  1599. c48 += c32 >>> 16;
  1600. c32 &= 0xffff;
  1601. c32 += a16 * b16;
  1602. c48 += c32 >>> 16;
  1603. c32 &= 0xffff;
  1604. c32 += a00 * b32;
  1605. c48 += c32 >>> 16;
  1606. c32 &= 0xffff;
  1607. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  1608. c48 &= 0xffff;
  1609. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  1610. }
  1611. mul(multiplier) {
  1612. return this.multiply(multiplier);
  1613. }
  1614. negate() {
  1615. if (!this.unsigned && this.eq(Long.MIN_VALUE))
  1616. return Long.MIN_VALUE;
  1617. return this.not().add(Long.ONE);
  1618. }
  1619. neg() {
  1620. return this.negate();
  1621. }
  1622. not() {
  1623. return Long.fromBits(~this.low, ~this.high, this.unsigned);
  1624. }
  1625. notEquals(other) {
  1626. return !this.equals(other);
  1627. }
  1628. neq(other) {
  1629. return this.notEquals(other);
  1630. }
  1631. ne(other) {
  1632. return this.notEquals(other);
  1633. }
  1634. or(other) {
  1635. if (!Long.isLong(other))
  1636. other = Long.fromValue(other);
  1637. return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  1638. }
  1639. shiftLeft(numBits) {
  1640. if (Long.isLong(numBits))
  1641. numBits = numBits.toInt();
  1642. if ((numBits &= 63) === 0)
  1643. return this;
  1644. else if (numBits < 32)
  1645. return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
  1646. else
  1647. return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
  1648. }
  1649. shl(numBits) {
  1650. return this.shiftLeft(numBits);
  1651. }
  1652. shiftRight(numBits) {
  1653. if (Long.isLong(numBits))
  1654. numBits = numBits.toInt();
  1655. if ((numBits &= 63) === 0)
  1656. return this;
  1657. else if (numBits < 32)
  1658. return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
  1659. else
  1660. return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  1661. }
  1662. shr(numBits) {
  1663. return this.shiftRight(numBits);
  1664. }
  1665. shiftRightUnsigned(numBits) {
  1666. if (Long.isLong(numBits))
  1667. numBits = numBits.toInt();
  1668. numBits &= 63;
  1669. if (numBits === 0)
  1670. return this;
  1671. else {
  1672. const high = this.high;
  1673. if (numBits < 32) {
  1674. const low = this.low;
  1675. return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
  1676. }
  1677. else if (numBits === 32)
  1678. return Long.fromBits(high, 0, this.unsigned);
  1679. else
  1680. return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
  1681. }
  1682. }
  1683. shr_u(numBits) {
  1684. return this.shiftRightUnsigned(numBits);
  1685. }
  1686. shru(numBits) {
  1687. return this.shiftRightUnsigned(numBits);
  1688. }
  1689. subtract(subtrahend) {
  1690. if (!Long.isLong(subtrahend))
  1691. subtrahend = Long.fromValue(subtrahend);
  1692. return this.add(subtrahend.neg());
  1693. }
  1694. sub(subtrahend) {
  1695. return this.subtract(subtrahend);
  1696. }
  1697. toInt() {
  1698. return this.unsigned ? this.low >>> 0 : this.low;
  1699. }
  1700. toNumber() {
  1701. if (this.unsigned)
  1702. return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
  1703. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  1704. }
  1705. toBigInt() {
  1706. return BigInt(this.toString());
  1707. }
  1708. toBytes(le) {
  1709. return le ? this.toBytesLE() : this.toBytesBE();
  1710. }
  1711. toBytesLE() {
  1712. const hi = this.high, lo = this.low;
  1713. return [
  1714. lo & 0xff,
  1715. (lo >>> 8) & 0xff,
  1716. (lo >>> 16) & 0xff,
  1717. lo >>> 24,
  1718. hi & 0xff,
  1719. (hi >>> 8) & 0xff,
  1720. (hi >>> 16) & 0xff,
  1721. hi >>> 24
  1722. ];
  1723. }
  1724. toBytesBE() {
  1725. const hi = this.high, lo = this.low;
  1726. return [
  1727. hi >>> 24,
  1728. (hi >>> 16) & 0xff,
  1729. (hi >>> 8) & 0xff,
  1730. hi & 0xff,
  1731. lo >>> 24,
  1732. (lo >>> 16) & 0xff,
  1733. (lo >>> 8) & 0xff,
  1734. lo & 0xff
  1735. ];
  1736. }
  1737. toSigned() {
  1738. if (!this.unsigned)
  1739. return this;
  1740. return Long.fromBits(this.low, this.high, false);
  1741. }
  1742. toString(radix) {
  1743. radix = radix || 10;
  1744. if (radix < 2 || 36 < radix)
  1745. throw new BSONError('radix');
  1746. if (this.isZero())
  1747. return '0';
  1748. if (this.isNegative()) {
  1749. if (this.eq(Long.MIN_VALUE)) {
  1750. const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
  1751. return div.toString(radix) + rem1.toInt().toString(radix);
  1752. }
  1753. else
  1754. return '-' + this.neg().toString(radix);
  1755. }
  1756. const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
  1757. let rem = this;
  1758. let result = '';
  1759. while (true) {
  1760. const remDiv = rem.div(radixToPower);
  1761. const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
  1762. let digits = intval.toString(radix);
  1763. rem = remDiv;
  1764. if (rem.isZero()) {
  1765. return digits + result;
  1766. }
  1767. else {
  1768. while (digits.length < 6)
  1769. digits = '0' + digits;
  1770. result = '' + digits + result;
  1771. }
  1772. }
  1773. }
  1774. toUnsigned() {
  1775. if (this.unsigned)
  1776. return this;
  1777. return Long.fromBits(this.low, this.high, true);
  1778. }
  1779. xor(other) {
  1780. if (!Long.isLong(other))
  1781. other = Long.fromValue(other);
  1782. return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  1783. }
  1784. eqz() {
  1785. return this.isZero();
  1786. }
  1787. le(other) {
  1788. return this.lessThanOrEqual(other);
  1789. }
  1790. toExtendedJSON(options) {
  1791. if (options && options.relaxed)
  1792. return this.toNumber();
  1793. return { $numberLong: this.toString() };
  1794. }
  1795. static fromExtendedJSON(doc, options) {
  1796. const { useBigInt64 = false, relaxed = true } = { ...options };
  1797. if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
  1798. throw new BSONError('$numberLong string is too long');
  1799. }
  1800. if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
  1801. throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
  1802. }
  1803. if (useBigInt64) {
  1804. const bigIntResult = BigInt(doc.$numberLong);
  1805. return BigInt.asIntN(64, bigIntResult);
  1806. }
  1807. const longResult = Long.fromString(doc.$numberLong);
  1808. if (relaxed) {
  1809. return longResult.toNumber();
  1810. }
  1811. return longResult;
  1812. }
  1813. inspect(depth, options, inspect) {
  1814. inspect ??= defaultInspect;
  1815. const longVal = inspect(this.toString(), options);
  1816. const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : '';
  1817. return `new Long(${longVal}${unsignedVal})`;
  1818. }
  1819. }
  1820. const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  1821. const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  1822. const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  1823. const EXPONENT_MAX = 6111;
  1824. const EXPONENT_MIN = -6176;
  1825. const EXPONENT_BIAS = 6176;
  1826. const MAX_DIGITS = 34;
  1827. const NAN_BUFFER = ByteUtils.fromNumberArray([
  1828. 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1829. ].reverse());
  1830. const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
  1831. 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1832. ].reverse());
  1833. const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
  1834. 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1835. ].reverse());
  1836. const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  1837. const COMBINATION_MASK = 0x1f;
  1838. const EXPONENT_MASK = 0x3fff;
  1839. const COMBINATION_INFINITY = 30;
  1840. const COMBINATION_NAN = 31;
  1841. function isDigit(value) {
  1842. return !isNaN(parseInt(value, 10));
  1843. }
  1844. function divideu128(value) {
  1845. const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
  1846. let _rem = Long.fromNumber(0);
  1847. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  1848. return { quotient: value, rem: _rem };
  1849. }
  1850. for (let i = 0; i <= 3; i++) {
  1851. _rem = _rem.shiftLeft(32);
  1852. _rem = _rem.add(new Long(value.parts[i], 0));
  1853. value.parts[i] = _rem.div(DIVISOR).low;
  1854. _rem = _rem.modulo(DIVISOR);
  1855. }
  1856. return { quotient: value, rem: _rem };
  1857. }
  1858. function multiply64x2(left, right) {
  1859. if (!left && !right) {
  1860. return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
  1861. }
  1862. const leftHigh = left.shiftRightUnsigned(32);
  1863. const leftLow = new Long(left.getLowBits(), 0);
  1864. const rightHigh = right.shiftRightUnsigned(32);
  1865. const rightLow = new Long(right.getLowBits(), 0);
  1866. let productHigh = leftHigh.multiply(rightHigh);
  1867. let productMid = leftHigh.multiply(rightLow);
  1868. const productMid2 = leftLow.multiply(rightHigh);
  1869. let productLow = leftLow.multiply(rightLow);
  1870. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1871. productMid = new Long(productMid.getLowBits(), 0)
  1872. .add(productMid2)
  1873. .add(productLow.shiftRightUnsigned(32));
  1874. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1875. productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
  1876. return { high: productHigh, low: productLow };
  1877. }
  1878. function lessThan(left, right) {
  1879. const uhleft = left.high >>> 0;
  1880. const uhright = right.high >>> 0;
  1881. if (uhleft < uhright) {
  1882. return true;
  1883. }
  1884. else if (uhleft === uhright) {
  1885. const ulleft = left.low >>> 0;
  1886. const ulright = right.low >>> 0;
  1887. if (ulleft < ulright)
  1888. return true;
  1889. }
  1890. return false;
  1891. }
  1892. function invalidErr(string, message) {
  1893. throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
  1894. }
  1895. class Decimal128 extends BSONValue {
  1896. get _bsontype() {
  1897. return 'Decimal128';
  1898. }
  1899. bytes;
  1900. constructor(bytes) {
  1901. super();
  1902. if (typeof bytes === 'string') {
  1903. this.bytes = Decimal128.fromString(bytes).bytes;
  1904. }
  1905. else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
  1906. if (bytes.byteLength !== 16) {
  1907. throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
  1908. }
  1909. this.bytes = bytes;
  1910. }
  1911. else {
  1912. throw new BSONError('Decimal128 must take a Buffer or string');
  1913. }
  1914. }
  1915. static fromString(representation) {
  1916. return Decimal128._fromString(representation, { allowRounding: false });
  1917. }
  1918. static fromStringWithRounding(representation) {
  1919. return Decimal128._fromString(representation, { allowRounding: true });
  1920. }
  1921. static _fromString(representation, options) {
  1922. let isNegative = false;
  1923. let sawSign = false;
  1924. let sawRadix = false;
  1925. let foundNonZero = false;
  1926. let significantDigits = 0;
  1927. let nDigitsRead = 0;
  1928. let nDigits = 0;
  1929. let radixPosition = 0;
  1930. let firstNonZero = 0;
  1931. const digits = [0];
  1932. let nDigitsStored = 0;
  1933. let digitsInsert = 0;
  1934. let lastDigit = 0;
  1935. let exponent = 0;
  1936. let significandHigh = new Long(0, 0);
  1937. let significandLow = new Long(0, 0);
  1938. let biasedExponent = 0;
  1939. let index = 0;
  1940. if (representation.length >= 7000) {
  1941. throw new BSONError('' + representation + ' not a valid Decimal128 string');
  1942. }
  1943. const stringMatch = representation.match(PARSE_STRING_REGEXP);
  1944. const infMatch = representation.match(PARSE_INF_REGEXP);
  1945. const nanMatch = representation.match(PARSE_NAN_REGEXP);
  1946. if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
  1947. throw new BSONError('' + representation + ' not a valid Decimal128 string');
  1948. }
  1949. if (stringMatch) {
  1950. const unsignedNumber = stringMatch[2];
  1951. const e = stringMatch[4];
  1952. const expSign = stringMatch[5];
  1953. const expNumber = stringMatch[6];
  1954. if (e && expNumber === undefined)
  1955. invalidErr(representation, 'missing exponent power');
  1956. if (e && unsignedNumber === undefined)
  1957. invalidErr(representation, 'missing exponent base');
  1958. if (e === undefined && (expSign || expNumber)) {
  1959. invalidErr(representation, 'missing e before exponent');
  1960. }
  1961. }
  1962. if (representation[index] === '+' || representation[index] === '-') {
  1963. sawSign = true;
  1964. isNegative = representation[index++] === '-';
  1965. }
  1966. if (!isDigit(representation[index]) && representation[index] !== '.') {
  1967. if (representation[index] === 'i' || representation[index] === 'I') {
  1968. return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
  1969. }
  1970. else if (representation[index] === 'N') {
  1971. return new Decimal128(NAN_BUFFER);
  1972. }
  1973. }
  1974. while (isDigit(representation[index]) || representation[index] === '.') {
  1975. if (representation[index] === '.') {
  1976. if (sawRadix)
  1977. invalidErr(representation, 'contains multiple periods');
  1978. sawRadix = true;
  1979. index = index + 1;
  1980. continue;
  1981. }
  1982. if (nDigitsStored < MAX_DIGITS) {
  1983. if (representation[index] !== '0' || foundNonZero) {
  1984. if (!foundNonZero) {
  1985. firstNonZero = nDigitsRead;
  1986. }
  1987. foundNonZero = true;
  1988. digits[digitsInsert++] = parseInt(representation[index], 10);
  1989. nDigitsStored = nDigitsStored + 1;
  1990. }
  1991. }
  1992. if (foundNonZero)
  1993. nDigits = nDigits + 1;
  1994. if (sawRadix)
  1995. radixPosition = radixPosition + 1;
  1996. nDigitsRead = nDigitsRead + 1;
  1997. index = index + 1;
  1998. }
  1999. if (sawRadix && !nDigitsRead)
  2000. throw new BSONError('' + representation + ' not a valid Decimal128 string');
  2001. if (representation[index] === 'e' || representation[index] === 'E') {
  2002. const match = representation.substr(++index).match(EXPONENT_REGEX);
  2003. if (!match || !match[2])
  2004. return new Decimal128(NAN_BUFFER);
  2005. exponent = parseInt(match[0], 10);
  2006. index = index + match[0].length;
  2007. }
  2008. if (representation[index])
  2009. return new Decimal128(NAN_BUFFER);
  2010. if (!nDigitsStored) {
  2011. digits[0] = 0;
  2012. nDigits = 1;
  2013. nDigitsStored = 1;
  2014. significantDigits = 0;
  2015. }
  2016. else {
  2017. lastDigit = nDigitsStored - 1;
  2018. significantDigits = nDigits;
  2019. if (significantDigits !== 1) {
  2020. while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') {
  2021. significantDigits = significantDigits - 1;
  2022. }
  2023. }
  2024. }
  2025. if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
  2026. exponent = EXPONENT_MIN;
  2027. }
  2028. else {
  2029. exponent = exponent - radixPosition;
  2030. }
  2031. while (exponent > EXPONENT_MAX) {
  2032. lastDigit = lastDigit + 1;
  2033. if (lastDigit >= MAX_DIGITS) {
  2034. if (significantDigits === 0) {
  2035. exponent = EXPONENT_MAX;
  2036. break;
  2037. }
  2038. invalidErr(representation, 'overflow');
  2039. }
  2040. exponent = exponent - 1;
  2041. }
  2042. if (options.allowRounding) {
  2043. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  2044. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  2045. exponent = EXPONENT_MIN;
  2046. significantDigits = 0;
  2047. break;
  2048. }
  2049. if (nDigitsStored < nDigits) {
  2050. nDigits = nDigits - 1;
  2051. }
  2052. else {
  2053. lastDigit = lastDigit - 1;
  2054. }
  2055. if (exponent < EXPONENT_MAX) {
  2056. exponent = exponent + 1;
  2057. }
  2058. else {
  2059. const digitsString = digits.join('');
  2060. if (digitsString.match(/^0+$/)) {
  2061. exponent = EXPONENT_MAX;
  2062. break;
  2063. }
  2064. invalidErr(representation, 'overflow');
  2065. }
  2066. }
  2067. if (lastDigit + 1 < significantDigits) {
  2068. let endOfString = nDigitsRead;
  2069. if (sawRadix) {
  2070. firstNonZero = firstNonZero + 1;
  2071. endOfString = endOfString + 1;
  2072. }
  2073. if (sawSign) {
  2074. firstNonZero = firstNonZero + 1;
  2075. endOfString = endOfString + 1;
  2076. }
  2077. const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  2078. let roundBit = 0;
  2079. if (roundDigit >= 5) {
  2080. roundBit = 1;
  2081. if (roundDigit === 5) {
  2082. roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
  2083. for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  2084. if (parseInt(representation[i], 10)) {
  2085. roundBit = 1;
  2086. break;
  2087. }
  2088. }
  2089. }
  2090. }
  2091. if (roundBit) {
  2092. let dIdx = lastDigit;
  2093. for (; dIdx >= 0; dIdx--) {
  2094. if (++digits[dIdx] > 9) {
  2095. digits[dIdx] = 0;
  2096. if (dIdx === 0) {
  2097. if (exponent < EXPONENT_MAX) {
  2098. exponent = exponent + 1;
  2099. digits[dIdx] = 1;
  2100. }
  2101. else {
  2102. return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
  2103. }
  2104. }
  2105. }
  2106. else {
  2107. break;
  2108. }
  2109. }
  2110. }
  2111. }
  2112. }
  2113. else {
  2114. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  2115. if (lastDigit === 0) {
  2116. if (significantDigits === 0) {
  2117. exponent = EXPONENT_MIN;
  2118. break;
  2119. }
  2120. invalidErr(representation, 'exponent underflow');
  2121. }
  2122. if (nDigitsStored < nDigits) {
  2123. if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
  2124. significantDigits !== 0) {
  2125. invalidErr(representation, 'inexact rounding');
  2126. }
  2127. nDigits = nDigits - 1;
  2128. }
  2129. else {
  2130. if (digits[lastDigit] !== 0) {
  2131. invalidErr(representation, 'inexact rounding');
  2132. }
  2133. lastDigit = lastDigit - 1;
  2134. }
  2135. if (exponent < EXPONENT_MAX) {
  2136. exponent = exponent + 1;
  2137. }
  2138. else {
  2139. invalidErr(representation, 'overflow');
  2140. }
  2141. }
  2142. if (lastDigit + 1 < significantDigits) {
  2143. if (sawRadix) {
  2144. firstNonZero = firstNonZero + 1;
  2145. }
  2146. if (sawSign) {
  2147. firstNonZero = firstNonZero + 1;
  2148. }
  2149. const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  2150. if (roundDigit !== 0) {
  2151. invalidErr(representation, 'inexact rounding');
  2152. }
  2153. }
  2154. }
  2155. significandHigh = Long.fromNumber(0);
  2156. significandLow = Long.fromNumber(0);
  2157. if (significantDigits === 0) {
  2158. significandHigh = Long.fromNumber(0);
  2159. significandLow = Long.fromNumber(0);
  2160. }
  2161. else if (lastDigit < 17) {
  2162. let dIdx = 0;
  2163. significandLow = Long.fromNumber(digits[dIdx++]);
  2164. significandHigh = new Long(0, 0);
  2165. for (; dIdx <= lastDigit; dIdx++) {
  2166. significandLow = significandLow.multiply(Long.fromNumber(10));
  2167. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  2168. }
  2169. }
  2170. else {
  2171. let dIdx = 0;
  2172. significandHigh = Long.fromNumber(digits[dIdx++]);
  2173. for (; dIdx <= lastDigit - 17; dIdx++) {
  2174. significandHigh = significandHigh.multiply(Long.fromNumber(10));
  2175. significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
  2176. }
  2177. significandLow = Long.fromNumber(digits[dIdx++]);
  2178. for (; dIdx <= lastDigit; dIdx++) {
  2179. significandLow = significandLow.multiply(Long.fromNumber(10));
  2180. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  2181. }
  2182. }
  2183. const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
  2184. significand.low = significand.low.add(significandLow);
  2185. if (lessThan(significand.low, significandLow)) {
  2186. significand.high = significand.high.add(Long.fromNumber(1));
  2187. }
  2188. biasedExponent = exponent + EXPONENT_BIAS;
  2189. const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
  2190. if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
  2191. dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
  2192. dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
  2193. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
  2194. }
  2195. else {
  2196. dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  2197. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
  2198. }
  2199. dec.low = significand.low;
  2200. if (isNegative) {
  2201. dec.high = dec.high.or(Long.fromString('9223372036854775808'));
  2202. }
  2203. const buffer = ByteUtils.allocateUnsafe(16);
  2204. index = 0;
  2205. buffer[index++] = dec.low.low & 0xff;
  2206. buffer[index++] = (dec.low.low >> 8) & 0xff;
  2207. buffer[index++] = (dec.low.low >> 16) & 0xff;
  2208. buffer[index++] = (dec.low.low >> 24) & 0xff;
  2209. buffer[index++] = dec.low.high & 0xff;
  2210. buffer[index++] = (dec.low.high >> 8) & 0xff;
  2211. buffer[index++] = (dec.low.high >> 16) & 0xff;
  2212. buffer[index++] = (dec.low.high >> 24) & 0xff;
  2213. buffer[index++] = dec.high.low & 0xff;
  2214. buffer[index++] = (dec.high.low >> 8) & 0xff;
  2215. buffer[index++] = (dec.high.low >> 16) & 0xff;
  2216. buffer[index++] = (dec.high.low >> 24) & 0xff;
  2217. buffer[index++] = dec.high.high & 0xff;
  2218. buffer[index++] = (dec.high.high >> 8) & 0xff;
  2219. buffer[index++] = (dec.high.high >> 16) & 0xff;
  2220. buffer[index++] = (dec.high.high >> 24) & 0xff;
  2221. return new Decimal128(buffer);
  2222. }
  2223. toString() {
  2224. let biased_exponent;
  2225. let significand_digits = 0;
  2226. const significand = new Array(36);
  2227. for (let i = 0; i < significand.length; i++)
  2228. significand[i] = 0;
  2229. let index = 0;
  2230. let is_zero = false;
  2231. let significand_msb;
  2232. let significand128 = { parts: [0, 0, 0, 0] };
  2233. let j, k;
  2234. const string = [];
  2235. index = 0;
  2236. const buffer = this.bytes;
  2237. const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2238. const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2239. const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2240. const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2241. index = 0;
  2242. const dec = {
  2243. low: new Long(low, midl),
  2244. high: new Long(midh, high)
  2245. };
  2246. if (dec.high.lessThan(Long.ZERO)) {
  2247. string.push('-');
  2248. }
  2249. const combination = (high >> 26) & COMBINATION_MASK;
  2250. if (combination >> 3 === 3) {
  2251. if (combination === COMBINATION_INFINITY) {
  2252. return string.join('') + 'Infinity';
  2253. }
  2254. else if (combination === COMBINATION_NAN) {
  2255. return 'NaN';
  2256. }
  2257. else {
  2258. biased_exponent = (high >> 15) & EXPONENT_MASK;
  2259. significand_msb = 0x08 + ((high >> 14) & 0x01);
  2260. }
  2261. }
  2262. else {
  2263. significand_msb = (high >> 14) & 0x07;
  2264. biased_exponent = (high >> 17) & EXPONENT_MASK;
  2265. }
  2266. const exponent = biased_exponent - EXPONENT_BIAS;
  2267. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  2268. significand128.parts[1] = midh;
  2269. significand128.parts[2] = midl;
  2270. significand128.parts[3] = low;
  2271. if (significand128.parts[0] === 0 &&
  2272. significand128.parts[1] === 0 &&
  2273. significand128.parts[2] === 0 &&
  2274. significand128.parts[3] === 0) {
  2275. is_zero = true;
  2276. }
  2277. else {
  2278. for (k = 3; k >= 0; k--) {
  2279. let least_digits = 0;
  2280. const result = divideu128(significand128);
  2281. significand128 = result.quotient;
  2282. least_digits = result.rem.low;
  2283. if (!least_digits)
  2284. continue;
  2285. for (j = 8; j >= 0; j--) {
  2286. significand[k * 9 + j] = least_digits % 10;
  2287. least_digits = Math.floor(least_digits / 10);
  2288. }
  2289. }
  2290. }
  2291. if (is_zero) {
  2292. significand_digits = 1;
  2293. significand[index] = 0;
  2294. }
  2295. else {
  2296. significand_digits = 36;
  2297. while (!significand[index]) {
  2298. significand_digits = significand_digits - 1;
  2299. index = index + 1;
  2300. }
  2301. }
  2302. const scientific_exponent = significand_digits - 1 + exponent;
  2303. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  2304. if (significand_digits > 34) {
  2305. string.push(`${0}`);
  2306. if (exponent > 0)
  2307. string.push(`E+${exponent}`);
  2308. else if (exponent < 0)
  2309. string.push(`E${exponent}`);
  2310. return string.join('');
  2311. }
  2312. string.push(`${significand[index++]}`);
  2313. significand_digits = significand_digits - 1;
  2314. if (significand_digits) {
  2315. string.push('.');
  2316. }
  2317. for (let i = 0; i < significand_digits; i++) {
  2318. string.push(`${significand[index++]}`);
  2319. }
  2320. string.push('E');
  2321. if (scientific_exponent > 0) {
  2322. string.push(`+${scientific_exponent}`);
  2323. }
  2324. else {
  2325. string.push(`${scientific_exponent}`);
  2326. }
  2327. }
  2328. else {
  2329. if (exponent >= 0) {
  2330. for (let i = 0; i < significand_digits; i++) {
  2331. string.push(`${significand[index++]}`);
  2332. }
  2333. }
  2334. else {
  2335. let radix_position = significand_digits + exponent;
  2336. if (radix_position > 0) {
  2337. for (let i = 0; i < radix_position; i++) {
  2338. string.push(`${significand[index++]}`);
  2339. }
  2340. }
  2341. else {
  2342. string.push('0');
  2343. }
  2344. string.push('.');
  2345. while (radix_position++ < 0) {
  2346. string.push('0');
  2347. }
  2348. for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  2349. string.push(`${significand[index++]}`);
  2350. }
  2351. }
  2352. }
  2353. return string.join('');
  2354. }
  2355. toJSON() {
  2356. return { $numberDecimal: this.toString() };
  2357. }
  2358. toExtendedJSON() {
  2359. return { $numberDecimal: this.toString() };
  2360. }
  2361. static fromExtendedJSON(doc) {
  2362. return Decimal128.fromString(doc.$numberDecimal);
  2363. }
  2364. inspect(depth, options, inspect) {
  2365. inspect ??= defaultInspect;
  2366. const d128string = inspect(this.toString(), options);
  2367. return `new Decimal128(${d128string})`;
  2368. }
  2369. }
  2370. class Double extends BSONValue {
  2371. get _bsontype() {
  2372. return 'Double';
  2373. }
  2374. value;
  2375. constructor(value) {
  2376. super();
  2377. if (value instanceof Number) {
  2378. value = value.valueOf();
  2379. }
  2380. this.value = +value;
  2381. }
  2382. static fromString(value) {
  2383. const coercedValue = Number(value);
  2384. if (value === 'NaN')
  2385. return new Double(NaN);
  2386. if (value === 'Infinity')
  2387. return new Double(Infinity);
  2388. if (value === '-Infinity')
  2389. return new Double(-Infinity);
  2390. if (!Number.isFinite(coercedValue)) {
  2391. throw new BSONError(`Input: ${value} is not representable as a Double`);
  2392. }
  2393. if (value.trim() !== value) {
  2394. throw new BSONError(`Input: '${value}' contains whitespace`);
  2395. }
  2396. if (value === '') {
  2397. throw new BSONError(`Input is an empty string`);
  2398. }
  2399. if (/[^-0-9.+eE]/.test(value)) {
  2400. throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
  2401. }
  2402. return new Double(coercedValue);
  2403. }
  2404. valueOf() {
  2405. return this.value;
  2406. }
  2407. toJSON() {
  2408. return this.value;
  2409. }
  2410. toString(radix) {
  2411. return this.value.toString(radix);
  2412. }
  2413. toExtendedJSON(options) {
  2414. if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
  2415. return this.value;
  2416. }
  2417. if (Object.is(Math.sign(this.value), -0)) {
  2418. return { $numberDouble: '-0.0' };
  2419. }
  2420. return {
  2421. $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
  2422. };
  2423. }
  2424. static fromExtendedJSON(doc, options) {
  2425. const doubleValue = parseFloat(doc.$numberDouble);
  2426. return options && options.relaxed ? doubleValue : new Double(doubleValue);
  2427. }
  2428. inspect(depth, options, inspect) {
  2429. inspect ??= defaultInspect;
  2430. return `new Double(${inspect(this.value, options)})`;
  2431. }
  2432. }
  2433. class Int32 extends BSONValue {
  2434. get _bsontype() {
  2435. return 'Int32';
  2436. }
  2437. value;
  2438. constructor(value) {
  2439. super();
  2440. if (value instanceof Number) {
  2441. value = value.valueOf();
  2442. }
  2443. this.value = +value | 0;
  2444. }
  2445. static fromString(value) {
  2446. const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
  2447. const coercedValue = Number(value);
  2448. if (BSON_INT32_MAX < coercedValue) {
  2449. throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
  2450. }
  2451. else if (BSON_INT32_MIN > coercedValue) {
  2452. throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
  2453. }
  2454. else if (!Number.isSafeInteger(coercedValue)) {
  2455. throw new BSONError(`Input: '${value}' is not a safe integer`);
  2456. }
  2457. else if (coercedValue.toString() !== cleanedValue) {
  2458. throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
  2459. }
  2460. return new Int32(coercedValue);
  2461. }
  2462. valueOf() {
  2463. return this.value;
  2464. }
  2465. toString(radix) {
  2466. return this.value.toString(radix);
  2467. }
  2468. toJSON() {
  2469. return this.value;
  2470. }
  2471. toExtendedJSON(options) {
  2472. if (options && (options.relaxed || options.legacy))
  2473. return this.value;
  2474. return { $numberInt: this.value.toString() };
  2475. }
  2476. static fromExtendedJSON(doc, options) {
  2477. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  2478. }
  2479. inspect(depth, options, inspect) {
  2480. inspect ??= defaultInspect;
  2481. return `new Int32(${inspect(this.value, options)})`;
  2482. }
  2483. }
  2484. class MaxKey extends BSONValue {
  2485. get _bsontype() {
  2486. return 'MaxKey';
  2487. }
  2488. toExtendedJSON() {
  2489. return { $maxKey: 1 };
  2490. }
  2491. static fromExtendedJSON() {
  2492. return new MaxKey();
  2493. }
  2494. inspect() {
  2495. return 'new MaxKey()';
  2496. }
  2497. }
  2498. class MinKey extends BSONValue {
  2499. get _bsontype() {
  2500. return 'MinKey';
  2501. }
  2502. toExtendedJSON() {
  2503. return { $minKey: 1 };
  2504. }
  2505. static fromExtendedJSON() {
  2506. return new MinKey();
  2507. }
  2508. inspect() {
  2509. return 'new MinKey()';
  2510. }
  2511. }
  2512. let PROCESS_UNIQUE = null;
  2513. const __idCache = new WeakMap();
  2514. class ObjectId extends BSONValue {
  2515. get _bsontype() {
  2516. return 'ObjectId';
  2517. }
  2518. static index = Math.floor(Math.random() * 0xffffff);
  2519. static cacheHexString;
  2520. buffer;
  2521. constructor(inputId) {
  2522. super();
  2523. let workingId;
  2524. if (typeof inputId === 'object' && inputId && 'id' in inputId) {
  2525. if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
  2526. throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
  2527. }
  2528. if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
  2529. workingId = ByteUtils.fromHex(inputId.toHexString());
  2530. }
  2531. else {
  2532. workingId = inputId.id;
  2533. }
  2534. }
  2535. else {
  2536. workingId = inputId;
  2537. }
  2538. if (workingId == null) {
  2539. this.buffer = ObjectId.generate();
  2540. }
  2541. else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
  2542. this.buffer = ByteUtils.toLocalBufferType(workingId);
  2543. }
  2544. else if (typeof workingId === 'string') {
  2545. if (ObjectId.validateHexString(workingId)) {
  2546. this.buffer = ByteUtils.fromHex(workingId);
  2547. if (ObjectId.cacheHexString) {
  2548. __idCache.set(this, workingId);
  2549. }
  2550. }
  2551. else {
  2552. throw new BSONError('input must be a 24 character hex string, 12 byte Uint8Array, or an integer');
  2553. }
  2554. }
  2555. else {
  2556. throw new BSONError('Argument passed in does not match the accepted types');
  2557. }
  2558. }
  2559. get id() {
  2560. return this.buffer;
  2561. }
  2562. set id(value) {
  2563. this.buffer = value;
  2564. if (ObjectId.cacheHexString) {
  2565. __idCache.set(this, ByteUtils.toHex(value));
  2566. }
  2567. }
  2568. static validateHexString(string) {
  2569. if (string?.length !== 24)
  2570. return false;
  2571. for (let i = 0; i < 24; i++) {
  2572. const char = string.charCodeAt(i);
  2573. if ((char >= 48 && char <= 57) ||
  2574. (char >= 97 && char <= 102) ||
  2575. (char >= 65 && char <= 70)) {
  2576. continue;
  2577. }
  2578. return false;
  2579. }
  2580. return true;
  2581. }
  2582. toHexString() {
  2583. if (ObjectId.cacheHexString) {
  2584. const __id = __idCache.get(this);
  2585. if (__id)
  2586. return __id;
  2587. }
  2588. const hexString = ByteUtils.toHex(this.id);
  2589. if (ObjectId.cacheHexString) {
  2590. __idCache.set(this, hexString);
  2591. }
  2592. return hexString;
  2593. }
  2594. static getInc() {
  2595. return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
  2596. }
  2597. static generate(time) {
  2598. if ('number' !== typeof time) {
  2599. time = Math.floor(Date.now() / 1000);
  2600. }
  2601. const inc = ObjectId.getInc();
  2602. const buffer = ByteUtils.allocateUnsafe(12);
  2603. NumberUtils.setInt32BE(buffer, 0, time);
  2604. if (PROCESS_UNIQUE === null) {
  2605. PROCESS_UNIQUE = ByteUtils.randomBytes(5);
  2606. }
  2607. buffer[4] = PROCESS_UNIQUE[0];
  2608. buffer[5] = PROCESS_UNIQUE[1];
  2609. buffer[6] = PROCESS_UNIQUE[2];
  2610. buffer[7] = PROCESS_UNIQUE[3];
  2611. buffer[8] = PROCESS_UNIQUE[4];
  2612. buffer[11] = inc & 0xff;
  2613. buffer[10] = (inc >> 8) & 0xff;
  2614. buffer[9] = (inc >> 16) & 0xff;
  2615. return buffer;
  2616. }
  2617. toString(encoding) {
  2618. if (encoding === 'base64')
  2619. return ByteUtils.toBase64(this.id);
  2620. if (encoding === 'hex')
  2621. return this.toHexString();
  2622. return this.toHexString();
  2623. }
  2624. toJSON() {
  2625. return this.toHexString();
  2626. }
  2627. static is(variable) {
  2628. return (variable != null &&
  2629. typeof variable === 'object' &&
  2630. '_bsontype' in variable &&
  2631. variable._bsontype === 'ObjectId');
  2632. }
  2633. equals(otherId) {
  2634. if (otherId === undefined || otherId === null) {
  2635. return false;
  2636. }
  2637. if (ObjectId.is(otherId)) {
  2638. return (this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer));
  2639. }
  2640. if (typeof otherId === 'string') {
  2641. return otherId.toLowerCase() === this.toHexString();
  2642. }
  2643. if (typeof otherId === 'object' && typeof otherId.toHexString === 'function') {
  2644. const otherIdString = otherId.toHexString();
  2645. const thisIdString = this.toHexString();
  2646. return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
  2647. }
  2648. return false;
  2649. }
  2650. getTimestamp() {
  2651. const timestamp = new Date();
  2652. const time = NumberUtils.getUint32BE(this.buffer, 0);
  2653. timestamp.setTime(Math.floor(time) * 1000);
  2654. return timestamp;
  2655. }
  2656. static createPk() {
  2657. return new ObjectId();
  2658. }
  2659. serializeInto(uint8array, index) {
  2660. uint8array[index] = this.buffer[0];
  2661. uint8array[index + 1] = this.buffer[1];
  2662. uint8array[index + 2] = this.buffer[2];
  2663. uint8array[index + 3] = this.buffer[3];
  2664. uint8array[index + 4] = this.buffer[4];
  2665. uint8array[index + 5] = this.buffer[5];
  2666. uint8array[index + 6] = this.buffer[6];
  2667. uint8array[index + 7] = this.buffer[7];
  2668. uint8array[index + 8] = this.buffer[8];
  2669. uint8array[index + 9] = this.buffer[9];
  2670. uint8array[index + 10] = this.buffer[10];
  2671. uint8array[index + 11] = this.buffer[11];
  2672. return 12;
  2673. }
  2674. static createFromTime(time) {
  2675. const buffer = ByteUtils.allocate(12);
  2676. for (let i = 11; i >= 4; i--)
  2677. buffer[i] = 0;
  2678. NumberUtils.setInt32BE(buffer, 0, time);
  2679. return new ObjectId(buffer);
  2680. }
  2681. static createFromHexString(hexString) {
  2682. if (hexString?.length !== 24) {
  2683. throw new BSONError('hex string must be 24 characters');
  2684. }
  2685. return new ObjectId(ByteUtils.fromHex(hexString));
  2686. }
  2687. static createFromBase64(base64) {
  2688. if (base64?.length !== 16) {
  2689. throw new BSONError('base64 string must be 16 characters');
  2690. }
  2691. return new ObjectId(ByteUtils.fromBase64(base64));
  2692. }
  2693. static isValid(id) {
  2694. if (id == null)
  2695. return false;
  2696. if (typeof id === 'string')
  2697. return ObjectId.validateHexString(id);
  2698. try {
  2699. new ObjectId(id);
  2700. return true;
  2701. }
  2702. catch {
  2703. return false;
  2704. }
  2705. }
  2706. toExtendedJSON() {
  2707. if (this.toHexString)
  2708. return { $oid: this.toHexString() };
  2709. return { $oid: this.toString('hex') };
  2710. }
  2711. static fromExtendedJSON(doc) {
  2712. return new ObjectId(doc.$oid);
  2713. }
  2714. isCached() {
  2715. return ObjectId.cacheHexString && __idCache.has(this);
  2716. }
  2717. inspect(depth, options, inspect) {
  2718. inspect ??= defaultInspect;
  2719. return `new ObjectId(${inspect(this.toHexString(), options)})`;
  2720. }
  2721. }
  2722. function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
  2723. let totalLength = 4 + 1;
  2724. if (Array.isArray(object)) {
  2725. for (let i = 0; i < object.length; i++) {
  2726. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  2727. }
  2728. }
  2729. else {
  2730. if (typeof object?.toBSON === 'function') {
  2731. object = object.toBSON();
  2732. }
  2733. for (const key of Object.keys(object)) {
  2734. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  2735. }
  2736. }
  2737. return totalLength;
  2738. }
  2739. function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
  2740. if (typeof value?.toBSON === 'function') {
  2741. value = value.toBSON();
  2742. }
  2743. switch (typeof value) {
  2744. case 'string':
  2745. return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
  2746. case 'number':
  2747. if (Math.floor(value) === value &&
  2748. value >= JS_INT_MIN &&
  2749. value <= JS_INT_MAX) {
  2750. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  2751. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
  2752. }
  2753. else {
  2754. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2755. }
  2756. }
  2757. else {
  2758. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2759. }
  2760. case 'undefined':
  2761. if (isArray || !ignoreUndefined)
  2762. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
  2763. return 0;
  2764. case 'boolean':
  2765. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
  2766. case 'object':
  2767. if (value != null &&
  2768. typeof value._bsontype === 'string' &&
  2769. value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
  2770. throw new BSONVersionError();
  2771. }
  2772. else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  2773. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
  2774. }
  2775. else if (value._bsontype === 'ObjectId') {
  2776. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
  2777. }
  2778. else if (value instanceof Date || isDate(value)) {
  2779. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2780. }
  2781. else if (ArrayBuffer.isView(value) ||
  2782. value instanceof ArrayBuffer ||
  2783. isAnyArrayBuffer(value)) {
  2784. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength);
  2785. }
  2786. else if (value._bsontype === 'Long' ||
  2787. value._bsontype === 'Double' ||
  2788. value._bsontype === 'Timestamp') {
  2789. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2790. }
  2791. else if (value._bsontype === 'Decimal128') {
  2792. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
  2793. }
  2794. else if (value._bsontype === 'Code') {
  2795. if (value.scope != null && Object.keys(value.scope).length > 0) {
  2796. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2797. 1 +
  2798. 4 +
  2799. 4 +
  2800. ByteUtils.utf8ByteLength(value.code.toString()) +
  2801. 1 +
  2802. internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
  2803. }
  2804. else {
  2805. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2806. 1 +
  2807. 4 +
  2808. ByteUtils.utf8ByteLength(value.code.toString()) +
  2809. 1);
  2810. }
  2811. }
  2812. else if (value._bsontype === 'Binary') {
  2813. const binary = value;
  2814. if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  2815. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2816. (binary.position + 1 + 4 + 1 + 4));
  2817. }
  2818. else {
  2819. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1));
  2820. }
  2821. }
  2822. else if (value._bsontype === 'Symbol') {
  2823. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2824. ByteUtils.utf8ByteLength(value.value) +
  2825. 4 +
  2826. 1 +
  2827. 1);
  2828. }
  2829. else if (value._bsontype === 'DBRef') {
  2830. const ordered_values = Object.assign({
  2831. $ref: value.collection,
  2832. $id: value.oid
  2833. }, value.fields);
  2834. if (value.db != null) {
  2835. ordered_values['$db'] = value.db;
  2836. }
  2837. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2838. 1 +
  2839. internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
  2840. }
  2841. else if (value instanceof RegExp || isRegExp(value)) {
  2842. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2843. 1 +
  2844. ByteUtils.utf8ByteLength(value.source) +
  2845. 1 +
  2846. (value.global ? 1 : 0) +
  2847. (value.ignoreCase ? 1 : 0) +
  2848. (value.multiline ? 1 : 0) +
  2849. 1);
  2850. }
  2851. else if (value._bsontype === 'BSONRegExp') {
  2852. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2853. 1 +
  2854. ByteUtils.utf8ByteLength(value.pattern) +
  2855. 1 +
  2856. ByteUtils.utf8ByteLength(value.options) +
  2857. 1);
  2858. }
  2859. else {
  2860. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2861. internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) +
  2862. 1);
  2863. }
  2864. case 'function':
  2865. if (serializeFunctions) {
  2866. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2867. 1 +
  2868. 4 +
  2869. ByteUtils.utf8ByteLength(value.toString()) +
  2870. 1);
  2871. }
  2872. return 0;
  2873. case 'bigint':
  2874. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2875. case 'symbol':
  2876. return 0;
  2877. default:
  2878. throw new BSONError(`Unrecognized JS type: ${typeof value}`);
  2879. }
  2880. return 0;
  2881. }
  2882. function alphabetize(str) {
  2883. return str.split('').sort().join('');
  2884. }
  2885. class BSONRegExp extends BSONValue {
  2886. get _bsontype() {
  2887. return 'BSONRegExp';
  2888. }
  2889. pattern;
  2890. options;
  2891. constructor(pattern, options) {
  2892. super();
  2893. this.pattern = pattern;
  2894. this.options = alphabetize(options ?? '');
  2895. if (this.pattern.indexOf('\x00') !== -1) {
  2896. throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
  2897. }
  2898. if (this.options.indexOf('\x00') !== -1) {
  2899. throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
  2900. }
  2901. for (let i = 0; i < this.options.length; i++) {
  2902. if (!(this.options[i] === 'i' ||
  2903. this.options[i] === 'm' ||
  2904. this.options[i] === 'x' ||
  2905. this.options[i] === 'l' ||
  2906. this.options[i] === 's' ||
  2907. this.options[i] === 'u')) {
  2908. throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
  2909. }
  2910. }
  2911. }
  2912. static parseOptions(options) {
  2913. return options ? options.split('').sort().join('') : '';
  2914. }
  2915. toExtendedJSON(options) {
  2916. options = options || {};
  2917. if (options.legacy) {
  2918. return { $regex: this.pattern, $options: this.options };
  2919. }
  2920. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  2921. }
  2922. static fromExtendedJSON(doc) {
  2923. if ('$regex' in doc) {
  2924. if (typeof doc.$regex !== 'string') {
  2925. if (doc.$regex._bsontype === 'BSONRegExp') {
  2926. return doc;
  2927. }
  2928. }
  2929. else {
  2930. return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
  2931. }
  2932. }
  2933. if ('$regularExpression' in doc) {
  2934. return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
  2935. }
  2936. throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
  2937. }
  2938. inspect(depth, options, inspect) {
  2939. const stylize = getStylizeFunction(options) ?? (v => v);
  2940. inspect ??= defaultInspect;
  2941. const pattern = stylize(inspect(this.pattern), 'regexp');
  2942. const flags = stylize(inspect(this.options), 'regexp');
  2943. return `new BSONRegExp(${pattern}, ${flags})`;
  2944. }
  2945. }
  2946. class BSONSymbol extends BSONValue {
  2947. get _bsontype() {
  2948. return 'BSONSymbol';
  2949. }
  2950. value;
  2951. constructor(value) {
  2952. super();
  2953. this.value = value;
  2954. }
  2955. valueOf() {
  2956. return this.value;
  2957. }
  2958. toString() {
  2959. return this.value;
  2960. }
  2961. toJSON() {
  2962. return this.value;
  2963. }
  2964. toExtendedJSON() {
  2965. return { $symbol: this.value };
  2966. }
  2967. static fromExtendedJSON(doc) {
  2968. return new BSONSymbol(doc.$symbol);
  2969. }
  2970. inspect(depth, options, inspect) {
  2971. inspect ??= defaultInspect;
  2972. return `new BSONSymbol(${inspect(this.value, options)})`;
  2973. }
  2974. }
  2975. const LongWithoutOverridesClass = Long;
  2976. class Timestamp extends LongWithoutOverridesClass {
  2977. get _bsontype() {
  2978. return 'Timestamp';
  2979. }
  2980. get [bsonType]() {
  2981. return 'Timestamp';
  2982. }
  2983. static MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
  2984. get i() {
  2985. return this.low >>> 0;
  2986. }
  2987. get t() {
  2988. return this.high >>> 0;
  2989. }
  2990. constructor(low) {
  2991. if (low == null) {
  2992. super(0, 0, true);
  2993. }
  2994. else if (typeof low === 'bigint') {
  2995. super(low, true);
  2996. }
  2997. else if (Long.isLong(low)) {
  2998. super(low.low, low.high, true);
  2999. }
  3000. else if (typeof low === 'object' && 't' in low && 'i' in low) {
  3001. if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) {
  3002. throw new BSONError('Timestamp constructed from { t, i } must provide t as a number');
  3003. }
  3004. if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
  3005. throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
  3006. }
  3007. const t = Number(low.t);
  3008. const i = Number(low.i);
  3009. if (t < 0 || Number.isNaN(t)) {
  3010. throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
  3011. }
  3012. if (i < 0 || Number.isNaN(i)) {
  3013. throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
  3014. }
  3015. if (t > 0xffff_ffff) {
  3016. throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max');
  3017. }
  3018. if (i > 0xffff_ffff) {
  3019. throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max');
  3020. }
  3021. super(i, t, true);
  3022. }
  3023. else {
  3024. throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }');
  3025. }
  3026. }
  3027. toJSON() {
  3028. return {
  3029. $timestamp: this.toString()
  3030. };
  3031. }
  3032. static fromInt(value) {
  3033. return new Timestamp(Long.fromInt(value, true));
  3034. }
  3035. static fromNumber(value) {
  3036. return new Timestamp(Long.fromNumber(value, true));
  3037. }
  3038. static fromBits(lowBits, highBits) {
  3039. return new Timestamp({ i: lowBits, t: highBits });
  3040. }
  3041. static fromString(str, optRadix) {
  3042. return new Timestamp(Long.fromString(str, true, optRadix));
  3043. }
  3044. toExtendedJSON() {
  3045. return { $timestamp: { t: this.t, i: this.i } };
  3046. }
  3047. static fromExtendedJSON(doc) {
  3048. const i = Long.isLong(doc.$timestamp.i)
  3049. ? doc.$timestamp.i.getLowBitsUnsigned()
  3050. : doc.$timestamp.i;
  3051. const t = Long.isLong(doc.$timestamp.t)
  3052. ? doc.$timestamp.t.getLowBitsUnsigned()
  3053. : doc.$timestamp.t;
  3054. return new Timestamp({ t, i });
  3055. }
  3056. inspect(depth, options, inspect) {
  3057. inspect ??= defaultInspect;
  3058. const t = inspect(this.t, options);
  3059. const i = inspect(this.i, options);
  3060. return `new Timestamp({ t: ${t}, i: ${i} })`;
  3061. }
  3062. }
  3063. const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
  3064. const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
  3065. function internalDeserialize(buffer, options, isArray) {
  3066. options = options == null ? {} : options;
  3067. const index = options && options.index ? options.index : 0;
  3068. const size = NumberUtils.getInt32LE(buffer, index);
  3069. if (size < 5) {
  3070. throw new BSONError(`bson size must be >= 5, is ${size}`);
  3071. }
  3072. if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
  3073. throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
  3074. }
  3075. if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
  3076. throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
  3077. }
  3078. if (size + index > buffer.byteLength) {
  3079. throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`);
  3080. }
  3081. if (buffer[index + size - 1] !== 0) {
  3082. throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  3083. }
  3084. return deserializeObject(buffer, index, options, isArray);
  3085. }
  3086. const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
  3087. function deserializeObject(buffer, index, options, isArray = false) {
  3088. const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
  3089. const raw = options['raw'] == null ? false : options['raw'];
  3090. const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
  3091. const promoteBuffers = options.promoteBuffers ?? false;
  3092. const promoteLongs = options.promoteLongs ?? true;
  3093. const promoteValues = options.promoteValues ?? true;
  3094. const useBigInt64 = options.useBigInt64 ?? false;
  3095. if (useBigInt64 && !promoteValues) {
  3096. throw new BSONError('Must either request bigint or Long for int64 deserialization');
  3097. }
  3098. if (useBigInt64 && !promoteLongs) {
  3099. throw new BSONError('Must either request bigint or Long for int64 deserialization');
  3100. }
  3101. const validation = options.validation == null ? { utf8: true } : options.validation;
  3102. let globalUTFValidation = true;
  3103. let validationSetting;
  3104. let utf8KeysSet;
  3105. const utf8ValidatedKeys = validation.utf8;
  3106. if (typeof utf8ValidatedKeys === 'boolean') {
  3107. validationSetting = utf8ValidatedKeys;
  3108. }
  3109. else {
  3110. globalUTFValidation = false;
  3111. const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
  3112. return utf8ValidatedKeys[key];
  3113. });
  3114. if (utf8ValidationValues.length === 0) {
  3115. throw new BSONError('UTF-8 validation setting cannot be empty');
  3116. }
  3117. if (typeof utf8ValidationValues[0] !== 'boolean') {
  3118. throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
  3119. }
  3120. validationSetting = utf8ValidationValues[0];
  3121. if (!utf8ValidationValues.every(item => item === validationSetting)) {
  3122. throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
  3123. }
  3124. }
  3125. if (!globalUTFValidation) {
  3126. utf8KeysSet = new Set();
  3127. for (const key of Object.keys(utf8ValidatedKeys)) {
  3128. utf8KeysSet.add(key);
  3129. }
  3130. }
  3131. const startIndex = index;
  3132. if (buffer.length < 5)
  3133. throw new BSONError('corrupt bson message < 5 bytes long');
  3134. const size = NumberUtils.getInt32LE(buffer, index);
  3135. index += 4;
  3136. if (size < 5 || size > buffer.length)
  3137. throw new BSONError('corrupt bson message');
  3138. const object = isArray ? [] : {};
  3139. let arrayIndex = 0;
  3140. const done = false;
  3141. let isPossibleDBRef = isArray ? false : null;
  3142. while (!done) {
  3143. const elementType = buffer[index++];
  3144. if (elementType === 0)
  3145. break;
  3146. let i = index;
  3147. while (buffer[i] !== 0x00 && i < buffer.length) {
  3148. i++;
  3149. }
  3150. if (i >= buffer.byteLength)
  3151. throw new BSONError('Bad BSON Document: illegal CString');
  3152. const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i, false);
  3153. let shouldValidateKey = true;
  3154. if (globalUTFValidation || utf8KeysSet?.has(name)) {
  3155. shouldValidateKey = validationSetting;
  3156. }
  3157. else {
  3158. shouldValidateKey = !validationSetting;
  3159. }
  3160. if (isPossibleDBRef !== false && name[0] === '$') {
  3161. isPossibleDBRef = allowedDBRefKeys.test(name);
  3162. }
  3163. let value;
  3164. index = i + 1;
  3165. if (elementType === BSON_DATA_STRING) {
  3166. const stringSize = NumberUtils.getInt32LE(buffer, index);
  3167. index += 4;
  3168. if (stringSize <= 0 ||
  3169. stringSize > buffer.length - index ||
  3170. buffer[index + stringSize - 1] !== 0) {
  3171. throw new BSONError('bad string length in bson');
  3172. }
  3173. value = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
  3174. index = index + stringSize;
  3175. }
  3176. else if (elementType === BSON_DATA_OID) {
  3177. const oid = ByteUtils.allocateUnsafe(12);
  3178. for (let i = 0; i < 12; i++)
  3179. oid[i] = buffer[index + i];
  3180. value = new ObjectId(oid);
  3181. index = index + 12;
  3182. }
  3183. else if (elementType === BSON_DATA_INT && promoteValues === false) {
  3184. value = new Int32(NumberUtils.getInt32LE(buffer, index));
  3185. index += 4;
  3186. }
  3187. else if (elementType === BSON_DATA_INT) {
  3188. value = NumberUtils.getInt32LE(buffer, index);
  3189. index += 4;
  3190. }
  3191. else if (elementType === BSON_DATA_NUMBER) {
  3192. value = NumberUtils.getFloat64LE(buffer, index);
  3193. index += 8;
  3194. if (promoteValues === false)
  3195. value = new Double(value);
  3196. }
  3197. else if (elementType === BSON_DATA_DATE) {
  3198. const lowBits = NumberUtils.getInt32LE(buffer, index);
  3199. const highBits = NumberUtils.getInt32LE(buffer, index + 4);
  3200. index += 8;
  3201. value = new Date(new Long(lowBits, highBits).toNumber());
  3202. }
  3203. else if (elementType === BSON_DATA_BOOLEAN) {
  3204. if (buffer[index] !== 0 && buffer[index] !== 1)
  3205. throw new BSONError('illegal boolean type value');
  3206. value = buffer[index++] === 1;
  3207. }
  3208. else if (elementType === BSON_DATA_OBJECT) {
  3209. const _index = index;
  3210. const objectSize = NumberUtils.getInt32LE(buffer, index);
  3211. if (objectSize <= 0 || objectSize > buffer.length - index)
  3212. throw new BSONError('bad embedded document length in bson');
  3213. if (raw) {
  3214. value = buffer.subarray(index, index + objectSize);
  3215. }
  3216. else {
  3217. let objectOptions = options;
  3218. if (!globalUTFValidation) {
  3219. objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
  3220. }
  3221. value = deserializeObject(buffer, _index, objectOptions, false);
  3222. }
  3223. index = index + objectSize;
  3224. }
  3225. else if (elementType === BSON_DATA_ARRAY) {
  3226. const _index = index;
  3227. const objectSize = NumberUtils.getInt32LE(buffer, index);
  3228. let arrayOptions = options;
  3229. const stopIndex = index + objectSize;
  3230. if (fieldsAsRaw && fieldsAsRaw[name]) {
  3231. arrayOptions = { ...options, raw: true };
  3232. }
  3233. if (!globalUTFValidation) {
  3234. arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
  3235. }
  3236. value = deserializeObject(buffer, _index, arrayOptions, true);
  3237. index = index + objectSize;
  3238. if (buffer[index - 1] !== 0)
  3239. throw new BSONError('invalid array terminator byte');
  3240. if (index !== stopIndex)
  3241. throw new BSONError('corrupted array bson');
  3242. }
  3243. else if (elementType === BSON_DATA_UNDEFINED) {
  3244. value = undefined;
  3245. }
  3246. else if (elementType === BSON_DATA_NULL) {
  3247. value = null;
  3248. }
  3249. else if (elementType === BSON_DATA_LONG) {
  3250. if (useBigInt64) {
  3251. value = NumberUtils.getBigInt64LE(buffer, index);
  3252. index += 8;
  3253. }
  3254. else {
  3255. const lowBits = NumberUtils.getInt32LE(buffer, index);
  3256. const highBits = NumberUtils.getInt32LE(buffer, index + 4);
  3257. index += 8;
  3258. const long = new Long(lowBits, highBits);
  3259. if (promoteLongs && promoteValues === true) {
  3260. value =
  3261. long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
  3262. ? long.toNumber()
  3263. : long;
  3264. }
  3265. else {
  3266. value = long;
  3267. }
  3268. }
  3269. }
  3270. else if (elementType === BSON_DATA_DECIMAL128) {
  3271. const bytes = ByteUtils.allocateUnsafe(16);
  3272. for (let i = 0; i < 16; i++)
  3273. bytes[i] = buffer[index + i];
  3274. index = index + 16;
  3275. value = new Decimal128(bytes);
  3276. }
  3277. else if (elementType === BSON_DATA_BINARY) {
  3278. let binarySize = NumberUtils.getInt32LE(buffer, index);
  3279. index += 4;
  3280. const totalBinarySize = binarySize;
  3281. const subType = buffer[index++];
  3282. if (binarySize < 0)
  3283. throw new BSONError('Negative binary type element size found');
  3284. if (binarySize > buffer.byteLength)
  3285. throw new BSONError('Binary type size larger than document size');
  3286. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  3287. binarySize = NumberUtils.getInt32LE(buffer, index);
  3288. index += 4;
  3289. if (binarySize < 0)
  3290. throw new BSONError('Negative binary type element size found for subtype 0x02');
  3291. if (binarySize > totalBinarySize - 4)
  3292. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  3293. if (binarySize < totalBinarySize - 4)
  3294. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  3295. }
  3296. if (promoteBuffers && promoteValues) {
  3297. value = ByteUtils.toLocalBufferType(buffer.subarray(index, index + binarySize));
  3298. }
  3299. else {
  3300. value = new Binary(buffer.subarray(index, index + binarySize), subType);
  3301. if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
  3302. value = value.toUUID();
  3303. }
  3304. }
  3305. index = index + binarySize;
  3306. }
  3307. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
  3308. i = index;
  3309. while (buffer[i] !== 0x00 && i < buffer.length) {
  3310. i++;
  3311. }
  3312. if (i >= buffer.length)
  3313. throw new BSONError('Bad BSON Document: illegal CString');
  3314. const source = ByteUtils.toUTF8(buffer, index, i, false);
  3315. index = i + 1;
  3316. i = index;
  3317. while (buffer[i] !== 0x00 && i < buffer.length) {
  3318. i++;
  3319. }
  3320. if (i >= buffer.length)
  3321. throw new BSONError('Bad BSON Document: illegal CString');
  3322. const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
  3323. index = i + 1;
  3324. const optionsArray = new Array(regExpOptions.length);
  3325. for (i = 0; i < regExpOptions.length; i++) {
  3326. switch (regExpOptions[i]) {
  3327. case 'm':
  3328. optionsArray[i] = 'm';
  3329. break;
  3330. case 's':
  3331. optionsArray[i] = 'g';
  3332. break;
  3333. case 'i':
  3334. optionsArray[i] = 'i';
  3335. break;
  3336. }
  3337. }
  3338. value = new RegExp(source, optionsArray.join(''));
  3339. }
  3340. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
  3341. i = index;
  3342. while (buffer[i] !== 0x00 && i < buffer.length) {
  3343. i++;
  3344. }
  3345. if (i >= buffer.length)
  3346. throw new BSONError('Bad BSON Document: illegal CString');
  3347. const source = ByteUtils.toUTF8(buffer, index, i, false);
  3348. index = i + 1;
  3349. i = index;
  3350. while (buffer[i] !== 0x00 && i < buffer.length) {
  3351. i++;
  3352. }
  3353. if (i >= buffer.length)
  3354. throw new BSONError('Bad BSON Document: illegal CString');
  3355. const regExpOptions = ByteUtils.toUTF8(buffer, index, i, false);
  3356. index = i + 1;
  3357. value = new BSONRegExp(source, regExpOptions);
  3358. }
  3359. else if (elementType === BSON_DATA_SYMBOL) {
  3360. const stringSize = NumberUtils.getInt32LE(buffer, index);
  3361. index += 4;
  3362. if (stringSize <= 0 ||
  3363. stringSize > buffer.length - index ||
  3364. buffer[index + stringSize - 1] !== 0) {
  3365. throw new BSONError('bad string length in bson');
  3366. }
  3367. const symbol = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
  3368. value = promoteValues ? symbol : new BSONSymbol(symbol);
  3369. index = index + stringSize;
  3370. }
  3371. else if (elementType === BSON_DATA_TIMESTAMP) {
  3372. value = new Timestamp({
  3373. i: NumberUtils.getUint32LE(buffer, index),
  3374. t: NumberUtils.getUint32LE(buffer, index + 4)
  3375. });
  3376. index += 8;
  3377. }
  3378. else if (elementType === BSON_DATA_MIN_KEY) {
  3379. value = new MinKey();
  3380. }
  3381. else if (elementType === BSON_DATA_MAX_KEY) {
  3382. value = new MaxKey();
  3383. }
  3384. else if (elementType === BSON_DATA_CODE) {
  3385. const stringSize = NumberUtils.getInt32LE(buffer, index);
  3386. index += 4;
  3387. if (stringSize <= 0 ||
  3388. stringSize > buffer.length - index ||
  3389. buffer[index + stringSize - 1] !== 0) {
  3390. throw new BSONError('bad string length in bson');
  3391. }
  3392. const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
  3393. value = new Code(functionString);
  3394. index = index + stringSize;
  3395. }
  3396. else if (elementType === BSON_DATA_CODE_W_SCOPE) {
  3397. const totalSize = NumberUtils.getInt32LE(buffer, index);
  3398. index += 4;
  3399. if (totalSize < 4 + 4 + 4 + 1) {
  3400. throw new BSONError('code_w_scope total size shorter minimum expected length');
  3401. }
  3402. const stringSize = NumberUtils.getInt32LE(buffer, index);
  3403. index += 4;
  3404. if (stringSize <= 0 ||
  3405. stringSize > buffer.length - index ||
  3406. buffer[index + stringSize - 1] !== 0) {
  3407. throw new BSONError('bad string length in bson');
  3408. }
  3409. const functionString = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
  3410. index = index + stringSize;
  3411. const _index = index;
  3412. const objectSize = NumberUtils.getInt32LE(buffer, index);
  3413. const scopeObject = deserializeObject(buffer, _index, options, false);
  3414. index = index + objectSize;
  3415. if (totalSize < 4 + 4 + objectSize + stringSize) {
  3416. throw new BSONError('code_w_scope total size is too short, truncating scope');
  3417. }
  3418. if (totalSize > 4 + 4 + objectSize + stringSize) {
  3419. throw new BSONError('code_w_scope total size is too long, clips outer document');
  3420. }
  3421. value = new Code(functionString, scopeObject);
  3422. }
  3423. else if (elementType === BSON_DATA_DBPOINTER) {
  3424. const stringSize = NumberUtils.getInt32LE(buffer, index);
  3425. index += 4;
  3426. if (stringSize <= 0 ||
  3427. stringSize > buffer.length - index ||
  3428. buffer[index + stringSize - 1] !== 0)
  3429. throw new BSONError('bad string length in bson');
  3430. const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1, shouldValidateKey);
  3431. index = index + stringSize;
  3432. const oidBuffer = ByteUtils.allocateUnsafe(12);
  3433. for (let i = 0; i < 12; i++)
  3434. oidBuffer[i] = buffer[index + i];
  3435. const oid = new ObjectId(oidBuffer);
  3436. index = index + 12;
  3437. value = new DBRef(namespace, oid);
  3438. }
  3439. else {
  3440. throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
  3441. }
  3442. if (name === '__proto__') {
  3443. Object.defineProperty(object, name, {
  3444. value,
  3445. writable: true,
  3446. enumerable: true,
  3447. configurable: true
  3448. });
  3449. }
  3450. else {
  3451. object[name] = value;
  3452. }
  3453. }
  3454. if (size !== index - startIndex) {
  3455. if (isArray)
  3456. throw new BSONError('corrupt array bson');
  3457. throw new BSONError('corrupt object bson');
  3458. }
  3459. if (!isPossibleDBRef)
  3460. return object;
  3461. if (isDBRefLike(object)) {
  3462. const copy = Object.assign({}, object);
  3463. delete copy.$ref;
  3464. delete copy.$id;
  3465. delete copy.$db;
  3466. return new DBRef(object.$ref, object.$id, object.$db, copy);
  3467. }
  3468. return object;
  3469. }
  3470. const regexp = /\x00/;
  3471. const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
  3472. function serializeString(buffer, key, value, index) {
  3473. buffer[index++] = BSON_DATA_STRING;
  3474. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3475. index = index + numberOfWrittenBytes + 1;
  3476. buffer[index - 1] = 0;
  3477. const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
  3478. NumberUtils.setInt32LE(buffer, index, size + 1);
  3479. index = index + 4 + size;
  3480. buffer[index++] = 0;
  3481. return index;
  3482. }
  3483. function serializeNumber(buffer, key, value, index) {
  3484. const isNegativeZero = Object.is(value, -0);
  3485. const type = !isNegativeZero &&
  3486. Number.isSafeInteger(value) &&
  3487. value <= BSON_INT32_MAX &&
  3488. value >= BSON_INT32_MIN
  3489. ? BSON_DATA_INT
  3490. : BSON_DATA_NUMBER;
  3491. buffer[index++] = type;
  3492. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3493. index = index + numberOfWrittenBytes;
  3494. buffer[index++] = 0x00;
  3495. if (type === BSON_DATA_INT) {
  3496. index += NumberUtils.setInt32LE(buffer, index, value);
  3497. }
  3498. else {
  3499. index += NumberUtils.setFloat64LE(buffer, index, value);
  3500. }
  3501. return index;
  3502. }
  3503. function serializeBigInt(buffer, key, value, index) {
  3504. buffer[index++] = BSON_DATA_LONG;
  3505. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3506. index += numberOfWrittenBytes;
  3507. buffer[index++] = 0;
  3508. index += NumberUtils.setBigInt64LE(buffer, index, value);
  3509. return index;
  3510. }
  3511. function serializeNull(buffer, key, _, index) {
  3512. buffer[index++] = BSON_DATA_NULL;
  3513. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3514. index = index + numberOfWrittenBytes;
  3515. buffer[index++] = 0;
  3516. return index;
  3517. }
  3518. function serializeBoolean(buffer, key, value, index) {
  3519. buffer[index++] = BSON_DATA_BOOLEAN;
  3520. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3521. index = index + numberOfWrittenBytes;
  3522. buffer[index++] = 0;
  3523. buffer[index++] = value ? 1 : 0;
  3524. return index;
  3525. }
  3526. function serializeDate(buffer, key, value, index) {
  3527. buffer[index++] = BSON_DATA_DATE;
  3528. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3529. index = index + numberOfWrittenBytes;
  3530. buffer[index++] = 0;
  3531. const dateInMilis = Long.fromNumber(value.getTime());
  3532. const lowBits = dateInMilis.getLowBits();
  3533. const highBits = dateInMilis.getHighBits();
  3534. index += NumberUtils.setInt32LE(buffer, index, lowBits);
  3535. index += NumberUtils.setInt32LE(buffer, index, highBits);
  3536. return index;
  3537. }
  3538. function serializeRegExp(buffer, key, value, index) {
  3539. buffer[index++] = BSON_DATA_REGEXP;
  3540. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3541. index = index + numberOfWrittenBytes;
  3542. buffer[index++] = 0;
  3543. if (value.source && value.source.match(regexp) != null) {
  3544. throw new BSONError('value ' + value.source + ' must not contain null bytes');
  3545. }
  3546. index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
  3547. buffer[index++] = 0x00;
  3548. if (value.ignoreCase)
  3549. buffer[index++] = 0x69;
  3550. if (value.global)
  3551. buffer[index++] = 0x73;
  3552. if (value.multiline)
  3553. buffer[index++] = 0x6d;
  3554. buffer[index++] = 0x00;
  3555. return index;
  3556. }
  3557. function serializeBSONRegExp(buffer, key, value, index) {
  3558. buffer[index++] = BSON_DATA_REGEXP;
  3559. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3560. index = index + numberOfWrittenBytes;
  3561. buffer[index++] = 0;
  3562. if (value.pattern.match(regexp) != null) {
  3563. throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
  3564. }
  3565. index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
  3566. buffer[index++] = 0x00;
  3567. const sortedOptions = value.options.split('').sort().join('');
  3568. index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
  3569. buffer[index++] = 0x00;
  3570. return index;
  3571. }
  3572. function serializeMinMax(buffer, key, value, index) {
  3573. if (value === null) {
  3574. buffer[index++] = BSON_DATA_NULL;
  3575. }
  3576. else if (value._bsontype === 'MinKey') {
  3577. buffer[index++] = BSON_DATA_MIN_KEY;
  3578. }
  3579. else {
  3580. buffer[index++] = BSON_DATA_MAX_KEY;
  3581. }
  3582. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3583. index = index + numberOfWrittenBytes;
  3584. buffer[index++] = 0;
  3585. return index;
  3586. }
  3587. function serializeObjectId(buffer, key, value, index) {
  3588. buffer[index++] = BSON_DATA_OID;
  3589. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3590. index = index + numberOfWrittenBytes;
  3591. buffer[index++] = 0;
  3592. index += value.serializeInto(buffer, index);
  3593. return index;
  3594. }
  3595. function serializeBuffer(buffer, key, value, index) {
  3596. buffer[index++] = BSON_DATA_BINARY;
  3597. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3598. index = index + numberOfWrittenBytes;
  3599. buffer[index++] = 0;
  3600. const size = value.length;
  3601. index += NumberUtils.setInt32LE(buffer, index, size);
  3602. buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
  3603. if (size <= 16) {
  3604. for (let i = 0; i < size; i++)
  3605. buffer[index + i] = value[i];
  3606. }
  3607. else {
  3608. buffer.set(value, index);
  3609. }
  3610. index = index + size;
  3611. return index;
  3612. }
  3613. function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
  3614. if (path.has(value)) {
  3615. throw new BSONError('Cannot convert circular structure to BSON');
  3616. }
  3617. path.add(value);
  3618. buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
  3619. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3620. index = index + numberOfWrittenBytes;
  3621. buffer[index++] = 0;
  3622. const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  3623. path.delete(value);
  3624. return endIndex;
  3625. }
  3626. function serializeDecimal128(buffer, key, value, index) {
  3627. buffer[index++] = BSON_DATA_DECIMAL128;
  3628. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3629. index = index + numberOfWrittenBytes;
  3630. buffer[index++] = 0;
  3631. for (let i = 0; i < 16; i++)
  3632. buffer[index + i] = value.bytes[i];
  3633. return index + 16;
  3634. }
  3635. function serializeLong(buffer, key, value, index) {
  3636. buffer[index++] =
  3637. value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
  3638. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3639. index = index + numberOfWrittenBytes;
  3640. buffer[index++] = 0;
  3641. const lowBits = value.getLowBits();
  3642. const highBits = value.getHighBits();
  3643. index += NumberUtils.setInt32LE(buffer, index, lowBits);
  3644. index += NumberUtils.setInt32LE(buffer, index, highBits);
  3645. return index;
  3646. }
  3647. function serializeInt32(buffer, key, value, index) {
  3648. value = value.valueOf();
  3649. buffer[index++] = BSON_DATA_INT;
  3650. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3651. index = index + numberOfWrittenBytes;
  3652. buffer[index++] = 0;
  3653. index += NumberUtils.setInt32LE(buffer, index, value);
  3654. return index;
  3655. }
  3656. function serializeDouble(buffer, key, value, index) {
  3657. buffer[index++] = BSON_DATA_NUMBER;
  3658. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3659. index = index + numberOfWrittenBytes;
  3660. buffer[index++] = 0;
  3661. index += NumberUtils.setFloat64LE(buffer, index, value.value);
  3662. return index;
  3663. }
  3664. function serializeFunction(buffer, key, value, index) {
  3665. buffer[index++] = BSON_DATA_CODE;
  3666. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3667. index = index + numberOfWrittenBytes;
  3668. buffer[index++] = 0;
  3669. const functionString = value.toString();
  3670. const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
  3671. NumberUtils.setInt32LE(buffer, index, size);
  3672. index = index + 4 + size - 1;
  3673. buffer[index++] = 0;
  3674. return index;
  3675. }
  3676. function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
  3677. if (value.scope && typeof value.scope === 'object') {
  3678. buffer[index++] = BSON_DATA_CODE_W_SCOPE;
  3679. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3680. index = index + numberOfWrittenBytes;
  3681. buffer[index++] = 0;
  3682. let startIndex = index;
  3683. const functionString = value.code;
  3684. index = index + 4;
  3685. const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
  3686. NumberUtils.setInt32LE(buffer, index, codeSize);
  3687. buffer[index + 4 + codeSize - 1] = 0;
  3688. index = index + codeSize + 4;
  3689. const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  3690. index = endIndex - 1;
  3691. const totalSize = endIndex - startIndex;
  3692. startIndex += NumberUtils.setInt32LE(buffer, startIndex, totalSize);
  3693. buffer[index++] = 0;
  3694. }
  3695. else {
  3696. buffer[index++] = BSON_DATA_CODE;
  3697. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3698. index = index + numberOfWrittenBytes;
  3699. buffer[index++] = 0;
  3700. const functionString = value.code.toString();
  3701. const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
  3702. NumberUtils.setInt32LE(buffer, index, size);
  3703. index = index + 4 + size - 1;
  3704. buffer[index++] = 0;
  3705. }
  3706. return index;
  3707. }
  3708. function serializeBinary(buffer, key, value, index) {
  3709. buffer[index++] = BSON_DATA_BINARY;
  3710. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3711. index = index + numberOfWrittenBytes;
  3712. buffer[index++] = 0;
  3713. const data = value.buffer;
  3714. let size = value.position;
  3715. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
  3716. size = size + 4;
  3717. index += NumberUtils.setInt32LE(buffer, index, size);
  3718. buffer[index++] = value.sub_type;
  3719. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  3720. size = size - 4;
  3721. index += NumberUtils.setInt32LE(buffer, index, size);
  3722. }
  3723. if (value.sub_type === Binary.SUBTYPE_VECTOR) {
  3724. validateBinaryVector(value);
  3725. }
  3726. if (size <= 16) {
  3727. for (let i = 0; i < size; i++)
  3728. buffer[index + i] = data[i];
  3729. }
  3730. else {
  3731. buffer.set(data, index);
  3732. }
  3733. index = index + value.position;
  3734. return index;
  3735. }
  3736. function serializeSymbol(buffer, key, value, index) {
  3737. buffer[index++] = BSON_DATA_SYMBOL;
  3738. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3739. index = index + numberOfWrittenBytes;
  3740. buffer[index++] = 0;
  3741. const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
  3742. NumberUtils.setInt32LE(buffer, index, size);
  3743. index = index + 4 + size - 1;
  3744. buffer[index++] = 0;
  3745. return index;
  3746. }
  3747. function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) {
  3748. buffer[index++] = BSON_DATA_OBJECT;
  3749. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3750. index = index + numberOfWrittenBytes;
  3751. buffer[index++] = 0;
  3752. let startIndex = index;
  3753. let output = {
  3754. $ref: value.collection || value.namespace,
  3755. $id: value.oid
  3756. };
  3757. if (value.db != null) {
  3758. output.$db = value.db;
  3759. }
  3760. output = Object.assign(output, value.fields);
  3761. const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path);
  3762. const size = endIndex - startIndex;
  3763. startIndex += NumberUtils.setInt32LE(buffer, index, size);
  3764. return endIndex;
  3765. }
  3766. function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  3767. if (path == null) {
  3768. if (object == null) {
  3769. buffer[0] = 0x05;
  3770. buffer[1] = 0x00;
  3771. buffer[2] = 0x00;
  3772. buffer[3] = 0x00;
  3773. buffer[4] = 0x00;
  3774. return 5;
  3775. }
  3776. if (Array.isArray(object)) {
  3777. throw new BSONError('serialize does not support an array as the root input');
  3778. }
  3779. if (typeof object !== 'object') {
  3780. throw new BSONError('serialize does not support non-object as the root input');
  3781. }
  3782. else if ('_bsontype' in object && typeof object._bsontype === 'string') {
  3783. throw new BSONError(`BSON types cannot be serialized as a document`);
  3784. }
  3785. else if (isDate(object) ||
  3786. isRegExp(object) ||
  3787. isUint8Array(object) ||
  3788. isAnyArrayBuffer(object)) {
  3789. throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
  3790. }
  3791. path = new Set();
  3792. }
  3793. path.add(object);
  3794. let index = startingIndex + 4;
  3795. if (Array.isArray(object)) {
  3796. for (let i = 0; i < object.length; i++) {
  3797. const key = `${i}`;
  3798. let value = object[i];
  3799. if (typeof value?.toBSON === 'function') {
  3800. value = value.toBSON();
  3801. }
  3802. const type = typeof value;
  3803. if (value === undefined) {
  3804. index = serializeNull(buffer, key, value, index);
  3805. }
  3806. else if (value === null) {
  3807. index = serializeNull(buffer, key, value, index);
  3808. }
  3809. else if (type === 'string') {
  3810. index = serializeString(buffer, key, value, index);
  3811. }
  3812. else if (type === 'number') {
  3813. index = serializeNumber(buffer, key, value, index);
  3814. }
  3815. else if (type === 'bigint') {
  3816. index = serializeBigInt(buffer, key, value, index);
  3817. }
  3818. else if (type === 'boolean') {
  3819. index = serializeBoolean(buffer, key, value, index);
  3820. }
  3821. else if (type === 'object' && value._bsontype == null) {
  3822. if (value instanceof Date || isDate(value)) {
  3823. index = serializeDate(buffer, key, value, index);
  3824. }
  3825. else if (value instanceof Uint8Array || isUint8Array(value)) {
  3826. index = serializeBuffer(buffer, key, value, index);
  3827. }
  3828. else if (value instanceof RegExp || isRegExp(value)) {
  3829. index = serializeRegExp(buffer, key, value, index);
  3830. }
  3831. else {
  3832. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3833. }
  3834. }
  3835. else if (type === 'object') {
  3836. if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
  3837. throw new BSONVersionError();
  3838. }
  3839. else if (value._bsontype === 'ObjectId') {
  3840. index = serializeObjectId(buffer, key, value, index);
  3841. }
  3842. else if (value._bsontype === 'Decimal128') {
  3843. index = serializeDecimal128(buffer, key, value, index);
  3844. }
  3845. else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
  3846. index = serializeLong(buffer, key, value, index);
  3847. }
  3848. else if (value._bsontype === 'Double') {
  3849. index = serializeDouble(buffer, key, value, index);
  3850. }
  3851. else if (value._bsontype === 'Code') {
  3852. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3853. }
  3854. else if (value._bsontype === 'Binary') {
  3855. index = serializeBinary(buffer, key, value, index);
  3856. }
  3857. else if (value._bsontype === 'BSONSymbol') {
  3858. index = serializeSymbol(buffer, key, value, index);
  3859. }
  3860. else if (value._bsontype === 'DBRef') {
  3861. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
  3862. }
  3863. else if (value._bsontype === 'BSONRegExp') {
  3864. index = serializeBSONRegExp(buffer, key, value, index);
  3865. }
  3866. else if (value._bsontype === 'Int32') {
  3867. index = serializeInt32(buffer, key, value, index);
  3868. }
  3869. else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  3870. index = serializeMinMax(buffer, key, value, index);
  3871. }
  3872. else if (typeof value._bsontype !== 'undefined') {
  3873. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  3874. }
  3875. }
  3876. else if (type === 'function' && serializeFunctions) {
  3877. index = serializeFunction(buffer, key, value, index);
  3878. }
  3879. }
  3880. }
  3881. else if (object instanceof Map || isMap(object)) {
  3882. const iterator = object.entries();
  3883. let done = false;
  3884. while (!done) {
  3885. const entry = iterator.next();
  3886. done = !!entry.done;
  3887. if (done)
  3888. continue;
  3889. const key = entry.value ? entry.value[0] : undefined;
  3890. let value = entry.value ? entry.value[1] : undefined;
  3891. if (typeof value?.toBSON === 'function') {
  3892. value = value.toBSON();
  3893. }
  3894. const type = typeof value;
  3895. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  3896. if (key.match(regexp) != null) {
  3897. throw new BSONError('key ' + key + ' must not contain null bytes');
  3898. }
  3899. if (checkKeys) {
  3900. if ('$' === key[0]) {
  3901. throw new BSONError('key ' + key + " must not start with '$'");
  3902. }
  3903. else if (key.includes('.')) {
  3904. throw new BSONError('key ' + key + " must not contain '.'");
  3905. }
  3906. }
  3907. }
  3908. if (value === undefined) {
  3909. if (ignoreUndefined === false)
  3910. index = serializeNull(buffer, key, value, index);
  3911. }
  3912. else if (value === null) {
  3913. index = serializeNull(buffer, key, value, index);
  3914. }
  3915. else if (type === 'string') {
  3916. index = serializeString(buffer, key, value, index);
  3917. }
  3918. else if (type === 'number') {
  3919. index = serializeNumber(buffer, key, value, index);
  3920. }
  3921. else if (type === 'bigint') {
  3922. index = serializeBigInt(buffer, key, value, index);
  3923. }
  3924. else if (type === 'boolean') {
  3925. index = serializeBoolean(buffer, key, value, index);
  3926. }
  3927. else if (type === 'object' && value._bsontype == null) {
  3928. if (value instanceof Date || isDate(value)) {
  3929. index = serializeDate(buffer, key, value, index);
  3930. }
  3931. else if (value instanceof Uint8Array || isUint8Array(value)) {
  3932. index = serializeBuffer(buffer, key, value, index);
  3933. }
  3934. else if (value instanceof RegExp || isRegExp(value)) {
  3935. index = serializeRegExp(buffer, key, value, index);
  3936. }
  3937. else {
  3938. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3939. }
  3940. }
  3941. else if (type === 'object') {
  3942. if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
  3943. throw new BSONVersionError();
  3944. }
  3945. else if (value._bsontype === 'ObjectId') {
  3946. index = serializeObjectId(buffer, key, value, index);
  3947. }
  3948. else if (value._bsontype === 'Decimal128') {
  3949. index = serializeDecimal128(buffer, key, value, index);
  3950. }
  3951. else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
  3952. index = serializeLong(buffer, key, value, index);
  3953. }
  3954. else if (value._bsontype === 'Double') {
  3955. index = serializeDouble(buffer, key, value, index);
  3956. }
  3957. else if (value._bsontype === 'Code') {
  3958. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3959. }
  3960. else if (value._bsontype === 'Binary') {
  3961. index = serializeBinary(buffer, key, value, index);
  3962. }
  3963. else if (value._bsontype === 'BSONSymbol') {
  3964. index = serializeSymbol(buffer, key, value, index);
  3965. }
  3966. else if (value._bsontype === 'DBRef') {
  3967. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
  3968. }
  3969. else if (value._bsontype === 'BSONRegExp') {
  3970. index = serializeBSONRegExp(buffer, key, value, index);
  3971. }
  3972. else if (value._bsontype === 'Int32') {
  3973. index = serializeInt32(buffer, key, value, index);
  3974. }
  3975. else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  3976. index = serializeMinMax(buffer, key, value, index);
  3977. }
  3978. else if (typeof value._bsontype !== 'undefined') {
  3979. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  3980. }
  3981. }
  3982. else if (type === 'function' && serializeFunctions) {
  3983. index = serializeFunction(buffer, key, value, index);
  3984. }
  3985. }
  3986. }
  3987. else {
  3988. if (typeof object?.toBSON === 'function') {
  3989. object = object.toBSON();
  3990. if (object != null && typeof object !== 'object') {
  3991. throw new BSONError('toBSON function did not return an object');
  3992. }
  3993. }
  3994. for (const key of Object.keys(object)) {
  3995. let value = object[key];
  3996. if (typeof value?.toBSON === 'function') {
  3997. value = value.toBSON();
  3998. }
  3999. const type = typeof value;
  4000. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  4001. if (key.match(regexp) != null) {
  4002. throw new BSONError('key ' + key + ' must not contain null bytes');
  4003. }
  4004. if (checkKeys) {
  4005. if ('$' === key[0]) {
  4006. throw new BSONError('key ' + key + " must not start with '$'");
  4007. }
  4008. else if (key.includes('.')) {
  4009. throw new BSONError('key ' + key + " must not contain '.'");
  4010. }
  4011. }
  4012. }
  4013. if (value === undefined) {
  4014. if (ignoreUndefined === false)
  4015. index = serializeNull(buffer, key, value, index);
  4016. }
  4017. else if (value === null) {
  4018. index = serializeNull(buffer, key, value, index);
  4019. }
  4020. else if (type === 'string') {
  4021. index = serializeString(buffer, key, value, index);
  4022. }
  4023. else if (type === 'number') {
  4024. index = serializeNumber(buffer, key, value, index);
  4025. }
  4026. else if (type === 'bigint') {
  4027. index = serializeBigInt(buffer, key, value, index);
  4028. }
  4029. else if (type === 'boolean') {
  4030. index = serializeBoolean(buffer, key, value, index);
  4031. }
  4032. else if (type === 'object' && value._bsontype == null) {
  4033. if (value instanceof Date || isDate(value)) {
  4034. index = serializeDate(buffer, key, value, index);
  4035. }
  4036. else if (value instanceof Uint8Array || isUint8Array(value)) {
  4037. index = serializeBuffer(buffer, key, value, index);
  4038. }
  4039. else if (value instanceof RegExp || isRegExp(value)) {
  4040. index = serializeRegExp(buffer, key, value, index);
  4041. }
  4042. else {
  4043. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  4044. }
  4045. }
  4046. else if (type === 'object') {
  4047. if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
  4048. throw new BSONVersionError();
  4049. }
  4050. else if (value._bsontype === 'ObjectId') {
  4051. index = serializeObjectId(buffer, key, value, index);
  4052. }
  4053. else if (value._bsontype === 'Decimal128') {
  4054. index = serializeDecimal128(buffer, key, value, index);
  4055. }
  4056. else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
  4057. index = serializeLong(buffer, key, value, index);
  4058. }
  4059. else if (value._bsontype === 'Double') {
  4060. index = serializeDouble(buffer, key, value, index);
  4061. }
  4062. else if (value._bsontype === 'Code') {
  4063. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  4064. }
  4065. else if (value._bsontype === 'Binary') {
  4066. index = serializeBinary(buffer, key, value, index);
  4067. }
  4068. else if (value._bsontype === 'BSONSymbol') {
  4069. index = serializeSymbol(buffer, key, value, index);
  4070. }
  4071. else if (value._bsontype === 'DBRef') {
  4072. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
  4073. }
  4074. else if (value._bsontype === 'BSONRegExp') {
  4075. index = serializeBSONRegExp(buffer, key, value, index);
  4076. }
  4077. else if (value._bsontype === 'Int32') {
  4078. index = serializeInt32(buffer, key, value, index);
  4079. }
  4080. else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  4081. index = serializeMinMax(buffer, key, value, index);
  4082. }
  4083. else if (typeof value._bsontype !== 'undefined') {
  4084. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  4085. }
  4086. }
  4087. else if (type === 'function' && serializeFunctions) {
  4088. index = serializeFunction(buffer, key, value, index);
  4089. }
  4090. }
  4091. }
  4092. path.delete(object);
  4093. buffer[index++] = 0x00;
  4094. const size = index - startingIndex;
  4095. startingIndex += NumberUtils.setInt32LE(buffer, startingIndex, size);
  4096. return index;
  4097. }
  4098. function isBSONType(value) {
  4099. return (value != null &&
  4100. typeof value === 'object' &&
  4101. '_bsontype' in value &&
  4102. typeof value._bsontype === 'string');
  4103. }
  4104. const keysToCodecs = {
  4105. $oid: ObjectId,
  4106. $binary: Binary,
  4107. $uuid: Binary,
  4108. $symbol: BSONSymbol,
  4109. $numberInt: Int32,
  4110. $numberDecimal: Decimal128,
  4111. $numberDouble: Double,
  4112. $numberLong: Long,
  4113. $minKey: MinKey,
  4114. $maxKey: MaxKey,
  4115. $regex: BSONRegExp,
  4116. $regularExpression: BSONRegExp,
  4117. $timestamp: Timestamp
  4118. };
  4119. function deserializeValue(value, options = {}) {
  4120. if (typeof value === 'number') {
  4121. const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
  4122. const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
  4123. if (options.relaxed || options.legacy) {
  4124. return value;
  4125. }
  4126. if (Number.isInteger(value) && !Object.is(value, -0)) {
  4127. if (in32BitRange) {
  4128. return new Int32(value);
  4129. }
  4130. if (in64BitRange) {
  4131. if (options.useBigInt64) {
  4132. return BigInt(value);
  4133. }
  4134. return Long.fromNumber(value);
  4135. }
  4136. }
  4137. return new Double(value);
  4138. }
  4139. if (value == null || typeof value !== 'object')
  4140. return value;
  4141. if (value.$undefined)
  4142. return null;
  4143. const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null);
  4144. for (let i = 0; i < keys.length; i++) {
  4145. const c = keysToCodecs[keys[i]];
  4146. if (c)
  4147. return c.fromExtendedJSON(value, options);
  4148. }
  4149. if (value.$date != null) {
  4150. const d = value.$date;
  4151. const date = new Date();
  4152. if (options.legacy) {
  4153. if (typeof d === 'number')
  4154. date.setTime(d);
  4155. else if (typeof d === 'string')
  4156. date.setTime(Date.parse(d));
  4157. else if (typeof d === 'bigint')
  4158. date.setTime(Number(d));
  4159. else
  4160. throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
  4161. }
  4162. else {
  4163. if (typeof d === 'string')
  4164. date.setTime(Date.parse(d));
  4165. else if (Long.isLong(d))
  4166. date.setTime(d.toNumber());
  4167. else if (typeof d === 'number' && options.relaxed)
  4168. date.setTime(d);
  4169. else if (typeof d === 'bigint')
  4170. date.setTime(Number(d));
  4171. else
  4172. throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
  4173. }
  4174. return date;
  4175. }
  4176. if (value.$code != null) {
  4177. const copy = Object.assign({}, value);
  4178. if (value.$scope) {
  4179. copy.$scope = deserializeValue(value.$scope);
  4180. }
  4181. return Code.fromExtendedJSON(value);
  4182. }
  4183. if (isDBRefLike(value) || value.$dbPointer) {
  4184. const v = value.$ref ? value : value.$dbPointer;
  4185. if (v instanceof DBRef)
  4186. return v;
  4187. const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
  4188. let valid = true;
  4189. dollarKeys.forEach(k => {
  4190. if (['$ref', '$id', '$db'].indexOf(k) === -1)
  4191. valid = false;
  4192. });
  4193. if (valid)
  4194. return DBRef.fromExtendedJSON(v);
  4195. }
  4196. return value;
  4197. }
  4198. function serializeArray(array, options) {
  4199. return array.map((v, index) => {
  4200. options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
  4201. try {
  4202. return serializeValue(v, options);
  4203. }
  4204. finally {
  4205. options.seenObjects.pop();
  4206. }
  4207. });
  4208. }
  4209. function getISOString(date) {
  4210. const isoStr = date.toISOString();
  4211. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  4212. }
  4213. function serializeValue(value, options) {
  4214. if (value instanceof Map || isMap(value)) {
  4215. const obj = Object.create(null);
  4216. for (const [k, v] of value) {
  4217. if (typeof k !== 'string') {
  4218. throw new BSONError('Can only serialize maps with string keys');
  4219. }
  4220. obj[k] = v;
  4221. }
  4222. return serializeValue(obj, options);
  4223. }
  4224. if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
  4225. const index = options.seenObjects.findIndex(entry => entry.obj === value);
  4226. if (index !== -1) {
  4227. const props = options.seenObjects.map(entry => entry.propertyName);
  4228. const leadingPart = props
  4229. .slice(0, index)
  4230. .map(prop => `${prop} -> `)
  4231. .join('');
  4232. const alreadySeen = props[index];
  4233. const circularPart = ' -> ' +
  4234. props
  4235. .slice(index + 1, props.length - 1)
  4236. .map(prop => `${prop} -> `)
  4237. .join('');
  4238. const current = props[props.length - 1];
  4239. const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
  4240. const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
  4241. throw new BSONError('Converting circular structure to EJSON:\n' +
  4242. ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
  4243. ` ${leadingSpace}\\${dashes}/`);
  4244. }
  4245. options.seenObjects[options.seenObjects.length - 1].obj = value;
  4246. }
  4247. if (Array.isArray(value))
  4248. return serializeArray(value, options);
  4249. if (value === undefined)
  4250. return null;
  4251. if (value instanceof Date || isDate(value)) {
  4252. const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000;
  4253. if (options.legacy) {
  4254. return options.relaxed && inRange
  4255. ? { $date: value.getTime() }
  4256. : { $date: getISOString(value) };
  4257. }
  4258. return options.relaxed && inRange
  4259. ? { $date: getISOString(value) }
  4260. : { $date: { $numberLong: value.getTime().toString() } };
  4261. }
  4262. if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
  4263. if (Number.isInteger(value) && !Object.is(value, -0)) {
  4264. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  4265. return { $numberInt: value.toString() };
  4266. }
  4267. if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
  4268. return { $numberLong: value.toString() };
  4269. }
  4270. }
  4271. return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
  4272. }
  4273. if (typeof value === 'bigint') {
  4274. if (!options.relaxed) {
  4275. return { $numberLong: BigInt.asIntN(64, value).toString() };
  4276. }
  4277. return Number(BigInt.asIntN(64, value));
  4278. }
  4279. if (value instanceof RegExp || isRegExp(value)) {
  4280. let flags = value.flags;
  4281. if (flags === undefined) {
  4282. const match = value.toString().match(/[gimuy]*$/);
  4283. if (match) {
  4284. flags = match[0];
  4285. }
  4286. }
  4287. const rx = new BSONRegExp(value.source, flags);
  4288. return rx.toExtendedJSON(options);
  4289. }
  4290. if (value != null && typeof value === 'object')
  4291. return serializeDocument(value, options);
  4292. return value;
  4293. }
  4294. const BSON_TYPE_MAPPINGS = {
  4295. Binary: (o) => new Binary(o.value(), o.sub_type),
  4296. Code: (o) => new Code(o.code, o.scope),
  4297. DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
  4298. Decimal128: (o) => new Decimal128(o.bytes),
  4299. Double: (o) => new Double(o.value),
  4300. Int32: (o) => new Int32(o.value),
  4301. 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_),
  4302. MaxKey: () => new MaxKey(),
  4303. MinKey: () => new MinKey(),
  4304. ObjectId: (o) => new ObjectId(o),
  4305. BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
  4306. BSONSymbol: (o) => new BSONSymbol(o.value),
  4307. Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
  4308. };
  4309. function serializeDocument(doc, options) {
  4310. if (doc == null || typeof doc !== 'object')
  4311. throw new BSONError('not an object instance');
  4312. const bsontype = doc._bsontype;
  4313. if (typeof bsontype === 'undefined') {
  4314. const _doc = {};
  4315. for (const name of Object.keys(doc)) {
  4316. options.seenObjects.push({ propertyName: name, obj: null });
  4317. try {
  4318. const value = serializeValue(doc[name], options);
  4319. if (name === '__proto__') {
  4320. Object.defineProperty(_doc, name, {
  4321. value,
  4322. writable: true,
  4323. enumerable: true,
  4324. configurable: true
  4325. });
  4326. }
  4327. else {
  4328. _doc[name] = value;
  4329. }
  4330. }
  4331. finally {
  4332. options.seenObjects.pop();
  4333. }
  4334. }
  4335. return _doc;
  4336. }
  4337. else if (doc != null &&
  4338. typeof doc === 'object' &&
  4339. typeof doc._bsontype === 'string' &&
  4340. doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
  4341. throw new BSONVersionError();
  4342. }
  4343. else if (isBSONType(doc)) {
  4344. let outDoc = doc;
  4345. if (typeof outDoc.toExtendedJSON !== 'function') {
  4346. const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
  4347. if (!mapper) {
  4348. throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
  4349. }
  4350. outDoc = mapper(outDoc);
  4351. }
  4352. if (bsontype === 'Code' && outDoc.scope) {
  4353. outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
  4354. }
  4355. else if (bsontype === 'DBRef' && outDoc.oid) {
  4356. outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
  4357. }
  4358. return outDoc.toExtendedJSON(options);
  4359. }
  4360. else {
  4361. throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
  4362. }
  4363. }
  4364. function parse(text, options) {
  4365. const ejsonOptions = {
  4366. useBigInt64: options?.useBigInt64 ?? false,
  4367. relaxed: options?.relaxed ?? true,
  4368. legacy: options?.legacy ?? false
  4369. };
  4370. return JSON.parse(text, (key, value) => {
  4371. if (key.indexOf('\x00') !== -1) {
  4372. throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
  4373. }
  4374. return deserializeValue(value, ejsonOptions);
  4375. });
  4376. }
  4377. function stringify(value, replacer, space, options) {
  4378. if (space != null && typeof space === 'object') {
  4379. options = space;
  4380. space = 0;
  4381. }
  4382. if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
  4383. options = replacer;
  4384. replacer = undefined;
  4385. space = 0;
  4386. }
  4387. const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
  4388. seenObjects: [{ propertyName: '(root)', obj: null }]
  4389. });
  4390. const doc = serializeValue(value, serializeOptions);
  4391. return JSON.stringify(doc, replacer, space);
  4392. }
  4393. function EJSONserialize(value, options) {
  4394. options = options || {};
  4395. return JSON.parse(stringify(value, options));
  4396. }
  4397. function EJSONdeserialize(ejson, options) {
  4398. options = options || {};
  4399. return parse(JSON.stringify(ejson), options);
  4400. }
  4401. const EJSON = Object.create(null);
  4402. EJSON.parse = parse;
  4403. EJSON.stringify = stringify;
  4404. EJSON.serialize = EJSONserialize;
  4405. EJSON.deserialize = EJSONdeserialize;
  4406. Object.freeze(EJSON);
  4407. const BSONElementType = {
  4408. double: 1,
  4409. string: 2,
  4410. object: 3,
  4411. array: 4,
  4412. binData: 5,
  4413. undefined: 6,
  4414. objectId: 7,
  4415. bool: 8,
  4416. date: 9,
  4417. null: 10,
  4418. regex: 11,
  4419. dbPointer: 12,
  4420. javascript: 13,
  4421. symbol: 14,
  4422. javascriptWithScope: 15,
  4423. int: 16,
  4424. timestamp: 17,
  4425. long: 18,
  4426. decimal: 19,
  4427. minKey: 255,
  4428. maxKey: 127
  4429. };
  4430. function getSize(source, offset) {
  4431. try {
  4432. return NumberUtils.getNonnegativeInt32LE(source, offset);
  4433. }
  4434. catch (cause) {
  4435. throw new BSONOffsetError('BSON size cannot be negative', offset, { cause });
  4436. }
  4437. }
  4438. function findNull(bytes, offset) {
  4439. let nullTerminatorOffset = offset;
  4440. for (; bytes[nullTerminatorOffset] !== 0x00; nullTerminatorOffset++)
  4441. ;
  4442. if (nullTerminatorOffset === bytes.length - 1) {
  4443. throw new BSONOffsetError('Null terminator not found', offset);
  4444. }
  4445. return nullTerminatorOffset;
  4446. }
  4447. function parseToElements(bytes, startOffset = 0) {
  4448. startOffset ??= 0;
  4449. if (bytes.length < 5) {
  4450. throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
  4451. }
  4452. const documentSize = getSize(bytes, startOffset);
  4453. if (documentSize > bytes.length - startOffset) {
  4454. throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
  4455. }
  4456. if (bytes[startOffset + documentSize - 1] !== 0x00) {
  4457. throw new BSONOffsetError('BSON documents must end in 0x00', startOffset + documentSize);
  4458. }
  4459. const elements = [];
  4460. let offset = startOffset + 4;
  4461. while (offset <= documentSize + startOffset) {
  4462. const type = bytes[offset];
  4463. offset += 1;
  4464. if (type === 0) {
  4465. if (offset - startOffset !== documentSize) {
  4466. throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
  4467. }
  4468. break;
  4469. }
  4470. const nameOffset = offset;
  4471. const nameLength = findNull(bytes, offset) - nameOffset;
  4472. offset += nameLength + 1;
  4473. let length;
  4474. if (type === BSONElementType.double ||
  4475. type === BSONElementType.long ||
  4476. type === BSONElementType.date ||
  4477. type === BSONElementType.timestamp) {
  4478. length = 8;
  4479. }
  4480. else if (type === BSONElementType.int) {
  4481. length = 4;
  4482. }
  4483. else if (type === BSONElementType.objectId) {
  4484. length = 12;
  4485. }
  4486. else if (type === BSONElementType.decimal) {
  4487. length = 16;
  4488. }
  4489. else if (type === BSONElementType.bool) {
  4490. length = 1;
  4491. }
  4492. else if (type === BSONElementType.null ||
  4493. type === BSONElementType.undefined ||
  4494. type === BSONElementType.maxKey ||
  4495. type === BSONElementType.minKey) {
  4496. length = 0;
  4497. }
  4498. else if (type === BSONElementType.regex) {
  4499. length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
  4500. }
  4501. else if (type === BSONElementType.object ||
  4502. type === BSONElementType.array ||
  4503. type === BSONElementType.javascriptWithScope) {
  4504. length = getSize(bytes, offset);
  4505. }
  4506. else if (type === BSONElementType.string ||
  4507. type === BSONElementType.binData ||
  4508. type === BSONElementType.dbPointer ||
  4509. type === BSONElementType.javascript ||
  4510. type === BSONElementType.symbol) {
  4511. length = getSize(bytes, offset) + 4;
  4512. if (type === BSONElementType.binData) {
  4513. length += 1;
  4514. }
  4515. if (type === BSONElementType.dbPointer) {
  4516. length += 12;
  4517. }
  4518. }
  4519. else {
  4520. throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, '0')} type byte`, offset);
  4521. }
  4522. if (length > documentSize) {
  4523. throw new BSONOffsetError('value reports length larger than document', offset);
  4524. }
  4525. elements.push([type, nameOffset, nameLength, offset, length]);
  4526. offset += length;
  4527. }
  4528. return elements;
  4529. }
  4530. const onDemand = Object.create(null);
  4531. onDemand.parseToElements = parseToElements;
  4532. onDemand.ByteUtils = ByteUtils;
  4533. onDemand.NumberUtils = NumberUtils;
  4534. Object.freeze(onDemand);
  4535. const MAXSIZE = 1024 * 1024 * 17;
  4536. let buffer = ByteUtils.allocate(MAXSIZE);
  4537. function setInternalBufferSize(size) {
  4538. if (buffer.length < size) {
  4539. buffer = ByteUtils.allocate(size);
  4540. }
  4541. }
  4542. function serialize(object, options = {}) {
  4543. const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4544. const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4545. const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4546. const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
  4547. if (buffer.length < minInternalBufferSize) {
  4548. buffer = ByteUtils.allocate(minInternalBufferSize);
  4549. }
  4550. const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
  4551. const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex);
  4552. finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
  4553. return finishedBuffer;
  4554. }
  4555. function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
  4556. const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4557. const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4558. const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4559. const startIndex = typeof options.index === 'number' ? options.index : 0;
  4560. const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
  4561. finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
  4562. return startIndex + serializationIndex - 1;
  4563. }
  4564. function deserialize(buffer, options = {}) {
  4565. return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
  4566. }
  4567. function calculateObjectSize(object, options = {}) {
  4568. options = options || {};
  4569. const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4570. const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4571. return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
  4572. }
  4573. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  4574. const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
  4575. const bufferData = ByteUtils.toLocalBufferType(data);
  4576. let index = startIndex;
  4577. for (let i = 0; i < numberOfDocuments; i++) {
  4578. const size = NumberUtils.getInt32LE(bufferData, index);
  4579. internalOptions.index = index;
  4580. documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
  4581. index = index + size;
  4582. }
  4583. return index;
  4584. }
  4585. var bson = /*#__PURE__*/Object.freeze({
  4586. __proto__: null,
  4587. BSONError: BSONError,
  4588. BSONOffsetError: BSONOffsetError,
  4589. BSONRegExp: BSONRegExp,
  4590. BSONRuntimeError: BSONRuntimeError,
  4591. BSONSymbol: BSONSymbol,
  4592. BSONType: BSONType,
  4593. BSONValue: BSONValue,
  4594. BSONVersionError: BSONVersionError,
  4595. Binary: Binary,
  4596. Code: Code,
  4597. DBRef: DBRef,
  4598. Decimal128: Decimal128,
  4599. Double: Double,
  4600. EJSON: EJSON,
  4601. Int32: Int32,
  4602. Long: Long,
  4603. MaxKey: MaxKey,
  4604. MinKey: MinKey,
  4605. ObjectId: ObjectId,
  4606. Timestamp: Timestamp,
  4607. UUID: UUID,
  4608. bsonType: bsonType,
  4609. calculateObjectSize: calculateObjectSize,
  4610. deserialize: deserialize,
  4611. deserializeStream: deserializeStream,
  4612. onDemand: onDemand,
  4613. serialize: serialize,
  4614. serializeWithBufferAndIndex: serializeWithBufferAndIndex,
  4615. setInternalBufferSize: setInternalBufferSize
  4616. });
  4617. exports.BSON = bson;
  4618. exports.BSONError = BSONError;
  4619. exports.BSONOffsetError = BSONOffsetError;
  4620. exports.BSONRegExp = BSONRegExp;
  4621. exports.BSONRuntimeError = BSONRuntimeError;
  4622. exports.BSONSymbol = BSONSymbol;
  4623. exports.BSONType = BSONType;
  4624. exports.BSONValue = BSONValue;
  4625. exports.BSONVersionError = BSONVersionError;
  4626. exports.Binary = Binary;
  4627. exports.Code = Code;
  4628. exports.DBRef = DBRef;
  4629. exports.Decimal128 = Decimal128;
  4630. exports.Double = Double;
  4631. exports.EJSON = EJSON;
  4632. exports.Int32 = Int32;
  4633. exports.Long = Long;
  4634. exports.MaxKey = MaxKey;
  4635. exports.MinKey = MinKey;
  4636. exports.ObjectId = ObjectId;
  4637. exports.Timestamp = Timestamp;
  4638. exports.UUID = UUID;
  4639. exports.bsonType = bsonType;
  4640. exports.calculateObjectSize = calculateObjectSize;
  4641. exports.deserialize = deserialize;
  4642. exports.deserializeStream = deserializeStream;
  4643. exports.onDemand = onDemand;
  4644. exports.serialize = serialize;
  4645. exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
  4646. exports.setInternalBufferSize = setInternalBufferSize;
  4647. //# sourceMappingURL=bson.rn.cjs.map