bson.cjs 174 KB

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