bson.browser.esm.js 272 KB

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