bson.bundle.js 280 KB

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