bson.browser.umd.js 281 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568
  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. */
  2007. var Binary = /** @class */ (function () {
  2008. /**
  2009. * @param buffer - a buffer object containing the binary data.
  2010. * @param subType - the option binary type.
  2011. */
  2012. function Binary(buffer, subType) {
  2013. if (!(this instanceof Binary))
  2014. return new Binary(buffer, subType);
  2015. if (!(buffer == null) &&
  2016. !(typeof buffer === 'string') &&
  2017. !ArrayBuffer.isView(buffer) &&
  2018. !(buffer instanceof ArrayBuffer) &&
  2019. !Array.isArray(buffer)) {
  2020. throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
  2021. }
  2022. this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT;
  2023. if (buffer == null) {
  2024. // create an empty binary buffer
  2025. this.buffer = buffer_1.alloc(Binary.BUFFER_SIZE);
  2026. this.position = 0;
  2027. }
  2028. else {
  2029. if (typeof buffer === 'string') {
  2030. // string
  2031. this.buffer = buffer_1.from(buffer, 'binary');
  2032. }
  2033. else if (Array.isArray(buffer)) {
  2034. // number[]
  2035. this.buffer = buffer_1.from(buffer);
  2036. }
  2037. else {
  2038. // Buffer | TypedArray | ArrayBuffer
  2039. this.buffer = ensureBuffer(buffer);
  2040. }
  2041. this.position = this.buffer.byteLength;
  2042. }
  2043. }
  2044. /**
  2045. * Updates this binary with byte_value.
  2046. *
  2047. * @param byteValue - a single byte we wish to write.
  2048. */
  2049. Binary.prototype.put = function (byteValue) {
  2050. // If it's a string and a has more than one character throw an error
  2051. if (typeof byteValue === 'string' && byteValue.length !== 1) {
  2052. throw new BSONTypeError('only accepts single character String');
  2053. }
  2054. else if (typeof byteValue !== 'number' && byteValue.length !== 1)
  2055. throw new BSONTypeError('only accepts single character Uint8Array or Array');
  2056. // Decode the byte value once
  2057. var decodedByte;
  2058. if (typeof byteValue === 'string') {
  2059. decodedByte = byteValue.charCodeAt(0);
  2060. }
  2061. else if (typeof byteValue === 'number') {
  2062. decodedByte = byteValue;
  2063. }
  2064. else {
  2065. decodedByte = byteValue[0];
  2066. }
  2067. if (decodedByte < 0 || decodedByte > 255) {
  2068. throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255');
  2069. }
  2070. if (this.buffer.length > this.position) {
  2071. this.buffer[this.position++] = decodedByte;
  2072. }
  2073. else {
  2074. var buffer = buffer_1.alloc(Binary.BUFFER_SIZE + this.buffer.length);
  2075. // Combine the two buffers together
  2076. this.buffer.copy(buffer, 0, 0, this.buffer.length);
  2077. this.buffer = buffer;
  2078. this.buffer[this.position++] = decodedByte;
  2079. }
  2080. };
  2081. /**
  2082. * Writes a buffer or string to the binary.
  2083. *
  2084. * @param sequence - a string or buffer to be written to the Binary BSON object.
  2085. * @param offset - specify the binary of where to write the content.
  2086. */
  2087. Binary.prototype.write = function (sequence, offset) {
  2088. offset = typeof offset === 'number' ? offset : this.position;
  2089. // If the buffer is to small let's extend the buffer
  2090. if (this.buffer.length < offset + sequence.length) {
  2091. var buffer = buffer_1.alloc(this.buffer.length + sequence.length);
  2092. this.buffer.copy(buffer, 0, 0, this.buffer.length);
  2093. // Assign the new buffer
  2094. this.buffer = buffer;
  2095. }
  2096. if (ArrayBuffer.isView(sequence)) {
  2097. this.buffer.set(ensureBuffer(sequence), offset);
  2098. this.position =
  2099. offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
  2100. }
  2101. else if (typeof sequence === 'string') {
  2102. this.buffer.write(sequence, offset, sequence.length, 'binary');
  2103. this.position =
  2104. offset + sequence.length > this.position ? offset + sequence.length : this.position;
  2105. }
  2106. };
  2107. /**
  2108. * Reads **length** bytes starting at **position**.
  2109. *
  2110. * @param position - read from the given position in the Binary.
  2111. * @param length - the number of bytes to read.
  2112. */
  2113. Binary.prototype.read = function (position, length) {
  2114. length = length && length > 0 ? length : this.position;
  2115. // Let's return the data based on the type we have
  2116. return this.buffer.slice(position, position + length);
  2117. };
  2118. /**
  2119. * Returns the value of this binary as a string.
  2120. * @param asRaw - Will skip converting to a string
  2121. * @remarks
  2122. * This is handy when calling this function conditionally for some key value pairs and not others
  2123. */
  2124. Binary.prototype.value = function (asRaw) {
  2125. asRaw = !!asRaw;
  2126. // Optimize to serialize for the situation where the data == size of buffer
  2127. if (asRaw && this.buffer.length === this.position) {
  2128. return this.buffer;
  2129. }
  2130. // If it's a node.js buffer object
  2131. if (asRaw) {
  2132. return this.buffer.slice(0, this.position);
  2133. }
  2134. return this.buffer.toString('binary', 0, this.position);
  2135. };
  2136. /** the length of the binary sequence */
  2137. Binary.prototype.length = function () {
  2138. return this.position;
  2139. };
  2140. Binary.prototype.toJSON = function () {
  2141. return this.buffer.toString('base64');
  2142. };
  2143. Binary.prototype.toString = function (format) {
  2144. return this.buffer.toString(format);
  2145. };
  2146. /** @internal */
  2147. Binary.prototype.toExtendedJSON = function (options) {
  2148. options = options || {};
  2149. var base64String = this.buffer.toString('base64');
  2150. var subType = Number(this.sub_type).toString(16);
  2151. if (options.legacy) {
  2152. return {
  2153. $binary: base64String,
  2154. $type: subType.length === 1 ? '0' + subType : subType
  2155. };
  2156. }
  2157. return {
  2158. $binary: {
  2159. base64: base64String,
  2160. subType: subType.length === 1 ? '0' + subType : subType
  2161. }
  2162. };
  2163. };
  2164. Binary.prototype.toUUID = function () {
  2165. if (this.sub_type === Binary.SUBTYPE_UUID) {
  2166. return new UUID(this.buffer.slice(0, this.position));
  2167. }
  2168. throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
  2169. };
  2170. /** @internal */
  2171. Binary.fromExtendedJSON = function (doc, options) {
  2172. options = options || {};
  2173. var data;
  2174. var type;
  2175. if ('$binary' in doc) {
  2176. if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
  2177. type = doc.$type ? parseInt(doc.$type, 16) : 0;
  2178. data = buffer_1.from(doc.$binary, 'base64');
  2179. }
  2180. else {
  2181. if (typeof doc.$binary !== 'string') {
  2182. type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  2183. data = buffer_1.from(doc.$binary.base64, 'base64');
  2184. }
  2185. }
  2186. }
  2187. else if ('$uuid' in doc) {
  2188. type = 4;
  2189. data = uuidHexStringToBuffer(doc.$uuid);
  2190. }
  2191. if (!data) {
  2192. throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
  2193. }
  2194. return new Binary(data, type);
  2195. };
  2196. /** @internal */
  2197. Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2198. return this.inspect();
  2199. };
  2200. Binary.prototype.inspect = function () {
  2201. var asBuffer = this.value(true);
  2202. return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")";
  2203. };
  2204. /**
  2205. * Binary default subtype
  2206. * @internal
  2207. */
  2208. Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
  2209. /** Initial buffer default size */
  2210. Binary.BUFFER_SIZE = 256;
  2211. /** Default BSON type */
  2212. Binary.SUBTYPE_DEFAULT = 0;
  2213. /** Function BSON type */
  2214. Binary.SUBTYPE_FUNCTION = 1;
  2215. /** Byte Array BSON type */
  2216. Binary.SUBTYPE_BYTE_ARRAY = 2;
  2217. /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
  2218. Binary.SUBTYPE_UUID_OLD = 3;
  2219. /** UUID BSON type */
  2220. Binary.SUBTYPE_UUID = 4;
  2221. /** MD5 BSON type */
  2222. Binary.SUBTYPE_MD5 = 5;
  2223. /** Encrypted BSON type */
  2224. Binary.SUBTYPE_ENCRYPTED = 6;
  2225. /** Column BSON type */
  2226. Binary.SUBTYPE_COLUMN = 7;
  2227. /** User BSON type */
  2228. Binary.SUBTYPE_USER_DEFINED = 128;
  2229. return Binary;
  2230. }());
  2231. Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' });
  2232. /**
  2233. * A class representation of the BSON Code type.
  2234. * @public
  2235. */
  2236. var Code = /** @class */ (function () {
  2237. /**
  2238. * @param code - a string or function.
  2239. * @param scope - an optional scope for the function.
  2240. */
  2241. function Code(code, scope) {
  2242. if (!(this instanceof Code))
  2243. return new Code(code, scope);
  2244. this.code = code;
  2245. this.scope = scope;
  2246. }
  2247. Code.prototype.toJSON = function () {
  2248. return { code: this.code, scope: this.scope };
  2249. };
  2250. /** @internal */
  2251. Code.prototype.toExtendedJSON = function () {
  2252. if (this.scope) {
  2253. return { $code: this.code, $scope: this.scope };
  2254. }
  2255. return { $code: this.code };
  2256. };
  2257. /** @internal */
  2258. Code.fromExtendedJSON = function (doc) {
  2259. return new Code(doc.$code, doc.$scope);
  2260. };
  2261. /** @internal */
  2262. Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2263. return this.inspect();
  2264. };
  2265. Code.prototype.inspect = function () {
  2266. var codeJson = this.toJSON();
  2267. return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")";
  2268. };
  2269. return Code;
  2270. }());
  2271. Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' });
  2272. /** @internal */
  2273. function isDBRefLike(value) {
  2274. return (isObjectLike(value) &&
  2275. value.$id != null &&
  2276. typeof value.$ref === 'string' &&
  2277. (value.$db == null || typeof value.$db === 'string'));
  2278. }
  2279. /**
  2280. * A class representation of the BSON DBRef type.
  2281. * @public
  2282. */
  2283. var DBRef = /** @class */ (function () {
  2284. /**
  2285. * @param collection - the collection name.
  2286. * @param oid - the reference ObjectId.
  2287. * @param db - optional db name, if omitted the reference is local to the current db.
  2288. */
  2289. function DBRef(collection, oid, db, fields) {
  2290. if (!(this instanceof DBRef))
  2291. return new DBRef(collection, oid, db, fields);
  2292. // check if namespace has been provided
  2293. var parts = collection.split('.');
  2294. if (parts.length === 2) {
  2295. db = parts.shift();
  2296. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  2297. collection = parts.shift();
  2298. }
  2299. this.collection = collection;
  2300. this.oid = oid;
  2301. this.db = db;
  2302. this.fields = fields || {};
  2303. }
  2304. Object.defineProperty(DBRef.prototype, "namespace", {
  2305. // Property provided for compatibility with the 1.x parser
  2306. // the 1.x parser used a "namespace" property, while 4.x uses "collection"
  2307. /** @internal */
  2308. get: function () {
  2309. return this.collection;
  2310. },
  2311. set: function (value) {
  2312. this.collection = value;
  2313. },
  2314. enumerable: false,
  2315. configurable: true
  2316. });
  2317. DBRef.prototype.toJSON = function () {
  2318. var o = Object.assign({
  2319. $ref: this.collection,
  2320. $id: this.oid
  2321. }, this.fields);
  2322. if (this.db != null)
  2323. o.$db = this.db;
  2324. return o;
  2325. };
  2326. /** @internal */
  2327. DBRef.prototype.toExtendedJSON = function (options) {
  2328. options = options || {};
  2329. var o = {
  2330. $ref: this.collection,
  2331. $id: this.oid
  2332. };
  2333. if (options.legacy) {
  2334. return o;
  2335. }
  2336. if (this.db)
  2337. o.$db = this.db;
  2338. o = Object.assign(o, this.fields);
  2339. return o;
  2340. };
  2341. /** @internal */
  2342. DBRef.fromExtendedJSON = function (doc) {
  2343. var copy = Object.assign({}, doc);
  2344. delete copy.$ref;
  2345. delete copy.$id;
  2346. delete copy.$db;
  2347. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  2348. };
  2349. /** @internal */
  2350. DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2351. return this.inspect();
  2352. };
  2353. DBRef.prototype.inspect = function () {
  2354. // NOTE: if OID is an ObjectId class it will just print the oid string.
  2355. var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
  2356. return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")";
  2357. };
  2358. return DBRef;
  2359. }());
  2360. Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' });
  2361. /**
  2362. * wasm optimizations, to do native i64 multiplication and divide
  2363. */
  2364. var wasm = undefined;
  2365. try {
  2366. wasm = new WebAssembly.Instance(new WebAssembly.Module(
  2367. // prettier-ignore
  2368. 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;
  2369. }
  2370. catch (_a) {
  2371. // no wasm support
  2372. }
  2373. var TWO_PWR_16_DBL = 1 << 16;
  2374. var TWO_PWR_24_DBL = 1 << 24;
  2375. var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  2376. var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  2377. var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  2378. /** A cache of the Long representations of small integer values. */
  2379. var INT_CACHE = {};
  2380. /** A cache of the Long representations of small unsigned integer values. */
  2381. var UINT_CACHE = {};
  2382. /**
  2383. * A class representing a 64-bit integer
  2384. * @public
  2385. * @remarks
  2386. * The internal representation of a long is the two given signed, 32-bit values.
  2387. * We use 32-bit pieces because these are the size of integers on which
  2388. * Javascript performs bit-operations. For operations like addition and
  2389. * multiplication, we split each number into 16 bit pieces, which can easily be
  2390. * multiplied within Javascript's floating-point representation without overflow
  2391. * or change in sign.
  2392. * In the algorithms below, we frequently reduce the negative case to the
  2393. * positive case by negating the input(s) and then post-processing the result.
  2394. * Note that we must ALWAYS check specially whether those values are MIN_VALUE
  2395. * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
  2396. * a positive number, it overflows back into a negative). Not handling this
  2397. * case would often result in infinite recursion.
  2398. * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
  2399. */
  2400. var Long = /** @class */ (function () {
  2401. /**
  2402. * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
  2403. * See the from* functions below for more convenient ways of constructing Longs.
  2404. *
  2405. * Acceptable signatures are:
  2406. * - Long(low, high, unsigned?)
  2407. * - Long(bigint, unsigned?)
  2408. * - Long(string, unsigned?)
  2409. *
  2410. * @param low - The low (signed) 32 bits of the long
  2411. * @param high - The high (signed) 32 bits of the long
  2412. * @param unsigned - Whether unsigned or not, defaults to signed
  2413. */
  2414. function Long(low, high, unsigned) {
  2415. if (low === void 0) { low = 0; }
  2416. if (!(this instanceof Long))
  2417. return new Long(low, high, unsigned);
  2418. if (typeof low === 'bigint') {
  2419. Object.assign(this, Long.fromBigInt(low, !!high));
  2420. }
  2421. else if (typeof low === 'string') {
  2422. Object.assign(this, Long.fromString(low, !!high));
  2423. }
  2424. else {
  2425. this.low = low | 0;
  2426. this.high = high | 0;
  2427. this.unsigned = !!unsigned;
  2428. }
  2429. Object.defineProperty(this, '__isLong__', {
  2430. value: true,
  2431. configurable: false,
  2432. writable: false,
  2433. enumerable: false
  2434. });
  2435. }
  2436. /**
  2437. * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.
  2438. * Each is assumed to use 32 bits.
  2439. * @param lowBits - The low 32 bits
  2440. * @param highBits - The high 32 bits
  2441. * @param unsigned - Whether unsigned or not, defaults to signed
  2442. * @returns The corresponding Long value
  2443. */
  2444. Long.fromBits = function (lowBits, highBits, unsigned) {
  2445. return new Long(lowBits, highBits, unsigned);
  2446. };
  2447. /**
  2448. * Returns a Long representing the given 32 bit integer value.
  2449. * @param value - The 32 bit integer in question
  2450. * @param unsigned - Whether unsigned or not, defaults to signed
  2451. * @returns The corresponding Long value
  2452. */
  2453. Long.fromInt = function (value, unsigned) {
  2454. var obj, cachedObj, cache;
  2455. if (unsigned) {
  2456. value >>>= 0;
  2457. if ((cache = 0 <= value && value < 256)) {
  2458. cachedObj = UINT_CACHE[value];
  2459. if (cachedObj)
  2460. return cachedObj;
  2461. }
  2462. obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  2463. if (cache)
  2464. UINT_CACHE[value] = obj;
  2465. return obj;
  2466. }
  2467. else {
  2468. value |= 0;
  2469. if ((cache = -128 <= value && value < 128)) {
  2470. cachedObj = INT_CACHE[value];
  2471. if (cachedObj)
  2472. return cachedObj;
  2473. }
  2474. obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
  2475. if (cache)
  2476. INT_CACHE[value] = obj;
  2477. return obj;
  2478. }
  2479. };
  2480. /**
  2481. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  2482. * @param value - The number in question
  2483. * @param unsigned - Whether unsigned or not, defaults to signed
  2484. * @returns The corresponding Long value
  2485. */
  2486. Long.fromNumber = function (value, unsigned) {
  2487. if (isNaN(value))
  2488. return unsigned ? Long.UZERO : Long.ZERO;
  2489. if (unsigned) {
  2490. if (value < 0)
  2491. return Long.UZERO;
  2492. if (value >= TWO_PWR_64_DBL)
  2493. return Long.MAX_UNSIGNED_VALUE;
  2494. }
  2495. else {
  2496. if (value <= -TWO_PWR_63_DBL)
  2497. return Long.MIN_VALUE;
  2498. if (value + 1 >= TWO_PWR_63_DBL)
  2499. return Long.MAX_VALUE;
  2500. }
  2501. if (value < 0)
  2502. return Long.fromNumber(-value, unsigned).neg();
  2503. return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  2504. };
  2505. /**
  2506. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  2507. * @param value - The number in question
  2508. * @param unsigned - Whether unsigned or not, defaults to signed
  2509. * @returns The corresponding Long value
  2510. */
  2511. Long.fromBigInt = function (value, unsigned) {
  2512. return Long.fromString(value.toString(), unsigned);
  2513. };
  2514. /**
  2515. * Returns a Long representation of the given string, written using the specified radix.
  2516. * @param str - The textual representation of the Long
  2517. * @param unsigned - Whether unsigned or not, defaults to signed
  2518. * @param radix - The radix in which the text is written (2-36), defaults to 10
  2519. * @returns The corresponding Long value
  2520. */
  2521. Long.fromString = function (str, unsigned, radix) {
  2522. if (str.length === 0)
  2523. throw Error('empty string');
  2524. if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity')
  2525. return Long.ZERO;
  2526. if (typeof unsigned === 'number') {
  2527. // For goog.math.long compatibility
  2528. (radix = unsigned), (unsigned = false);
  2529. }
  2530. else {
  2531. unsigned = !!unsigned;
  2532. }
  2533. radix = radix || 10;
  2534. if (radix < 2 || 36 < radix)
  2535. throw RangeError('radix');
  2536. var p;
  2537. if ((p = str.indexOf('-')) > 0)
  2538. throw Error('interior hyphen');
  2539. else if (p === 0) {
  2540. return Long.fromString(str.substring(1), unsigned, radix).neg();
  2541. }
  2542. // Do several (8) digits each time through the loop, so as to
  2543. // minimize the calls to the very expensive emulated div.
  2544. var radixToPower = Long.fromNumber(Math.pow(radix, 8));
  2545. var result = Long.ZERO;
  2546. for (var i = 0; i < str.length; i += 8) {
  2547. var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
  2548. if (size < 8) {
  2549. var power = Long.fromNumber(Math.pow(radix, size));
  2550. result = result.mul(power).add(Long.fromNumber(value));
  2551. }
  2552. else {
  2553. result = result.mul(radixToPower);
  2554. result = result.add(Long.fromNumber(value));
  2555. }
  2556. }
  2557. result.unsigned = unsigned;
  2558. return result;
  2559. };
  2560. /**
  2561. * Creates a Long from its byte representation.
  2562. * @param bytes - Byte representation
  2563. * @param unsigned - Whether unsigned or not, defaults to signed
  2564. * @param le - Whether little or big endian, defaults to big endian
  2565. * @returns The corresponding Long value
  2566. */
  2567. Long.fromBytes = function (bytes, unsigned, le) {
  2568. return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
  2569. };
  2570. /**
  2571. * Creates a Long from its little endian byte representation.
  2572. * @param bytes - Little endian byte representation
  2573. * @param unsigned - Whether unsigned or not, defaults to signed
  2574. * @returns The corresponding Long value
  2575. */
  2576. Long.fromBytesLE = function (bytes, unsigned) {
  2577. 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);
  2578. };
  2579. /**
  2580. * Creates a Long from its big endian byte representation.
  2581. * @param bytes - Big endian byte representation
  2582. * @param unsigned - Whether unsigned or not, defaults to signed
  2583. * @returns The corresponding Long value
  2584. */
  2585. Long.fromBytesBE = function (bytes, unsigned) {
  2586. 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);
  2587. };
  2588. /**
  2589. * Tests if the specified object is a Long.
  2590. */
  2591. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  2592. Long.isLong = function (value) {
  2593. return isObjectLike(value) && value['__isLong__'] === true;
  2594. };
  2595. /**
  2596. * Converts the specified value to a Long.
  2597. * @param unsigned - Whether unsigned or not, defaults to signed
  2598. */
  2599. Long.fromValue = function (val, unsigned) {
  2600. if (typeof val === 'number')
  2601. return Long.fromNumber(val, unsigned);
  2602. if (typeof val === 'string')
  2603. return Long.fromString(val, unsigned);
  2604. // Throws for non-objects, converts non-instanceof Long:
  2605. return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
  2606. };
  2607. /** Returns the sum of this and the specified Long. */
  2608. Long.prototype.add = function (addend) {
  2609. if (!Long.isLong(addend))
  2610. addend = Long.fromValue(addend);
  2611. // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
  2612. var a48 = this.high >>> 16;
  2613. var a32 = this.high & 0xffff;
  2614. var a16 = this.low >>> 16;
  2615. var a00 = this.low & 0xffff;
  2616. var b48 = addend.high >>> 16;
  2617. var b32 = addend.high & 0xffff;
  2618. var b16 = addend.low >>> 16;
  2619. var b00 = addend.low & 0xffff;
  2620. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  2621. c00 += a00 + b00;
  2622. c16 += c00 >>> 16;
  2623. c00 &= 0xffff;
  2624. c16 += a16 + b16;
  2625. c32 += c16 >>> 16;
  2626. c16 &= 0xffff;
  2627. c32 += a32 + b32;
  2628. c48 += c32 >>> 16;
  2629. c32 &= 0xffff;
  2630. c48 += a48 + b48;
  2631. c48 &= 0xffff;
  2632. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  2633. };
  2634. /**
  2635. * Returns the sum of this and the specified Long.
  2636. * @returns Sum
  2637. */
  2638. Long.prototype.and = function (other) {
  2639. if (!Long.isLong(other))
  2640. other = Long.fromValue(other);
  2641. return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  2642. };
  2643. /**
  2644. * Compares this Long's value with the specified's.
  2645. * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
  2646. */
  2647. Long.prototype.compare = function (other) {
  2648. if (!Long.isLong(other))
  2649. other = Long.fromValue(other);
  2650. if (this.eq(other))
  2651. return 0;
  2652. var thisNeg = this.isNegative(), otherNeg = other.isNegative();
  2653. if (thisNeg && !otherNeg)
  2654. return -1;
  2655. if (!thisNeg && otherNeg)
  2656. return 1;
  2657. // At this point the sign bits are the same
  2658. if (!this.unsigned)
  2659. return this.sub(other).isNegative() ? -1 : 1;
  2660. // Both are positive if at least one is unsigned
  2661. return other.high >>> 0 > this.high >>> 0 ||
  2662. (other.high === this.high && other.low >>> 0 > this.low >>> 0)
  2663. ? -1
  2664. : 1;
  2665. };
  2666. /** This is an alias of {@link Long.compare} */
  2667. Long.prototype.comp = function (other) {
  2668. return this.compare(other);
  2669. };
  2670. /**
  2671. * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.
  2672. * @returns Quotient
  2673. */
  2674. Long.prototype.divide = function (divisor) {
  2675. if (!Long.isLong(divisor))
  2676. divisor = Long.fromValue(divisor);
  2677. if (divisor.isZero())
  2678. throw Error('division by zero');
  2679. // use wasm support if present
  2680. if (wasm) {
  2681. // guard against signed division overflow: the largest
  2682. // negative number / -1 would be 1 larger than the largest
  2683. // positive number, due to two's complement.
  2684. if (!this.unsigned &&
  2685. this.high === -0x80000000 &&
  2686. divisor.low === -1 &&
  2687. divisor.high === -1) {
  2688. // be consistent with non-wasm code path
  2689. return this;
  2690. }
  2691. var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
  2692. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  2693. }
  2694. if (this.isZero())
  2695. return this.unsigned ? Long.UZERO : Long.ZERO;
  2696. var approx, rem, res;
  2697. if (!this.unsigned) {
  2698. // This section is only relevant for signed longs and is derived from the
  2699. // closure library as a whole.
  2700. if (this.eq(Long.MIN_VALUE)) {
  2701. if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
  2702. return Long.MIN_VALUE;
  2703. // recall that -MIN_VALUE == MIN_VALUE
  2704. else if (divisor.eq(Long.MIN_VALUE))
  2705. return Long.ONE;
  2706. else {
  2707. // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
  2708. var halfThis = this.shr(1);
  2709. approx = halfThis.div(divisor).shl(1);
  2710. if (approx.eq(Long.ZERO)) {
  2711. return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
  2712. }
  2713. else {
  2714. rem = this.sub(divisor.mul(approx));
  2715. res = approx.add(rem.div(divisor));
  2716. return res;
  2717. }
  2718. }
  2719. }
  2720. else if (divisor.eq(Long.MIN_VALUE))
  2721. return this.unsigned ? Long.UZERO : Long.ZERO;
  2722. if (this.isNegative()) {
  2723. if (divisor.isNegative())
  2724. return this.neg().div(divisor.neg());
  2725. return this.neg().div(divisor).neg();
  2726. }
  2727. else if (divisor.isNegative())
  2728. return this.div(divisor.neg()).neg();
  2729. res = Long.ZERO;
  2730. }
  2731. else {
  2732. // The algorithm below has not been made for unsigned longs. It's therefore
  2733. // required to take special care of the MSB prior to running it.
  2734. if (!divisor.unsigned)
  2735. divisor = divisor.toUnsigned();
  2736. if (divisor.gt(this))
  2737. return Long.UZERO;
  2738. if (divisor.gt(this.shru(1)))
  2739. // 15 >>> 1 = 7 ; with divisor = 8 ; true
  2740. return Long.UONE;
  2741. res = Long.UZERO;
  2742. }
  2743. // Repeat the following until the remainder is less than other: find a
  2744. // floating-point that approximates remainder / other *from below*, add this
  2745. // into the result, and subtract it from the remainder. It is critical that
  2746. // the approximate value is less than or equal to the real value so that the
  2747. // remainder never becomes negative.
  2748. rem = this;
  2749. while (rem.gte(divisor)) {
  2750. // Approximate the result of division. This may be a little greater or
  2751. // smaller than the actual value.
  2752. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  2753. // We will tweak the approximate result by changing it in the 48-th digit or
  2754. // the smallest non-fractional digit, whichever is larger.
  2755. var log2 = Math.ceil(Math.log(approx) / Math.LN2);
  2756. var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
  2757. // Decrease the approximation until it is smaller than the remainder. Note
  2758. // that if it is too large, the product overflows and is negative.
  2759. var approxRes = Long.fromNumber(approx);
  2760. var approxRem = approxRes.mul(divisor);
  2761. while (approxRem.isNegative() || approxRem.gt(rem)) {
  2762. approx -= delta;
  2763. approxRes = Long.fromNumber(approx, this.unsigned);
  2764. approxRem = approxRes.mul(divisor);
  2765. }
  2766. // We know the answer can't be zero... and actually, zero would cause
  2767. // infinite recursion since we would make no progress.
  2768. if (approxRes.isZero())
  2769. approxRes = Long.ONE;
  2770. res = res.add(approxRes);
  2771. rem = rem.sub(approxRem);
  2772. }
  2773. return res;
  2774. };
  2775. /**This is an alias of {@link Long.divide} */
  2776. Long.prototype.div = function (divisor) {
  2777. return this.divide(divisor);
  2778. };
  2779. /**
  2780. * Tests if this Long's value equals the specified's.
  2781. * @param other - Other value
  2782. */
  2783. Long.prototype.equals = function (other) {
  2784. if (!Long.isLong(other))
  2785. other = Long.fromValue(other);
  2786. if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
  2787. return false;
  2788. return this.high === other.high && this.low === other.low;
  2789. };
  2790. /** This is an alias of {@link Long.equals} */
  2791. Long.prototype.eq = function (other) {
  2792. return this.equals(other);
  2793. };
  2794. /** Gets the high 32 bits as a signed integer. */
  2795. Long.prototype.getHighBits = function () {
  2796. return this.high;
  2797. };
  2798. /** Gets the high 32 bits as an unsigned integer. */
  2799. Long.prototype.getHighBitsUnsigned = function () {
  2800. return this.high >>> 0;
  2801. };
  2802. /** Gets the low 32 bits as a signed integer. */
  2803. Long.prototype.getLowBits = function () {
  2804. return this.low;
  2805. };
  2806. /** Gets the low 32 bits as an unsigned integer. */
  2807. Long.prototype.getLowBitsUnsigned = function () {
  2808. return this.low >>> 0;
  2809. };
  2810. /** Gets the number of bits needed to represent the absolute value of this Long. */
  2811. Long.prototype.getNumBitsAbs = function () {
  2812. if (this.isNegative()) {
  2813. // Unsigned Longs are never negative
  2814. return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  2815. }
  2816. var val = this.high !== 0 ? this.high : this.low;
  2817. var bit;
  2818. for (bit = 31; bit > 0; bit--)
  2819. if ((val & (1 << bit)) !== 0)
  2820. break;
  2821. return this.high !== 0 ? bit + 33 : bit + 1;
  2822. };
  2823. /** Tests if this Long's value is greater than the specified's. */
  2824. Long.prototype.greaterThan = function (other) {
  2825. return this.comp(other) > 0;
  2826. };
  2827. /** This is an alias of {@link Long.greaterThan} */
  2828. Long.prototype.gt = function (other) {
  2829. return this.greaterThan(other);
  2830. };
  2831. /** Tests if this Long's value is greater than or equal the specified's. */
  2832. Long.prototype.greaterThanOrEqual = function (other) {
  2833. return this.comp(other) >= 0;
  2834. };
  2835. /** This is an alias of {@link Long.greaterThanOrEqual} */
  2836. Long.prototype.gte = function (other) {
  2837. return this.greaterThanOrEqual(other);
  2838. };
  2839. /** This is an alias of {@link Long.greaterThanOrEqual} */
  2840. Long.prototype.ge = function (other) {
  2841. return this.greaterThanOrEqual(other);
  2842. };
  2843. /** Tests if this Long's value is even. */
  2844. Long.prototype.isEven = function () {
  2845. return (this.low & 1) === 0;
  2846. };
  2847. /** Tests if this Long's value is negative. */
  2848. Long.prototype.isNegative = function () {
  2849. return !this.unsigned && this.high < 0;
  2850. };
  2851. /** Tests if this Long's value is odd. */
  2852. Long.prototype.isOdd = function () {
  2853. return (this.low & 1) === 1;
  2854. };
  2855. /** Tests if this Long's value is positive. */
  2856. Long.prototype.isPositive = function () {
  2857. return this.unsigned || this.high >= 0;
  2858. };
  2859. /** Tests if this Long's value equals zero. */
  2860. Long.prototype.isZero = function () {
  2861. return this.high === 0 && this.low === 0;
  2862. };
  2863. /** Tests if this Long's value is less than the specified's. */
  2864. Long.prototype.lessThan = function (other) {
  2865. return this.comp(other) < 0;
  2866. };
  2867. /** This is an alias of {@link Long#lessThan}. */
  2868. Long.prototype.lt = function (other) {
  2869. return this.lessThan(other);
  2870. };
  2871. /** Tests if this Long's value is less than or equal the specified's. */
  2872. Long.prototype.lessThanOrEqual = function (other) {
  2873. return this.comp(other) <= 0;
  2874. };
  2875. /** This is an alias of {@link Long.lessThanOrEqual} */
  2876. Long.prototype.lte = function (other) {
  2877. return this.lessThanOrEqual(other);
  2878. };
  2879. /** Returns this Long modulo the specified. */
  2880. Long.prototype.modulo = function (divisor) {
  2881. if (!Long.isLong(divisor))
  2882. divisor = Long.fromValue(divisor);
  2883. // use wasm support if present
  2884. if (wasm) {
  2885. var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
  2886. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  2887. }
  2888. return this.sub(this.div(divisor).mul(divisor));
  2889. };
  2890. /** This is an alias of {@link Long.modulo} */
  2891. Long.prototype.mod = function (divisor) {
  2892. return this.modulo(divisor);
  2893. };
  2894. /** This is an alias of {@link Long.modulo} */
  2895. Long.prototype.rem = function (divisor) {
  2896. return this.modulo(divisor);
  2897. };
  2898. /**
  2899. * Returns the product of this and the specified Long.
  2900. * @param multiplier - Multiplier
  2901. * @returns Product
  2902. */
  2903. Long.prototype.multiply = function (multiplier) {
  2904. if (this.isZero())
  2905. return Long.ZERO;
  2906. if (!Long.isLong(multiplier))
  2907. multiplier = Long.fromValue(multiplier);
  2908. // use wasm support if present
  2909. if (wasm) {
  2910. var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
  2911. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  2912. }
  2913. if (multiplier.isZero())
  2914. return Long.ZERO;
  2915. if (this.eq(Long.MIN_VALUE))
  2916. return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  2917. if (multiplier.eq(Long.MIN_VALUE))
  2918. return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  2919. if (this.isNegative()) {
  2920. if (multiplier.isNegative())
  2921. return this.neg().mul(multiplier.neg());
  2922. else
  2923. return this.neg().mul(multiplier).neg();
  2924. }
  2925. else if (multiplier.isNegative())
  2926. return this.mul(multiplier.neg()).neg();
  2927. // If both longs are small, use float multiplication
  2928. if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
  2929. return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  2930. // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
  2931. // We can skip products that would overflow.
  2932. var a48 = this.high >>> 16;
  2933. var a32 = this.high & 0xffff;
  2934. var a16 = this.low >>> 16;
  2935. var a00 = this.low & 0xffff;
  2936. var b48 = multiplier.high >>> 16;
  2937. var b32 = multiplier.high & 0xffff;
  2938. var b16 = multiplier.low >>> 16;
  2939. var b00 = multiplier.low & 0xffff;
  2940. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  2941. c00 += a00 * b00;
  2942. c16 += c00 >>> 16;
  2943. c00 &= 0xffff;
  2944. c16 += a16 * b00;
  2945. c32 += c16 >>> 16;
  2946. c16 &= 0xffff;
  2947. c16 += a00 * b16;
  2948. c32 += c16 >>> 16;
  2949. c16 &= 0xffff;
  2950. c32 += a32 * b00;
  2951. c48 += c32 >>> 16;
  2952. c32 &= 0xffff;
  2953. c32 += a16 * b16;
  2954. c48 += c32 >>> 16;
  2955. c32 &= 0xffff;
  2956. c32 += a00 * b32;
  2957. c48 += c32 >>> 16;
  2958. c32 &= 0xffff;
  2959. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  2960. c48 &= 0xffff;
  2961. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  2962. };
  2963. /** This is an alias of {@link Long.multiply} */
  2964. Long.prototype.mul = function (multiplier) {
  2965. return this.multiply(multiplier);
  2966. };
  2967. /** Returns the Negation of this Long's value. */
  2968. Long.prototype.negate = function () {
  2969. if (!this.unsigned && this.eq(Long.MIN_VALUE))
  2970. return Long.MIN_VALUE;
  2971. return this.not().add(Long.ONE);
  2972. };
  2973. /** This is an alias of {@link Long.negate} */
  2974. Long.prototype.neg = function () {
  2975. return this.negate();
  2976. };
  2977. /** Returns the bitwise NOT of this Long. */
  2978. Long.prototype.not = function () {
  2979. return Long.fromBits(~this.low, ~this.high, this.unsigned);
  2980. };
  2981. /** Tests if this Long's value differs from the specified's. */
  2982. Long.prototype.notEquals = function (other) {
  2983. return !this.equals(other);
  2984. };
  2985. /** This is an alias of {@link Long.notEquals} */
  2986. Long.prototype.neq = function (other) {
  2987. return this.notEquals(other);
  2988. };
  2989. /** This is an alias of {@link Long.notEquals} */
  2990. Long.prototype.ne = function (other) {
  2991. return this.notEquals(other);
  2992. };
  2993. /**
  2994. * Returns the bitwise OR of this Long and the specified.
  2995. */
  2996. Long.prototype.or = function (other) {
  2997. if (!Long.isLong(other))
  2998. other = Long.fromValue(other);
  2999. return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  3000. };
  3001. /**
  3002. * Returns this Long with bits shifted to the left by the given amount.
  3003. * @param numBits - Number of bits
  3004. * @returns Shifted Long
  3005. */
  3006. Long.prototype.shiftLeft = function (numBits) {
  3007. if (Long.isLong(numBits))
  3008. numBits = numBits.toInt();
  3009. if ((numBits &= 63) === 0)
  3010. return this;
  3011. else if (numBits < 32)
  3012. return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
  3013. else
  3014. return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
  3015. };
  3016. /** This is an alias of {@link Long.shiftLeft} */
  3017. Long.prototype.shl = function (numBits) {
  3018. return this.shiftLeft(numBits);
  3019. };
  3020. /**
  3021. * Returns this Long with bits arithmetically shifted to the right by the given amount.
  3022. * @param numBits - Number of bits
  3023. * @returns Shifted Long
  3024. */
  3025. Long.prototype.shiftRight = function (numBits) {
  3026. if (Long.isLong(numBits))
  3027. numBits = numBits.toInt();
  3028. if ((numBits &= 63) === 0)
  3029. return this;
  3030. else if (numBits < 32)
  3031. return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
  3032. else
  3033. return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  3034. };
  3035. /** This is an alias of {@link Long.shiftRight} */
  3036. Long.prototype.shr = function (numBits) {
  3037. return this.shiftRight(numBits);
  3038. };
  3039. /**
  3040. * Returns this Long with bits logically shifted to the right by the given amount.
  3041. * @param numBits - Number of bits
  3042. * @returns Shifted Long
  3043. */
  3044. Long.prototype.shiftRightUnsigned = function (numBits) {
  3045. if (Long.isLong(numBits))
  3046. numBits = numBits.toInt();
  3047. numBits &= 63;
  3048. if (numBits === 0)
  3049. return this;
  3050. else {
  3051. var high = this.high;
  3052. if (numBits < 32) {
  3053. var low = this.low;
  3054. return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
  3055. }
  3056. else if (numBits === 32)
  3057. return Long.fromBits(high, 0, this.unsigned);
  3058. else
  3059. return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
  3060. }
  3061. };
  3062. /** This is an alias of {@link Long.shiftRightUnsigned} */
  3063. Long.prototype.shr_u = function (numBits) {
  3064. return this.shiftRightUnsigned(numBits);
  3065. };
  3066. /** This is an alias of {@link Long.shiftRightUnsigned} */
  3067. Long.prototype.shru = function (numBits) {
  3068. return this.shiftRightUnsigned(numBits);
  3069. };
  3070. /**
  3071. * Returns the difference of this and the specified Long.
  3072. * @param subtrahend - Subtrahend
  3073. * @returns Difference
  3074. */
  3075. Long.prototype.subtract = function (subtrahend) {
  3076. if (!Long.isLong(subtrahend))
  3077. subtrahend = Long.fromValue(subtrahend);
  3078. return this.add(subtrahend.neg());
  3079. };
  3080. /** This is an alias of {@link Long.subtract} */
  3081. Long.prototype.sub = function (subtrahend) {
  3082. return this.subtract(subtrahend);
  3083. };
  3084. /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */
  3085. Long.prototype.toInt = function () {
  3086. return this.unsigned ? this.low >>> 0 : this.low;
  3087. };
  3088. /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */
  3089. Long.prototype.toNumber = function () {
  3090. if (this.unsigned)
  3091. return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
  3092. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  3093. };
  3094. /** Converts the Long to a BigInt (arbitrary precision). */
  3095. Long.prototype.toBigInt = function () {
  3096. return BigInt(this.toString());
  3097. };
  3098. /**
  3099. * Converts this Long to its byte representation.
  3100. * @param le - Whether little or big endian, defaults to big endian
  3101. * @returns Byte representation
  3102. */
  3103. Long.prototype.toBytes = function (le) {
  3104. return le ? this.toBytesLE() : this.toBytesBE();
  3105. };
  3106. /**
  3107. * Converts this Long to its little endian byte representation.
  3108. * @returns Little endian byte representation
  3109. */
  3110. Long.prototype.toBytesLE = function () {
  3111. var hi = this.high, lo = this.low;
  3112. return [
  3113. lo & 0xff,
  3114. (lo >>> 8) & 0xff,
  3115. (lo >>> 16) & 0xff,
  3116. lo >>> 24,
  3117. hi & 0xff,
  3118. (hi >>> 8) & 0xff,
  3119. (hi >>> 16) & 0xff,
  3120. hi >>> 24
  3121. ];
  3122. };
  3123. /**
  3124. * Converts this Long to its big endian byte representation.
  3125. * @returns Big endian byte representation
  3126. */
  3127. Long.prototype.toBytesBE = function () {
  3128. var hi = this.high, lo = this.low;
  3129. return [
  3130. hi >>> 24,
  3131. (hi >>> 16) & 0xff,
  3132. (hi >>> 8) & 0xff,
  3133. hi & 0xff,
  3134. lo >>> 24,
  3135. (lo >>> 16) & 0xff,
  3136. (lo >>> 8) & 0xff,
  3137. lo & 0xff
  3138. ];
  3139. };
  3140. /**
  3141. * Converts this Long to signed.
  3142. */
  3143. Long.prototype.toSigned = function () {
  3144. if (!this.unsigned)
  3145. return this;
  3146. return Long.fromBits(this.low, this.high, false);
  3147. };
  3148. /**
  3149. * Converts the Long to a string written in the specified radix.
  3150. * @param radix - Radix (2-36), defaults to 10
  3151. * @throws RangeError If `radix` is out of range
  3152. */
  3153. Long.prototype.toString = function (radix) {
  3154. radix = radix || 10;
  3155. if (radix < 2 || 36 < radix)
  3156. throw RangeError('radix');
  3157. if (this.isZero())
  3158. return '0';
  3159. if (this.isNegative()) {
  3160. // Unsigned Longs are never negative
  3161. if (this.eq(Long.MIN_VALUE)) {
  3162. // We need to change the Long value before it can be negated, so we remove
  3163. // the bottom-most digit in this base and then recurse to do the rest.
  3164. var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
  3165. return div.toString(radix) + rem1.toInt().toString(radix);
  3166. }
  3167. else
  3168. return '-' + this.neg().toString(radix);
  3169. }
  3170. // Do several (6) digits each time through the loop, so as to
  3171. // minimize the calls to the very expensive emulated div.
  3172. var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
  3173. // eslint-disable-next-line @typescript-eslint/no-this-alias
  3174. var rem = this;
  3175. var result = '';
  3176. // eslint-disable-next-line no-constant-condition
  3177. while (true) {
  3178. var remDiv = rem.div(radixToPower);
  3179. var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
  3180. var digits = intval.toString(radix);
  3181. rem = remDiv;
  3182. if (rem.isZero()) {
  3183. return digits + result;
  3184. }
  3185. else {
  3186. while (digits.length < 6)
  3187. digits = '0' + digits;
  3188. result = '' + digits + result;
  3189. }
  3190. }
  3191. };
  3192. /** Converts this Long to unsigned. */
  3193. Long.prototype.toUnsigned = function () {
  3194. if (this.unsigned)
  3195. return this;
  3196. return Long.fromBits(this.low, this.high, true);
  3197. };
  3198. /** Returns the bitwise XOR of this Long and the given one. */
  3199. Long.prototype.xor = function (other) {
  3200. if (!Long.isLong(other))
  3201. other = Long.fromValue(other);
  3202. return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  3203. };
  3204. /** This is an alias of {@link Long.isZero} */
  3205. Long.prototype.eqz = function () {
  3206. return this.isZero();
  3207. };
  3208. /** This is an alias of {@link Long.lessThanOrEqual} */
  3209. Long.prototype.le = function (other) {
  3210. return this.lessThanOrEqual(other);
  3211. };
  3212. /*
  3213. ****************************************************************
  3214. * BSON SPECIFIC ADDITIONS *
  3215. ****************************************************************
  3216. */
  3217. Long.prototype.toExtendedJSON = function (options) {
  3218. if (options && options.relaxed)
  3219. return this.toNumber();
  3220. return { $numberLong: this.toString() };
  3221. };
  3222. Long.fromExtendedJSON = function (doc, options) {
  3223. var result = Long.fromString(doc.$numberLong);
  3224. return options && options.relaxed ? result.toNumber() : result;
  3225. };
  3226. /** @internal */
  3227. Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  3228. return this.inspect();
  3229. };
  3230. Long.prototype.inspect = function () {
  3231. return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")";
  3232. };
  3233. Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
  3234. /** Maximum unsigned value. */
  3235. Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
  3236. /** Signed zero */
  3237. Long.ZERO = Long.fromInt(0);
  3238. /** Unsigned zero. */
  3239. Long.UZERO = Long.fromInt(0, true);
  3240. /** Signed one. */
  3241. Long.ONE = Long.fromInt(1);
  3242. /** Unsigned one. */
  3243. Long.UONE = Long.fromInt(1, true);
  3244. /** Signed negative one. */
  3245. Long.NEG_ONE = Long.fromInt(-1);
  3246. /** Maximum signed value. */
  3247. Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
  3248. /** Minimum signed value. */
  3249. Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
  3250. return Long;
  3251. }());
  3252. Object.defineProperty(Long.prototype, '__isLong__', { value: true });
  3253. Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' });
  3254. var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  3255. var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  3256. var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  3257. var EXPONENT_MAX = 6111;
  3258. var EXPONENT_MIN = -6176;
  3259. var EXPONENT_BIAS = 6176;
  3260. var MAX_DIGITS = 34;
  3261. // Nan value bits as 32 bit values (due to lack of longs)
  3262. var NAN_BUFFER = [
  3263. 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  3264. ].reverse();
  3265. // Infinity value bits 32 bit values (due to lack of longs)
  3266. var INF_NEGATIVE_BUFFER = [
  3267. 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  3268. ].reverse();
  3269. var INF_POSITIVE_BUFFER = [
  3270. 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  3271. ].reverse();
  3272. var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  3273. // Extract least significant 5 bits
  3274. var COMBINATION_MASK = 0x1f;
  3275. // Extract least significant 14 bits
  3276. var EXPONENT_MASK = 0x3fff;
  3277. // Value of combination field for Inf
  3278. var COMBINATION_INFINITY = 30;
  3279. // Value of combination field for NaN
  3280. var COMBINATION_NAN = 31;
  3281. // Detect if the value is a digit
  3282. function isDigit(value) {
  3283. return !isNaN(parseInt(value, 10));
  3284. }
  3285. // Divide two uint128 values
  3286. function divideu128(value) {
  3287. var DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
  3288. var _rem = Long.fromNumber(0);
  3289. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  3290. return { quotient: value, rem: _rem };
  3291. }
  3292. for (var i = 0; i <= 3; i++) {
  3293. // Adjust remainder to match value of next dividend
  3294. _rem = _rem.shiftLeft(32);
  3295. // Add the divided to _rem
  3296. _rem = _rem.add(new Long(value.parts[i], 0));
  3297. value.parts[i] = _rem.div(DIVISOR).low;
  3298. _rem = _rem.modulo(DIVISOR);
  3299. }
  3300. return { quotient: value, rem: _rem };
  3301. }
  3302. // Multiply two Long values and return the 128 bit value
  3303. function multiply64x2(left, right) {
  3304. if (!left && !right) {
  3305. return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
  3306. }
  3307. var leftHigh = left.shiftRightUnsigned(32);
  3308. var leftLow = new Long(left.getLowBits(), 0);
  3309. var rightHigh = right.shiftRightUnsigned(32);
  3310. var rightLow = new Long(right.getLowBits(), 0);
  3311. var productHigh = leftHigh.multiply(rightHigh);
  3312. var productMid = leftHigh.multiply(rightLow);
  3313. var productMid2 = leftLow.multiply(rightHigh);
  3314. var productLow = leftLow.multiply(rightLow);
  3315. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  3316. productMid = new Long(productMid.getLowBits(), 0)
  3317. .add(productMid2)
  3318. .add(productLow.shiftRightUnsigned(32));
  3319. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  3320. productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
  3321. // Return the 128 bit result
  3322. return { high: productHigh, low: productLow };
  3323. }
  3324. function lessThan(left, right) {
  3325. // Make values unsigned
  3326. var uhleft = left.high >>> 0;
  3327. var uhright = right.high >>> 0;
  3328. // Compare high bits first
  3329. if (uhleft < uhright) {
  3330. return true;
  3331. }
  3332. else if (uhleft === uhright) {
  3333. var ulleft = left.low >>> 0;
  3334. var ulright = right.low >>> 0;
  3335. if (ulleft < ulright)
  3336. return true;
  3337. }
  3338. return false;
  3339. }
  3340. function invalidErr(string, message) {
  3341. throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
  3342. }
  3343. /**
  3344. * A class representation of the BSON Decimal128 type.
  3345. * @public
  3346. */
  3347. var Decimal128 = /** @class */ (function () {
  3348. /**
  3349. * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order,
  3350. * or a string representation as returned by .toString()
  3351. */
  3352. function Decimal128(bytes) {
  3353. if (!(this instanceof Decimal128))
  3354. return new Decimal128(bytes);
  3355. if (typeof bytes === 'string') {
  3356. this.bytes = Decimal128.fromString(bytes).bytes;
  3357. }
  3358. else if (isUint8Array(bytes)) {
  3359. if (bytes.byteLength !== 16) {
  3360. throw new BSONTypeError('Decimal128 must take a Buffer of 16 bytes');
  3361. }
  3362. this.bytes = bytes;
  3363. }
  3364. else {
  3365. throw new BSONTypeError('Decimal128 must take a Buffer or string');
  3366. }
  3367. }
  3368. /**
  3369. * Create a Decimal128 instance from a string representation
  3370. *
  3371. * @param representation - a numeric string representation.
  3372. */
  3373. Decimal128.fromString = function (representation) {
  3374. // Parse state tracking
  3375. var isNegative = false;
  3376. var sawRadix = false;
  3377. var foundNonZero = false;
  3378. // Total number of significant digits (no leading or trailing zero)
  3379. var significantDigits = 0;
  3380. // Total number of significand digits read
  3381. var nDigitsRead = 0;
  3382. // Total number of digits (no leading zeros)
  3383. var nDigits = 0;
  3384. // The number of the digits after radix
  3385. var radixPosition = 0;
  3386. // The index of the first non-zero in *str*
  3387. var firstNonZero = 0;
  3388. // Digits Array
  3389. var digits = [0];
  3390. // The number of digits in digits
  3391. var nDigitsStored = 0;
  3392. // Insertion pointer for digits
  3393. var digitsInsert = 0;
  3394. // The index of the first non-zero digit
  3395. var firstDigit = 0;
  3396. // The index of the last digit
  3397. var lastDigit = 0;
  3398. // Exponent
  3399. var exponent = 0;
  3400. // loop index over array
  3401. var i = 0;
  3402. // The high 17 digits of the significand
  3403. var significandHigh = new Long(0, 0);
  3404. // The low 17 digits of the significand
  3405. var significandLow = new Long(0, 0);
  3406. // The biased exponent
  3407. var biasedExponent = 0;
  3408. // Read index
  3409. var index = 0;
  3410. // Naively prevent against REDOS attacks.
  3411. // TODO: implementing a custom parsing for this, or refactoring the regex would yield
  3412. // further gains.
  3413. if (representation.length >= 7000) {
  3414. throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
  3415. }
  3416. // Results
  3417. var stringMatch = representation.match(PARSE_STRING_REGEXP);
  3418. var infMatch = representation.match(PARSE_INF_REGEXP);
  3419. var nanMatch = representation.match(PARSE_NAN_REGEXP);
  3420. // Validate the string
  3421. if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
  3422. throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
  3423. }
  3424. if (stringMatch) {
  3425. // full_match = stringMatch[0]
  3426. // sign = stringMatch[1]
  3427. var unsignedNumber = stringMatch[2];
  3428. // stringMatch[3] is undefined if a whole number (ex "1", 12")
  3429. // but defined if a number w/ decimal in it (ex "1.0, 12.2")
  3430. var e = stringMatch[4];
  3431. var expSign = stringMatch[5];
  3432. var expNumber = stringMatch[6];
  3433. // they provided e, but didn't give an exponent number. for ex "1e"
  3434. if (e && expNumber === undefined)
  3435. invalidErr(representation, 'missing exponent power');
  3436. // they provided e, but didn't give a number before it. for ex "e1"
  3437. if (e && unsignedNumber === undefined)
  3438. invalidErr(representation, 'missing exponent base');
  3439. if (e === undefined && (expSign || expNumber)) {
  3440. invalidErr(representation, 'missing e before exponent');
  3441. }
  3442. }
  3443. // Get the negative or positive sign
  3444. if (representation[index] === '+' || representation[index] === '-') {
  3445. isNegative = representation[index++] === '-';
  3446. }
  3447. // Check if user passed Infinity or NaN
  3448. if (!isDigit(representation[index]) && representation[index] !== '.') {
  3449. if (representation[index] === 'i' || representation[index] === 'I') {
  3450. return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  3451. }
  3452. else if (representation[index] === 'N') {
  3453. return new Decimal128(buffer_1.from(NAN_BUFFER));
  3454. }
  3455. }
  3456. // Read all the digits
  3457. while (isDigit(representation[index]) || representation[index] === '.') {
  3458. if (representation[index] === '.') {
  3459. if (sawRadix)
  3460. invalidErr(representation, 'contains multiple periods');
  3461. sawRadix = true;
  3462. index = index + 1;
  3463. continue;
  3464. }
  3465. if (nDigitsStored < 34) {
  3466. if (representation[index] !== '0' || foundNonZero) {
  3467. if (!foundNonZero) {
  3468. firstNonZero = nDigitsRead;
  3469. }
  3470. foundNonZero = true;
  3471. // Only store 34 digits
  3472. digits[digitsInsert++] = parseInt(representation[index], 10);
  3473. nDigitsStored = nDigitsStored + 1;
  3474. }
  3475. }
  3476. if (foundNonZero)
  3477. nDigits = nDigits + 1;
  3478. if (sawRadix)
  3479. radixPosition = radixPosition + 1;
  3480. nDigitsRead = nDigitsRead + 1;
  3481. index = index + 1;
  3482. }
  3483. if (sawRadix && !nDigitsRead)
  3484. throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
  3485. // Read exponent if exists
  3486. if (representation[index] === 'e' || representation[index] === 'E') {
  3487. // Read exponent digits
  3488. var match = representation.substr(++index).match(EXPONENT_REGEX);
  3489. // No digits read
  3490. if (!match || !match[2])
  3491. return new Decimal128(buffer_1.from(NAN_BUFFER));
  3492. // Get exponent
  3493. exponent = parseInt(match[0], 10);
  3494. // Adjust the index
  3495. index = index + match[0].length;
  3496. }
  3497. // Return not a number
  3498. if (representation[index])
  3499. return new Decimal128(buffer_1.from(NAN_BUFFER));
  3500. // Done reading input
  3501. // Find first non-zero digit in digits
  3502. firstDigit = 0;
  3503. if (!nDigitsStored) {
  3504. firstDigit = 0;
  3505. lastDigit = 0;
  3506. digits[0] = 0;
  3507. nDigits = 1;
  3508. nDigitsStored = 1;
  3509. significantDigits = 0;
  3510. }
  3511. else {
  3512. lastDigit = nDigitsStored - 1;
  3513. significantDigits = nDigits;
  3514. if (significantDigits !== 1) {
  3515. while (digits[firstNonZero + significantDigits - 1] === 0) {
  3516. significantDigits = significantDigits - 1;
  3517. }
  3518. }
  3519. }
  3520. // Normalization of exponent
  3521. // Correct exponent based on radix position, and shift significand as needed
  3522. // to represent user input
  3523. // Overflow prevention
  3524. if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
  3525. exponent = EXPONENT_MIN;
  3526. }
  3527. else {
  3528. exponent = exponent - radixPosition;
  3529. }
  3530. // Attempt to normalize the exponent
  3531. while (exponent > EXPONENT_MAX) {
  3532. // Shift exponent to significand and decrease
  3533. lastDigit = lastDigit + 1;
  3534. if (lastDigit - firstDigit > MAX_DIGITS) {
  3535. // Check if we have a zero then just hard clamp, otherwise fail
  3536. var digitsString = digits.join('');
  3537. if (digitsString.match(/^0+$/)) {
  3538. exponent = EXPONENT_MAX;
  3539. break;
  3540. }
  3541. invalidErr(representation, 'overflow');
  3542. }
  3543. exponent = exponent - 1;
  3544. }
  3545. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  3546. // Shift last digit. can only do this if < significant digits than # stored.
  3547. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  3548. exponent = EXPONENT_MIN;
  3549. significantDigits = 0;
  3550. break;
  3551. }
  3552. if (nDigitsStored < nDigits) {
  3553. // adjust to match digits not stored
  3554. nDigits = nDigits - 1;
  3555. }
  3556. else {
  3557. // adjust to round
  3558. lastDigit = lastDigit - 1;
  3559. }
  3560. if (exponent < EXPONENT_MAX) {
  3561. exponent = exponent + 1;
  3562. }
  3563. else {
  3564. // Check if we have a zero then just hard clamp, otherwise fail
  3565. var digitsString = digits.join('');
  3566. if (digitsString.match(/^0+$/)) {
  3567. exponent = EXPONENT_MAX;
  3568. break;
  3569. }
  3570. invalidErr(representation, 'overflow');
  3571. }
  3572. }
  3573. // Round
  3574. // We've normalized the exponent, but might still need to round.
  3575. if (lastDigit - firstDigit + 1 < significantDigits) {
  3576. var endOfString = nDigitsRead;
  3577. // If we have seen a radix point, 'string' is 1 longer than we have
  3578. // documented with ndigits_read, so inc the position of the first nonzero
  3579. // digit and the position that digits are read to.
  3580. if (sawRadix) {
  3581. firstNonZero = firstNonZero + 1;
  3582. endOfString = endOfString + 1;
  3583. }
  3584. // if negative, we need to increment again to account for - sign at start.
  3585. if (isNegative) {
  3586. firstNonZero = firstNonZero + 1;
  3587. endOfString = endOfString + 1;
  3588. }
  3589. var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  3590. var roundBit = 0;
  3591. if (roundDigit >= 5) {
  3592. roundBit = 1;
  3593. if (roundDigit === 5) {
  3594. roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
  3595. for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  3596. if (parseInt(representation[i], 10)) {
  3597. roundBit = 1;
  3598. break;
  3599. }
  3600. }
  3601. }
  3602. }
  3603. if (roundBit) {
  3604. var dIdx = lastDigit;
  3605. for (; dIdx >= 0; dIdx--) {
  3606. if (++digits[dIdx] > 9) {
  3607. digits[dIdx] = 0;
  3608. // overflowed most significant digit
  3609. if (dIdx === 0) {
  3610. if (exponent < EXPONENT_MAX) {
  3611. exponent = exponent + 1;
  3612. digits[dIdx] = 1;
  3613. }
  3614. else {
  3615. return new Decimal128(buffer_1.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  3616. }
  3617. }
  3618. }
  3619. }
  3620. }
  3621. }
  3622. // Encode significand
  3623. // The high 17 digits of the significand
  3624. significandHigh = Long.fromNumber(0);
  3625. // The low 17 digits of the significand
  3626. significandLow = Long.fromNumber(0);
  3627. // read a zero
  3628. if (significantDigits === 0) {
  3629. significandHigh = Long.fromNumber(0);
  3630. significandLow = Long.fromNumber(0);
  3631. }
  3632. else if (lastDigit - firstDigit < 17) {
  3633. var dIdx = firstDigit;
  3634. significandLow = Long.fromNumber(digits[dIdx++]);
  3635. significandHigh = new Long(0, 0);
  3636. for (; dIdx <= lastDigit; dIdx++) {
  3637. significandLow = significandLow.multiply(Long.fromNumber(10));
  3638. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  3639. }
  3640. }
  3641. else {
  3642. var dIdx = firstDigit;
  3643. significandHigh = Long.fromNumber(digits[dIdx++]);
  3644. for (; dIdx <= lastDigit - 17; dIdx++) {
  3645. significandHigh = significandHigh.multiply(Long.fromNumber(10));
  3646. significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
  3647. }
  3648. significandLow = Long.fromNumber(digits[dIdx++]);
  3649. for (; dIdx <= lastDigit; dIdx++) {
  3650. significandLow = significandLow.multiply(Long.fromNumber(10));
  3651. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  3652. }
  3653. }
  3654. var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
  3655. significand.low = significand.low.add(significandLow);
  3656. if (lessThan(significand.low, significandLow)) {
  3657. significand.high = significand.high.add(Long.fromNumber(1));
  3658. }
  3659. // Biased exponent
  3660. biasedExponent = exponent + EXPONENT_BIAS;
  3661. var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
  3662. // Encode combination, exponent, and significand.
  3663. if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
  3664. // Encode '11' into bits 1 to 3
  3665. dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
  3666. dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
  3667. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
  3668. }
  3669. else {
  3670. dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  3671. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
  3672. }
  3673. dec.low = significand.low;
  3674. // Encode sign
  3675. if (isNegative) {
  3676. dec.high = dec.high.or(Long.fromString('9223372036854775808'));
  3677. }
  3678. // Encode into a buffer
  3679. var buffer = buffer_1.alloc(16);
  3680. index = 0;
  3681. // Encode the low 64 bits of the decimal
  3682. // Encode low bits
  3683. buffer[index++] = dec.low.low & 0xff;
  3684. buffer[index++] = (dec.low.low >> 8) & 0xff;
  3685. buffer[index++] = (dec.low.low >> 16) & 0xff;
  3686. buffer[index++] = (dec.low.low >> 24) & 0xff;
  3687. // Encode high bits
  3688. buffer[index++] = dec.low.high & 0xff;
  3689. buffer[index++] = (dec.low.high >> 8) & 0xff;
  3690. buffer[index++] = (dec.low.high >> 16) & 0xff;
  3691. buffer[index++] = (dec.low.high >> 24) & 0xff;
  3692. // Encode the high 64 bits of the decimal
  3693. // Encode low bits
  3694. buffer[index++] = dec.high.low & 0xff;
  3695. buffer[index++] = (dec.high.low >> 8) & 0xff;
  3696. buffer[index++] = (dec.high.low >> 16) & 0xff;
  3697. buffer[index++] = (dec.high.low >> 24) & 0xff;
  3698. // Encode high bits
  3699. buffer[index++] = dec.high.high & 0xff;
  3700. buffer[index++] = (dec.high.high >> 8) & 0xff;
  3701. buffer[index++] = (dec.high.high >> 16) & 0xff;
  3702. buffer[index++] = (dec.high.high >> 24) & 0xff;
  3703. // Return the new Decimal128
  3704. return new Decimal128(buffer);
  3705. };
  3706. /** Create a string representation of the raw Decimal128 value */
  3707. Decimal128.prototype.toString = function () {
  3708. // Note: bits in this routine are referred to starting at 0,
  3709. // from the sign bit, towards the coefficient.
  3710. // decoded biased exponent (14 bits)
  3711. var biased_exponent;
  3712. // the number of significand digits
  3713. var significand_digits = 0;
  3714. // the base-10 digits in the significand
  3715. var significand = new Array(36);
  3716. for (var i = 0; i < significand.length; i++)
  3717. significand[i] = 0;
  3718. // read pointer into significand
  3719. var index = 0;
  3720. // true if the number is zero
  3721. var is_zero = false;
  3722. // the most significant significand bits (50-46)
  3723. var significand_msb;
  3724. // temporary storage for significand decoding
  3725. var significand128 = { parts: [0, 0, 0, 0] };
  3726. // indexing variables
  3727. var j, k;
  3728. // Output string
  3729. var string = [];
  3730. // Unpack index
  3731. index = 0;
  3732. // Buffer reference
  3733. var buffer = this.bytes;
  3734. // Unpack the low 64bits into a long
  3735. // bits 96 - 127
  3736. var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  3737. // bits 64 - 95
  3738. var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  3739. // Unpack the high 64bits into a long
  3740. // bits 32 - 63
  3741. var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  3742. // bits 0 - 31
  3743. var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  3744. // Unpack index
  3745. index = 0;
  3746. // Create the state of the decimal
  3747. var dec = {
  3748. low: new Long(low, midl),
  3749. high: new Long(midh, high)
  3750. };
  3751. if (dec.high.lessThan(Long.ZERO)) {
  3752. string.push('-');
  3753. }
  3754. // Decode combination field and exponent
  3755. // bits 1 - 5
  3756. var combination = (high >> 26) & COMBINATION_MASK;
  3757. if (combination >> 3 === 3) {
  3758. // Check for 'special' values
  3759. if (combination === COMBINATION_INFINITY) {
  3760. return string.join('') + 'Infinity';
  3761. }
  3762. else if (combination === COMBINATION_NAN) {
  3763. return 'NaN';
  3764. }
  3765. else {
  3766. biased_exponent = (high >> 15) & EXPONENT_MASK;
  3767. significand_msb = 0x08 + ((high >> 14) & 0x01);
  3768. }
  3769. }
  3770. else {
  3771. significand_msb = (high >> 14) & 0x07;
  3772. biased_exponent = (high >> 17) & EXPONENT_MASK;
  3773. }
  3774. // unbiased exponent
  3775. var exponent = biased_exponent - EXPONENT_BIAS;
  3776. // Create string of significand digits
  3777. // Convert the 114-bit binary number represented by
  3778. // (significand_high, significand_low) to at most 34 decimal
  3779. // digits through modulo and division.
  3780. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  3781. significand128.parts[1] = midh;
  3782. significand128.parts[2] = midl;
  3783. significand128.parts[3] = low;
  3784. if (significand128.parts[0] === 0 &&
  3785. significand128.parts[1] === 0 &&
  3786. significand128.parts[2] === 0 &&
  3787. significand128.parts[3] === 0) {
  3788. is_zero = true;
  3789. }
  3790. else {
  3791. for (k = 3; k >= 0; k--) {
  3792. var least_digits = 0;
  3793. // Perform the divide
  3794. var result = divideu128(significand128);
  3795. significand128 = result.quotient;
  3796. least_digits = result.rem.low;
  3797. // We now have the 9 least significant digits (in base 2).
  3798. // Convert and output to string.
  3799. if (!least_digits)
  3800. continue;
  3801. for (j = 8; j >= 0; j--) {
  3802. // significand[k * 9 + j] = Math.round(least_digits % 10);
  3803. significand[k * 9 + j] = least_digits % 10;
  3804. // least_digits = Math.round(least_digits / 10);
  3805. least_digits = Math.floor(least_digits / 10);
  3806. }
  3807. }
  3808. }
  3809. // Output format options:
  3810. // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
  3811. // Regular - ddd.ddd
  3812. if (is_zero) {
  3813. significand_digits = 1;
  3814. significand[index] = 0;
  3815. }
  3816. else {
  3817. significand_digits = 36;
  3818. while (!significand[index]) {
  3819. significand_digits = significand_digits - 1;
  3820. index = index + 1;
  3821. }
  3822. }
  3823. // the exponent if scientific notation is used
  3824. var scientific_exponent = significand_digits - 1 + exponent;
  3825. // The scientific exponent checks are dictated by the string conversion
  3826. // specification and are somewhat arbitrary cutoffs.
  3827. //
  3828. // We must check exponent > 0, because if this is the case, the number
  3829. // has trailing zeros. However, we *cannot* output these trailing zeros,
  3830. // because doing so would change the precision of the value, and would
  3831. // change stored data if the string converted number is round tripped.
  3832. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  3833. // Scientific format
  3834. // if there are too many significant digits, we should just be treating numbers
  3835. // as + or - 0 and using the non-scientific exponent (this is for the "invalid
  3836. // representation should be treated as 0/-0" spec cases in decimal128-1.json)
  3837. if (significand_digits > 34) {
  3838. string.push("" + 0);
  3839. if (exponent > 0)
  3840. string.push('E+' + exponent);
  3841. else if (exponent < 0)
  3842. string.push('E' + exponent);
  3843. return string.join('');
  3844. }
  3845. string.push("" + significand[index++]);
  3846. significand_digits = significand_digits - 1;
  3847. if (significand_digits) {
  3848. string.push('.');
  3849. }
  3850. for (var i = 0; i < significand_digits; i++) {
  3851. string.push("" + significand[index++]);
  3852. }
  3853. // Exponent
  3854. string.push('E');
  3855. if (scientific_exponent > 0) {
  3856. string.push('+' + scientific_exponent);
  3857. }
  3858. else {
  3859. string.push("" + scientific_exponent);
  3860. }
  3861. }
  3862. else {
  3863. // Regular format with no decimal place
  3864. if (exponent >= 0) {
  3865. for (var i = 0; i < significand_digits; i++) {
  3866. string.push("" + significand[index++]);
  3867. }
  3868. }
  3869. else {
  3870. var radix_position = significand_digits + exponent;
  3871. // non-zero digits before radix
  3872. if (radix_position > 0) {
  3873. for (var i = 0; i < radix_position; i++) {
  3874. string.push("" + significand[index++]);
  3875. }
  3876. }
  3877. else {
  3878. string.push('0');
  3879. }
  3880. string.push('.');
  3881. // add leading zeros after radix
  3882. while (radix_position++ < 0) {
  3883. string.push('0');
  3884. }
  3885. for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  3886. string.push("" + significand[index++]);
  3887. }
  3888. }
  3889. }
  3890. return string.join('');
  3891. };
  3892. Decimal128.prototype.toJSON = function () {
  3893. return { $numberDecimal: this.toString() };
  3894. };
  3895. /** @internal */
  3896. Decimal128.prototype.toExtendedJSON = function () {
  3897. return { $numberDecimal: this.toString() };
  3898. };
  3899. /** @internal */
  3900. Decimal128.fromExtendedJSON = function (doc) {
  3901. return Decimal128.fromString(doc.$numberDecimal);
  3902. };
  3903. /** @internal */
  3904. Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  3905. return this.inspect();
  3906. };
  3907. Decimal128.prototype.inspect = function () {
  3908. return "new Decimal128(\"" + this.toString() + "\")";
  3909. };
  3910. return Decimal128;
  3911. }());
  3912. Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' });
  3913. /**
  3914. * A class representation of the BSON Double type.
  3915. * @public
  3916. */
  3917. var Double = /** @class */ (function () {
  3918. /**
  3919. * Create a Double type
  3920. *
  3921. * @param value - the number we want to represent as a double.
  3922. */
  3923. function Double(value) {
  3924. if (!(this instanceof Double))
  3925. return new Double(value);
  3926. if (value instanceof Number) {
  3927. value = value.valueOf();
  3928. }
  3929. this.value = +value;
  3930. }
  3931. /**
  3932. * Access the number value.
  3933. *
  3934. * @returns returns the wrapped double number.
  3935. */
  3936. Double.prototype.valueOf = function () {
  3937. return this.value;
  3938. };
  3939. Double.prototype.toJSON = function () {
  3940. return this.value;
  3941. };
  3942. Double.prototype.toString = function (radix) {
  3943. return this.value.toString(radix);
  3944. };
  3945. /** @internal */
  3946. Double.prototype.toExtendedJSON = function (options) {
  3947. if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
  3948. return this.value;
  3949. }
  3950. // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
  3951. // explicitly provided `-0` then we need to ensure the sign makes it into the output
  3952. if (Object.is(Math.sign(this.value), -0)) {
  3953. return { $numberDouble: "-" + this.value.toFixed(1) };
  3954. }
  3955. var $numberDouble;
  3956. if (Number.isInteger(this.value)) {
  3957. $numberDouble = this.value.toFixed(1);
  3958. if ($numberDouble.length >= 13) {
  3959. $numberDouble = this.value.toExponential(13).toUpperCase();
  3960. }
  3961. }
  3962. else {
  3963. $numberDouble = this.value.toString();
  3964. }
  3965. return { $numberDouble: $numberDouble };
  3966. };
  3967. /** @internal */
  3968. Double.fromExtendedJSON = function (doc, options) {
  3969. var doubleValue = parseFloat(doc.$numberDouble);
  3970. return options && options.relaxed ? doubleValue : new Double(doubleValue);
  3971. };
  3972. /** @internal */
  3973. Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  3974. return this.inspect();
  3975. };
  3976. Double.prototype.inspect = function () {
  3977. var eJSON = this.toExtendedJSON();
  3978. return "new Double(" + eJSON.$numberDouble + ")";
  3979. };
  3980. return Double;
  3981. }());
  3982. Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' });
  3983. /**
  3984. * A class representation of a BSON Int32 type.
  3985. * @public
  3986. */
  3987. var Int32 = /** @class */ (function () {
  3988. /**
  3989. * Create an Int32 type
  3990. *
  3991. * @param value - the number we want to represent as an int32.
  3992. */
  3993. function Int32(value) {
  3994. if (!(this instanceof Int32))
  3995. return new Int32(value);
  3996. if (value instanceof Number) {
  3997. value = value.valueOf();
  3998. }
  3999. this.value = +value | 0;
  4000. }
  4001. /**
  4002. * Access the number value.
  4003. *
  4004. * @returns returns the wrapped int32 number.
  4005. */
  4006. Int32.prototype.valueOf = function () {
  4007. return this.value;
  4008. };
  4009. Int32.prototype.toString = function (radix) {
  4010. return this.value.toString(radix);
  4011. };
  4012. Int32.prototype.toJSON = function () {
  4013. return this.value;
  4014. };
  4015. /** @internal */
  4016. Int32.prototype.toExtendedJSON = function (options) {
  4017. if (options && (options.relaxed || options.legacy))
  4018. return this.value;
  4019. return { $numberInt: this.value.toString() };
  4020. };
  4021. /** @internal */
  4022. Int32.fromExtendedJSON = function (doc, options) {
  4023. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  4024. };
  4025. /** @internal */
  4026. Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4027. return this.inspect();
  4028. };
  4029. Int32.prototype.inspect = function () {
  4030. return "new Int32(" + this.valueOf() + ")";
  4031. };
  4032. return Int32;
  4033. }());
  4034. Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' });
  4035. /**
  4036. * A class representation of the BSON MaxKey type.
  4037. * @public
  4038. */
  4039. var MaxKey = /** @class */ (function () {
  4040. function MaxKey() {
  4041. if (!(this instanceof MaxKey))
  4042. return new MaxKey();
  4043. }
  4044. /** @internal */
  4045. MaxKey.prototype.toExtendedJSON = function () {
  4046. return { $maxKey: 1 };
  4047. };
  4048. /** @internal */
  4049. MaxKey.fromExtendedJSON = function () {
  4050. return new MaxKey();
  4051. };
  4052. /** @internal */
  4053. MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4054. return this.inspect();
  4055. };
  4056. MaxKey.prototype.inspect = function () {
  4057. return 'new MaxKey()';
  4058. };
  4059. return MaxKey;
  4060. }());
  4061. Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' });
  4062. /**
  4063. * A class representation of the BSON MinKey type.
  4064. * @public
  4065. */
  4066. var MinKey = /** @class */ (function () {
  4067. function MinKey() {
  4068. if (!(this instanceof MinKey))
  4069. return new MinKey();
  4070. }
  4071. /** @internal */
  4072. MinKey.prototype.toExtendedJSON = function () {
  4073. return { $minKey: 1 };
  4074. };
  4075. /** @internal */
  4076. MinKey.fromExtendedJSON = function () {
  4077. return new MinKey();
  4078. };
  4079. /** @internal */
  4080. MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4081. return this.inspect();
  4082. };
  4083. MinKey.prototype.inspect = function () {
  4084. return 'new MinKey()';
  4085. };
  4086. return MinKey;
  4087. }());
  4088. Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' });
  4089. // Regular expression that checks for hex value
  4090. var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
  4091. // Unique sequence for the current process (initialized on first use)
  4092. var PROCESS_UNIQUE = null;
  4093. var kId = Symbol('id');
  4094. /**
  4095. * A class representation of the BSON ObjectId type.
  4096. * @public
  4097. */
  4098. var ObjectId = /** @class */ (function () {
  4099. /**
  4100. * Create an ObjectId type
  4101. *
  4102. * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
  4103. */
  4104. function ObjectId(inputId) {
  4105. if (!(this instanceof ObjectId))
  4106. return new ObjectId(inputId);
  4107. // workingId is set based on type of input and whether valid id exists for the input
  4108. var workingId;
  4109. if (typeof inputId === 'object' && inputId && 'id' in inputId) {
  4110. if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
  4111. throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer');
  4112. }
  4113. if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
  4114. workingId = buffer_1.from(inputId.toHexString(), 'hex');
  4115. }
  4116. else {
  4117. workingId = inputId.id;
  4118. }
  4119. }
  4120. else {
  4121. workingId = inputId;
  4122. }
  4123. // the following cases use workingId to construct an ObjectId
  4124. if (workingId == null || typeof workingId === 'number') {
  4125. // The most common use case (blank id, new objectId instance)
  4126. // Generate a new id
  4127. this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
  4128. }
  4129. else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
  4130. this[kId] = ensureBuffer(workingId);
  4131. }
  4132. else if (typeof workingId === 'string') {
  4133. if (workingId.length === 12) {
  4134. var bytes = buffer_1.from(workingId);
  4135. if (bytes.byteLength === 12) {
  4136. this[kId] = bytes;
  4137. }
  4138. else {
  4139. throw new BSONTypeError('Argument passed in must be a string of 12 bytes');
  4140. }
  4141. }
  4142. else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
  4143. this[kId] = buffer_1.from(workingId, 'hex');
  4144. }
  4145. else {
  4146. throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters');
  4147. }
  4148. }
  4149. else {
  4150. throw new BSONTypeError('Argument passed in does not match the accepted types');
  4151. }
  4152. // If we are caching the hex string
  4153. if (ObjectId.cacheHexString) {
  4154. this.__id = this.id.toString('hex');
  4155. }
  4156. }
  4157. Object.defineProperty(ObjectId.prototype, "id", {
  4158. /**
  4159. * The ObjectId bytes
  4160. * @readonly
  4161. */
  4162. get: function () {
  4163. return this[kId];
  4164. },
  4165. set: function (value) {
  4166. this[kId] = value;
  4167. if (ObjectId.cacheHexString) {
  4168. this.__id = value.toString('hex');
  4169. }
  4170. },
  4171. enumerable: false,
  4172. configurable: true
  4173. });
  4174. Object.defineProperty(ObjectId.prototype, "generationTime", {
  4175. /**
  4176. * The generation time of this ObjectId instance
  4177. * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch
  4178. */
  4179. get: function () {
  4180. return this.id.readInt32BE(0);
  4181. },
  4182. set: function (value) {
  4183. // Encode time into first 4 bytes
  4184. this.id.writeUInt32BE(value, 0);
  4185. },
  4186. enumerable: false,
  4187. configurable: true
  4188. });
  4189. /** Returns the ObjectId id as a 24 character hex string representation */
  4190. ObjectId.prototype.toHexString = function () {
  4191. if (ObjectId.cacheHexString && this.__id) {
  4192. return this.__id;
  4193. }
  4194. var hexString = this.id.toString('hex');
  4195. if (ObjectId.cacheHexString && !this.__id) {
  4196. this.__id = hexString;
  4197. }
  4198. return hexString;
  4199. };
  4200. /**
  4201. * Update the ObjectId index
  4202. * @privateRemarks
  4203. * Used in generating new ObjectId's on the driver
  4204. * @internal
  4205. */
  4206. ObjectId.getInc = function () {
  4207. return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
  4208. };
  4209. /**
  4210. * Generate a 12 byte id buffer used in ObjectId's
  4211. *
  4212. * @param time - pass in a second based timestamp.
  4213. */
  4214. ObjectId.generate = function (time) {
  4215. if ('number' !== typeof time) {
  4216. time = Math.floor(Date.now() / 1000);
  4217. }
  4218. var inc = ObjectId.getInc();
  4219. var buffer = buffer_1.alloc(12);
  4220. // 4-byte timestamp
  4221. buffer.writeUInt32BE(time, 0);
  4222. // set PROCESS_UNIQUE if yet not initialized
  4223. if (PROCESS_UNIQUE === null) {
  4224. PROCESS_UNIQUE = randomBytes(5);
  4225. }
  4226. // 5-byte process unique
  4227. buffer[4] = PROCESS_UNIQUE[0];
  4228. buffer[5] = PROCESS_UNIQUE[1];
  4229. buffer[6] = PROCESS_UNIQUE[2];
  4230. buffer[7] = PROCESS_UNIQUE[3];
  4231. buffer[8] = PROCESS_UNIQUE[4];
  4232. // 3-byte counter
  4233. buffer[11] = inc & 0xff;
  4234. buffer[10] = (inc >> 8) & 0xff;
  4235. buffer[9] = (inc >> 16) & 0xff;
  4236. return buffer;
  4237. };
  4238. /**
  4239. * Converts the id into a 24 character hex string for printing
  4240. *
  4241. * @param format - The Buffer toString format parameter.
  4242. */
  4243. ObjectId.prototype.toString = function (format) {
  4244. // Is the id a buffer then use the buffer toString method to return the format
  4245. if (format)
  4246. return this.id.toString(format);
  4247. return this.toHexString();
  4248. };
  4249. /** Converts to its JSON the 24 character hex string representation. */
  4250. ObjectId.prototype.toJSON = function () {
  4251. return this.toHexString();
  4252. };
  4253. /**
  4254. * Compares the equality of this ObjectId with `otherID`.
  4255. *
  4256. * @param otherId - ObjectId instance to compare against.
  4257. */
  4258. ObjectId.prototype.equals = function (otherId) {
  4259. if (otherId === undefined || otherId === null) {
  4260. return false;
  4261. }
  4262. if (otherId instanceof ObjectId) {
  4263. return this.toString() === otherId.toString();
  4264. }
  4265. if (typeof otherId === 'string' &&
  4266. ObjectId.isValid(otherId) &&
  4267. otherId.length === 12 &&
  4268. isUint8Array(this.id)) {
  4269. return otherId === buffer_1.prototype.toString.call(this.id, 'latin1');
  4270. }
  4271. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
  4272. return otherId.toLowerCase() === this.toHexString();
  4273. }
  4274. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
  4275. return buffer_1.from(otherId).equals(this.id);
  4276. }
  4277. if (typeof otherId === 'object' &&
  4278. 'toHexString' in otherId &&
  4279. typeof otherId.toHexString === 'function') {
  4280. return otherId.toHexString() === this.toHexString();
  4281. }
  4282. return false;
  4283. };
  4284. /** Returns the generation date (accurate up to the second) that this ID was generated. */
  4285. ObjectId.prototype.getTimestamp = function () {
  4286. var timestamp = new Date();
  4287. var time = this.id.readUInt32BE(0);
  4288. timestamp.setTime(Math.floor(time) * 1000);
  4289. return timestamp;
  4290. };
  4291. /** @internal */
  4292. ObjectId.createPk = function () {
  4293. return new ObjectId();
  4294. };
  4295. /**
  4296. * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
  4297. *
  4298. * @param time - an integer number representing a number of seconds.
  4299. */
  4300. ObjectId.createFromTime = function (time) {
  4301. var buffer = buffer_1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  4302. // Encode time into first 4 bytes
  4303. buffer.writeUInt32BE(time, 0);
  4304. // Return the new objectId
  4305. return new ObjectId(buffer);
  4306. };
  4307. /**
  4308. * Creates an ObjectId from a hex string representation of an ObjectId.
  4309. *
  4310. * @param hexString - create a ObjectId from a passed in 24 character hexstring.
  4311. */
  4312. ObjectId.createFromHexString = function (hexString) {
  4313. // Throw an error if it's not a valid setup
  4314. if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
  4315. throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  4316. }
  4317. return new ObjectId(buffer_1.from(hexString, 'hex'));
  4318. };
  4319. /**
  4320. * Checks if a value is a valid bson ObjectId
  4321. *
  4322. * @param id - ObjectId instance to validate.
  4323. */
  4324. ObjectId.isValid = function (id) {
  4325. if (id == null)
  4326. return false;
  4327. try {
  4328. new ObjectId(id);
  4329. return true;
  4330. }
  4331. catch (_a) {
  4332. return false;
  4333. }
  4334. };
  4335. /** @internal */
  4336. ObjectId.prototype.toExtendedJSON = function () {
  4337. if (this.toHexString)
  4338. return { $oid: this.toHexString() };
  4339. return { $oid: this.toString('hex') };
  4340. };
  4341. /** @internal */
  4342. ObjectId.fromExtendedJSON = function (doc) {
  4343. return new ObjectId(doc.$oid);
  4344. };
  4345. /**
  4346. * Converts to a string representation of this Id.
  4347. *
  4348. * @returns return the 24 character hex string representation.
  4349. * @internal
  4350. */
  4351. ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4352. return this.inspect();
  4353. };
  4354. ObjectId.prototype.inspect = function () {
  4355. return "new ObjectId(\"" + this.toHexString() + "\")";
  4356. };
  4357. /** @internal */
  4358. ObjectId.index = Math.floor(Math.random() * 0xffffff);
  4359. return ObjectId;
  4360. }());
  4361. // Deprecated methods
  4362. Object.defineProperty(ObjectId.prototype, 'generate', {
  4363. value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead')
  4364. });
  4365. Object.defineProperty(ObjectId.prototype, 'getInc', {
  4366. value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  4367. });
  4368. Object.defineProperty(ObjectId.prototype, 'get_inc', {
  4369. value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  4370. });
  4371. Object.defineProperty(ObjectId, 'get_inc', {
  4372. value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  4373. });
  4374. Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' });
  4375. function alphabetize(str) {
  4376. return str.split('').sort().join('');
  4377. }
  4378. /**
  4379. * A class representation of the BSON RegExp type.
  4380. * @public
  4381. */
  4382. var BSONRegExp = /** @class */ (function () {
  4383. /**
  4384. * @param pattern - The regular expression pattern to match
  4385. * @param options - The regular expression options
  4386. */
  4387. function BSONRegExp(pattern, options) {
  4388. if (!(this instanceof BSONRegExp))
  4389. return new BSONRegExp(pattern, options);
  4390. this.pattern = pattern;
  4391. this.options = alphabetize(options !== null && options !== void 0 ? options : '');
  4392. if (this.pattern.indexOf('\x00') !== -1) {
  4393. throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern));
  4394. }
  4395. if (this.options.indexOf('\x00') !== -1) {
  4396. throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options));
  4397. }
  4398. // Validate options
  4399. for (var i = 0; i < this.options.length; i++) {
  4400. if (!(this.options[i] === 'i' ||
  4401. this.options[i] === 'm' ||
  4402. this.options[i] === 'x' ||
  4403. this.options[i] === 'l' ||
  4404. this.options[i] === 's' ||
  4405. this.options[i] === 'u')) {
  4406. throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported");
  4407. }
  4408. }
  4409. }
  4410. BSONRegExp.parseOptions = function (options) {
  4411. return options ? options.split('').sort().join('') : '';
  4412. };
  4413. /** @internal */
  4414. BSONRegExp.prototype.toExtendedJSON = function (options) {
  4415. options = options || {};
  4416. if (options.legacy) {
  4417. return { $regex: this.pattern, $options: this.options };
  4418. }
  4419. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  4420. };
  4421. /** @internal */
  4422. BSONRegExp.fromExtendedJSON = function (doc) {
  4423. if ('$regex' in doc) {
  4424. if (typeof doc.$regex !== 'string') {
  4425. // This is for $regex query operators that have extended json values.
  4426. if (doc.$regex._bsontype === 'BSONRegExp') {
  4427. return doc;
  4428. }
  4429. }
  4430. else {
  4431. return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
  4432. }
  4433. }
  4434. if ('$regularExpression' in doc) {
  4435. return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
  4436. }
  4437. throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
  4438. };
  4439. return BSONRegExp;
  4440. }());
  4441. Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' });
  4442. /**
  4443. * A class representation of the BSON Symbol type.
  4444. * @public
  4445. */
  4446. var BSONSymbol = /** @class */ (function () {
  4447. /**
  4448. * @param value - the string representing the symbol.
  4449. */
  4450. function BSONSymbol(value) {
  4451. if (!(this instanceof BSONSymbol))
  4452. return new BSONSymbol(value);
  4453. this.value = value;
  4454. }
  4455. /** Access the wrapped string value. */
  4456. BSONSymbol.prototype.valueOf = function () {
  4457. return this.value;
  4458. };
  4459. BSONSymbol.prototype.toString = function () {
  4460. return this.value;
  4461. };
  4462. /** @internal */
  4463. BSONSymbol.prototype.inspect = function () {
  4464. return "new BSONSymbol(\"" + this.value + "\")";
  4465. };
  4466. BSONSymbol.prototype.toJSON = function () {
  4467. return this.value;
  4468. };
  4469. /** @internal */
  4470. BSONSymbol.prototype.toExtendedJSON = function () {
  4471. return { $symbol: this.value };
  4472. };
  4473. /** @internal */
  4474. BSONSymbol.fromExtendedJSON = function (doc) {
  4475. return new BSONSymbol(doc.$symbol);
  4476. };
  4477. /** @internal */
  4478. BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4479. return this.inspect();
  4480. };
  4481. return BSONSymbol;
  4482. }());
  4483. Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' });
  4484. /** @public */
  4485. var LongWithoutOverridesClass = Long;
  4486. /** @public */
  4487. var Timestamp = /** @class */ (function (_super) {
  4488. __extends(Timestamp, _super);
  4489. function Timestamp(low, high) {
  4490. var _this = this;
  4491. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  4492. ///@ts-expect-error
  4493. if (!(_this instanceof Timestamp))
  4494. return new Timestamp(low, high);
  4495. if (Long.isLong(low)) {
  4496. _this = _super.call(this, low.low, low.high, true) || this;
  4497. }
  4498. else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') {
  4499. _this = _super.call(this, low.i, low.t, true) || this;
  4500. }
  4501. else {
  4502. _this = _super.call(this, low, high, true) || this;
  4503. }
  4504. Object.defineProperty(_this, '_bsontype', {
  4505. value: 'Timestamp',
  4506. writable: false,
  4507. configurable: false,
  4508. enumerable: false
  4509. });
  4510. return _this;
  4511. }
  4512. Timestamp.prototype.toJSON = function () {
  4513. return {
  4514. $timestamp: this.toString()
  4515. };
  4516. };
  4517. /** Returns a Timestamp represented by the given (32-bit) integer value. */
  4518. Timestamp.fromInt = function (value) {
  4519. return new Timestamp(Long.fromInt(value, true));
  4520. };
  4521. /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */
  4522. Timestamp.fromNumber = function (value) {
  4523. return new Timestamp(Long.fromNumber(value, true));
  4524. };
  4525. /**
  4526. * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
  4527. *
  4528. * @param lowBits - the low 32-bits.
  4529. * @param highBits - the high 32-bits.
  4530. */
  4531. Timestamp.fromBits = function (lowBits, highBits) {
  4532. return new Timestamp(lowBits, highBits);
  4533. };
  4534. /**
  4535. * Returns a Timestamp from the given string, optionally using the given radix.
  4536. *
  4537. * @param str - the textual representation of the Timestamp.
  4538. * @param optRadix - the radix in which the text is written.
  4539. */
  4540. Timestamp.fromString = function (str, optRadix) {
  4541. return new Timestamp(Long.fromString(str, true, optRadix));
  4542. };
  4543. /** @internal */
  4544. Timestamp.prototype.toExtendedJSON = function () {
  4545. return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } };
  4546. };
  4547. /** @internal */
  4548. Timestamp.fromExtendedJSON = function (doc) {
  4549. return new Timestamp(doc.$timestamp);
  4550. };
  4551. /** @internal */
  4552. Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  4553. return this.inspect();
  4554. };
  4555. Timestamp.prototype.inspect = function () {
  4556. return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })";
  4557. };
  4558. Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
  4559. return Timestamp;
  4560. }(LongWithoutOverridesClass));
  4561. function isBSONType(value) {
  4562. return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string');
  4563. }
  4564. // INT32 boundaries
  4565. var BSON_INT32_MAX$1 = 0x7fffffff;
  4566. var BSON_INT32_MIN$1 = -0x80000000;
  4567. // INT64 boundaries
  4568. var BSON_INT64_MAX$1 = 0x7fffffffffffffff;
  4569. var BSON_INT64_MIN$1 = -0x8000000000000000;
  4570. // all the types where we don't need to do any special processing and can just pass the EJSON
  4571. //straight to type.fromExtendedJSON
  4572. var keysToCodecs = {
  4573. $oid: ObjectId,
  4574. $binary: Binary,
  4575. $uuid: Binary,
  4576. $symbol: BSONSymbol,
  4577. $numberInt: Int32,
  4578. $numberDecimal: Decimal128,
  4579. $numberDouble: Double,
  4580. $numberLong: Long,
  4581. $minKey: MinKey,
  4582. $maxKey: MaxKey,
  4583. $regex: BSONRegExp,
  4584. $regularExpression: BSONRegExp,
  4585. $timestamp: Timestamp
  4586. };
  4587. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4588. function deserializeValue(value, options) {
  4589. if (options === void 0) { options = {}; }
  4590. if (typeof value === 'number') {
  4591. if (options.relaxed || options.legacy) {
  4592. return value;
  4593. }
  4594. // if it's an integer, should interpret as smallest BSON integer
  4595. // that can represent it exactly. (if out of range, interpret as double.)
  4596. if (Math.floor(value) === value) {
  4597. if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1)
  4598. return new Int32(value);
  4599. if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1)
  4600. return Long.fromNumber(value);
  4601. }
  4602. // If the number is a non-integer or out of integer range, should interpret as BSON Double.
  4603. return new Double(value);
  4604. }
  4605. // from here on out we're looking for bson types, so bail if its not an object
  4606. if (value == null || typeof value !== 'object')
  4607. return value;
  4608. // upgrade deprecated undefined to null
  4609. if (value.$undefined)
  4610. return null;
  4611. var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; });
  4612. for (var i = 0; i < keys.length; i++) {
  4613. var c = keysToCodecs[keys[i]];
  4614. if (c)
  4615. return c.fromExtendedJSON(value, options);
  4616. }
  4617. if (value.$date != null) {
  4618. var d = value.$date;
  4619. var date = new Date();
  4620. if (options.legacy) {
  4621. if (typeof d === 'number')
  4622. date.setTime(d);
  4623. else if (typeof d === 'string')
  4624. date.setTime(Date.parse(d));
  4625. }
  4626. else {
  4627. if (typeof d === 'string')
  4628. date.setTime(Date.parse(d));
  4629. else if (Long.isLong(d))
  4630. date.setTime(d.toNumber());
  4631. else if (typeof d === 'number' && options.relaxed)
  4632. date.setTime(d);
  4633. }
  4634. return date;
  4635. }
  4636. if (value.$code != null) {
  4637. var copy = Object.assign({}, value);
  4638. if (value.$scope) {
  4639. copy.$scope = deserializeValue(value.$scope);
  4640. }
  4641. return Code.fromExtendedJSON(value);
  4642. }
  4643. if (isDBRefLike(value) || value.$dbPointer) {
  4644. var v = value.$ref ? value : value.$dbPointer;
  4645. // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
  4646. // because of the order JSON.parse goes through the document
  4647. if (v instanceof DBRef)
  4648. return v;
  4649. var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); });
  4650. var valid_1 = true;
  4651. dollarKeys.forEach(function (k) {
  4652. if (['$ref', '$id', '$db'].indexOf(k) === -1)
  4653. valid_1 = false;
  4654. });
  4655. // only make DBRef if $ keys are all valid
  4656. if (valid_1)
  4657. return DBRef.fromExtendedJSON(v);
  4658. }
  4659. return value;
  4660. }
  4661. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4662. function serializeArray(array, options) {
  4663. return array.map(function (v, index) {
  4664. options.seenObjects.push({ propertyName: "index " + index, obj: null });
  4665. try {
  4666. return serializeValue(v, options);
  4667. }
  4668. finally {
  4669. options.seenObjects.pop();
  4670. }
  4671. });
  4672. }
  4673. function getISOString(date) {
  4674. var isoStr = date.toISOString();
  4675. // we should only show milliseconds in timestamp if they're non-zero
  4676. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  4677. }
  4678. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4679. function serializeValue(value, options) {
  4680. if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
  4681. var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; });
  4682. if (index !== -1) {
  4683. var props = options.seenObjects.map(function (entry) { return entry.propertyName; });
  4684. var leadingPart = props
  4685. .slice(0, index)
  4686. .map(function (prop) { return prop + " -> "; })
  4687. .join('');
  4688. var alreadySeen = props[index];
  4689. var circularPart = ' -> ' +
  4690. props
  4691. .slice(index + 1, props.length - 1)
  4692. .map(function (prop) { return prop + " -> "; })
  4693. .join('');
  4694. var current = props[props.length - 1];
  4695. var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
  4696. var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
  4697. throw new BSONTypeError('Converting circular structure to EJSON:\n' +
  4698. (" " + leadingPart + alreadySeen + circularPart + current + "\n") +
  4699. (" " + leadingSpace + "\\" + dashes + "/"));
  4700. }
  4701. options.seenObjects[options.seenObjects.length - 1].obj = value;
  4702. }
  4703. if (Array.isArray(value))
  4704. return serializeArray(value, options);
  4705. if (value === undefined)
  4706. return null;
  4707. if (value instanceof Date || isDate(value)) {
  4708. var dateNum = value.getTime(),
  4709. // is it in year range 1970-9999?
  4710. inRange = dateNum > -1 && dateNum < 253402318800000;
  4711. if (options.legacy) {
  4712. return options.relaxed && inRange
  4713. ? { $date: value.getTime() }
  4714. : { $date: getISOString(value) };
  4715. }
  4716. return options.relaxed && inRange
  4717. ? { $date: getISOString(value) }
  4718. : { $date: { $numberLong: value.getTime().toString() } };
  4719. }
  4720. if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
  4721. // it's an integer
  4722. if (Math.floor(value) === value) {
  4723. var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1;
  4724. // interpret as being of the smallest BSON integer type that can represent the number exactly
  4725. if (int32Range)
  4726. return { $numberInt: value.toString() };
  4727. if (int64Range)
  4728. return { $numberLong: value.toString() };
  4729. }
  4730. return { $numberDouble: value.toString() };
  4731. }
  4732. if (value instanceof RegExp || isRegExp(value)) {
  4733. var flags = value.flags;
  4734. if (flags === undefined) {
  4735. var match = value.toString().match(/[gimuy]*$/);
  4736. if (match) {
  4737. flags = match[0];
  4738. }
  4739. }
  4740. var rx = new BSONRegExp(value.source, flags);
  4741. return rx.toExtendedJSON(options);
  4742. }
  4743. if (value != null && typeof value === 'object')
  4744. return serializeDocument(value, options);
  4745. return value;
  4746. }
  4747. var BSON_TYPE_MAPPINGS = {
  4748. Binary: function (o) { return new Binary(o.value(), o.sub_type); },
  4749. Code: function (o) { return new Code(o.code, o.scope); },
  4750. DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); },
  4751. Decimal128: function (o) { return new Decimal128(o.bytes); },
  4752. Double: function (o) { return new Double(o.value); },
  4753. Int32: function (o) { return new Int32(o.value); },
  4754. Long: function (o) {
  4755. return Long.fromBits(
  4756. // underscore variants for 1.x backwards compatibility
  4757. o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_);
  4758. },
  4759. MaxKey: function () { return new MaxKey(); },
  4760. MinKey: function () { return new MinKey(); },
  4761. ObjectID: function (o) { return new ObjectId(o); },
  4762. ObjectId: function (o) { return new ObjectId(o); },
  4763. BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); },
  4764. Symbol: function (o) { return new BSONSymbol(o.value); },
  4765. Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); }
  4766. };
  4767. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4768. function serializeDocument(doc, options) {
  4769. if (doc == null || typeof doc !== 'object')
  4770. throw new BSONError('not an object instance');
  4771. var bsontype = doc._bsontype;
  4772. if (typeof bsontype === 'undefined') {
  4773. // It's a regular object. Recursively serialize its property values.
  4774. var _doc = {};
  4775. for (var name in doc) {
  4776. options.seenObjects.push({ propertyName: name, obj: null });
  4777. try {
  4778. _doc[name] = serializeValue(doc[name], options);
  4779. }
  4780. finally {
  4781. options.seenObjects.pop();
  4782. }
  4783. }
  4784. return _doc;
  4785. }
  4786. else if (isBSONType(doc)) {
  4787. // the "document" is really just a BSON type object
  4788. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4789. var outDoc = doc;
  4790. if (typeof outDoc.toExtendedJSON !== 'function') {
  4791. // There's no EJSON serialization function on the object. It's probably an
  4792. // object created by a previous version of this library (or another library)
  4793. // that's duck-typing objects to look like they were generated by this library).
  4794. // Copy the object into this library's version of that type.
  4795. var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
  4796. if (!mapper) {
  4797. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
  4798. }
  4799. outDoc = mapper(outDoc);
  4800. }
  4801. // Two BSON types may have nested objects that may need to be serialized too
  4802. if (bsontype === 'Code' && outDoc.scope) {
  4803. outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
  4804. }
  4805. else if (bsontype === 'DBRef' && outDoc.oid) {
  4806. outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
  4807. }
  4808. return outDoc.toExtendedJSON(options);
  4809. }
  4810. else {
  4811. throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
  4812. }
  4813. }
  4814. /**
  4815. * EJSON parse / stringify API
  4816. * @public
  4817. */
  4818. // the namespace here is used to emulate `export * as EJSON from '...'`
  4819. // which as of now (sept 2020) api-extractor does not support
  4820. // eslint-disable-next-line @typescript-eslint/no-namespace
  4821. exports.EJSON = void 0;
  4822. (function (EJSON) {
  4823. /**
  4824. * Parse an Extended JSON string, constructing the JavaScript value or object described by that
  4825. * string.
  4826. *
  4827. * @example
  4828. * ```js
  4829. * const { EJSON } = require('bson');
  4830. * const text = '{ "int32": { "$numberInt": "10" } }';
  4831. *
  4832. * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
  4833. * console.log(EJSON.parse(text, { relaxed: false }));
  4834. *
  4835. * // prints { int32: 10 }
  4836. * console.log(EJSON.parse(text));
  4837. * ```
  4838. */
  4839. function parse(text, options) {
  4840. var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options);
  4841. // relaxed implies not strict
  4842. if (typeof finalOptions.relaxed === 'boolean')
  4843. finalOptions.strict = !finalOptions.relaxed;
  4844. if (typeof finalOptions.strict === 'boolean')
  4845. finalOptions.relaxed = !finalOptions.strict;
  4846. return JSON.parse(text, function (key, value) {
  4847. if (key.indexOf('\x00') !== -1) {
  4848. throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key));
  4849. }
  4850. return deserializeValue(value, finalOptions);
  4851. });
  4852. }
  4853. EJSON.parse = parse;
  4854. /**
  4855. * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
  4856. * function is specified or optionally including only the specified properties if a replacer array
  4857. * is specified.
  4858. *
  4859. * @param value - The value to convert to extended JSON
  4860. * @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
  4861. * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
  4862. * @param options - Optional settings
  4863. *
  4864. * @example
  4865. * ```js
  4866. * const { EJSON } = require('bson');
  4867. * const Int32 = require('mongodb').Int32;
  4868. * const doc = { int32: new Int32(10) };
  4869. *
  4870. * // prints '{"int32":{"$numberInt":"10"}}'
  4871. * console.log(EJSON.stringify(doc, { relaxed: false }));
  4872. *
  4873. * // prints '{"int32":10}'
  4874. * console.log(EJSON.stringify(doc));
  4875. * ```
  4876. */
  4877. function stringify(value,
  4878. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4879. replacer, space, options) {
  4880. if (space != null && typeof space === 'object') {
  4881. options = space;
  4882. space = 0;
  4883. }
  4884. if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
  4885. options = replacer;
  4886. replacer = undefined;
  4887. space = 0;
  4888. }
  4889. var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
  4890. seenObjects: [{ propertyName: '(root)', obj: null }]
  4891. });
  4892. var doc = serializeValue(value, serializeOptions);
  4893. return JSON.stringify(doc, replacer, space);
  4894. }
  4895. EJSON.stringify = stringify;
  4896. /**
  4897. * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
  4898. *
  4899. * @param value - The object to serialize
  4900. * @param options - Optional settings passed to the `stringify` function
  4901. */
  4902. function serialize(value, options) {
  4903. options = options || {};
  4904. return JSON.parse(stringify(value, options));
  4905. }
  4906. EJSON.serialize = serialize;
  4907. /**
  4908. * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
  4909. *
  4910. * @param ejson - The Extended JSON object to deserialize
  4911. * @param options - Optional settings passed to the parse method
  4912. */
  4913. function deserialize(ejson, options) {
  4914. options = options || {};
  4915. return parse(JSON.stringify(ejson), options);
  4916. }
  4917. EJSON.deserialize = deserialize;
  4918. })(exports.EJSON || (exports.EJSON = {}));
  4919. /* eslint-disable @typescript-eslint/no-explicit-any */
  4920. /** @public */
  4921. exports.Map = void 0;
  4922. var bsonGlobal = getGlobal();
  4923. if (bsonGlobal.Map) {
  4924. exports.Map = bsonGlobal.Map;
  4925. }
  4926. else {
  4927. // We will return a polyfill
  4928. exports.Map = /** @class */ (function () {
  4929. function Map(array) {
  4930. if (array === void 0) { array = []; }
  4931. this._keys = [];
  4932. this._values = {};
  4933. for (var i = 0; i < array.length; i++) {
  4934. if (array[i] == null)
  4935. continue; // skip null and undefined
  4936. var entry = array[i];
  4937. var key = entry[0];
  4938. var value = entry[1];
  4939. // Add the key to the list of keys in order
  4940. this._keys.push(key);
  4941. // Add the key and value to the values dictionary with a point
  4942. // to the location in the ordered keys list
  4943. this._values[key] = { v: value, i: this._keys.length - 1 };
  4944. }
  4945. }
  4946. Map.prototype.clear = function () {
  4947. this._keys = [];
  4948. this._values = {};
  4949. };
  4950. Map.prototype.delete = function (key) {
  4951. var value = this._values[key];
  4952. if (value == null)
  4953. return false;
  4954. // Delete entry
  4955. delete this._values[key];
  4956. // Remove the key from the ordered keys list
  4957. this._keys.splice(value.i, 1);
  4958. return true;
  4959. };
  4960. Map.prototype.entries = function () {
  4961. var _this = this;
  4962. var index = 0;
  4963. return {
  4964. next: function () {
  4965. var key = _this._keys[index++];
  4966. return {
  4967. value: key !== undefined ? [key, _this._values[key].v] : undefined,
  4968. done: key !== undefined ? false : true
  4969. };
  4970. }
  4971. };
  4972. };
  4973. Map.prototype.forEach = function (callback, self) {
  4974. self = self || this;
  4975. for (var i = 0; i < this._keys.length; i++) {
  4976. var key = this._keys[i];
  4977. // Call the forEach callback
  4978. callback.call(self, this._values[key].v, key, self);
  4979. }
  4980. };
  4981. Map.prototype.get = function (key) {
  4982. return this._values[key] ? this._values[key].v : undefined;
  4983. };
  4984. Map.prototype.has = function (key) {
  4985. return this._values[key] != null;
  4986. };
  4987. Map.prototype.keys = function () {
  4988. var _this = this;
  4989. var index = 0;
  4990. return {
  4991. next: function () {
  4992. var key = _this._keys[index++];
  4993. return {
  4994. value: key !== undefined ? key : undefined,
  4995. done: key !== undefined ? false : true
  4996. };
  4997. }
  4998. };
  4999. };
  5000. Map.prototype.set = function (key, value) {
  5001. if (this._values[key]) {
  5002. this._values[key].v = value;
  5003. return this;
  5004. }
  5005. // Add the key to the list of keys in order
  5006. this._keys.push(key);
  5007. // Add the key and value to the values dictionary with a point
  5008. // to the location in the ordered keys list
  5009. this._values[key] = { v: value, i: this._keys.length - 1 };
  5010. return this;
  5011. };
  5012. Map.prototype.values = function () {
  5013. var _this = this;
  5014. var index = 0;
  5015. return {
  5016. next: function () {
  5017. var key = _this._keys[index++];
  5018. return {
  5019. value: key !== undefined ? _this._values[key].v : undefined,
  5020. done: key !== undefined ? false : true
  5021. };
  5022. }
  5023. };
  5024. };
  5025. Object.defineProperty(Map.prototype, "size", {
  5026. get: function () {
  5027. return this._keys.length;
  5028. },
  5029. enumerable: false,
  5030. configurable: true
  5031. });
  5032. return Map;
  5033. }());
  5034. }
  5035. /** @internal */
  5036. var BSON_INT32_MAX = 0x7fffffff;
  5037. /** @internal */
  5038. var BSON_INT32_MIN = -0x80000000;
  5039. /** @internal */
  5040. var BSON_INT64_MAX = Math.pow(2, 63) - 1;
  5041. /** @internal */
  5042. var BSON_INT64_MIN = -Math.pow(2, 63);
  5043. /**
  5044. * Any integer up to 2^53 can be precisely represented by a double.
  5045. * @internal
  5046. */
  5047. var JS_INT_MAX = Math.pow(2, 53);
  5048. /**
  5049. * Any integer down to -2^53 can be precisely represented by a double.
  5050. * @internal
  5051. */
  5052. var JS_INT_MIN = -Math.pow(2, 53);
  5053. /** Number BSON Type @internal */
  5054. var BSON_DATA_NUMBER = 1;
  5055. /** String BSON Type @internal */
  5056. var BSON_DATA_STRING = 2;
  5057. /** Object BSON Type @internal */
  5058. var BSON_DATA_OBJECT = 3;
  5059. /** Array BSON Type @internal */
  5060. var BSON_DATA_ARRAY = 4;
  5061. /** Binary BSON Type @internal */
  5062. var BSON_DATA_BINARY = 5;
  5063. /** Binary BSON Type @internal */
  5064. var BSON_DATA_UNDEFINED = 6;
  5065. /** ObjectId BSON Type @internal */
  5066. var BSON_DATA_OID = 7;
  5067. /** Boolean BSON Type @internal */
  5068. var BSON_DATA_BOOLEAN = 8;
  5069. /** Date BSON Type @internal */
  5070. var BSON_DATA_DATE = 9;
  5071. /** null BSON Type @internal */
  5072. var BSON_DATA_NULL = 10;
  5073. /** RegExp BSON Type @internal */
  5074. var BSON_DATA_REGEXP = 11;
  5075. /** Code BSON Type @internal */
  5076. var BSON_DATA_DBPOINTER = 12;
  5077. /** Code BSON Type @internal */
  5078. var BSON_DATA_CODE = 13;
  5079. /** Symbol BSON Type @internal */
  5080. var BSON_DATA_SYMBOL = 14;
  5081. /** Code with Scope BSON Type @internal */
  5082. var BSON_DATA_CODE_W_SCOPE = 15;
  5083. /** 32 bit Integer BSON Type @internal */
  5084. var BSON_DATA_INT = 16;
  5085. /** Timestamp BSON Type @internal */
  5086. var BSON_DATA_TIMESTAMP = 17;
  5087. /** Long BSON Type @internal */
  5088. var BSON_DATA_LONG = 18;
  5089. /** Decimal128 BSON Type @internal */
  5090. var BSON_DATA_DECIMAL128 = 19;
  5091. /** MinKey BSON Type @internal */
  5092. var BSON_DATA_MIN_KEY = 0xff;
  5093. /** MaxKey BSON Type @internal */
  5094. var BSON_DATA_MAX_KEY = 0x7f;
  5095. /** Binary Default Type @internal */
  5096. var BSON_BINARY_SUBTYPE_DEFAULT = 0;
  5097. /** Binary Function Type @internal */
  5098. var BSON_BINARY_SUBTYPE_FUNCTION = 1;
  5099. /** Binary Byte Array Type @internal */
  5100. var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
  5101. /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */
  5102. var BSON_BINARY_SUBTYPE_UUID = 3;
  5103. /** Binary UUID Type @internal */
  5104. var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
  5105. /** Binary MD5 Type @internal */
  5106. var BSON_BINARY_SUBTYPE_MD5 = 5;
  5107. /** Encrypted BSON type @internal */
  5108. var BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
  5109. /** Column BSON type @internal */
  5110. var BSON_BINARY_SUBTYPE_COLUMN = 7;
  5111. /** Binary User Defined Type @internal */
  5112. var BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
  5113. function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) {
  5114. var totalLength = 4 + 1;
  5115. if (Array.isArray(object)) {
  5116. for (var i = 0; i < object.length; i++) {
  5117. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  5118. }
  5119. }
  5120. else {
  5121. // If we have toBSON defined, override the current object
  5122. if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
  5123. object = object.toBSON();
  5124. }
  5125. // Calculate size
  5126. for (var key in object) {
  5127. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  5128. }
  5129. }
  5130. return totalLength;
  5131. }
  5132. /** @internal */
  5133. function calculateElement(name,
  5134. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5135. value, serializeFunctions, isArray, ignoreUndefined) {
  5136. if (serializeFunctions === void 0) { serializeFunctions = false; }
  5137. if (isArray === void 0) { isArray = false; }
  5138. if (ignoreUndefined === void 0) { ignoreUndefined = false; }
  5139. // If we have toBSON defined, override the current object
  5140. if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
  5141. value = value.toBSON();
  5142. }
  5143. switch (typeof value) {
  5144. case 'string':
  5145. return 1 + buffer_1.byteLength(name, 'utf8') + 1 + 4 + buffer_1.byteLength(value, 'utf8') + 1;
  5146. case 'number':
  5147. if (Math.floor(value) === value &&
  5148. value >= JS_INT_MIN &&
  5149. value <= JS_INT_MAX) {
  5150. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  5151. // 32 bit
  5152. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (4 + 1);
  5153. }
  5154. else {
  5155. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  5156. }
  5157. }
  5158. else {
  5159. // 64 bit
  5160. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  5161. }
  5162. case 'undefined':
  5163. if (isArray || !ignoreUndefined)
  5164. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1;
  5165. return 0;
  5166. case 'boolean':
  5167. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 1);
  5168. case 'object':
  5169. if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  5170. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + 1;
  5171. }
  5172. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  5173. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (12 + 1);
  5174. }
  5175. else if (value instanceof Date || isDate(value)) {
  5176. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  5177. }
  5178. else if (ArrayBuffer.isView(value) ||
  5179. value instanceof ArrayBuffer ||
  5180. isAnyArrayBuffer(value)) {
  5181. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength);
  5182. }
  5183. else if (value['_bsontype'] === 'Long' ||
  5184. value['_bsontype'] === 'Double' ||
  5185. value['_bsontype'] === 'Timestamp') {
  5186. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  5187. }
  5188. else if (value['_bsontype'] === 'Decimal128') {
  5189. return (name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (16 + 1);
  5190. }
  5191. else if (value['_bsontype'] === 'Code') {
  5192. // Calculate size depending on the availability of a scope
  5193. if (value.scope != null && Object.keys(value.scope).length > 0) {
  5194. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5195. 1 +
  5196. 4 +
  5197. 4 +
  5198. buffer_1.byteLength(value.code.toString(), 'utf8') +
  5199. 1 +
  5200. calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined));
  5201. }
  5202. else {
  5203. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5204. 1 +
  5205. 4 +
  5206. buffer_1.byteLength(value.code.toString(), 'utf8') +
  5207. 1);
  5208. }
  5209. }
  5210. else if (value['_bsontype'] === 'Binary') {
  5211. // Check what kind of subtype we have
  5212. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  5213. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5214. (value.position + 1 + 4 + 1 + 4));
  5215. }
  5216. else {
  5217. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1));
  5218. }
  5219. }
  5220. else if (value['_bsontype'] === 'Symbol') {
  5221. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5222. buffer_1.byteLength(value.value, 'utf8') +
  5223. 4 +
  5224. 1 +
  5225. 1);
  5226. }
  5227. else if (value['_bsontype'] === 'DBRef') {
  5228. // Set up correct object for serialization
  5229. var ordered_values = Object.assign({
  5230. $ref: value.collection,
  5231. $id: value.oid
  5232. }, value.fields);
  5233. // Add db reference if it exists
  5234. if (value.db != null) {
  5235. ordered_values['$db'] = value.db;
  5236. }
  5237. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5238. 1 +
  5239. calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined));
  5240. }
  5241. else if (value instanceof RegExp || isRegExp(value)) {
  5242. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5243. 1 +
  5244. buffer_1.byteLength(value.source, 'utf8') +
  5245. 1 +
  5246. (value.global ? 1 : 0) +
  5247. (value.ignoreCase ? 1 : 0) +
  5248. (value.multiline ? 1 : 0) +
  5249. 1);
  5250. }
  5251. else if (value['_bsontype'] === 'BSONRegExp') {
  5252. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5253. 1 +
  5254. buffer_1.byteLength(value.pattern, 'utf8') +
  5255. 1 +
  5256. buffer_1.byteLength(value.options, 'utf8') +
  5257. 1);
  5258. }
  5259. else {
  5260. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5261. calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) +
  5262. 1);
  5263. }
  5264. case 'function':
  5265. // WTF for 0.4.X where typeof /someregexp/ === 'function'
  5266. if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') {
  5267. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5268. 1 +
  5269. buffer_1.byteLength(value.source, 'utf8') +
  5270. 1 +
  5271. (value.global ? 1 : 0) +
  5272. (value.ignoreCase ? 1 : 0) +
  5273. (value.multiline ? 1 : 0) +
  5274. 1);
  5275. }
  5276. else {
  5277. if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
  5278. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5279. 1 +
  5280. 4 +
  5281. 4 +
  5282. buffer_1.byteLength(normalizedFunctionString(value), 'utf8') +
  5283. 1 +
  5284. calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined));
  5285. }
  5286. else if (serializeFunctions) {
  5287. return ((name != null ? buffer_1.byteLength(name, 'utf8') + 1 : 0) +
  5288. 1 +
  5289. 4 +
  5290. buffer_1.byteLength(normalizedFunctionString(value), 'utf8') +
  5291. 1);
  5292. }
  5293. }
  5294. }
  5295. return 0;
  5296. }
  5297. var FIRST_BIT = 0x80;
  5298. var FIRST_TWO_BITS = 0xc0;
  5299. var FIRST_THREE_BITS = 0xe0;
  5300. var FIRST_FOUR_BITS = 0xf0;
  5301. var FIRST_FIVE_BITS = 0xf8;
  5302. var TWO_BIT_CHAR = 0xc0;
  5303. var THREE_BIT_CHAR = 0xe0;
  5304. var FOUR_BIT_CHAR = 0xf0;
  5305. var CONTINUING_CHAR = 0x80;
  5306. /**
  5307. * Determines if the passed in bytes are valid utf8
  5308. * @param bytes - An array of 8-bit bytes. Must be indexable and have length property
  5309. * @param start - The index to start validating
  5310. * @param end - The index to end validating
  5311. */
  5312. function validateUtf8(bytes, start, end) {
  5313. var continuation = 0;
  5314. for (var i = start; i < end; i += 1) {
  5315. var byte = bytes[i];
  5316. if (continuation) {
  5317. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  5318. return false;
  5319. }
  5320. continuation -= 1;
  5321. }
  5322. else if (byte & FIRST_BIT) {
  5323. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  5324. continuation = 1;
  5325. }
  5326. else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  5327. continuation = 2;
  5328. }
  5329. else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  5330. continuation = 3;
  5331. }
  5332. else {
  5333. return false;
  5334. }
  5335. }
  5336. }
  5337. return !continuation;
  5338. }
  5339. // Internal long versions
  5340. var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
  5341. var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
  5342. var functionCache = {};
  5343. function deserialize$1(buffer, options, isArray) {
  5344. options = options == null ? {} : options;
  5345. var index = options && options.index ? options.index : 0;
  5346. // Read the document size
  5347. var size = buffer[index] |
  5348. (buffer[index + 1] << 8) |
  5349. (buffer[index + 2] << 16) |
  5350. (buffer[index + 3] << 24);
  5351. if (size < 5) {
  5352. throw new BSONError("bson size must be >= 5, is " + size);
  5353. }
  5354. if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
  5355. throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size);
  5356. }
  5357. if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
  5358. throw new BSONError("buffer length " + buffer.length + " must === bson size " + size);
  5359. }
  5360. if (size + index > buffer.byteLength) {
  5361. throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
  5362. }
  5363. // Illegal end value
  5364. if (buffer[index + size - 1] !== 0) {
  5365. throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  5366. }
  5367. // Start deserializtion
  5368. return deserializeObject(buffer, index, options, isArray);
  5369. }
  5370. var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
  5371. function deserializeObject(buffer, index, options, isArray) {
  5372. if (isArray === void 0) { isArray = false; }
  5373. var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];
  5374. var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];
  5375. var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
  5376. // Return raw bson buffer instead of parsing it
  5377. var raw = options['raw'] == null ? false : options['raw'];
  5378. // Return BSONRegExp objects instead of native regular expressions
  5379. var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
  5380. // Controls the promotion of values vs wrapper classes
  5381. var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
  5382. var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
  5383. var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
  5384. // Ensures default validation option if none given
  5385. var validation = options.validation == null ? { utf8: true } : options.validation;
  5386. // Shows if global utf-8 validation is enabled or disabled
  5387. var globalUTFValidation = true;
  5388. // Reflects utf-8 validation setting regardless of global or specific key validation
  5389. var validationSetting;
  5390. // Set of keys either to enable or disable validation on
  5391. var utf8KeysSet = new Set();
  5392. // Check for boolean uniformity and empty validation option
  5393. var utf8ValidatedKeys = validation.utf8;
  5394. if (typeof utf8ValidatedKeys === 'boolean') {
  5395. validationSetting = utf8ValidatedKeys;
  5396. }
  5397. else {
  5398. globalUTFValidation = false;
  5399. var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
  5400. return utf8ValidatedKeys[key];
  5401. });
  5402. if (utf8ValidationValues.length === 0) {
  5403. throw new BSONError('UTF-8 validation setting cannot be empty');
  5404. }
  5405. if (typeof utf8ValidationValues[0] !== 'boolean') {
  5406. throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
  5407. }
  5408. validationSetting = utf8ValidationValues[0];
  5409. // Ensures boolean uniformity in utf-8 validation (all true or all false)
  5410. if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) {
  5411. throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
  5412. }
  5413. }
  5414. // Add keys to set that will either be validated or not based on validationSetting
  5415. if (!globalUTFValidation) {
  5416. for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) {
  5417. var key = _a[_i];
  5418. utf8KeysSet.add(key);
  5419. }
  5420. }
  5421. // Set the start index
  5422. var startIndex = index;
  5423. // Validate that we have at least 4 bytes of buffer
  5424. if (buffer.length < 5)
  5425. throw new BSONError('corrupt bson message < 5 bytes long');
  5426. // Read the document size
  5427. var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  5428. // Ensure buffer is valid size
  5429. if (size < 5 || size > buffer.length)
  5430. throw new BSONError('corrupt bson message');
  5431. // Create holding object
  5432. var object = isArray ? [] : {};
  5433. // Used for arrays to skip having to perform utf8 decoding
  5434. var arrayIndex = 0;
  5435. var done = false;
  5436. var isPossibleDBRef = isArray ? false : null;
  5437. // While we have more left data left keep parsing
  5438. while (!done) {
  5439. // Read the type
  5440. var elementType = buffer[index++];
  5441. // If we get a zero it's the last byte, exit
  5442. if (elementType === 0)
  5443. break;
  5444. // Get the start search index
  5445. var i = index;
  5446. // Locate the end of the c string
  5447. while (buffer[i] !== 0x00 && i < buffer.length) {
  5448. i++;
  5449. }
  5450. // If are at the end of the buffer there is a problem with the document
  5451. if (i >= buffer.byteLength)
  5452. throw new BSONError('Bad BSON Document: illegal CString');
  5453. // Represents the key
  5454. var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);
  5455. // shouldValidateKey is true if the key should be validated, false otherwise
  5456. var shouldValidateKey = true;
  5457. if (globalUTFValidation || utf8KeysSet.has(name)) {
  5458. shouldValidateKey = validationSetting;
  5459. }
  5460. else {
  5461. shouldValidateKey = !validationSetting;
  5462. }
  5463. if (isPossibleDBRef !== false && name[0] === '$') {
  5464. isPossibleDBRef = allowedDBRefKeys.test(name);
  5465. }
  5466. var value = void 0;
  5467. index = i + 1;
  5468. if (elementType === BSON_DATA_STRING) {
  5469. var stringSize = buffer[index++] |
  5470. (buffer[index++] << 8) |
  5471. (buffer[index++] << 16) |
  5472. (buffer[index++] << 24);
  5473. if (stringSize <= 0 ||
  5474. stringSize > buffer.length - index ||
  5475. buffer[index + stringSize - 1] !== 0) {
  5476. throw new BSONError('bad string length in bson');
  5477. }
  5478. value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  5479. index = index + stringSize;
  5480. }
  5481. else if (elementType === BSON_DATA_OID) {
  5482. var oid = buffer_1.alloc(12);
  5483. buffer.copy(oid, 0, index, index + 12);
  5484. value = new ObjectId(oid);
  5485. index = index + 12;
  5486. }
  5487. else if (elementType === BSON_DATA_INT && promoteValues === false) {
  5488. value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24));
  5489. }
  5490. else if (elementType === BSON_DATA_INT) {
  5491. value =
  5492. buffer[index++] |
  5493. (buffer[index++] << 8) |
  5494. (buffer[index++] << 16) |
  5495. (buffer[index++] << 24);
  5496. }
  5497. else if (elementType === BSON_DATA_NUMBER && promoteValues === false) {
  5498. value = new Double(buffer.readDoubleLE(index));
  5499. index = index + 8;
  5500. }
  5501. else if (elementType === BSON_DATA_NUMBER) {
  5502. value = buffer.readDoubleLE(index);
  5503. index = index + 8;
  5504. }
  5505. else if (elementType === BSON_DATA_DATE) {
  5506. var lowBits = buffer[index++] |
  5507. (buffer[index++] << 8) |
  5508. (buffer[index++] << 16) |
  5509. (buffer[index++] << 24);
  5510. var highBits = buffer[index++] |
  5511. (buffer[index++] << 8) |
  5512. (buffer[index++] << 16) |
  5513. (buffer[index++] << 24);
  5514. value = new Date(new Long(lowBits, highBits).toNumber());
  5515. }
  5516. else if (elementType === BSON_DATA_BOOLEAN) {
  5517. if (buffer[index] !== 0 && buffer[index] !== 1)
  5518. throw new BSONError('illegal boolean type value');
  5519. value = buffer[index++] === 1;
  5520. }
  5521. else if (elementType === BSON_DATA_OBJECT) {
  5522. var _index = index;
  5523. var objectSize = buffer[index] |
  5524. (buffer[index + 1] << 8) |
  5525. (buffer[index + 2] << 16) |
  5526. (buffer[index + 3] << 24);
  5527. if (objectSize <= 0 || objectSize > buffer.length - index)
  5528. throw new BSONError('bad embedded document length in bson');
  5529. // We have a raw value
  5530. if (raw) {
  5531. value = buffer.slice(index, index + objectSize);
  5532. }
  5533. else {
  5534. var objectOptions = options;
  5535. if (!globalUTFValidation) {
  5536. objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } });
  5537. }
  5538. value = deserializeObject(buffer, _index, objectOptions, false);
  5539. }
  5540. index = index + objectSize;
  5541. }
  5542. else if (elementType === BSON_DATA_ARRAY) {
  5543. var _index = index;
  5544. var objectSize = buffer[index] |
  5545. (buffer[index + 1] << 8) |
  5546. (buffer[index + 2] << 16) |
  5547. (buffer[index + 3] << 24);
  5548. var arrayOptions = options;
  5549. // Stop index
  5550. var stopIndex = index + objectSize;
  5551. // All elements of array to be returned as raw bson
  5552. if (fieldsAsRaw && fieldsAsRaw[name]) {
  5553. arrayOptions = {};
  5554. for (var n in options) {
  5555. arrayOptions[n] = options[n];
  5556. }
  5557. arrayOptions['raw'] = true;
  5558. }
  5559. if (!globalUTFValidation) {
  5560. arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } });
  5561. }
  5562. value = deserializeObject(buffer, _index, arrayOptions, true);
  5563. index = index + objectSize;
  5564. if (buffer[index - 1] !== 0)
  5565. throw new BSONError('invalid array terminator byte');
  5566. if (index !== stopIndex)
  5567. throw new BSONError('corrupted array bson');
  5568. }
  5569. else if (elementType === BSON_DATA_UNDEFINED) {
  5570. value = undefined;
  5571. }
  5572. else if (elementType === BSON_DATA_NULL) {
  5573. value = null;
  5574. }
  5575. else if (elementType === BSON_DATA_LONG) {
  5576. // Unpack the low and high bits
  5577. var lowBits = buffer[index++] |
  5578. (buffer[index++] << 8) |
  5579. (buffer[index++] << 16) |
  5580. (buffer[index++] << 24);
  5581. var highBits = buffer[index++] |
  5582. (buffer[index++] << 8) |
  5583. (buffer[index++] << 16) |
  5584. (buffer[index++] << 24);
  5585. var long = new Long(lowBits, highBits);
  5586. // Promote the long if possible
  5587. if (promoteLongs && promoteValues === true) {
  5588. value =
  5589. long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
  5590. ? long.toNumber()
  5591. : long;
  5592. }
  5593. else {
  5594. value = long;
  5595. }
  5596. }
  5597. else if (elementType === BSON_DATA_DECIMAL128) {
  5598. // Buffer to contain the decimal bytes
  5599. var bytes = buffer_1.alloc(16);
  5600. // Copy the next 16 bytes into the bytes buffer
  5601. buffer.copy(bytes, 0, index, index + 16);
  5602. // Update index
  5603. index = index + 16;
  5604. // Assign the new Decimal128 value
  5605. var decimal128 = new Decimal128(bytes);
  5606. // If we have an alternative mapper use that
  5607. if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') {
  5608. value = decimal128.toObject();
  5609. }
  5610. else {
  5611. value = decimal128;
  5612. }
  5613. }
  5614. else if (elementType === BSON_DATA_BINARY) {
  5615. var binarySize = buffer[index++] |
  5616. (buffer[index++] << 8) |
  5617. (buffer[index++] << 16) |
  5618. (buffer[index++] << 24);
  5619. var totalBinarySize = binarySize;
  5620. var subType = buffer[index++];
  5621. // Did we have a negative binary size, throw
  5622. if (binarySize < 0)
  5623. throw new BSONError('Negative binary type element size found');
  5624. // Is the length longer than the document
  5625. if (binarySize > buffer.byteLength)
  5626. throw new BSONError('Binary type size larger than document size');
  5627. // Decode as raw Buffer object if options specifies it
  5628. if (buffer['slice'] != null) {
  5629. // If we have subtype 2 skip the 4 bytes for the size
  5630. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  5631. binarySize =
  5632. buffer[index++] |
  5633. (buffer[index++] << 8) |
  5634. (buffer[index++] << 16) |
  5635. (buffer[index++] << 24);
  5636. if (binarySize < 0)
  5637. throw new BSONError('Negative binary type element size found for subtype 0x02');
  5638. if (binarySize > totalBinarySize - 4)
  5639. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  5640. if (binarySize < totalBinarySize - 4)
  5641. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  5642. }
  5643. if (promoteBuffers && promoteValues) {
  5644. value = buffer.slice(index, index + binarySize);
  5645. }
  5646. else {
  5647. value = new Binary(buffer.slice(index, index + binarySize), subType);
  5648. }
  5649. }
  5650. else {
  5651. var _buffer = buffer_1.alloc(binarySize);
  5652. // If we have subtype 2 skip the 4 bytes for the size
  5653. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  5654. binarySize =
  5655. buffer[index++] |
  5656. (buffer[index++] << 8) |
  5657. (buffer[index++] << 16) |
  5658. (buffer[index++] << 24);
  5659. if (binarySize < 0)
  5660. throw new BSONError('Negative binary type element size found for subtype 0x02');
  5661. if (binarySize > totalBinarySize - 4)
  5662. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  5663. if (binarySize < totalBinarySize - 4)
  5664. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  5665. }
  5666. // Copy the data
  5667. for (i = 0; i < binarySize; i++) {
  5668. _buffer[i] = buffer[index + i];
  5669. }
  5670. if (promoteBuffers && promoteValues) {
  5671. value = _buffer;
  5672. }
  5673. else {
  5674. value = new Binary(_buffer, subType);
  5675. }
  5676. }
  5677. // Update the index
  5678. index = index + binarySize;
  5679. }
  5680. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
  5681. // Get the start search index
  5682. i = index;
  5683. // Locate the end of the c string
  5684. while (buffer[i] !== 0x00 && i < buffer.length) {
  5685. i++;
  5686. }
  5687. // If are at the end of the buffer there is a problem with the document
  5688. if (i >= buffer.length)
  5689. throw new BSONError('Bad BSON Document: illegal CString');
  5690. // Return the C string
  5691. var source = buffer.toString('utf8', index, i);
  5692. // Create the regexp
  5693. index = i + 1;
  5694. // Get the start search index
  5695. i = index;
  5696. // Locate the end of the c string
  5697. while (buffer[i] !== 0x00 && i < buffer.length) {
  5698. i++;
  5699. }
  5700. // If are at the end of the buffer there is a problem with the document
  5701. if (i >= buffer.length)
  5702. throw new BSONError('Bad BSON Document: illegal CString');
  5703. // Return the C string
  5704. var regExpOptions = buffer.toString('utf8', index, i);
  5705. index = i + 1;
  5706. // For each option add the corresponding one for javascript
  5707. var optionsArray = new Array(regExpOptions.length);
  5708. // Parse options
  5709. for (i = 0; i < regExpOptions.length; i++) {
  5710. switch (regExpOptions[i]) {
  5711. case 'm':
  5712. optionsArray[i] = 'm';
  5713. break;
  5714. case 's':
  5715. optionsArray[i] = 'g';
  5716. break;
  5717. case 'i':
  5718. optionsArray[i] = 'i';
  5719. break;
  5720. }
  5721. }
  5722. value = new RegExp(source, optionsArray.join(''));
  5723. }
  5724. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
  5725. // Get the start search index
  5726. i = index;
  5727. // Locate the end of the c string
  5728. while (buffer[i] !== 0x00 && i < buffer.length) {
  5729. i++;
  5730. }
  5731. // If are at the end of the buffer there is a problem with the document
  5732. if (i >= buffer.length)
  5733. throw new BSONError('Bad BSON Document: illegal CString');
  5734. // Return the C string
  5735. var source = buffer.toString('utf8', index, i);
  5736. index = i + 1;
  5737. // Get the start search index
  5738. i = index;
  5739. // Locate the end of the c string
  5740. while (buffer[i] !== 0x00 && i < buffer.length) {
  5741. i++;
  5742. }
  5743. // If are at the end of the buffer there is a problem with the document
  5744. if (i >= buffer.length)
  5745. throw new BSONError('Bad BSON Document: illegal CString');
  5746. // Return the C string
  5747. var regExpOptions = buffer.toString('utf8', index, i);
  5748. index = i + 1;
  5749. // Set the object
  5750. value = new BSONRegExp(source, regExpOptions);
  5751. }
  5752. else if (elementType === BSON_DATA_SYMBOL) {
  5753. var stringSize = buffer[index++] |
  5754. (buffer[index++] << 8) |
  5755. (buffer[index++] << 16) |
  5756. (buffer[index++] << 24);
  5757. if (stringSize <= 0 ||
  5758. stringSize > buffer.length - index ||
  5759. buffer[index + stringSize - 1] !== 0) {
  5760. throw new BSONError('bad string length in bson');
  5761. }
  5762. var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  5763. value = promoteValues ? symbol : new BSONSymbol(symbol);
  5764. index = index + stringSize;
  5765. }
  5766. else if (elementType === BSON_DATA_TIMESTAMP) {
  5767. var lowBits = buffer[index++] |
  5768. (buffer[index++] << 8) |
  5769. (buffer[index++] << 16) |
  5770. (buffer[index++] << 24);
  5771. var highBits = buffer[index++] |
  5772. (buffer[index++] << 8) |
  5773. (buffer[index++] << 16) |
  5774. (buffer[index++] << 24);
  5775. value = new Timestamp(lowBits, highBits);
  5776. }
  5777. else if (elementType === BSON_DATA_MIN_KEY) {
  5778. value = new MinKey();
  5779. }
  5780. else if (elementType === BSON_DATA_MAX_KEY) {
  5781. value = new MaxKey();
  5782. }
  5783. else if (elementType === BSON_DATA_CODE) {
  5784. var stringSize = buffer[index++] |
  5785. (buffer[index++] << 8) |
  5786. (buffer[index++] << 16) |
  5787. (buffer[index++] << 24);
  5788. if (stringSize <= 0 ||
  5789. stringSize > buffer.length - index ||
  5790. buffer[index + stringSize - 1] !== 0) {
  5791. throw new BSONError('bad string length in bson');
  5792. }
  5793. var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  5794. // If we are evaluating the functions
  5795. if (evalFunctions) {
  5796. // If we have cache enabled let's look for the md5 of the function in the cache
  5797. if (cacheFunctions) {
  5798. // Got to do this to avoid V8 deoptimizing the call due to finding eval
  5799. value = isolateEval(functionString, functionCache, object);
  5800. }
  5801. else {
  5802. value = isolateEval(functionString);
  5803. }
  5804. }
  5805. else {
  5806. value = new Code(functionString);
  5807. }
  5808. // Update parse index position
  5809. index = index + stringSize;
  5810. }
  5811. else if (elementType === BSON_DATA_CODE_W_SCOPE) {
  5812. var totalSize = buffer[index++] |
  5813. (buffer[index++] << 8) |
  5814. (buffer[index++] << 16) |
  5815. (buffer[index++] << 24);
  5816. // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
  5817. if (totalSize < 4 + 4 + 4 + 1) {
  5818. throw new BSONError('code_w_scope total size shorter minimum expected length');
  5819. }
  5820. // Get the code string size
  5821. var stringSize = buffer[index++] |
  5822. (buffer[index++] << 8) |
  5823. (buffer[index++] << 16) |
  5824. (buffer[index++] << 24);
  5825. // Check if we have a valid string
  5826. if (stringSize <= 0 ||
  5827. stringSize > buffer.length - index ||
  5828. buffer[index + stringSize - 1] !== 0) {
  5829. throw new BSONError('bad string length in bson');
  5830. }
  5831. // Javascript function
  5832. var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  5833. // Update parse index position
  5834. index = index + stringSize;
  5835. // Parse the element
  5836. var _index = index;
  5837. // Decode the size of the object document
  5838. var objectSize = buffer[index] |
  5839. (buffer[index + 1] << 8) |
  5840. (buffer[index + 2] << 16) |
  5841. (buffer[index + 3] << 24);
  5842. // Decode the scope object
  5843. var scopeObject = deserializeObject(buffer, _index, options, false);
  5844. // Adjust the index
  5845. index = index + objectSize;
  5846. // Check if field length is too short
  5847. if (totalSize < 4 + 4 + objectSize + stringSize) {
  5848. throw new BSONError('code_w_scope total size is too short, truncating scope');
  5849. }
  5850. // Check if totalSize field is too long
  5851. if (totalSize > 4 + 4 + objectSize + stringSize) {
  5852. throw new BSONError('code_w_scope total size is too long, clips outer document');
  5853. }
  5854. // If we are evaluating the functions
  5855. if (evalFunctions) {
  5856. // If we have cache enabled let's look for the md5 of the function in the cache
  5857. if (cacheFunctions) {
  5858. // Got to do this to avoid V8 deoptimizing the call due to finding eval
  5859. value = isolateEval(functionString, functionCache, object);
  5860. }
  5861. else {
  5862. value = isolateEval(functionString);
  5863. }
  5864. value.scope = scopeObject;
  5865. }
  5866. else {
  5867. value = new Code(functionString, scopeObject);
  5868. }
  5869. }
  5870. else if (elementType === BSON_DATA_DBPOINTER) {
  5871. // Get the code string size
  5872. var stringSize = buffer[index++] |
  5873. (buffer[index++] << 8) |
  5874. (buffer[index++] << 16) |
  5875. (buffer[index++] << 24);
  5876. // Check if we have a valid string
  5877. if (stringSize <= 0 ||
  5878. stringSize > buffer.length - index ||
  5879. buffer[index + stringSize - 1] !== 0)
  5880. throw new BSONError('bad string length in bson');
  5881. // Namespace
  5882. if (validation != null && validation.utf8) {
  5883. if (!validateUtf8(buffer, index, index + stringSize - 1)) {
  5884. throw new BSONError('Invalid UTF-8 string in BSON document');
  5885. }
  5886. }
  5887. var namespace = buffer.toString('utf8', index, index + stringSize - 1);
  5888. // Update parse index position
  5889. index = index + stringSize;
  5890. // Read the oid
  5891. var oidBuffer = buffer_1.alloc(12);
  5892. buffer.copy(oidBuffer, 0, index, index + 12);
  5893. var oid = new ObjectId(oidBuffer);
  5894. // Update the index
  5895. index = index + 12;
  5896. // Upgrade to DBRef type
  5897. value = new DBRef(namespace, oid);
  5898. }
  5899. else {
  5900. throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
  5901. }
  5902. if (name === '__proto__') {
  5903. Object.defineProperty(object, name, {
  5904. value: value,
  5905. writable: true,
  5906. enumerable: true,
  5907. configurable: true
  5908. });
  5909. }
  5910. else {
  5911. object[name] = value;
  5912. }
  5913. }
  5914. // Check if the deserialization was against a valid array/object
  5915. if (size !== index - startIndex) {
  5916. if (isArray)
  5917. throw new BSONError('corrupt array bson');
  5918. throw new BSONError('corrupt object bson');
  5919. }
  5920. // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef
  5921. if (!isPossibleDBRef)
  5922. return object;
  5923. if (isDBRefLike(object)) {
  5924. var copy = Object.assign({}, object);
  5925. delete copy.$ref;
  5926. delete copy.$id;
  5927. delete copy.$db;
  5928. return new DBRef(object.$ref, object.$id, object.$db, copy);
  5929. }
  5930. return object;
  5931. }
  5932. /**
  5933. * Ensure eval is isolated, store the result in functionCache.
  5934. *
  5935. * @internal
  5936. */
  5937. function isolateEval(functionString, functionCache, object) {
  5938. if (!functionCache)
  5939. return new Function(functionString);
  5940. // Check for cache hit, eval if missing and return cached function
  5941. if (functionCache[functionString] == null) {
  5942. functionCache[functionString] = new Function(functionString);
  5943. }
  5944. // Set the object
  5945. return functionCache[functionString].bind(object);
  5946. }
  5947. function getValidatedString(buffer, start, end, shouldValidateUtf8) {
  5948. var value = buffer.toString('utf8', start, end);
  5949. // if utf8 validation is on, do the check
  5950. if (shouldValidateUtf8) {
  5951. for (var i = 0; i < value.length; i++) {
  5952. if (value.charCodeAt(i) === 0xfffd) {
  5953. if (!validateUtf8(buffer, start, end)) {
  5954. throw new BSONError('Invalid UTF-8 string in BSON document');
  5955. }
  5956. break;
  5957. }
  5958. }
  5959. }
  5960. return value;
  5961. }
  5962. // Copyright (c) 2008, Fair Oaks Labs, Inc.
  5963. function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) {
  5964. var e;
  5965. var m;
  5966. var c;
  5967. var bBE = endian === 'big';
  5968. var eLen = nBytes * 8 - mLen - 1;
  5969. var eMax = (1 << eLen) - 1;
  5970. var eBias = eMax >> 1;
  5971. var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  5972. var i = bBE ? nBytes - 1 : 0;
  5973. var d = bBE ? -1 : 1;
  5974. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  5975. value = Math.abs(value);
  5976. if (isNaN(value) || value === Infinity) {
  5977. m = isNaN(value) ? 1 : 0;
  5978. e = eMax;
  5979. }
  5980. else {
  5981. e = Math.floor(Math.log(value) / Math.LN2);
  5982. if (value * (c = Math.pow(2, -e)) < 1) {
  5983. e--;
  5984. c *= 2;
  5985. }
  5986. if (e + eBias >= 1) {
  5987. value += rt / c;
  5988. }
  5989. else {
  5990. value += rt * Math.pow(2, 1 - eBias);
  5991. }
  5992. if (value * c >= 2) {
  5993. e++;
  5994. c /= 2;
  5995. }
  5996. if (e + eBias >= eMax) {
  5997. m = 0;
  5998. e = eMax;
  5999. }
  6000. else if (e + eBias >= 1) {
  6001. m = (value * c - 1) * Math.pow(2, mLen);
  6002. e = e + eBias;
  6003. }
  6004. else {
  6005. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  6006. e = 0;
  6007. }
  6008. }
  6009. if (isNaN(value))
  6010. m = 0;
  6011. while (mLen >= 8) {
  6012. buffer[offset + i] = m & 0xff;
  6013. i += d;
  6014. m /= 256;
  6015. mLen -= 8;
  6016. }
  6017. e = (e << mLen) | m;
  6018. if (isNaN(value))
  6019. e += 8;
  6020. eLen += mLen;
  6021. while (eLen > 0) {
  6022. buffer[offset + i] = e & 0xff;
  6023. i += d;
  6024. e /= 256;
  6025. eLen -= 8;
  6026. }
  6027. buffer[offset + i - d] |= s * 128;
  6028. }
  6029. var regexp = /\x00/; // eslint-disable-line no-control-regex
  6030. var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
  6031. /*
  6032. * isArray indicates if we are writing to a BSON array (type 0x04)
  6033. * which forces the "key" which really an array index as a string to be written as ascii
  6034. * This will catch any errors in index as a string generation
  6035. */
  6036. function serializeString(buffer, key, value, index, isArray) {
  6037. // Encode String type
  6038. buffer[index++] = BSON_DATA_STRING;
  6039. // Number of written bytes
  6040. var numberOfWrittenBytes = !isArray
  6041. ? buffer.write(key, index, undefined, 'utf8')
  6042. : buffer.write(key, index, undefined, 'ascii');
  6043. // Encode the name
  6044. index = index + numberOfWrittenBytes + 1;
  6045. buffer[index - 1] = 0;
  6046. // Write the string
  6047. var size = buffer.write(value, index + 4, undefined, 'utf8');
  6048. // Write the size of the string to buffer
  6049. buffer[index + 3] = ((size + 1) >> 24) & 0xff;
  6050. buffer[index + 2] = ((size + 1) >> 16) & 0xff;
  6051. buffer[index + 1] = ((size + 1) >> 8) & 0xff;
  6052. buffer[index] = (size + 1) & 0xff;
  6053. // Update index
  6054. index = index + 4 + size;
  6055. // Write zero
  6056. buffer[index++] = 0;
  6057. return index;
  6058. }
  6059. function serializeNumber(buffer, key, value, index, isArray) {
  6060. // We have an integer value
  6061. // TODO(NODE-2529): Add support for big int
  6062. if (Number.isInteger(value) &&
  6063. value >= BSON_INT32_MIN &&
  6064. value <= BSON_INT32_MAX) {
  6065. // If the value fits in 32 bits encode as int32
  6066. // Set int type 32 bits or less
  6067. buffer[index++] = BSON_DATA_INT;
  6068. // Number of written bytes
  6069. var numberOfWrittenBytes = !isArray
  6070. ? buffer.write(key, index, undefined, 'utf8')
  6071. : buffer.write(key, index, undefined, 'ascii');
  6072. // Encode the name
  6073. index = index + numberOfWrittenBytes;
  6074. buffer[index++] = 0;
  6075. // Write the int value
  6076. buffer[index++] = value & 0xff;
  6077. buffer[index++] = (value >> 8) & 0xff;
  6078. buffer[index++] = (value >> 16) & 0xff;
  6079. buffer[index++] = (value >> 24) & 0xff;
  6080. }
  6081. else {
  6082. // Encode as double
  6083. buffer[index++] = BSON_DATA_NUMBER;
  6084. // Number of written bytes
  6085. var numberOfWrittenBytes = !isArray
  6086. ? buffer.write(key, index, undefined, 'utf8')
  6087. : buffer.write(key, index, undefined, 'ascii');
  6088. // Encode the name
  6089. index = index + numberOfWrittenBytes;
  6090. buffer[index++] = 0;
  6091. // Write float
  6092. writeIEEE754(buffer, value, index, 'little', 52, 8);
  6093. // Adjust index
  6094. index = index + 8;
  6095. }
  6096. return index;
  6097. }
  6098. function serializeNull(buffer, key, _, index, isArray) {
  6099. // Set long type
  6100. buffer[index++] = BSON_DATA_NULL;
  6101. // Number of written bytes
  6102. var numberOfWrittenBytes = !isArray
  6103. ? buffer.write(key, index, undefined, 'utf8')
  6104. : buffer.write(key, index, undefined, 'ascii');
  6105. // Encode the name
  6106. index = index + numberOfWrittenBytes;
  6107. buffer[index++] = 0;
  6108. return index;
  6109. }
  6110. function serializeBoolean(buffer, key, value, index, isArray) {
  6111. // Write the type
  6112. buffer[index++] = BSON_DATA_BOOLEAN;
  6113. // Number of written bytes
  6114. var numberOfWrittenBytes = !isArray
  6115. ? buffer.write(key, index, undefined, 'utf8')
  6116. : buffer.write(key, index, undefined, 'ascii');
  6117. // Encode the name
  6118. index = index + numberOfWrittenBytes;
  6119. buffer[index++] = 0;
  6120. // Encode the boolean value
  6121. buffer[index++] = value ? 1 : 0;
  6122. return index;
  6123. }
  6124. function serializeDate(buffer, key, value, index, isArray) {
  6125. // Write the type
  6126. buffer[index++] = BSON_DATA_DATE;
  6127. // Number of written bytes
  6128. var numberOfWrittenBytes = !isArray
  6129. ? buffer.write(key, index, undefined, 'utf8')
  6130. : buffer.write(key, index, undefined, 'ascii');
  6131. // Encode the name
  6132. index = index + numberOfWrittenBytes;
  6133. buffer[index++] = 0;
  6134. // Write the date
  6135. var dateInMilis = Long.fromNumber(value.getTime());
  6136. var lowBits = dateInMilis.getLowBits();
  6137. var highBits = dateInMilis.getHighBits();
  6138. // Encode low bits
  6139. buffer[index++] = lowBits & 0xff;
  6140. buffer[index++] = (lowBits >> 8) & 0xff;
  6141. buffer[index++] = (lowBits >> 16) & 0xff;
  6142. buffer[index++] = (lowBits >> 24) & 0xff;
  6143. // Encode high bits
  6144. buffer[index++] = highBits & 0xff;
  6145. buffer[index++] = (highBits >> 8) & 0xff;
  6146. buffer[index++] = (highBits >> 16) & 0xff;
  6147. buffer[index++] = (highBits >> 24) & 0xff;
  6148. return index;
  6149. }
  6150. function serializeRegExp(buffer, key, value, index, isArray) {
  6151. // Write the type
  6152. buffer[index++] = BSON_DATA_REGEXP;
  6153. // Number of written bytes
  6154. var numberOfWrittenBytes = !isArray
  6155. ? buffer.write(key, index, undefined, 'utf8')
  6156. : buffer.write(key, index, undefined, 'ascii');
  6157. // Encode the name
  6158. index = index + numberOfWrittenBytes;
  6159. buffer[index++] = 0;
  6160. if (value.source && value.source.match(regexp) != null) {
  6161. throw Error('value ' + value.source + ' must not contain null bytes');
  6162. }
  6163. // Adjust the index
  6164. index = index + buffer.write(value.source, index, undefined, 'utf8');
  6165. // Write zero
  6166. buffer[index++] = 0x00;
  6167. // Write the parameters
  6168. if (value.ignoreCase)
  6169. buffer[index++] = 0x69; // i
  6170. if (value.global)
  6171. buffer[index++] = 0x73; // s
  6172. if (value.multiline)
  6173. buffer[index++] = 0x6d; // m
  6174. // Add ending zero
  6175. buffer[index++] = 0x00;
  6176. return index;
  6177. }
  6178. function serializeBSONRegExp(buffer, key, value, index, isArray) {
  6179. // Write the type
  6180. buffer[index++] = BSON_DATA_REGEXP;
  6181. // Number of written bytes
  6182. var numberOfWrittenBytes = !isArray
  6183. ? buffer.write(key, index, undefined, 'utf8')
  6184. : buffer.write(key, index, undefined, 'ascii');
  6185. // Encode the name
  6186. index = index + numberOfWrittenBytes;
  6187. buffer[index++] = 0;
  6188. // Check the pattern for 0 bytes
  6189. if (value.pattern.match(regexp) != null) {
  6190. // The BSON spec doesn't allow keys with null bytes because keys are
  6191. // null-terminated.
  6192. throw Error('pattern ' + value.pattern + ' must not contain null bytes');
  6193. }
  6194. // Adjust the index
  6195. index = index + buffer.write(value.pattern, index, undefined, 'utf8');
  6196. // Write zero
  6197. buffer[index++] = 0x00;
  6198. // Write the options
  6199. index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8');
  6200. // Add ending zero
  6201. buffer[index++] = 0x00;
  6202. return index;
  6203. }
  6204. function serializeMinMax(buffer, key, value, index, isArray) {
  6205. // Write the type of either min or max key
  6206. if (value === null) {
  6207. buffer[index++] = BSON_DATA_NULL;
  6208. }
  6209. else if (value._bsontype === 'MinKey') {
  6210. buffer[index++] = BSON_DATA_MIN_KEY;
  6211. }
  6212. else {
  6213. buffer[index++] = BSON_DATA_MAX_KEY;
  6214. }
  6215. // Number of written bytes
  6216. var numberOfWrittenBytes = !isArray
  6217. ? buffer.write(key, index, undefined, 'utf8')
  6218. : buffer.write(key, index, undefined, 'ascii');
  6219. // Encode the name
  6220. index = index + numberOfWrittenBytes;
  6221. buffer[index++] = 0;
  6222. return index;
  6223. }
  6224. function serializeObjectId(buffer, key, value, index, isArray) {
  6225. // Write the type
  6226. buffer[index++] = BSON_DATA_OID;
  6227. // Number of written bytes
  6228. var numberOfWrittenBytes = !isArray
  6229. ? buffer.write(key, index, undefined, 'utf8')
  6230. : buffer.write(key, index, undefined, 'ascii');
  6231. // Encode the name
  6232. index = index + numberOfWrittenBytes;
  6233. buffer[index++] = 0;
  6234. // Write the objectId into the shared buffer
  6235. if (typeof value.id === 'string') {
  6236. buffer.write(value.id, index, undefined, 'binary');
  6237. }
  6238. else if (isUint8Array(value.id)) {
  6239. // Use the standard JS methods here because buffer.copy() is buggy with the
  6240. // browser polyfill
  6241. buffer.set(value.id.subarray(0, 12), index);
  6242. }
  6243. else {
  6244. throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
  6245. }
  6246. // Adjust index
  6247. return index + 12;
  6248. }
  6249. function serializeBuffer(buffer, key, value, index, isArray) {
  6250. // Write the type
  6251. buffer[index++] = BSON_DATA_BINARY;
  6252. // Number of written bytes
  6253. var numberOfWrittenBytes = !isArray
  6254. ? buffer.write(key, index, undefined, 'utf8')
  6255. : buffer.write(key, index, undefined, 'ascii');
  6256. // Encode the name
  6257. index = index + numberOfWrittenBytes;
  6258. buffer[index++] = 0;
  6259. // Get size of the buffer (current write point)
  6260. var size = value.length;
  6261. // Write the size of the string to buffer
  6262. buffer[index++] = size & 0xff;
  6263. buffer[index++] = (size >> 8) & 0xff;
  6264. buffer[index++] = (size >> 16) & 0xff;
  6265. buffer[index++] = (size >> 24) & 0xff;
  6266. // Write the default subtype
  6267. buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
  6268. // Copy the content form the binary field to the buffer
  6269. buffer.set(ensureBuffer(value), index);
  6270. // Adjust the index
  6271. index = index + size;
  6272. return index;
  6273. }
  6274. function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) {
  6275. if (checkKeys === void 0) { checkKeys = false; }
  6276. if (depth === void 0) { depth = 0; }
  6277. if (serializeFunctions === void 0) { serializeFunctions = false; }
  6278. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  6279. if (isArray === void 0) { isArray = false; }
  6280. if (path === void 0) { path = []; }
  6281. for (var i = 0; i < path.length; i++) {
  6282. if (path[i] === value)
  6283. throw new BSONError('cyclic dependency detected');
  6284. }
  6285. // Push value to stack
  6286. path.push(value);
  6287. // Write the type
  6288. buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
  6289. // Number of written bytes
  6290. var numberOfWrittenBytes = !isArray
  6291. ? buffer.write(key, index, undefined, 'utf8')
  6292. : buffer.write(key, index, undefined, 'ascii');
  6293. // Encode the name
  6294. index = index + numberOfWrittenBytes;
  6295. buffer[index++] = 0;
  6296. var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  6297. // Pop stack
  6298. path.pop();
  6299. return endIndex;
  6300. }
  6301. function serializeDecimal128(buffer, key, value, index, isArray) {
  6302. buffer[index++] = BSON_DATA_DECIMAL128;
  6303. // Number of written bytes
  6304. var numberOfWrittenBytes = !isArray
  6305. ? buffer.write(key, index, undefined, 'utf8')
  6306. : buffer.write(key, index, undefined, 'ascii');
  6307. // Encode the name
  6308. index = index + numberOfWrittenBytes;
  6309. buffer[index++] = 0;
  6310. // Write the data from the value
  6311. // Prefer the standard JS methods because their typechecking is not buggy,
  6312. // unlike the `buffer` polyfill's.
  6313. buffer.set(value.bytes.subarray(0, 16), index);
  6314. return index + 16;
  6315. }
  6316. function serializeLong(buffer, key, value, index, isArray) {
  6317. // Write the type
  6318. buffer[index++] =
  6319. value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
  6320. // Number of written bytes
  6321. var numberOfWrittenBytes = !isArray
  6322. ? buffer.write(key, index, undefined, 'utf8')
  6323. : buffer.write(key, index, undefined, 'ascii');
  6324. // Encode the name
  6325. index = index + numberOfWrittenBytes;
  6326. buffer[index++] = 0;
  6327. // Write the date
  6328. var lowBits = value.getLowBits();
  6329. var highBits = value.getHighBits();
  6330. // Encode low bits
  6331. buffer[index++] = lowBits & 0xff;
  6332. buffer[index++] = (lowBits >> 8) & 0xff;
  6333. buffer[index++] = (lowBits >> 16) & 0xff;
  6334. buffer[index++] = (lowBits >> 24) & 0xff;
  6335. // Encode high bits
  6336. buffer[index++] = highBits & 0xff;
  6337. buffer[index++] = (highBits >> 8) & 0xff;
  6338. buffer[index++] = (highBits >> 16) & 0xff;
  6339. buffer[index++] = (highBits >> 24) & 0xff;
  6340. return index;
  6341. }
  6342. function serializeInt32(buffer, key, value, index, isArray) {
  6343. value = value.valueOf();
  6344. // Set int type 32 bits or less
  6345. buffer[index++] = BSON_DATA_INT;
  6346. // Number of written bytes
  6347. var numberOfWrittenBytes = !isArray
  6348. ? buffer.write(key, index, undefined, 'utf8')
  6349. : buffer.write(key, index, undefined, 'ascii');
  6350. // Encode the name
  6351. index = index + numberOfWrittenBytes;
  6352. buffer[index++] = 0;
  6353. // Write the int value
  6354. buffer[index++] = value & 0xff;
  6355. buffer[index++] = (value >> 8) & 0xff;
  6356. buffer[index++] = (value >> 16) & 0xff;
  6357. buffer[index++] = (value >> 24) & 0xff;
  6358. return index;
  6359. }
  6360. function serializeDouble(buffer, key, value, index, isArray) {
  6361. // Encode as double
  6362. buffer[index++] = BSON_DATA_NUMBER;
  6363. // Number of written bytes
  6364. var numberOfWrittenBytes = !isArray
  6365. ? buffer.write(key, index, undefined, 'utf8')
  6366. : buffer.write(key, index, undefined, 'ascii');
  6367. // Encode the name
  6368. index = index + numberOfWrittenBytes;
  6369. buffer[index++] = 0;
  6370. // Write float
  6371. writeIEEE754(buffer, value.value, index, 'little', 52, 8);
  6372. // Adjust index
  6373. index = index + 8;
  6374. return index;
  6375. }
  6376. function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) {
  6377. buffer[index++] = BSON_DATA_CODE;
  6378. // Number of written bytes
  6379. var numberOfWrittenBytes = !isArray
  6380. ? buffer.write(key, index, undefined, 'utf8')
  6381. : buffer.write(key, index, undefined, 'ascii');
  6382. // Encode the name
  6383. index = index + numberOfWrittenBytes;
  6384. buffer[index++] = 0;
  6385. // Function string
  6386. var functionString = normalizedFunctionString(value);
  6387. // Write the string
  6388. var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  6389. // Write the size of the string to buffer
  6390. buffer[index] = size & 0xff;
  6391. buffer[index + 1] = (size >> 8) & 0xff;
  6392. buffer[index + 2] = (size >> 16) & 0xff;
  6393. buffer[index + 3] = (size >> 24) & 0xff;
  6394. // Update index
  6395. index = index + 4 + size - 1;
  6396. // Write zero
  6397. buffer[index++] = 0;
  6398. return index;
  6399. }
  6400. function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) {
  6401. if (checkKeys === void 0) { checkKeys = false; }
  6402. if (depth === void 0) { depth = 0; }
  6403. if (serializeFunctions === void 0) { serializeFunctions = false; }
  6404. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  6405. if (isArray === void 0) { isArray = false; }
  6406. if (value.scope && typeof value.scope === 'object') {
  6407. // Write the type
  6408. buffer[index++] = BSON_DATA_CODE_W_SCOPE;
  6409. // Number of written bytes
  6410. var numberOfWrittenBytes = !isArray
  6411. ? buffer.write(key, index, undefined, 'utf8')
  6412. : buffer.write(key, index, undefined, 'ascii');
  6413. // Encode the name
  6414. index = index + numberOfWrittenBytes;
  6415. buffer[index++] = 0;
  6416. // Starting index
  6417. var startIndex = index;
  6418. // Serialize the function
  6419. // Get the function string
  6420. var functionString = typeof value.code === 'string' ? value.code : value.code.toString();
  6421. // Index adjustment
  6422. index = index + 4;
  6423. // Write string into buffer
  6424. var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  6425. // Write the size of the string to buffer
  6426. buffer[index] = codeSize & 0xff;
  6427. buffer[index + 1] = (codeSize >> 8) & 0xff;
  6428. buffer[index + 2] = (codeSize >> 16) & 0xff;
  6429. buffer[index + 3] = (codeSize >> 24) & 0xff;
  6430. // Write end 0
  6431. buffer[index + 4 + codeSize - 1] = 0;
  6432. // Write the
  6433. index = index + codeSize + 4;
  6434. //
  6435. // Serialize the scope value
  6436. var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined);
  6437. index = endIndex - 1;
  6438. // Writ the total
  6439. var totalSize = endIndex - startIndex;
  6440. // Write the total size of the object
  6441. buffer[startIndex++] = totalSize & 0xff;
  6442. buffer[startIndex++] = (totalSize >> 8) & 0xff;
  6443. buffer[startIndex++] = (totalSize >> 16) & 0xff;
  6444. buffer[startIndex++] = (totalSize >> 24) & 0xff;
  6445. // Write trailing zero
  6446. buffer[index++] = 0;
  6447. }
  6448. else {
  6449. buffer[index++] = BSON_DATA_CODE;
  6450. // Number of written bytes
  6451. var numberOfWrittenBytes = !isArray
  6452. ? buffer.write(key, index, undefined, 'utf8')
  6453. : buffer.write(key, index, undefined, 'ascii');
  6454. // Encode the name
  6455. index = index + numberOfWrittenBytes;
  6456. buffer[index++] = 0;
  6457. // Function string
  6458. var functionString = value.code.toString();
  6459. // Write the string
  6460. var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  6461. // Write the size of the string to buffer
  6462. buffer[index] = size & 0xff;
  6463. buffer[index + 1] = (size >> 8) & 0xff;
  6464. buffer[index + 2] = (size >> 16) & 0xff;
  6465. buffer[index + 3] = (size >> 24) & 0xff;
  6466. // Update index
  6467. index = index + 4 + size - 1;
  6468. // Write zero
  6469. buffer[index++] = 0;
  6470. }
  6471. return index;
  6472. }
  6473. function serializeBinary(buffer, key, value, index, isArray) {
  6474. // Write the type
  6475. buffer[index++] = BSON_DATA_BINARY;
  6476. // Number of written bytes
  6477. var numberOfWrittenBytes = !isArray
  6478. ? buffer.write(key, index, undefined, 'utf8')
  6479. : buffer.write(key, index, undefined, 'ascii');
  6480. // Encode the name
  6481. index = index + numberOfWrittenBytes;
  6482. buffer[index++] = 0;
  6483. // Extract the buffer
  6484. var data = value.value(true);
  6485. // Calculate size
  6486. var size = value.position;
  6487. // Add the deprecated 02 type 4 bytes of size to total
  6488. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
  6489. size = size + 4;
  6490. // Write the size of the string to buffer
  6491. buffer[index++] = size & 0xff;
  6492. buffer[index++] = (size >> 8) & 0xff;
  6493. buffer[index++] = (size >> 16) & 0xff;
  6494. buffer[index++] = (size >> 24) & 0xff;
  6495. // Write the subtype to the buffer
  6496. buffer[index++] = value.sub_type;
  6497. // If we have binary type 2 the 4 first bytes are the size
  6498. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  6499. size = size - 4;
  6500. buffer[index++] = size & 0xff;
  6501. buffer[index++] = (size >> 8) & 0xff;
  6502. buffer[index++] = (size >> 16) & 0xff;
  6503. buffer[index++] = (size >> 24) & 0xff;
  6504. }
  6505. // Write the data to the object
  6506. buffer.set(data, index);
  6507. // Adjust the index
  6508. index = index + value.position;
  6509. return index;
  6510. }
  6511. function serializeSymbol(buffer, key, value, index, isArray) {
  6512. // Write the type
  6513. buffer[index++] = BSON_DATA_SYMBOL;
  6514. // Number of written bytes
  6515. var numberOfWrittenBytes = !isArray
  6516. ? buffer.write(key, index, undefined, 'utf8')
  6517. : buffer.write(key, index, undefined, 'ascii');
  6518. // Encode the name
  6519. index = index + numberOfWrittenBytes;
  6520. buffer[index++] = 0;
  6521. // Write the string
  6522. var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1;
  6523. // Write the size of the string to buffer
  6524. buffer[index] = size & 0xff;
  6525. buffer[index + 1] = (size >> 8) & 0xff;
  6526. buffer[index + 2] = (size >> 16) & 0xff;
  6527. buffer[index + 3] = (size >> 24) & 0xff;
  6528. // Update index
  6529. index = index + 4 + size - 1;
  6530. // Write zero
  6531. buffer[index++] = 0x00;
  6532. return index;
  6533. }
  6534. function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) {
  6535. // Write the type
  6536. buffer[index++] = BSON_DATA_OBJECT;
  6537. // Number of written bytes
  6538. var numberOfWrittenBytes = !isArray
  6539. ? buffer.write(key, index, undefined, 'utf8')
  6540. : buffer.write(key, index, undefined, 'ascii');
  6541. // Encode the name
  6542. index = index + numberOfWrittenBytes;
  6543. buffer[index++] = 0;
  6544. var startIndex = index;
  6545. var output = {
  6546. $ref: value.collection || value.namespace,
  6547. $id: value.oid
  6548. };
  6549. if (value.db != null) {
  6550. output.$db = value.db;
  6551. }
  6552. output = Object.assign(output, value.fields);
  6553. var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions);
  6554. // Calculate object size
  6555. var size = endIndex - startIndex;
  6556. // Write the size
  6557. buffer[startIndex++] = size & 0xff;
  6558. buffer[startIndex++] = (size >> 8) & 0xff;
  6559. buffer[startIndex++] = (size >> 16) & 0xff;
  6560. buffer[startIndex++] = (size >> 24) & 0xff;
  6561. // Set index
  6562. return endIndex;
  6563. }
  6564. function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  6565. if (checkKeys === void 0) { checkKeys = false; }
  6566. if (startingIndex === void 0) { startingIndex = 0; }
  6567. if (depth === void 0) { depth = 0; }
  6568. if (serializeFunctions === void 0) { serializeFunctions = false; }
  6569. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  6570. if (path === void 0) { path = []; }
  6571. startingIndex = startingIndex || 0;
  6572. path = path || [];
  6573. // Push the object to the path
  6574. path.push(object);
  6575. // Start place to serialize into
  6576. var index = startingIndex + 4;
  6577. // Special case isArray
  6578. if (Array.isArray(object)) {
  6579. // Get object keys
  6580. for (var i = 0; i < object.length; i++) {
  6581. var key = '' + i;
  6582. var value = object[i];
  6583. // Is there an override value
  6584. if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
  6585. value = value.toBSON();
  6586. }
  6587. if (typeof value === 'string') {
  6588. index = serializeString(buffer, key, value, index, true);
  6589. }
  6590. else if (typeof value === 'number') {
  6591. index = serializeNumber(buffer, key, value, index, true);
  6592. }
  6593. else if (typeof value === 'bigint') {
  6594. throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
  6595. }
  6596. else if (typeof value === 'boolean') {
  6597. index = serializeBoolean(buffer, key, value, index, true);
  6598. }
  6599. else if (value instanceof Date || isDate(value)) {
  6600. index = serializeDate(buffer, key, value, index, true);
  6601. }
  6602. else if (value === undefined) {
  6603. index = serializeNull(buffer, key, value, index, true);
  6604. }
  6605. else if (value === null) {
  6606. index = serializeNull(buffer, key, value, index, true);
  6607. }
  6608. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  6609. index = serializeObjectId(buffer, key, value, index, true);
  6610. }
  6611. else if (isUint8Array(value)) {
  6612. index = serializeBuffer(buffer, key, value, index, true);
  6613. }
  6614. else if (value instanceof RegExp || isRegExp(value)) {
  6615. index = serializeRegExp(buffer, key, value, index, true);
  6616. }
  6617. else if (typeof value === 'object' && value['_bsontype'] == null) {
  6618. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path);
  6619. }
  6620. else if (typeof value === 'object' &&
  6621. isBSONType(value) &&
  6622. value._bsontype === 'Decimal128') {
  6623. index = serializeDecimal128(buffer, key, value, index, true);
  6624. }
  6625. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  6626. index = serializeLong(buffer, key, value, index, true);
  6627. }
  6628. else if (value['_bsontype'] === 'Double') {
  6629. index = serializeDouble(buffer, key, value, index, true);
  6630. }
  6631. else if (typeof value === 'function' && serializeFunctions) {
  6632. index = serializeFunction(buffer, key, value, index, checkKeys, depth, true);
  6633. }
  6634. else if (value['_bsontype'] === 'Code') {
  6635. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true);
  6636. }
  6637. else if (value['_bsontype'] === 'Binary') {
  6638. index = serializeBinary(buffer, key, value, index, true);
  6639. }
  6640. else if (value['_bsontype'] === 'Symbol') {
  6641. index = serializeSymbol(buffer, key, value, index, true);
  6642. }
  6643. else if (value['_bsontype'] === 'DBRef') {
  6644. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true);
  6645. }
  6646. else if (value['_bsontype'] === 'BSONRegExp') {
  6647. index = serializeBSONRegExp(buffer, key, value, index, true);
  6648. }
  6649. else if (value['_bsontype'] === 'Int32') {
  6650. index = serializeInt32(buffer, key, value, index, true);
  6651. }
  6652. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  6653. index = serializeMinMax(buffer, key, value, index, true);
  6654. }
  6655. else if (typeof value['_bsontype'] !== 'undefined') {
  6656. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  6657. }
  6658. }
  6659. }
  6660. else if (object instanceof exports.Map || isMap(object)) {
  6661. var iterator = object.entries();
  6662. var done = false;
  6663. while (!done) {
  6664. // Unpack the next entry
  6665. var entry = iterator.next();
  6666. done = !!entry.done;
  6667. // Are we done, then skip and terminate
  6668. if (done)
  6669. continue;
  6670. // Get the entry values
  6671. var key = entry.value[0];
  6672. var value = entry.value[1];
  6673. // Check the type of the value
  6674. var type = typeof value;
  6675. // Check the key and throw error if it's illegal
  6676. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  6677. if (key.match(regexp) != null) {
  6678. // The BSON spec doesn't allow keys with null bytes because keys are
  6679. // null-terminated.
  6680. throw Error('key ' + key + ' must not contain null bytes');
  6681. }
  6682. if (checkKeys) {
  6683. if ('$' === key[0]) {
  6684. throw Error('key ' + key + " must not start with '$'");
  6685. }
  6686. else if (~key.indexOf('.')) {
  6687. throw Error('key ' + key + " must not contain '.'");
  6688. }
  6689. }
  6690. }
  6691. if (type === 'string') {
  6692. index = serializeString(buffer, key, value, index);
  6693. }
  6694. else if (type === 'number') {
  6695. index = serializeNumber(buffer, key, value, index);
  6696. }
  6697. else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) {
  6698. throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
  6699. }
  6700. else if (type === 'boolean') {
  6701. index = serializeBoolean(buffer, key, value, index);
  6702. }
  6703. else if (value instanceof Date || isDate(value)) {
  6704. index = serializeDate(buffer, key, value, index);
  6705. }
  6706. else if (value === null || (value === undefined && ignoreUndefined === false)) {
  6707. index = serializeNull(buffer, key, value, index);
  6708. }
  6709. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  6710. index = serializeObjectId(buffer, key, value, index);
  6711. }
  6712. else if (isUint8Array(value)) {
  6713. index = serializeBuffer(buffer, key, value, index);
  6714. }
  6715. else if (value instanceof RegExp || isRegExp(value)) {
  6716. index = serializeRegExp(buffer, key, value, index);
  6717. }
  6718. else if (type === 'object' && value['_bsontype'] == null) {
  6719. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  6720. }
  6721. else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  6722. index = serializeDecimal128(buffer, key, value, index);
  6723. }
  6724. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  6725. index = serializeLong(buffer, key, value, index);
  6726. }
  6727. else if (value['_bsontype'] === 'Double') {
  6728. index = serializeDouble(buffer, key, value, index);
  6729. }
  6730. else if (value['_bsontype'] === 'Code') {
  6731. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  6732. }
  6733. else if (typeof value === 'function' && serializeFunctions) {
  6734. index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
  6735. }
  6736. else if (value['_bsontype'] === 'Binary') {
  6737. index = serializeBinary(buffer, key, value, index);
  6738. }
  6739. else if (value['_bsontype'] === 'Symbol') {
  6740. index = serializeSymbol(buffer, key, value, index);
  6741. }
  6742. else if (value['_bsontype'] === 'DBRef') {
  6743. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
  6744. }
  6745. else if (value['_bsontype'] === 'BSONRegExp') {
  6746. index = serializeBSONRegExp(buffer, key, value, index);
  6747. }
  6748. else if (value['_bsontype'] === 'Int32') {
  6749. index = serializeInt32(buffer, key, value, index);
  6750. }
  6751. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  6752. index = serializeMinMax(buffer, key, value, index);
  6753. }
  6754. else if (typeof value['_bsontype'] !== 'undefined') {
  6755. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  6756. }
  6757. }
  6758. }
  6759. else {
  6760. if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
  6761. // Provided a custom serialization method
  6762. object = object.toBSON();
  6763. if (object != null && typeof object !== 'object') {
  6764. throw new BSONTypeError('toBSON function did not return an object');
  6765. }
  6766. }
  6767. // Iterate over all the keys
  6768. for (var key in object) {
  6769. var value = object[key];
  6770. // Is there an override value
  6771. if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
  6772. value = value.toBSON();
  6773. }
  6774. // Check the type of the value
  6775. var type = typeof value;
  6776. // Check the key and throw error if it's illegal
  6777. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  6778. if (key.match(regexp) != null) {
  6779. // The BSON spec doesn't allow keys with null bytes because keys are
  6780. // null-terminated.
  6781. throw Error('key ' + key + ' must not contain null bytes');
  6782. }
  6783. if (checkKeys) {
  6784. if ('$' === key[0]) {
  6785. throw Error('key ' + key + " must not start with '$'");
  6786. }
  6787. else if (~key.indexOf('.')) {
  6788. throw Error('key ' + key + " must not contain '.'");
  6789. }
  6790. }
  6791. }
  6792. if (type === 'string') {
  6793. index = serializeString(buffer, key, value, index);
  6794. }
  6795. else if (type === 'number') {
  6796. index = serializeNumber(buffer, key, value, index);
  6797. }
  6798. else if (type === 'bigint') {
  6799. throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
  6800. }
  6801. else if (type === 'boolean') {
  6802. index = serializeBoolean(buffer, key, value, index);
  6803. }
  6804. else if (value instanceof Date || isDate(value)) {
  6805. index = serializeDate(buffer, key, value, index);
  6806. }
  6807. else if (value === undefined) {
  6808. if (ignoreUndefined === false)
  6809. index = serializeNull(buffer, key, value, index);
  6810. }
  6811. else if (value === null) {
  6812. index = serializeNull(buffer, key, value, index);
  6813. }
  6814. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  6815. index = serializeObjectId(buffer, key, value, index);
  6816. }
  6817. else if (isUint8Array(value)) {
  6818. index = serializeBuffer(buffer, key, value, index);
  6819. }
  6820. else if (value instanceof RegExp || isRegExp(value)) {
  6821. index = serializeRegExp(buffer, key, value, index);
  6822. }
  6823. else if (type === 'object' && value['_bsontype'] == null) {
  6824. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  6825. }
  6826. else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  6827. index = serializeDecimal128(buffer, key, value, index);
  6828. }
  6829. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  6830. index = serializeLong(buffer, key, value, index);
  6831. }
  6832. else if (value['_bsontype'] === 'Double') {
  6833. index = serializeDouble(buffer, key, value, index);
  6834. }
  6835. else if (value['_bsontype'] === 'Code') {
  6836. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  6837. }
  6838. else if (typeof value === 'function' && serializeFunctions) {
  6839. index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
  6840. }
  6841. else if (value['_bsontype'] === 'Binary') {
  6842. index = serializeBinary(buffer, key, value, index);
  6843. }
  6844. else if (value['_bsontype'] === 'Symbol') {
  6845. index = serializeSymbol(buffer, key, value, index);
  6846. }
  6847. else if (value['_bsontype'] === 'DBRef') {
  6848. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
  6849. }
  6850. else if (value['_bsontype'] === 'BSONRegExp') {
  6851. index = serializeBSONRegExp(buffer, key, value, index);
  6852. }
  6853. else if (value['_bsontype'] === 'Int32') {
  6854. index = serializeInt32(buffer, key, value, index);
  6855. }
  6856. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  6857. index = serializeMinMax(buffer, key, value, index);
  6858. }
  6859. else if (typeof value['_bsontype'] !== 'undefined') {
  6860. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  6861. }
  6862. }
  6863. }
  6864. // Remove the path
  6865. path.pop();
  6866. // Final padding byte for object
  6867. buffer[index++] = 0x00;
  6868. // Final size
  6869. var size = index - startingIndex;
  6870. // Write the size of the object
  6871. buffer[startingIndex++] = size & 0xff;
  6872. buffer[startingIndex++] = (size >> 8) & 0xff;
  6873. buffer[startingIndex++] = (size >> 16) & 0xff;
  6874. buffer[startingIndex++] = (size >> 24) & 0xff;
  6875. return index;
  6876. }
  6877. /** @internal */
  6878. // Default Max Size
  6879. var MAXSIZE = 1024 * 1024 * 17;
  6880. // Current Internal Temporary Serialization Buffer
  6881. var buffer = buffer_1.alloc(MAXSIZE);
  6882. /**
  6883. * Sets the size of the internal serialization buffer.
  6884. *
  6885. * @param size - The desired size for the internal serialization buffer
  6886. * @public
  6887. */
  6888. function setInternalBufferSize(size) {
  6889. // Resize the internal serialization buffer if needed
  6890. if (buffer.length < size) {
  6891. buffer = buffer_1.alloc(size);
  6892. }
  6893. }
  6894. /**
  6895. * Serialize a Javascript object.
  6896. *
  6897. * @param object - the Javascript object to serialize.
  6898. * @returns Buffer object containing the serialized object.
  6899. * @public
  6900. */
  6901. function serialize(object, options) {
  6902. if (options === void 0) { options = {}; }
  6903. // Unpack the options
  6904. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  6905. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  6906. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  6907. var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
  6908. // Resize the internal serialization buffer if needed
  6909. if (buffer.length < minInternalBufferSize) {
  6910. buffer = buffer_1.alloc(minInternalBufferSize);
  6911. }
  6912. // Attempt to serialize
  6913. var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []);
  6914. // Create the final buffer
  6915. var finishedBuffer = buffer_1.alloc(serializationIndex);
  6916. // Copy into the finished buffer
  6917. buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length);
  6918. // Return the buffer
  6919. return finishedBuffer;
  6920. }
  6921. /**
  6922. * Serialize a Javascript object using a predefined Buffer and index into the buffer,
  6923. * useful when pre-allocating the space for serialization.
  6924. *
  6925. * @param object - the Javascript object to serialize.
  6926. * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object.
  6927. * @returns the index pointing to the last written byte in the buffer.
  6928. * @public
  6929. */
  6930. function serializeWithBufferAndIndex(object, finalBuffer, options) {
  6931. if (options === void 0) { options = {}; }
  6932. // Unpack the options
  6933. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  6934. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  6935. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  6936. var startIndex = typeof options.index === 'number' ? options.index : 0;
  6937. // Attempt to serialize
  6938. var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined);
  6939. buffer.copy(finalBuffer, startIndex, 0, serializationIndex);
  6940. // Return the index
  6941. return startIndex + serializationIndex - 1;
  6942. }
  6943. /**
  6944. * Deserialize data as BSON.
  6945. *
  6946. * @param buffer - the buffer containing the serialized set of BSON documents.
  6947. * @returns returns the deserialized Javascript Object.
  6948. * @public
  6949. */
  6950. function deserialize(buffer, options) {
  6951. if (options === void 0) { options = {}; }
  6952. return deserialize$1(buffer instanceof buffer_1 ? buffer : ensureBuffer(buffer), options);
  6953. }
  6954. /**
  6955. * Calculate the bson size for a passed in Javascript object.
  6956. *
  6957. * @param object - the Javascript object to calculate the BSON byte size for
  6958. * @returns size of BSON object in bytes
  6959. * @public
  6960. */
  6961. function calculateObjectSize(object, options) {
  6962. if (options === void 0) { options = {}; }
  6963. options = options || {};
  6964. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  6965. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  6966. return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined);
  6967. }
  6968. /**
  6969. * Deserialize stream data as BSON documents.
  6970. *
  6971. * @param data - the buffer containing the serialized set of BSON documents.
  6972. * @param startIndex - the start index in the data Buffer where the deserialization is to start.
  6973. * @param numberOfDocuments - number of documents to deserialize.
  6974. * @param documents - an array where to store the deserialized documents.
  6975. * @param docStartIndex - the index in the documents array from where to start inserting documents.
  6976. * @param options - additional options used for the deserialization.
  6977. * @returns next index in the buffer after deserialization **x** numbers of documents.
  6978. * @public
  6979. */
  6980. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  6981. var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
  6982. var bufferData = ensureBuffer(data);
  6983. var index = startIndex;
  6984. // Loop over all documents
  6985. for (var i = 0; i < numberOfDocuments; i++) {
  6986. // Find size of the document
  6987. var size = bufferData[index] |
  6988. (bufferData[index + 1] << 8) |
  6989. (bufferData[index + 2] << 16) |
  6990. (bufferData[index + 3] << 24);
  6991. // Update options with index
  6992. internalOptions.index = index;
  6993. // Parse the document at this point
  6994. documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions);
  6995. // Adjust index by the document size
  6996. index = index + size;
  6997. }
  6998. // Return object containing end index of parsing and list of documents
  6999. return index;
  7000. }
  7001. /**
  7002. * BSON default export
  7003. * @deprecated Please use named exports
  7004. * @privateRemarks
  7005. * We want to someday deprecate the default export,
  7006. * so none of the new TS types are being exported on the default
  7007. * @public
  7008. */
  7009. var BSON = {
  7010. Binary: Binary,
  7011. Code: Code,
  7012. DBRef: DBRef,
  7013. Decimal128: Decimal128,
  7014. Double: Double,
  7015. Int32: Int32,
  7016. Long: Long,
  7017. UUID: UUID,
  7018. Map: exports.Map,
  7019. MaxKey: MaxKey,
  7020. MinKey: MinKey,
  7021. ObjectId: ObjectId,
  7022. ObjectID: ObjectId,
  7023. BSONRegExp: BSONRegExp,
  7024. BSONSymbol: BSONSymbol,
  7025. Timestamp: Timestamp,
  7026. EJSON: exports.EJSON,
  7027. setInternalBufferSize: setInternalBufferSize,
  7028. serialize: serialize,
  7029. serializeWithBufferAndIndex: serializeWithBufferAndIndex,
  7030. deserialize: deserialize,
  7031. calculateObjectSize: calculateObjectSize,
  7032. deserializeStream: deserializeStream,
  7033. BSONError: BSONError,
  7034. BSONTypeError: BSONTypeError
  7035. };
  7036. exports.BSONError = BSONError;
  7037. exports.BSONRegExp = BSONRegExp;
  7038. exports.BSONSymbol = BSONSymbol;
  7039. exports.BSONTypeError = BSONTypeError;
  7040. exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = BSON_BINARY_SUBTYPE_BYTE_ARRAY;
  7041. exports.BSON_BINARY_SUBTYPE_COLUMN = BSON_BINARY_SUBTYPE_COLUMN;
  7042. exports.BSON_BINARY_SUBTYPE_DEFAULT = BSON_BINARY_SUBTYPE_DEFAULT;
  7043. exports.BSON_BINARY_SUBTYPE_ENCRYPTED = BSON_BINARY_SUBTYPE_ENCRYPTED;
  7044. exports.BSON_BINARY_SUBTYPE_FUNCTION = BSON_BINARY_SUBTYPE_FUNCTION;
  7045. exports.BSON_BINARY_SUBTYPE_MD5 = BSON_BINARY_SUBTYPE_MD5;
  7046. exports.BSON_BINARY_SUBTYPE_USER_DEFINED = BSON_BINARY_SUBTYPE_USER_DEFINED;
  7047. exports.BSON_BINARY_SUBTYPE_UUID = BSON_BINARY_SUBTYPE_UUID;
  7048. exports.BSON_BINARY_SUBTYPE_UUID_NEW = BSON_BINARY_SUBTYPE_UUID_NEW;
  7049. exports.BSON_DATA_ARRAY = BSON_DATA_ARRAY;
  7050. exports.BSON_DATA_BINARY = BSON_DATA_BINARY;
  7051. exports.BSON_DATA_BOOLEAN = BSON_DATA_BOOLEAN;
  7052. exports.BSON_DATA_CODE = BSON_DATA_CODE;
  7053. exports.BSON_DATA_CODE_W_SCOPE = BSON_DATA_CODE_W_SCOPE;
  7054. exports.BSON_DATA_DATE = BSON_DATA_DATE;
  7055. exports.BSON_DATA_DBPOINTER = BSON_DATA_DBPOINTER;
  7056. exports.BSON_DATA_DECIMAL128 = BSON_DATA_DECIMAL128;
  7057. exports.BSON_DATA_INT = BSON_DATA_INT;
  7058. exports.BSON_DATA_LONG = BSON_DATA_LONG;
  7059. exports.BSON_DATA_MAX_KEY = BSON_DATA_MAX_KEY;
  7060. exports.BSON_DATA_MIN_KEY = BSON_DATA_MIN_KEY;
  7061. exports.BSON_DATA_NULL = BSON_DATA_NULL;
  7062. exports.BSON_DATA_NUMBER = BSON_DATA_NUMBER;
  7063. exports.BSON_DATA_OBJECT = BSON_DATA_OBJECT;
  7064. exports.BSON_DATA_OID = BSON_DATA_OID;
  7065. exports.BSON_DATA_REGEXP = BSON_DATA_REGEXP;
  7066. exports.BSON_DATA_STRING = BSON_DATA_STRING;
  7067. exports.BSON_DATA_SYMBOL = BSON_DATA_SYMBOL;
  7068. exports.BSON_DATA_TIMESTAMP = BSON_DATA_TIMESTAMP;
  7069. exports.BSON_DATA_UNDEFINED = BSON_DATA_UNDEFINED;
  7070. exports.BSON_INT32_MAX = BSON_INT32_MAX;
  7071. exports.BSON_INT32_MIN = BSON_INT32_MIN;
  7072. exports.BSON_INT64_MAX = BSON_INT64_MAX;
  7073. exports.BSON_INT64_MIN = BSON_INT64_MIN;
  7074. exports.Binary = Binary;
  7075. exports.Code = Code;
  7076. exports.DBRef = DBRef;
  7077. exports.Decimal128 = Decimal128;
  7078. exports.Double = Double;
  7079. exports.Int32 = Int32;
  7080. exports.Long = Long;
  7081. exports.LongWithoutOverridesClass = LongWithoutOverridesClass;
  7082. exports.MaxKey = MaxKey;
  7083. exports.MinKey = MinKey;
  7084. exports.ObjectID = ObjectId;
  7085. exports.ObjectId = ObjectId;
  7086. exports.Timestamp = Timestamp;
  7087. exports.UUID = UUID;
  7088. exports.calculateObjectSize = calculateObjectSize;
  7089. exports.default = BSON;
  7090. exports.deserialize = deserialize;
  7091. exports.deserializeStream = deserializeStream;
  7092. exports.serialize = serialize;
  7093. exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
  7094. exports.setInternalBufferSize = setInternalBufferSize;
  7095. Object.defineProperty(exports, '__esModule', { value: true });
  7096. })));
  7097. //# sourceMappingURL=bson.browser.umd.js.map