bson.browser.umd.js 281 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.BSON = {}));
  5. }(this, (function (exports) { 'use strict';
  6. function createCommonjsModule(fn, module) {
  7. return module = { exports: {} }, fn(module, module.exports), module.exports;
  8. }
  9. var byteLength_1 = byteLength;
  10. var toByteArray_1 = toByteArray;
  11. var fromByteArray_1 = fromByteArray;
  12. var lookup = [];
  13. var revLookup = [];
  14. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  15. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  16. for (var i = 0, len = code.length; i < len; ++i) {
  17. lookup[i] = code[i];
  18. revLookup[code.charCodeAt(i)] = i;
  19. } // Support decoding URL-safe base64 strings, as Node.js does.
  20. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  21. revLookup['-'.charCodeAt(0)] = 62;
  22. revLookup['_'.charCodeAt(0)] = 63;
  23. function getLens(b64) {
  24. var len = b64.length;
  25. if (len % 4 > 0) {
  26. throw new Error('Invalid string. Length must be a multiple of 4');
  27. } // Trim off extra bytes after placeholder bytes are found
  28. // See: https://github.com/beatgammit/base64-js/issues/42
  29. var validLen = b64.indexOf('=');
  30. if (validLen === -1) validLen = len;
  31. var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
  32. return [validLen, placeHoldersLen];
  33. } // base64 is 4/3 + up to two characters of the original data
  34. function byteLength(b64) {
  35. var lens = getLens(b64);
  36. var validLen = lens[0];
  37. var placeHoldersLen = lens[1];
  38. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  39. }
  40. function _byteLength(b64, validLen, placeHoldersLen) {
  41. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  42. }
  43. function toByteArray(b64) {
  44. var tmp;
  45. var lens = getLens(b64);
  46. var validLen = lens[0];
  47. var placeHoldersLen = lens[1];
  48. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
  49. var curByte = 0; // if there are placeholders, only get up to the last complete 4 chars
  50. var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
  51. var i;
  52. for (i = 0; i < len; i += 4) {
  53. tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
  54. arr[curByte++] = tmp >> 16 & 0xFF;
  55. arr[curByte++] = tmp >> 8 & 0xFF;
  56. arr[curByte++] = tmp & 0xFF;
  57. }
  58. if (placeHoldersLen === 2) {
  59. tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
  60. arr[curByte++] = tmp & 0xFF;
  61. }
  62. if (placeHoldersLen === 1) {
  63. tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
  64. arr[curByte++] = tmp >> 8 & 0xFF;
  65. arr[curByte++] = tmp & 0xFF;
  66. }
  67. return arr;
  68. }
  69. function tripletToBase64(num) {
  70. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
  71. }
  72. function encodeChunk(uint8, start, end) {
  73. var tmp;
  74. var output = [];
  75. for (var i = start; i < end; i += 3) {
  76. tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF);
  77. output.push(tripletToBase64(tmp));
  78. }
  79. return output.join('');
  80. }
  81. function fromByteArray(uint8) {
  82. var tmp;
  83. var len = uint8.length;
  84. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  85. var parts = [];
  86. var maxChunkLength = 16383; // must be multiple of 3
  87. // go through the array every three bytes, we'll deal with trailing stuff later
  88. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  89. parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
  90. } // pad the end with zeros, but make sure to not forget the extra bytes
  91. if (extraBytes === 1) {
  92. tmp = uint8[len - 1];
  93. parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '==');
  94. } else if (extraBytes === 2) {
  95. tmp = (uint8[len - 2] << 8) + uint8[len - 1];
  96. parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '=');
  97. }
  98. return parts.join('');
  99. }
  100. var base64Js = {
  101. byteLength: byteLength_1,
  102. toByteArray: toByteArray_1,
  103. fromByteArray: fromByteArray_1
  104. };
  105. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  106. var read = function read(buffer, offset, isLE, mLen, nBytes) {
  107. var e, m;
  108. var eLen = nBytes * 8 - mLen - 1;
  109. var eMax = (1 << eLen) - 1;
  110. var eBias = eMax >> 1;
  111. var nBits = -7;
  112. var i = isLE ? nBytes - 1 : 0;
  113. var d = isLE ? -1 : 1;
  114. var s = buffer[offset + i];
  115. i += d;
  116. e = s & (1 << -nBits) - 1;
  117. s >>= -nBits;
  118. nBits += eLen;
  119. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  120. m = e & (1 << -nBits) - 1;
  121. e >>= -nBits;
  122. nBits += mLen;
  123. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  124. if (e === 0) {
  125. e = 1 - eBias;
  126. } else if (e === eMax) {
  127. return m ? NaN : (s ? -1 : 1) * Infinity;
  128. } else {
  129. m = m + Math.pow(2, mLen);
  130. e = e - eBias;
  131. }
  132. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  133. };
  134. var write = function write(buffer, value, offset, isLE, mLen, nBytes) {
  135. var e, m, c;
  136. var eLen = nBytes * 8 - mLen - 1;
  137. var eMax = (1 << eLen) - 1;
  138. var eBias = eMax >> 1;
  139. var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  140. var i = isLE ? 0 : nBytes - 1;
  141. var d = isLE ? 1 : -1;
  142. var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  143. value = Math.abs(value);
  144. if (isNaN(value) || value === Infinity) {
  145. m = isNaN(value) ? 1 : 0;
  146. e = eMax;
  147. } else {
  148. e = Math.floor(Math.log(value) / Math.LN2);
  149. if (value * (c = Math.pow(2, -e)) < 1) {
  150. e--;
  151. c *= 2;
  152. }
  153. if (e + eBias >= 1) {
  154. value += rt / c;
  155. } else {
  156. value += rt * Math.pow(2, 1 - eBias);
  157. }
  158. if (value * c >= 2) {
  159. e++;
  160. c /= 2;
  161. }
  162. if (e + eBias >= eMax) {
  163. m = 0;
  164. e = eMax;
  165. } else if (e + eBias >= 1) {
  166. m = (value * c - 1) * Math.pow(2, mLen);
  167. e = e + eBias;
  168. } else {
  169. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  170. e = 0;
  171. }
  172. }
  173. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  174. e = e << mLen | m;
  175. eLen += mLen;
  176. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  177. buffer[offset + i - d] |= s * 128;
  178. };
  179. var ieee754 = {
  180. read: read,
  181. write: write
  182. };
  183. var buffer$1 = createCommonjsModule(function (module, exports) {
  184. var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' ? // eslint-disable-line dot-notation
  185. Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
  186. : null;
  187. exports.Buffer = Buffer;
  188. exports.SlowBuffer = SlowBuffer;
  189. exports.INSPECT_MAX_BYTES = 50;
  190. var K_MAX_LENGTH = 0x7fffffff;
  191. exports.kMaxLength = K_MAX_LENGTH;
  192. /**
  193. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  194. * === true Use Uint8Array implementation (fastest)
  195. * === false Print warning and recommend using `buffer` v4.x which has an Object
  196. * implementation (most compatible, even IE6)
  197. *
  198. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  199. * Opera 11.6+, iOS 4.2+.
  200. *
  201. * We report that the browser does not support typed arrays if the are not subclassable
  202. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  203. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  204. * for __proto__ and has a buggy typed array implementation.
  205. */
  206. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
  207. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') {
  208. console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.');
  209. }
  210. function typedArraySupport() {
  211. // Can typed array instances can be augmented?
  212. try {
  213. var arr = new Uint8Array(1);
  214. var proto = {
  215. foo: function foo() {
  216. return 42;
  217. }
  218. };
  219. Object.setPrototypeOf(proto, Uint8Array.prototype);
  220. Object.setPrototypeOf(arr, proto);
  221. return arr.foo() === 42;
  222. } catch (e) {
  223. return false;
  224. }
  225. }
  226. Object.defineProperty(Buffer.prototype, 'parent', {
  227. enumerable: true,
  228. get: function get() {
  229. if (!Buffer.isBuffer(this)) return undefined;
  230. return this.buffer;
  231. }
  232. });
  233. Object.defineProperty(Buffer.prototype, 'offset', {
  234. enumerable: true,
  235. get: function get() {
  236. if (!Buffer.isBuffer(this)) return undefined;
  237. return this.byteOffset;
  238. }
  239. });
  240. function createBuffer(length) {
  241. if (length > K_MAX_LENGTH) {
  242. throw new RangeError('The value "' + length + '" is invalid for option "size"');
  243. } // Return an augmented `Uint8Array` instance
  244. var buf = new Uint8Array(length);
  245. Object.setPrototypeOf(buf, Buffer.prototype);
  246. return buf;
  247. }
  248. /**
  249. * The Buffer constructor returns instances of `Uint8Array` that have their
  250. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  251. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  252. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  253. * returns a single octet.
  254. *
  255. * The `Uint8Array` prototype remains unmodified.
  256. */
  257. function Buffer(arg, encodingOrOffset, length) {
  258. // Common case.
  259. if (typeof arg === 'number') {
  260. if (typeof encodingOrOffset === 'string') {
  261. throw new TypeError('The "string" argument must be of type string. Received type number');
  262. }
  263. return allocUnsafe(arg);
  264. }
  265. return from(arg, encodingOrOffset, length);
  266. }
  267. Buffer.poolSize = 8192; // not used by this implementation
  268. function from(value, encodingOrOffset, length) {
  269. if (typeof value === 'string') {
  270. return fromString(value, encodingOrOffset);
  271. }
  272. if (ArrayBuffer.isView(value)) {
  273. return fromArrayView(value);
  274. }
  275. if (value == null) {
  276. throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value));
  277. }
  278. if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
  279. return fromArrayBuffer(value, encodingOrOffset, length);
  280. }
  281. if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
  282. return fromArrayBuffer(value, encodingOrOffset, length);
  283. }
  284. if (typeof value === 'number') {
  285. throw new TypeError('The "value" argument must not be of type number. Received type number');
  286. }
  287. var valueOf = value.valueOf && value.valueOf();
  288. if (valueOf != null && valueOf !== value) {
  289. return Buffer.from(valueOf, encodingOrOffset, length);
  290. }
  291. var b = fromObject(value);
  292. if (b) return b;
  293. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') {
  294. return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length);
  295. }
  296. throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + babelHelpers["typeof"](value));
  297. }
  298. /**
  299. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  300. * if value is a number.
  301. * Buffer.from(str[, encoding])
  302. * Buffer.from(array)
  303. * Buffer.from(buffer)
  304. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  305. **/
  306. Buffer.from = function (value, encodingOrOffset, length) {
  307. return from(value, encodingOrOffset, length);
  308. }; // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  309. // https://github.com/feross/buffer/pull/148
  310. Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
  311. Object.setPrototypeOf(Buffer, Uint8Array);
  312. function assertSize(size) {
  313. if (typeof size !== 'number') {
  314. throw new TypeError('"size" argument must be of type number');
  315. } else if (size < 0) {
  316. throw new RangeError('The value "' + size + '" is invalid for option "size"');
  317. }
  318. }
  319. function alloc(size, fill, encoding) {
  320. assertSize(size);
  321. if (size <= 0) {
  322. return createBuffer(size);
  323. }
  324. if (fill !== undefined) {
  325. // Only pay attention to encoding if it's a string. This
  326. // prevents accidentally sending in a number that would
  327. // be interpreted as a start offset.
  328. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
  329. }
  330. return createBuffer(size);
  331. }
  332. /**
  333. * Creates a new filled Buffer instance.
  334. * alloc(size[, fill[, encoding]])
  335. **/
  336. Buffer.alloc = function (size, fill, encoding) {
  337. return alloc(size, fill, encoding);
  338. };
  339. function allocUnsafe(size) {
  340. assertSize(size);
  341. return createBuffer(size < 0 ? 0 : checked(size) | 0);
  342. }
  343. /**
  344. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  345. * */
  346. Buffer.allocUnsafe = function (size) {
  347. return allocUnsafe(size);
  348. };
  349. /**
  350. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  351. */
  352. Buffer.allocUnsafeSlow = function (size) {
  353. return allocUnsafe(size);
  354. };
  355. function fromString(string, encoding) {
  356. if (typeof encoding !== 'string' || encoding === '') {
  357. encoding = 'utf8';
  358. }
  359. if (!Buffer.isEncoding(encoding)) {
  360. throw new TypeError('Unknown encoding: ' + encoding);
  361. }
  362. var length = byteLength(string, encoding) | 0;
  363. var buf = createBuffer(length);
  364. var actual = buf.write(string, encoding);
  365. if (actual !== length) {
  366. // Writing a hex string, for example, that contains invalid characters will
  367. // cause everything after the first invalid character to be ignored. (e.g.
  368. // 'abxxcd' will be treated as 'ab')
  369. buf = buf.slice(0, actual);
  370. }
  371. return buf;
  372. }
  373. function fromArrayLike(array) {
  374. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  375. var buf = createBuffer(length);
  376. for (var i = 0; i < length; i += 1) {
  377. buf[i] = array[i] & 255;
  378. }
  379. return buf;
  380. }
  381. function fromArrayView(arrayView) {
  382. if (isInstance(arrayView, Uint8Array)) {
  383. var copy = new Uint8Array(arrayView);
  384. return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
  385. }
  386. return fromArrayLike(arrayView);
  387. }
  388. function fromArrayBuffer(array, byteOffset, length) {
  389. if (byteOffset < 0 || array.byteLength < byteOffset) {
  390. throw new RangeError('"offset" is outside of buffer bounds');
  391. }
  392. if (array.byteLength < byteOffset + (length || 0)) {
  393. throw new RangeError('"length" is outside of buffer bounds');
  394. }
  395. var buf;
  396. if (byteOffset === undefined && length === undefined) {
  397. buf = new Uint8Array(array);
  398. } else if (length === undefined) {
  399. buf = new Uint8Array(array, byteOffset);
  400. } else {
  401. buf = new Uint8Array(array, byteOffset, length);
  402. } // Return an augmented `Uint8Array` instance
  403. Object.setPrototypeOf(buf, Buffer.prototype);
  404. return buf;
  405. }
  406. function fromObject(obj) {
  407. if (Buffer.isBuffer(obj)) {
  408. var len = checked(obj.length) | 0;
  409. var buf = createBuffer(len);
  410. if (buf.length === 0) {
  411. return buf;
  412. }
  413. obj.copy(buf, 0, 0, len);
  414. return buf;
  415. }
  416. if (obj.length !== undefined) {
  417. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  418. return createBuffer(0);
  419. }
  420. return fromArrayLike(obj);
  421. }
  422. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  423. return fromArrayLike(obj.data);
  424. }
  425. }
  426. function checked(length) {
  427. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  428. // length is NaN (which is otherwise coerced to zero.)
  429. if (length >= K_MAX_LENGTH) {
  430. throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes');
  431. }
  432. return length | 0;
  433. }
  434. function SlowBuffer(length) {
  435. if (+length != length) {
  436. // eslint-disable-line eqeqeq
  437. length = 0;
  438. }
  439. return Buffer.alloc(+length);
  440. }
  441. Buffer.isBuffer = function isBuffer(b) {
  442. return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false
  443. };
  444. Buffer.compare = function compare(a, b) {
  445. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
  446. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
  447. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  448. throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
  449. }
  450. if (a === b) return 0;
  451. var x = a.length;
  452. var y = b.length;
  453. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  454. if (a[i] !== b[i]) {
  455. x = a[i];
  456. y = b[i];
  457. break;
  458. }
  459. }
  460. if (x < y) return -1;
  461. if (y < x) return 1;
  462. return 0;
  463. };
  464. Buffer.isEncoding = function isEncoding(encoding) {
  465. switch (String(encoding).toLowerCase()) {
  466. case 'hex':
  467. case 'utf8':
  468. case 'utf-8':
  469. case 'ascii':
  470. case 'latin1':
  471. case 'binary':
  472. case 'base64':
  473. case 'ucs2':
  474. case 'ucs-2':
  475. case 'utf16le':
  476. case 'utf-16le':
  477. return true;
  478. default:
  479. return false;
  480. }
  481. };
  482. Buffer.concat = function concat(list, length) {
  483. if (!Array.isArray(list)) {
  484. throw new TypeError('"list" argument must be an Array of Buffers');
  485. }
  486. if (list.length === 0) {
  487. return Buffer.alloc(0);
  488. }
  489. var i;
  490. if (length === undefined) {
  491. length = 0;
  492. for (i = 0; i < list.length; ++i) {
  493. length += list[i].length;
  494. }
  495. }
  496. var buffer = Buffer.allocUnsafe(length);
  497. var pos = 0;
  498. for (i = 0; i < list.length; ++i) {
  499. var buf = list[i];
  500. if (isInstance(buf, Uint8Array)) {
  501. if (pos + buf.length > buffer.length) {
  502. Buffer.from(buf).copy(buffer, pos);
  503. } else {
  504. Uint8Array.prototype.set.call(buffer, buf, pos);
  505. }
  506. } else if (!Buffer.isBuffer(buf)) {
  507. throw new TypeError('"list" argument must be an Array of Buffers');
  508. } else {
  509. buf.copy(buffer, pos);
  510. }
  511. pos += buf.length;
  512. }
  513. return buffer;
  514. };
  515. function byteLength(string, encoding) {
  516. if (Buffer.isBuffer(string)) {
  517. return string.length;
  518. }
  519. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  520. return string.byteLength;
  521. }
  522. if (typeof string !== 'string') {
  523. throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + babelHelpers["typeof"](string));
  524. }
  525. var len = string.length;
  526. var mustMatch = arguments.length > 2 && arguments[2] === true;
  527. if (!mustMatch && len === 0) return 0; // Use a for loop to avoid recursion
  528. var loweredCase = false;
  529. for (;;) {
  530. switch (encoding) {
  531. case 'ascii':
  532. case 'latin1':
  533. case 'binary':
  534. return len;
  535. case 'utf8':
  536. case 'utf-8':
  537. return utf8ToBytes(string).length;
  538. case 'ucs2':
  539. case 'ucs-2':
  540. case 'utf16le':
  541. case 'utf-16le':
  542. return len * 2;
  543. case 'hex':
  544. return len >>> 1;
  545. case 'base64':
  546. return base64ToBytes(string).length;
  547. default:
  548. if (loweredCase) {
  549. return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8
  550. }
  551. encoding = ('' + encoding).toLowerCase();
  552. loweredCase = true;
  553. }
  554. }
  555. }
  556. Buffer.byteLength = byteLength;
  557. function slowToString(encoding, start, end) {
  558. var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  559. // property of a typed array.
  560. // This behaves neither like String nor Uint8Array in that we set start/end
  561. // to their upper/lower bounds if the value passed is out of range.
  562. // undefined is handled specially as per ECMA-262 6th Edition,
  563. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  564. if (start === undefined || start < 0) {
  565. start = 0;
  566. } // Return early if start > this.length. Done here to prevent potential uint32
  567. // coercion fail below.
  568. if (start > this.length) {
  569. return '';
  570. }
  571. if (end === undefined || end > this.length) {
  572. end = this.length;
  573. }
  574. if (end <= 0) {
  575. return '';
  576. } // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
  577. end >>>= 0;
  578. start >>>= 0;
  579. if (end <= start) {
  580. return '';
  581. }
  582. if (!encoding) encoding = 'utf8';
  583. while (true) {
  584. switch (encoding) {
  585. case 'hex':
  586. return hexSlice(this, start, end);
  587. case 'utf8':
  588. case 'utf-8':
  589. return utf8Slice(this, start, end);
  590. case 'ascii':
  591. return asciiSlice(this, start, end);
  592. case 'latin1':
  593. case 'binary':
  594. return latin1Slice(this, start, end);
  595. case 'base64':
  596. return base64Slice(this, start, end);
  597. case 'ucs2':
  598. case 'ucs-2':
  599. case 'utf16le':
  600. case 'utf-16le':
  601. return utf16leSlice(this, start, end);
  602. default:
  603. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
  604. encoding = (encoding + '').toLowerCase();
  605. loweredCase = true;
  606. }
  607. }
  608. } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  609. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  610. // reliably in a browserify context because there could be multiple different
  611. // copies of the 'buffer' package in use. This method works even for Buffer
  612. // instances that were created from another copy of the `buffer` package.
  613. // See: https://github.com/feross/buffer/issues/154
  614. Buffer.prototype._isBuffer = true;
  615. function swap(b, n, m) {
  616. var i = b[n];
  617. b[n] = b[m];
  618. b[m] = i;
  619. }
  620. Buffer.prototype.swap16 = function swap16() {
  621. var len = this.length;
  622. if (len % 2 !== 0) {
  623. throw new RangeError('Buffer size must be a multiple of 16-bits');
  624. }
  625. for (var i = 0; i < len; i += 2) {
  626. swap(this, i, i + 1);
  627. }
  628. return this;
  629. };
  630. Buffer.prototype.swap32 = function swap32() {
  631. var len = this.length;
  632. if (len % 4 !== 0) {
  633. throw new RangeError('Buffer size must be a multiple of 32-bits');
  634. }
  635. for (var i = 0; i < len; i += 4) {
  636. swap(this, i, i + 3);
  637. swap(this, i + 1, i + 2);
  638. }
  639. return this;
  640. };
  641. Buffer.prototype.swap64 = function swap64() {
  642. var len = this.length;
  643. if (len % 8 !== 0) {
  644. throw new RangeError('Buffer size must be a multiple of 64-bits');
  645. }
  646. for (var i = 0; i < len; i += 8) {
  647. swap(this, i, i + 7);
  648. swap(this, i + 1, i + 6);
  649. swap(this, i + 2, i + 5);
  650. swap(this, i + 3, i + 4);
  651. }
  652. return this;
  653. };
  654. Buffer.prototype.toString = function toString() {
  655. var length = this.length;
  656. if (length === 0) return '';
  657. if (arguments.length === 0) return utf8Slice(this, 0, length);
  658. return slowToString.apply(this, arguments);
  659. };
  660. Buffer.prototype.toLocaleString = Buffer.prototype.toString;
  661. Buffer.prototype.equals = function equals(b) {
  662. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer');
  663. if (this === b) return true;
  664. return Buffer.compare(this, b) === 0;
  665. };
  666. Buffer.prototype.inspect = function inspect() {
  667. var str = '';
  668. var max = exports.INSPECT_MAX_BYTES;
  669. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
  670. if (this.length > max) str += ' ... ';
  671. return '<Buffer ' + str + '>';
  672. };
  673. if (customInspectSymbol) {
  674. Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
  675. }
  676. Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
  677. if (isInstance(target, Uint8Array)) {
  678. target = Buffer.from(target, target.offset, target.byteLength);
  679. }
  680. if (!Buffer.isBuffer(target)) {
  681. throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + babelHelpers["typeof"](target));
  682. }
  683. if (start === undefined) {
  684. start = 0;
  685. }
  686. if (end === undefined) {
  687. end = target ? target.length : 0;
  688. }
  689. if (thisStart === undefined) {
  690. thisStart = 0;
  691. }
  692. if (thisEnd === undefined) {
  693. thisEnd = this.length;
  694. }
  695. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  696. throw new RangeError('out of range index');
  697. }
  698. if (thisStart >= thisEnd && start >= end) {
  699. return 0;
  700. }
  701. if (thisStart >= thisEnd) {
  702. return -1;
  703. }
  704. if (start >= end) {
  705. return 1;
  706. }
  707. start >>>= 0;
  708. end >>>= 0;
  709. thisStart >>>= 0;
  710. thisEnd >>>= 0;
  711. if (this === target) return 0;
  712. var x = thisEnd - thisStart;
  713. var y = end - start;
  714. var len = Math.min(x, y);
  715. var thisCopy = this.slice(thisStart, thisEnd);
  716. var targetCopy = target.slice(start, end);
  717. for (var i = 0; i < len; ++i) {
  718. if (thisCopy[i] !== targetCopy[i]) {
  719. x = thisCopy[i];
  720. y = targetCopy[i];
  721. break;
  722. }
  723. }
  724. if (x < y) return -1;
  725. if (y < x) return 1;
  726. return 0;
  727. }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  728. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  729. //
  730. // Arguments:
  731. // - buffer - a Buffer to search
  732. // - val - a string, Buffer, or number
  733. // - byteOffset - an index into `buffer`; will be clamped to an int32
  734. // - encoding - an optional encoding, relevant is val is a string
  735. // - dir - true for indexOf, false for lastIndexOf
  736. function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  737. // Empty buffer means no match
  738. if (buffer.length === 0) return -1; // Normalize byteOffset
  739. if (typeof byteOffset === 'string') {
  740. encoding = byteOffset;
  741. byteOffset = 0;
  742. } else if (byteOffset > 0x7fffffff) {
  743. byteOffset = 0x7fffffff;
  744. } else if (byteOffset < -0x80000000) {
  745. byteOffset = -0x80000000;
  746. }
  747. byteOffset = +byteOffset; // Coerce to Number.
  748. if (numberIsNaN(byteOffset)) {
  749. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  750. byteOffset = dir ? 0 : buffer.length - 1;
  751. } // Normalize byteOffset: negative offsets start from the end of the buffer
  752. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  753. if (byteOffset >= buffer.length) {
  754. if (dir) return -1;else byteOffset = buffer.length - 1;
  755. } else if (byteOffset < 0) {
  756. if (dir) byteOffset = 0;else return -1;
  757. } // Normalize val
  758. if (typeof val === 'string') {
  759. val = Buffer.from(val, encoding);
  760. } // Finally, search either indexOf (if dir is true) or lastIndexOf
  761. if (Buffer.isBuffer(val)) {
  762. // Special case: looking for empty string/buffer always fails
  763. if (val.length === 0) {
  764. return -1;
  765. }
  766. return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
  767. } else if (typeof val === 'number') {
  768. val = val & 0xFF; // Search for a byte value [0-255]
  769. if (typeof Uint8Array.prototype.indexOf === 'function') {
  770. if (dir) {
  771. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
  772. } else {
  773. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
  774. }
  775. }
  776. return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
  777. }
  778. throw new TypeError('val must be string, number or Buffer');
  779. }
  780. function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  781. var indexSize = 1;
  782. var arrLength = arr.length;
  783. var valLength = val.length;
  784. if (encoding !== undefined) {
  785. encoding = String(encoding).toLowerCase();
  786. if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
  787. if (arr.length < 2 || val.length < 2) {
  788. return -1;
  789. }
  790. indexSize = 2;
  791. arrLength /= 2;
  792. valLength /= 2;
  793. byteOffset /= 2;
  794. }
  795. }
  796. function read(buf, i) {
  797. if (indexSize === 1) {
  798. return buf[i];
  799. } else {
  800. return buf.readUInt16BE(i * indexSize);
  801. }
  802. }
  803. var i;
  804. if (dir) {
  805. var foundIndex = -1;
  806. for (i = byteOffset; i < arrLength; i++) {
  807. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  808. if (foundIndex === -1) foundIndex = i;
  809. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
  810. } else {
  811. if (foundIndex !== -1) i -= i - foundIndex;
  812. foundIndex = -1;
  813. }
  814. }
  815. } else {
  816. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  817. for (i = byteOffset; i >= 0; i--) {
  818. var found = true;
  819. for (var j = 0; j < valLength; j++) {
  820. if (read(arr, i + j) !== read(val, j)) {
  821. found = false;
  822. break;
  823. }
  824. }
  825. if (found) return i;
  826. }
  827. }
  828. return -1;
  829. }
  830. Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
  831. return this.indexOf(val, byteOffset, encoding) !== -1;
  832. };
  833. Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
  834. return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
  835. };
  836. Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
  837. return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
  838. };
  839. function hexWrite(buf, string, offset, length) {
  840. offset = Number(offset) || 0;
  841. var remaining = buf.length - offset;
  842. if (!length) {
  843. length = remaining;
  844. } else {
  845. length = Number(length);
  846. if (length > remaining) {
  847. length = remaining;
  848. }
  849. }
  850. var strLen = string.length;
  851. if (length > strLen / 2) {
  852. length = strLen / 2;
  853. }
  854. for (var i = 0; i < length; ++i) {
  855. var parsed = parseInt(string.substr(i * 2, 2), 16);
  856. if (numberIsNaN(parsed)) return i;
  857. buf[offset + i] = parsed;
  858. }
  859. return i;
  860. }
  861. function utf8Write(buf, string, offset, length) {
  862. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
  863. }
  864. function asciiWrite(buf, string, offset, length) {
  865. return blitBuffer(asciiToBytes(string), buf, offset, length);
  866. }
  867. function base64Write(buf, string, offset, length) {
  868. return blitBuffer(base64ToBytes(string), buf, offset, length);
  869. }
  870. function ucs2Write(buf, string, offset, length) {
  871. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
  872. }
  873. Buffer.prototype.write = function write(string, offset, length, encoding) {
  874. // Buffer#write(string)
  875. if (offset === undefined) {
  876. encoding = 'utf8';
  877. length = this.length;
  878. offset = 0; // Buffer#write(string, encoding)
  879. } else if (length === undefined && typeof offset === 'string') {
  880. encoding = offset;
  881. length = this.length;
  882. offset = 0; // Buffer#write(string, offset[, length][, encoding])
  883. } else if (isFinite(offset)) {
  884. offset = offset >>> 0;
  885. if (isFinite(length)) {
  886. length = length >>> 0;
  887. if (encoding === undefined) encoding = 'utf8';
  888. } else {
  889. encoding = length;
  890. length = undefined;
  891. }
  892. } else {
  893. throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
  894. }
  895. var remaining = this.length - offset;
  896. if (length === undefined || length > remaining) length = remaining;
  897. if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
  898. throw new RangeError('Attempt to write outside buffer bounds');
  899. }
  900. if (!encoding) encoding = 'utf8';
  901. var loweredCase = false;
  902. for (;;) {
  903. switch (encoding) {
  904. case 'hex':
  905. return hexWrite(this, string, offset, length);
  906. case 'utf8':
  907. case 'utf-8':
  908. return utf8Write(this, string, offset, length);
  909. case 'ascii':
  910. case 'latin1':
  911. case 'binary':
  912. return asciiWrite(this, string, offset, length);
  913. case 'base64':
  914. // Warning: maxLength not taken into account in base64Write
  915. return base64Write(this, string, offset, length);
  916. case 'ucs2':
  917. case 'ucs-2':
  918. case 'utf16le':
  919. case 'utf-16le':
  920. return ucs2Write(this, string, offset, length);
  921. default:
  922. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
  923. encoding = ('' + encoding).toLowerCase();
  924. loweredCase = true;
  925. }
  926. }
  927. };
  928. Buffer.prototype.toJSON = function toJSON() {
  929. return {
  930. type: 'Buffer',
  931. data: Array.prototype.slice.call(this._arr || this, 0)
  932. };
  933. };
  934. function base64Slice(buf, start, end) {
  935. if (start === 0 && end === buf.length) {
  936. return base64Js.fromByteArray(buf);
  937. } else {
  938. return base64Js.fromByteArray(buf.slice(start, end));
  939. }
  940. }
  941. function utf8Slice(buf, start, end) {
  942. end = Math.min(buf.length, end);
  943. var res = [];
  944. var i = start;
  945. while (i < end) {
  946. var firstByte = buf[i];
  947. var codePoint = null;
  948. var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
  949. if (i + bytesPerSequence <= end) {
  950. var secondByte, thirdByte, fourthByte, tempCodePoint;
  951. switch (bytesPerSequence) {
  952. case 1:
  953. if (firstByte < 0x80) {
  954. codePoint = firstByte;
  955. }
  956. break;
  957. case 2:
  958. secondByte = buf[i + 1];
  959. if ((secondByte & 0xC0) === 0x80) {
  960. tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
  961. if (tempCodePoint > 0x7F) {
  962. codePoint = tempCodePoint;
  963. }
  964. }
  965. break;
  966. case 3:
  967. secondByte = buf[i + 1];
  968. thirdByte = buf[i + 2];
  969. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  970. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
  971. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  972. codePoint = tempCodePoint;
  973. }
  974. }
  975. break;
  976. case 4:
  977. secondByte = buf[i + 1];
  978. thirdByte = buf[i + 2];
  979. fourthByte = buf[i + 3];
  980. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  981. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
  982. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  983. codePoint = tempCodePoint;
  984. }
  985. }
  986. }
  987. }
  988. if (codePoint === null) {
  989. // we did not generate a valid codePoint so insert a
  990. // replacement char (U+FFFD) and advance only 1 byte
  991. codePoint = 0xFFFD;
  992. bytesPerSequence = 1;
  993. } else if (codePoint > 0xFFFF) {
  994. // encode to utf16 (surrogate pair dance)
  995. codePoint -= 0x10000;
  996. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  997. codePoint = 0xDC00 | codePoint & 0x3FF;
  998. }
  999. res.push(codePoint);
  1000. i += bytesPerSequence;
  1001. }
  1002. return decodeCodePointsArray(res);
  1003. } // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1004. // the lowest limit is Chrome, with 0x10000 args.
  1005. // We go 1 magnitude less, for safety
  1006. var MAX_ARGUMENTS_LENGTH = 0x1000;
  1007. function decodeCodePointsArray(codePoints) {
  1008. var len = codePoints.length;
  1009. if (len <= MAX_ARGUMENTS_LENGTH) {
  1010. return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
  1011. } // Decode in chunks to avoid "call stack size exceeded".
  1012. var res = '';
  1013. var i = 0;
  1014. while (i < len) {
  1015. res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
  1016. }
  1017. return res;
  1018. }
  1019. function asciiSlice(buf, start, end) {
  1020. var ret = '';
  1021. end = Math.min(buf.length, end);
  1022. for (var i = start; i < end; ++i) {
  1023. ret += String.fromCharCode(buf[i] & 0x7F);
  1024. }
  1025. return ret;
  1026. }
  1027. function latin1Slice(buf, start, end) {
  1028. var ret = '';
  1029. end = Math.min(buf.length, end);
  1030. for (var i = start; i < end; ++i) {
  1031. ret += String.fromCharCode(buf[i]);
  1032. }
  1033. return ret;
  1034. }
  1035. function hexSlice(buf, start, end) {
  1036. var len = buf.length;
  1037. if (!start || start < 0) start = 0;
  1038. if (!end || end < 0 || end > len) end = len;
  1039. var out = '';
  1040. for (var i = start; i < end; ++i) {
  1041. out += hexSliceLookupTable[buf[i]];
  1042. }
  1043. return out;
  1044. }
  1045. function utf16leSlice(buf, start, end) {
  1046. var bytes = buf.slice(start, end);
  1047. var res = ''; // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
  1048. for (var i = 0; i < bytes.length - 1; i += 2) {
  1049. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1050. }
  1051. return res;
  1052. }
  1053. Buffer.prototype.slice = function slice(start, end) {
  1054. var len = this.length;
  1055. start = ~~start;
  1056. end = end === undefined ? len : ~~end;
  1057. if (start < 0) {
  1058. start += len;
  1059. if (start < 0) start = 0;
  1060. } else if (start > len) {
  1061. start = len;
  1062. }
  1063. if (end < 0) {
  1064. end += len;
  1065. if (end < 0) end = 0;
  1066. } else if (end > len) {
  1067. end = len;
  1068. }
  1069. if (end < start) end = start;
  1070. var newBuf = this.subarray(start, end); // Return an augmented `Uint8Array` instance
  1071. Object.setPrototypeOf(newBuf, Buffer.prototype);
  1072. return newBuf;
  1073. };
  1074. /*
  1075. * Need to make sure that buffer isn't trying to write out of bounds.
  1076. */
  1077. function checkOffset(offset, ext, length) {
  1078. if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
  1079. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
  1080. }
  1081. Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
  1082. offset = offset >>> 0;
  1083. byteLength = byteLength >>> 0;
  1084. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1085. var val = this[offset];
  1086. var mul = 1;
  1087. var i = 0;
  1088. while (++i < byteLength && (mul *= 0x100)) {
  1089. val += this[offset + i] * mul;
  1090. }
  1091. return val;
  1092. };
  1093. Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
  1094. offset = offset >>> 0;
  1095. byteLength = byteLength >>> 0;
  1096. if (!noAssert) {
  1097. checkOffset(offset, byteLength, this.length);
  1098. }
  1099. var val = this[offset + --byteLength];
  1100. var mul = 1;
  1101. while (byteLength > 0 && (mul *= 0x100)) {
  1102. val += this[offset + --byteLength] * mul;
  1103. }
  1104. return val;
  1105. };
  1106. Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
  1107. offset = offset >>> 0;
  1108. if (!noAssert) checkOffset(offset, 1, this.length);
  1109. return this[offset];
  1110. };
  1111. Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
  1112. offset = offset >>> 0;
  1113. if (!noAssert) checkOffset(offset, 2, this.length);
  1114. return this[offset] | this[offset + 1] << 8;
  1115. };
  1116. Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
  1117. offset = offset >>> 0;
  1118. if (!noAssert) checkOffset(offset, 2, this.length);
  1119. return this[offset] << 8 | this[offset + 1];
  1120. };
  1121. Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
  1122. offset = offset >>> 0;
  1123. if (!noAssert) checkOffset(offset, 4, this.length);
  1124. return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
  1125. };
  1126. Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
  1127. offset = offset >>> 0;
  1128. if (!noAssert) checkOffset(offset, 4, this.length);
  1129. return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
  1130. };
  1131. Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
  1132. offset = offset >>> 0;
  1133. byteLength = byteLength >>> 0;
  1134. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1135. var val = this[offset];
  1136. var mul = 1;
  1137. var i = 0;
  1138. while (++i < byteLength && (mul *= 0x100)) {
  1139. val += this[offset + i] * mul;
  1140. }
  1141. mul *= 0x80;
  1142. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1143. return val;
  1144. };
  1145. Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
  1146. offset = offset >>> 0;
  1147. byteLength = byteLength >>> 0;
  1148. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1149. var i = byteLength;
  1150. var mul = 1;
  1151. var val = this[offset + --i];
  1152. while (i > 0 && (mul *= 0x100)) {
  1153. val += this[offset + --i] * mul;
  1154. }
  1155. mul *= 0x80;
  1156. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1157. return val;
  1158. };
  1159. Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
  1160. offset = offset >>> 0;
  1161. if (!noAssert) checkOffset(offset, 1, this.length);
  1162. if (!(this[offset] & 0x80)) return this[offset];
  1163. return (0xff - this[offset] + 1) * -1;
  1164. };
  1165. Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
  1166. offset = offset >>> 0;
  1167. if (!noAssert) checkOffset(offset, 2, this.length);
  1168. var val = this[offset] | this[offset + 1] << 8;
  1169. return val & 0x8000 ? val | 0xFFFF0000 : val;
  1170. };
  1171. Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
  1172. offset = offset >>> 0;
  1173. if (!noAssert) checkOffset(offset, 2, this.length);
  1174. var val = this[offset + 1] | this[offset] << 8;
  1175. return val & 0x8000 ? val | 0xFFFF0000 : val;
  1176. };
  1177. Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
  1178. offset = offset >>> 0;
  1179. if (!noAssert) checkOffset(offset, 4, this.length);
  1180. return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
  1181. };
  1182. Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
  1183. offset = offset >>> 0;
  1184. if (!noAssert) checkOffset(offset, 4, this.length);
  1185. return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
  1186. };
  1187. Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
  1188. offset = offset >>> 0;
  1189. if (!noAssert) checkOffset(offset, 4, this.length);
  1190. return ieee754.read(this, offset, true, 23, 4);
  1191. };
  1192. Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
  1193. offset = offset >>> 0;
  1194. if (!noAssert) checkOffset(offset, 4, this.length);
  1195. return ieee754.read(this, offset, false, 23, 4);
  1196. };
  1197. Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
  1198. offset = offset >>> 0;
  1199. if (!noAssert) checkOffset(offset, 8, this.length);
  1200. return ieee754.read(this, offset, true, 52, 8);
  1201. };
  1202. Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
  1203. offset = offset >>> 0;
  1204. if (!noAssert) checkOffset(offset, 8, this.length);
  1205. return ieee754.read(this, offset, false, 52, 8);
  1206. };
  1207. function checkInt(buf, value, offset, ext, max, min) {
  1208. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
  1209. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
  1210. if (offset + ext > buf.length) throw new RangeError('Index out of range');
  1211. }
  1212. Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
  1213. value = +value;
  1214. offset = offset >>> 0;
  1215. byteLength = byteLength >>> 0;
  1216. if (!noAssert) {
  1217. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1218. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1219. }
  1220. var mul = 1;
  1221. var i = 0;
  1222. this[offset] = value & 0xFF;
  1223. while (++i < byteLength && (mul *= 0x100)) {
  1224. this[offset + i] = value / mul & 0xFF;
  1225. }
  1226. return offset + byteLength;
  1227. };
  1228. Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
  1229. value = +value;
  1230. offset = offset >>> 0;
  1231. byteLength = byteLength >>> 0;
  1232. if (!noAssert) {
  1233. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1234. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1235. }
  1236. var i = byteLength - 1;
  1237. var mul = 1;
  1238. this[offset + i] = value & 0xFF;
  1239. while (--i >= 0 && (mul *= 0x100)) {
  1240. this[offset + i] = value / mul & 0xFF;
  1241. }
  1242. return offset + byteLength;
  1243. };
  1244. Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
  1245. value = +value;
  1246. offset = offset >>> 0;
  1247. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  1248. this[offset] = value & 0xff;
  1249. return offset + 1;
  1250. };
  1251. Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
  1252. value = +value;
  1253. offset = offset >>> 0;
  1254. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1255. this[offset] = value & 0xff;
  1256. this[offset + 1] = value >>> 8;
  1257. return offset + 2;
  1258. };
  1259. Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
  1260. value = +value;
  1261. offset = offset >>> 0;
  1262. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1263. this[offset] = value >>> 8;
  1264. this[offset + 1] = value & 0xff;
  1265. return offset + 2;
  1266. };
  1267. Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
  1268. value = +value;
  1269. offset = offset >>> 0;
  1270. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1271. this[offset + 3] = value >>> 24;
  1272. this[offset + 2] = value >>> 16;
  1273. this[offset + 1] = value >>> 8;
  1274. this[offset] = value & 0xff;
  1275. return offset + 4;
  1276. };
  1277. Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
  1278. value = +value;
  1279. offset = offset >>> 0;
  1280. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1281. this[offset] = value >>> 24;
  1282. this[offset + 1] = value >>> 16;
  1283. this[offset + 2] = value >>> 8;
  1284. this[offset + 3] = value & 0xff;
  1285. return offset + 4;
  1286. };
  1287. Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
  1288. value = +value;
  1289. offset = offset >>> 0;
  1290. if (!noAssert) {
  1291. var limit = Math.pow(2, 8 * byteLength - 1);
  1292. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1293. }
  1294. var i = 0;
  1295. var mul = 1;
  1296. var sub = 0;
  1297. this[offset] = value & 0xFF;
  1298. while (++i < byteLength && (mul *= 0x100)) {
  1299. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1300. sub = 1;
  1301. }
  1302. this[offset + i] = (value / mul >> 0) - sub & 0xFF;
  1303. }
  1304. return offset + byteLength;
  1305. };
  1306. Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
  1307. value = +value;
  1308. offset = offset >>> 0;
  1309. if (!noAssert) {
  1310. var limit = Math.pow(2, 8 * byteLength - 1);
  1311. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1312. }
  1313. var i = byteLength - 1;
  1314. var mul = 1;
  1315. var sub = 0;
  1316. this[offset + i] = value & 0xFF;
  1317. while (--i >= 0 && (mul *= 0x100)) {
  1318. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1319. sub = 1;
  1320. }
  1321. this[offset + i] = (value / mul >> 0) - sub & 0xFF;
  1322. }
  1323. return offset + byteLength;
  1324. };
  1325. Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
  1326. value = +value;
  1327. offset = offset >>> 0;
  1328. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  1329. if (value < 0) value = 0xff + value + 1;
  1330. this[offset] = value & 0xff;
  1331. return offset + 1;
  1332. };
  1333. Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
  1334. value = +value;
  1335. offset = offset >>> 0;
  1336. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1337. this[offset] = value & 0xff;
  1338. this[offset + 1] = value >>> 8;
  1339. return offset + 2;
  1340. };
  1341. Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
  1342. value = +value;
  1343. offset = offset >>> 0;
  1344. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1345. this[offset] = value >>> 8;
  1346. this[offset + 1] = value & 0xff;
  1347. return offset + 2;
  1348. };
  1349. Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
  1350. value = +value;
  1351. offset = offset >>> 0;
  1352. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1353. this[offset] = value & 0xff;
  1354. this[offset + 1] = value >>> 8;
  1355. this[offset + 2] = value >>> 16;
  1356. this[offset + 3] = value >>> 24;
  1357. return offset + 4;
  1358. };
  1359. Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
  1360. value = +value;
  1361. offset = offset >>> 0;
  1362. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1363. if (value < 0) value = 0xffffffff + value + 1;
  1364. this[offset] = value >>> 24;
  1365. this[offset + 1] = value >>> 16;
  1366. this[offset + 2] = value >>> 8;
  1367. this[offset + 3] = value & 0xff;
  1368. return offset + 4;
  1369. };
  1370. function checkIEEE754(buf, value, offset, ext, max, min) {
  1371. if (offset + ext > buf.length) throw new RangeError('Index out of range');
  1372. if (offset < 0) throw new RangeError('Index out of range');
  1373. }
  1374. function writeFloat(buf, value, offset, littleEndian, noAssert) {
  1375. value = +value;
  1376. offset = offset >>> 0;
  1377. if (!noAssert) {
  1378. checkIEEE754(buf, value, offset, 4);
  1379. }
  1380. ieee754.write(buf, value, offset, littleEndian, 23, 4);
  1381. return offset + 4;
  1382. }
  1383. Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
  1384. return writeFloat(this, value, offset, true, noAssert);
  1385. };
  1386. Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
  1387. return writeFloat(this, value, offset, false, noAssert);
  1388. };
  1389. function writeDouble(buf, value, offset, littleEndian, noAssert) {
  1390. value = +value;
  1391. offset = offset >>> 0;
  1392. if (!noAssert) {
  1393. checkIEEE754(buf, value, offset, 8);
  1394. }
  1395. ieee754.write(buf, value, offset, littleEndian, 52, 8);
  1396. return offset + 8;
  1397. }
  1398. Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
  1399. return writeDouble(this, value, offset, true, noAssert);
  1400. };
  1401. Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
  1402. return writeDouble(this, value, offset, false, noAssert);
  1403. }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1404. Buffer.prototype.copy = function copy(target, targetStart, start, end) {
  1405. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer');
  1406. if (!start) start = 0;
  1407. if (!end && end !== 0) end = this.length;
  1408. if (targetStart >= target.length) targetStart = target.length;
  1409. if (!targetStart) targetStart = 0;
  1410. if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done
  1411. if (end === start) return 0;
  1412. if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions
  1413. if (targetStart < 0) {
  1414. throw new RangeError('targetStart out of bounds');
  1415. }
  1416. if (start < 0 || start >= this.length) throw new RangeError('Index out of range');
  1417. if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob?
  1418. if (end > this.length) end = this.length;
  1419. if (target.length - targetStart < end - start) {
  1420. end = target.length - targetStart + start;
  1421. }
  1422. var len = end - start;
  1423. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  1424. // Use built-in when available, missing from IE11
  1425. this.copyWithin(targetStart, start, end);
  1426. } else {
  1427. Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
  1428. }
  1429. return len;
  1430. }; // Usage:
  1431. // buffer.fill(number[, offset[, end]])
  1432. // buffer.fill(buffer[, offset[, end]])
  1433. // buffer.fill(string[, offset[, end]][, encoding])
  1434. Buffer.prototype.fill = function fill(val, start, end, encoding) {
  1435. // Handle string cases:
  1436. if (typeof val === 'string') {
  1437. if (typeof start === 'string') {
  1438. encoding = start;
  1439. start = 0;
  1440. end = this.length;
  1441. } else if (typeof end === 'string') {
  1442. encoding = end;
  1443. end = this.length;
  1444. }
  1445. if (encoding !== undefined && typeof encoding !== 'string') {
  1446. throw new TypeError('encoding must be a string');
  1447. }
  1448. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1449. throw new TypeError('Unknown encoding: ' + encoding);
  1450. }
  1451. if (val.length === 1) {
  1452. var code = val.charCodeAt(0);
  1453. if (encoding === 'utf8' && code < 128 || encoding === 'latin1') {
  1454. // Fast path: If `val` fits into a single byte, use that numeric value.
  1455. val = code;
  1456. }
  1457. }
  1458. } else if (typeof val === 'number') {
  1459. val = val & 255;
  1460. } else if (typeof val === 'boolean') {
  1461. val = Number(val);
  1462. } // Invalid ranges are not set to a default, so can range check early.
  1463. if (start < 0 || this.length < start || this.length < end) {
  1464. throw new RangeError('Out of range index');
  1465. }
  1466. if (end <= start) {
  1467. return this;
  1468. }
  1469. start = start >>> 0;
  1470. end = end === undefined ? this.length : end >>> 0;
  1471. if (!val) val = 0;
  1472. var i;
  1473. if (typeof val === 'number') {
  1474. for (i = start; i < end; ++i) {
  1475. this[i] = val;
  1476. }
  1477. } else {
  1478. var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding);
  1479. var len = bytes.length;
  1480. if (len === 0) {
  1481. throw new TypeError('The value "' + val + '" is invalid for argument "value"');
  1482. }
  1483. for (i = 0; i < end - start; ++i) {
  1484. this[i + start] = bytes[i % len];
  1485. }
  1486. }
  1487. return this;
  1488. }; // HELPER FUNCTIONS
  1489. // ================
  1490. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
  1491. function base64clean(str) {
  1492. // Node takes equal signs as end of the Base64 encoding
  1493. str = str.split('=')[0]; // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1494. str = str.trim().replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to ''
  1495. if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1496. while (str.length % 4 !== 0) {
  1497. str = str + '=';
  1498. }
  1499. return str;
  1500. }
  1501. function utf8ToBytes(string, units) {
  1502. units = units || Infinity;
  1503. var codePoint;
  1504. var length = string.length;
  1505. var leadSurrogate = null;
  1506. var bytes = [];
  1507. for (var i = 0; i < length; ++i) {
  1508. codePoint = string.charCodeAt(i); // is surrogate component
  1509. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1510. // last char was a lead
  1511. if (!leadSurrogate) {
  1512. // no lead yet
  1513. if (codePoint > 0xDBFF) {
  1514. // unexpected trail
  1515. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1516. continue;
  1517. } else if (i + 1 === length) {
  1518. // unpaired lead
  1519. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1520. continue;
  1521. } // valid lead
  1522. leadSurrogate = codePoint;
  1523. continue;
  1524. } // 2 leads in a row
  1525. if (codePoint < 0xDC00) {
  1526. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1527. leadSurrogate = codePoint;
  1528. continue;
  1529. } // valid surrogate pair
  1530. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  1531. } else if (leadSurrogate) {
  1532. // valid bmp char, but last char was a lead
  1533. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1534. }
  1535. leadSurrogate = null; // encode utf8
  1536. if (codePoint < 0x80) {
  1537. if ((units -= 1) < 0) break;
  1538. bytes.push(codePoint);
  1539. } else if (codePoint < 0x800) {
  1540. if ((units -= 2) < 0) break;
  1541. bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
  1542. } else if (codePoint < 0x10000) {
  1543. if ((units -= 3) < 0) break;
  1544. bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
  1545. } else if (codePoint < 0x110000) {
  1546. if ((units -= 4) < 0) break;
  1547. bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
  1548. } else {
  1549. throw new Error('Invalid code point');
  1550. }
  1551. }
  1552. return bytes;
  1553. }
  1554. function asciiToBytes(str) {
  1555. var byteArray = [];
  1556. for (var i = 0; i < str.length; ++i) {
  1557. // Node's code seems to be doing this and not & 0x7F..
  1558. byteArray.push(str.charCodeAt(i) & 0xFF);
  1559. }
  1560. return byteArray;
  1561. }
  1562. function utf16leToBytes(str, units) {
  1563. var c, hi, lo;
  1564. var byteArray = [];
  1565. for (var i = 0; i < str.length; ++i) {
  1566. if ((units -= 2) < 0) break;
  1567. c = str.charCodeAt(i);
  1568. hi = c >> 8;
  1569. lo = c % 256;
  1570. byteArray.push(lo);
  1571. byteArray.push(hi);
  1572. }
  1573. return byteArray;
  1574. }
  1575. function base64ToBytes(str) {
  1576. return base64Js.toByteArray(base64clean(str));
  1577. }
  1578. function blitBuffer(src, dst, offset, length) {
  1579. for (var i = 0; i < length; ++i) {
  1580. if (i + offset >= dst.length || i >= src.length) break;
  1581. dst[i + offset] = src[i];
  1582. }
  1583. return i;
  1584. } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  1585. // the `instanceof` check but they should be treated as of that type.
  1586. // See: https://github.com/feross/buffer/issues/166
  1587. function isInstance(obj, type) {
  1588. return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
  1589. }
  1590. function numberIsNaN(obj) {
  1591. // For IE11 support
  1592. return obj !== obj; // eslint-disable-line no-self-compare
  1593. } // Create lookup table for `toString('hex')`
  1594. // See: https://github.com/feross/buffer/issues/219
  1595. var hexSliceLookupTable = function () {
  1596. var alphabet = '0123456789abcdef';
  1597. var table = new Array(256);
  1598. for (var i = 0; i < 16; ++i) {
  1599. var i16 = i * 16;
  1600. for (var j = 0; j < 16; ++j) {
  1601. table[i16 + j] = alphabet[i] + alphabet[j];
  1602. }
  1603. }
  1604. return table;
  1605. }();
  1606. });
  1607. var buffer_1 = buffer$1.Buffer;
  1608. buffer$1.SlowBuffer;
  1609. buffer$1.INSPECT_MAX_BYTES;
  1610. buffer$1.kMaxLength;
  1611. /*! *****************************************************************************
  1612. Copyright (c) Microsoft Corporation.
  1613. Permission to use, copy, modify, and/or distribute this software for any
  1614. purpose with or without fee is hereby granted.
  1615. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  1616. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  1617. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  1618. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  1619. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  1620. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  1621. PERFORMANCE OF THIS SOFTWARE.
  1622. ***************************************************************************** */
  1623. /* global Reflect, Promise */
  1624. var _extendStatics = function extendStatics(d, b) {
  1625. _extendStatics = Object.setPrototypeOf || {
  1626. __proto__: []
  1627. } instanceof Array && function (d, b) {
  1628. d.__proto__ = b;
  1629. } || function (d, b) {
  1630. for (var p in b) {
  1631. if (b.hasOwnProperty(p)) d[p] = b[p];
  1632. }
  1633. };
  1634. return _extendStatics(d, b);
  1635. };
  1636. function __extends(d, b) {
  1637. _extendStatics(d, b);
  1638. function __() {
  1639. this.constructor = d;
  1640. }
  1641. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1642. }
  1643. var _assign = function __assign() {
  1644. _assign = Object.assign || function __assign(t) {
  1645. for (var s, i = 1, n = arguments.length; i < n; i++) {
  1646. s = arguments[i];
  1647. for (var p in s) {
  1648. if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  1649. }
  1650. }
  1651. return t;
  1652. };
  1653. return _assign.apply(this, arguments);
  1654. };
  1655. /** @public */
  1656. var BSONError = /** @class */ (function (_super) {
  1657. __extends(BSONError, _super);
  1658. function BSONError(message) {
  1659. var _this = _super.call(this, message) || this;
  1660. Object.setPrototypeOf(_this, BSONError.prototype);
  1661. return _this;
  1662. }
  1663. Object.defineProperty(BSONError.prototype, "name", {
  1664. get: function () {
  1665. return 'BSONError';
  1666. },
  1667. enumerable: false,
  1668. configurable: true
  1669. });
  1670. return BSONError;
  1671. }(Error));
  1672. /** @public */
  1673. var BSONTypeError = /** @class */ (function (_super) {
  1674. __extends(BSONTypeError, _super);
  1675. function BSONTypeError(message) {
  1676. var _this = _super.call(this, message) || this;
  1677. Object.setPrototypeOf(_this, BSONTypeError.prototype);
  1678. return _this;
  1679. }
  1680. Object.defineProperty(BSONTypeError.prototype, "name", {
  1681. get: function () {
  1682. return 'BSONTypeError';
  1683. },
  1684. enumerable: false,
  1685. configurable: true
  1686. });
  1687. return BSONTypeError;
  1688. }(TypeError));
  1689. function checkForMath(potentialGlobal) {
  1690. // eslint-disable-next-line eqeqeq
  1691. return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal;
  1692. }
  1693. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  1694. function getGlobal() {
  1695. // eslint-disable-next-line no-undef
  1696. return (checkForMath(typeof globalThis === 'object' && globalThis) ||
  1697. checkForMath(typeof window === 'object' && window) ||
  1698. checkForMath(typeof self === 'object' && self) ||
  1699. checkForMath(typeof global === 'object' && global) ||
  1700. Function('return this')());
  1701. }
  1702. /**
  1703. * Normalizes our expected stringified form of a function across versions of node
  1704. * @param fn - The function to stringify
  1705. */
  1706. function normalizedFunctionString(fn) {
  1707. return fn.toString().replace('function(', 'function (');
  1708. }
  1709. function isReactNative() {
  1710. var g = getGlobal();
  1711. return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative';
  1712. }
  1713. var insecureRandomBytes = function insecureRandomBytes(size) {
  1714. var insecureWarning = isReactNative()
  1715. ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'
  1716. : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.';
  1717. console.warn(insecureWarning);
  1718. var result = buffer_1.alloc(size);
  1719. for (var i = 0; i < size; ++i)
  1720. result[i] = Math.floor(Math.random() * 256);
  1721. return result;
  1722. };
  1723. var detectRandomBytes = function () {
  1724. if (typeof window !== 'undefined') {
  1725. // browser crypto implementation(s)
  1726. var target_1 = window.crypto || window.msCrypto; // allow for IE11
  1727. if (target_1 && target_1.getRandomValues) {
  1728. return function (size) { return target_1.getRandomValues(buffer_1.alloc(size)); };
  1729. }
  1730. }
  1731. if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) {
  1732. // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global
  1733. return function (size) { return global.crypto.getRandomValues(buffer_1.alloc(size)); };
  1734. }
  1735. var requiredRandomBytes;
  1736. try {
  1737. // eslint-disable-next-line @typescript-eslint/no-var-requires
  1738. requiredRandomBytes = require('crypto').randomBytes;
  1739. }
  1740. catch (e) {
  1741. // keep the fallback
  1742. }
  1743. // NOTE: in transpiled cases the above require might return null/undefined
  1744. return requiredRandomBytes || insecureRandomBytes;
  1745. };
  1746. var randomBytes = detectRandomBytes();
  1747. function isAnyArrayBuffer(value) {
  1748. return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value));
  1749. }
  1750. function isUint8Array(value) {
  1751. return Object.prototype.toString.call(value) === '[object Uint8Array]';
  1752. }
  1753. function isBigInt64Array(value) {
  1754. return Object.prototype.toString.call(value) === '[object BigInt64Array]';
  1755. }
  1756. function isBigUInt64Array(value) {
  1757. return Object.prototype.toString.call(value) === '[object BigUint64Array]';
  1758. }
  1759. function isRegExp(d) {
  1760. return Object.prototype.toString.call(d) === '[object RegExp]';
  1761. }
  1762. function isMap(d) {
  1763. return Object.prototype.toString.call(d) === '[object Map]';
  1764. }
  1765. // To ensure that 0.4 of node works correctly
  1766. function isDate(d) {
  1767. return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]';
  1768. }
  1769. /**
  1770. * @internal
  1771. * this is to solve the `'someKey' in x` problem where x is unknown.
  1772. * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753
  1773. */
  1774. function isObjectLike(candidate) {
  1775. return typeof candidate === 'object' && candidate !== null;
  1776. }
  1777. function deprecate(fn, message) {
  1778. var warned = false;
  1779. function deprecated() {
  1780. var args = [];
  1781. for (var _i = 0; _i < arguments.length; _i++) {
  1782. args[_i] = arguments[_i];
  1783. }
  1784. if (!warned) {
  1785. console.warn(message);
  1786. warned = true;
  1787. }
  1788. return fn.apply(this, args);
  1789. }
  1790. return deprecated;
  1791. }
  1792. /**
  1793. * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
  1794. *
  1795. * @param potentialBuffer - The potential buffer
  1796. * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
  1797. * wraps a passed in Uint8Array
  1798. * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in
  1799. */
  1800. function ensureBuffer(potentialBuffer) {
  1801. if (ArrayBuffer.isView(potentialBuffer)) {
  1802. return buffer_1.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
  1803. }
  1804. if (isAnyArrayBuffer(potentialBuffer)) {
  1805. return buffer_1.from(potentialBuffer);
  1806. }
  1807. throw new BSONTypeError('Must use either Buffer or TypedArray');
  1808. }
  1809. // Validation regex for v4 uuid (validates with or without dashes)
  1810. var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;
  1811. var uuidValidateString = function (str) {
  1812. return typeof str === 'string' && VALIDATION_REGEX.test(str);
  1813. };
  1814. var uuidHexStringToBuffer = function (hexString) {
  1815. if (!uuidValidateString(hexString)) {
  1816. throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".');
  1817. }
  1818. var sanitizedHexString = hexString.replace(/-/g, '');
  1819. return buffer_1.from(sanitizedHexString, 'hex');
  1820. };
  1821. var bufferToUuidHexString = function (buffer, includeDashes) {
  1822. if (includeDashes === void 0) { includeDashes = true; }
  1823. return includeDashes
  1824. ? buffer.toString('hex', 0, 4) +
  1825. '-' +
  1826. buffer.toString('hex', 4, 6) +
  1827. '-' +
  1828. buffer.toString('hex', 6, 8) +
  1829. '-' +
  1830. buffer.toString('hex', 8, 10) +
  1831. '-' +
  1832. buffer.toString('hex', 10, 16)
  1833. : buffer.toString('hex');
  1834. };
  1835. var BYTE_LENGTH = 16;
  1836. var kId$1 = Symbol('id');
  1837. /**
  1838. * A class representation of the BSON UUID type.
  1839. * @public
  1840. */
  1841. var UUID = /** @class */ (function () {
  1842. /**
  1843. * Create an UUID type
  1844. *
  1845. * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
  1846. */
  1847. function UUID(input) {
  1848. if (typeof input === 'undefined') {
  1849. // The most common use case (blank id, new UUID() instance)
  1850. this.id = UUID.generate();
  1851. }
  1852. else if (input instanceof UUID) {
  1853. this[kId$1] = buffer_1.from(input.id);
  1854. this.__id = input.__id;
  1855. }
  1856. else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) {
  1857. this.id = ensureBuffer(input);
  1858. }
  1859. else if (typeof input === 'string') {
  1860. this.id = uuidHexStringToBuffer(input);
  1861. }
  1862. else {
  1863. throw new BSONTypeError('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).');
  1864. }
  1865. }
  1866. Object.defineProperty(UUID.prototype, "id", {
  1867. /**
  1868. * The UUID bytes
  1869. * @readonly
  1870. */
  1871. get: function () {
  1872. return this[kId$1];
  1873. },
  1874. set: function (value) {
  1875. this[kId$1] = value;
  1876. if (UUID.cacheHexString) {
  1877. this.__id = bufferToUuidHexString(value);
  1878. }
  1879. },
  1880. enumerable: false,
  1881. configurable: true
  1882. });
  1883. /**
  1884. * Generate a 16 byte uuid v4 buffer used in UUIDs
  1885. */
  1886. /**
  1887. * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
  1888. * @param includeDashes - should the string exclude dash-separators.
  1889. * */
  1890. UUID.prototype.toHexString = function (includeDashes) {
  1891. if (includeDashes === void 0) { includeDashes = true; }
  1892. if (UUID.cacheHexString && this.__id) {
  1893. return this.__id;
  1894. }
  1895. var uuidHexString = bufferToUuidHexString(this.id, includeDashes);
  1896. if (UUID.cacheHexString) {
  1897. this.__id = uuidHexString;
  1898. }
  1899. return uuidHexString;
  1900. };
  1901. /**
  1902. * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
  1903. */
  1904. UUID.prototype.toString = function (encoding) {
  1905. return encoding ? this.id.toString(encoding) : this.toHexString();
  1906. };
  1907. /**
  1908. * Converts the id into its JSON string representation.
  1909. * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  1910. */
  1911. UUID.prototype.toJSON = function () {
  1912. return this.toHexString();
  1913. };
  1914. /**
  1915. * Compares the equality of this UUID with `otherID`.
  1916. *
  1917. * @param otherId - UUID instance to compare against.
  1918. */
  1919. UUID.prototype.equals = function (otherId) {
  1920. if (!otherId) {
  1921. return false;
  1922. }
  1923. if (otherId instanceof UUID) {
  1924. return otherId.id.equals(this.id);
  1925. }
  1926. try {
  1927. return new UUID(otherId).id.equals(this.id);
  1928. }
  1929. catch (_a) {
  1930. return false;
  1931. }
  1932. };
  1933. /**
  1934. * Creates a Binary instance from the current UUID.
  1935. */
  1936. UUID.prototype.toBinary = function () {
  1937. return new Binary(this.id, Binary.SUBTYPE_UUID);
  1938. };
  1939. /**
  1940. * Generates a populated buffer containing a v4 uuid
  1941. */
  1942. UUID.generate = function () {
  1943. var bytes = randomBytes(BYTE_LENGTH);
  1944. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  1945. // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js
  1946. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  1947. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  1948. return buffer_1.from(bytes);
  1949. };
  1950. /**
  1951. * Checks if a value is a valid bson UUID
  1952. * @param input - UUID, string or Buffer to validate.
  1953. */
  1954. UUID.isValid = function (input) {
  1955. if (!input) {
  1956. return false;
  1957. }
  1958. if (input instanceof UUID) {
  1959. return true;
  1960. }
  1961. if (typeof input === 'string') {
  1962. return uuidValidateString(input);
  1963. }
  1964. if (isUint8Array(input)) {
  1965. // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3)
  1966. if (input.length !== BYTE_LENGTH) {
  1967. return false;
  1968. }
  1969. try {
  1970. // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx
  1971. // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx
  1972. return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID;
  1973. }
  1974. catch (_a) {
  1975. return false;
  1976. }
  1977. }
  1978. return false;
  1979. };
  1980. /**
  1981. * Creates an UUID from a hex string representation of an UUID.
  1982. * @param hexString - 32 or 36 character hex string (dashes excluded/included).
  1983. */
  1984. UUID.createFromHexString = function (hexString) {
  1985. var buffer = uuidHexStringToBuffer(hexString);
  1986. return new UUID(buffer);
  1987. };
  1988. /**
  1989. * Converts to a string representation of this Id.
  1990. *
  1991. * @returns return the 36 character hex string representation.
  1992. * @internal
  1993. */
  1994. UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  1995. return this.inspect();
  1996. };
  1997. UUID.prototype.inspect = function () {
  1998. return "new UUID(\"" + this.toHexString() + "\")";
  1999. };
  2000. return UUID;
  2001. }());
  2002. Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' });
  2003. /**
  2004. * A class representation of the BSON Binary type.
  2005. * @public
  2006. * @category BSONType
  2007. */
  2008. var Binary = /** @class */ (function () {
  2009. /**
  2010. * @param buffer - a buffer object containing the binary data.
  2011. * @param subType - the option binary type.
  2012. */
  2013. function Binary(buffer, subType) {
  2014. if (!(this instanceof Binary))
  2015. return new Binary(buffer, subType);
  2016. if (!(buffer == null) &&
  2017. !(typeof buffer === 'string') &&
  2018. !ArrayBuffer.isView(buffer) &&
  2019. !(buffer instanceof ArrayBuffer) &&
  2020. !Array.isArray(buffer)) {
  2021. throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
  2022. }
  2023. this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT;
  2024. if (buffer == null) {
  2025. // create an empty binary buffer
  2026. this.buffer = buffer_1.alloc(Binary.BUFFER_SIZE);
  2027. this.position = 0;
  2028. }
  2029. else {
  2030. if (typeof buffer === 'string') {
  2031. // string
  2032. this.buffer = buffer_1.from(buffer, 'binary');
  2033. }
  2034. else if (Array.isArray(buffer)) {
  2035. // number[]
  2036. this.buffer = buffer_1.from(buffer);
  2037. }
  2038. else {
  2039. // Buffer | TypedArray | ArrayBuffer
  2040. this.buffer = ensureBuffer(buffer);
  2041. }
  2042. this.position = this.buffer.byteLength;
  2043. }
  2044. }
  2045. /**
  2046. * Updates this binary with byte_value.
  2047. *
  2048. * @param byteValue - a single byte we wish to write.
  2049. */
  2050. Binary.prototype.put = function (byteValue) {
  2051. // If it's a string and a has more than one character throw an error
  2052. if (typeof byteValue === 'string' && byteValue.length !== 1) {
  2053. throw new BSONTypeError('only accepts single character String');
  2054. }
  2055. else if (typeof byteValue !== 'number' && byteValue.length !== 1)
  2056. throw new BSONTypeError('only accepts single character Uint8Array or Array');
  2057. // Decode the byte value once
  2058. var decodedByte;
  2059. if (typeof byteValue === 'string') {
  2060. decodedByte = byteValue.charCodeAt(0);
  2061. }
  2062. else if (typeof byteValue === 'number') {
  2063. decodedByte = byteValue;
  2064. }
  2065. else {
  2066. decodedByte = byteValue[0];
  2067. }
  2068. if (decodedByte < 0 || decodedByte > 255) {
  2069. throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255');
  2070. }
  2071. if (this.buffer.length > this.position) {
  2072. this.buffer[this.position++] = decodedByte;
  2073. }
  2074. else {
  2075. var buffer = buffer_1.alloc(Binary.BUFFER_SIZE + this.buffer.length);
  2076. // Combine the two buffers together
  2077. this.buffer.copy(buffer, 0, 0, this.buffer.length);
  2078. this.buffer = buffer;
  2079. this.buffer[this.position++] = decodedByte;
  2080. }
  2081. };
  2082. /**
  2083. * Writes a buffer or string to the binary.
  2084. *
  2085. * @param sequence - a string or buffer to be written to the Binary BSON object.
  2086. * @param offset - specify the binary of where to write the content.
  2087. */
  2088. Binary.prototype.write = function (sequence, offset) {
  2089. offset = typeof offset === 'number' ? offset : this.position;
  2090. // If the buffer is to small let's extend the buffer
  2091. if (this.buffer.length < offset + sequence.length) {
  2092. var buffer = buffer_1.alloc(this.buffer.length + sequence.length);
  2093. this.buffer.copy(buffer, 0, 0, this.buffer.length);
  2094. // Assign the new buffer
  2095. this.buffer = buffer;
  2096. }
  2097. if (ArrayBuffer.isView(sequence)) {
  2098. this.buffer.set(ensureBuffer(sequence), offset);
  2099. this.position =
  2100. offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
  2101. }
  2102. else if (typeof sequence === 'string') {
  2103. this.buffer.write(sequence, offset, sequence.length, 'binary');
  2104. this.position =
  2105. offset + sequence.length > this.position ? offset + sequence.length : this.position;
  2106. }
  2107. };
  2108. /**
  2109. * Reads **length** bytes starting at **position**.
  2110. *
  2111. * @param position - read from the given position in the Binary.
  2112. * @param length - the number of bytes to read.
  2113. */
  2114. Binary.prototype.read = function (position, length) {
  2115. length = length && length > 0 ? length : this.position;
  2116. // Let's return the data based on the type we have
  2117. return this.buffer.slice(position, position + length);
  2118. };
  2119. /**
  2120. * Returns the value of this binary as a string.
  2121. * @param asRaw - Will skip converting to a string
  2122. * @remarks
  2123. * This is handy when calling this function conditionally for some key value pairs and not others
  2124. */
  2125. Binary.prototype.value = function (asRaw) {
  2126. asRaw = !!asRaw;
  2127. // Optimize to serialize for the situation where the data == size of buffer
  2128. if (asRaw && this.buffer.length === this.position) {
  2129. return this.buffer;
  2130. }
  2131. // If it's a node.js buffer object
  2132. if (asRaw) {
  2133. return this.buffer.slice(0, this.position);
  2134. }
  2135. return this.buffer.toString('binary', 0, this.position);
  2136. };
  2137. /** the length of the binary sequence */
  2138. Binary.prototype.length = function () {
  2139. return this.position;
  2140. };
  2141. Binary.prototype.toJSON = function () {
  2142. return this.buffer.toString('base64');
  2143. };
  2144. Binary.prototype.toString = function (format) {
  2145. return this.buffer.toString(format);
  2146. };
  2147. /** @internal */
  2148. Binary.prototype.toExtendedJSON = function (options) {
  2149. options = options || {};
  2150. var base64String = this.buffer.toString('base64');
  2151. var subType = Number(this.sub_type).toString(16);
  2152. if (options.legacy) {
  2153. return {
  2154. $binary: base64String,
  2155. $type: subType.length === 1 ? '0' + subType : subType
  2156. };
  2157. }
  2158. return {
  2159. $binary: {
  2160. base64: base64String,
  2161. subType: subType.length === 1 ? '0' + subType : subType
  2162. }
  2163. };
  2164. };
  2165. Binary.prototype.toUUID = function () {
  2166. if (this.sub_type === Binary.SUBTYPE_UUID) {
  2167. return new UUID(this.buffer.slice(0, this.position));
  2168. }
  2169. throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
  2170. };
  2171. /** @internal */
  2172. Binary.fromExtendedJSON = function (doc, options) {
  2173. options = options || {};
  2174. var data;
  2175. var type;
  2176. if ('$binary' in doc) {
  2177. if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
  2178. type = doc.$type ? parseInt(doc.$type, 16) : 0;
  2179. data = buffer_1.from(doc.$binary, 'base64');
  2180. }
  2181. else {
  2182. if (typeof doc.$binary !== 'string') {
  2183. type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  2184. data = buffer_1.from(doc.$binary.base64, 'base64');
  2185. }
  2186. }
  2187. }
  2188. else if ('$uuid' in doc) {
  2189. type = 4;
  2190. data = uuidHexStringToBuffer(doc.$uuid);
  2191. }
  2192. if (!data) {
  2193. throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
  2194. }
  2195. return new Binary(data, type);
  2196. };
  2197. /** @internal */
  2198. Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2199. return this.inspect();
  2200. };
  2201. Binary.prototype.inspect = function () {
  2202. var asBuffer = this.value(true);
  2203. return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")";
  2204. };
  2205. /**
  2206. * Binary default subtype
  2207. * @internal
  2208. */
  2209. Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
  2210. /** Initial buffer default size */
  2211. Binary.BUFFER_SIZE = 256;
  2212. /** Default BSON type */
  2213. Binary.SUBTYPE_DEFAULT = 0;
  2214. /** Function BSON type */
  2215. Binary.SUBTYPE_FUNCTION = 1;
  2216. /** Byte Array BSON type */
  2217. Binary.SUBTYPE_BYTE_ARRAY = 2;
  2218. /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
  2219. Binary.SUBTYPE_UUID_OLD = 3;
  2220. /** UUID BSON type */
  2221. Binary.SUBTYPE_UUID = 4;
  2222. /** MD5 BSON type */
  2223. Binary.SUBTYPE_MD5 = 5;
  2224. /** Encrypted BSON type */
  2225. Binary.SUBTYPE_ENCRYPTED = 6;
  2226. /** Column BSON type */
  2227. Binary.SUBTYPE_COLUMN = 7;
  2228. /** User BSON type */
  2229. Binary.SUBTYPE_USER_DEFINED = 128;
  2230. return Binary;
  2231. }());
  2232. Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' });
  2233. /**
  2234. * A class representation of the BSON Code type.
  2235. * @public
  2236. * @category BSONType
  2237. */
  2238. var Code = /** @class */ (function () {
  2239. /**
  2240. * @param code - a string or function.
  2241. * @param scope - an optional scope for the function.
  2242. */
  2243. function Code(code, scope) {
  2244. if (!(this instanceof Code))
  2245. return new Code(code, scope);
  2246. this.code = code;
  2247. this.scope = scope;
  2248. }
  2249. Code.prototype.toJSON = function () {
  2250. return { code: this.code, scope: this.scope };
  2251. };
  2252. /** @internal */
  2253. Code.prototype.toExtendedJSON = function () {
  2254. if (this.scope) {
  2255. return { $code: this.code, $scope: this.scope };
  2256. }
  2257. return { $code: this.code };
  2258. };
  2259. /** @internal */
  2260. Code.fromExtendedJSON = function (doc) {
  2261. return new Code(doc.$code, doc.$scope);
  2262. };
  2263. /** @internal */
  2264. Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2265. return this.inspect();
  2266. };
  2267. Code.prototype.inspect = function () {
  2268. var codeJson = this.toJSON();
  2269. return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")";
  2270. };
  2271. return Code;
  2272. }());
  2273. Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' });
  2274. /** @internal */
  2275. function isDBRefLike(value) {
  2276. return (isObjectLike(value) &&
  2277. value.$id != null &&
  2278. typeof value.$ref === 'string' &&
  2279. (value.$db == null || typeof value.$db === 'string'));
  2280. }
  2281. /**
  2282. * A class representation of the BSON DBRef type.
  2283. * @public
  2284. * @category BSONType
  2285. */
  2286. var DBRef = /** @class */ (function () {
  2287. /**
  2288. * @param collection - the collection name.
  2289. * @param oid - the reference ObjectId.
  2290. * @param db - optional db name, if omitted the reference is local to the current db.
  2291. */
  2292. function DBRef(collection, oid, db, fields) {
  2293. if (!(this instanceof DBRef))
  2294. return new DBRef(collection, oid, db, fields);
  2295. // check if namespace has been provided
  2296. var parts = collection.split('.');
  2297. if (parts.length === 2) {
  2298. db = parts.shift();
  2299. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  2300. collection = parts.shift();
  2301. }
  2302. this.collection = collection;
  2303. this.oid = oid;
  2304. this.db = db;
  2305. this.fields = fields || {};
  2306. }
  2307. Object.defineProperty(DBRef.prototype, "namespace", {
  2308. // Property provided for compatibility with the 1.x parser
  2309. // the 1.x parser used a "namespace" property, while 4.x uses "collection"
  2310. /** @internal */
  2311. get: function () {
  2312. return this.collection;
  2313. },
  2314. set: function (value) {
  2315. this.collection = value;
  2316. },
  2317. enumerable: false,
  2318. configurable: true
  2319. });
  2320. DBRef.prototype.toJSON = function () {
  2321. var o = Object.assign({
  2322. $ref: this.collection,
  2323. $id: this.oid
  2324. }, this.fields);
  2325. if (this.db != null)
  2326. o.$db = this.db;
  2327. return o;
  2328. };
  2329. /** @internal */
  2330. DBRef.prototype.toExtendedJSON = function (options) {
  2331. options = options || {};
  2332. var o = {
  2333. $ref: this.collection,
  2334. $id: this.oid
  2335. };
  2336. if (options.legacy) {
  2337. return o;
  2338. }
  2339. if (this.db)
  2340. o.$db = this.db;
  2341. o = Object.assign(o, this.fields);
  2342. return o;
  2343. };
  2344. /** @internal */
  2345. DBRef.fromExtendedJSON = function (doc) {
  2346. var copy = Object.assign({}, doc);
  2347. delete copy.$ref;
  2348. delete copy.$id;
  2349. delete copy.$db;
  2350. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  2351. };
  2352. /** @internal */
  2353. DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2354. return this.inspect();
  2355. };
  2356. DBRef.prototype.inspect = function () {
  2357. // NOTE: if OID is an ObjectId class it will just print the oid string.
  2358. var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
  2359. return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")";
  2360. };
  2361. return DBRef;
  2362. }());
  2363. Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' });
  2364. /**
  2365. * wasm optimizations, to do native i64 multiplication and divide
  2366. */
  2367. var wasm = undefined;
  2368. try {
  2369. wasm = new WebAssembly.Instance(new WebAssembly.Module(
  2370. // prettier-ignore
  2371. 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;
  2372. }
  2373. catch (_a) {
  2374. // no wasm support
  2375. }
  2376. var TWO_PWR_16_DBL = 1 << 16;
  2377. var TWO_PWR_24_DBL = 1 << 24;
  2378. var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  2379. var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  2380. var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  2381. /** A cache of the Long representations of small integer values. */
  2382. var INT_CACHE = {};
  2383. /** A cache of the Long representations of small unsigned integer values. */
  2384. var UINT_CACHE = {};
  2385. /**
  2386. * A class representing a 64-bit integer
  2387. * @public
  2388. * @category BSONType
  2389. * @remarks
  2390. * The internal representation of a long is the two given signed, 32-bit values.
  2391. * We use 32-bit pieces because these are the size of integers on which
  2392. * Javascript performs bit-operations. For operations like addition and
  2393. * multiplication, we split each number into 16 bit pieces, which can easily be
  2394. * multiplied within Javascript's floating-point representation without overflow
  2395. * or change in sign.
  2396. * In the algorithms below, we frequently reduce the negative case to the
  2397. * positive case by negating the input(s) and then post-processing the result.
  2398. * Note that we must ALWAYS check specially whether those values are MIN_VALUE
  2399. * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
  2400. * a positive number, it overflows back into a negative). Not handling this
  2401. * case would often result in infinite recursion.
  2402. * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
  2403. */
  2404. var Long = /** @class */ (function () {
  2405. /**
  2406. * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
  2407. * See the from* functions below for more convenient ways of constructing Longs.
  2408. *
  2409. * Acceptable signatures are:
  2410. * - Long(low, high, unsigned?)
  2411. * - Long(bigint, unsigned?)
  2412. * - Long(string, unsigned?)
  2413. *
  2414. * @param low - The low (signed) 32 bits of the long
  2415. * @param high - The high (signed) 32 bits of the long
  2416. * @param unsigned - Whether unsigned or not, defaults to signed
  2417. */
  2418. function Long(low, high, unsigned) {
  2419. if (low === void 0) { low = 0; }
  2420. if (!(this instanceof Long))
  2421. return new Long(low, high, unsigned);
  2422. if (typeof low === 'bigint') {
  2423. Object.assign(this, Long.fromBigInt(low, !!high));
  2424. }
  2425. else if (typeof low === 'string') {
  2426. Object.assign(this, Long.fromString(low, !!high));
  2427. }
  2428. else {
  2429. this.low = low | 0;
  2430. this.high = high | 0;
  2431. this.unsigned = !!unsigned;
  2432. }
  2433. Object.defineProperty(this, '__isLong__', {
  2434. value: true,
  2435. configurable: false,
  2436. writable: false,
  2437. enumerable: false
  2438. });
  2439. }
  2440. /**
  2441. * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.
  2442. * Each is assumed to use 32 bits.
  2443. * @param lowBits - The low 32 bits
  2444. * @param highBits - The high 32 bits
  2445. * @param unsigned - Whether unsigned or not, defaults to signed
  2446. * @returns The corresponding Long value
  2447. */
  2448. Long.fromBits = function (lowBits, highBits, unsigned) {
  2449. return new Long(lowBits, highBits, unsigned);
  2450. };
  2451. /**
  2452. * Returns a Long representing the given 32 bit integer value.
  2453. * @param value - The 32 bit integer in question
  2454. * @param unsigned - Whether unsigned or not, defaults to signed
  2455. * @returns The corresponding Long value
  2456. */
  2457. Long.fromInt = function (value, unsigned) {
  2458. var obj, cachedObj, cache;
  2459. if (unsigned) {
  2460. value >>>= 0;
  2461. if ((cache = 0 <= value && value < 256)) {
  2462. cachedObj = UINT_CACHE[value];
  2463. if (cachedObj)
  2464. return cachedObj;
  2465. }
  2466. obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  2467. if (cache)
  2468. UINT_CACHE[value] = obj;
  2469. return obj;
  2470. }
  2471. else {
  2472. value |= 0;
  2473. if ((cache = -128 <= value && value < 128)) {
  2474. cachedObj = INT_CACHE[value];
  2475. if (cachedObj)
  2476. return cachedObj;
  2477. }
  2478. obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
  2479. if (cache)
  2480. INT_CACHE[value] = obj;
  2481. return obj;
  2482. }
  2483. };
  2484. /**
  2485. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  2486. * @param value - The number in question
  2487. * @param unsigned - Whether unsigned or not, defaults to signed
  2488. * @returns The corresponding Long value
  2489. */
  2490. Long.fromNumber = function (value, unsigned) {
  2491. if (isNaN(value))
  2492. return unsigned ? Long.UZERO : Long.ZERO;
  2493. if (unsigned) {
  2494. if (value < 0)
  2495. return Long.UZERO;
  2496. if (value >= TWO_PWR_64_DBL)
  2497. return Long.MAX_UNSIGNED_VALUE;
  2498. }
  2499. else {
  2500. if (value <= -TWO_PWR_63_DBL)
  2501. return Long.MIN_VALUE;
  2502. if (value + 1 >= TWO_PWR_63_DBL)
  2503. return Long.MAX_VALUE;
  2504. }
  2505. if (value < 0)
  2506. return Long.fromNumber(-value, unsigned).neg();
  2507. return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  2508. };
  2509. /**
  2510. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  2511. * @param value - The number in question
  2512. * @param unsigned - Whether unsigned or not, defaults to signed
  2513. * @returns The corresponding Long value
  2514. */
  2515. Long.fromBigInt = function (value, unsigned) {
  2516. return Long.fromString(value.toString(), unsigned);
  2517. };
  2518. /**
  2519. * Returns a Long representation of the given string, written using the specified radix.
  2520. * @param str - The textual representation of the Long
  2521. * @param unsigned - Whether unsigned or not, defaults to signed
  2522. * @param radix - The radix in which the text is written (2-36), defaults to 10
  2523. * @returns The corresponding Long value
  2524. */
  2525. Long.fromString = function (str, unsigned, radix) {
  2526. if (str.length === 0)
  2527. throw Error('empty string');
  2528. if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity')
  2529. return Long.ZERO;
  2530. if (typeof unsigned === 'number') {
  2531. // For goog.math.long compatibility
  2532. (radix = unsigned), (unsigned = false);
  2533. }
  2534. else {
  2535. unsigned = !!unsigned;
  2536. }
  2537. radix = radix || 10;
  2538. if (radix < 2 || 36 < radix)
  2539. throw RangeError('radix');
  2540. var p;
  2541. if ((p = str.indexOf('-')) > 0)
  2542. throw Error('interior hyphen');
  2543. else if (p === 0) {
  2544. return Long.fromString(str.substring(1), unsigned, radix).neg();
  2545. }
  2546. // Do several (8) digits each time through the loop, so as to
  2547. // minimize the calls to the very expensive emulated div.
  2548. var radixToPower = Long.fromNumber(Math.pow(radix, 8));
  2549. var result = Long.ZERO;
  2550. for (var i = 0; i < str.length; i += 8) {
  2551. var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
  2552. if (size < 8) {
  2553. var power = Long.fromNumber(Math.pow(radix, size));
  2554. result = result.mul(power).add(Long.fromNumber(value));
  2555. }
  2556. else {
  2557. result = result.mul(radixToPower);
  2558. result = result.add(Long.fromNumber(value));
  2559. }
  2560. }
  2561. result.unsigned = unsigned;
  2562. return result;
  2563. };
  2564. /**
  2565. * Creates a Long from its byte representation.
  2566. * @param bytes - Byte representation
  2567. * @param unsigned - Whether unsigned or not, defaults to signed
  2568. * @param le - Whether little or big endian, defaults to big endian
  2569. * @returns The corresponding Long value
  2570. */
  2571. Long.fromBytes = function (bytes, unsigned, le) {
  2572. return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
  2573. };
  2574. /**
  2575. * Creates a Long from its little endian byte representation.
  2576. * @param bytes - Little endian byte representation
  2577. * @param unsigned - Whether unsigned or not, defaults to signed
  2578. * @returns The corresponding Long value
  2579. */
  2580. Long.fromBytesLE = function (bytes, unsigned) {
  2581. 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);
  2582. };
  2583. /**
  2584. * Creates a Long from its big endian byte representation.
  2585. * @param bytes - Big endian byte representation
  2586. * @param unsigned - Whether unsigned or not, defaults to signed
  2587. * @returns The corresponding Long value
  2588. */
  2589. Long.fromBytesBE = function (bytes, unsigned) {
  2590. 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);
  2591. };
  2592. /**
  2593. * Tests if the specified object is a Long.
  2594. */
  2595. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  2596. Long.isLong = function (value) {
  2597. return isObjectLike(value) && value['__isLong__'] === true;
  2598. };
  2599. /**
  2600. * Converts the specified value to a Long.
  2601. * @param unsigned - Whether unsigned or not, defaults to signed
  2602. */
  2603. Long.fromValue = function (val, unsigned) {
  2604. if (typeof val === 'number')
  2605. return Long.fromNumber(val, unsigned);
  2606. if (typeof val === 'string')
  2607. return Long.fromString(val, unsigned);
  2608. // Throws for non-objects, converts non-instanceof Long:
  2609. return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
  2610. };
  2611. /** Returns the sum of this and the specified Long. */
  2612. Long.prototype.add = function (addend) {
  2613. if (!Long.isLong(addend))
  2614. addend = Long.fromValue(addend);
  2615. // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
  2616. var a48 = this.high >>> 16;
  2617. var a32 = this.high & 0xffff;
  2618. var a16 = this.low >>> 16;
  2619. var a00 = this.low & 0xffff;
  2620. var b48 = addend.high >>> 16;
  2621. var b32 = addend.high & 0xffff;
  2622. var b16 = addend.low >>> 16;
  2623. var b00 = addend.low & 0xffff;
  2624. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  2625. c00 += a00 + b00;
  2626. c16 += c00 >>> 16;
  2627. c00 &= 0xffff;
  2628. c16 += a16 + b16;
  2629. c32 += c16 >>> 16;
  2630. c16 &= 0xffff;
  2631. c32 += a32 + b32;
  2632. c48 += c32 >>> 16;
  2633. c32 &= 0xffff;
  2634. c48 += a48 + b48;
  2635. c48 &= 0xffff;
  2636. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  2637. };
  2638. /**
  2639. * Returns the sum of this and the specified Long.
  2640. * @returns Sum
  2641. */
  2642. Long.prototype.and = function (other) {
  2643. if (!Long.isLong(other))
  2644. other = Long.fromValue(other);
  2645. return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  2646. };
  2647. /**
  2648. * Compares this Long's value with the specified's.
  2649. * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
  2650. */
  2651. Long.prototype.compare = function (other) {
  2652. if (!Long.isLong(other))
  2653. other = Long.fromValue(other);
  2654. if (this.eq(other))
  2655. return 0;
  2656. var thisNeg = this.isNegative(), otherNeg = other.isNegative();
  2657. if (thisNeg && !otherNeg)
  2658. return -1;
  2659. if (!thisNeg && otherNeg)
  2660. return 1;
  2661. // At this point the sign bits are the same
  2662. if (!this.unsigned)
  2663. return this.sub(other).isNegative() ? -1 : 1;
  2664. // Both are positive if at least one is unsigned
  2665. return other.high >>> 0 > this.high >>> 0 ||
  2666. (other.high === this.high && other.low >>> 0 > this.low >>> 0)
  2667. ? -1
  2668. : 1;
  2669. };
  2670. /** This is an alias of {@link Long.compare} */
  2671. Long.prototype.comp = function (other) {
  2672. return this.compare(other);
  2673. };
  2674. /**
  2675. * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.
  2676. * @returns Quotient
  2677. */
  2678. Long.prototype.divide = function (divisor) {
  2679. if (!Long.isLong(divisor))
  2680. divisor = Long.fromValue(divisor);
  2681. if (divisor.isZero())
  2682. throw Error('division by zero');
  2683. // use wasm support if present
  2684. if (wasm) {
  2685. // guard against signed division overflow: the largest
  2686. // negative number / -1 would be 1 larger than the largest
  2687. // positive number, due to two's complement.
  2688. if (!this.unsigned &&
  2689. this.high === -0x80000000 &&
  2690. divisor.low === -1 &&
  2691. divisor.high === -1) {
  2692. // be consistent with non-wasm code path
  2693. return this;
  2694. }
  2695. var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
  2696. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  2697. }
  2698. if (this.isZero())
  2699. return this.unsigned ? Long.UZERO : Long.ZERO;
  2700. var approx, rem, res;
  2701. if (!this.unsigned) {
  2702. // This section is only relevant for signed longs and is derived from the
  2703. // closure library as a whole.
  2704. if (this.eq(Long.MIN_VALUE)) {
  2705. if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
  2706. return Long.MIN_VALUE;
  2707. // recall that -MIN_VALUE == MIN_VALUE
  2708. else if (divisor.eq(Long.MIN_VALUE))
  2709. return Long.ONE;
  2710. else {
  2711. // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
  2712. var halfThis = this.shr(1);
  2713. approx = halfThis.div(divisor).shl(1);
  2714. if (approx.eq(Long.ZERO)) {
  2715. return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
  2716. }
  2717. else {
  2718. rem = this.sub(divisor.mul(approx));
  2719. res = approx.add(rem.div(divisor));
  2720. return res;
  2721. }
  2722. }
  2723. }
  2724. else if (divisor.eq(Long.MIN_VALUE))
  2725. return this.unsigned ? Long.UZERO : Long.ZERO;
  2726. if (this.isNegative()) {
  2727. if (divisor.isNegative())
  2728. return this.neg().div(divisor.neg());
  2729. return this.neg().div(divisor).neg();
  2730. }
  2731. else if (divisor.isNegative())
  2732. return this.div(divisor.neg()).neg();
  2733. res = Long.ZERO;
  2734. }
  2735. else {
  2736. // The algorithm below has not been made for unsigned longs. It's therefore
  2737. // required to take special care of the MSB prior to running it.
  2738. if (!divisor.unsigned)
  2739. divisor = divisor.toUnsigned();
  2740. if (divisor.gt(this))
  2741. return Long.UZERO;
  2742. if (divisor.gt(this.shru(1)))
  2743. // 15 >>> 1 = 7 ; with divisor = 8 ; true
  2744. return Long.UONE;
  2745. res = Long.UZERO;
  2746. }
  2747. // Repeat the following until the remainder is less than other: find a
  2748. // floating-point that approximates remainder / other *from below*, add this
  2749. // into the result, and subtract it from the remainder. It is critical that
  2750. // the approximate value is less than or equal to the real value so that the
  2751. // remainder never becomes negative.
  2752. rem = this;
  2753. while (rem.gte(divisor)) {
  2754. // Approximate the result of division. This may be a little greater or
  2755. // smaller than the actual value.
  2756. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  2757. // We will tweak the approximate result by changing it in the 48-th digit or
  2758. // the smallest non-fractional digit, whichever is larger.
  2759. var log2 = Math.ceil(Math.log(approx) / Math.LN2);
  2760. var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
  2761. // Decrease the approximation until it is smaller than the remainder. Note
  2762. // that if it is too large, the product overflows and is negative.
  2763. var approxRes = Long.fromNumber(approx);
  2764. var approxRem = approxRes.mul(divisor);
  2765. while (approxRem.isNegative() || approxRem.gt(rem)) {
  2766. approx -= delta;
  2767. approxRes = Long.fromNumber(approx, this.unsigned);
  2768. approxRem = approxRes.mul(divisor);
  2769. }
  2770. // We know the answer can't be zero... and actually, zero would cause
  2771. // infinite recursion since we would make no progress.
  2772. if (approxRes.isZero())
  2773. approxRes = Long.ONE;
  2774. res = res.add(approxRes);
  2775. rem = rem.sub(approxRem);
  2776. }
  2777. return res;
  2778. };
  2779. /**This is an alias of {@link Long.divide} */
  2780. Long.prototype.div = function (divisor) {
  2781. return this.divide(divisor);
  2782. };
  2783. /**
  2784. * Tests if this Long's value equals the specified's.
  2785. * @param other - Other value
  2786. */
  2787. Long.prototype.equals = function (other) {
  2788. if (!Long.isLong(other))
  2789. other = Long.fromValue(other);
  2790. if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
  2791. return false;
  2792. return this.high === other.high && this.low === other.low;
  2793. };
  2794. /** This is an alias of {@link Long.equals} */
  2795. Long.prototype.eq = function (other) {
  2796. return this.equals(other);
  2797. };
  2798. /** Gets the high 32 bits as a signed integer. */
  2799. Long.prototype.getHighBits = function () {
  2800. return this.high;
  2801. };
  2802. /** Gets the high 32 bits as an unsigned integer. */
  2803. Long.prototype.getHighBitsUnsigned = function () {
  2804. return this.high >>> 0;
  2805. };
  2806. /** Gets the low 32 bits as a signed integer. */
  2807. Long.prototype.getLowBits = function () {
  2808. return this.low;
  2809. };
  2810. /** Gets the low 32 bits as an unsigned integer. */
  2811. Long.prototype.getLowBitsUnsigned = function () {
  2812. return this.low >>> 0;
  2813. };
  2814. /** Gets the number of bits needed to represent the absolute value of this Long. */
  2815. Long.prototype.getNumBitsAbs = function () {
  2816. if (this.isNegative()) {
  2817. // Unsigned Longs are never negative
  2818. return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  2819. }
  2820. var val = this.high !== 0 ? this.high : this.low;
  2821. var bit;
  2822. for (bit = 31; bit > 0; bit--)
  2823. if ((val & (1 << bit)) !== 0)
  2824. break;
  2825. return this.high !== 0 ? bit + 33 : bit + 1;
  2826. };
  2827. /** Tests if this Long's value is greater than the specified's. */
  2828. Long.prototype.greaterThan = function (other) {
  2829. return this.comp(other) > 0;
  2830. };
  2831. /** This is an alias of {@link Long.greaterThan} */
  2832. Long.prototype.gt = function (other) {
  2833. return this.greaterThan(other);
  2834. };
  2835. /** Tests if this Long's value is greater than or equal the specified's. */
  2836. Long.prototype.greaterThanOrEqual = function (other) {
  2837. return this.comp(other) >= 0;
  2838. };
  2839. /** This is an alias of {@link Long.greaterThanOrEqual} */
  2840. Long.prototype.gte = function (other) {
  2841. return this.greaterThanOrEqual(other);
  2842. };
  2843. /** This is an alias of {@link Long.greaterThanOrEqual} */
  2844. Long.prototype.ge = function (other) {
  2845. return this.greaterThanOrEqual(other);
  2846. };
  2847. /** Tests if this Long's value is even. */
  2848. Long.prototype.isEven = function () {
  2849. return (this.low & 1) === 0;
  2850. };
  2851. /** Tests if this Long's value is negative. */
  2852. Long.prototype.isNegative = function () {
  2853. return !this.unsigned && this.high < 0;
  2854. };
  2855. /** Tests if this Long's value is odd. */
  2856. Long.prototype.isOdd = function () {
  2857. return (this.low & 1) === 1;
  2858. };
  2859. /** Tests if this Long's value is positive. */
  2860. Long.prototype.isPositive = function () {
  2861. return this.unsigned || this.high >= 0;
  2862. };
  2863. /** Tests if this Long's value equals zero. */
  2864. Long.prototype.isZero = function () {
  2865. return this.high === 0 && this.low === 0;
  2866. };
  2867. /** Tests if this Long's value is less than the specified's. */
  2868. Long.prototype.lessThan = function (other) {
  2869. return this.comp(other) < 0;
  2870. };
  2871. /** This is an alias of {@link Long#lessThan}. */
  2872. Long.prototype.lt = function (other) {
  2873. return this.lessThan(other);
  2874. };
  2875. /** Tests if this Long's value is less than or equal the specified's. */
  2876. Long.prototype.lessThanOrEqual = function (other) {
  2877. return this.comp(other) <= 0;
  2878. };
  2879. /** This is an alias of {@link Long.lessThanOrEqual} */
  2880. Long.prototype.lte = function (other) {
  2881. return this.lessThanOrEqual(other);
  2882. };
  2883. /** Returns this Long modulo the specified. */
  2884. Long.prototype.modulo = function (divisor) {
  2885. if (!Long.isLong(divisor))
  2886. divisor = Long.fromValue(divisor);
  2887. // use wasm support if present
  2888. if (wasm) {
  2889. var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
  2890. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  2891. }
  2892. return this.sub(this.div(divisor).mul(divisor));
  2893. };
  2894. /** This is an alias of {@link Long.modulo} */
  2895. Long.prototype.mod = function (divisor) {
  2896. return this.modulo(divisor);
  2897. };
  2898. /** This is an alias of {@link Long.modulo} */
  2899. Long.prototype.rem = function (divisor) {
  2900. return this.modulo(divisor);
  2901. };
  2902. /**
  2903. * Returns the product of this and the specified Long.
  2904. * @param multiplier - Multiplier
  2905. * @returns Product
  2906. */
  2907. Long.prototype.multiply = function (multiplier) {
  2908. if (this.isZero())
  2909. return Long.ZERO;
  2910. if (!Long.isLong(multiplier))
  2911. multiplier = Long.fromValue(multiplier);
  2912. // use wasm support if present
  2913. if (wasm) {
  2914. var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
  2915. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  2916. }
  2917. if (multiplier.isZero())
  2918. return Long.ZERO;
  2919. if (this.eq(Long.MIN_VALUE))
  2920. return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  2921. if (multiplier.eq(Long.MIN_VALUE))
  2922. return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  2923. if (this.isNegative()) {
  2924. if (multiplier.isNegative())
  2925. return this.neg().mul(multiplier.neg());
  2926. else
  2927. return this.neg().mul(multiplier).neg();
  2928. }
  2929. else if (multiplier.isNegative())
  2930. return this.mul(multiplier.neg()).neg();
  2931. // If both longs are small, use float multiplication
  2932. if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
  2933. return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  2934. // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
  2935. // We can skip products that would overflow.
  2936. var a48 = this.high >>> 16;
  2937. var a32 = this.high & 0xffff;
  2938. var a16 = this.low >>> 16;
  2939. var a00 = this.low & 0xffff;
  2940. var b48 = multiplier.high >>> 16;
  2941. var b32 = multiplier.high & 0xffff;
  2942. var b16 = multiplier.low >>> 16;
  2943. var b00 = multiplier.low & 0xffff;
  2944. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  2945. c00 += a00 * b00;
  2946. c16 += c00 >>> 16;
  2947. c00 &= 0xffff;
  2948. c16 += a16 * b00;
  2949. c32 += c16 >>> 16;
  2950. c16 &= 0xffff;
  2951. c16 += a00 * b16;
  2952. c32 += c16 >>> 16;
  2953. c16 &= 0xffff;
  2954. c32 += a32 * b00;
  2955. c48 += c32 >>> 16;
  2956. c32 &= 0xffff;
  2957. c32 += a16 * b16;
  2958. c48 += c32 >>> 16;
  2959. c32 &= 0xffff;
  2960. c32 += a00 * b32;
  2961. c48 += c32 >>> 16;
  2962. c32 &= 0xffff;
  2963. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  2964. c48 &= 0xffff;
  2965. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  2966. };
  2967. /** This is an alias of {@link Long.multiply} */
  2968. Long.prototype.mul = function (multiplier) {
  2969. return this.multiply(multiplier);
  2970. };
  2971. /** Returns the Negation of this Long's value. */
  2972. Long.prototype.negate = function () {
  2973. if (!this.unsigned && this.eq(Long.MIN_VALUE))
  2974. return Long.MIN_VALUE;
  2975. return this.not().add(Long.ONE);
  2976. };
  2977. /** This is an alias of {@link Long.negate} */
  2978. Long.prototype.neg = function () {
  2979. return this.negate();
  2980. };
  2981. /** Returns the bitwise NOT of this Long. */
  2982. Long.prototype.not = function () {
  2983. return Long.fromBits(~this.low, ~this.high, this.unsigned);
  2984. };
  2985. /** Tests if this Long's value differs from the specified's. */
  2986. Long.prototype.notEquals = function (other) {
  2987. return !this.equals(other);
  2988. };
  2989. /** This is an alias of {@link Long.notEquals} */
  2990. Long.prototype.neq = function (other) {
  2991. return this.notEquals(other);
  2992. };
  2993. /** This is an alias of {@link Long.notEquals} */
  2994. Long.prototype.ne = function (other) {
  2995. return this.notEquals(other);
  2996. };
  2997. /**
  2998. * Returns the bitwise OR of this Long and the specified.
  2999. */
  3000. Long.prototype.or = function (other) {
  3001. if (!Long.isLong(other))
  3002. other = Long.fromValue(other);
  3003. return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  3004. };
  3005. /**
  3006. * Returns this Long with bits shifted to the left by the given amount.
  3007. * @param numBits - Number of bits
  3008. * @returns Shifted Long
  3009. */
  3010. Long.prototype.shiftLeft = function (numBits) {
  3011. if (Long.isLong(numBits))
  3012. numBits = numBits.toInt();
  3013. if ((numBits &= 63) === 0)
  3014. return this;
  3015. else if (numBits < 32)
  3016. return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
  3017. else
  3018. return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
  3019. };
  3020. /** This is an alias of {@link Long.shiftLeft} */
  3021. Long.prototype.shl = function (numBits) {
  3022. return this.shiftLeft(numBits);
  3023. };
  3024. /**
  3025. * Returns this Long with bits arithmetically shifted to the right by the given amount.
  3026. * @param numBits - Number of bits
  3027. * @returns Shifted Long
  3028. */
  3029. Long.prototype.shiftRight = function (numBits) {
  3030. if (Long.isLong(numBits))
  3031. numBits = numBits.toInt();
  3032. if ((numBits &= 63) === 0)
  3033. return this;
  3034. else if (numBits < 32)
  3035. return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
  3036. else
  3037. return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  3038. };
  3039. /** This is an alias of {@link Long.shiftRight} */
  3040. Long.prototype.shr = function (numBits) {
  3041. return this.shiftRight(numBits);
  3042. };
  3043. /**
  3044. * Returns this Long with bits logically shifted to the right by the given amount.
  3045. * @param numBits - Number of bits
  3046. * @returns Shifted Long
  3047. */
  3048. Long.prototype.shiftRightUnsigned = function (numBits) {
  3049. if (Long.isLong(numBits))
  3050. numBits = numBits.toInt();
  3051. numBits &= 63;
  3052. if (numBits === 0)
  3053. return this;
  3054. else {
  3055. var high = this.high;
  3056. if (numBits < 32) {
  3057. var low = this.low;
  3058. return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
  3059. }
  3060. else if (numBits === 32)
  3061. return Long.fromBits(high, 0, this.unsigned);
  3062. else
  3063. return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
  3064. }
  3065. };
  3066. /** This is an alias of {@link Long.shiftRightUnsigned} */
  3067. Long.prototype.shr_u = function (numBits) {
  3068. return this.shiftRightUnsigned(numBits);
  3069. };
  3070. /** This is an alias of {@link Long.shiftRightUnsigned} */
  3071. Long.prototype.shru = function (numBits) {
  3072. return this.shiftRightUnsigned(numBits);
  3073. };
  3074. /**
  3075. * Returns the difference of this and the specified Long.
  3076. * @param subtrahend - Subtrahend
  3077. * @returns Difference
  3078. */
  3079. Long.prototype.subtract = function (subtrahend) {
  3080. if (!Long.isLong(subtrahend))
  3081. subtrahend = Long.fromValue(subtrahend);
  3082. return this.add(subtrahend.neg());
  3083. };
  3084. /** This is an alias of {@link Long.subtract} */
  3085. Long.prototype.sub = function (subtrahend) {
  3086. return this.subtract(subtrahend);
  3087. };
  3088. /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */
  3089. Long.prototype.toInt = function () {
  3090. return this.unsigned ? this.low >>> 0 : this.low;
  3091. };
  3092. /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */
  3093. Long.prototype.toNumber = function () {
  3094. if (this.unsigned)
  3095. return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
  3096. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  3097. };
  3098. /** Converts the Long to a BigInt (arbitrary precision). */
  3099. Long.prototype.toBigInt = function () {
  3100. return BigInt(this.toString());
  3101. };
  3102. /**
  3103. * Converts this Long to its byte representation.
  3104. * @param le - Whether little or big endian, defaults to big endian
  3105. * @returns Byte representation
  3106. */
  3107. Long.prototype.toBytes = function (le) {
  3108. return le ? this.toBytesLE() : this.toBytesBE();
  3109. };
  3110. /**
  3111. * Converts this Long to its little endian byte representation.
  3112. * @returns Little endian byte representation
  3113. */
  3114. Long.prototype.toBytesLE = function () {
  3115. var hi = this.high, lo = this.low;
  3116. return [
  3117. lo & 0xff,
  3118. (lo >>> 8) & 0xff,
  3119. (lo >>> 16) & 0xff,
  3120. lo >>> 24,
  3121. hi & 0xff,
  3122. (hi >>> 8) & 0xff,
  3123. (hi >>> 16) & 0xff,
  3124. hi >>> 24
  3125. ];
  3126. };
  3127. /**
  3128. * Converts this Long to its big endian byte representation.
  3129. * @returns Big endian byte representation
  3130. */
  3131. Long.prototype.toBytesBE = function () {
  3132. var hi = this.high, lo = this.low;
  3133. return [
  3134. hi >>> 24,
  3135. (hi >>> 16) & 0xff,
  3136. (hi >>> 8) & 0xff,
  3137. hi & 0xff,
  3138. lo >>> 24,
  3139. (lo >>> 16) & 0xff,
  3140. (lo >>> 8) & 0xff,
  3141. lo & 0xff
  3142. ];
  3143. };
  3144. /**
  3145. * Converts this Long to signed.
  3146. */
  3147. Long.prototype.toSigned = function () {
  3148. if (!this.unsigned)
  3149. return this;
  3150. return Long.fromBits(this.low, this.high, false);
  3151. };
  3152. /**
  3153. * Converts the Long to a string written in the specified radix.
  3154. * @param radix - Radix (2-36), defaults to 10
  3155. * @throws RangeError If `radix` is out of range
  3156. */
  3157. Long.prototype.toString = function (radix) {
  3158. radix = radix || 10;
  3159. if (radix < 2 || 36 < radix)
  3160. throw RangeError('radix');
  3161. if (this.isZero())
  3162. return '0';
  3163. if (this.isNegative()) {
  3164. // Unsigned Longs are never negative
  3165. if (this.eq(Long.MIN_VALUE)) {
  3166. // We need to change the Long value before it can be negated, so we remove
  3167. // the bottom-most digit in this base and then recurse to do the rest.
  3168. var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
  3169. return div.toString(radix) + rem1.toInt().toString(radix);
  3170. }
  3171. else
  3172. return '-' + this.neg().toString(radix);
  3173. }
  3174. // Do several (6) digits each time through the loop, so as to
  3175. // minimize the calls to the very expensive emulated div.
  3176. var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
  3177. // eslint-disable-next-line @typescript-eslint/no-this-alias
  3178. var rem = this;
  3179. var result = '';
  3180. // eslint-disable-next-line no-constant-condition
  3181. while (true) {
  3182. var remDiv = rem.div(radixToPower);
  3183. var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
  3184. var digits = intval.toString(radix);
  3185. rem = remDiv;
  3186. if (rem.isZero()) {
  3187. return digits + result;
  3188. }
  3189. else {
  3190. while (digits.length < 6)
  3191. digits = '0' + digits;
  3192. result = '' + digits + result;
  3193. }
  3194. }
  3195. };
  3196. /** Converts this Long to unsigned. */
  3197. Long.prototype.toUnsigned = function () {
  3198. if (this.unsigned)
  3199. return this;
  3200. return Long.fromBits(this.low, this.high, true);
  3201. };
  3202. /** Returns the bitwise XOR of this Long and the given one. */
  3203. Long.prototype.xor = function (other) {
  3204. if (!Long.isLong(other))
  3205. other = Long.fromValue(other);
  3206. return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  3207. };
  3208. /** This is an alias of {@link Long.isZero} */
  3209. Long.prototype.eqz = function () {
  3210. return this.isZero();
  3211. };
  3212. /** This is an alias of {@link Long.lessThanOrEqual} */
  3213. Long.prototype.le = function (other) {
  3214. return this.lessThanOrEqual(other);
  3215. };
  3216. /*
  3217. ****************************************************************
  3218. * BSON SPECIFIC ADDITIONS *
  3219. ****************************************************************
  3220. */
  3221. Long.prototype.toExtendedJSON = function (options) {
  3222. if (options && options.relaxed)
  3223. return this.toNumber();
  3224. return { $numberLong: this.toString() };
  3225. };
  3226. Long.fromExtendedJSON = function (doc, options) {
  3227. var result = Long.fromString(doc.$numberLong);
  3228. return options && options.relaxed ? result.toNumber() : result;
  3229. };
  3230. /** @internal */
  3231. Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  3232. return this.inspect();
  3233. };
  3234. Long.prototype.inspect = function () {
  3235. return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")";
  3236. };
  3237. Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
  3238. /** Maximum unsigned value. */
  3239. Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
  3240. /** Signed zero */
  3241. Long.ZERO = Long.fromInt(0);
  3242. /** Unsigned zero. */
  3243. Long.UZERO = Long.fromInt(0, true);
  3244. /** Signed one. */
  3245. Long.ONE = Long.fromInt(1);
  3246. /** Unsigned one. */
  3247. Long.UONE = Long.fromInt(1, true);
  3248. /** Signed negative one. */
  3249. Long.NEG_ONE = Long.fromInt(-1);
  3250. /** Maximum signed value. */
  3251. Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
  3252. /** Minimum signed value. */
  3253. Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
  3254. return Long;
  3255. }());
  3256. Object.defineProperty(Long.prototype, '__isLong__', { value: true });
  3257. Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' });
  3258. var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  3259. var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  3260. var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  3261. var EXPONENT_MAX = 6111;
  3262. var EXPONENT_MIN = -6176;
  3263. var EXPONENT_BIAS = 6176;
  3264. var MAX_DIGITS = 34;
  3265. // Nan value bits as 32 bit values (due to lack of longs)
  3266. var NAN_BUFFER = [
  3267. 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  3268. ].reverse();
  3269. // Infinity value bits 32 bit values (due to lack of longs)
  3270. var INF_NEGATIVE_BUFFER = [
  3271. 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  3272. ].reverse();
  3273. var INF_POSITIVE_BUFFER = [
  3274. 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  3275. ].reverse();
  3276. var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  3277. // Extract least significant 5 bits
  3278. var COMBINATION_MASK = 0x1f;
  3279. // Extract least significant 14 bits
  3280. var EXPONENT_MASK = 0x3fff;
  3281. // Value of combination field for Inf
  3282. var COMBINATION_INFINITY = 30;
  3283. // Value of combination field for NaN
  3284. var COMBINATION_NAN = 31;
  3285. // Detect if the value is a digit
  3286. function isDigit(value) {
  3287. return !isNaN(parseInt(value, 10));
  3288. }
  3289. // Divide two uint128 values
  3290. function divideu128(value) {
  3291. var DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
  3292. var _rem = Long.fromNumber(0);
  3293. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  3294. return { quotient: value, rem: _rem };
  3295. }
  3296. for (var i = 0; i <= 3; i++) {
  3297. // Adjust remainder to match value of next dividend
  3298. _rem = _rem.shiftLeft(32);
  3299. // Add the divided to _rem
  3300. _rem = _rem.add(new Long(value.parts[i], 0));
  3301. value.parts[i] = _rem.div(DIVISOR).low;
  3302. _rem = _rem.modulo(DIVISOR);
  3303. }
  3304. return { quotient: value, rem: _rem };
  3305. }
  3306. // Multiply two Long values and return the 128 bit value
  3307. function multiply64x2(left, right) {
  3308. if (!left && !right) {
  3309. return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
  3310. }
  3311. var leftHigh = left.shiftRightUnsigned(32);
  3312. var leftLow = new Long(left.getLowBits(), 0);
  3313. var rightHigh = right.shiftRightUnsigned(32);
  3314. var rightLow = new Long(right.getLowBits(), 0);
  3315. var productHigh = leftHigh.multiply(rightHigh);
  3316. var productMid = leftHigh.multiply(rightLow);
  3317. var productMid2 = leftLow.multiply(rightHigh);
  3318. var productLow = leftLow.multiply(rightLow);
  3319. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  3320. productMid = new Long(productMid.getLowBits(), 0)
  3321. .add(productMid2)
  3322. .add(productLow.shiftRightUnsigned(32));
  3323. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  3324. productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
  3325. // Return the 128 bit result
  3326. return { high: productHigh, low: productLow };
  3327. }
  3328. function lessThan(left, right) {
  3329. // Make values unsigned
  3330. var uhleft = left.high >>> 0;
  3331. var uhright = right.high >>> 0;
  3332. // Compare high bits first
  3333. if (uhleft < uhright) {
  3334. return true;
  3335. }
  3336. else if (uhleft === uhright) {
  3337. var ulleft = left.low >>> 0;
  3338. var ulright = right.low >>> 0;
  3339. if (ulleft < ulright)
  3340. return true;
  3341. }
  3342. return false;
  3343. }
  3344. function invalidErr(string, message) {
  3345. throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
  3346. }
  3347. /**
  3348. * A class representation of the BSON Decimal128 type.
  3349. * @public
  3350. * @category BSONType
  3351. */
  3352. var Decimal128 = /** @class */ (function () {
  3353. /**
  3354. * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order,
  3355. * or a string representation as returned by .toString()
  3356. */
  3357. function Decimal128(bytes) {
  3358. if (!(this instanceof Decimal128))
  3359. return new Decimal128(bytes);
  3360. if (typeof bytes === 'string') {
  3361. this.bytes = Decimal128.fromString(bytes).bytes;
  3362. }
  3363. else if (isUint8Array(bytes)) {
  3364. if (bytes.byteLength !== 16) {
  3365. throw new BSONTypeError('Decimal128 must take a Buffer of 16 bytes');
  3366. }
  3367. this.bytes = bytes;
  3368. }
  3369. else {
  3370. throw new BSONTypeError('Decimal128 must take a Buffer or string');
  3371. }
  3372. }
  3373. /**
  3374. * Create a Decimal128 instance from a string representation
  3375. *
  3376. * @param representation - a numeric string representation.
  3377. */
  3378. Decimal128.fromString = function (representation) {
  3379. // Parse state tracking
  3380. var isNegative = false;
  3381. var sawRadix = false;
  3382. var foundNonZero = false;
  3383. // Total number of significant digits (no leading or trailing zero)
  3384. var significantDigits = 0;
  3385. // Total number of significand digits read
  3386. var nDigitsRead = 0;
  3387. // Total number of digits (no leading zeros)
  3388. var nDigits = 0;
  3389. // The number of the digits after radix
  3390. var radixPosition = 0;
  3391. // The index of the first non-zero in *str*
  3392. var firstNonZero = 0;
  3393. // Digits Array
  3394. var digits = [0];
  3395. // The number of digits in digits
  3396. var nDigitsStored = 0;
  3397. // Insertion pointer for digits
  3398. var digitsInsert = 0;
  3399. // The index of the first non-zero digit
  3400. var firstDigit = 0;
  3401. // The index of the last digit
  3402. var lastDigit = 0;
  3403. // Exponent
  3404. var exponent = 0;
  3405. // loop index over array
  3406. var i = 0;
  3407. // The high 17 digits of the significand
  3408. var significandHigh = new Long(0, 0);
  3409. // The low 17 digits of the significand
  3410. var significandLow = new Long(0, 0);
  3411. // The biased exponent
  3412. var biasedExponent = 0;
  3413. // Read index
  3414. var index = 0;
  3415. // Naively prevent against REDOS attacks.
  3416. // TODO: implementing a custom parsing for this, or refactoring the regex would yield
  3417. // further gains.
  3418. if (representation.length >= 7000) {
  3419. throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
  3420. }
  3421. // Results
  3422. var stringMatch = representation.match(PARSE_STRING_REGEXP);
  3423. var infMatch = representation.match(PARSE_INF_REGEXP);
  3424. var nanMatch = representation.match(PARSE_NAN_REGEXP);
  3425. // Validate the string
  3426. if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
  3427. throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
  3428. }
  3429. if (stringMatch) {
  3430. // full_match = stringMatch[0]
  3431. // sign = stringMatch[1]
  3432. var unsignedNumber = stringMatch[2];
  3433. // stringMatch[3] is undefined if a whole number (ex "1", 12")
  3434. // but defined if a number w/ decimal in it (ex "1.0, 12.2")
  3435. var e = stringMatch[4];
  3436. var expSign = stringMatch[5];
  3437. var expNumber = stringMatch[6];
  3438. // they provided e, but didn't give an exponent number. for ex "1e"
  3439. if (e && expNumber === undefined)
  3440. invalidErr(representation, 'missing exponent power');
  3441. // they provided e, but didn't give a number before it. for ex "e1"
  3442. if (e && unsignedNumber === undefined)
  3443. invalidErr(representation, 'missing exponent base');
  3444. if (e === undefined && (expSign || expNumber)) {
  3445. invalidErr(representation, 'missing e before exponent');
  3446. }
  3447. }
  3448. // Get the negative or positive sign
  3449. if (representation[index] === '+' || representation[index] === '-') {
  3450. isNegative = representation[index++] === '-';
  3451. }
  3452. // Check if user passed Infinity or NaN
  3453. if (!isDigit(representation[index]) && representation[index] !== '.') {
  3454. if (representation[index] === 'i' || representation[index] === 'I') {
  3455. return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  3456. }
  3457. else if (representation[index] === 'N') {
  3458. return new Decimal128(buffer_1.from(NAN_BUFFER));
  3459. }
  3460. }
  3461. // Read all the digits
  3462. while (isDigit(representation[index]) || representation[index] === '.') {
  3463. if (representation[index] === '.') {
  3464. if (sawRadix)
  3465. invalidErr(representation, 'contains multiple periods');
  3466. sawRadix = true;
  3467. index = index + 1;
  3468. continue;
  3469. }
  3470. if (nDigitsStored < 34) {
  3471. if (representation[index] !== '0' || foundNonZero) {
  3472. if (!foundNonZero) {
  3473. firstNonZero = nDigitsRead;
  3474. }
  3475. foundNonZero = true;
  3476. // Only store 34 digits
  3477. digits[digitsInsert++] = parseInt(representation[index], 10);
  3478. nDigitsStored = nDigitsStored + 1;
  3479. }
  3480. }
  3481. if (foundNonZero)
  3482. nDigits = nDigits + 1;
  3483. if (sawRadix)
  3484. radixPosition = radixPosition + 1;
  3485. nDigitsRead = nDigitsRead + 1;
  3486. index = index + 1;
  3487. }
  3488. if (sawRadix && !nDigitsRead)
  3489. throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
  3490. // Read exponent if exists
  3491. if (representation[index] === 'e' || representation[index] === 'E') {
  3492. // Read exponent digits
  3493. var match = representation.substr(++index).match(EXPONENT_REGEX);
  3494. // No digits read
  3495. if (!match || !match[2])
  3496. return new Decimal128(buffer_1.from(NAN_BUFFER));
  3497. // Get exponent
  3498. exponent = parseInt(match[0], 10);
  3499. // Adjust the index
  3500. index = index + match[0].length;
  3501. }
  3502. // Return not a number
  3503. if (representation[index])
  3504. return new Decimal128(buffer_1.from(NAN_BUFFER));
  3505. // Done reading input
  3506. // Find first non-zero digit in digits
  3507. firstDigit = 0;
  3508. if (!nDigitsStored) {
  3509. firstDigit = 0;
  3510. lastDigit = 0;
  3511. digits[0] = 0;
  3512. nDigits = 1;
  3513. nDigitsStored = 1;
  3514. significantDigits = 0;
  3515. }
  3516. else {
  3517. lastDigit = nDigitsStored - 1;
  3518. significantDigits = nDigits;
  3519. if (significantDigits !== 1) {
  3520. while (digits[firstNonZero + significantDigits - 1] === 0) {
  3521. significantDigits = significantDigits - 1;
  3522. }
  3523. }
  3524. }
  3525. // Normalization of exponent
  3526. // Correct exponent based on radix position, and shift significand as needed
  3527. // to represent user input
  3528. // Overflow prevention
  3529. if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
  3530. exponent = EXPONENT_MIN;
  3531. }
  3532. else {
  3533. exponent = exponent - radixPosition;
  3534. }
  3535. // Attempt to normalize the exponent
  3536. while (exponent > EXPONENT_MAX) {
  3537. // Shift exponent to significand and decrease
  3538. lastDigit = lastDigit + 1;
  3539. if (lastDigit - firstDigit > MAX_DIGITS) {
  3540. // Check if we have a zero then just hard clamp, otherwise fail
  3541. var digitsString = digits.join('');
  3542. if (digitsString.match(/^0+$/)) {
  3543. exponent = EXPONENT_MAX;
  3544. break;
  3545. }
  3546. invalidErr(representation, 'overflow');
  3547. }
  3548. exponent = exponent - 1;
  3549. }
  3550. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  3551. // Shift last digit. can only do this if < significant digits than # stored.
  3552. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  3553. exponent = EXPONENT_MIN;
  3554. significantDigits = 0;
  3555. break;
  3556. }
  3557. if (nDigitsStored < nDigits) {
  3558. // adjust to match digits not stored
  3559. nDigits = nDigits - 1;
  3560. }
  3561. else {
  3562. // adjust to round
  3563. lastDigit = lastDigit - 1;
  3564. }
  3565. if (exponent < EXPONENT_MAX) {
  3566. exponent = exponent + 1;
  3567. }
  3568. else {
  3569. // Check if we have a zero then just hard clamp, otherwise fail
  3570. var digitsString = digits.join('');
  3571. if (digitsString.match(/^0+$/)) {
  3572. exponent = EXPONENT_MAX;
  3573. break;
  3574. }
  3575. invalidErr(representation, 'overflow');
  3576. }
  3577. }
  3578. // Round
  3579. // We've normalized the exponent, but might still need to round.
  3580. if (lastDigit - firstDigit + 1 < significantDigits) {
  3581. var endOfString = nDigitsRead;
  3582. // If we have seen a radix point, 'string' is 1 longer than we have
  3583. // documented with ndigits_read, so inc the position of the first nonzero
  3584. // digit and the position that digits are read to.
  3585. if (sawRadix) {
  3586. firstNonZero = firstNonZero + 1;
  3587. endOfString = endOfString + 1;
  3588. }
  3589. // if negative, we need to increment again to account for - sign at start.
  3590. if (isNegative) {
  3591. firstNonZero = firstNonZero + 1;
  3592. endOfString = endOfString + 1;
  3593. }
  3594. var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  3595. var roundBit = 0;
  3596. if (roundDigit >= 5) {
  3597. roundBit = 1;
  3598. if (roundDigit === 5) {
  3599. roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
  3600. for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  3601. if (parseInt(representation[i], 10)) {
  3602. roundBit = 1;
  3603. break;
  3604. }
  3605. }
  3606. }
  3607. }
  3608. if (roundBit) {
  3609. var dIdx = lastDigit;
  3610. for (; dIdx >= 0; dIdx--) {
  3611. if (++digits[dIdx] > 9) {
  3612. digits[dIdx] = 0;
  3613. // overflowed most significant digit
  3614. if (dIdx === 0) {
  3615. if (exponent < EXPONENT_MAX) {
  3616. exponent = exponent + 1;
  3617. digits[dIdx] = 1;
  3618. }
  3619. else {
  3620. return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  3621. }
  3622. }
  3623. }
  3624. }
  3625. }
  3626. }
  3627. // Encode significand
  3628. // The high 17 digits of the significand
  3629. significandHigh = Long.fromNumber(0);
  3630. // The low 17 digits of the significand
  3631. significandLow = Long.fromNumber(0);
  3632. // read a zero
  3633. if (significantDigits === 0) {
  3634. significandHigh = Long.fromNumber(0);
  3635. significandLow = Long.fromNumber(0);
  3636. }
  3637. else if (lastDigit - firstDigit < 17) {
  3638. var dIdx = firstDigit;
  3639. significandLow = Long.fromNumber(digits[dIdx++]);
  3640. significandHigh = new Long(0, 0);
  3641. for (; dIdx <= lastDigit; dIdx++) {
  3642. significandLow = significandLow.multiply(Long.fromNumber(10));
  3643. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  3644. }
  3645. }
  3646. else {
  3647. var dIdx = firstDigit;
  3648. significandHigh = Long.fromNumber(digits[dIdx++]);
  3649. for (; dIdx <= lastDigit - 17; dIdx++) {
  3650. significandHigh = significandHigh.multiply(Long.fromNumber(10));
  3651. significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
  3652. }
  3653. significandLow = Long.fromNumber(digits[dIdx++]);
  3654. for (; dIdx <= lastDigit; dIdx++) {
  3655. significandLow = significandLow.multiply(Long.fromNumber(10));
  3656. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  3657. }
  3658. }
  3659. var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
  3660. significand.low = significand.low.add(significandLow);
  3661. if (lessThan(significand.low, significandLow)) {
  3662. significand.high = significand.high.add(Long.fromNumber(1));
  3663. }
  3664. // Biased exponent
  3665. biasedExponent = exponent + EXPONENT_BIAS;
  3666. var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
  3667. // Encode combination, exponent, and significand.
  3668. if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
  3669. // Encode '11' into bits 1 to 3
  3670. dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
  3671. dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
  3672. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
  3673. }
  3674. else {
  3675. dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  3676. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
  3677. }
  3678. dec.low = significand.low;
  3679. // Encode sign
  3680. if (isNegative) {
  3681. dec.high = dec.high.or(Long.fromString('9223372036854775808'));
  3682. }
  3683. // Encode into a buffer
  3684. var buffer = buffer_1.alloc(16);
  3685. index = 0;
  3686. // Encode the low 64 bits of the decimal
  3687. // Encode low bits
  3688. buffer[index++] = dec.low.low & 0xff;
  3689. buffer[index++] = (dec.low.low >> 8) & 0xff;
  3690. buffer[index++] = (dec.low.low >> 16) & 0xff;
  3691. buffer[index++] = (dec.low.low >> 24) & 0xff;
  3692. // Encode high bits
  3693. buffer[index++] = dec.low.high & 0xff;
  3694. buffer[index++] = (dec.low.high >> 8) & 0xff;
  3695. buffer[index++] = (dec.low.high >> 16) & 0xff;
  3696. buffer[index++] = (dec.low.high >> 24) & 0xff;
  3697. // Encode the high 64 bits of the decimal
  3698. // Encode low bits
  3699. buffer[index++] = dec.high.low & 0xff;
  3700. buffer[index++] = (dec.high.low >> 8) & 0xff;
  3701. buffer[index++] = (dec.high.low >> 16) & 0xff;
  3702. buffer[index++] = (dec.high.low >> 24) & 0xff;
  3703. // Encode high bits
  3704. buffer[index++] = dec.high.high & 0xff;
  3705. buffer[index++] = (dec.high.high >> 8) & 0xff;
  3706. buffer[index++] = (dec.high.high >> 16) & 0xff;
  3707. buffer[index++] = (dec.high.high >> 24) & 0xff;
  3708. // Return the new Decimal128
  3709. return new Decimal128(buffer);
  3710. };
  3711. /** Create a string representation of the raw Decimal128 value */
  3712. Decimal128.prototype.toString = function () {
  3713. // Note: bits in this routine are referred to starting at 0,
  3714. // from the sign bit, towards the coefficient.
  3715. // decoded biased exponent (14 bits)
  3716. var biased_exponent;
  3717. // the number of significand digits
  3718. var significand_digits = 0;
  3719. // the base-10 digits in the significand
  3720. var significand = new Array(36);
  3721. for (var i = 0; i < significand.length; i++)
  3722. significand[i] = 0;
  3723. // read pointer into significand
  3724. var index = 0;
  3725. // true if the number is zero
  3726. var is_zero = false;
  3727. // the most significant significand bits (50-46)
  3728. var significand_msb;
  3729. // temporary storage for significand decoding
  3730. var significand128 = { parts: [0, 0, 0, 0] };
  3731. // indexing variables
  3732. var j, k;
  3733. // Output string
  3734. var string = [];
  3735. // Unpack index
  3736. index = 0;
  3737. // Buffer reference
  3738. var buffer = this.bytes;
  3739. // Unpack the low 64bits into a long
  3740. // bits 96 - 127
  3741. var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  3742. // bits 64 - 95
  3743. var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  3744. // Unpack the high 64bits into a long
  3745. // bits 32 - 63
  3746. var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  3747. // bits 0 - 31
  3748. var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  3749. // Unpack index
  3750. index = 0;
  3751. // Create the state of the decimal
  3752. var dec = {
  3753. low: new Long(low, midl),
  3754. high: new Long(midh, high)
  3755. };
  3756. if (dec.high.lessThan(Long.ZERO)) {
  3757. string.push('-');
  3758. }
  3759. // Decode combination field and exponent
  3760. // bits 1 - 5
  3761. var combination = (high >> 26) & COMBINATION_MASK;
  3762. if (combination >> 3 === 3) {
  3763. // Check for 'special' values
  3764. if (combination === COMBINATION_INFINITY) {
  3765. return string.join('') + 'Infinity';
  3766. }
  3767. else if (combination === COMBINATION_NAN) {
  3768. return 'NaN';
  3769. }
  3770. else {
  3771. biased_exponent = (high >> 15) & EXPONENT_MASK;
  3772. significand_msb = 0x08 + ((high >> 14) & 0x01);
  3773. }
  3774. }
  3775. else {
  3776. significand_msb = (high >> 14) & 0x07;
  3777. biased_exponent = (high >> 17) & EXPONENT_MASK;
  3778. }
  3779. // unbiased exponent
  3780. var exponent = biased_exponent - EXPONENT_BIAS;
  3781. // Create string of significand digits
  3782. // Convert the 114-bit binary number represented by
  3783. // (significand_high, significand_low) to at most 34 decimal
  3784. // digits through modulo and division.
  3785. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  3786. significand128.parts[1] = midh;
  3787. significand128.parts[2] = midl;
  3788. significand128.parts[3] = low;
  3789. if (significand128.parts[0] === 0 &&
  3790. significand128.parts[1] === 0 &&
  3791. significand128.parts[2] === 0 &&
  3792. significand128.parts[3] === 0) {
  3793. is_zero = true;
  3794. }
  3795. else {
  3796. for (k = 3; k >= 0; k--) {
  3797. var least_digits = 0;
  3798. // Perform the divide
  3799. var result = divideu128(significand128);
  3800. significand128 = result.quotient;
  3801. least_digits = result.rem.low;
  3802. // We now have the 9 least significant digits (in base 2).
  3803. // Convert and output to string.
  3804. if (!least_digits)
  3805. continue;
  3806. for (j = 8; j >= 0; j--) {
  3807. // significand[k * 9 + j] = Math.round(least_digits % 10);
  3808. significand[k * 9 + j] = least_digits % 10;
  3809. // least_digits = Math.round(least_digits / 10);
  3810. least_digits = Math.floor(least_digits / 10);
  3811. }
  3812. }
  3813. }
  3814. // Output format options:
  3815. // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
  3816. // Regular - ddd.ddd
  3817. if (is_zero) {
  3818. significand_digits = 1;
  3819. significand[index] = 0;
  3820. }
  3821. else {
  3822. significand_digits = 36;
  3823. while (!significand[index]) {
  3824. significand_digits = significand_digits - 1;
  3825. index = index + 1;
  3826. }
  3827. }
  3828. // the exponent if scientific notation is used
  3829. var scientific_exponent = significand_digits - 1 + exponent;
  3830. // The scientific exponent checks are dictated by the string conversion
  3831. // specification and are somewhat arbitrary cutoffs.
  3832. //
  3833. // We must check exponent > 0, because if this is the case, the number
  3834. // has trailing zeros. However, we *cannot* output these trailing zeros,
  3835. // because doing so would change the precision of the value, and would
  3836. // change stored data if the string converted number is round tripped.
  3837. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  3838. // Scientific format
  3839. // if there are too many significant digits, we should just be treating numbers
  3840. // as + or - 0 and using the non-scientific exponent (this is for the "invalid
  3841. // representation should be treated as 0/-0" spec cases in decimal128-1.json)
  3842. if (significand_digits > 34) {
  3843. string.push("" + 0);
  3844. if (exponent > 0)
  3845. string.push('E+' + exponent);
  3846. else if (exponent < 0)
  3847. string.push('E' + exponent);
  3848. return string.join('');
  3849. }
  3850. string.push("" + significand[index++]);
  3851. significand_digits = significand_digits - 1;
  3852. if (significand_digits) {
  3853. string.push('.');
  3854. }
  3855. for (var i = 0; i < significand_digits; i++) {
  3856. string.push("" + significand[index++]);
  3857. }
  3858. // Exponent
  3859. string.push('E');
  3860. if (scientific_exponent > 0) {
  3861. string.push('+' + scientific_exponent);
  3862. }
  3863. else {
  3864. string.push("" + scientific_exponent);
  3865. }
  3866. }
  3867. else {
  3868. // Regular format with no decimal place
  3869. if (exponent >= 0) {
  3870. for (var i = 0; i < significand_digits; i++) {
  3871. string.push("" + significand[index++]);
  3872. }
  3873. }
  3874. else {
  3875. var radix_position = significand_digits + exponent;
  3876. // non-zero digits before radix
  3877. if (radix_position > 0) {
  3878. for (var i = 0; i < radix_position; i++) {
  3879. string.push("" + significand[index++]);
  3880. }
  3881. }
  3882. else {
  3883. string.push('0');
  3884. }
  3885. string.push('.');
  3886. // add leading zeros after radix
  3887. while (radix_position++ < 0) {
  3888. string.push('0');
  3889. }
  3890. for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  3891. string.push("" + significand[index++]);
  3892. }
  3893. }
  3894. }
  3895. return string.join('');
  3896. };
  3897. Decimal128.prototype.toJSON = function () {
  3898. return { $numberDecimal: this.toString() };
  3899. };
  3900. /** @internal */
  3901. Decimal128.prototype.toExtendedJSON = function () {
  3902. return { $numberDecimal: this.toString() };
  3903. };
  3904. /** @internal */
  3905. Decimal128.fromExtendedJSON = function (doc) {
  3906. return Decimal128.fromString(doc.$numberDecimal);
  3907. };
  3908. /** @internal */
  3909. Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  3910. return this.inspect();
  3911. };
  3912. Decimal128.prototype.inspect = function () {
  3913. return "new Decimal128(\"" + this.toString() + "\")";
  3914. };
  3915. return Decimal128;
  3916. }());
  3917. Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' });
  3918. /**
  3919. * A class representation of the BSON Double type.
  3920. * @public
  3921. * @category BSONType
  3922. */
  3923. var Double = /** @class */ (function () {
  3924. /**
  3925. * Create a Double type
  3926. *
  3927. * @param value - the number we want to represent as a double.
  3928. */
  3929. function Double(value) {
  3930. if (!(this instanceof Double))
  3931. return new Double(value);
  3932. if (value instanceof Number) {
  3933. value = value.valueOf();
  3934. }
  3935. this.value = +value;
  3936. }
  3937. /**
  3938. * Access the number value.
  3939. *
  3940. * @returns returns the wrapped double number.
  3941. */
  3942. Double.prototype.valueOf = function () {
  3943. return this.value;
  3944. };
  3945. Double.prototype.toJSON = function () {
  3946. return this.value;
  3947. };
  3948. Double.prototype.toString = function (radix) {
  3949. return this.value.toString(radix);
  3950. };
  3951. /** @internal */
  3952. Double.prototype.toExtendedJSON = function (options) {
  3953. if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
  3954. return this.value;
  3955. }
  3956. // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
  3957. // explicitly provided `-0` then we need to ensure the sign makes it into the output
  3958. if (Object.is(Math.sign(this.value), -0)) {
  3959. return { $numberDouble: "-" + this.value.toFixed(1) };
  3960. }
  3961. var $numberDouble;
  3962. if (Number.isInteger(this.value)) {
  3963. $numberDouble = this.value.toFixed(1);
  3964. if ($numberDouble.length >= 13) {
  3965. $numberDouble = this.value.toExponential(13).toUpperCase();
  3966. }
  3967. }
  3968. else {
  3969. $numberDouble = this.value.toString();
  3970. }
  3971. return { $numberDouble: $numberDouble };
  3972. };
  3973. /** @internal */
  3974. Double.fromExtendedJSON = function (doc, options) {
  3975. var doubleValue = parseFloat(doc.$numberDouble);
  3976. return options && options.relaxed ? doubleValue : new Double(doubleValue);
  3977. };
  3978. /** @internal */
  3979. Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  3980. return this.inspect();
  3981. };
  3982. Double.prototype.inspect = function () {
  3983. var eJSON = this.toExtendedJSON();
  3984. return "new Double(" + eJSON.$numberDouble + ")";
  3985. };
  3986. return Double;
  3987. }());
  3988. Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' });
  3989. /**
  3990. * A class representation of a BSON Int32 type.
  3991. * @public
  3992. * @category BSONType
  3993. */
  3994. var Int32 = /** @class */ (function () {
  3995. /**
  3996. * Create an Int32 type
  3997. *
  3998. * @param value - the number we want to represent as an int32.
  3999. */
  4000. function Int32(value) {
  4001. if (!(this instanceof Int32))
  4002. return new Int32(value);
  4003. if (value instanceof Number) {
  4004. value = value.valueOf();
  4005. }
  4006. this.value = +value | 0;
  4007. }
  4008. /**
  4009. * Access the number value.
  4010. *
  4011. * @returns returns the wrapped int32 number.
  4012. */
  4013. Int32.prototype.valueOf = function () {
  4014. return this.value;
  4015. };
  4016. Int32.prototype.toString = function (radix) {
  4017. return this.value.toString(radix);
  4018. };
  4019. Int32.prototype.toJSON = function () {
  4020. return this.value;
  4021. };
  4022. /** @internal */
  4023. Int32.prototype.toExtendedJSON = function (options) {
  4024. if (options && (options.relaxed || options.legacy))
  4025. return this.value;
  4026. return { $numberInt: this.value.toString() };
  4027. };
  4028. /** @internal */
  4029. Int32.fromExtendedJSON = function (doc, options) {
  4030. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  4031. };
  4032. /** @internal */
  4033. Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4034. return this.inspect();
  4035. };
  4036. Int32.prototype.inspect = function () {
  4037. return "new Int32(" + this.valueOf() + ")";
  4038. };
  4039. return Int32;
  4040. }());
  4041. Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' });
  4042. /**
  4043. * A class representation of the BSON MaxKey type.
  4044. * @public
  4045. * @category BSONType
  4046. */
  4047. var MaxKey = /** @class */ (function () {
  4048. function MaxKey() {
  4049. if (!(this instanceof MaxKey))
  4050. return new MaxKey();
  4051. }
  4052. /** @internal */
  4053. MaxKey.prototype.toExtendedJSON = function () {
  4054. return { $maxKey: 1 };
  4055. };
  4056. /** @internal */
  4057. MaxKey.fromExtendedJSON = function () {
  4058. return new MaxKey();
  4059. };
  4060. /** @internal */
  4061. MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4062. return this.inspect();
  4063. };
  4064. MaxKey.prototype.inspect = function () {
  4065. return 'new MaxKey()';
  4066. };
  4067. return MaxKey;
  4068. }());
  4069. Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' });
  4070. /**
  4071. * A class representation of the BSON MinKey type.
  4072. * @public
  4073. * @category BSONType
  4074. */
  4075. var MinKey = /** @class */ (function () {
  4076. function MinKey() {
  4077. if (!(this instanceof MinKey))
  4078. return new MinKey();
  4079. }
  4080. /** @internal */
  4081. MinKey.prototype.toExtendedJSON = function () {
  4082. return { $minKey: 1 };
  4083. };
  4084. /** @internal */
  4085. MinKey.fromExtendedJSON = function () {
  4086. return new MinKey();
  4087. };
  4088. /** @internal */
  4089. MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4090. return this.inspect();
  4091. };
  4092. MinKey.prototype.inspect = function () {
  4093. return 'new MinKey()';
  4094. };
  4095. return MinKey;
  4096. }());
  4097. Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' });
  4098. // Regular expression that checks for hex value
  4099. var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
  4100. // Unique sequence for the current process (initialized on first use)
  4101. var PROCESS_UNIQUE = null;
  4102. var kId = Symbol('id');
  4103. /**
  4104. * A class representation of the BSON ObjectId type.
  4105. * @public
  4106. * @category BSONType
  4107. */
  4108. var ObjectId = /** @class */ (function () {
  4109. /**
  4110. * Create an ObjectId type
  4111. *
  4112. * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
  4113. */
  4114. function ObjectId(inputId) {
  4115. if (!(this instanceof ObjectId))
  4116. return new ObjectId(inputId);
  4117. // workingId is set based on type of input and whether valid id exists for the input
  4118. var workingId;
  4119. if (typeof inputId === 'object' && inputId && 'id' in inputId) {
  4120. if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
  4121. throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer');
  4122. }
  4123. if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
  4124. workingId = buffer_1.from(inputId.toHexString(), 'hex');
  4125. }
  4126. else {
  4127. workingId = inputId.id;
  4128. }
  4129. }
  4130. else {
  4131. workingId = inputId;
  4132. }
  4133. // the following cases use workingId to construct an ObjectId
  4134. if (workingId == null || typeof workingId === 'number') {
  4135. // The most common use case (blank id, new objectId instance)
  4136. // Generate a new id
  4137. this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
  4138. }
  4139. else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
  4140. // If intstanceof matches we can escape calling ensure buffer in Node.js environments
  4141. this[kId] = workingId instanceof buffer_1 ? workingId : ensureBuffer(workingId);
  4142. }
  4143. else if (typeof workingId === 'string') {
  4144. if (workingId.length === 12) {
  4145. var bytes = buffer_1.from(workingId);
  4146. if (bytes.byteLength === 12) {
  4147. this[kId] = bytes;
  4148. }
  4149. else {
  4150. throw new BSONTypeError('Argument passed in must be a string of 12 bytes');
  4151. }
  4152. }
  4153. else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
  4154. this[kId] = buffer_1.from(workingId, 'hex');
  4155. }
  4156. else {
  4157. throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer');
  4158. }
  4159. }
  4160. else {
  4161. throw new BSONTypeError('Argument passed in does not match the accepted types');
  4162. }
  4163. // If we are caching the hex string
  4164. if (ObjectId.cacheHexString) {
  4165. this.__id = this.id.toString('hex');
  4166. }
  4167. }
  4168. Object.defineProperty(ObjectId.prototype, "id", {
  4169. /**
  4170. * The ObjectId bytes
  4171. * @readonly
  4172. */
  4173. get: function () {
  4174. return this[kId];
  4175. },
  4176. set: function (value) {
  4177. this[kId] = value;
  4178. if (ObjectId.cacheHexString) {
  4179. this.__id = value.toString('hex');
  4180. }
  4181. },
  4182. enumerable: false,
  4183. configurable: true
  4184. });
  4185. Object.defineProperty(ObjectId.prototype, "generationTime", {
  4186. /**
  4187. * The generation time of this ObjectId instance
  4188. * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch
  4189. */
  4190. get: function () {
  4191. return this.id.readInt32BE(0);
  4192. },
  4193. set: function (value) {
  4194. // Encode time into first 4 bytes
  4195. this.id.writeUInt32BE(value, 0);
  4196. },
  4197. enumerable: false,
  4198. configurable: true
  4199. });
  4200. /** Returns the ObjectId id as a 24 character hex string representation */
  4201. ObjectId.prototype.toHexString = function () {
  4202. if (ObjectId.cacheHexString && this.__id) {
  4203. return this.__id;
  4204. }
  4205. var hexString = this.id.toString('hex');
  4206. if (ObjectId.cacheHexString && !this.__id) {
  4207. this.__id = hexString;
  4208. }
  4209. return hexString;
  4210. };
  4211. /**
  4212. * Update the ObjectId index
  4213. * @privateRemarks
  4214. * Used in generating new ObjectId's on the driver
  4215. * @internal
  4216. */
  4217. ObjectId.getInc = function () {
  4218. return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
  4219. };
  4220. /**
  4221. * Generate a 12 byte id buffer used in ObjectId's
  4222. *
  4223. * @param time - pass in a second based timestamp.
  4224. */
  4225. ObjectId.generate = function (time) {
  4226. if ('number' !== typeof time) {
  4227. time = Math.floor(Date.now() / 1000);
  4228. }
  4229. var inc = ObjectId.getInc();
  4230. var buffer = buffer_1.alloc(12);
  4231. // 4-byte timestamp
  4232. buffer.writeUInt32BE(time, 0);
  4233. // set PROCESS_UNIQUE if yet not initialized
  4234. if (PROCESS_UNIQUE === null) {
  4235. PROCESS_UNIQUE = randomBytes(5);
  4236. }
  4237. // 5-byte process unique
  4238. buffer[4] = PROCESS_UNIQUE[0];
  4239. buffer[5] = PROCESS_UNIQUE[1];
  4240. buffer[6] = PROCESS_UNIQUE[2];
  4241. buffer[7] = PROCESS_UNIQUE[3];
  4242. buffer[8] = PROCESS_UNIQUE[4];
  4243. // 3-byte counter
  4244. buffer[11] = inc & 0xff;
  4245. buffer[10] = (inc >> 8) & 0xff;
  4246. buffer[9] = (inc >> 16) & 0xff;
  4247. return buffer;
  4248. };
  4249. /**
  4250. * Converts the id into a 24 character hex string for printing
  4251. *
  4252. * @param format - The Buffer toString format parameter.
  4253. */
  4254. ObjectId.prototype.toString = function (format) {
  4255. // Is the id a buffer then use the buffer toString method to return the format
  4256. if (format)
  4257. return this.id.toString(format);
  4258. return this.toHexString();
  4259. };
  4260. /** Converts to its JSON the 24 character hex string representation. */
  4261. ObjectId.prototype.toJSON = function () {
  4262. return this.toHexString();
  4263. };
  4264. /**
  4265. * Compares the equality of this ObjectId with `otherID`.
  4266. *
  4267. * @param otherId - ObjectId instance to compare against.
  4268. */
  4269. ObjectId.prototype.equals = function (otherId) {
  4270. if (otherId === undefined || otherId === null) {
  4271. return false;
  4272. }
  4273. if (otherId instanceof ObjectId) {
  4274. return this[kId][11] === otherId[kId][11] && this[kId].equals(otherId[kId]);
  4275. }
  4276. if (typeof otherId === 'string' &&
  4277. ObjectId.isValid(otherId) &&
  4278. otherId.length === 12 &&
  4279. isUint8Array(this.id)) {
  4280. return otherId === buffer_1.prototype.toString.call(this.id, 'latin1');
  4281. }
  4282. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
  4283. return otherId.toLowerCase() === this.toHexString();
  4284. }
  4285. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
  4286. return buffer_1.from(otherId).equals(this.id);
  4287. }
  4288. if (typeof otherId === 'object' &&
  4289. 'toHexString' in otherId &&
  4290. typeof otherId.toHexString === 'function') {
  4291. var otherIdString = otherId.toHexString();
  4292. var thisIdString = this.toHexString().toLowerCase();
  4293. return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
  4294. }
  4295. return false;
  4296. };
  4297. /** Returns the generation date (accurate up to the second) that this ID was generated. */
  4298. ObjectId.prototype.getTimestamp = function () {
  4299. var timestamp = new Date();
  4300. var time = this.id.readUInt32BE(0);
  4301. timestamp.setTime(Math.floor(time) * 1000);
  4302. return timestamp;
  4303. };
  4304. /** @internal */
  4305. ObjectId.createPk = function () {
  4306. return new ObjectId();
  4307. };
  4308. /**
  4309. * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
  4310. *
  4311. * @param time - an integer number representing a number of seconds.
  4312. */
  4313. ObjectId.createFromTime = function (time) {
  4314. var buffer = buffer_1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4315. // Encode time into first 4 bytes
  4316. buffer.writeUInt32BE(time, 0);
  4317. // Return the new objectId
  4318. return new ObjectId(buffer);
  4319. };
  4320. /**
  4321. * Creates an ObjectId from a hex string representation of an ObjectId.
  4322. *
  4323. * @param hexString - create a ObjectId from a passed in 24 character hexstring.
  4324. */
  4325. ObjectId.createFromHexString = function (hexString) {
  4326. // Throw an error if it's not a valid setup
  4327. if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
  4328. throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  4329. }
  4330. return new ObjectId(buffer_1.from(hexString, 'hex'));
  4331. };
  4332. /**
  4333. * Checks if a value is a valid bson ObjectId
  4334. *
  4335. * @param id - ObjectId instance to validate.
  4336. */
  4337. ObjectId.isValid = function (id) {
  4338. if (id == null)
  4339. return false;
  4340. try {
  4341. new ObjectId(id);
  4342. return true;
  4343. }
  4344. catch (_a) {
  4345. return false;
  4346. }
  4347. };
  4348. /** @internal */
  4349. ObjectId.prototype.toExtendedJSON = function () {
  4350. if (this.toHexString)
  4351. return { $oid: this.toHexString() };
  4352. return { $oid: this.toString('hex') };
  4353. };
  4354. /** @internal */
  4355. ObjectId.fromExtendedJSON = function (doc) {
  4356. return new ObjectId(doc.$oid);
  4357. };
  4358. /**
  4359. * Converts to a string representation of this Id.
  4360. *
  4361. * @returns return the 24 character hex string representation.
  4362. * @internal
  4363. */
  4364. ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4365. return this.inspect();
  4366. };
  4367. ObjectId.prototype.inspect = function () {
  4368. return "new ObjectId(\"" + this.toHexString() + "\")";
  4369. };
  4370. /** @internal */
  4371. ObjectId.index = Math.floor(Math.random() * 0xffffff);
  4372. return ObjectId;
  4373. }());
  4374. // Deprecated methods
  4375. Object.defineProperty(ObjectId.prototype, 'generate', {
  4376. value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead')
  4377. });
  4378. Object.defineProperty(ObjectId.prototype, 'getInc', {
  4379. value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  4380. });
  4381. Object.defineProperty(ObjectId.prototype, 'get_inc', {
  4382. value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  4383. });
  4384. Object.defineProperty(ObjectId, 'get_inc', {
  4385. value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  4386. });
  4387. Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' });
  4388. function alphabetize(str) {
  4389. return str.split('').sort().join('');
  4390. }
  4391. /**
  4392. * A class representation of the BSON RegExp type.
  4393. * @public
  4394. * @category BSONType
  4395. */
  4396. var BSONRegExp = /** @class */ (function () {
  4397. /**
  4398. * @param pattern - The regular expression pattern to match
  4399. * @param options - The regular expression options
  4400. */
  4401. function BSONRegExp(pattern, options) {
  4402. if (!(this instanceof BSONRegExp))
  4403. return new BSONRegExp(pattern, options);
  4404. this.pattern = pattern;
  4405. this.options = alphabetize(options !== null && options !== void 0 ? options : '');
  4406. if (this.pattern.indexOf('\x00') !== -1) {
  4407. throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern));
  4408. }
  4409. if (this.options.indexOf('\x00') !== -1) {
  4410. throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options));
  4411. }
  4412. // Validate options
  4413. for (var i = 0; i < this.options.length; i++) {
  4414. if (!(this.options[i] === 'i' ||
  4415. this.options[i] === 'm' ||
  4416. this.options[i] === 'x' ||
  4417. this.options[i] === 'l' ||
  4418. this.options[i] === 's' ||
  4419. this.options[i] === 'u')) {
  4420. throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported");
  4421. }
  4422. }
  4423. }
  4424. BSONRegExp.parseOptions = function (options) {
  4425. return options ? options.split('').sort().join('') : '';
  4426. };
  4427. /** @internal */
  4428. BSONRegExp.prototype.toExtendedJSON = function (options) {
  4429. options = options || {};
  4430. if (options.legacy) {
  4431. return { $regex: this.pattern, $options: this.options };
  4432. }
  4433. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  4434. };
  4435. /** @internal */
  4436. BSONRegExp.fromExtendedJSON = function (doc) {
  4437. if ('$regex' in doc) {
  4438. if (typeof doc.$regex !== 'string') {
  4439. // This is for $regex query operators that have extended json values.
  4440. if (doc.$regex._bsontype === 'BSONRegExp') {
  4441. return doc;
  4442. }
  4443. }
  4444. else {
  4445. return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
  4446. }
  4447. }
  4448. if ('$regularExpression' in doc) {
  4449. return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
  4450. }
  4451. throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
  4452. };
  4453. return BSONRegExp;
  4454. }());
  4455. Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' });
  4456. /**
  4457. * A class representation of the BSON Symbol type.
  4458. * @public
  4459. * @category BSONType
  4460. */
  4461. var BSONSymbol = /** @class */ (function () {
  4462. /**
  4463. * @param value - the string representing the symbol.
  4464. */
  4465. function BSONSymbol(value) {
  4466. if (!(this instanceof BSONSymbol))
  4467. return new BSONSymbol(value);
  4468. this.value = value;
  4469. }
  4470. /** Access the wrapped string value. */
  4471. BSONSymbol.prototype.valueOf = function () {
  4472. return this.value;
  4473. };
  4474. BSONSymbol.prototype.toString = function () {
  4475. return this.value;
  4476. };
  4477. /** @internal */
  4478. BSONSymbol.prototype.inspect = function () {
  4479. return "new BSONSymbol(\"" + this.value + "\")";
  4480. };
  4481. BSONSymbol.prototype.toJSON = function () {
  4482. return this.value;
  4483. };
  4484. /** @internal */
  4485. BSONSymbol.prototype.toExtendedJSON = function () {
  4486. return { $symbol: this.value };
  4487. };
  4488. /** @internal */
  4489. BSONSymbol.fromExtendedJSON = function (doc) {
  4490. return new BSONSymbol(doc.$symbol);
  4491. };
  4492. /** @internal */
  4493. BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4494. return this.inspect();
  4495. };
  4496. return BSONSymbol;
  4497. }());
  4498. Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' });
  4499. /** @public */
  4500. var LongWithoutOverridesClass = Long;
  4501. /**
  4502. * @public
  4503. * @category BSONType
  4504. * */
  4505. var Timestamp = /** @class */ (function (_super) {
  4506. __extends(Timestamp, _super);
  4507. function Timestamp(low, high) {
  4508. var _this = this;
  4509. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  4510. ///@ts-expect-error
  4511. if (!(_this instanceof Timestamp))
  4512. return new Timestamp(low, high);
  4513. if (Long.isLong(low)) {
  4514. _this = _super.call(this, low.low, low.high, true) || this;
  4515. }
  4516. else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') {
  4517. _this = _super.call(this, low.i, low.t, true) || this;
  4518. }
  4519. else {
  4520. _this = _super.call(this, low, high, true) || this;
  4521. }
  4522. Object.defineProperty(_this, '_bsontype', {
  4523. value: 'Timestamp',
  4524. writable: false,
  4525. configurable: false,
  4526. enumerable: false
  4527. });
  4528. return _this;
  4529. }
  4530. Timestamp.prototype.toJSON = function () {
  4531. return {
  4532. $timestamp: this.toString()
  4533. };
  4534. };
  4535. /** Returns a Timestamp represented by the given (32-bit) integer value. */
  4536. Timestamp.fromInt = function (value) {
  4537. return new Timestamp(Long.fromInt(value, true));
  4538. };
  4539. /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */
  4540. Timestamp.fromNumber = function (value) {
  4541. return new Timestamp(Long.fromNumber(value, true));
  4542. };
  4543. /**
  4544. * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
  4545. *
  4546. * @param lowBits - the low 32-bits.
  4547. * @param highBits - the high 32-bits.
  4548. */
  4549. Timestamp.fromBits = function (lowBits, highBits) {
  4550. return new Timestamp(lowBits, highBits);
  4551. };
  4552. /**
  4553. * Returns a Timestamp from the given string, optionally using the given radix.
  4554. *
  4555. * @param str - the textual representation of the Timestamp.
  4556. * @param optRadix - the radix in which the text is written.
  4557. */
  4558. Timestamp.fromString = function (str, optRadix) {
  4559. return new Timestamp(Long.fromString(str, true, optRadix));
  4560. };
  4561. /** @internal */
  4562. Timestamp.prototype.toExtendedJSON = function () {
  4563. return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } };
  4564. };
  4565. /** @internal */
  4566. Timestamp.fromExtendedJSON = function (doc) {
  4567. return new Timestamp(doc.$timestamp);
  4568. };
  4569. /** @internal */
  4570. Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4571. return this.inspect();
  4572. };
  4573. Timestamp.prototype.inspect = function () {
  4574. return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })";
  4575. };
  4576. Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
  4577. return Timestamp;
  4578. }(LongWithoutOverridesClass));
  4579. function isBSONType(value) {
  4580. return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string');
  4581. }
  4582. // INT32 boundaries
  4583. var BSON_INT32_MAX$1 = 0x7fffffff;
  4584. var BSON_INT32_MIN$1 = -0x80000000;
  4585. // INT64 boundaries
  4586. var BSON_INT64_MAX$1 = 0x7fffffffffffffff;
  4587. var BSON_INT64_MIN$1 = -0x8000000000000000;
  4588. // all the types where we don't need to do any special processing and can just pass the EJSON
  4589. //straight to type.fromExtendedJSON
  4590. var keysToCodecs = {
  4591. $oid: ObjectId,
  4592. $binary: Binary,
  4593. $uuid: Binary,
  4594. $symbol: BSONSymbol,
  4595. $numberInt: Int32,
  4596. $numberDecimal: Decimal128,
  4597. $numberDouble: Double,
  4598. $numberLong: Long,
  4599. $minKey: MinKey,
  4600. $maxKey: MaxKey,
  4601. $regex: BSONRegExp,
  4602. $regularExpression: BSONRegExp,
  4603. $timestamp: Timestamp
  4604. };
  4605. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4606. function deserializeValue(value, options) {
  4607. if (options === void 0) { options = {}; }
  4608. if (typeof value === 'number') {
  4609. if (options.relaxed || options.legacy) {
  4610. return value;
  4611. }
  4612. // if it's an integer, should interpret as smallest BSON integer
  4613. // that can represent it exactly. (if out of range, interpret as double.)
  4614. if (Math.floor(value) === value) {
  4615. if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1)
  4616. return new Int32(value);
  4617. if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1)
  4618. return Long.fromNumber(value);
  4619. }
  4620. // If the number is a non-integer or out of integer range, should interpret as BSON Double.
  4621. return new Double(value);
  4622. }
  4623. // from here on out we're looking for bson types, so bail if its not an object
  4624. if (value == null || typeof value !== 'object')
  4625. return value;
  4626. // upgrade deprecated undefined to null
  4627. if (value.$undefined)
  4628. return null;
  4629. var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; });
  4630. for (var i = 0; i < keys.length; i++) {
  4631. var c = keysToCodecs[keys[i]];
  4632. if (c)
  4633. return c.fromExtendedJSON(value, options);
  4634. }
  4635. if (value.$date != null) {
  4636. var d = value.$date;
  4637. var date = new Date();
  4638. if (options.legacy) {
  4639. if (typeof d === 'number')
  4640. date.setTime(d);
  4641. else if (typeof d === 'string')
  4642. date.setTime(Date.parse(d));
  4643. }
  4644. else {
  4645. if (typeof d === 'string')
  4646. date.setTime(Date.parse(d));
  4647. else if (Long.isLong(d))
  4648. date.setTime(d.toNumber());
  4649. else if (typeof d === 'number' && options.relaxed)
  4650. date.setTime(d);
  4651. }
  4652. return date;
  4653. }
  4654. if (value.$code != null) {
  4655. var copy = Object.assign({}, value);
  4656. if (value.$scope) {
  4657. copy.$scope = deserializeValue(value.$scope);
  4658. }
  4659. return Code.fromExtendedJSON(value);
  4660. }
  4661. if (isDBRefLike(value) || value.$dbPointer) {
  4662. var v = value.$ref ? value : value.$dbPointer;
  4663. // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
  4664. // because of the order JSON.parse goes through the document
  4665. if (v instanceof DBRef)
  4666. return v;
  4667. var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); });
  4668. var valid_1 = true;
  4669. dollarKeys.forEach(function (k) {
  4670. if (['$ref', '$id', '$db'].indexOf(k) === -1)
  4671. valid_1 = false;
  4672. });
  4673. // only make DBRef if $ keys are all valid
  4674. if (valid_1)
  4675. return DBRef.fromExtendedJSON(v);
  4676. }
  4677. return value;
  4678. }
  4679. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4680. function serializeArray(array, options) {
  4681. return array.map(function (v, index) {
  4682. options.seenObjects.push({ propertyName: "index " + index, obj: null });
  4683. try {
  4684. return serializeValue(v, options);
  4685. }
  4686. finally {
  4687. options.seenObjects.pop();
  4688. }
  4689. });
  4690. }
  4691. function getISOString(date) {
  4692. var isoStr = date.toISOString();
  4693. // we should only show milliseconds in timestamp if they're non-zero
  4694. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  4695. }
  4696. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4697. function serializeValue(value, options) {
  4698. if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
  4699. var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; });
  4700. if (index !== -1) {
  4701. var props = options.seenObjects.map(function (entry) { return entry.propertyName; });
  4702. var leadingPart = props
  4703. .slice(0, index)
  4704. .map(function (prop) { return prop + " -> "; })
  4705. .join('');
  4706. var alreadySeen = props[index];
  4707. var circularPart = ' -> ' +
  4708. props
  4709. .slice(index + 1, props.length - 1)
  4710. .map(function (prop) { return prop + " -> "; })
  4711. .join('');
  4712. var current = props[props.length - 1];
  4713. var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
  4714. var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
  4715. throw new BSONTypeError('Converting circular structure to EJSON:\n' +
  4716. (" " + leadingPart + alreadySeen + circularPart + current + "\n") +
  4717. (" " + leadingSpace + "\\" + dashes + "/"));
  4718. }
  4719. options.seenObjects[options.seenObjects.length - 1].obj = value;
  4720. }
  4721. if (Array.isArray(value))
  4722. return serializeArray(value, options);
  4723. if (value === undefined)
  4724. return null;
  4725. if (value instanceof Date || isDate(value)) {
  4726. var dateNum = value.getTime(),
  4727. // is it in year range 1970-9999?
  4728. inRange = dateNum > -1 && dateNum < 253402318800000;
  4729. if (options.legacy) {
  4730. return options.relaxed && inRange
  4731. ? { $date: value.getTime() }
  4732. : { $date: getISOString(value) };
  4733. }
  4734. return options.relaxed && inRange
  4735. ? { $date: getISOString(value) }
  4736. : { $date: { $numberLong: value.getTime().toString() } };
  4737. }
  4738. if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
  4739. // it's an integer
  4740. if (Math.floor(value) === value) {
  4741. var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1;
  4742. // interpret as being of the smallest BSON integer type that can represent the number exactly
  4743. if (int32Range)
  4744. return { $numberInt: value.toString() };
  4745. if (int64Range)
  4746. return { $numberLong: value.toString() };
  4747. }
  4748. return { $numberDouble: value.toString() };
  4749. }
  4750. if (value instanceof RegExp || isRegExp(value)) {
  4751. var flags = value.flags;
  4752. if (flags === undefined) {
  4753. var match = value.toString().match(/[gimuy]*$/);
  4754. if (match) {
  4755. flags = match[0];
  4756. }
  4757. }
  4758. var rx = new BSONRegExp(value.source, flags);
  4759. return rx.toExtendedJSON(options);
  4760. }
  4761. if (value != null && typeof value === 'object')
  4762. return serializeDocument(value, options);
  4763. return value;
  4764. }
  4765. var BSON_TYPE_MAPPINGS = {
  4766. Binary: function (o) { return new Binary(o.value(), o.sub_type); },
  4767. Code: function (o) { return new Code(o.code, o.scope); },
  4768. DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); },
  4769. Decimal128: function (o) { return new Decimal128(o.bytes); },
  4770. Double: function (o) { return new Double(o.value); },
  4771. Int32: function (o) { return new Int32(o.value); },
  4772. Long: function (o) {
  4773. return Long.fromBits(
  4774. // underscore variants for 1.x backwards compatibility
  4775. o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_);
  4776. },
  4777. MaxKey: function () { return new MaxKey(); },
  4778. MinKey: function () { return new MinKey(); },
  4779. ObjectID: function (o) { return new ObjectId(o); },
  4780. ObjectId: function (o) { return new ObjectId(o); },
  4781. BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); },
  4782. Symbol: function (o) { return new BSONSymbol(o.value); },
  4783. Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); }
  4784. };
  4785. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4786. function serializeDocument(doc, options) {
  4787. if (doc == null || typeof doc !== 'object')
  4788. throw new BSONError('not an object instance');
  4789. var bsontype = doc._bsontype;
  4790. if (typeof bsontype === 'undefined') {
  4791. // It's a regular object. Recursively serialize its property values.
  4792. var _doc = {};
  4793. for (var name in doc) {
  4794. options.seenObjects.push({ propertyName: name, obj: null });
  4795. try {
  4796. _doc[name] = serializeValue(doc[name], options);
  4797. }
  4798. finally {
  4799. options.seenObjects.pop();
  4800. }
  4801. }
  4802. return _doc;
  4803. }
  4804. else if (isBSONType(doc)) {
  4805. // the "document" is really just a BSON type object
  4806. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4807. var outDoc = doc;
  4808. if (typeof outDoc.toExtendedJSON !== 'function') {
  4809. // There's no EJSON serialization function on the object. It's probably an
  4810. // object created by a previous version of this library (or another library)
  4811. // that's duck-typing objects to look like they were generated by this library).
  4812. // Copy the object into this library's version of that type.
  4813. var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
  4814. if (!mapper) {
  4815. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
  4816. }
  4817. outDoc = mapper(outDoc);
  4818. }
  4819. // Two BSON types may have nested objects that may need to be serialized too
  4820. if (bsontype === 'Code' && outDoc.scope) {
  4821. outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
  4822. }
  4823. else if (bsontype === 'DBRef' && outDoc.oid) {
  4824. outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
  4825. }
  4826. return outDoc.toExtendedJSON(options);
  4827. }
  4828. else {
  4829. throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
  4830. }
  4831. }
  4832. /**
  4833. * EJSON parse / stringify API
  4834. * @public
  4835. */
  4836. // the namespace here is used to emulate `export * as EJSON from '...'`
  4837. // which as of now (sept 2020) api-extractor does not support
  4838. // eslint-disable-next-line @typescript-eslint/no-namespace
  4839. exports.EJSON = void 0;
  4840. (function (EJSON) {
  4841. /**
  4842. * Parse an Extended JSON string, constructing the JavaScript value or object described by that
  4843. * string.
  4844. *
  4845. * @example
  4846. * ```js
  4847. * const { EJSON } = require('bson');
  4848. * const text = '{ "int32": { "$numberInt": "10" } }';
  4849. *
  4850. * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
  4851. * console.log(EJSON.parse(text, { relaxed: false }));
  4852. *
  4853. * // prints { int32: 10 }
  4854. * console.log(EJSON.parse(text));
  4855. * ```
  4856. */
  4857. function parse(text, options) {
  4858. var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options);
  4859. // relaxed implies not strict
  4860. if (typeof finalOptions.relaxed === 'boolean')
  4861. finalOptions.strict = !finalOptions.relaxed;
  4862. if (typeof finalOptions.strict === 'boolean')
  4863. finalOptions.relaxed = !finalOptions.strict;
  4864. return JSON.parse(text, function (key, value) {
  4865. if (key.indexOf('\x00') !== -1) {
  4866. throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key));
  4867. }
  4868. return deserializeValue(value, finalOptions);
  4869. });
  4870. }
  4871. EJSON.parse = parse;
  4872. /**
  4873. * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
  4874. * function is specified or optionally including only the specified properties if a replacer array
  4875. * is specified.
  4876. *
  4877. * @param value - The value to convert to extended JSON
  4878. * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
  4879. * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
  4880. * @param options - Optional settings
  4881. *
  4882. * @example
  4883. * ```js
  4884. * const { EJSON } = require('bson');
  4885. * const Int32 = require('mongodb').Int32;
  4886. * const doc = { int32: new Int32(10) };
  4887. *
  4888. * // prints '{"int32":{"$numberInt":"10"}}'
  4889. * console.log(EJSON.stringify(doc, { relaxed: false }));
  4890. *
  4891. * // prints '{"int32":10}'
  4892. * console.log(EJSON.stringify(doc));
  4893. * ```
  4894. */
  4895. function stringify(value,
  4896. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4897. replacer, space, options) {
  4898. if (space != null && typeof space === 'object') {
  4899. options = space;
  4900. space = 0;
  4901. }
  4902. if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
  4903. options = replacer;
  4904. replacer = undefined;
  4905. space = 0;
  4906. }
  4907. var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
  4908. seenObjects: [{ propertyName: '(root)', obj: null }]
  4909. });
  4910. var doc = serializeValue(value, serializeOptions);
  4911. return JSON.stringify(doc, replacer, space);
  4912. }
  4913. EJSON.stringify = stringify;
  4914. /**
  4915. * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
  4916. *
  4917. * @param value - The object to serialize
  4918. * @param options - Optional settings passed to the `stringify` function
  4919. */
  4920. function serialize(value, options) {
  4921. options = options || {};
  4922. return JSON.parse(stringify(value, options));
  4923. }
  4924. EJSON.serialize = serialize;
  4925. /**
  4926. * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
  4927. *
  4928. * @param ejson - The Extended JSON object to deserialize
  4929. * @param options - Optional settings passed to the parse method
  4930. */
  4931. function deserialize(ejson, options) {
  4932. options = options || {};
  4933. return parse(JSON.stringify(ejson), options);
  4934. }
  4935. EJSON.deserialize = deserialize;
  4936. })(exports.EJSON || (exports.EJSON = {}));
  4937. /* eslint-disable @typescript-eslint/no-explicit-any */
  4938. /** @public */
  4939. exports.Map = void 0;
  4940. var bsonGlobal = getGlobal();
  4941. if (bsonGlobal.Map) {
  4942. exports.Map = bsonGlobal.Map;
  4943. }
  4944. else {
  4945. // We will return a polyfill
  4946. exports.Map = /** @class */ (function () {
  4947. function Map(array) {
  4948. if (array === void 0) { array = []; }
  4949. this._keys = [];
  4950. this._values = {};
  4951. for (var i = 0; i < array.length; i++) {
  4952. if (array[i] == null)
  4953. continue; // skip null and undefined
  4954. var entry = array[i];
  4955. var key = entry[0];
  4956. var value = entry[1];
  4957. // Add the key to the list of keys in order
  4958. this._keys.push(key);
  4959. // Add the key and value to the values dictionary with a point
  4960. // to the location in the ordered keys list
  4961. this._values[key] = { v: value, i: this._keys.length - 1 };
  4962. }
  4963. }
  4964. Map.prototype.clear = function () {
  4965. this._keys = [];
  4966. this._values = {};
  4967. };
  4968. Map.prototype.delete = function (key) {
  4969. var value = this._values[key];
  4970. if (value == null)
  4971. return false;
  4972. // Delete entry
  4973. delete this._values[key];
  4974. // Remove the key from the ordered keys list
  4975. this._keys.splice(value.i, 1);
  4976. return true;
  4977. };
  4978. Map.prototype.entries = function () {
  4979. var _this = this;
  4980. var index = 0;
  4981. return {
  4982. next: function () {
  4983. var key = _this._keys[index++];
  4984. return {
  4985. value: key !== undefined ? [key, _this._values[key].v] : undefined,
  4986. done: key !== undefined ? false : true
  4987. };
  4988. }
  4989. };
  4990. };
  4991. Map.prototype.forEach = function (callback, self) {
  4992. self = self || this;
  4993. for (var i = 0; i < this._keys.length; i++) {
  4994. var key = this._keys[i];
  4995. // Call the forEach callback
  4996. callback.call(self, this._values[key].v, key, self);
  4997. }
  4998. };
  4999. Map.prototype.get = function (key) {
  5000. return this._values[key] ? this._values[key].v : undefined;
  5001. };
  5002. Map.prototype.has = function (key) {
  5003. return this._values[key] != null;
  5004. };
  5005. Map.prototype.keys = function () {
  5006. var _this = this;
  5007. var index = 0;
  5008. return {
  5009. next: function () {
  5010. var key = _this._keys[index++];
  5011. return {
  5012. value: key !== undefined ? key : undefined,
  5013. done: key !== undefined ? false : true
  5014. };
  5015. }
  5016. };
  5017. };
  5018. Map.prototype.set = function (key, value) {
  5019. if (this._values[key]) {
  5020. this._values[key].v = value;
  5021. return this;
  5022. }
  5023. // Add the key to the list of keys in order
  5024. this._keys.push(key);
  5025. // Add the key and value to the values dictionary with a point
  5026. // to the location in the ordered keys list
  5027. this._values[key] = { v: value, i: this._keys.length - 1 };
  5028. return this;
  5029. };
  5030. Map.prototype.values = function () {
  5031. var _this = this;
  5032. var index = 0;
  5033. return {
  5034. next: function () {
  5035. var key = _this._keys[index++];
  5036. return {
  5037. value: key !== undefined ? _this._values[key].v : undefined,
  5038. done: key !== undefined ? false : true
  5039. };
  5040. }
  5041. };
  5042. };
  5043. Object.defineProperty(Map.prototype, "size", {
  5044. get: function () {
  5045. return this._keys.length;
  5046. },
  5047. enumerable: false,
  5048. configurable: true
  5049. });
  5050. return Map;
  5051. }());
  5052. }
  5053. /** @internal */
  5054. var BSON_INT32_MAX = 0x7fffffff;
  5055. /** @internal */
  5056. var BSON_INT32_MIN = -0x80000000;
  5057. /** @internal */
  5058. var BSON_INT64_MAX = Math.pow(2, 63) - 1;
  5059. /** @internal */
  5060. var BSON_INT64_MIN = -Math.pow(2, 63);
  5061. /**
  5062. * Any integer up to 2^53 can be precisely represented by a double.
  5063. * @internal
  5064. */
  5065. var JS_INT_MAX = Math.pow(2, 53);
  5066. /**
  5067. * Any integer down to -2^53 can be precisely represented by a double.
  5068. * @internal
  5069. */
  5070. var JS_INT_MIN = -Math.pow(2, 53);
  5071. /** Number BSON Type @internal */
  5072. var BSON_DATA_NUMBER = 1;
  5073. /** String BSON Type @internal */
  5074. var BSON_DATA_STRING = 2;
  5075. /** Object BSON Type @internal */
  5076. var BSON_DATA_OBJECT = 3;
  5077. /** Array BSON Type @internal */
  5078. var BSON_DATA_ARRAY = 4;
  5079. /** Binary BSON Type @internal */
  5080. var BSON_DATA_BINARY = 5;
  5081. /** Binary BSON Type @internal */
  5082. var BSON_DATA_UNDEFINED = 6;
  5083. /** ObjectId BSON Type @internal */
  5084. var BSON_DATA_OID = 7;
  5085. /** Boolean BSON Type @internal */
  5086. var BSON_DATA_BOOLEAN = 8;
  5087. /** Date BSON Type @internal */
  5088. var BSON_DATA_DATE = 9;
  5089. /** null BSON Type @internal */
  5090. var BSON_DATA_NULL = 10;
  5091. /** RegExp BSON Type @internal */
  5092. var BSON_DATA_REGEXP = 11;
  5093. /** Code BSON Type @internal */
  5094. var BSON_DATA_DBPOINTER = 12;
  5095. /** Code BSON Type @internal */
  5096. var BSON_DATA_CODE = 13;
  5097. /** Symbol BSON Type @internal */
  5098. var BSON_DATA_SYMBOL = 14;
  5099. /** Code with Scope BSON Type @internal */
  5100. var BSON_DATA_CODE_W_SCOPE = 15;
  5101. /** 32 bit Integer BSON Type @internal */
  5102. var BSON_DATA_INT = 16;
  5103. /** Timestamp BSON Type @internal */
  5104. var BSON_DATA_TIMESTAMP = 17;
  5105. /** Long BSON Type @internal */
  5106. var BSON_DATA_LONG = 18;
  5107. /** Decimal128 BSON Type @internal */
  5108. var BSON_DATA_DECIMAL128 = 19;
  5109. /** MinKey BSON Type @internal */
  5110. var BSON_DATA_MIN_KEY = 0xff;
  5111. /** MaxKey BSON Type @internal */
  5112. var BSON_DATA_MAX_KEY = 0x7f;
  5113. /** Binary Default Type @internal */
  5114. var BSON_BINARY_SUBTYPE_DEFAULT = 0;
  5115. /** Binary Function Type @internal */
  5116. var BSON_BINARY_SUBTYPE_FUNCTION = 1;
  5117. /** Binary Byte Array Type @internal */
  5118. var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
  5119. /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */
  5120. var BSON_BINARY_SUBTYPE_UUID = 3;
  5121. /** Binary UUID Type @internal */
  5122. var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
  5123. /** Binary MD5 Type @internal */
  5124. var BSON_BINARY_SUBTYPE_MD5 = 5;
  5125. /** Encrypted BSON type @internal */
  5126. var BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
  5127. /** Column BSON type @internal */
  5128. var BSON_BINARY_SUBTYPE_COLUMN = 7;
  5129. /** Binary User Defined Type @internal */
  5130. var BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
  5131. function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) {
  5132. var totalLength = 4 + 1;
  5133. if (Array.isArray(object)) {
  5134. for (var i = 0; i < object.length; i++) {
  5135. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  5136. }
  5137. }
  5138. else {
  5139. // If we have toBSON defined, override the current object
  5140. if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
  5141. object = object.toBSON();
  5142. }
  5143. // Calculate size
  5144. for (var key in object) {
  5145. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  5146. }
  5147. }
  5148. return totalLength;
  5149. }
  5150. /** @internal */
  5151. function calculateElement(name,
  5152. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5153. value, serializeFunctions, isArray, ignoreUndefined) {
  5154. if (serializeFunctions === void 0) { serializeFunctions = false; }
  5155. if (isArray === void 0) { isArray = false; }
  5156. if (ignoreUndefined === void 0) { ignoreUndefined = false; }
  5157. // If we have toBSON defined, override the current object
  5158. if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
  5159. value = value.toBSON();
  5160. }
  5161. switch (typeof value) {
  5162. case 'string':
  5163. return 1 + buffer_1.byteLength(name, 'utf8') + 1 + 4 + buffer_1.byteLength(value, 'utf8') + 1;
  5164. case 'number':
  5165. if (Math.floor(value) === value &&
  5166. value >= JS_INT_MIN &&
  5167. value <= JS_INT_MAX) {
  5168. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  5169. // 32 bit
  5170. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (4 + 1);
  5171. }
  5172. else {
  5173. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  5174. }
  5175. }
  5176. else {
  5177. // 64 bit
  5178. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  5179. }
  5180. case 'undefined':
  5181. if (isArray || !ignoreUndefined)
  5182. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1;
  5183. return 0;
  5184. case 'boolean':
  5185. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 1);
  5186. case 'object':
  5187. if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  5188. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1;
  5189. }
  5190. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  5191. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (12 + 1);
  5192. }
  5193. else if (value instanceof Date || isDate(value)) {
  5194. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  5195. }
  5196. else if (ArrayBuffer.isView(value) ||
  5197. value instanceof ArrayBuffer ||
  5198. isAnyArrayBuffer(value)) {
  5199. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength);
  5200. }
  5201. else if (value['_bsontype'] === 'Long' ||
  5202. value['_bsontype'] === 'Double' ||
  5203. value['_bsontype'] === 'Timestamp') {
  5204. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  5205. }
  5206. else if (value['_bsontype'] === 'Decimal128') {
  5207. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (16 + 1);
  5208. }
  5209. else if (value['_bsontype'] === 'Code') {
  5210. // Calculate size depending on the availability of a scope
  5211. if (value.scope != null && Object.keys(value.scope).length > 0) {
  5212. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5213. 1 +
  5214. 4 +
  5215. 4 +
  5216. buffer_1.byteLength(value.code.toString(), 'utf8') +
  5217. 1 +
  5218. calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined));
  5219. }
  5220. else {
  5221. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5222. 1 +
  5223. 4 +
  5224. buffer_1.byteLength(value.code.toString(), 'utf8') +
  5225. 1);
  5226. }
  5227. }
  5228. else if (value['_bsontype'] === 'Binary') {
  5229. // Check what kind of subtype we have
  5230. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  5231. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5232. (value.position + 1 + 4 + 1 + 4));
  5233. }
  5234. else {
  5235. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1));
  5236. }
  5237. }
  5238. else if (value['_bsontype'] === 'Symbol') {
  5239. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5240. buffer_1.byteLength(value.value, 'utf8') +
  5241. 4 +
  5242. 1 +
  5243. 1);
  5244. }
  5245. else if (value['_bsontype'] === 'DBRef') {
  5246. // Set up correct object for serialization
  5247. var ordered_values = Object.assign({
  5248. $ref: value.collection,
  5249. $id: value.oid
  5250. }, value.fields);
  5251. // Add db reference if it exists
  5252. if (value.db != null) {
  5253. ordered_values['$db'] = value.db;
  5254. }
  5255. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5256. 1 +
  5257. calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined));
  5258. }
  5259. else if (value instanceof RegExp || isRegExp(value)) {
  5260. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5261. 1 +
  5262. buffer_1.byteLength(value.source, 'utf8') +
  5263. 1 +
  5264. (value.global ? 1 : 0) +
  5265. (value.ignoreCase ? 1 : 0) +
  5266. (value.multiline ? 1 : 0) +
  5267. 1);
  5268. }
  5269. else if (value['_bsontype'] === 'BSONRegExp') {
  5270. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5271. 1 +
  5272. buffer_1.byteLength(value.pattern, 'utf8') +
  5273. 1 +
  5274. buffer_1.byteLength(value.options, 'utf8') +
  5275. 1);
  5276. }
  5277. else {
  5278. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5279. calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) +
  5280. 1);
  5281. }
  5282. case 'function':
  5283. // WTF for 0.4.X where typeof /someregexp/ === 'function'
  5284. if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') {
  5285. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5286. 1 +
  5287. buffer_1.byteLength(value.source, 'utf8') +
  5288. 1 +
  5289. (value.global ? 1 : 0) +
  5290. (value.ignoreCase ? 1 : 0) +
  5291. (value.multiline ? 1 : 0) +
  5292. 1);
  5293. }
  5294. else {
  5295. if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
  5296. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5297. 1 +
  5298. 4 +
  5299. 4 +
  5300. buffer_1.byteLength(normalizedFunctionString(value), 'utf8') +
  5301. 1 +
  5302. calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined));
  5303. }
  5304. else if (serializeFunctions) {
  5305. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5306. 1 +
  5307. 4 +
  5308. buffer_1.byteLength(normalizedFunctionString(value), 'utf8') +
  5309. 1);
  5310. }
  5311. }
  5312. }
  5313. return 0;
  5314. }
  5315. var FIRST_BIT = 0x80;
  5316. var FIRST_TWO_BITS = 0xc0;
  5317. var FIRST_THREE_BITS = 0xe0;
  5318. var FIRST_FOUR_BITS = 0xf0;
  5319. var FIRST_FIVE_BITS = 0xf8;
  5320. var TWO_BIT_CHAR = 0xc0;
  5321. var THREE_BIT_CHAR = 0xe0;
  5322. var FOUR_BIT_CHAR = 0xf0;
  5323. var CONTINUING_CHAR = 0x80;
  5324. /**
  5325. * Determines if the passed in bytes are valid utf8
  5326. * @param bytes - An array of 8-bit bytes. Must be indexable and have length property
  5327. * @param start - The index to start validating
  5328. * @param end - The index to end validating
  5329. */
  5330. function validateUtf8(bytes, start, end) {
  5331. var continuation = 0;
  5332. for (var i = start; i < end; i += 1) {
  5333. var byte = bytes[i];
  5334. if (continuation) {
  5335. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  5336. return false;
  5337. }
  5338. continuation -= 1;
  5339. }
  5340. else if (byte & FIRST_BIT) {
  5341. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  5342. continuation = 1;
  5343. }
  5344. else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  5345. continuation = 2;
  5346. }
  5347. else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  5348. continuation = 3;
  5349. }
  5350. else {
  5351. return false;
  5352. }
  5353. }
  5354. }
  5355. return !continuation;
  5356. }
  5357. // Internal long versions
  5358. var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
  5359. var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
  5360. var functionCache = {};
  5361. function deserialize$1(buffer, options, isArray) {
  5362. options = options == null ? {} : options;
  5363. var index = options && options.index ? options.index : 0;
  5364. // Read the document size
  5365. var size = buffer[index] |
  5366. (buffer[index + 1] << 8) |
  5367. (buffer[index + 2] << 16) |
  5368. (buffer[index + 3] << 24);
  5369. if (size < 5) {
  5370. throw new BSONError("bson size must be >= 5, is " + size);
  5371. }
  5372. if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
  5373. throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size);
  5374. }
  5375. if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
  5376. throw new BSONError("buffer length " + buffer.length + " must === bson size " + size);
  5377. }
  5378. if (size + index > buffer.byteLength) {
  5379. throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
  5380. }
  5381. // Illegal end value
  5382. if (buffer[index + size - 1] !== 0) {
  5383. throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  5384. }
  5385. // Start deserializtion
  5386. return deserializeObject(buffer, index, options, isArray);
  5387. }
  5388. var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
  5389. function deserializeObject(buffer, index, options, isArray) {
  5390. if (isArray === void 0) { isArray = false; }
  5391. var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];
  5392. var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];
  5393. var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
  5394. // Return raw bson buffer instead of parsing it
  5395. var raw = options['raw'] == null ? false : options['raw'];
  5396. // Return BSONRegExp objects instead of native regular expressions
  5397. var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
  5398. // Controls the promotion of values vs wrapper classes
  5399. var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
  5400. var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
  5401. var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
  5402. // Ensures default validation option if none given
  5403. var validation = options.validation == null ? { utf8: true } : options.validation;
  5404. // Shows if global utf-8 validation is enabled or disabled
  5405. var globalUTFValidation = true;
  5406. // Reflects utf-8 validation setting regardless of global or specific key validation
  5407. var validationSetting;
  5408. // Set of keys either to enable or disable validation on
  5409. var utf8KeysSet = new Set();
  5410. // Check for boolean uniformity and empty validation option
  5411. var utf8ValidatedKeys = validation.utf8;
  5412. if (typeof utf8ValidatedKeys === 'boolean') {
  5413. validationSetting = utf8ValidatedKeys;
  5414. }
  5415. else {
  5416. globalUTFValidation = false;
  5417. var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
  5418. return utf8ValidatedKeys[key];
  5419. });
  5420. if (utf8ValidationValues.length === 0) {
  5421. throw new BSONError('UTF-8 validation setting cannot be empty');
  5422. }
  5423. if (typeof utf8ValidationValues[0] !== 'boolean') {
  5424. throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
  5425. }
  5426. validationSetting = utf8ValidationValues[0];
  5427. // Ensures boolean uniformity in utf-8 validation (all true or all false)
  5428. if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) {
  5429. throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
  5430. }
  5431. }
  5432. // Add keys to set that will either be validated or not based on validationSetting
  5433. if (!globalUTFValidation) {
  5434. for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) {
  5435. var key = _a[_i];
  5436. utf8KeysSet.add(key);
  5437. }
  5438. }
  5439. // Set the start index
  5440. var startIndex = index;
  5441. // Validate that we have at least 4 bytes of buffer
  5442. if (buffer.length < 5)
  5443. throw new BSONError('corrupt bson message < 5 bytes long');
  5444. // Read the document size
  5445. var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  5446. // Ensure buffer is valid size
  5447. if (size < 5 || size > buffer.length)
  5448. throw new BSONError('corrupt bson message');
  5449. // Create holding object
  5450. var object = isArray ? [] : {};
  5451. // Used for arrays to skip having to perform utf8 decoding
  5452. var arrayIndex = 0;
  5453. var done = false;
  5454. var isPossibleDBRef = isArray ? false : null;
  5455. // While we have more left data left keep parsing
  5456. while (!done) {
  5457. // Read the type
  5458. var elementType = buffer[index++];
  5459. // If we get a zero it's the last byte, exit
  5460. if (elementType === 0)
  5461. break;
  5462. // Get the start search index
  5463. var i = index;
  5464. // Locate the end of the c string
  5465. while (buffer[i] !== 0x00 && i < buffer.length) {
  5466. i++;
  5467. }
  5468. // If are at the end of the buffer there is a problem with the document
  5469. if (i >= buffer.byteLength)
  5470. throw new BSONError('Bad BSON Document: illegal CString');
  5471. // Represents the key
  5472. var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);
  5473. // shouldValidateKey is true if the key should be validated, false otherwise
  5474. var shouldValidateKey = true;
  5475. if (globalUTFValidation || utf8KeysSet.has(name)) {
  5476. shouldValidateKey = validationSetting;
  5477. }
  5478. else {
  5479. shouldValidateKey = !validationSetting;
  5480. }
  5481. if (isPossibleDBRef !== false && name[0] === '$') {
  5482. isPossibleDBRef = allowedDBRefKeys.test(name);
  5483. }
  5484. var value = void 0;
  5485. index = i + 1;
  5486. if (elementType === BSON_DATA_STRING) {
  5487. var stringSize = buffer[index++] |
  5488. (buffer[index++] << 8) |
  5489. (buffer[index++] << 16) |
  5490. (buffer[index++] << 24);
  5491. if (stringSize <= 0 ||
  5492. stringSize > buffer.length - index ||
  5493. buffer[index + stringSize - 1] !== 0) {
  5494. throw new BSONError('bad string length in bson');
  5495. }
  5496. value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  5497. index = index + stringSize;
  5498. }
  5499. else if (elementType === BSON_DATA_OID) {
  5500. var oid = buffer_1.alloc(12);
  5501. buffer.copy(oid, 0, index, index + 12);
  5502. value = new ObjectId(oid);
  5503. index = index + 12;
  5504. }
  5505. else if (elementType === BSON_DATA_INT && promoteValues === false) {
  5506. value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24));
  5507. }
  5508. else if (elementType === BSON_DATA_INT) {
  5509. value =
  5510. buffer[index++] |
  5511. (buffer[index++] << 8) |
  5512. (buffer[index++] << 16) |
  5513. (buffer[index++] << 24);
  5514. }
  5515. else if (elementType === BSON_DATA_NUMBER && promoteValues === false) {
  5516. value = new Double(buffer.readDoubleLE(index));
  5517. index = index + 8;
  5518. }
  5519. else if (elementType === BSON_DATA_NUMBER) {
  5520. value = buffer.readDoubleLE(index);
  5521. index = index + 8;
  5522. }
  5523. else if (elementType === BSON_DATA_DATE) {
  5524. var lowBits = buffer[index++] |
  5525. (buffer[index++] << 8) |
  5526. (buffer[index++] << 16) |
  5527. (buffer[index++] << 24);
  5528. var highBits = buffer[index++] |
  5529. (buffer[index++] << 8) |
  5530. (buffer[index++] << 16) |
  5531. (buffer[index++] << 24);
  5532. value = new Date(new Long(lowBits, highBits).toNumber());
  5533. }
  5534. else if (elementType === BSON_DATA_BOOLEAN) {
  5535. if (buffer[index] !== 0 && buffer[index] !== 1)
  5536. throw new BSONError('illegal boolean type value');
  5537. value = buffer[index++] === 1;
  5538. }
  5539. else if (elementType === BSON_DATA_OBJECT) {
  5540. var _index = index;
  5541. var objectSize = buffer[index] |
  5542. (buffer[index + 1] << 8) |
  5543. (buffer[index + 2] << 16) |
  5544. (buffer[index + 3] << 24);
  5545. if (objectSize <= 0 || objectSize > buffer.length - index)
  5546. throw new BSONError('bad embedded document length in bson');
  5547. // We have a raw value
  5548. if (raw) {
  5549. value = buffer.slice(index, index + objectSize);
  5550. }
  5551. else {
  5552. var objectOptions = options;
  5553. if (!globalUTFValidation) {
  5554. objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } });
  5555. }
  5556. value = deserializeObject(buffer, _index, objectOptions, false);
  5557. }
  5558. index = index + objectSize;
  5559. }
  5560. else if (elementType === BSON_DATA_ARRAY) {
  5561. var _index = index;
  5562. var objectSize = buffer[index] |
  5563. (buffer[index + 1] << 8) |
  5564. (buffer[index + 2] << 16) |
  5565. (buffer[index + 3] << 24);
  5566. var arrayOptions = options;
  5567. // Stop index
  5568. var stopIndex = index + objectSize;
  5569. // All elements of array to be returned as raw bson
  5570. if (fieldsAsRaw && fieldsAsRaw[name]) {
  5571. arrayOptions = {};
  5572. for (var n in options) {
  5573. arrayOptions[n] = options[n];
  5574. }
  5575. arrayOptions['raw'] = true;
  5576. }
  5577. if (!globalUTFValidation) {
  5578. arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } });
  5579. }
  5580. value = deserializeObject(buffer, _index, arrayOptions, true);
  5581. index = index + objectSize;
  5582. if (buffer[index - 1] !== 0)
  5583. throw new BSONError('invalid array terminator byte');
  5584. if (index !== stopIndex)
  5585. throw new BSONError('corrupted array bson');
  5586. }
  5587. else if (elementType === BSON_DATA_UNDEFINED) {
  5588. value = undefined;
  5589. }
  5590. else if (elementType === BSON_DATA_NULL) {
  5591. value = null;
  5592. }
  5593. else if (elementType === BSON_DATA_LONG) {
  5594. // Unpack the low and high bits
  5595. var lowBits = buffer[index++] |
  5596. (buffer[index++] << 8) |
  5597. (buffer[index++] << 16) |
  5598. (buffer[index++] << 24);
  5599. var highBits = buffer[index++] |
  5600. (buffer[index++] << 8) |
  5601. (buffer[index++] << 16) |
  5602. (buffer[index++] << 24);
  5603. var long = new Long(lowBits, highBits);
  5604. // Promote the long if possible
  5605. if (promoteLongs && promoteValues === true) {
  5606. value =
  5607. long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
  5608. ? long.toNumber()
  5609. : long;
  5610. }
  5611. else {
  5612. value = long;
  5613. }
  5614. }
  5615. else if (elementType === BSON_DATA_DECIMAL128) {
  5616. // Buffer to contain the decimal bytes
  5617. var bytes = buffer_1.alloc(16);
  5618. // Copy the next 16 bytes into the bytes buffer
  5619. buffer.copy(bytes, 0, index, index + 16);
  5620. // Update index
  5621. index = index + 16;
  5622. // Assign the new Decimal128 value
  5623. var decimal128 = new Decimal128(bytes);
  5624. // If we have an alternative mapper use that
  5625. if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') {
  5626. value = decimal128.toObject();
  5627. }
  5628. else {
  5629. value = decimal128;
  5630. }
  5631. }
  5632. else if (elementType === BSON_DATA_BINARY) {
  5633. var binarySize = buffer[index++] |
  5634. (buffer[index++] << 8) |
  5635. (buffer[index++] << 16) |
  5636. (buffer[index++] << 24);
  5637. var totalBinarySize = binarySize;
  5638. var subType = buffer[index++];
  5639. // Did we have a negative binary size, throw
  5640. if (binarySize < 0)
  5641. throw new BSONError('Negative binary type element size found');
  5642. // Is the length longer than the document
  5643. if (binarySize > buffer.byteLength)
  5644. throw new BSONError('Binary type size larger than document size');
  5645. // Decode as raw Buffer object if options specifies it
  5646. if (buffer['slice'] != null) {
  5647. // If we have subtype 2 skip the 4 bytes for the size
  5648. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  5649. binarySize =
  5650. buffer[index++] |
  5651. (buffer[index++] << 8) |
  5652. (buffer[index++] << 16) |
  5653. (buffer[index++] << 24);
  5654. if (binarySize < 0)
  5655. throw new BSONError('Negative binary type element size found for subtype 0x02');
  5656. if (binarySize > totalBinarySize - 4)
  5657. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  5658. if (binarySize < totalBinarySize - 4)
  5659. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  5660. }
  5661. if (promoteBuffers && promoteValues) {
  5662. value = buffer.slice(index, index + binarySize);
  5663. }
  5664. else {
  5665. value = new Binary(buffer.slice(index, index + binarySize), subType);
  5666. }
  5667. }
  5668. else {
  5669. var _buffer = buffer_1.alloc(binarySize);
  5670. // If we have subtype 2 skip the 4 bytes for the size
  5671. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  5672. binarySize =
  5673. buffer[index++] |
  5674. (buffer[index++] << 8) |
  5675. (buffer[index++] << 16) |
  5676. (buffer[index++] << 24);
  5677. if (binarySize < 0)
  5678. throw new BSONError('Negative binary type element size found for subtype 0x02');
  5679. if (binarySize > totalBinarySize - 4)
  5680. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  5681. if (binarySize < totalBinarySize - 4)
  5682. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  5683. }
  5684. // Copy the data
  5685. for (i = 0; i < binarySize; i++) {
  5686. _buffer[i] = buffer[index + i];
  5687. }
  5688. if (promoteBuffers && promoteValues) {
  5689. value = _buffer;
  5690. }
  5691. else {
  5692. value = new Binary(_buffer, subType);
  5693. }
  5694. }
  5695. // Update the index
  5696. index = index + binarySize;
  5697. }
  5698. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
  5699. // Get the start search index
  5700. i = index;
  5701. // Locate the end of the c string
  5702. while (buffer[i] !== 0x00 && i < buffer.length) {
  5703. i++;
  5704. }
  5705. // If are at the end of the buffer there is a problem with the document
  5706. if (i >= buffer.length)
  5707. throw new BSONError('Bad BSON Document: illegal CString');
  5708. // Return the C string
  5709. var source = buffer.toString('utf8', index, i);
  5710. // Create the regexp
  5711. index = i + 1;
  5712. // Get the start search index
  5713. i = index;
  5714. // Locate the end of the c string
  5715. while (buffer[i] !== 0x00 && i < buffer.length) {
  5716. i++;
  5717. }
  5718. // If are at the end of the buffer there is a problem with the document
  5719. if (i >= buffer.length)
  5720. throw new BSONError('Bad BSON Document: illegal CString');
  5721. // Return the C string
  5722. var regExpOptions = buffer.toString('utf8', index, i);
  5723. index = i + 1;
  5724. // For each option add the corresponding one for javascript
  5725. var optionsArray = new Array(regExpOptions.length);
  5726. // Parse options
  5727. for (i = 0; i < regExpOptions.length; i++) {
  5728. switch (regExpOptions[i]) {
  5729. case 'm':
  5730. optionsArray[i] = 'm';
  5731. break;
  5732. case 's':
  5733. optionsArray[i] = 'g';
  5734. break;
  5735. case 'i':
  5736. optionsArray[i] = 'i';
  5737. break;
  5738. }
  5739. }
  5740. value = new RegExp(source, optionsArray.join(''));
  5741. }
  5742. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
  5743. // Get the start search index
  5744. i = index;
  5745. // Locate the end of the c string
  5746. while (buffer[i] !== 0x00 && i < buffer.length) {
  5747. i++;
  5748. }
  5749. // If are at the end of the buffer there is a problem with the document
  5750. if (i >= buffer.length)
  5751. throw new BSONError('Bad BSON Document: illegal CString');
  5752. // Return the C string
  5753. var source = buffer.toString('utf8', index, i);
  5754. index = i + 1;
  5755. // Get the start search index
  5756. i = index;
  5757. // Locate the end of the c string
  5758. while (buffer[i] !== 0x00 && i < buffer.length) {
  5759. i++;
  5760. }
  5761. // If are at the end of the buffer there is a problem with the document
  5762. if (i >= buffer.length)
  5763. throw new BSONError('Bad BSON Document: illegal CString');
  5764. // Return the C string
  5765. var regExpOptions = buffer.toString('utf8', index, i);
  5766. index = i + 1;
  5767. // Set the object
  5768. value = new BSONRegExp(source, regExpOptions);
  5769. }
  5770. else if (elementType === BSON_DATA_SYMBOL) {
  5771. var stringSize = buffer[index++] |
  5772. (buffer[index++] << 8) |
  5773. (buffer[index++] << 16) |
  5774. (buffer[index++] << 24);
  5775. if (stringSize <= 0 ||
  5776. stringSize > buffer.length - index ||
  5777. buffer[index + stringSize - 1] !== 0) {
  5778. throw new BSONError('bad string length in bson');
  5779. }
  5780. var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  5781. value = promoteValues ? symbol : new BSONSymbol(symbol);
  5782. index = index + stringSize;
  5783. }
  5784. else if (elementType === BSON_DATA_TIMESTAMP) {
  5785. var lowBits = buffer[index++] |
  5786. (buffer[index++] << 8) |
  5787. (buffer[index++] << 16) |
  5788. (buffer[index++] << 24);
  5789. var highBits = buffer[index++] |
  5790. (buffer[index++] << 8) |
  5791. (buffer[index++] << 16) |
  5792. (buffer[index++] << 24);
  5793. value = new Timestamp(lowBits, highBits);
  5794. }
  5795. else if (elementType === BSON_DATA_MIN_KEY) {
  5796. value = new MinKey();
  5797. }
  5798. else if (elementType === BSON_DATA_MAX_KEY) {
  5799. value = new MaxKey();
  5800. }
  5801. else if (elementType === BSON_DATA_CODE) {
  5802. var stringSize = buffer[index++] |
  5803. (buffer[index++] << 8) |
  5804. (buffer[index++] << 16) |
  5805. (buffer[index++] << 24);
  5806. if (stringSize <= 0 ||
  5807. stringSize > buffer.length - index ||
  5808. buffer[index + stringSize - 1] !== 0) {
  5809. throw new BSONError('bad string length in bson');
  5810. }
  5811. var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  5812. // If we are evaluating the functions
  5813. if (evalFunctions) {
  5814. // If we have cache enabled let's look for the md5 of the function in the cache
  5815. if (cacheFunctions) {
  5816. // Got to do this to avoid V8 deoptimizing the call due to finding eval
  5817. value = isolateEval(functionString, functionCache, object);
  5818. }
  5819. else {
  5820. value = isolateEval(functionString);
  5821. }
  5822. }
  5823. else {
  5824. value = new Code(functionString);
  5825. }
  5826. // Update parse index position
  5827. index = index + stringSize;
  5828. }
  5829. else if (elementType === BSON_DATA_CODE_W_SCOPE) {
  5830. var totalSize = buffer[index++] |
  5831. (buffer[index++] << 8) |
  5832. (buffer[index++] << 16) |
  5833. (buffer[index++] << 24);
  5834. // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
  5835. if (totalSize < 4 + 4 + 4 + 1) {
  5836. throw new BSONError('code_w_scope total size shorter minimum expected length');
  5837. }
  5838. // Get the code string size
  5839. var stringSize = buffer[index++] |
  5840. (buffer[index++] << 8) |
  5841. (buffer[index++] << 16) |
  5842. (buffer[index++] << 24);
  5843. // Check if we have a valid string
  5844. if (stringSize <= 0 ||
  5845. stringSize > buffer.length - index ||
  5846. buffer[index + stringSize - 1] !== 0) {
  5847. throw new BSONError('bad string length in bson');
  5848. }
  5849. // Javascript function
  5850. var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  5851. // Update parse index position
  5852. index = index + stringSize;
  5853. // Parse the element
  5854. var _index = index;
  5855. // Decode the size of the object document
  5856. var objectSize = buffer[index] |
  5857. (buffer[index + 1] << 8) |
  5858. (buffer[index + 2] << 16) |
  5859. (buffer[index + 3] << 24);
  5860. // Decode the scope object
  5861. var scopeObject = deserializeObject(buffer, _index, options, false);
  5862. // Adjust the index
  5863. index = index + objectSize;
  5864. // Check if field length is too short
  5865. if (totalSize < 4 + 4 + objectSize + stringSize) {
  5866. throw new BSONError('code_w_scope total size is too short, truncating scope');
  5867. }
  5868. // Check if totalSize field is too long
  5869. if (totalSize > 4 + 4 + objectSize + stringSize) {
  5870. throw new BSONError('code_w_scope total size is too long, clips outer document');
  5871. }
  5872. // If we are evaluating the functions
  5873. if (evalFunctions) {
  5874. // If we have cache enabled let's look for the md5 of the function in the cache
  5875. if (cacheFunctions) {
  5876. // Got to do this to avoid V8 deoptimizing the call due to finding eval
  5877. value = isolateEval(functionString, functionCache, object);
  5878. }
  5879. else {
  5880. value = isolateEval(functionString);
  5881. }
  5882. value.scope = scopeObject;
  5883. }
  5884. else {
  5885. value = new Code(functionString, scopeObject);
  5886. }
  5887. }
  5888. else if (elementType === BSON_DATA_DBPOINTER) {
  5889. // Get the code string size
  5890. var stringSize = buffer[index++] |
  5891. (buffer[index++] << 8) |
  5892. (buffer[index++] << 16) |
  5893. (buffer[index++] << 24);
  5894. // Check if we have a valid string
  5895. if (stringSize <= 0 ||
  5896. stringSize > buffer.length - index ||
  5897. buffer[index + stringSize - 1] !== 0)
  5898. throw new BSONError('bad string length in bson');
  5899. // Namespace
  5900. if (validation != null && validation.utf8) {
  5901. if (!validateUtf8(buffer, index, index + stringSize - 1)) {
  5902. throw new BSONError('Invalid UTF-8 string in BSON document');
  5903. }
  5904. }
  5905. var namespace = buffer.toString('utf8', index, index + stringSize - 1);
  5906. // Update parse index position
  5907. index = index + stringSize;
  5908. // Read the oid
  5909. var oidBuffer = buffer_1.alloc(12);
  5910. buffer.copy(oidBuffer, 0, index, index + 12);
  5911. var oid = new ObjectId(oidBuffer);
  5912. // Update the index
  5913. index = index + 12;
  5914. // Upgrade to DBRef type
  5915. value = new DBRef(namespace, oid);
  5916. }
  5917. else {
  5918. throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
  5919. }
  5920. if (name === '__proto__') {
  5921. Object.defineProperty(object, name, {
  5922. value: value,
  5923. writable: true,
  5924. enumerable: true,
  5925. configurable: true
  5926. });
  5927. }
  5928. else {
  5929. object[name] = value;
  5930. }
  5931. }
  5932. // Check if the deserialization was against a valid array/object
  5933. if (size !== index - startIndex) {
  5934. if (isArray)
  5935. throw new BSONError('corrupt array bson');
  5936. throw new BSONError('corrupt object bson');
  5937. }
  5938. // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef
  5939. if (!isPossibleDBRef)
  5940. return object;
  5941. if (isDBRefLike(object)) {
  5942. var copy = Object.assign({}, object);
  5943. delete copy.$ref;
  5944. delete copy.$id;
  5945. delete copy.$db;
  5946. return new DBRef(object.$ref, object.$id, object.$db, copy);
  5947. }
  5948. return object;
  5949. }
  5950. /**
  5951. * Ensure eval is isolated, store the result in functionCache.
  5952. *
  5953. * @internal
  5954. */
  5955. function isolateEval(functionString, functionCache, object) {
  5956. if (!functionCache)
  5957. return new Function(functionString);
  5958. // Check for cache hit, eval if missing and return cached function
  5959. if (functionCache[functionString] == null) {
  5960. functionCache[functionString] = new Function(functionString);
  5961. }
  5962. // Set the object
  5963. return functionCache[functionString].bind(object);
  5964. }
  5965. function getValidatedString(buffer, start, end, shouldValidateUtf8) {
  5966. var value = buffer.toString('utf8', start, end);
  5967. // if utf8 validation is on, do the check
  5968. if (shouldValidateUtf8) {
  5969. for (var i = 0; i < value.length; i++) {
  5970. if (value.charCodeAt(i) === 0xfffd) {
  5971. if (!validateUtf8(buffer, start, end)) {
  5972. throw new BSONError('Invalid UTF-8 string in BSON document');
  5973. }
  5974. break;
  5975. }
  5976. }
  5977. }
  5978. return value;
  5979. }
  5980. // Copyright (c) 2008, Fair Oaks Labs, Inc.
  5981. function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) {
  5982. var e;
  5983. var m;
  5984. var c;
  5985. var bBE = endian === 'big';
  5986. var eLen = nBytes * 8 - mLen - 1;
  5987. var eMax = (1 << eLen) - 1;
  5988. var eBias = eMax >> 1;
  5989. var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  5990. var i = bBE ? nBytes - 1 : 0;
  5991. var d = bBE ? -1 : 1;
  5992. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  5993. value = Math.abs(value);
  5994. if (isNaN(value) || value === Infinity) {
  5995. m = isNaN(value) ? 1 : 0;
  5996. e = eMax;
  5997. }
  5998. else {
  5999. e = Math.floor(Math.log(value) / Math.LN2);
  6000. if (value * (c = Math.pow(2, -e)) < 1) {
  6001. e--;
  6002. c *= 2;
  6003. }
  6004. if (e + eBias >= 1) {
  6005. value += rt / c;
  6006. }
  6007. else {
  6008. value += rt * Math.pow(2, 1 - eBias);
  6009. }
  6010. if (value * c >= 2) {
  6011. e++;
  6012. c /= 2;
  6013. }
  6014. if (e + eBias >= eMax) {
  6015. m = 0;
  6016. e = eMax;
  6017. }
  6018. else if (e + eBias >= 1) {
  6019. m = (value * c - 1) * Math.pow(2, mLen);
  6020. e = e + eBias;
  6021. }
  6022. else {
  6023. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  6024. e = 0;
  6025. }
  6026. }
  6027. if (isNaN(value))
  6028. m = 0;
  6029. while (mLen >= 8) {
  6030. buffer[offset + i] = m & 0xff;
  6031. i += d;
  6032. m /= 256;
  6033. mLen -= 8;
  6034. }
  6035. e = (e << mLen) | m;
  6036. if (isNaN(value))
  6037. e += 8;
  6038. eLen += mLen;
  6039. while (eLen > 0) {
  6040. buffer[offset + i] = e & 0xff;
  6041. i += d;
  6042. e /= 256;
  6043. eLen -= 8;
  6044. }
  6045. buffer[offset + i - d] |= s * 128;
  6046. }
  6047. var regexp = /\x00/; // eslint-disable-line no-control-regex
  6048. var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
  6049. /*
  6050. * isArray indicates if we are writing to a BSON array (type 0x04)
  6051. * which forces the "key" which really an array index as a string to be written as ascii
  6052. * This will catch any errors in index as a string generation
  6053. */
  6054. function serializeString(buffer, key, value, index, isArray) {
  6055. // Encode String type
  6056. buffer[index++] = BSON_DATA_STRING;
  6057. // Number of written bytes
  6058. var numberOfWrittenBytes = !isArray
  6059. ? buffer.write(key, index, undefined, 'utf8')
  6060. : buffer.write(key, index, undefined, 'ascii');
  6061. // Encode the name
  6062. index = index + numberOfWrittenBytes + 1;
  6063. buffer[index - 1] = 0;
  6064. // Write the string
  6065. var size = buffer.write(value, index + 4, undefined, 'utf8');
  6066. // Write the size of the string to buffer
  6067. buffer[index + 3] = ((size + 1) >> 24) & 0xff;
  6068. buffer[index + 2] = ((size + 1) >> 16) & 0xff;
  6069. buffer[index + 1] = ((size + 1) >> 8) & 0xff;
  6070. buffer[index] = (size + 1) & 0xff;
  6071. // Update index
  6072. index = index + 4 + size;
  6073. // Write zero
  6074. buffer[index++] = 0;
  6075. return index;
  6076. }
  6077. function serializeNumber(buffer, key, value, index, isArray) {
  6078. // We have an integer value
  6079. // TODO(NODE-2529): Add support for big int
  6080. if (Number.isInteger(value) &&
  6081. value >= BSON_INT32_MIN &&
  6082. value <= BSON_INT32_MAX) {
  6083. // If the value fits in 32 bits encode as int32
  6084. // Set int type 32 bits or less
  6085. buffer[index++] = BSON_DATA_INT;
  6086. // Number of written bytes
  6087. var numberOfWrittenBytes = !isArray
  6088. ? buffer.write(key, index, undefined, 'utf8')
  6089. : buffer.write(key, index, undefined, 'ascii');
  6090. // Encode the name
  6091. index = index + numberOfWrittenBytes;
  6092. buffer[index++] = 0;
  6093. // Write the int value
  6094. buffer[index++] = value & 0xff;
  6095. buffer[index++] = (value >> 8) & 0xff;
  6096. buffer[index++] = (value >> 16) & 0xff;
  6097. buffer[index++] = (value >> 24) & 0xff;
  6098. }
  6099. else {
  6100. // Encode as double
  6101. buffer[index++] = BSON_DATA_NUMBER;
  6102. // Number of written bytes
  6103. var numberOfWrittenBytes = !isArray
  6104. ? buffer.write(key, index, undefined, 'utf8')
  6105. : buffer.write(key, index, undefined, 'ascii');
  6106. // Encode the name
  6107. index = index + numberOfWrittenBytes;
  6108. buffer[index++] = 0;
  6109. // Write float
  6110. writeIEEE754(buffer, value, index, 'little', 52, 8);
  6111. // Adjust index
  6112. index = index + 8;
  6113. }
  6114. return index;
  6115. }
  6116. function serializeNull(buffer, key, _, index, isArray) {
  6117. // Set long type
  6118. buffer[index++] = BSON_DATA_NULL;
  6119. // Number of written bytes
  6120. var numberOfWrittenBytes = !isArray
  6121. ? buffer.write(key, index, undefined, 'utf8')
  6122. : buffer.write(key, index, undefined, 'ascii');
  6123. // Encode the name
  6124. index = index + numberOfWrittenBytes;
  6125. buffer[index++] = 0;
  6126. return index;
  6127. }
  6128. function serializeBoolean(buffer, key, value, index, isArray) {
  6129. // Write the type
  6130. buffer[index++] = BSON_DATA_BOOLEAN;
  6131. // Number of written bytes
  6132. var numberOfWrittenBytes = !isArray
  6133. ? buffer.write(key, index, undefined, 'utf8')
  6134. : buffer.write(key, index, undefined, 'ascii');
  6135. // Encode the name
  6136. index = index + numberOfWrittenBytes;
  6137. buffer[index++] = 0;
  6138. // Encode the boolean value
  6139. buffer[index++] = value ? 1 : 0;
  6140. return index;
  6141. }
  6142. function serializeDate(buffer, key, value, index, isArray) {
  6143. // Write the type
  6144. buffer[index++] = BSON_DATA_DATE;
  6145. // Number of written bytes
  6146. var numberOfWrittenBytes = !isArray
  6147. ? buffer.write(key, index, undefined, 'utf8')
  6148. : buffer.write(key, index, undefined, 'ascii');
  6149. // Encode the name
  6150. index = index + numberOfWrittenBytes;
  6151. buffer[index++] = 0;
  6152. // Write the date
  6153. var dateInMilis = Long.fromNumber(value.getTime());
  6154. var lowBits = dateInMilis.getLowBits();
  6155. var highBits = dateInMilis.getHighBits();
  6156. // Encode low bits
  6157. buffer[index++] = lowBits & 0xff;
  6158. buffer[index++] = (lowBits >> 8) & 0xff;
  6159. buffer[index++] = (lowBits >> 16) & 0xff;
  6160. buffer[index++] = (lowBits >> 24) & 0xff;
  6161. // Encode high bits
  6162. buffer[index++] = highBits & 0xff;
  6163. buffer[index++] = (highBits >> 8) & 0xff;
  6164. buffer[index++] = (highBits >> 16) & 0xff;
  6165. buffer[index++] = (highBits >> 24) & 0xff;
  6166. return index;
  6167. }
  6168. function serializeRegExp(buffer, key, value, index, isArray) {
  6169. // Write the type
  6170. buffer[index++] = BSON_DATA_REGEXP;
  6171. // Number of written bytes
  6172. var numberOfWrittenBytes = !isArray
  6173. ? buffer.write(key, index, undefined, 'utf8')
  6174. : buffer.write(key, index, undefined, 'ascii');
  6175. // Encode the name
  6176. index = index + numberOfWrittenBytes;
  6177. buffer[index++] = 0;
  6178. if (value.source && value.source.match(regexp) != null) {
  6179. throw Error('value ' + value.source + ' must not contain null bytes');
  6180. }
  6181. // Adjust the index
  6182. index = index + buffer.write(value.source, index, undefined, 'utf8');
  6183. // Write zero
  6184. buffer[index++] = 0x00;
  6185. // Write the parameters
  6186. if (value.ignoreCase)
  6187. buffer[index++] = 0x69; // i
  6188. if (value.global)
  6189. buffer[index++] = 0x73; // s
  6190. if (value.multiline)
  6191. buffer[index++] = 0x6d; // m
  6192. // Add ending zero
  6193. buffer[index++] = 0x00;
  6194. return index;
  6195. }
  6196. function serializeBSONRegExp(buffer, key, value, index, isArray) {
  6197. // Write the type
  6198. buffer[index++] = BSON_DATA_REGEXP;
  6199. // Number of written bytes
  6200. var numberOfWrittenBytes = !isArray
  6201. ? buffer.write(key, index, undefined, 'utf8')
  6202. : buffer.write(key, index, undefined, 'ascii');
  6203. // Encode the name
  6204. index = index + numberOfWrittenBytes;
  6205. buffer[index++] = 0;
  6206. // Check the pattern for 0 bytes
  6207. if (value.pattern.match(regexp) != null) {
  6208. // The BSON spec doesn't allow keys with null bytes because keys are
  6209. // null-terminated.
  6210. throw Error('pattern ' + value.pattern + ' must not contain null bytes');
  6211. }
  6212. // Adjust the index
  6213. index = index + buffer.write(value.pattern, index, undefined, 'utf8');
  6214. // Write zero
  6215. buffer[index++] = 0x00;
  6216. // Write the options
  6217. index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8');
  6218. // Add ending zero
  6219. buffer[index++] = 0x00;
  6220. return index;
  6221. }
  6222. function serializeMinMax(buffer, key, value, index, isArray) {
  6223. // Write the type of either min or max key
  6224. if (value === null) {
  6225. buffer[index++] = BSON_DATA_NULL;
  6226. }
  6227. else if (value._bsontype === 'MinKey') {
  6228. buffer[index++] = BSON_DATA_MIN_KEY;
  6229. }
  6230. else {
  6231. buffer[index++] = BSON_DATA_MAX_KEY;
  6232. }
  6233. // Number of written bytes
  6234. var numberOfWrittenBytes = !isArray
  6235. ? buffer.write(key, index, undefined, 'utf8')
  6236. : buffer.write(key, index, undefined, 'ascii');
  6237. // Encode the name
  6238. index = index + numberOfWrittenBytes;
  6239. buffer[index++] = 0;
  6240. return index;
  6241. }
  6242. function serializeObjectId(buffer, key, value, index, isArray) {
  6243. // Write the type
  6244. buffer[index++] = BSON_DATA_OID;
  6245. // Number of written bytes
  6246. var numberOfWrittenBytes = !isArray
  6247. ? buffer.write(key, index, undefined, 'utf8')
  6248. : buffer.write(key, index, undefined, 'ascii');
  6249. // Encode the name
  6250. index = index + numberOfWrittenBytes;
  6251. buffer[index++] = 0;
  6252. // Write the objectId into the shared buffer
  6253. if (typeof value.id === 'string') {
  6254. buffer.write(value.id, index, undefined, 'binary');
  6255. }
  6256. else if (isUint8Array(value.id)) {
  6257. // Use the standard JS methods here because buffer.copy() is buggy with the
  6258. // browser polyfill
  6259. buffer.set(value.id.subarray(0, 12), index);
  6260. }
  6261. else {
  6262. throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
  6263. }
  6264. // Adjust index
  6265. return index + 12;
  6266. }
  6267. function serializeBuffer(buffer, key, value, index, isArray) {
  6268. // Write the type
  6269. buffer[index++] = BSON_DATA_BINARY;
  6270. // Number of written bytes
  6271. var numberOfWrittenBytes = !isArray
  6272. ? buffer.write(key, index, undefined, 'utf8')
  6273. : buffer.write(key, index, undefined, 'ascii');
  6274. // Encode the name
  6275. index = index + numberOfWrittenBytes;
  6276. buffer[index++] = 0;
  6277. // Get size of the buffer (current write point)
  6278. var size = value.length;
  6279. // Write the size of the string to buffer
  6280. buffer[index++] = size & 0xff;
  6281. buffer[index++] = (size >> 8) & 0xff;
  6282. buffer[index++] = (size >> 16) & 0xff;
  6283. buffer[index++] = (size >> 24) & 0xff;
  6284. // Write the default subtype
  6285. buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
  6286. // Copy the content form the binary field to the buffer
  6287. buffer.set(ensureBuffer(value), index);
  6288. // Adjust the index
  6289. index = index + size;
  6290. return index;
  6291. }
  6292. function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) {
  6293. if (checkKeys === void 0) { checkKeys = false; }
  6294. if (depth === void 0) { depth = 0; }
  6295. if (serializeFunctions === void 0) { serializeFunctions = false; }
  6296. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  6297. if (isArray === void 0) { isArray = false; }
  6298. if (path === void 0) { path = []; }
  6299. for (var i = 0; i < path.length; i++) {
  6300. if (path[i] === value)
  6301. throw new BSONError('cyclic dependency detected');
  6302. }
  6303. // Push value to stack
  6304. path.push(value);
  6305. // Write the type
  6306. buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
  6307. // Number of written bytes
  6308. var numberOfWrittenBytes = !isArray
  6309. ? buffer.write(key, index, undefined, 'utf8')
  6310. : buffer.write(key, index, undefined, 'ascii');
  6311. // Encode the name
  6312. index = index + numberOfWrittenBytes;
  6313. buffer[index++] = 0;
  6314. var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  6315. // Pop stack
  6316. path.pop();
  6317. return endIndex;
  6318. }
  6319. function serializeDecimal128(buffer, key, value, index, isArray) {
  6320. buffer[index++] = BSON_DATA_DECIMAL128;
  6321. // Number of written bytes
  6322. var numberOfWrittenBytes = !isArray
  6323. ? buffer.write(key, index, undefined, 'utf8')
  6324. : buffer.write(key, index, undefined, 'ascii');
  6325. // Encode the name
  6326. index = index + numberOfWrittenBytes;
  6327. buffer[index++] = 0;
  6328. // Write the data from the value
  6329. // Prefer the standard JS methods because their typechecking is not buggy,
  6330. // unlike the `buffer` polyfill's.
  6331. buffer.set(value.bytes.subarray(0, 16), index);
  6332. return index + 16;
  6333. }
  6334. function serializeLong(buffer, key, value, index, isArray) {
  6335. // Write the type
  6336. buffer[index++] =
  6337. value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
  6338. // Number of written bytes
  6339. var numberOfWrittenBytes = !isArray
  6340. ? buffer.write(key, index, undefined, 'utf8')
  6341. : buffer.write(key, index, undefined, 'ascii');
  6342. // Encode the name
  6343. index = index + numberOfWrittenBytes;
  6344. buffer[index++] = 0;
  6345. // Write the date
  6346. var lowBits = value.getLowBits();
  6347. var highBits = value.getHighBits();
  6348. // Encode low bits
  6349. buffer[index++] = lowBits & 0xff;
  6350. buffer[index++] = (lowBits >> 8) & 0xff;
  6351. buffer[index++] = (lowBits >> 16) & 0xff;
  6352. buffer[index++] = (lowBits >> 24) & 0xff;
  6353. // Encode high bits
  6354. buffer[index++] = highBits & 0xff;
  6355. buffer[index++] = (highBits >> 8) & 0xff;
  6356. buffer[index++] = (highBits >> 16) & 0xff;
  6357. buffer[index++] = (highBits >> 24) & 0xff;
  6358. return index;
  6359. }
  6360. function serializeInt32(buffer, key, value, index, isArray) {
  6361. value = value.valueOf();
  6362. // Set int type 32 bits or less
  6363. buffer[index++] = BSON_DATA_INT;
  6364. // Number of written bytes
  6365. var numberOfWrittenBytes = !isArray
  6366. ? buffer.write(key, index, undefined, 'utf8')
  6367. : buffer.write(key, index, undefined, 'ascii');
  6368. // Encode the name
  6369. index = index + numberOfWrittenBytes;
  6370. buffer[index++] = 0;
  6371. // Write the int value
  6372. buffer[index++] = value & 0xff;
  6373. buffer[index++] = (value >> 8) & 0xff;
  6374. buffer[index++] = (value >> 16) & 0xff;
  6375. buffer[index++] = (value >> 24) & 0xff;
  6376. return index;
  6377. }
  6378. function serializeDouble(buffer, key, value, index, isArray) {
  6379. // Encode as double
  6380. buffer[index++] = BSON_DATA_NUMBER;
  6381. // Number of written bytes
  6382. var numberOfWrittenBytes = !isArray
  6383. ? buffer.write(key, index, undefined, 'utf8')
  6384. : buffer.write(key, index, undefined, 'ascii');
  6385. // Encode the name
  6386. index = index + numberOfWrittenBytes;
  6387. buffer[index++] = 0;
  6388. // Write float
  6389. writeIEEE754(buffer, value.value, index, 'little', 52, 8);
  6390. // Adjust index
  6391. index = index + 8;
  6392. return index;
  6393. }
  6394. function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) {
  6395. buffer[index++] = BSON_DATA_CODE;
  6396. // Number of written bytes
  6397. var numberOfWrittenBytes = !isArray
  6398. ? buffer.write(key, index, undefined, 'utf8')
  6399. : buffer.write(key, index, undefined, 'ascii');
  6400. // Encode the name
  6401. index = index + numberOfWrittenBytes;
  6402. buffer[index++] = 0;
  6403. // Function string
  6404. var functionString = normalizedFunctionString(value);
  6405. // Write the string
  6406. var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  6407. // Write the size of the string to buffer
  6408. buffer[index] = size & 0xff;
  6409. buffer[index + 1] = (size >> 8) & 0xff;
  6410. buffer[index + 2] = (size >> 16) & 0xff;
  6411. buffer[index + 3] = (size >> 24) & 0xff;
  6412. // Update index
  6413. index = index + 4 + size - 1;
  6414. // Write zero
  6415. buffer[index++] = 0;
  6416. return index;
  6417. }
  6418. function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) {
  6419. if (checkKeys === void 0) { checkKeys = false; }
  6420. if (depth === void 0) { depth = 0; }
  6421. if (serializeFunctions === void 0) { serializeFunctions = false; }
  6422. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  6423. if (isArray === void 0) { isArray = false; }
  6424. if (value.scope && typeof value.scope === 'object') {
  6425. // Write the type
  6426. buffer[index++] = BSON_DATA_CODE_W_SCOPE;
  6427. // Number of written bytes
  6428. var numberOfWrittenBytes = !isArray
  6429. ? buffer.write(key, index, undefined, 'utf8')
  6430. : buffer.write(key, index, undefined, 'ascii');
  6431. // Encode the name
  6432. index = index + numberOfWrittenBytes;
  6433. buffer[index++] = 0;
  6434. // Starting index
  6435. var startIndex = index;
  6436. // Serialize the function
  6437. // Get the function string
  6438. var functionString = typeof value.code === 'string' ? value.code : value.code.toString();
  6439. // Index adjustment
  6440. index = index + 4;
  6441. // Write string into buffer
  6442. var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  6443. // Write the size of the string to buffer
  6444. buffer[index] = codeSize & 0xff;
  6445. buffer[index + 1] = (codeSize >> 8) & 0xff;
  6446. buffer[index + 2] = (codeSize >> 16) & 0xff;
  6447. buffer[index + 3] = (codeSize >> 24) & 0xff;
  6448. // Write end 0
  6449. buffer[index + 4 + codeSize - 1] = 0;
  6450. // Write the
  6451. index = index + codeSize + 4;
  6452. //
  6453. // Serialize the scope value
  6454. var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined);
  6455. index = endIndex - 1;
  6456. // Writ the total
  6457. var totalSize = endIndex - startIndex;
  6458. // Write the total size of the object
  6459. buffer[startIndex++] = totalSize & 0xff;
  6460. buffer[startIndex++] = (totalSize >> 8) & 0xff;
  6461. buffer[startIndex++] = (totalSize >> 16) & 0xff;
  6462. buffer[startIndex++] = (totalSize >> 24) & 0xff;
  6463. // Write trailing zero
  6464. buffer[index++] = 0;
  6465. }
  6466. else {
  6467. buffer[index++] = BSON_DATA_CODE;
  6468. // Number of written bytes
  6469. var numberOfWrittenBytes = !isArray
  6470. ? buffer.write(key, index, undefined, 'utf8')
  6471. : buffer.write(key, index, undefined, 'ascii');
  6472. // Encode the name
  6473. index = index + numberOfWrittenBytes;
  6474. buffer[index++] = 0;
  6475. // Function string
  6476. var functionString = value.code.toString();
  6477. // Write the string
  6478. var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  6479. // Write the size of the string to buffer
  6480. buffer[index] = size & 0xff;
  6481. buffer[index + 1] = (size >> 8) & 0xff;
  6482. buffer[index + 2] = (size >> 16) & 0xff;
  6483. buffer[index + 3] = (size >> 24) & 0xff;
  6484. // Update index
  6485. index = index + 4 + size - 1;
  6486. // Write zero
  6487. buffer[index++] = 0;
  6488. }
  6489. return index;
  6490. }
  6491. function serializeBinary(buffer, key, value, index, isArray) {
  6492. // Write the type
  6493. buffer[index++] = BSON_DATA_BINARY;
  6494. // Number of written bytes
  6495. var numberOfWrittenBytes = !isArray
  6496. ? buffer.write(key, index, undefined, 'utf8')
  6497. : buffer.write(key, index, undefined, 'ascii');
  6498. // Encode the name
  6499. index = index + numberOfWrittenBytes;
  6500. buffer[index++] = 0;
  6501. // Extract the buffer
  6502. var data = value.value(true);
  6503. // Calculate size
  6504. var size = value.position;
  6505. // Add the deprecated 02 type 4 bytes of size to total
  6506. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
  6507. size = size + 4;
  6508. // Write the size of the string to buffer
  6509. buffer[index++] = size & 0xff;
  6510. buffer[index++] = (size >> 8) & 0xff;
  6511. buffer[index++] = (size >> 16) & 0xff;
  6512. buffer[index++] = (size >> 24) & 0xff;
  6513. // Write the subtype to the buffer
  6514. buffer[index++] = value.sub_type;
  6515. // If we have binary type 2 the 4 first bytes are the size
  6516. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  6517. size = size - 4;
  6518. buffer[index++] = size & 0xff;
  6519. buffer[index++] = (size >> 8) & 0xff;
  6520. buffer[index++] = (size >> 16) & 0xff;
  6521. buffer[index++] = (size >> 24) & 0xff;
  6522. }
  6523. // Write the data to the object
  6524. buffer.set(data, index);
  6525. // Adjust the index
  6526. index = index + value.position;
  6527. return index;
  6528. }
  6529. function serializeSymbol(buffer, key, value, index, isArray) {
  6530. // Write the type
  6531. buffer[index++] = BSON_DATA_SYMBOL;
  6532. // Number of written bytes
  6533. var numberOfWrittenBytes = !isArray
  6534. ? buffer.write(key, index, undefined, 'utf8')
  6535. : buffer.write(key, index, undefined, 'ascii');
  6536. // Encode the name
  6537. index = index + numberOfWrittenBytes;
  6538. buffer[index++] = 0;
  6539. // Write the string
  6540. var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1;
  6541. // Write the size of the string to buffer
  6542. buffer[index] = size & 0xff;
  6543. buffer[index + 1] = (size >> 8) & 0xff;
  6544. buffer[index + 2] = (size >> 16) & 0xff;
  6545. buffer[index + 3] = (size >> 24) & 0xff;
  6546. // Update index
  6547. index = index + 4 + size - 1;
  6548. // Write zero
  6549. buffer[index++] = 0x00;
  6550. return index;
  6551. }
  6552. function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) {
  6553. // Write the type
  6554. buffer[index++] = BSON_DATA_OBJECT;
  6555. // Number of written bytes
  6556. var numberOfWrittenBytes = !isArray
  6557. ? buffer.write(key, index, undefined, 'utf8')
  6558. : buffer.write(key, index, undefined, 'ascii');
  6559. // Encode the name
  6560. index = index + numberOfWrittenBytes;
  6561. buffer[index++] = 0;
  6562. var startIndex = index;
  6563. var output = {
  6564. $ref: value.collection || value.namespace,
  6565. $id: value.oid
  6566. };
  6567. if (value.db != null) {
  6568. output.$db = value.db;
  6569. }
  6570. output = Object.assign(output, value.fields);
  6571. var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions);
  6572. // Calculate object size
  6573. var size = endIndex - startIndex;
  6574. // Write the size
  6575. buffer[startIndex++] = size & 0xff;
  6576. buffer[startIndex++] = (size >> 8) & 0xff;
  6577. buffer[startIndex++] = (size >> 16) & 0xff;
  6578. buffer[startIndex++] = (size >> 24) & 0xff;
  6579. // Set index
  6580. return endIndex;
  6581. }
  6582. function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  6583. if (checkKeys === void 0) { checkKeys = false; }
  6584. if (startingIndex === void 0) { startingIndex = 0; }
  6585. if (depth === void 0) { depth = 0; }
  6586. if (serializeFunctions === void 0) { serializeFunctions = false; }
  6587. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  6588. if (path === void 0) { path = []; }
  6589. startingIndex = startingIndex || 0;
  6590. path = path || [];
  6591. // Push the object to the path
  6592. path.push(object);
  6593. // Start place to serialize into
  6594. var index = startingIndex + 4;
  6595. // Special case isArray
  6596. if (Array.isArray(object)) {
  6597. // Get object keys
  6598. for (var i = 0; i < object.length; i++) {
  6599. var key = '' + i;
  6600. var value = object[i];
  6601. // Is there an override value
  6602. if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
  6603. value = value.toBSON();
  6604. }
  6605. if (typeof value === 'string') {
  6606. index = serializeString(buffer, key, value, index, true);
  6607. }
  6608. else if (typeof value === 'number') {
  6609. index = serializeNumber(buffer, key, value, index, true);
  6610. }
  6611. else if (typeof value === 'bigint') {
  6612. throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
  6613. }
  6614. else if (typeof value === 'boolean') {
  6615. index = serializeBoolean(buffer, key, value, index, true);
  6616. }
  6617. else if (value instanceof Date || isDate(value)) {
  6618. index = serializeDate(buffer, key, value, index, true);
  6619. }
  6620. else if (value === undefined) {
  6621. index = serializeNull(buffer, key, value, index, true);
  6622. }
  6623. else if (value === null) {
  6624. index = serializeNull(buffer, key, value, index, true);
  6625. }
  6626. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  6627. index = serializeObjectId(buffer, key, value, index, true);
  6628. }
  6629. else if (isUint8Array(value)) {
  6630. index = serializeBuffer(buffer, key, value, index, true);
  6631. }
  6632. else if (value instanceof RegExp || isRegExp(value)) {
  6633. index = serializeRegExp(buffer, key, value, index, true);
  6634. }
  6635. else if (typeof value === 'object' && value['_bsontype'] == null) {
  6636. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path);
  6637. }
  6638. else if (typeof value === 'object' &&
  6639. isBSONType(value) &&
  6640. value._bsontype === 'Decimal128') {
  6641. index = serializeDecimal128(buffer, key, value, index, true);
  6642. }
  6643. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  6644. index = serializeLong(buffer, key, value, index, true);
  6645. }
  6646. else if (value['_bsontype'] === 'Double') {
  6647. index = serializeDouble(buffer, key, value, index, true);
  6648. }
  6649. else if (typeof value === 'function' && serializeFunctions) {
  6650. index = serializeFunction(buffer, key, value, index, checkKeys, depth, true);
  6651. }
  6652. else if (value['_bsontype'] === 'Code') {
  6653. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true);
  6654. }
  6655. else if (value['_bsontype'] === 'Binary') {
  6656. index = serializeBinary(buffer, key, value, index, true);
  6657. }
  6658. else if (value['_bsontype'] === 'Symbol') {
  6659. index = serializeSymbol(buffer, key, value, index, true);
  6660. }
  6661. else if (value['_bsontype'] === 'DBRef') {
  6662. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true);
  6663. }
  6664. else if (value['_bsontype'] === 'BSONRegExp') {
  6665. index = serializeBSONRegExp(buffer, key, value, index, true);
  6666. }
  6667. else if (value['_bsontype'] === 'Int32') {
  6668. index = serializeInt32(buffer, key, value, index, true);
  6669. }
  6670. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  6671. index = serializeMinMax(buffer, key, value, index, true);
  6672. }
  6673. else if (typeof value['_bsontype'] !== 'undefined') {
  6674. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  6675. }
  6676. }
  6677. }
  6678. else if (object instanceof exports.Map || isMap(object)) {
  6679. var iterator = object.entries();
  6680. var done = false;
  6681. while (!done) {
  6682. // Unpack the next entry
  6683. var entry = iterator.next();
  6684. done = !!entry.done;
  6685. // Are we done, then skip and terminate
  6686. if (done)
  6687. continue;
  6688. // Get the entry values
  6689. var key = entry.value[0];
  6690. var value = entry.value[1];
  6691. // Check the type of the value
  6692. var type = typeof value;
  6693. // Check the key and throw error if it's illegal
  6694. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  6695. if (key.match(regexp) != null) {
  6696. // The BSON spec doesn't allow keys with null bytes because keys are
  6697. // null-terminated.
  6698. throw Error('key ' + key + ' must not contain null bytes');
  6699. }
  6700. if (checkKeys) {
  6701. if ('$' === key[0]) {
  6702. throw Error('key ' + key + " must not start with '$'");
  6703. }
  6704. else if (~key.indexOf('.')) {
  6705. throw Error('key ' + key + " must not contain '.'");
  6706. }
  6707. }
  6708. }
  6709. if (type === 'string') {
  6710. index = serializeString(buffer, key, value, index);
  6711. }
  6712. else if (type === 'number') {
  6713. index = serializeNumber(buffer, key, value, index);
  6714. }
  6715. else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) {
  6716. throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
  6717. }
  6718. else if (type === 'boolean') {
  6719. index = serializeBoolean(buffer, key, value, index);
  6720. }
  6721. else if (value instanceof Date || isDate(value)) {
  6722. index = serializeDate(buffer, key, value, index);
  6723. }
  6724. else if (value === null || (value === undefined && ignoreUndefined === false)) {
  6725. index = serializeNull(buffer, key, value, index);
  6726. }
  6727. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  6728. index = serializeObjectId(buffer, key, value, index);
  6729. }
  6730. else if (isUint8Array(value)) {
  6731. index = serializeBuffer(buffer, key, value, index);
  6732. }
  6733. else if (value instanceof RegExp || isRegExp(value)) {
  6734. index = serializeRegExp(buffer, key, value, index);
  6735. }
  6736. else if (type === 'object' && value['_bsontype'] == null) {
  6737. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  6738. }
  6739. else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  6740. index = serializeDecimal128(buffer, key, value, index);
  6741. }
  6742. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  6743. index = serializeLong(buffer, key, value, index);
  6744. }
  6745. else if (value['_bsontype'] === 'Double') {
  6746. index = serializeDouble(buffer, key, value, index);
  6747. }
  6748. else if (value['_bsontype'] === 'Code') {
  6749. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  6750. }
  6751. else if (typeof value === 'function' && serializeFunctions) {
  6752. index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
  6753. }
  6754. else if (value['_bsontype'] === 'Binary') {
  6755. index = serializeBinary(buffer, key, value, index);
  6756. }
  6757. else if (value['_bsontype'] === 'Symbol') {
  6758. index = serializeSymbol(buffer, key, value, index);
  6759. }
  6760. else if (value['_bsontype'] === 'DBRef') {
  6761. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
  6762. }
  6763. else if (value['_bsontype'] === 'BSONRegExp') {
  6764. index = serializeBSONRegExp(buffer, key, value, index);
  6765. }
  6766. else if (value['_bsontype'] === 'Int32') {
  6767. index = serializeInt32(buffer, key, value, index);
  6768. }
  6769. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  6770. index = serializeMinMax(buffer, key, value, index);
  6771. }
  6772. else if (typeof value['_bsontype'] !== 'undefined') {
  6773. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  6774. }
  6775. }
  6776. }
  6777. else {
  6778. if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
  6779. // Provided a custom serialization method
  6780. object = object.toBSON();
  6781. if (object != null && typeof object !== 'object') {
  6782. throw new BSONTypeError('toBSON function did not return an object');
  6783. }
  6784. }
  6785. // Iterate over all the keys
  6786. for (var key in object) {
  6787. var value = object[key];
  6788. // Is there an override value
  6789. if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
  6790. value = value.toBSON();
  6791. }
  6792. // Check the type of the value
  6793. var type = typeof value;
  6794. // Check the key and throw error if it's illegal
  6795. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  6796. if (key.match(regexp) != null) {
  6797. // The BSON spec doesn't allow keys with null bytes because keys are
  6798. // null-terminated.
  6799. throw Error('key ' + key + ' must not contain null bytes');
  6800. }
  6801. if (checkKeys) {
  6802. if ('$' === key[0]) {
  6803. throw Error('key ' + key + " must not start with '$'");
  6804. }
  6805. else if (~key.indexOf('.')) {
  6806. throw Error('key ' + key + " must not contain '.'");
  6807. }
  6808. }
  6809. }
  6810. if (type === 'string') {
  6811. index = serializeString(buffer, key, value, index);
  6812. }
  6813. else if (type === 'number') {
  6814. index = serializeNumber(buffer, key, value, index);
  6815. }
  6816. else if (type === 'bigint') {
  6817. throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
  6818. }
  6819. else if (type === 'boolean') {
  6820. index = serializeBoolean(buffer, key, value, index);
  6821. }
  6822. else if (value instanceof Date || isDate(value)) {
  6823. index = serializeDate(buffer, key, value, index);
  6824. }
  6825. else if (value === undefined) {
  6826. if (ignoreUndefined === false)
  6827. index = serializeNull(buffer, key, value, index);
  6828. }
  6829. else if (value === null) {
  6830. index = serializeNull(buffer, key, value, index);
  6831. }
  6832. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  6833. index = serializeObjectId(buffer, key, value, index);
  6834. }
  6835. else if (isUint8Array(value)) {
  6836. index = serializeBuffer(buffer, key, value, index);
  6837. }
  6838. else if (value instanceof RegExp || isRegExp(value)) {
  6839. index = serializeRegExp(buffer, key, value, index);
  6840. }
  6841. else if (type === 'object' && value['_bsontype'] == null) {
  6842. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  6843. }
  6844. else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  6845. index = serializeDecimal128(buffer, key, value, index);
  6846. }
  6847. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  6848. index = serializeLong(buffer, key, value, index);
  6849. }
  6850. else if (value['_bsontype'] === 'Double') {
  6851. index = serializeDouble(buffer, key, value, index);
  6852. }
  6853. else if (value['_bsontype'] === 'Code') {
  6854. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  6855. }
  6856. else if (typeof value === 'function' && serializeFunctions) {
  6857. index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
  6858. }
  6859. else if (value['_bsontype'] === 'Binary') {
  6860. index = serializeBinary(buffer, key, value, index);
  6861. }
  6862. else if (value['_bsontype'] === 'Symbol') {
  6863. index = serializeSymbol(buffer, key, value, index);
  6864. }
  6865. else if (value['_bsontype'] === 'DBRef') {
  6866. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
  6867. }
  6868. else if (value['_bsontype'] === 'BSONRegExp') {
  6869. index = serializeBSONRegExp(buffer, key, value, index);
  6870. }
  6871. else if (value['_bsontype'] === 'Int32') {
  6872. index = serializeInt32(buffer, key, value, index);
  6873. }
  6874. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  6875. index = serializeMinMax(buffer, key, value, index);
  6876. }
  6877. else if (typeof value['_bsontype'] !== 'undefined') {
  6878. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  6879. }
  6880. }
  6881. }
  6882. // Remove the path
  6883. path.pop();
  6884. // Final padding byte for object
  6885. buffer[index++] = 0x00;
  6886. // Final size
  6887. var size = index - startingIndex;
  6888. // Write the size of the object
  6889. buffer[startingIndex++] = size & 0xff;
  6890. buffer[startingIndex++] = (size >> 8) & 0xff;
  6891. buffer[startingIndex++] = (size >> 16) & 0xff;
  6892. buffer[startingIndex++] = (size >> 24) & 0xff;
  6893. return index;
  6894. }
  6895. /** @internal */
  6896. // Default Max Size
  6897. var MAXSIZE = 1024 * 1024 * 17;
  6898. // Current Internal Temporary Serialization Buffer
  6899. var buffer = buffer_1.alloc(MAXSIZE);
  6900. /**
  6901. * Sets the size of the internal serialization buffer.
  6902. *
  6903. * @param size - The desired size for the internal serialization buffer
  6904. * @public
  6905. */
  6906. function setInternalBufferSize(size) {
  6907. // Resize the internal serialization buffer if needed
  6908. if (buffer.length < size) {
  6909. buffer = buffer_1.alloc(size);
  6910. }
  6911. }
  6912. /**
  6913. * Serialize a Javascript object.
  6914. *
  6915. * @param object - the Javascript object to serialize.
  6916. * @returns Buffer object containing the serialized object.
  6917. * @public
  6918. */
  6919. function serialize(object, options) {
  6920. if (options === void 0) { options = {}; }
  6921. // Unpack the options
  6922. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  6923. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  6924. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  6925. var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
  6926. // Resize the internal serialization buffer if needed
  6927. if (buffer.length < minInternalBufferSize) {
  6928. buffer = buffer_1.alloc(minInternalBufferSize);
  6929. }
  6930. // Attempt to serialize
  6931. var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []);
  6932. // Create the final buffer
  6933. var finishedBuffer = buffer_1.alloc(serializationIndex);
  6934. // Copy into the finished buffer
  6935. buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length);
  6936. // Return the buffer
  6937. return finishedBuffer;
  6938. }
  6939. /**
  6940. * Serialize a Javascript object using a predefined Buffer and index into the buffer,
  6941. * useful when pre-allocating the space for serialization.
  6942. *
  6943. * @param object - the Javascript object to serialize.
  6944. * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object.
  6945. * @returns the index pointing to the last written byte in the buffer.
  6946. * @public
  6947. */
  6948. function serializeWithBufferAndIndex(object, finalBuffer, options) {
  6949. if (options === void 0) { options = {}; }
  6950. // Unpack the options
  6951. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  6952. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  6953. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  6954. var startIndex = typeof options.index === 'number' ? options.index : 0;
  6955. // Attempt to serialize
  6956. var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined);
  6957. buffer.copy(finalBuffer, startIndex, 0, serializationIndex);
  6958. // Return the index
  6959. return startIndex + serializationIndex - 1;
  6960. }
  6961. /**
  6962. * Deserialize data as BSON.
  6963. *
  6964. * @param buffer - the buffer containing the serialized set of BSON documents.
  6965. * @returns returns the deserialized Javascript Object.
  6966. * @public
  6967. */
  6968. function deserialize(buffer, options) {
  6969. if (options === void 0) { options = {}; }
  6970. return deserialize$1(buffer instanceof buffer_1 ? buffer : ensureBuffer(buffer), options);
  6971. }
  6972. /**
  6973. * Calculate the bson size for a passed in Javascript object.
  6974. *
  6975. * @param object - the Javascript object to calculate the BSON byte size for
  6976. * @returns size of BSON object in bytes
  6977. * @public
  6978. */
  6979. function calculateObjectSize(object, options) {
  6980. if (options === void 0) { options = {}; }
  6981. options = options || {};
  6982. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  6983. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  6984. return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined);
  6985. }
  6986. /**
  6987. * Deserialize stream data as BSON documents.
  6988. *
  6989. * @param data - the buffer containing the serialized set of BSON documents.
  6990. * @param startIndex - the start index in the data Buffer where the deserialization is to start.
  6991. * @param numberOfDocuments - number of documents to deserialize.
  6992. * @param documents - an array where to store the deserialized documents.
  6993. * @param docStartIndex - the index in the documents array from where to start inserting documents.
  6994. * @param options - additional options used for the deserialization.
  6995. * @returns next index in the buffer after deserialization **x** numbers of documents.
  6996. * @public
  6997. */
  6998. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  6999. var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
  7000. var bufferData = ensureBuffer(data);
  7001. var index = startIndex;
  7002. // Loop over all documents
  7003. for (var i = 0; i < numberOfDocuments; i++) {
  7004. // Find size of the document
  7005. var size = bufferData[index] |
  7006. (bufferData[index + 1] << 8) |
  7007. (bufferData[index + 2] << 16) |
  7008. (bufferData[index + 3] << 24);
  7009. // Update options with index
  7010. internalOptions.index = index;
  7011. // Parse the document at this point
  7012. documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions);
  7013. // Adjust index by the document size
  7014. index = index + size;
  7015. }
  7016. // Return object containing end index of parsing and list of documents
  7017. return index;
  7018. }
  7019. /**
  7020. * BSON default export
  7021. * @deprecated Please use named exports
  7022. * @privateRemarks
  7023. * We want to someday deprecate the default export,
  7024. * so none of the new TS types are being exported on the default
  7025. * @public
  7026. */
  7027. var BSON = {
  7028. Binary: Binary,
  7029. Code: Code,
  7030. DBRef: DBRef,
  7031. Decimal128: Decimal128,
  7032. Double: Double,
  7033. Int32: Int32,
  7034. Long: Long,
  7035. UUID: UUID,
  7036. Map: exports.Map,
  7037. MaxKey: MaxKey,
  7038. MinKey: MinKey,
  7039. ObjectId: ObjectId,
  7040. ObjectID: ObjectId,
  7041. BSONRegExp: BSONRegExp,
  7042. BSONSymbol: BSONSymbol,
  7043. Timestamp: Timestamp,
  7044. EJSON: exports.EJSON,
  7045. setInternalBufferSize: setInternalBufferSize,
  7046. serialize: serialize,
  7047. serializeWithBufferAndIndex: serializeWithBufferAndIndex,
  7048. deserialize: deserialize,
  7049. calculateObjectSize: calculateObjectSize,
  7050. deserializeStream: deserializeStream,
  7051. BSONError: BSONError,
  7052. BSONTypeError: BSONTypeError
  7053. };
  7054. exports.BSONError = BSONError;
  7055. exports.BSONRegExp = BSONRegExp;
  7056. exports.BSONSymbol = BSONSymbol;
  7057. exports.BSONTypeError = BSONTypeError;
  7058. exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = BSON_BINARY_SUBTYPE_BYTE_ARRAY;
  7059. exports.BSON_BINARY_SUBTYPE_COLUMN = BSON_BINARY_SUBTYPE_COLUMN;
  7060. exports.BSON_BINARY_SUBTYPE_DEFAULT = BSON_BINARY_SUBTYPE_DEFAULT;
  7061. exports.BSON_BINARY_SUBTYPE_ENCRYPTED = BSON_BINARY_SUBTYPE_ENCRYPTED;
  7062. exports.BSON_BINARY_SUBTYPE_FUNCTION = BSON_BINARY_SUBTYPE_FUNCTION;
  7063. exports.BSON_BINARY_SUBTYPE_MD5 = BSON_BINARY_SUBTYPE_MD5;
  7064. exports.BSON_BINARY_SUBTYPE_USER_DEFINED = BSON_BINARY_SUBTYPE_USER_DEFINED;
  7065. exports.BSON_BINARY_SUBTYPE_UUID = BSON_BINARY_SUBTYPE_UUID;
  7066. exports.BSON_BINARY_SUBTYPE_UUID_NEW = BSON_BINARY_SUBTYPE_UUID_NEW;
  7067. exports.BSON_DATA_ARRAY = BSON_DATA_ARRAY;
  7068. exports.BSON_DATA_BINARY = BSON_DATA_BINARY;
  7069. exports.BSON_DATA_BOOLEAN = BSON_DATA_BOOLEAN;
  7070. exports.BSON_DATA_CODE = BSON_DATA_CODE;
  7071. exports.BSON_DATA_CODE_W_SCOPE = BSON_DATA_CODE_W_SCOPE;
  7072. exports.BSON_DATA_DATE = BSON_DATA_DATE;
  7073. exports.BSON_DATA_DBPOINTER = BSON_DATA_DBPOINTER;
  7074. exports.BSON_DATA_DECIMAL128 = BSON_DATA_DECIMAL128;
  7075. exports.BSON_DATA_INT = BSON_DATA_INT;
  7076. exports.BSON_DATA_LONG = BSON_DATA_LONG;
  7077. exports.BSON_DATA_MAX_KEY = BSON_DATA_MAX_KEY;
  7078. exports.BSON_DATA_MIN_KEY = BSON_DATA_MIN_KEY;
  7079. exports.BSON_DATA_NULL = BSON_DATA_NULL;
  7080. exports.BSON_DATA_NUMBER = BSON_DATA_NUMBER;
  7081. exports.BSON_DATA_OBJECT = BSON_DATA_OBJECT;
  7082. exports.BSON_DATA_OID = BSON_DATA_OID;
  7083. exports.BSON_DATA_REGEXP = BSON_DATA_REGEXP;
  7084. exports.BSON_DATA_STRING = BSON_DATA_STRING;
  7085. exports.BSON_DATA_SYMBOL = BSON_DATA_SYMBOL;
  7086. exports.BSON_DATA_TIMESTAMP = BSON_DATA_TIMESTAMP;
  7087. exports.BSON_DATA_UNDEFINED = BSON_DATA_UNDEFINED;
  7088. exports.BSON_INT32_MAX = BSON_INT32_MAX;
  7089. exports.BSON_INT32_MIN = BSON_INT32_MIN;
  7090. exports.BSON_INT64_MAX = BSON_INT64_MAX;
  7091. exports.BSON_INT64_MIN = BSON_INT64_MIN;
  7092. exports.Binary = Binary;
  7093. exports.Code = Code;
  7094. exports.DBRef = DBRef;
  7095. exports.Decimal128 = Decimal128;
  7096. exports.Double = Double;
  7097. exports.Int32 = Int32;
  7098. exports.Long = Long;
  7099. exports.LongWithoutOverridesClass = LongWithoutOverridesClass;
  7100. exports.MaxKey = MaxKey;
  7101. exports.MinKey = MinKey;
  7102. exports.ObjectID = ObjectId;
  7103. exports.ObjectId = ObjectId;
  7104. exports.Timestamp = Timestamp;
  7105. exports.UUID = UUID;
  7106. exports.calculateObjectSize = calculateObjectSize;
  7107. exports.default = BSON;
  7108. exports.deserialize = deserialize;
  7109. exports.deserializeStream = deserializeStream;
  7110. exports.serialize = serialize;
  7111. exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
  7112. exports.setInternalBufferSize = setInternalBufferSize;
  7113. Object.defineProperty(exports, '__esModule', { value: true });
  7114. })));
  7115. //# sourceMappingURL=bson.browser.umd.js.map