bson.browser.esm.js 272 KB

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