bson.js 181 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('long'), require('buffer')) :
  3. typeof define === 'function' && define.amd ? define(['exports', 'long', 'buffer'], factory) :
  4. (factory((global.BSON = {}),global.long,global.Buffer));
  5. }(this, (function (exports,long,buffer) { 'use strict';
  6. long = long && long.hasOwnProperty('default') ? long['default'] : long;
  7. buffer = buffer && buffer.hasOwnProperty('default') ? buffer['default'] : buffer;
  8. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  9. function createCommonjsModule(fn, module) {
  10. return module = { exports: {} }, fn(module, module.exports), module.exports;
  11. }
  12. function getCjsExportFromNamespace (n) {
  13. return n && n.default || n;
  14. }
  15. var map = createCommonjsModule(function (module) {
  16. if (typeof commonjsGlobal.Map !== 'undefined') {
  17. module.exports = commonjsGlobal.Map;
  18. module.exports.Map = commonjsGlobal.Map;
  19. } else {
  20. // We will return a polyfill
  21. var Map = function Map(array) {
  22. this._keys = [];
  23. this._values = {};
  24. for (var i = 0; i < array.length; i++) {
  25. if (array[i] == null) continue; // skip null and undefined
  26. var entry = array[i];
  27. var key = entry[0];
  28. var value = entry[1]; // Add the key to the list of keys in order
  29. this._keys.push(key); // Add the key and value to the values dictionary with a point
  30. // to the location in the ordered keys list
  31. this._values[key] = {
  32. v: value,
  33. i: this._keys.length - 1
  34. };
  35. }
  36. };
  37. Map.prototype.clear = function () {
  38. this._keys = [];
  39. this._values = {};
  40. };
  41. Map.prototype.delete = function (key) {
  42. var value = this._values[key];
  43. if (value == null) return false; // Delete entry
  44. delete this._values[key]; // Remove the key from the ordered keys list
  45. this._keys.splice(value.i, 1);
  46. return true;
  47. };
  48. Map.prototype.entries = function () {
  49. var self = this;
  50. var index = 0;
  51. return {
  52. next: function next() {
  53. var key = self._keys[index++];
  54. return {
  55. value: key !== undefined ? [key, self._values[key].v] : undefined,
  56. done: key !== undefined ? false : true
  57. };
  58. }
  59. };
  60. };
  61. Map.prototype.forEach = function (callback, self) {
  62. self = self || this;
  63. for (var i = 0; i < this._keys.length; i++) {
  64. var key = this._keys[i]; // Call the forEach callback
  65. callback.call(self, this._values[key].v, key, self);
  66. }
  67. };
  68. Map.prototype.get = function (key) {
  69. return this._values[key] ? this._values[key].v : undefined;
  70. };
  71. Map.prototype.has = function (key) {
  72. return this._values[key] != null;
  73. };
  74. Map.prototype.keys = function () {
  75. var self = this;
  76. var index = 0;
  77. return {
  78. next: function next() {
  79. var key = self._keys[index++];
  80. return {
  81. value: key !== undefined ? key : undefined,
  82. done: key !== undefined ? false : true
  83. };
  84. }
  85. };
  86. };
  87. Map.prototype.set = function (key, value) {
  88. if (this._values[key]) {
  89. this._values[key].v = value;
  90. return this;
  91. } // Add the key to the list of keys in order
  92. this._keys.push(key); // Add the key and value to the values dictionary with a point
  93. // to the location in the ordered keys list
  94. this._values[key] = {
  95. v: value,
  96. i: this._keys.length - 1
  97. };
  98. return this;
  99. };
  100. Map.prototype.values = function () {
  101. var self = this;
  102. var index = 0;
  103. return {
  104. next: function next() {
  105. var key = self._keys[index++];
  106. return {
  107. value: key !== undefined ? self._values[key].v : undefined,
  108. done: key !== undefined ? false : true
  109. };
  110. }
  111. };
  112. }; // Last ismaster
  113. Object.defineProperty(Map.prototype, 'size', {
  114. enumerable: true,
  115. get: function get() {
  116. return this._keys.length;
  117. }
  118. });
  119. module.exports = Map;
  120. }
  121. });
  122. var map_1 = map.Map;
  123. /**
  124. * @ignore
  125. */
  126. long.prototype.toExtendedJSON = function (options) {
  127. if (options && options.relaxed) return this.toNumber();
  128. return {
  129. $numberLong: this.toString()
  130. };
  131. };
  132. /**
  133. * @ignore
  134. */
  135. long.fromExtendedJSON = function (doc, options) {
  136. var result = long.fromString(doc.$numberLong);
  137. return options && options.relaxed ? result.toNumber() : result;
  138. };
  139. Object.defineProperty(long.prototype, '_bsontype', {
  140. value: 'Long'
  141. });
  142. var long_1 = long;
  143. function _typeof(obj) {
  144. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  145. _typeof = function (obj) {
  146. return typeof obj;
  147. };
  148. } else {
  149. _typeof = function (obj) {
  150. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  151. };
  152. }
  153. return _typeof(obj);
  154. }
  155. function _classCallCheck(instance, Constructor) {
  156. if (!(instance instanceof Constructor)) {
  157. throw new TypeError("Cannot call a class as a function");
  158. }
  159. }
  160. function _defineProperties(target, props) {
  161. for (var i = 0; i < props.length; i++) {
  162. var descriptor = props[i];
  163. descriptor.enumerable = descriptor.enumerable || false;
  164. descriptor.configurable = true;
  165. if ("value" in descriptor) descriptor.writable = true;
  166. Object.defineProperty(target, descriptor.key, descriptor);
  167. }
  168. }
  169. function _createClass(Constructor, protoProps, staticProps) {
  170. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  171. if (staticProps) _defineProperties(Constructor, staticProps);
  172. return Constructor;
  173. }
  174. function _inherits(subClass, superClass) {
  175. if (typeof superClass !== "function" && superClass !== null) {
  176. throw new TypeError("Super expression must either be null or a function");
  177. }
  178. subClass.prototype = Object.create(superClass && superClass.prototype, {
  179. constructor: {
  180. value: subClass,
  181. writable: true,
  182. configurable: true
  183. }
  184. });
  185. if (superClass) _setPrototypeOf(subClass, superClass);
  186. }
  187. function _getPrototypeOf(o) {
  188. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  189. return o.__proto__ || Object.getPrototypeOf(o);
  190. };
  191. return _getPrototypeOf(o);
  192. }
  193. function _setPrototypeOf(o, p) {
  194. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  195. o.__proto__ = p;
  196. return o;
  197. };
  198. return _setPrototypeOf(o, p);
  199. }
  200. function _assertThisInitialized(self) {
  201. if (self === void 0) {
  202. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  203. }
  204. return self;
  205. }
  206. function _possibleConstructorReturn(self, call) {
  207. if (call && (typeof call === "object" || typeof call === "function")) {
  208. return call;
  209. }
  210. return _assertThisInitialized(self);
  211. }
  212. var Double =
  213. /*#__PURE__*/
  214. function () {
  215. /**
  216. * Create a Double type
  217. *
  218. * @param {number} value the number we want to represent as a double.
  219. * @return {Double}
  220. */
  221. function Double(value) {
  222. _classCallCheck(this, Double);
  223. this.value = value;
  224. }
  225. /**
  226. * Access the number value.
  227. *
  228. * @method
  229. * @return {number} returns the wrapped double number.
  230. */
  231. _createClass(Double, [{
  232. key: "valueOf",
  233. value: function valueOf() {
  234. return this.value;
  235. }
  236. /**
  237. * @ignore
  238. */
  239. }, {
  240. key: "toJSON",
  241. value: function toJSON() {
  242. return this.value;
  243. }
  244. /**
  245. * @ignore
  246. */
  247. }, {
  248. key: "toExtendedJSON",
  249. value: function toExtendedJSON(options) {
  250. if (options && options.relaxed && isFinite(this.value)) return this.value;
  251. return {
  252. $numberDouble: this.value.toString()
  253. };
  254. }
  255. /**
  256. * @ignore
  257. */
  258. }], [{
  259. key: "fromExtendedJSON",
  260. value: function fromExtendedJSON(doc, options) {
  261. return options && options.relaxed ? parseFloat(doc.$numberDouble) : new Double(parseFloat(doc.$numberDouble));
  262. }
  263. }]);
  264. return Double;
  265. }();
  266. Object.defineProperty(Double.prototype, '_bsontype', {
  267. value: 'Double'
  268. });
  269. var double_1 = Double;
  270. /**
  271. * @class
  272. * @param {number} low the low (signed) 32 bits of the Timestamp.
  273. * @param {number} high the high (signed) 32 bits of the Timestamp.
  274. * @return {Timestamp}
  275. */
  276. var Timestamp =
  277. /*#__PURE__*/
  278. function (_Long) {
  279. _inherits(Timestamp, _Long);
  280. function Timestamp(low, high) {
  281. var _this;
  282. _classCallCheck(this, Timestamp);
  283. if (low instanceof long_1) {
  284. _this = _possibleConstructorReturn(this, _getPrototypeOf(Timestamp).call(this, low.low, low.high));
  285. } else {
  286. _this = _possibleConstructorReturn(this, _getPrototypeOf(Timestamp).call(this, low, high));
  287. }
  288. return _possibleConstructorReturn(_this);
  289. }
  290. /**
  291. * Return the JSON value.
  292. *
  293. * @method
  294. * @return {String} the JSON representation.
  295. */
  296. _createClass(Timestamp, [{
  297. key: "toJSON",
  298. value: function toJSON() {
  299. return {
  300. $timestamp: this.toString()
  301. };
  302. }
  303. /**
  304. * Returns a Timestamp represented by the given (32-bit) integer value.
  305. *
  306. * @method
  307. * @param {number} value the 32-bit integer in question.
  308. * @return {Timestamp} the timestamp.
  309. */
  310. }, {
  311. key: "toExtendedJSON",
  312. /**
  313. * @ignore
  314. */
  315. value: function toExtendedJSON() {
  316. return {
  317. $timestamp: {
  318. t: this.high,
  319. i: this.low
  320. }
  321. };
  322. }
  323. /**
  324. * @ignore
  325. */
  326. }], [{
  327. key: "fromInt",
  328. value: function fromInt(value) {
  329. return new Timestamp(long_1.fromInt(value));
  330. }
  331. /**
  332. * Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned.
  333. *
  334. * @method
  335. * @param {number} value the number in question.
  336. * @return {Timestamp} the timestamp.
  337. */
  338. }, {
  339. key: "fromNumber",
  340. value: function fromNumber(value) {
  341. return new Timestamp(long_1.fromNumber(value));
  342. }
  343. /**
  344. * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
  345. *
  346. * @method
  347. * @param {number} lowBits the low 32-bits.
  348. * @param {number} highBits the high 32-bits.
  349. * @return {Timestamp} the timestamp.
  350. */
  351. }, {
  352. key: "fromBits",
  353. value: function fromBits(lowBits, highBits) {
  354. return new Timestamp(lowBits, highBits);
  355. }
  356. /**
  357. * Returns a Timestamp from the given string, optionally using the given radix.
  358. *
  359. * @method
  360. * @param {String} str the textual representation of the Timestamp.
  361. * @param {number} [opt_radix] the radix in which the text is written.
  362. * @return {Timestamp} the timestamp.
  363. */
  364. }, {
  365. key: "fromString",
  366. value: function fromString(str, opt_radix) {
  367. return new Timestamp(long_1.fromString(str, opt_radix));
  368. }
  369. }, {
  370. key: "fromExtendedJSON",
  371. value: function fromExtendedJSON(doc) {
  372. return new Timestamp(doc.$timestamp.i, doc.$timestamp.t);
  373. }
  374. }]);
  375. return Timestamp;
  376. }(long_1);
  377. Object.defineProperty(Timestamp.prototype, '_bsontype', {
  378. value: 'Timestamp'
  379. });
  380. var timestamp = Timestamp;
  381. var empty = {};
  382. var empty$1 = /*#__PURE__*/Object.freeze({
  383. default: empty
  384. });
  385. var require$$0 = getCjsExportFromNamespace(empty$1);
  386. /* global window */
  387. /**
  388. * Normalizes our expected stringified form of a function across versions of node
  389. * @param {Function} fn The function to stringify
  390. */
  391. function normalizedFunctionString(fn) {
  392. return fn.toString().replace('function(', 'function (');
  393. }
  394. function insecureRandomBytes(size) {
  395. var result = new Uint8Array(size);
  396. for (var i = 0; i < size; ++i) {
  397. result[i] = Math.floor(Math.random() * 256);
  398. }
  399. return result;
  400. }
  401. var randomBytes = insecureRandomBytes;
  402. if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
  403. randomBytes = function randomBytes(size) {
  404. return window.crypto.getRandomValues(new Uint8Array(size));
  405. };
  406. } else {
  407. try {
  408. randomBytes = require$$0.randomBytes;
  409. } catch (e) {} // keep the fallback
  410. // NOTE: in transpiled cases the above require might return null/undefined
  411. if (randomBytes == null) {
  412. randomBytes = insecureRandomBytes;
  413. }
  414. }
  415. var utils = {
  416. normalizedFunctionString: normalizedFunctionString,
  417. randomBytes: randomBytes
  418. };
  419. // shim for using process in browser
  420. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  421. function defaultSetTimout() {
  422. throw new Error('setTimeout has not been defined');
  423. }
  424. function defaultClearTimeout() {
  425. throw new Error('clearTimeout has not been defined');
  426. }
  427. var cachedSetTimeout = defaultSetTimout;
  428. var cachedClearTimeout = defaultClearTimeout;
  429. if (typeof global.setTimeout === 'function') {
  430. cachedSetTimeout = setTimeout;
  431. }
  432. if (typeof global.clearTimeout === 'function') {
  433. cachedClearTimeout = clearTimeout;
  434. }
  435. function runTimeout(fun) {
  436. if (cachedSetTimeout === setTimeout) {
  437. //normal enviroments in sane situations
  438. return setTimeout(fun, 0);
  439. } // if setTimeout wasn't available but was latter defined
  440. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  441. cachedSetTimeout = setTimeout;
  442. return setTimeout(fun, 0);
  443. }
  444. try {
  445. // when when somebody has screwed with setTimeout but no I.E. maddness
  446. return cachedSetTimeout(fun, 0);
  447. } catch (e) {
  448. try {
  449. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  450. return cachedSetTimeout.call(null, fun, 0);
  451. } catch (e) {
  452. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  453. return cachedSetTimeout.call(this, fun, 0);
  454. }
  455. }
  456. }
  457. function runClearTimeout(marker) {
  458. if (cachedClearTimeout === clearTimeout) {
  459. //normal enviroments in sane situations
  460. return clearTimeout(marker);
  461. } // if clearTimeout wasn't available but was latter defined
  462. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  463. cachedClearTimeout = clearTimeout;
  464. return clearTimeout(marker);
  465. }
  466. try {
  467. // when when somebody has screwed with setTimeout but no I.E. maddness
  468. return cachedClearTimeout(marker);
  469. } catch (e) {
  470. try {
  471. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  472. return cachedClearTimeout.call(null, marker);
  473. } catch (e) {
  474. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  475. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  476. return cachedClearTimeout.call(this, marker);
  477. }
  478. }
  479. }
  480. var queue = [];
  481. var draining = false;
  482. var currentQueue;
  483. var queueIndex = -1;
  484. function cleanUpNextTick() {
  485. if (!draining || !currentQueue) {
  486. return;
  487. }
  488. draining = false;
  489. if (currentQueue.length) {
  490. queue = currentQueue.concat(queue);
  491. } else {
  492. queueIndex = -1;
  493. }
  494. if (queue.length) {
  495. drainQueue();
  496. }
  497. }
  498. function drainQueue() {
  499. if (draining) {
  500. return;
  501. }
  502. var timeout = runTimeout(cleanUpNextTick);
  503. draining = true;
  504. var len = queue.length;
  505. while (len) {
  506. currentQueue = queue;
  507. queue = [];
  508. while (++queueIndex < len) {
  509. if (currentQueue) {
  510. currentQueue[queueIndex].run();
  511. }
  512. }
  513. queueIndex = -1;
  514. len = queue.length;
  515. }
  516. currentQueue = null;
  517. draining = false;
  518. runClearTimeout(timeout);
  519. }
  520. function nextTick(fun) {
  521. var args = new Array(arguments.length - 1);
  522. if (arguments.length > 1) {
  523. for (var i = 1; i < arguments.length; i++) {
  524. args[i - 1] = arguments[i];
  525. }
  526. }
  527. queue.push(new Item(fun, args));
  528. if (queue.length === 1 && !draining) {
  529. runTimeout(drainQueue);
  530. }
  531. } // v8 likes predictible objects
  532. function Item(fun, array) {
  533. this.fun = fun;
  534. this.array = array;
  535. }
  536. Item.prototype.run = function () {
  537. this.fun.apply(null, this.array);
  538. };
  539. var title = 'browser';
  540. var platform = 'browser';
  541. var browser = true;
  542. var env = {};
  543. var argv = [];
  544. var version = ''; // empty string to avoid regexp issues
  545. var versions = {};
  546. var release = {};
  547. var config = {};
  548. function noop() {}
  549. var on = noop;
  550. var addListener = noop;
  551. var once = noop;
  552. var off = noop;
  553. var removeListener = noop;
  554. var removeAllListeners = noop;
  555. var emit = noop;
  556. function binding(name) {
  557. throw new Error('process.binding is not supported');
  558. }
  559. function cwd() {
  560. return '/';
  561. }
  562. function chdir(dir) {
  563. throw new Error('process.chdir is not supported');
  564. }
  565. function umask() {
  566. return 0;
  567. } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  568. var performance = global.performance || {};
  569. var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
  570. return new Date().getTime();
  571. }; // generate timestamp or delta
  572. // see http://nodejs.org/api/process.html#process_process_hrtime
  573. function hrtime(previousTimestamp) {
  574. var clocktime = performanceNow.call(performance) * 1e-3;
  575. var seconds = Math.floor(clocktime);
  576. var nanoseconds = Math.floor(clocktime % 1 * 1e9);
  577. if (previousTimestamp) {
  578. seconds = seconds - previousTimestamp[0];
  579. nanoseconds = nanoseconds - previousTimestamp[1];
  580. if (nanoseconds < 0) {
  581. seconds--;
  582. nanoseconds += 1e9;
  583. }
  584. }
  585. return [seconds, nanoseconds];
  586. }
  587. var startTime = new Date();
  588. function uptime() {
  589. var currentTime = new Date();
  590. var dif = currentTime - startTime;
  591. return dif / 1000;
  592. }
  593. var process = {
  594. nextTick: nextTick,
  595. title: title,
  596. browser: browser,
  597. env: env,
  598. argv: argv,
  599. version: version,
  600. versions: versions,
  601. on: on,
  602. addListener: addListener,
  603. once: once,
  604. off: off,
  605. removeListener: removeListener,
  606. removeAllListeners: removeAllListeners,
  607. emit: emit,
  608. binding: binding,
  609. cwd: cwd,
  610. chdir: chdir,
  611. umask: umask,
  612. hrtime: hrtime,
  613. platform: platform,
  614. release: release,
  615. config: config,
  616. uptime: uptime
  617. };
  618. var inherits;
  619. if (typeof Object.create === 'function') {
  620. inherits = function inherits(ctor, superCtor) {
  621. // implementation from standard node.js 'util' module
  622. ctor.super_ = superCtor;
  623. ctor.prototype = Object.create(superCtor.prototype, {
  624. constructor: {
  625. value: ctor,
  626. enumerable: false,
  627. writable: true,
  628. configurable: true
  629. }
  630. });
  631. };
  632. } else {
  633. inherits = function inherits(ctor, superCtor) {
  634. ctor.super_ = superCtor;
  635. var TempCtor = function TempCtor() {};
  636. TempCtor.prototype = superCtor.prototype;
  637. ctor.prototype = new TempCtor();
  638. ctor.prototype.constructor = ctor;
  639. };
  640. }
  641. var inherits$1 = inherits;
  642. var formatRegExp = /%[sdj%]/g;
  643. function format(f) {
  644. if (!isString(f)) {
  645. var objects = [];
  646. for (var i = 0; i < arguments.length; i++) {
  647. objects.push(inspect(arguments[i]));
  648. }
  649. return objects.join(' ');
  650. }
  651. var i = 1;
  652. var args = arguments;
  653. var len = args.length;
  654. var str = String(f).replace(formatRegExp, function (x) {
  655. if (x === '%%') return '%';
  656. if (i >= len) return x;
  657. switch (x) {
  658. case '%s':
  659. return String(args[i++]);
  660. case '%d':
  661. return Number(args[i++]);
  662. case '%j':
  663. try {
  664. return JSON.stringify(args[i++]);
  665. } catch (_) {
  666. return '[Circular]';
  667. }
  668. default:
  669. return x;
  670. }
  671. });
  672. for (var x = args[i]; i < len; x = args[++i]) {
  673. if (isNull(x) || !isObject(x)) {
  674. str += ' ' + x;
  675. } else {
  676. str += ' ' + inspect(x);
  677. }
  678. }
  679. return str;
  680. }
  681. // Returns a modified function which warns once by default.
  682. // If --no-deprecation is set, then it is a no-op.
  683. function deprecate(fn, msg) {
  684. // Allow for deprecating things in the process of starting up.
  685. if (isUndefined(global.process)) {
  686. return function () {
  687. return deprecate(fn, msg).apply(this, arguments);
  688. };
  689. }
  690. var warned = false;
  691. function deprecated() {
  692. if (!warned) {
  693. {
  694. console.error(msg);
  695. }
  696. warned = true;
  697. }
  698. return fn.apply(this, arguments);
  699. }
  700. return deprecated;
  701. }
  702. var debugs = {};
  703. var debugEnviron;
  704. function debuglog(set) {
  705. if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || '';
  706. set = set.toUpperCase();
  707. if (!debugs[set]) {
  708. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  709. var pid = 0;
  710. debugs[set] = function () {
  711. var msg = format.apply(null, arguments);
  712. console.error('%s %d: %s', set, pid, msg);
  713. };
  714. } else {
  715. debugs[set] = function () {};
  716. }
  717. }
  718. return debugs[set];
  719. }
  720. /**
  721. * Echos the value of a value. Trys to print the value out
  722. * in the best way possible given the different types.
  723. *
  724. * @param {Object} obj The object to print out.
  725. * @param {Object} opts Optional options object that alters the output.
  726. */
  727. /* legacy: obj, showHidden, depth, colors*/
  728. function inspect(obj, opts) {
  729. // default options
  730. var ctx = {
  731. seen: [],
  732. stylize: stylizeNoColor
  733. }; // legacy...
  734. if (arguments.length >= 3) ctx.depth = arguments[2];
  735. if (arguments.length >= 4) ctx.colors = arguments[3];
  736. if (isBoolean(opts)) {
  737. // legacy...
  738. ctx.showHidden = opts;
  739. } else if (opts) {
  740. // got an "options" object
  741. _extend(ctx, opts);
  742. } // set default options
  743. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  744. if (isUndefined(ctx.depth)) ctx.depth = 2;
  745. if (isUndefined(ctx.colors)) ctx.colors = false;
  746. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  747. if (ctx.colors) ctx.stylize = stylizeWithColor;
  748. return formatValue(ctx, obj, ctx.depth);
  749. } // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  750. inspect.colors = {
  751. 'bold': [1, 22],
  752. 'italic': [3, 23],
  753. 'underline': [4, 24],
  754. 'inverse': [7, 27],
  755. 'white': [37, 39],
  756. 'grey': [90, 39],
  757. 'black': [30, 39],
  758. 'blue': [34, 39],
  759. 'cyan': [36, 39],
  760. 'green': [32, 39],
  761. 'magenta': [35, 39],
  762. 'red': [31, 39],
  763. 'yellow': [33, 39]
  764. }; // Don't use 'blue' not visible on cmd.exe
  765. inspect.styles = {
  766. 'special': 'cyan',
  767. 'number': 'yellow',
  768. 'boolean': 'yellow',
  769. 'undefined': 'grey',
  770. 'null': 'bold',
  771. 'string': 'green',
  772. 'date': 'magenta',
  773. // "name": intentionally not styling
  774. 'regexp': 'red'
  775. };
  776. function stylizeWithColor(str, styleType) {
  777. var style = inspect.styles[styleType];
  778. if (style) {
  779. return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm';
  780. } else {
  781. return str;
  782. }
  783. }
  784. function stylizeNoColor(str, styleType) {
  785. return str;
  786. }
  787. function arrayToHash(array) {
  788. var hash = {};
  789. array.forEach(function (val, idx) {
  790. hash[val] = true;
  791. });
  792. return hash;
  793. }
  794. function formatValue(ctx, value, recurseTimes) {
  795. // Provide a hook for user-specified inspect functions.
  796. // Check that value is an object with an inspect function on it
  797. if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special
  798. value.inspect !== inspect && // Also filter out any prototype objects using the circular check.
  799. !(value.constructor && value.constructor.prototype === value)) {
  800. var ret = value.inspect(recurseTimes, ctx);
  801. if (!isString(ret)) {
  802. ret = formatValue(ctx, ret, recurseTimes);
  803. }
  804. return ret;
  805. } // Primitive types cannot have properties
  806. var primitive = formatPrimitive(ctx, value);
  807. if (primitive) {
  808. return primitive;
  809. } // Look up the keys of the object.
  810. var keys = Object.keys(value);
  811. var visibleKeys = arrayToHash(keys);
  812. if (ctx.showHidden) {
  813. keys = Object.getOwnPropertyNames(value);
  814. } // IE doesn't make error fields non-enumerable
  815. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  816. if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  817. return formatError(value);
  818. } // Some type of object without properties can be shortcutted.
  819. if (keys.length === 0) {
  820. if (isFunction(value)) {
  821. var name = value.name ? ': ' + value.name : '';
  822. return ctx.stylize('[Function' + name + ']', 'special');
  823. }
  824. if (isRegExp(value)) {
  825. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  826. }
  827. if (isDate(value)) {
  828. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  829. }
  830. if (isError(value)) {
  831. return formatError(value);
  832. }
  833. }
  834. var base = '',
  835. array = false,
  836. braces = ['{', '}']; // Make Array say that they are Array
  837. if (isArray(value)) {
  838. array = true;
  839. braces = ['[', ']'];
  840. } // Make functions say that they are functions
  841. if (isFunction(value)) {
  842. var n = value.name ? ': ' + value.name : '';
  843. base = ' [Function' + n + ']';
  844. } // Make RegExps say that they are RegExps
  845. if (isRegExp(value)) {
  846. base = ' ' + RegExp.prototype.toString.call(value);
  847. } // Make dates with properties first say the date
  848. if (isDate(value)) {
  849. base = ' ' + Date.prototype.toUTCString.call(value);
  850. } // Make error with message first say the error
  851. if (isError(value)) {
  852. base = ' ' + formatError(value);
  853. }
  854. if (keys.length === 0 && (!array || value.length == 0)) {
  855. return braces[0] + base + braces[1];
  856. }
  857. if (recurseTimes < 0) {
  858. if (isRegExp(value)) {
  859. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  860. } else {
  861. return ctx.stylize('[Object]', 'special');
  862. }
  863. }
  864. ctx.seen.push(value);
  865. var output;
  866. if (array) {
  867. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  868. } else {
  869. output = keys.map(function (key) {
  870. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  871. });
  872. }
  873. ctx.seen.pop();
  874. return reduceToSingleString(output, base, braces);
  875. }
  876. function formatPrimitive(ctx, value) {
  877. if (isUndefined(value)) return ctx.stylize('undefined', 'undefined');
  878. if (isString(value)) {
  879. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\'';
  880. return ctx.stylize(simple, 'string');
  881. }
  882. if (isNumber(value)) return ctx.stylize('' + value, 'number');
  883. if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here.
  884. if (isNull(value)) return ctx.stylize('null', 'null');
  885. }
  886. function formatError(value) {
  887. return '[' + Error.prototype.toString.call(value) + ']';
  888. }
  889. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  890. var output = [];
  891. for (var i = 0, l = value.length; i < l; ++i) {
  892. if (hasOwnProperty(value, String(i))) {
  893. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
  894. } else {
  895. output.push('');
  896. }
  897. }
  898. keys.forEach(function (key) {
  899. if (!key.match(/^\d+$/)) {
  900. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
  901. }
  902. });
  903. return output;
  904. }
  905. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  906. var name, str, desc;
  907. desc = Object.getOwnPropertyDescriptor(value, key) || {
  908. value: value[key]
  909. };
  910. if (desc.get) {
  911. if (desc.set) {
  912. str = ctx.stylize('[Getter/Setter]', 'special');
  913. } else {
  914. str = ctx.stylize('[Getter]', 'special');
  915. }
  916. } else {
  917. if (desc.set) {
  918. str = ctx.stylize('[Setter]', 'special');
  919. }
  920. }
  921. if (!hasOwnProperty(visibleKeys, key)) {
  922. name = '[' + key + ']';
  923. }
  924. if (!str) {
  925. if (ctx.seen.indexOf(desc.value) < 0) {
  926. if (isNull(recurseTimes)) {
  927. str = formatValue(ctx, desc.value, null);
  928. } else {
  929. str = formatValue(ctx, desc.value, recurseTimes - 1);
  930. }
  931. if (str.indexOf('\n') > -1) {
  932. if (array) {
  933. str = str.split('\n').map(function (line) {
  934. return ' ' + line;
  935. }).join('\n').substr(2);
  936. } else {
  937. str = '\n' + str.split('\n').map(function (line) {
  938. return ' ' + line;
  939. }).join('\n');
  940. }
  941. }
  942. } else {
  943. str = ctx.stylize('[Circular]', 'special');
  944. }
  945. }
  946. if (isUndefined(name)) {
  947. if (array && key.match(/^\d+$/)) {
  948. return str;
  949. }
  950. name = JSON.stringify('' + key);
  951. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  952. name = name.substr(1, name.length - 2);
  953. name = ctx.stylize(name, 'name');
  954. } else {
  955. name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
  956. name = ctx.stylize(name, 'string');
  957. }
  958. }
  959. return name + ': ' + str;
  960. }
  961. function reduceToSingleString(output, base, braces) {
  962. var length = output.reduce(function (prev, cur) {
  963. if (cur.indexOf('\n') >= 0) ;
  964. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  965. }, 0);
  966. if (length > 60) {
  967. return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1];
  968. }
  969. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  970. } // NOTE: These type checking functions intentionally don't use `instanceof`
  971. // because it is fragile and can be easily faked with `Object.create()`.
  972. function isArray(ar) {
  973. return Array.isArray(ar);
  974. }
  975. function isBoolean(arg) {
  976. return typeof arg === 'boolean';
  977. }
  978. function isNull(arg) {
  979. return arg === null;
  980. }
  981. function isNullOrUndefined(arg) {
  982. return arg == null;
  983. }
  984. function isNumber(arg) {
  985. return typeof arg === 'number';
  986. }
  987. function isString(arg) {
  988. return typeof arg === 'string';
  989. }
  990. function isSymbol(arg) {
  991. return _typeof(arg) === 'symbol';
  992. }
  993. function isUndefined(arg) {
  994. return arg === void 0;
  995. }
  996. function isRegExp(re) {
  997. return isObject(re) && objectToString(re) === '[object RegExp]';
  998. }
  999. function isObject(arg) {
  1000. return _typeof(arg) === 'object' && arg !== null;
  1001. }
  1002. function isDate(d) {
  1003. return isObject(d) && objectToString(d) === '[object Date]';
  1004. }
  1005. function isError(e) {
  1006. return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error);
  1007. }
  1008. function isFunction(arg) {
  1009. return typeof arg === 'function';
  1010. }
  1011. function isPrimitive(arg) {
  1012. return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || _typeof(arg) === 'symbol' || // ES6 symbol
  1013. typeof arg === 'undefined';
  1014. }
  1015. function isBuffer(maybeBuf) {
  1016. return Buffer.isBuffer(maybeBuf);
  1017. }
  1018. function objectToString(o) {
  1019. return Object.prototype.toString.call(o);
  1020. }
  1021. function pad(n) {
  1022. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  1023. }
  1024. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34
  1025. function timestamp$1() {
  1026. var d = new Date();
  1027. var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':');
  1028. return [d.getDate(), months[d.getMonth()], time].join(' ');
  1029. } // log is just a thin wrapper to console.log that prepends a timestamp
  1030. function log() {
  1031. console.log('%s - %s', timestamp$1(), format.apply(null, arguments));
  1032. }
  1033. function _extend(origin, add) {
  1034. // Don't do anything if add isn't an object
  1035. if (!add || !isObject(add)) return origin;
  1036. var keys = Object.keys(add);
  1037. var i = keys.length;
  1038. while (i--) {
  1039. origin[keys[i]] = add[keys[i]];
  1040. }
  1041. return origin;
  1042. }
  1043. function hasOwnProperty(obj, prop) {
  1044. return Object.prototype.hasOwnProperty.call(obj, prop);
  1045. }
  1046. var util = {
  1047. inherits: inherits$1,
  1048. _extend: _extend,
  1049. log: log,
  1050. isBuffer: isBuffer,
  1051. isPrimitive: isPrimitive,
  1052. isFunction: isFunction,
  1053. isError: isError,
  1054. isDate: isDate,
  1055. isObject: isObject,
  1056. isRegExp: isRegExp,
  1057. isUndefined: isUndefined,
  1058. isSymbol: isSymbol,
  1059. isString: isString,
  1060. isNumber: isNumber,
  1061. isNullOrUndefined: isNullOrUndefined,
  1062. isNull: isNull,
  1063. isBoolean: isBoolean,
  1064. isArray: isArray,
  1065. inspect: inspect,
  1066. deprecate: deprecate,
  1067. format: format,
  1068. debuglog: debuglog
  1069. };
  1070. var util$1 = /*#__PURE__*/Object.freeze({
  1071. format: format,
  1072. deprecate: deprecate,
  1073. debuglog: debuglog,
  1074. inspect: inspect,
  1075. isArray: isArray,
  1076. isBoolean: isBoolean,
  1077. isNull: isNull,
  1078. isNullOrUndefined: isNullOrUndefined,
  1079. isNumber: isNumber,
  1080. isString: isString,
  1081. isSymbol: isSymbol,
  1082. isUndefined: isUndefined,
  1083. isRegExp: isRegExp,
  1084. isObject: isObject,
  1085. isDate: isDate,
  1086. isError: isError,
  1087. isFunction: isFunction,
  1088. isPrimitive: isPrimitive,
  1089. isBuffer: isBuffer,
  1090. log: log,
  1091. inherits: inherits$1,
  1092. _extend: _extend,
  1093. default: util
  1094. });
  1095. var require$$2 = getCjsExportFromNamespace(util$1);
  1096. var Buffer$1 = buffer.Buffer;
  1097. var randomBytes$1 = utils.randomBytes;
  1098. var deprecate$1 = require$$2.deprecate; // constants
  1099. var PROCESS_UNIQUE = randomBytes$1(5); // Regular expression that checks for hex value
  1100. var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
  1101. var hasBufferType = false; // Check if buffer exists
  1102. try {
  1103. if (Buffer$1 && Buffer$1.from) hasBufferType = true;
  1104. } catch (err) {
  1105. hasBufferType = false;
  1106. } // Precomputed hex table enables speedy hex string conversion
  1107. var hexTable = [];
  1108. for (var _i = 0; _i < 256; _i++) {
  1109. hexTable[_i] = (_i <= 15 ? '0' : '') + _i.toString(16);
  1110. } // Lookup tables
  1111. var decodeLookup = [];
  1112. var i = 0;
  1113. while (i < 10) {
  1114. decodeLookup[0x30 + i] = i++;
  1115. }
  1116. while (i < 16) {
  1117. decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;
  1118. }
  1119. var _Buffer = Buffer$1;
  1120. function convertToHex(bytes) {
  1121. return bytes.toString('hex');
  1122. }
  1123. function makeObjectIdError(invalidString, index) {
  1124. var invalidCharacter = invalidString[index];
  1125. return new TypeError("ObjectId string \"".concat(invalidString, "\" contains invalid character \"").concat(invalidCharacter, "\" with character code (").concat(invalidString.charCodeAt(index), "). All character codes for a non-hex string must be less than 256."));
  1126. }
  1127. /**
  1128. * A class representation of the BSON ObjectId type.
  1129. */
  1130. var ObjectId =
  1131. /*#__PURE__*/
  1132. function () {
  1133. /**
  1134. * Create an ObjectId type
  1135. *
  1136. * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
  1137. * @property {number} generationTime The generation time of this ObjectId instance
  1138. * @return {ObjectId} instance of ObjectId.
  1139. */
  1140. function ObjectId(id) {
  1141. _classCallCheck(this, ObjectId);
  1142. // Duck-typing to support ObjectId from different npm packages
  1143. if (id instanceof ObjectId) return id; // The most common usecase (blank id, new objectId instance)
  1144. if (id == null || typeof id === 'number') {
  1145. // Generate a new id
  1146. this.id = this.generate(id); // If we are caching the hex string
  1147. if (ObjectId.cacheHexString) this.__id = this.toString('hex'); // Return the object
  1148. return;
  1149. } // Check if the passed in id is valid
  1150. var valid = ObjectId.isValid(id); // Throw an error if it's not a valid setup
  1151. if (!valid && id != null) {
  1152. throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  1153. } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {
  1154. return new ObjectId(Buffer$1.from(id, 'hex'));
  1155. } else if (valid && typeof id === 'string' && id.length === 24) {
  1156. return ObjectId.createFromHexString(id);
  1157. } else if (id != null && id.length === 12) {
  1158. // assume 12 byte string
  1159. this.id = id;
  1160. } else if (id != null && id.toHexString) {
  1161. // Duck-typing to support ObjectId from different npm packages
  1162. return id;
  1163. } else {
  1164. throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  1165. }
  1166. if (ObjectId.cacheHexString) this.__id = this.toString('hex');
  1167. }
  1168. /**
  1169. * Return the ObjectId id as a 24 byte hex string representation
  1170. *
  1171. * @method
  1172. * @return {string} return the 24 byte hex string representation.
  1173. */
  1174. _createClass(ObjectId, [{
  1175. key: "toHexString",
  1176. value: function toHexString() {
  1177. if (ObjectId.cacheHexString && this.__id) return this.__id;
  1178. var hexString = '';
  1179. if (!this.id || !this.id.length) {
  1180. throw new TypeError('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']');
  1181. }
  1182. if (this.id instanceof _Buffer) {
  1183. hexString = convertToHex(this.id);
  1184. if (ObjectId.cacheHexString) this.__id = hexString;
  1185. return hexString;
  1186. }
  1187. for (var _i2 = 0; _i2 < this.id.length; _i2++) {
  1188. var hexChar = hexTable[this.id.charCodeAt(_i2)];
  1189. if (typeof hexChar !== 'string') {
  1190. throw makeObjectIdError(this.id, _i2);
  1191. }
  1192. hexString += hexChar;
  1193. }
  1194. if (ObjectId.cacheHexString) this.__id = hexString;
  1195. return hexString;
  1196. }
  1197. /**
  1198. * Update the ObjectId index used in generating new ObjectId's on the driver
  1199. *
  1200. * @method
  1201. * @return {number} returns next index value.
  1202. * @ignore
  1203. */
  1204. }, {
  1205. key: "toString",
  1206. /**
  1207. * Converts the id into a 24 byte hex string for printing
  1208. *
  1209. * @param {String} format The Buffer toString format parameter.
  1210. * @return {String} return the 24 byte hex string representation.
  1211. * @ignore
  1212. */
  1213. value: function toString(format) {
  1214. // Is the id a buffer then use the buffer toString method to return the format
  1215. if (this.id && this.id.copy) {
  1216. return this.id.toString(typeof format === 'string' ? format : 'hex');
  1217. }
  1218. return this.toHexString();
  1219. }
  1220. /**
  1221. * Converts to its JSON representation.
  1222. *
  1223. * @return {String} return the 24 byte hex string representation.
  1224. * @ignore
  1225. */
  1226. }, {
  1227. key: "toJSON",
  1228. value: function toJSON() {
  1229. return this.toHexString();
  1230. }
  1231. /**
  1232. * Compares the equality of this ObjectId with `otherID`.
  1233. *
  1234. * @method
  1235. * @param {object} otherID ObjectId instance to compare against.
  1236. * @return {boolean} the result of comparing two ObjectId's
  1237. */
  1238. }, {
  1239. key: "equals",
  1240. value: function equals(otherId) {
  1241. if (otherId instanceof ObjectId) {
  1242. return this.toString() === otherId.toString();
  1243. }
  1244. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) {
  1245. return otherId === this.id.toString('binary');
  1246. }
  1247. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
  1248. return otherId.toLowerCase() === this.toHexString();
  1249. }
  1250. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
  1251. return otherId === this.id;
  1252. }
  1253. if (otherId != null && (otherId instanceof ObjectId || otherId.toHexString)) {
  1254. return otherId.toHexString() === this.toHexString();
  1255. }
  1256. return false;
  1257. }
  1258. /**
  1259. * Returns the generation date (accurate up to the second) that this ID was generated.
  1260. *
  1261. * @method
  1262. * @return {date} the generation date
  1263. */
  1264. }, {
  1265. key: "getTimestamp",
  1266. value: function getTimestamp() {
  1267. var timestamp = new Date();
  1268. var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
  1269. timestamp.setTime(Math.floor(time) * 1000);
  1270. return timestamp;
  1271. }
  1272. /**
  1273. * @ignore
  1274. */
  1275. }, {
  1276. key: "toExtendedJSON",
  1277. /**
  1278. * @ignore
  1279. */
  1280. value: function toExtendedJSON() {
  1281. if (this.toHexString) return {
  1282. $oid: this.toHexString()
  1283. };
  1284. return {
  1285. $oid: this.toString('hex')
  1286. };
  1287. }
  1288. /**
  1289. * @ignore
  1290. */
  1291. }], [{
  1292. key: "getInc",
  1293. value: function getInc() {
  1294. return ObjectId.index = (ObjectId.index + 1) % 0xffffff;
  1295. }
  1296. /**
  1297. * Generate a 12 byte id buffer used in ObjectId's
  1298. *
  1299. * @method
  1300. * @param {number} [time] optional parameter allowing to pass in a second based timestamp.
  1301. * @return {Buffer} return the 12 byte id buffer string.
  1302. */
  1303. }, {
  1304. key: "generate",
  1305. value: function generate(time) {
  1306. if ('number' !== typeof time) {
  1307. time = ~~(Date.now() / 1000);
  1308. }
  1309. var inc = this.get_inc();
  1310. var buffer$$1 = Buffer$1.alloc(12); // 4-byte timestamp
  1311. buffer$$1[3] = time & 0xff;
  1312. buffer$$1[2] = time >> 8 & 0xff;
  1313. buffer$$1[1] = time >> 16 & 0xff;
  1314. buffer$$1[0] = time >> 24 & 0xff; // 5-byte process unique
  1315. buffer$$1[4] = PROCESS_UNIQUE[0];
  1316. buffer$$1[5] = PROCESS_UNIQUE[1];
  1317. buffer$$1[6] = PROCESS_UNIQUE[2];
  1318. buffer$$1[7] = PROCESS_UNIQUE[3];
  1319. buffer$$1[8] = PROCESS_UNIQUE[4]; // 3-byte counter
  1320. buffer$$1[11] = inc & 0xff;
  1321. buffer$$1[10] = inc >> 8 & 0xff;
  1322. buffer$$1[9] = inc >> 16 & 0xff;
  1323. return buffer$$1;
  1324. }
  1325. }, {
  1326. key: "createPk",
  1327. value: function createPk() {
  1328. return new ObjectId();
  1329. }
  1330. /**
  1331. * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
  1332. *
  1333. * @method
  1334. * @param {number} time an integer number representing a number of seconds.
  1335. * @return {ObjectId} return the created ObjectId
  1336. */
  1337. }, {
  1338. key: "createFromTime",
  1339. value: function createFromTime(time) {
  1340. var buffer$$1 = Buffer$1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // Encode time into first 4 bytes
  1341. buffer$$1[3] = time & 0xff;
  1342. buffer$$1[2] = time >> 8 & 0xff;
  1343. buffer$$1[1] = time >> 16 & 0xff;
  1344. buffer$$1[0] = time >> 24 & 0xff; // Return the new objectId
  1345. return new ObjectId(buffer$$1);
  1346. }
  1347. /**
  1348. * Creates an ObjectId from a hex string representation of an ObjectId.
  1349. *
  1350. * @method
  1351. * @param {string} hexString create a ObjectId from a passed in 24 byte hexstring.
  1352. * @return {ObjectId} return the created ObjectId
  1353. */
  1354. }, {
  1355. key: "createFromHexString",
  1356. value: function createFromHexString(string) {
  1357. // Throw an error if it's not a valid setup
  1358. if (typeof string === 'undefined' || string != null && string.length !== 24) {
  1359. throw new TypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  1360. } // Use Buffer.from method if available
  1361. if (hasBufferType) return new ObjectId(Buffer$1.from(string, 'hex')); // Calculate lengths
  1362. var array = new _Buffer(12);
  1363. var n = 0;
  1364. var i = 0;
  1365. while (i < 24) {
  1366. array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)];
  1367. }
  1368. return new ObjectId(array);
  1369. }
  1370. /**
  1371. * Checks if a value is a valid bson ObjectId
  1372. *
  1373. * @method
  1374. * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
  1375. */
  1376. }, {
  1377. key: "isValid",
  1378. value: function isValid(id) {
  1379. if (id == null) return false;
  1380. if (typeof id === 'number') {
  1381. return true;
  1382. }
  1383. if (typeof id === 'string') {
  1384. return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id);
  1385. }
  1386. if (id instanceof ObjectId) {
  1387. return true;
  1388. }
  1389. if (id instanceof _Buffer && id.length === 12) {
  1390. return true;
  1391. } // Duck-Typing detection of ObjectId like objects
  1392. if (id.toHexString) {
  1393. return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id);
  1394. }
  1395. return false;
  1396. }
  1397. }, {
  1398. key: "fromExtendedJSON",
  1399. value: function fromExtendedJSON(doc) {
  1400. return new ObjectId(doc.$oid);
  1401. }
  1402. }]);
  1403. return ObjectId;
  1404. }(); // Deprecated methods
  1405. ObjectId.get_inc = deprecate$1(function () {
  1406. return ObjectId.getInc();
  1407. }, 'Please use the static `ObjectId.getInc()` instead');
  1408. ObjectId.prototype.get_inc = deprecate$1(function () {
  1409. return ObjectId.getInc();
  1410. }, 'Please use the static `ObjectId.getInc()` instead');
  1411. ObjectId.prototype.getInc = deprecate$1(function () {
  1412. return ObjectId.getInc();
  1413. }, 'Please use the static `ObjectId.getInc()` instead');
  1414. ObjectId.prototype.generate = deprecate$1(function (time) {
  1415. return ObjectId.generate(time);
  1416. }, 'Please use the static `ObjectId.generate(time)` instead');
  1417. /**
  1418. * @ignore
  1419. */
  1420. Object.defineProperty(ObjectId.prototype, 'generationTime', {
  1421. enumerable: true,
  1422. get: function get() {
  1423. return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
  1424. },
  1425. set: function set(value) {
  1426. // Encode time into first 4 bytes
  1427. this.id[3] = value & 0xff;
  1428. this.id[2] = value >> 8 & 0xff;
  1429. this.id[1] = value >> 16 & 0xff;
  1430. this.id[0] = value >> 24 & 0xff;
  1431. }
  1432. });
  1433. /**
  1434. * Converts to a string representation of this Id.
  1435. *
  1436. * @return {String} return the 24 byte hex string representation.
  1437. * @ignore
  1438. */
  1439. ObjectId.prototype.inspect = ObjectId.prototype.toString;
  1440. /**
  1441. * @ignore
  1442. */
  1443. ObjectId.index = ~~(Math.random() * 0xffffff);
  1444. Object.defineProperty(ObjectId.prototype, '_bsontype', {
  1445. value: 'ObjectId'
  1446. });
  1447. var objectid = ObjectId;
  1448. function alphabetize(str) {
  1449. return str.split('').sort().join('');
  1450. }
  1451. /**
  1452. * A class representation of the BSON RegExp type.
  1453. */
  1454. var BSONRegExp =
  1455. /*#__PURE__*/
  1456. function () {
  1457. /**
  1458. * Create a RegExp type
  1459. *
  1460. * @param {string} pattern The regular expression pattern to match
  1461. * @param {string} options The regular expression options
  1462. */
  1463. function BSONRegExp(pattern, options) {
  1464. _classCallCheck(this, BSONRegExp);
  1465. // Execute
  1466. this.pattern = pattern || '';
  1467. this.options = options ? alphabetize(options) : ''; // Validate options
  1468. for (var i = 0; i < this.options.length; i++) {
  1469. if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) {
  1470. throw new Error("The regular expression option [".concat(this.options[i], "] is not supported"));
  1471. }
  1472. }
  1473. }
  1474. /**
  1475. * @ignore
  1476. */
  1477. _createClass(BSONRegExp, [{
  1478. key: "toExtendedJSON",
  1479. value: function toExtendedJSON() {
  1480. return {
  1481. $regularExpression: {
  1482. pattern: this.pattern,
  1483. options: this.options
  1484. }
  1485. };
  1486. }
  1487. /**
  1488. * @ignore
  1489. */
  1490. }], [{
  1491. key: "fromExtendedJSON",
  1492. value: function fromExtendedJSON(doc) {
  1493. return new BSONRegExp(doc.$regularExpression.pattern, doc.$regularExpression.options.split('').sort().join(''));
  1494. }
  1495. }]);
  1496. return BSONRegExp;
  1497. }();
  1498. Object.defineProperty(BSONRegExp.prototype, '_bsontype', {
  1499. value: 'BSONRegExp'
  1500. });
  1501. var regexp = BSONRegExp;
  1502. var BSONSymbol =
  1503. /*#__PURE__*/
  1504. function () {
  1505. /**
  1506. * Create a Symbol type
  1507. *
  1508. * @param {string} value the string representing the symbol.
  1509. */
  1510. function BSONSymbol(value) {
  1511. _classCallCheck(this, BSONSymbol);
  1512. this.value = value;
  1513. }
  1514. /**
  1515. * Access the wrapped string value.
  1516. *
  1517. * @method
  1518. * @return {String} returns the wrapped string.
  1519. */
  1520. _createClass(BSONSymbol, [{
  1521. key: "valueOf",
  1522. value: function valueOf() {
  1523. return this.value;
  1524. }
  1525. /**
  1526. * @ignore
  1527. */
  1528. }, {
  1529. key: "toString",
  1530. value: function toString() {
  1531. return this.value;
  1532. }
  1533. /**
  1534. * @ignore
  1535. */
  1536. }, {
  1537. key: "inspect",
  1538. value: function inspect() {
  1539. return this.value;
  1540. }
  1541. /**
  1542. * @ignore
  1543. */
  1544. }, {
  1545. key: "toJSON",
  1546. value: function toJSON() {
  1547. return this.value;
  1548. }
  1549. /**
  1550. * @ignore
  1551. */
  1552. }, {
  1553. key: "toExtendedJSON",
  1554. value: function toExtendedJSON() {
  1555. return {
  1556. $symbol: this.value
  1557. };
  1558. }
  1559. /**
  1560. * @ignore
  1561. */
  1562. }], [{
  1563. key: "fromExtendedJSON",
  1564. value: function fromExtendedJSON(doc) {
  1565. return new BSONSymbol(doc.$symbol);
  1566. }
  1567. }]);
  1568. return BSONSymbol;
  1569. }();
  1570. Object.defineProperty(BSONSymbol.prototype, '_bsontype', {
  1571. value: 'Symbol'
  1572. });
  1573. var symbol = BSONSymbol;
  1574. var Int32 =
  1575. /*#__PURE__*/
  1576. function () {
  1577. /**
  1578. * Create an Int32 type
  1579. *
  1580. * @param {number} value the number we want to represent as an int32.
  1581. * @return {Int32}
  1582. */
  1583. function Int32(value) {
  1584. _classCallCheck(this, Int32);
  1585. this.value = value;
  1586. }
  1587. /**
  1588. * Access the number value.
  1589. *
  1590. * @method
  1591. * @return {number} returns the wrapped int32 number.
  1592. */
  1593. _createClass(Int32, [{
  1594. key: "valueOf",
  1595. value: function valueOf() {
  1596. return this.value;
  1597. }
  1598. /**
  1599. * @ignore
  1600. */
  1601. }, {
  1602. key: "toJSON",
  1603. value: function toJSON() {
  1604. return this.value;
  1605. }
  1606. /**
  1607. * @ignore
  1608. */
  1609. }, {
  1610. key: "toExtendedJSON",
  1611. value: function toExtendedJSON(options) {
  1612. if (options && options.relaxed) return this.value;
  1613. return {
  1614. $numberInt: this.value.toString()
  1615. };
  1616. }
  1617. /**
  1618. * @ignore
  1619. */
  1620. }], [{
  1621. key: "fromExtendedJSON",
  1622. value: function fromExtendedJSON(doc, options) {
  1623. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  1624. }
  1625. }]);
  1626. return Int32;
  1627. }();
  1628. Object.defineProperty(Int32.prototype, '_bsontype', {
  1629. value: 'Int32'
  1630. });
  1631. var int_32 = Int32;
  1632. var Code =
  1633. /*#__PURE__*/
  1634. function () {
  1635. /**
  1636. * Create a Code type
  1637. *
  1638. * @param {(string|function)} code a string or function.
  1639. * @param {Object} [scope] an optional scope for the function.
  1640. * @return {Code}
  1641. */
  1642. function Code(code, scope) {
  1643. _classCallCheck(this, Code);
  1644. this.code = code;
  1645. this.scope = scope;
  1646. }
  1647. /**
  1648. * @ignore
  1649. */
  1650. _createClass(Code, [{
  1651. key: "toJSON",
  1652. value: function toJSON() {
  1653. return {
  1654. scope: this.scope,
  1655. code: this.code
  1656. };
  1657. }
  1658. /**
  1659. * @ignore
  1660. */
  1661. }, {
  1662. key: "toExtendedJSON",
  1663. value: function toExtendedJSON() {
  1664. if (this.scope) {
  1665. return {
  1666. $code: this.code,
  1667. $scope: this.scope
  1668. };
  1669. }
  1670. return {
  1671. $code: this.code
  1672. };
  1673. }
  1674. /**
  1675. * @ignore
  1676. */
  1677. }], [{
  1678. key: "fromExtendedJSON",
  1679. value: function fromExtendedJSON(doc) {
  1680. return new Code(doc.$code, doc.$scope);
  1681. }
  1682. }]);
  1683. return Code;
  1684. }();
  1685. Object.defineProperty(Code.prototype, '_bsontype', {
  1686. value: 'Code'
  1687. });
  1688. var code = Code;
  1689. var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  1690. var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  1691. var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  1692. var EXPONENT_MAX = 6111;
  1693. var EXPONENT_MIN = -6176;
  1694. var EXPONENT_BIAS = 6176;
  1695. var MAX_DIGITS = 34; // Nan value bits as 32 bit values (due to lack of longs)
  1696. var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); // Infinity value bits 32 bit values (due to lack of longs)
  1697. var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse();
  1698. var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse();
  1699. var EXPONENT_REGEX = /^([-+])?(\d+)?$/; // Detect if the value is a digit
  1700. function isDigit(value) {
  1701. return !isNaN(parseInt(value, 10));
  1702. } // Divide two uint128 values
  1703. function divideu128(value) {
  1704. var DIVISOR = long_1.fromNumber(1000 * 1000 * 1000);
  1705. var _rem = long_1.fromNumber(0);
  1706. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  1707. return {
  1708. quotient: value,
  1709. rem: _rem
  1710. };
  1711. }
  1712. for (var i = 0; i <= 3; i++) {
  1713. // Adjust remainder to match value of next dividend
  1714. _rem = _rem.shiftLeft(32); // Add the divided to _rem
  1715. _rem = _rem.add(new long_1(value.parts[i], 0));
  1716. value.parts[i] = _rem.div(DIVISOR).low;
  1717. _rem = _rem.modulo(DIVISOR);
  1718. }
  1719. return {
  1720. quotient: value,
  1721. rem: _rem
  1722. };
  1723. } // Multiply two Long values and return the 128 bit value
  1724. function multiply64x2(left, right) {
  1725. if (!left && !right) {
  1726. return {
  1727. high: long_1.fromNumber(0),
  1728. low: long_1.fromNumber(0)
  1729. };
  1730. }
  1731. var leftHigh = left.shiftRightUnsigned(32);
  1732. var leftLow = new long_1(left.getLowBits(), 0);
  1733. var rightHigh = right.shiftRightUnsigned(32);
  1734. var rightLow = new long_1(right.getLowBits(), 0);
  1735. var productHigh = leftHigh.multiply(rightHigh);
  1736. var productMid = leftHigh.multiply(rightLow);
  1737. var productMid2 = leftLow.multiply(rightHigh);
  1738. var productLow = leftLow.multiply(rightLow);
  1739. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1740. productMid = new long_1(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32));
  1741. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1742. productLow = productMid.shiftLeft(32).add(new long_1(productLow.getLowBits(), 0)); // Return the 128 bit result
  1743. return {
  1744. high: productHigh,
  1745. low: productLow
  1746. };
  1747. }
  1748. function lessThan(left, right) {
  1749. // Make values unsigned
  1750. var uhleft = left.high >>> 0;
  1751. var uhright = right.high >>> 0; // Compare high bits first
  1752. if (uhleft < uhright) {
  1753. return true;
  1754. } else if (uhleft === uhright) {
  1755. var ulleft = left.low >>> 0;
  1756. var ulright = right.low >>> 0;
  1757. if (ulleft < ulright) return true;
  1758. }
  1759. return false;
  1760. }
  1761. function invalidErr(string, message) {
  1762. throw new TypeError("\"".concat(string, "\" is not a valid Decimal128 string - ").concat(message));
  1763. }
  1764. /**
  1765. * A class representation of the BSON Decimal128 type.
  1766. *
  1767. * @class
  1768. * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes.
  1769. * @return {Double}
  1770. */
  1771. function Decimal128(bytes) {
  1772. this.bytes = bytes;
  1773. }
  1774. /**
  1775. * Create a Decimal128 instance from a string representation
  1776. *
  1777. * @method
  1778. * @param {string} string a numeric string representation.
  1779. * @return {Decimal128} returns a Decimal128 instance.
  1780. */
  1781. Decimal128.fromString = function (string) {
  1782. // Parse state tracking
  1783. var isNegative = false;
  1784. var sawRadix = false;
  1785. var foundNonZero = false; // Total number of significant digits (no leading or trailing zero)
  1786. var significantDigits = 0; // Total number of significand digits read
  1787. var nDigitsRead = 0; // Total number of digits (no leading zeros)
  1788. var nDigits = 0; // The number of the digits after radix
  1789. var radixPosition = 0; // The index of the first non-zero in *str*
  1790. var firstNonZero = 0; // Digits Array
  1791. var digits = [0]; // The number of digits in digits
  1792. var nDigitsStored = 0; // Insertion pointer for digits
  1793. var digitsInsert = 0; // The index of the first non-zero digit
  1794. var firstDigit = 0; // The index of the last digit
  1795. var lastDigit = 0; // Exponent
  1796. var exponent = 0; // loop index over array
  1797. var i = 0; // The high 17 digits of the significand
  1798. var significandHigh = [0, 0]; // The low 17 digits of the significand
  1799. var significandLow = [0, 0]; // The biased exponent
  1800. var biasedExponent = 0; // Read index
  1801. var index = 0; // Naively prevent against REDOS attacks.
  1802. // TODO: implementing a custom parsing for this, or refactoring the regex would yield
  1803. // further gains.
  1804. if (string.length >= 7000) {
  1805. throw new TypeError('' + string + ' not a valid Decimal128 string');
  1806. } // Results
  1807. var stringMatch = string.match(PARSE_STRING_REGEXP);
  1808. var infMatch = string.match(PARSE_INF_REGEXP);
  1809. var nanMatch = string.match(PARSE_NAN_REGEXP); // Validate the string
  1810. if (!stringMatch && !infMatch && !nanMatch || string.length === 0) {
  1811. throw new TypeError('' + string + ' not a valid Decimal128 string');
  1812. }
  1813. if (stringMatch) {
  1814. // full_match = stringMatch[0]
  1815. // sign = stringMatch[1]
  1816. var unsignedNumber = stringMatch[2]; // stringMatch[3] is undefined if a whole number (ex "1", 12")
  1817. // but defined if a number w/ decimal in it (ex "1.0, 12.2")
  1818. var e = stringMatch[4];
  1819. var expSign = stringMatch[5];
  1820. var expNumber = stringMatch[6]; // they provided e, but didn't give an exponent number. for ex "1e"
  1821. if (e && expNumber === undefined) invalidErr(string, 'missing exponent power'); // they provided e, but didn't give a number before it. for ex "e1"
  1822. if (e && unsignedNumber === undefined) invalidErr(string, 'missing exponent base');
  1823. if (e === undefined && (expSign || expNumber)) {
  1824. invalidErr(string, 'missing e before exponent');
  1825. }
  1826. } // Get the negative or positive sign
  1827. if (string[index] === '+' || string[index] === '-') {
  1828. isNegative = string[index++] === '-';
  1829. } // Check if user passed Infinity or NaN
  1830. if (!isDigit(string[index]) && string[index] !== '.') {
  1831. if (string[index] === 'i' || string[index] === 'I') {
  1832. return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  1833. } else if (string[index] === 'N') {
  1834. return new Decimal128(Buffer.from(NAN_BUFFER));
  1835. }
  1836. } // Read all the digits
  1837. while (isDigit(string[index]) || string[index] === '.') {
  1838. if (string[index] === '.') {
  1839. if (sawRadix) invalidErr(string, 'contains multiple periods');
  1840. sawRadix = true;
  1841. index = index + 1;
  1842. continue;
  1843. }
  1844. if (nDigitsStored < 34) {
  1845. if (string[index] !== '0' || foundNonZero) {
  1846. if (!foundNonZero) {
  1847. firstNonZero = nDigitsRead;
  1848. }
  1849. foundNonZero = true; // Only store 34 digits
  1850. digits[digitsInsert++] = parseInt(string[index], 10);
  1851. nDigitsStored = nDigitsStored + 1;
  1852. }
  1853. }
  1854. if (foundNonZero) nDigits = nDigits + 1;
  1855. if (sawRadix) radixPosition = radixPosition + 1;
  1856. nDigitsRead = nDigitsRead + 1;
  1857. index = index + 1;
  1858. }
  1859. if (sawRadix && !nDigitsRead) throw new TypeError('' + string + ' not a valid Decimal128 string'); // Read exponent if exists
  1860. if (string[index] === 'e' || string[index] === 'E') {
  1861. // Read exponent digits
  1862. var match = string.substr(++index).match(EXPONENT_REGEX); // No digits read
  1863. if (!match || !match[2]) return new Decimal128(Buffer.from(NAN_BUFFER)); // Get exponent
  1864. exponent = parseInt(match[0], 10); // Adjust the index
  1865. index = index + match[0].length;
  1866. } // Return not a number
  1867. if (string[index]) return new Decimal128(Buffer.from(NAN_BUFFER)); // Done reading input
  1868. // Find first non-zero digit in digits
  1869. firstDigit = 0;
  1870. if (!nDigitsStored) {
  1871. firstDigit = 0;
  1872. lastDigit = 0;
  1873. digits[0] = 0;
  1874. nDigits = 1;
  1875. nDigitsStored = 1;
  1876. significantDigits = 0;
  1877. } else {
  1878. lastDigit = nDigitsStored - 1;
  1879. significantDigits = nDigits;
  1880. if (significantDigits !== 1) {
  1881. while (string[firstNonZero + significantDigits - 1] === '0') {
  1882. significantDigits = significantDigits - 1;
  1883. }
  1884. }
  1885. } // Normalization of exponent
  1886. // Correct exponent based on radix position, and shift significand as needed
  1887. // to represent user input
  1888. // Overflow prevention
  1889. if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
  1890. exponent = EXPONENT_MIN;
  1891. } else {
  1892. exponent = exponent - radixPosition;
  1893. } // Attempt to normalize the exponent
  1894. while (exponent > EXPONENT_MAX) {
  1895. // Shift exponent to significand and decrease
  1896. lastDigit = lastDigit + 1;
  1897. if (lastDigit - firstDigit > MAX_DIGITS) {
  1898. // Check if we have a zero then just hard clamp, otherwise fail
  1899. var digitsString = digits.join('');
  1900. if (digitsString.match(/^0+$/)) {
  1901. exponent = EXPONENT_MAX;
  1902. break;
  1903. }
  1904. invalidErr(string, 'overflow');
  1905. }
  1906. exponent = exponent - 1;
  1907. }
  1908. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  1909. // Shift last digit. can only do this if < significant digits than # stored.
  1910. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  1911. exponent = EXPONENT_MIN;
  1912. significantDigits = 0;
  1913. break;
  1914. }
  1915. if (nDigitsStored < nDigits) {
  1916. // adjust to match digits not stored
  1917. nDigits = nDigits - 1;
  1918. } else {
  1919. // adjust to round
  1920. lastDigit = lastDigit - 1;
  1921. }
  1922. if (exponent < EXPONENT_MAX) {
  1923. exponent = exponent + 1;
  1924. } else {
  1925. // Check if we have a zero then just hard clamp, otherwise fail
  1926. var _digitsString = digits.join('');
  1927. if (_digitsString.match(/^0+$/)) {
  1928. exponent = EXPONENT_MAX;
  1929. break;
  1930. }
  1931. invalidErr(string, 'overflow');
  1932. }
  1933. } // Round
  1934. // We've normalized the exponent, but might still need to round.
  1935. if (lastDigit - firstDigit + 1 < significantDigits) {
  1936. var endOfString = nDigitsRead; // If we have seen a radix point, 'string' is 1 longer than we have
  1937. // documented with ndigits_read, so inc the position of the first nonzero
  1938. // digit and the position that digits are read to.
  1939. if (sawRadix) {
  1940. firstNonZero = firstNonZero + 1;
  1941. endOfString = endOfString + 1;
  1942. } // if negative, we need to increment again to account for - sign at start.
  1943. if (isNegative) {
  1944. firstNonZero = firstNonZero + 1;
  1945. endOfString = endOfString + 1;
  1946. }
  1947. var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10);
  1948. var roundBit = 0;
  1949. if (roundDigit >= 5) {
  1950. roundBit = 1;
  1951. if (roundDigit === 5) {
  1952. roundBit = digits[lastDigit] % 2 === 1;
  1953. for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  1954. if (parseInt(string[i], 10)) {
  1955. roundBit = 1;
  1956. break;
  1957. }
  1958. }
  1959. }
  1960. }
  1961. if (roundBit) {
  1962. var dIdx = lastDigit;
  1963. for (; dIdx >= 0; dIdx--) {
  1964. if (++digits[dIdx] > 9) {
  1965. digits[dIdx] = 0; // overflowed most significant digit
  1966. if (dIdx === 0) {
  1967. if (exponent < EXPONENT_MAX) {
  1968. exponent = exponent + 1;
  1969. digits[dIdx] = 1;
  1970. } else {
  1971. return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  1972. }
  1973. }
  1974. }
  1975. }
  1976. }
  1977. } // Encode significand
  1978. // The high 17 digits of the significand
  1979. significandHigh = long_1.fromNumber(0); // The low 17 digits of the significand
  1980. significandLow = long_1.fromNumber(0); // read a zero
  1981. if (significantDigits === 0) {
  1982. significandHigh = long_1.fromNumber(0);
  1983. significandLow = long_1.fromNumber(0);
  1984. } else if (lastDigit - firstDigit < 17) {
  1985. var _dIdx = firstDigit;
  1986. significandLow = long_1.fromNumber(digits[_dIdx++]);
  1987. significandHigh = new long_1(0, 0);
  1988. for (; _dIdx <= lastDigit; _dIdx++) {
  1989. significandLow = significandLow.multiply(long_1.fromNumber(10));
  1990. significandLow = significandLow.add(long_1.fromNumber(digits[_dIdx]));
  1991. }
  1992. } else {
  1993. var _dIdx2 = firstDigit;
  1994. significandHigh = long_1.fromNumber(digits[_dIdx2++]);
  1995. for (; _dIdx2 <= lastDigit - 17; _dIdx2++) {
  1996. significandHigh = significandHigh.multiply(long_1.fromNumber(10));
  1997. significandHigh = significandHigh.add(long_1.fromNumber(digits[_dIdx2]));
  1998. }
  1999. significandLow = long_1.fromNumber(digits[_dIdx2++]);
  2000. for (; _dIdx2 <= lastDigit; _dIdx2++) {
  2001. significandLow = significandLow.multiply(long_1.fromNumber(10));
  2002. significandLow = significandLow.add(long_1.fromNumber(digits[_dIdx2]));
  2003. }
  2004. }
  2005. var significand = multiply64x2(significandHigh, long_1.fromString('100000000000000000'));
  2006. significand.low = significand.low.add(significandLow);
  2007. if (lessThan(significand.low, significandLow)) {
  2008. significand.high = significand.high.add(long_1.fromNumber(1));
  2009. } // Biased exponent
  2010. biasedExponent = exponent + EXPONENT_BIAS;
  2011. var dec = {
  2012. low: long_1.fromNumber(0),
  2013. high: long_1.fromNumber(0)
  2014. }; // Encode combination, exponent, and significand.
  2015. if (significand.high.shiftRightUnsigned(49).and(long_1.fromNumber(1)).equals(long_1.fromNumber(1))) {
  2016. // Encode '11' into bits 1 to 3
  2017. dec.high = dec.high.or(long_1.fromNumber(0x3).shiftLeft(61));
  2018. dec.high = dec.high.or(long_1.fromNumber(biasedExponent).and(long_1.fromNumber(0x3fff).shiftLeft(47)));
  2019. dec.high = dec.high.or(significand.high.and(long_1.fromNumber(0x7fffffffffff)));
  2020. } else {
  2021. dec.high = dec.high.or(long_1.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  2022. dec.high = dec.high.or(significand.high.and(long_1.fromNumber(0x1ffffffffffff)));
  2023. }
  2024. dec.low = significand.low; // Encode sign
  2025. if (isNegative) {
  2026. dec.high = dec.high.or(long_1.fromString('9223372036854775808'));
  2027. } // Encode into a buffer
  2028. var buffer$$1 = Buffer.alloc(16);
  2029. index = 0; // Encode the low 64 bits of the decimal
  2030. // Encode low bits
  2031. buffer$$1[index++] = dec.low.low & 0xff;
  2032. buffer$$1[index++] = dec.low.low >> 8 & 0xff;
  2033. buffer$$1[index++] = dec.low.low >> 16 & 0xff;
  2034. buffer$$1[index++] = dec.low.low >> 24 & 0xff; // Encode high bits
  2035. buffer$$1[index++] = dec.low.high & 0xff;
  2036. buffer$$1[index++] = dec.low.high >> 8 & 0xff;
  2037. buffer$$1[index++] = dec.low.high >> 16 & 0xff;
  2038. buffer$$1[index++] = dec.low.high >> 24 & 0xff; // Encode the high 64 bits of the decimal
  2039. // Encode low bits
  2040. buffer$$1[index++] = dec.high.low & 0xff;
  2041. buffer$$1[index++] = dec.high.low >> 8 & 0xff;
  2042. buffer$$1[index++] = dec.high.low >> 16 & 0xff;
  2043. buffer$$1[index++] = dec.high.low >> 24 & 0xff; // Encode high bits
  2044. buffer$$1[index++] = dec.high.high & 0xff;
  2045. buffer$$1[index++] = dec.high.high >> 8 & 0xff;
  2046. buffer$$1[index++] = dec.high.high >> 16 & 0xff;
  2047. buffer$$1[index++] = dec.high.high >> 24 & 0xff; // Return the new Decimal128
  2048. return new Decimal128(buffer$$1);
  2049. }; // Extract least significant 5 bits
  2050. var COMBINATION_MASK = 0x1f; // Extract least significant 14 bits
  2051. var EXPONENT_MASK = 0x3fff; // Value of combination field for Inf
  2052. var COMBINATION_INFINITY = 30; // Value of combination field for NaN
  2053. var COMBINATION_NAN = 31;
  2054. /**
  2055. * Create a string representation of the raw Decimal128 value
  2056. *
  2057. * @method
  2058. * @return {string} returns a Decimal128 string representation.
  2059. */
  2060. Decimal128.prototype.toString = function () {
  2061. // Note: bits in this routine are referred to starting at 0,
  2062. // from the sign bit, towards the coefficient.
  2063. // bits 0 - 31
  2064. var high; // bits 32 - 63
  2065. var midh; // bits 64 - 95
  2066. var midl; // bits 96 - 127
  2067. var low; // bits 1 - 5
  2068. var combination; // decoded biased exponent (14 bits)
  2069. var biased_exponent; // the number of significand digits
  2070. var significand_digits = 0; // the base-10 digits in the significand
  2071. var significand = new Array(36);
  2072. for (var i = 0; i < significand.length; i++) {
  2073. significand[i] = 0;
  2074. } // read pointer into significand
  2075. var index = 0; // unbiased exponent
  2076. var exponent; // the exponent if scientific notation is used
  2077. var scientific_exponent; // true if the number is zero
  2078. var is_zero = false; // the most signifcant significand bits (50-46)
  2079. var significand_msb; // temporary storage for significand decoding
  2080. var significand128 = {
  2081. parts: new Array(4)
  2082. }; // indexing variables
  2083. var j, k; // Output string
  2084. var string = []; // Unpack index
  2085. index = 0; // Buffer reference
  2086. var buffer$$1 = this.bytes; // Unpack the low 64bits into a long
  2087. low = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  2088. midl = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Unpack the high 64bits into a long
  2089. midh = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  2090. high = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Unpack index
  2091. index = 0; // Create the state of the decimal
  2092. var dec = {
  2093. low: new long_1(low, midl),
  2094. high: new long_1(midh, high)
  2095. };
  2096. if (dec.high.lessThan(long_1.ZERO)) {
  2097. string.push('-');
  2098. } // Decode combination field and exponent
  2099. combination = high >> 26 & COMBINATION_MASK;
  2100. if (combination >> 3 === 3) {
  2101. // Check for 'special' values
  2102. if (combination === COMBINATION_INFINITY) {
  2103. return string.join('') + 'Infinity';
  2104. } else if (combination === COMBINATION_NAN) {
  2105. return 'NaN';
  2106. } else {
  2107. biased_exponent = high >> 15 & EXPONENT_MASK;
  2108. significand_msb = 0x08 + (high >> 14 & 0x01);
  2109. }
  2110. } else {
  2111. significand_msb = high >> 14 & 0x07;
  2112. biased_exponent = high >> 17 & EXPONENT_MASK;
  2113. }
  2114. exponent = biased_exponent - EXPONENT_BIAS; // Create string of significand digits
  2115. // Convert the 114-bit binary number represented by
  2116. // (significand_high, significand_low) to at most 34 decimal
  2117. // digits through modulo and division.
  2118. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  2119. significand128.parts[1] = midh;
  2120. significand128.parts[2] = midl;
  2121. significand128.parts[3] = low;
  2122. if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) {
  2123. is_zero = true;
  2124. } else {
  2125. for (k = 3; k >= 0; k--) {
  2126. var least_digits = 0; // Peform the divide
  2127. var result = divideu128(significand128);
  2128. significand128 = result.quotient;
  2129. least_digits = result.rem.low; // We now have the 9 least significant digits (in base 2).
  2130. // Convert and output to string.
  2131. if (!least_digits) continue;
  2132. for (j = 8; j >= 0; j--) {
  2133. // significand[k * 9 + j] = Math.round(least_digits % 10);
  2134. significand[k * 9 + j] = least_digits % 10; // least_digits = Math.round(least_digits / 10);
  2135. least_digits = Math.floor(least_digits / 10);
  2136. }
  2137. }
  2138. } // Output format options:
  2139. // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
  2140. // Regular - ddd.ddd
  2141. if (is_zero) {
  2142. significand_digits = 1;
  2143. significand[index] = 0;
  2144. } else {
  2145. significand_digits = 36;
  2146. while (!significand[index]) {
  2147. significand_digits = significand_digits - 1;
  2148. index = index + 1;
  2149. }
  2150. }
  2151. scientific_exponent = significand_digits - 1 + exponent; // The scientific exponent checks are dictated by the string conversion
  2152. // specification and are somewhat arbitrary cutoffs.
  2153. //
  2154. // We must check exponent > 0, because if this is the case, the number
  2155. // has trailing zeros. However, we *cannot* output these trailing zeros,
  2156. // because doing so would change the precision of the value, and would
  2157. // change stored data if the string converted number is round tripped.
  2158. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  2159. // Scientific format
  2160. // if there are too many significant digits, we should just be treating numbers
  2161. // as + or - 0 and using the non-scientific exponent (this is for the "invalid
  2162. // representation should be treated as 0/-0" spec cases in decimal128-1.json)
  2163. if (significand_digits > 34) {
  2164. string.push(0);
  2165. if (exponent > 0) string.push('E+' + exponent);else if (exponent < 0) string.push('E' + exponent);
  2166. return string.join('');
  2167. }
  2168. string.push(significand[index++]);
  2169. significand_digits = significand_digits - 1;
  2170. if (significand_digits) {
  2171. string.push('.');
  2172. }
  2173. for (var _i = 0; _i < significand_digits; _i++) {
  2174. string.push(significand[index++]);
  2175. } // Exponent
  2176. string.push('E');
  2177. if (scientific_exponent > 0) {
  2178. string.push('+' + scientific_exponent);
  2179. } else {
  2180. string.push(scientific_exponent);
  2181. }
  2182. } else {
  2183. // Regular format with no decimal place
  2184. if (exponent >= 0) {
  2185. for (var _i2 = 0; _i2 < significand_digits; _i2++) {
  2186. string.push(significand[index++]);
  2187. }
  2188. } else {
  2189. var radix_position = significand_digits + exponent; // non-zero digits before radix
  2190. if (radix_position > 0) {
  2191. for (var _i3 = 0; _i3 < radix_position; _i3++) {
  2192. string.push(significand[index++]);
  2193. }
  2194. } else {
  2195. string.push('0');
  2196. }
  2197. string.push('.'); // add leading zeros after radix
  2198. while (radix_position++ < 0) {
  2199. string.push('0');
  2200. }
  2201. for (var _i4 = 0; _i4 < significand_digits - Math.max(radix_position - 1, 0); _i4++) {
  2202. string.push(significand[index++]);
  2203. }
  2204. }
  2205. }
  2206. return string.join('');
  2207. };
  2208. Decimal128.prototype.toJSON = function () {
  2209. return {
  2210. $numberDecimal: this.toString()
  2211. };
  2212. };
  2213. /**
  2214. * @ignore
  2215. */
  2216. Decimal128.prototype.toExtendedJSON = function () {
  2217. return {
  2218. $numberDecimal: this.toString()
  2219. };
  2220. };
  2221. /**
  2222. * @ignore
  2223. */
  2224. Decimal128.fromExtendedJSON = function (doc) {
  2225. return Decimal128.fromString(doc.$numberDecimal);
  2226. };
  2227. Object.defineProperty(Decimal128.prototype, '_bsontype', {
  2228. value: 'Decimal128'
  2229. });
  2230. var decimal128 = Decimal128;
  2231. var MinKey =
  2232. /*#__PURE__*/
  2233. function () {
  2234. /**
  2235. * Create a MinKey type
  2236. *
  2237. * @return {MinKey} A MinKey instance
  2238. */
  2239. function MinKey() {
  2240. _classCallCheck(this, MinKey);
  2241. }
  2242. /**
  2243. * @ignore
  2244. */
  2245. _createClass(MinKey, [{
  2246. key: "toExtendedJSON",
  2247. value: function toExtendedJSON() {
  2248. return {
  2249. $minKey: 1
  2250. };
  2251. }
  2252. /**
  2253. * @ignore
  2254. */
  2255. }], [{
  2256. key: "fromExtendedJSON",
  2257. value: function fromExtendedJSON() {
  2258. return new MinKey();
  2259. }
  2260. }]);
  2261. return MinKey;
  2262. }();
  2263. Object.defineProperty(MinKey.prototype, '_bsontype', {
  2264. value: 'MinKey'
  2265. });
  2266. var min_key = MinKey;
  2267. var MaxKey =
  2268. /*#__PURE__*/
  2269. function () {
  2270. /**
  2271. * Create a MaxKey type
  2272. *
  2273. * @return {MaxKey} A MaxKey instance
  2274. */
  2275. function MaxKey() {
  2276. _classCallCheck(this, MaxKey);
  2277. }
  2278. /**
  2279. * @ignore
  2280. */
  2281. _createClass(MaxKey, [{
  2282. key: "toExtendedJSON",
  2283. value: function toExtendedJSON() {
  2284. return {
  2285. $maxKey: 1
  2286. };
  2287. }
  2288. /**
  2289. * @ignore
  2290. */
  2291. }], [{
  2292. key: "fromExtendedJSON",
  2293. value: function fromExtendedJSON() {
  2294. return new MaxKey();
  2295. }
  2296. }]);
  2297. return MaxKey;
  2298. }();
  2299. Object.defineProperty(MaxKey.prototype, '_bsontype', {
  2300. value: 'MaxKey'
  2301. });
  2302. var max_key = MaxKey;
  2303. var DBRef =
  2304. /*#__PURE__*/
  2305. function () {
  2306. /**
  2307. * Create a DBRef type
  2308. *
  2309. * @param {string} collection the collection name.
  2310. * @param {ObjectId} oid the reference ObjectId.
  2311. * @param {string} [db] optional db name, if omitted the reference is local to the current db.
  2312. * @return {DBRef}
  2313. */
  2314. function DBRef(collection, oid, db, fields) {
  2315. _classCallCheck(this, DBRef);
  2316. // check if namespace has been provided
  2317. var parts = collection.split('.');
  2318. if (parts.length === 2) {
  2319. db = parts.shift();
  2320. collection = parts.shift();
  2321. }
  2322. this.collection = collection;
  2323. this.oid = oid;
  2324. this.db = db;
  2325. this.fields = fields || {};
  2326. }
  2327. /**
  2328. * @ignore
  2329. * @api private
  2330. */
  2331. _createClass(DBRef, [{
  2332. key: "toJSON",
  2333. value: function toJSON() {
  2334. var o = Object.assign({
  2335. $ref: this.collection,
  2336. $id: this.oid
  2337. }, this.fields);
  2338. if (this.db != null) o.$db = this.db;
  2339. return o;
  2340. }
  2341. /**
  2342. * @ignore
  2343. */
  2344. }, {
  2345. key: "toExtendedJSON",
  2346. value: function toExtendedJSON() {
  2347. var o = {
  2348. $ref: this.collection,
  2349. $id: this.oid
  2350. };
  2351. if (this.db) o.$db = this.db;
  2352. o = Object.assign(o, this.fields);
  2353. return o;
  2354. }
  2355. /**
  2356. * @ignore
  2357. */
  2358. }], [{
  2359. key: "fromExtendedJSON",
  2360. value: function fromExtendedJSON(doc) {
  2361. var copy = Object.assign({}, doc);
  2362. ['$ref', '$id', '$db'].forEach(function (k) {
  2363. return delete copy[k];
  2364. });
  2365. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  2366. }
  2367. }]);
  2368. return DBRef;
  2369. }();
  2370. Object.defineProperty(DBRef.prototype, '_bsontype', {
  2371. value: 'DBRef'
  2372. });
  2373. var db_ref = DBRef;
  2374. var Binary =
  2375. /*#__PURE__*/
  2376. function () {
  2377. /**
  2378. * Create a Binary type
  2379. *
  2380. * Sub types
  2381. * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type.
  2382. * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type.
  2383. * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type.
  2384. * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type.
  2385. * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type.
  2386. * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type.
  2387. *
  2388. * @param {Buffer} buffer a buffer object containing the binary data.
  2389. * @param {Number} [subType] the option binary type.
  2390. * @return {Binary}
  2391. */
  2392. function Binary(buffer$$1, subType) {
  2393. _classCallCheck(this, Binary);
  2394. if (buffer$$1 != null && !(typeof buffer$$1 === 'string') && !Buffer.isBuffer(buffer$$1) && !(buffer$$1 instanceof Uint8Array) && !Array.isArray(buffer$$1)) {
  2395. throw new TypeError('only String, Buffer, Uint8Array or Array accepted');
  2396. }
  2397. this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType;
  2398. this.position = 0;
  2399. if (buffer$$1 != null && !(buffer$$1 instanceof Number)) {
  2400. // Only accept Buffer, Uint8Array or Arrays
  2401. if (typeof buffer$$1 === 'string') {
  2402. // Different ways of writing the length of the string for the different types
  2403. if (typeof Buffer !== 'undefined') {
  2404. this.buffer = Buffer.from(buffer$$1);
  2405. } else if (typeof Uint8Array !== 'undefined' || Array.isArray(buffer$$1)) {
  2406. this.buffer = writeStringToArray(buffer$$1);
  2407. } else {
  2408. throw new TypeError('only String, Buffer, Uint8Array or Array accepted');
  2409. }
  2410. } else {
  2411. this.buffer = buffer$$1;
  2412. }
  2413. this.position = buffer$$1.length;
  2414. } else {
  2415. if (typeof Buffer !== 'undefined') {
  2416. this.buffer = Buffer.alloc(Binary.BUFFER_SIZE);
  2417. } else if (typeof Uint8Array !== 'undefined') {
  2418. this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));
  2419. } else {
  2420. this.buffer = new Array(Binary.BUFFER_SIZE);
  2421. }
  2422. }
  2423. }
  2424. /**
  2425. * Updates this binary with byte_value.
  2426. *
  2427. * @method
  2428. * @param {string} byte_value a single byte we wish to write.
  2429. */
  2430. _createClass(Binary, [{
  2431. key: "put",
  2432. value: function put(byte_value) {
  2433. // If it's a string and a has more than one character throw an error
  2434. if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new TypeError('only accepts single character String, Uint8Array or Array');
  2435. if (typeof byte_value !== 'number' && byte_value < 0 || byte_value > 255) throw new TypeError('only accepts number in a valid unsigned byte range 0-255'); // Decode the byte value once
  2436. var decoded_byte = null;
  2437. if (typeof byte_value === 'string') {
  2438. decoded_byte = byte_value.charCodeAt(0);
  2439. } else if (byte_value['length'] != null) {
  2440. decoded_byte = byte_value[0];
  2441. } else {
  2442. decoded_byte = byte_value;
  2443. }
  2444. if (this.buffer.length > this.position) {
  2445. this.buffer[this.position++] = decoded_byte;
  2446. } else {
  2447. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
  2448. // Create additional overflow buffer
  2449. var buffer$$1 = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length); // Combine the two buffers together
  2450. this.buffer.copy(buffer$$1, 0, 0, this.buffer.length);
  2451. this.buffer = buffer$$1;
  2452. this.buffer[this.position++] = decoded_byte;
  2453. } else {
  2454. var _buffer = null; // Create a new buffer (typed or normal array)
  2455. if (isUint8Array(this.buffer)) {
  2456. _buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length));
  2457. } else {
  2458. _buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length);
  2459. } // We need to copy all the content to the new array
  2460. for (var i = 0; i < this.buffer.length; i++) {
  2461. _buffer[i] = this.buffer[i];
  2462. } // Reassign the buffer
  2463. this.buffer = _buffer; // Write the byte
  2464. this.buffer[this.position++] = decoded_byte;
  2465. }
  2466. }
  2467. }
  2468. /**
  2469. * Writes a buffer or string to the binary.
  2470. *
  2471. * @method
  2472. * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object.
  2473. * @param {number} offset specify the binary of where to write the content.
  2474. * @return {null}
  2475. */
  2476. }, {
  2477. key: "write",
  2478. value: function write(string, offset) {
  2479. offset = typeof offset === 'number' ? offset : this.position; // If the buffer is to small let's extend the buffer
  2480. if (this.buffer.length < offset + string.length) {
  2481. var buffer$$1 = null; // If we are in node.js
  2482. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
  2483. buffer$$1 = Buffer.alloc(this.buffer.length + string.length);
  2484. this.buffer.copy(buffer$$1, 0, 0, this.buffer.length);
  2485. } else if (isUint8Array(this.buffer)) {
  2486. // Create a new buffer
  2487. buffer$$1 = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); // Copy the content
  2488. for (var i = 0; i < this.position; i++) {
  2489. buffer$$1[i] = this.buffer[i];
  2490. }
  2491. } // Assign the new buffer
  2492. this.buffer = buffer$$1;
  2493. }
  2494. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) {
  2495. string.copy(this.buffer, offset, 0, string.length);
  2496. this.position = offset + string.length > this.position ? offset + string.length : this.position; // offset = string.length
  2497. } else if (typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer)) {
  2498. this.buffer.write(string, offset, 'binary');
  2499. this.position = offset + string.length > this.position ? offset + string.length : this.position; // offset = string.length;
  2500. } else if (isUint8Array(string) || Array.isArray(string) && typeof string !== 'string') {
  2501. for (var _i = 0; _i < string.length; _i++) {
  2502. this.buffer[offset++] = string[_i];
  2503. }
  2504. this.position = offset > this.position ? offset : this.position;
  2505. } else if (typeof string === 'string') {
  2506. for (var _i2 = 0; _i2 < string.length; _i2++) {
  2507. this.buffer[offset++] = string.charCodeAt(_i2);
  2508. }
  2509. this.position = offset > this.position ? offset : this.position;
  2510. }
  2511. }
  2512. /**
  2513. * Reads **length** bytes starting at **position**.
  2514. *
  2515. * @method
  2516. * @param {number} position read from the given position in the Binary.
  2517. * @param {number} length the number of bytes to read.
  2518. * @return {Buffer}
  2519. */
  2520. }, {
  2521. key: "read",
  2522. value: function read(position, length) {
  2523. length = length && length > 0 ? length : this.position; // Let's return the data based on the type we have
  2524. if (this.buffer['slice']) {
  2525. return this.buffer.slice(position, position + length);
  2526. } // Create a buffer to keep the result
  2527. var buffer$$1 = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length);
  2528. for (var i = 0; i < length; i++) {
  2529. buffer$$1[i] = this.buffer[position++];
  2530. } // Return the buffer
  2531. return buffer$$1;
  2532. }
  2533. /**
  2534. * Returns the value of this binary as a string.
  2535. *
  2536. * @method
  2537. * @return {string}
  2538. */
  2539. }, {
  2540. key: "value",
  2541. value: function value(asRaw) {
  2542. asRaw = asRaw == null ? false : asRaw; // Optimize to serialize for the situation where the data == size of buffer
  2543. if (asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position) return this.buffer; // If it's a node.js buffer object
  2544. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
  2545. return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position);
  2546. } else {
  2547. if (asRaw) {
  2548. // we support the slice command use it
  2549. if (this.buffer['slice'] != null) {
  2550. return this.buffer.slice(0, this.position);
  2551. } else {
  2552. // Create a new buffer to copy content to
  2553. var newBuffer = isUint8Array(this.buffer) ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); // Copy content
  2554. for (var i = 0; i < this.position; i++) {
  2555. newBuffer[i] = this.buffer[i];
  2556. } // Return the buffer
  2557. return newBuffer;
  2558. }
  2559. } else {
  2560. return convertArraytoUtf8BinaryString(this.buffer, 0, this.position);
  2561. }
  2562. }
  2563. }
  2564. /**
  2565. * Length.
  2566. *
  2567. * @method
  2568. * @return {number} the length of the binary.
  2569. */
  2570. }, {
  2571. key: "length",
  2572. value: function length() {
  2573. return this.position;
  2574. }
  2575. /**
  2576. * @ignore
  2577. */
  2578. }, {
  2579. key: "toJSON",
  2580. value: function toJSON() {
  2581. return this.buffer != null ? this.buffer.toString('base64') : '';
  2582. }
  2583. /**
  2584. * @ignore
  2585. */
  2586. }, {
  2587. key: "toString",
  2588. value: function toString(format) {
  2589. return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : '';
  2590. }
  2591. /**
  2592. * @ignore
  2593. */
  2594. }, {
  2595. key: "toExtendedJSON",
  2596. value: function toExtendedJSON() {
  2597. var base64String = Buffer.isBuffer(this.buffer) ? this.buffer.toString('base64') : Buffer.from(this.buffer).toString('base64');
  2598. var subType = Number(this.sub_type).toString(16);
  2599. return {
  2600. $binary: {
  2601. base64: base64String,
  2602. subType: subType.length === 1 ? '0' + subType : subType
  2603. }
  2604. };
  2605. }
  2606. /**
  2607. * @ignore
  2608. */
  2609. }], [{
  2610. key: "fromExtendedJSON",
  2611. value: function fromExtendedJSON(doc) {
  2612. var type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  2613. var data = new Buffer(doc.$binary.base64, 'base64');
  2614. return new Binary(data, type);
  2615. }
  2616. }]);
  2617. return Binary;
  2618. }();
  2619. /**
  2620. * Binary default subtype
  2621. * @ignore
  2622. */
  2623. var BSON_BINARY_SUBTYPE_DEFAULT = 0;
  2624. function isUint8Array(obj) {
  2625. return Object.prototype.toString.call(obj) === '[object Uint8Array]';
  2626. }
  2627. /**
  2628. * @ignore
  2629. */
  2630. function writeStringToArray(data) {
  2631. // Create a buffer
  2632. var buffer$$1 = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); // Write the content to the buffer
  2633. for (var i = 0; i < data.length; i++) {
  2634. buffer$$1[i] = data.charCodeAt(i);
  2635. } // Write the string to the buffer
  2636. return buffer$$1;
  2637. }
  2638. /**
  2639. * Convert Array ot Uint8Array to Binary String
  2640. *
  2641. * @ignore
  2642. */
  2643. function convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex) {
  2644. var result = '';
  2645. for (var i = startIndex; i < endIndex; i++) {
  2646. result = result + String.fromCharCode(byteArray[i]);
  2647. }
  2648. return result;
  2649. }
  2650. Binary.BUFFER_SIZE = 256;
  2651. /**
  2652. * Default BSON type
  2653. *
  2654. * @classconstant SUBTYPE_DEFAULT
  2655. **/
  2656. Binary.SUBTYPE_DEFAULT = 0;
  2657. /**
  2658. * Function BSON type
  2659. *
  2660. * @classconstant SUBTYPE_DEFAULT
  2661. **/
  2662. Binary.SUBTYPE_FUNCTION = 1;
  2663. /**
  2664. * Byte Array BSON type
  2665. *
  2666. * @classconstant SUBTYPE_DEFAULT
  2667. **/
  2668. Binary.SUBTYPE_BYTE_ARRAY = 2;
  2669. /**
  2670. * OLD UUID BSON type
  2671. *
  2672. * @classconstant SUBTYPE_DEFAULT
  2673. **/
  2674. Binary.SUBTYPE_UUID_OLD = 3;
  2675. /**
  2676. * UUID BSON type
  2677. *
  2678. * @classconstant SUBTYPE_DEFAULT
  2679. **/
  2680. Binary.SUBTYPE_UUID = 4;
  2681. /**
  2682. * MD5 BSON type
  2683. *
  2684. * @classconstant SUBTYPE_DEFAULT
  2685. **/
  2686. Binary.SUBTYPE_MD5 = 5;
  2687. /**
  2688. * User BSON type
  2689. *
  2690. * @classconstant SUBTYPE_DEFAULT
  2691. **/
  2692. Binary.SUBTYPE_USER_DEFINED = 128;
  2693. Object.defineProperty(Binary.prototype, '_bsontype', {
  2694. value: 'Binary'
  2695. });
  2696. var binary = Binary;
  2697. var constants = {
  2698. // BSON MAX VALUES
  2699. BSON_INT32_MAX: 0x7fffffff,
  2700. BSON_INT32_MIN: -0x80000000,
  2701. BSON_INT64_MAX: Math.pow(2, 63) - 1,
  2702. BSON_INT64_MIN: -Math.pow(2, 63),
  2703. // JS MAX PRECISE VALUES
  2704. JS_INT_MAX: 0x20000000000000,
  2705. // Any integer up to 2^53 can be precisely represented by a double.
  2706. JS_INT_MIN: -0x20000000000000,
  2707. // Any integer down to -2^53 can be precisely represented by a double.
  2708. /**
  2709. * Number BSON Type
  2710. *
  2711. * @classconstant BSON_DATA_NUMBER
  2712. **/
  2713. BSON_DATA_NUMBER: 1,
  2714. /**
  2715. * String BSON Type
  2716. *
  2717. * @classconstant BSON_DATA_STRING
  2718. **/
  2719. BSON_DATA_STRING: 2,
  2720. /**
  2721. * Object BSON Type
  2722. *
  2723. * @classconstant BSON_DATA_OBJECT
  2724. **/
  2725. BSON_DATA_OBJECT: 3,
  2726. /**
  2727. * Array BSON Type
  2728. *
  2729. * @classconstant BSON_DATA_ARRAY
  2730. **/
  2731. BSON_DATA_ARRAY: 4,
  2732. /**
  2733. * Binary BSON Type
  2734. *
  2735. * @classconstant BSON_DATA_BINARY
  2736. **/
  2737. BSON_DATA_BINARY: 5,
  2738. /**
  2739. * Binary BSON Type
  2740. *
  2741. * @classconstant BSON_DATA_UNDEFINED
  2742. **/
  2743. BSON_DATA_UNDEFINED: 6,
  2744. /**
  2745. * ObjectId BSON Type
  2746. *
  2747. * @classconstant BSON_DATA_OID
  2748. **/
  2749. BSON_DATA_OID: 7,
  2750. /**
  2751. * Boolean BSON Type
  2752. *
  2753. * @classconstant BSON_DATA_BOOLEAN
  2754. **/
  2755. BSON_DATA_BOOLEAN: 8,
  2756. /**
  2757. * Date BSON Type
  2758. *
  2759. * @classconstant BSON_DATA_DATE
  2760. **/
  2761. BSON_DATA_DATE: 9,
  2762. /**
  2763. * null BSON Type
  2764. *
  2765. * @classconstant BSON_DATA_NULL
  2766. **/
  2767. BSON_DATA_NULL: 10,
  2768. /**
  2769. * RegExp BSON Type
  2770. *
  2771. * @classconstant BSON_DATA_REGEXP
  2772. **/
  2773. BSON_DATA_REGEXP: 11,
  2774. /**
  2775. * Code BSON Type
  2776. *
  2777. * @classconstant BSON_DATA_DBPOINTER
  2778. **/
  2779. BSON_DATA_DBPOINTER: 12,
  2780. /**
  2781. * Code BSON Type
  2782. *
  2783. * @classconstant BSON_DATA_CODE
  2784. **/
  2785. BSON_DATA_CODE: 13,
  2786. /**
  2787. * Symbol BSON Type
  2788. *
  2789. * @classconstant BSON_DATA_SYMBOL
  2790. **/
  2791. BSON_DATA_SYMBOL: 14,
  2792. /**
  2793. * Code with Scope BSON Type
  2794. *
  2795. * @classconstant BSON_DATA_CODE_W_SCOPE
  2796. **/
  2797. BSON_DATA_CODE_W_SCOPE: 15,
  2798. /**
  2799. * 32 bit Integer BSON Type
  2800. *
  2801. * @classconstant BSON_DATA_INT
  2802. **/
  2803. BSON_DATA_INT: 16,
  2804. /**
  2805. * Timestamp BSON Type
  2806. *
  2807. * @classconstant BSON_DATA_TIMESTAMP
  2808. **/
  2809. BSON_DATA_TIMESTAMP: 17,
  2810. /**
  2811. * Long BSON Type
  2812. *
  2813. * @classconstant BSON_DATA_LONG
  2814. **/
  2815. BSON_DATA_LONG: 18,
  2816. /**
  2817. * Long BSON Type
  2818. *
  2819. * @classconstant BSON_DATA_DECIMAL128
  2820. **/
  2821. BSON_DATA_DECIMAL128: 19,
  2822. /**
  2823. * MinKey BSON Type
  2824. *
  2825. * @classconstant BSON_DATA_MIN_KEY
  2826. **/
  2827. BSON_DATA_MIN_KEY: 0xff,
  2828. /**
  2829. * MaxKey BSON Type
  2830. *
  2831. * @classconstant BSON_DATA_MAX_KEY
  2832. **/
  2833. BSON_DATA_MAX_KEY: 0x7f,
  2834. /**
  2835. * Binary Default Type
  2836. *
  2837. * @classconstant BSON_BINARY_SUBTYPE_DEFAULT
  2838. **/
  2839. BSON_BINARY_SUBTYPE_DEFAULT: 0,
  2840. /**
  2841. * Binary Function Type
  2842. *
  2843. * @classconstant BSON_BINARY_SUBTYPE_FUNCTION
  2844. **/
  2845. BSON_BINARY_SUBTYPE_FUNCTION: 1,
  2846. /**
  2847. * Binary Byte Array Type
  2848. *
  2849. * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY
  2850. **/
  2851. BSON_BINARY_SUBTYPE_BYTE_ARRAY: 2,
  2852. /**
  2853. * Binary UUID Type
  2854. *
  2855. * @classconstant BSON_BINARY_SUBTYPE_UUID
  2856. **/
  2857. BSON_BINARY_SUBTYPE_UUID: 3,
  2858. /**
  2859. * Binary MD5 Type
  2860. *
  2861. * @classconstant BSON_BINARY_SUBTYPE_MD5
  2862. **/
  2863. BSON_BINARY_SUBTYPE_MD5: 4,
  2864. /**
  2865. * Binary User Defined Type
  2866. *
  2867. * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED
  2868. **/
  2869. BSON_BINARY_SUBTYPE_USER_DEFINED: 128
  2870. };
  2871. // const Map = require('./map');
  2872. /**
  2873. * @namespace EJSON
  2874. */
  2875. // all the types where we don't need to do any special processing and can just pass the EJSON
  2876. //straight to type.fromExtendedJSON
  2877. var keysToCodecs = {
  2878. $oid: objectid,
  2879. $binary: binary,
  2880. $symbol: symbol,
  2881. $numberInt: int_32,
  2882. $numberDecimal: decimal128,
  2883. $numberDouble: double_1,
  2884. $numberLong: long_1,
  2885. $minKey: min_key,
  2886. $maxKey: max_key,
  2887. $regularExpression: regexp,
  2888. $timestamp: timestamp
  2889. };
  2890. function deserializeValue(self, key, value, options) {
  2891. if (typeof value === 'number') {
  2892. if (options.relaxed) {
  2893. return value;
  2894. } // if it's an integer, should interpret as smallest BSON integer
  2895. // that can represent it exactly. (if out of range, interpret as double.)
  2896. if (Math.floor(value) === value) {
  2897. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) return new int_32(value);
  2898. if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) return new long_1.fromNumber(value);
  2899. } // If the number is a non-integer or out of integer range, should interpret as BSON Double.
  2900. return new double_1(value);
  2901. } // from here on out we're looking for bson types, so bail if its not an object
  2902. if (value == null || _typeof(value) !== 'object') return value; // upgrade deprecated undefined to null
  2903. if (value.$undefined) return null;
  2904. var keys = Object.keys(value).filter(function (k) {
  2905. return k.startsWith('$') && value[k] != null;
  2906. });
  2907. for (var i = 0; i < keys.length; i++) {
  2908. var c = keysToCodecs[keys[i]];
  2909. if (c) return c.fromExtendedJSON(value, options);
  2910. }
  2911. if (value.$date != null) {
  2912. var d = value.$date;
  2913. var date = new Date();
  2914. if (typeof d === 'string') date.setTime(Date.parse(d));else if (d instanceof long_1) date.setTime(d.toNumber());else if (typeof d === 'number' && options.relaxed) date.setTime(d);
  2915. return date;
  2916. }
  2917. if (value.$code != null) {
  2918. var copy = Object.assign({}, value);
  2919. if (value.$scope) {
  2920. copy.$scope = deserializeValue(self, null, value.$scope);
  2921. }
  2922. return code.fromExtendedJSON(value);
  2923. }
  2924. if (value.$ref != null || value.$dbPointer != null) {
  2925. var v = value.$ref ? value : value.$dbPointer; // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
  2926. // because of the order JSON.parse goes through the document
  2927. if (v instanceof db_ref) return v;
  2928. var dollarKeys = Object.keys(v).filter(function (k) {
  2929. return k.startsWith('$');
  2930. });
  2931. var valid = true;
  2932. dollarKeys.forEach(function (k) {
  2933. if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
  2934. }); // only make DBRef if $ keys are all valid
  2935. if (valid) return db_ref.fromExtendedJSON(v);
  2936. }
  2937. return value;
  2938. }
  2939. /**
  2940. * Parse an Extended JSON string, constructing the JavaScript value or object described by that
  2941. * string.
  2942. *
  2943. * @memberof EJSON
  2944. * @param {string} text
  2945. * @param {object} [options] Optional settings
  2946. * @param {boolean} [options.relaxed=true] Attempt to return native JS types where possible, rather than BSON types (if true)
  2947. * @return {object}
  2948. *
  2949. * @example
  2950. * const { EJSON } = require('bson');
  2951. * const text = '{ "int32": { "$numberInt": "10" } }';
  2952. *
  2953. * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
  2954. * console.log(EJSON.parse(text, { relaxed: false }));
  2955. *
  2956. * // prints { int32: 10 }
  2957. * console.log(EJSON.parse(text));
  2958. */
  2959. function parse(text, options) {
  2960. var _this = this;
  2961. options = Object.assign({}, {
  2962. relaxed: true
  2963. }, options); // relaxed implies not strict
  2964. if (typeof options.relaxed === 'boolean') options.strict = !options.relaxed;
  2965. if (typeof options.strict === 'boolean') options.relaxed = !options.strict;
  2966. return JSON.parse(text, function (key, value) {
  2967. return deserializeValue(_this, key, value, options);
  2968. });
  2969. } //
  2970. // Serializer
  2971. //
  2972. // MAX INT32 boundaries
  2973. var BSON_INT32_MAX = 0x7fffffff,
  2974. BSON_INT32_MIN = -0x80000000,
  2975. BSON_INT64_MAX = 0x7fffffffffffffff,
  2976. BSON_INT64_MIN = -0x8000000000000000;
  2977. /**
  2978. * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
  2979. * function is specified or optionally including only the specified properties if a replacer array
  2980. * is specified.
  2981. *
  2982. * @memberof EJSON
  2983. * @param {object} value The value to convert to extended JSON
  2984. * @param {function|array} [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
  2985. * @param {string|number} [space] A String or Number object that's used to insert white space into the output JSON string for readability purposes.
  2986. * @param {object} [options] Optional settings
  2987. * @param {boolean} [options.relaxed=true] Enabled Extended JSON's `relaxed` mode
  2988. * @returns {string}
  2989. *
  2990. * @example
  2991. * const { EJSON } = require('bson');
  2992. * const Int32 = require('mongodb').Int32;
  2993. * const doc = { int32: new Int32(10) };
  2994. *
  2995. * // prints '{"int32":{"$numberInt":"10"}}'
  2996. * console.log(EJSON.stringify(doc, { relaxed: false }));
  2997. *
  2998. * // prints '{"int32":10}'
  2999. * console.log(EJSON.stringify(doc));
  3000. */
  3001. function stringify(value, replacer, space, options) {
  3002. if (space != null && _typeof(space) === 'object') options = space, space = 0;
  3003. if (replacer != null && _typeof(replacer) === 'object') options = replacer, replacer = null, space = 0;
  3004. options = Object.assign({}, {
  3005. relaxed: true
  3006. }, options);
  3007. var doc = Array.isArray(value) ? serializeArray(value, options) : serializeDocument(value, options);
  3008. return JSON.stringify(doc, replacer, space);
  3009. }
  3010. /**
  3011. * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
  3012. *
  3013. * @memberof EJSON
  3014. * @param {object} bson The object to serialize
  3015. * @param {object} [options] Optional settings passed to the `stringify` function
  3016. * @return {object}
  3017. */
  3018. function serialize(bson, options) {
  3019. options = options || {};
  3020. return JSON.parse(stringify(bson, options));
  3021. }
  3022. /**
  3023. * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
  3024. *
  3025. * @memberof EJSON
  3026. * @param {object} ejson The Extended JSON object to deserialize
  3027. * @param {object} [options] Optional settings passed to the parse method
  3028. * @return {object}
  3029. */
  3030. function deserialize(ejson, options) {
  3031. options = options || {};
  3032. return parse(JSON.stringify(ejson), options);
  3033. }
  3034. function serializeArray(array, options) {
  3035. return array.map(function (v) {
  3036. return serializeValue(v, options);
  3037. });
  3038. }
  3039. function getISOString(date) {
  3040. var isoStr = date.toISOString(); // we should only show milliseconds in timestamp if they're non-zero
  3041. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  3042. }
  3043. function serializeValue(value, options) {
  3044. if (Array.isArray(value)) return serializeArray(value, options);
  3045. if (value === undefined) return null;
  3046. if (value instanceof Date) {
  3047. var dateNum = value.getTime(),
  3048. // is it in year range 1970-9999?
  3049. inRange = dateNum > -1 && dateNum < 253402318800000;
  3050. return options.relaxed && inRange ? {
  3051. $date: getISOString(value)
  3052. } : {
  3053. $date: {
  3054. $numberLong: value.getTime().toString()
  3055. }
  3056. };
  3057. }
  3058. if (typeof value === 'number' && !options.relaxed) {
  3059. // it's an integer
  3060. if (Math.floor(value) === value) {
  3061. var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX,
  3062. int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX; // interpret as being of the smallest BSON integer type that can represent the number exactly
  3063. if (int32Range) return {
  3064. $numberInt: value.toString()
  3065. };
  3066. if (int64Range) return {
  3067. $numberLong: value.toString()
  3068. };
  3069. }
  3070. return {
  3071. $numberDouble: value.toString()
  3072. };
  3073. }
  3074. if (value != null && _typeof(value) === 'object') return serializeDocument(value, options);
  3075. return value;
  3076. }
  3077. function serializeDocument(doc, options) {
  3078. if (doc == null || _typeof(doc) !== 'object') throw new Error('not an object instance'); // the document itself is a BSON type
  3079. if (doc._bsontype && typeof doc.toExtendedJSON === 'function') {
  3080. if (doc._bsontype === 'Code' && doc.scope) {
  3081. doc.scope = serializeDocument(doc.scope, options);
  3082. } else if (doc._bsontype === 'DBRef' && doc.oid) {
  3083. doc.oid = serializeDocument(doc.oid, options);
  3084. }
  3085. return doc.toExtendedJSON(options);
  3086. } // the document is an object with nested BSON types
  3087. var _doc = {};
  3088. for (var name in doc) {
  3089. var val = doc[name];
  3090. if (Array.isArray(val)) {
  3091. _doc[name] = serializeArray(val, options);
  3092. } else if (val != null && typeof val.toExtendedJSON === 'function') {
  3093. if (val._bsontype === 'Code' && val.scope) {
  3094. val.scope = serializeDocument(val.scope, options);
  3095. } else if (val._bsontype === 'DBRef' && val.oid) {
  3096. val.oid = serializeDocument(val.oid, options);
  3097. }
  3098. _doc[name] = val.toExtendedJSON(options);
  3099. } else if (val instanceof Date) {
  3100. _doc[name] = serializeValue(val, options);
  3101. } else if (val != null && _typeof(val) === 'object') {
  3102. _doc[name] = serializeDocument(val, options);
  3103. }
  3104. _doc[name] = serializeValue(val, options);
  3105. if (val instanceof RegExp) {
  3106. var flags = val.flags;
  3107. if (flags === undefined) {
  3108. flags = val.toString().match(/[gimuy]*$/)[0];
  3109. }
  3110. var rx = new regexp(val.source, flags);
  3111. _doc[name] = rx.toExtendedJSON();
  3112. }
  3113. }
  3114. return _doc;
  3115. }
  3116. var extended_json = {
  3117. parse: parse,
  3118. deserialize: deserialize,
  3119. serialize: serialize,
  3120. stringify: stringify
  3121. };
  3122. var FIRST_BIT = 0x80;
  3123. var FIRST_TWO_BITS = 0xc0;
  3124. var FIRST_THREE_BITS = 0xe0;
  3125. var FIRST_FOUR_BITS = 0xf0;
  3126. var FIRST_FIVE_BITS = 0xf8;
  3127. var TWO_BIT_CHAR = 0xc0;
  3128. var THREE_BIT_CHAR = 0xe0;
  3129. var FOUR_BIT_CHAR = 0xf0;
  3130. var CONTINUING_CHAR = 0x80;
  3131. /**
  3132. * Determines if the passed in bytes are valid utf8
  3133. * @param {Buffer|Uint8Array} bytes An array of 8-bit bytes. Must be indexable and have length property
  3134. * @param {Number} start The index to start validating
  3135. * @param {Number} end The index to end validating
  3136. * @returns {boolean} True if valid utf8
  3137. */
  3138. function validateUtf8(bytes, start, end) {
  3139. var continuation = 0;
  3140. for (var i = start; i < end; i += 1) {
  3141. var byte = bytes[i];
  3142. if (continuation) {
  3143. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  3144. return false;
  3145. }
  3146. continuation -= 1;
  3147. } else if (byte & FIRST_BIT) {
  3148. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  3149. continuation = 1;
  3150. } else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  3151. continuation = 2;
  3152. } else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  3153. continuation = 3;
  3154. } else {
  3155. return false;
  3156. }
  3157. }
  3158. }
  3159. return !continuation;
  3160. }
  3161. var validateUtf8_1 = validateUtf8;
  3162. var validate_utf8 = {
  3163. validateUtf8: validateUtf8_1
  3164. };
  3165. var Buffer$2 = buffer.Buffer;
  3166. var validateUtf8$1 = validate_utf8.validateUtf8; // Internal long versions
  3167. var JS_INT_MAX_LONG = long_1.fromNumber(constants.JS_INT_MAX);
  3168. var JS_INT_MIN_LONG = long_1.fromNumber(constants.JS_INT_MIN);
  3169. var functionCache = {};
  3170. function deserialize$1(buffer$$1, options, isArray) {
  3171. options = options == null ? {} : options;
  3172. var index = options && options.index ? options.index : 0; // Read the document size
  3173. var size = buffer$$1[index] | buffer$$1[index + 1] << 8 | buffer$$1[index + 2] << 16 | buffer$$1[index + 3] << 24;
  3174. if (size < 5) {
  3175. throw new Error("bson size must be >= 5, is ".concat(size));
  3176. }
  3177. if (options.allowObjectSmallerThanBufferSize && buffer$$1.length < size) {
  3178. throw new Error("buffer length ".concat(buffer$$1.length, " must be >= bson size ").concat(size));
  3179. }
  3180. if (!options.allowObjectSmallerThanBufferSize && buffer$$1.length !== size) {
  3181. throw new Error("buffer length ".concat(buffer$$1.length, " must === bson size ").concat(size));
  3182. }
  3183. if (size + index > buffer$$1.length) {
  3184. throw new Error("(bson size ".concat(size, " + options.index ").concat(index, " must be <= buffer length ").concat(Buffer$2.byteLength(buffer$$1), ")"));
  3185. } // Illegal end value
  3186. if (buffer$$1[index + size - 1] !== 0) {
  3187. throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  3188. } // Start deserializtion
  3189. return deserializeObject(buffer$$1, index, options, isArray);
  3190. }
  3191. function deserializeObject(buffer$$1, index, options, isArray) {
  3192. var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];
  3193. var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];
  3194. var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32'];
  3195. if (!cacheFunctionsCrc32) var crc32 = null;
  3196. var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; // Return raw bson buffer instead of parsing it
  3197. var raw = options['raw'] == null ? false : options['raw']; // Return BSONRegExp objects instead of native regular expressions
  3198. var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; // Controls the promotion of values vs wrapper classes
  3199. var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
  3200. var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
  3201. var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; // Set the start index
  3202. var startIndex = index; // Validate that we have at least 4 bytes of buffer
  3203. if (buffer$$1.length < 5) throw new Error('corrupt bson message < 5 bytes long'); // Read the document size
  3204. var size = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Ensure buffer is valid size
  3205. if (size < 5 || size > buffer$$1.length) throw new Error('corrupt bson message'); // Create holding object
  3206. var object = isArray ? [] : {}; // Used for arrays to skip having to perform utf8 decoding
  3207. var arrayIndex = 0;
  3208. var done = false; // While we have more left data left keep parsing
  3209. while (!done) {
  3210. // Read the type
  3211. var elementType = buffer$$1[index++]; // If we get a zero it's the last byte, exit
  3212. if (elementType === 0) break; // Get the start search index
  3213. var i = index; // Locate the end of the c string
  3214. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3215. i++;
  3216. } // If are at the end of the buffer there is a problem with the document
  3217. if (i >= Buffer$2.byteLength(buffer$$1)) throw new Error('Bad BSON Document: illegal CString');
  3218. var name = isArray ? arrayIndex++ : buffer$$1.toString('utf8', index, i);
  3219. index = i + 1;
  3220. if (elementType === constants.BSON_DATA_STRING) {
  3221. var stringSize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3222. if (stringSize <= 0 || stringSize > buffer$$1.length - index || buffer$$1[index + stringSize - 1] !== 0) throw new Error('bad string length in bson');
  3223. if (!validateUtf8$1(buffer$$1, index, index + stringSize - 1)) {
  3224. throw new Error('Invalid UTF-8 string in BSON document');
  3225. }
  3226. var s = buffer$$1.toString('utf8', index, index + stringSize - 1);
  3227. object[name] = s;
  3228. index = index + stringSize;
  3229. } else if (elementType === constants.BSON_DATA_OID) {
  3230. var oid = Buffer$2.alloc(12);
  3231. buffer$$1.copy(oid, 0, index, index + 12);
  3232. object[name] = new objectid(oid);
  3233. index = index + 12;
  3234. } else if (elementType === constants.BSON_DATA_INT && promoteValues === false) {
  3235. object[name] = new int_32(buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24);
  3236. } else if (elementType === constants.BSON_DATA_INT) {
  3237. object[name] = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3238. } else if (elementType === constants.BSON_DATA_NUMBER && promoteValues === false) {
  3239. object[name] = new double_1(buffer$$1.readDoubleLE(index));
  3240. index = index + 8;
  3241. } else if (elementType === constants.BSON_DATA_NUMBER) {
  3242. object[name] = buffer$$1.readDoubleLE(index);
  3243. index = index + 8;
  3244. } else if (elementType === constants.BSON_DATA_DATE) {
  3245. var lowBits = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3246. var highBits = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3247. object[name] = new Date(new long_1(lowBits, highBits).toNumber());
  3248. } else if (elementType === constants.BSON_DATA_BOOLEAN) {
  3249. if (buffer$$1[index] !== 0 && buffer$$1[index] !== 1) throw new Error('illegal boolean type value');
  3250. object[name] = buffer$$1[index++] === 1;
  3251. } else if (elementType === constants.BSON_DATA_OBJECT) {
  3252. var _index = index;
  3253. var objectSize = buffer$$1[index] | buffer$$1[index + 1] << 8 | buffer$$1[index + 2] << 16 | buffer$$1[index + 3] << 24;
  3254. if (objectSize <= 0 || objectSize > buffer$$1.length - index) throw new Error('bad embedded document length in bson'); // We have a raw value
  3255. if (raw) {
  3256. object[name] = buffer$$1.slice(index, index + objectSize);
  3257. } else {
  3258. object[name] = deserializeObject(buffer$$1, _index, options, false);
  3259. }
  3260. index = index + objectSize;
  3261. } else if (elementType === constants.BSON_DATA_ARRAY) {
  3262. var _index2 = index;
  3263. var _objectSize = buffer$$1[index] | buffer$$1[index + 1] << 8 | buffer$$1[index + 2] << 16 | buffer$$1[index + 3] << 24;
  3264. var arrayOptions = options; // Stop index
  3265. var stopIndex = index + _objectSize; // All elements of array to be returned as raw bson
  3266. if (fieldsAsRaw && fieldsAsRaw[name]) {
  3267. arrayOptions = {};
  3268. for (var n in options) {
  3269. arrayOptions[n] = options[n];
  3270. }
  3271. arrayOptions['raw'] = true;
  3272. }
  3273. object[name] = deserializeObject(buffer$$1, _index2, arrayOptions, true);
  3274. index = index + _objectSize;
  3275. if (buffer$$1[index - 1] !== 0) throw new Error('invalid array terminator byte');
  3276. if (index !== stopIndex) throw new Error('corrupted array bson');
  3277. } else if (elementType === constants.BSON_DATA_UNDEFINED) {
  3278. object[name] = undefined;
  3279. } else if (elementType === constants.BSON_DATA_NULL) {
  3280. object[name] = null;
  3281. } else if (elementType === constants.BSON_DATA_LONG) {
  3282. // Unpack the low and high bits
  3283. var _lowBits = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3284. var _highBits = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3285. var long$$1 = new long_1(_lowBits, _highBits); // Promote the long if possible
  3286. if (promoteLongs && promoteValues === true) {
  3287. object[name] = long$$1.lessThanOrEqual(JS_INT_MAX_LONG) && long$$1.greaterThanOrEqual(JS_INT_MIN_LONG) ? long$$1.toNumber() : long$$1;
  3288. } else {
  3289. object[name] = long$$1;
  3290. }
  3291. } else if (elementType === constants.BSON_DATA_DECIMAL128) {
  3292. // Buffer to contain the decimal bytes
  3293. var bytes = Buffer$2.alloc(16); // Copy the next 16 bytes into the bytes buffer
  3294. buffer$$1.copy(bytes, 0, index, index + 16); // Update index
  3295. index = index + 16; // Assign the new Decimal128 value
  3296. var decimal128$$1 = new decimal128(bytes); // If we have an alternative mapper use that
  3297. object[name] = decimal128$$1.toObject ? decimal128$$1.toObject() : decimal128$$1;
  3298. } else if (elementType === constants.BSON_DATA_BINARY) {
  3299. var binarySize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3300. var totalBinarySize = binarySize;
  3301. var subType = buffer$$1[index++]; // Did we have a negative binary size, throw
  3302. if (binarySize < 0) throw new Error('Negative binary type element size found'); // Is the length longer than the document
  3303. if (binarySize > Buffer$2.byteLength(buffer$$1)) throw new Error('Binary type size larger than document size'); // Decode as raw Buffer object if options specifies it
  3304. if (buffer$$1['slice'] != null) {
  3305. // If we have subtype 2 skip the 4 bytes for the size
  3306. if (subType === binary.SUBTYPE_BYTE_ARRAY) {
  3307. binarySize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3308. if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02');
  3309. if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size');
  3310. if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size');
  3311. }
  3312. if (promoteBuffers && promoteValues) {
  3313. object[name] = buffer$$1.slice(index, index + binarySize);
  3314. } else {
  3315. object[name] = new binary(buffer$$1.slice(index, index + binarySize), subType);
  3316. }
  3317. } else {
  3318. var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); // If we have subtype 2 skip the 4 bytes for the size
  3319. if (subType === binary.SUBTYPE_BYTE_ARRAY) {
  3320. binarySize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3321. if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02');
  3322. if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size');
  3323. if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size');
  3324. } // Copy the data
  3325. for (i = 0; i < binarySize; i++) {
  3326. _buffer[i] = buffer$$1[index + i];
  3327. }
  3328. if (promoteBuffers && promoteValues) {
  3329. object[name] = _buffer;
  3330. } else {
  3331. object[name] = new binary(_buffer, subType);
  3332. }
  3333. } // Update the index
  3334. index = index + binarySize;
  3335. } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === false) {
  3336. // Get the start search index
  3337. i = index; // Locate the end of the c string
  3338. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3339. i++;
  3340. } // If are at the end of the buffer there is a problem with the document
  3341. if (i >= buffer$$1.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string
  3342. var source = buffer$$1.toString('utf8', index, i); // Create the regexp
  3343. index = i + 1; // Get the start search index
  3344. i = index; // Locate the end of the c string
  3345. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3346. i++;
  3347. } // If are at the end of the buffer there is a problem with the document
  3348. if (i >= buffer$$1.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string
  3349. var regExpOptions = buffer$$1.toString('utf8', index, i);
  3350. index = i + 1; // For each option add the corresponding one for javascript
  3351. var optionsArray = new Array(regExpOptions.length); // Parse options
  3352. for (i = 0; i < regExpOptions.length; i++) {
  3353. switch (regExpOptions[i]) {
  3354. case 'm':
  3355. optionsArray[i] = 'm';
  3356. break;
  3357. case 's':
  3358. optionsArray[i] = 'g';
  3359. break;
  3360. case 'i':
  3361. optionsArray[i] = 'i';
  3362. break;
  3363. }
  3364. }
  3365. object[name] = new RegExp(source, optionsArray.join(''));
  3366. } else if (elementType === constants.BSON_DATA_REGEXP && bsonRegExp === true) {
  3367. // Get the start search index
  3368. i = index; // Locate the end of the c string
  3369. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3370. i++;
  3371. } // If are at the end of the buffer there is a problem with the document
  3372. if (i >= buffer$$1.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string
  3373. var _source = buffer$$1.toString('utf8', index, i);
  3374. index = i + 1; // Get the start search index
  3375. i = index; // Locate the end of the c string
  3376. while (buffer$$1[i] !== 0x00 && i < buffer$$1.length) {
  3377. i++;
  3378. } // If are at the end of the buffer there is a problem with the document
  3379. if (i >= buffer$$1.length) throw new Error('Bad BSON Document: illegal CString'); // Return the C string
  3380. var _regExpOptions = buffer$$1.toString('utf8', index, i);
  3381. index = i + 1; // Set the object
  3382. object[name] = new regexp(_source, _regExpOptions);
  3383. } else if (elementType === constants.BSON_DATA_SYMBOL) {
  3384. var _stringSize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3385. if (_stringSize <= 0 || _stringSize > buffer$$1.length - index || buffer$$1[index + _stringSize - 1] !== 0) throw new Error('bad string length in bson'); // symbol is deprecated - upgrade to string.
  3386. object[name] = buffer$$1.toString('utf8', index, index + _stringSize - 1);
  3387. index = index + _stringSize;
  3388. } else if (elementType === constants.BSON_DATA_TIMESTAMP) {
  3389. var _lowBits2 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3390. var _highBits2 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3391. object[name] = new timestamp(_lowBits2, _highBits2);
  3392. } else if (elementType === constants.BSON_DATA_MIN_KEY) {
  3393. object[name] = new min_key();
  3394. } else if (elementType === constants.BSON_DATA_MAX_KEY) {
  3395. object[name] = new max_key();
  3396. } else if (elementType === constants.BSON_DATA_CODE) {
  3397. var _stringSize2 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24;
  3398. if (_stringSize2 <= 0 || _stringSize2 > buffer$$1.length - index || buffer$$1[index + _stringSize2 - 1] !== 0) throw new Error('bad string length in bson');
  3399. var functionString = buffer$$1.toString('utf8', index, index + _stringSize2 - 1); // If we are evaluating the functions
  3400. if (evalFunctions) {
  3401. // If we have cache enabled let's look for the md5 of the function in the cache
  3402. if (cacheFunctions) {
  3403. var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; // Got to do this to avoid V8 deoptimizing the call due to finding eval
  3404. object[name] = isolateEvalWithHash(functionCache, hash, functionString, object);
  3405. } else {
  3406. object[name] = isolateEval(functionString);
  3407. }
  3408. } else {
  3409. object[name] = new code(functionString);
  3410. } // Update parse index position
  3411. index = index + _stringSize2;
  3412. } else if (elementType === constants.BSON_DATA_CODE_W_SCOPE) {
  3413. var totalSize = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
  3414. if (totalSize < 4 + 4 + 4 + 1) {
  3415. throw new Error('code_w_scope total size shorter minimum expected length');
  3416. } // Get the code string size
  3417. var _stringSize3 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Check if we have a valid string
  3418. if (_stringSize3 <= 0 || _stringSize3 > buffer$$1.length - index || buffer$$1[index + _stringSize3 - 1] !== 0) throw new Error('bad string length in bson'); // Javascript function
  3419. var _functionString = buffer$$1.toString('utf8', index, index + _stringSize3 - 1); // Update parse index position
  3420. index = index + _stringSize3; // Parse the element
  3421. var _index3 = index; // Decode the size of the object document
  3422. var _objectSize2 = buffer$$1[index] | buffer$$1[index + 1] << 8 | buffer$$1[index + 2] << 16 | buffer$$1[index + 3] << 24; // Decode the scope object
  3423. var scopeObject = deserializeObject(buffer$$1, _index3, options, false); // Adjust the index
  3424. index = index + _objectSize2; // Check if field length is to short
  3425. if (totalSize < 4 + 4 + _objectSize2 + _stringSize3) {
  3426. throw new Error('code_w_scope total size is to short, truncating scope');
  3427. } // Check if totalSize field is to long
  3428. if (totalSize > 4 + 4 + _objectSize2 + _stringSize3) {
  3429. throw new Error('code_w_scope total size is to long, clips outer document');
  3430. } // If we are evaluating the functions
  3431. if (evalFunctions) {
  3432. // If we have cache enabled let's look for the md5 of the function in the cache
  3433. if (cacheFunctions) {
  3434. var _hash = cacheFunctionsCrc32 ? crc32(_functionString) : _functionString; // Got to do this to avoid V8 deoptimizing the call due to finding eval
  3435. object[name] = isolateEvalWithHash(functionCache, _hash, _functionString, object);
  3436. } else {
  3437. object[name] = isolateEval(_functionString);
  3438. }
  3439. object[name].scope = scopeObject;
  3440. } else {
  3441. object[name] = new code(_functionString, scopeObject);
  3442. }
  3443. } else if (elementType === constants.BSON_DATA_DBPOINTER) {
  3444. // Get the code string size
  3445. var _stringSize4 = buffer$$1[index++] | buffer$$1[index++] << 8 | buffer$$1[index++] << 16 | buffer$$1[index++] << 24; // Check if we have a valid string
  3446. if (_stringSize4 <= 0 || _stringSize4 > buffer$$1.length - index || buffer$$1[index + _stringSize4 - 1] !== 0) throw new Error('bad string length in bson'); // Namespace
  3447. if (!validateUtf8$1(buffer$$1, index, index + _stringSize4 - 1)) {
  3448. throw new Error('Invalid UTF-8 string in BSON document');
  3449. }
  3450. var namespace = buffer$$1.toString('utf8', index, index + _stringSize4 - 1); // Update parse index position
  3451. index = index + _stringSize4; // Read the oid
  3452. var oidBuffer = Buffer$2.alloc(12);
  3453. buffer$$1.copy(oidBuffer, 0, index, index + 12);
  3454. var _oid = new objectid(oidBuffer); // Update the index
  3455. index = index + 12; // Upgrade to DBRef type
  3456. object[name] = new db_ref(namespace, _oid);
  3457. } else {
  3458. throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser?');
  3459. }
  3460. } // Check if the deserialization was against a valid array/object
  3461. if (size !== index - startIndex) {
  3462. if (isArray) throw new Error('corrupt array bson');
  3463. throw new Error('corrupt object bson');
  3464. } // check if object's $ keys are those of a DBRef
  3465. var dollarKeys = Object.keys(object).filter(function (k) {
  3466. return k.startsWith('$');
  3467. });
  3468. var valid = true;
  3469. dollarKeys.forEach(function (k) {
  3470. if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
  3471. }); // if a $key not in "$ref", "$id", "$db", don't make a DBRef
  3472. if (!valid) return object;
  3473. if (object['$id'] != null && object['$ref'] != null) {
  3474. var copy = Object.assign({}, object);
  3475. delete copy.$ref;
  3476. delete copy.$id;
  3477. delete copy.$db;
  3478. return new db_ref(object.$ref, object.$id, object.$db || null, copy);
  3479. }
  3480. return object;
  3481. }
  3482. /**
  3483. * Ensure eval is isolated.
  3484. *
  3485. * @ignore
  3486. * @api private
  3487. */
  3488. function isolateEvalWithHash(functionCache, hash, functionString, object) {
  3489. // Contains the value we are going to set
  3490. var value = null; // Check for cache hit, eval if missing and return cached function
  3491. if (functionCache[hash] == null) {
  3492. eval('value = ' + functionString);
  3493. functionCache[hash] = value;
  3494. } // Set the object
  3495. return functionCache[hash].bind(object);
  3496. }
  3497. /**
  3498. * Ensure eval is isolated.
  3499. *
  3500. * @ignore
  3501. * @api private
  3502. */
  3503. function isolateEval(functionString) {
  3504. // Contains the value we are going to set
  3505. var value = null; // Eval the function
  3506. eval('value = ' + functionString);
  3507. return value;
  3508. }
  3509. var deserializer = deserialize$1;
  3510. // All rights reserved.
  3511. //
  3512. // Redistribution and use in source and binary forms, with or without
  3513. // modification, are permitted provided that the following conditions are met:
  3514. //
  3515. // * Redistributions of source code must retain the above copyright notice,
  3516. // this list of conditions and the following disclaimer.
  3517. //
  3518. // * Redistributions in binary form must reproduce the above copyright notice,
  3519. // this list of conditions and the following disclaimer in the documentation
  3520. // and/or other materials provided with the distribution.
  3521. //
  3522. // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors
  3523. // may be used to endorse or promote products derived from this software
  3524. // without specific prior written permission.
  3525. //
  3526. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3527. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3528. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3529. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  3530. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  3531. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  3532. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  3533. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  3534. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  3535. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  3536. // POSSIBILITY OF SUCH DAMAGE.
  3537. //
  3538. //
  3539. // Modifications to writeIEEE754 to support negative zeroes made by Brian White
  3540. function readIEEE754(buffer$$1, offset, endian, mLen, nBytes) {
  3541. var e,
  3542. m,
  3543. bBE = endian === 'big',
  3544. eLen = nBytes * 8 - mLen - 1,
  3545. eMax = (1 << eLen) - 1,
  3546. eBias = eMax >> 1,
  3547. nBits = -7,
  3548. i = bBE ? 0 : nBytes - 1,
  3549. d = bBE ? 1 : -1,
  3550. s = buffer$$1[offset + i];
  3551. i += d;
  3552. e = s & (1 << -nBits) - 1;
  3553. s >>= -nBits;
  3554. nBits += eLen;
  3555. for (; nBits > 0; e = e * 256 + buffer$$1[offset + i], i += d, nBits -= 8) {
  3556. }
  3557. m = e & (1 << -nBits) - 1;
  3558. e >>= -nBits;
  3559. nBits += mLen;
  3560. for (; nBits > 0; m = m * 256 + buffer$$1[offset + i], i += d, nBits -= 8) {
  3561. }
  3562. if (e === 0) {
  3563. e = 1 - eBias;
  3564. } else if (e === eMax) {
  3565. return m ? NaN : (s ? -1 : 1) * Infinity;
  3566. } else {
  3567. m = m + Math.pow(2, mLen);
  3568. e = e - eBias;
  3569. }
  3570. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  3571. }
  3572. function writeIEEE754(buffer$$1, value, offset, endian, mLen, nBytes) {
  3573. var e,
  3574. m,
  3575. c,
  3576. bBE = endian === 'big',
  3577. eLen = nBytes * 8 - mLen - 1,
  3578. eMax = (1 << eLen) - 1,
  3579. eBias = eMax >> 1,
  3580. rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0,
  3581. i = bBE ? nBytes - 1 : 0,
  3582. d = bBE ? -1 : 1,
  3583. s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  3584. value = Math.abs(value);
  3585. if (isNaN(value) || value === Infinity) {
  3586. m = isNaN(value) ? 1 : 0;
  3587. e = eMax;
  3588. } else {
  3589. e = Math.floor(Math.log(value) / Math.LN2);
  3590. if (value * (c = Math.pow(2, -e)) < 1) {
  3591. e--;
  3592. c *= 2;
  3593. }
  3594. if (e + eBias >= 1) {
  3595. value += rt / c;
  3596. } else {
  3597. value += rt * Math.pow(2, 1 - eBias);
  3598. }
  3599. if (value * c >= 2) {
  3600. e++;
  3601. c /= 2;
  3602. }
  3603. if (e + eBias >= eMax) {
  3604. m = 0;
  3605. e = eMax;
  3606. } else if (e + eBias >= 1) {
  3607. m = (value * c - 1) * Math.pow(2, mLen);
  3608. e = e + eBias;
  3609. } else {
  3610. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  3611. e = 0;
  3612. }
  3613. }
  3614. if (isNaN(value)) m = 0;
  3615. while (mLen >= 8) {
  3616. buffer$$1[offset + i] = m & 0xff;
  3617. i += d;
  3618. m /= 256;
  3619. mLen -= 8;
  3620. }
  3621. e = e << mLen | m;
  3622. if (isNaN(value)) e += 8;
  3623. eLen += mLen;
  3624. while (eLen > 0) {
  3625. buffer$$1[offset + i] = e & 0xff;
  3626. i += d;
  3627. e /= 256;
  3628. eLen -= 8;
  3629. }
  3630. buffer$$1[offset + i - d] |= s * 128;
  3631. }
  3632. var float_parser = {
  3633. readIEEE754: readIEEE754,
  3634. writeIEEE754: writeIEEE754
  3635. };
  3636. var Buffer$3 = buffer.Buffer;
  3637. var writeIEEE754$1 = float_parser.writeIEEE754;
  3638. var normalizedFunctionString$1 = utils.normalizedFunctionString;
  3639. var regexp$1 = /\x00/; // eslint-disable-line no-control-regex
  3640. var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); // To ensure that 0.4 of node works correctly
  3641. var isDate$1 = function isDate(d) {
  3642. return _typeof(d) === 'object' && Object.prototype.toString.call(d) === '[object Date]';
  3643. };
  3644. var isRegExp$1 = function isRegExp(d) {
  3645. return Object.prototype.toString.call(d) === '[object RegExp]';
  3646. };
  3647. function serializeString(buffer$$1, key, value, index, isArray) {
  3648. // Encode String type
  3649. buffer$$1[index++] = constants.BSON_DATA_STRING; // Number of written bytes
  3650. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3651. index = index + numberOfWrittenBytes + 1;
  3652. buffer$$1[index - 1] = 0; // Write the string
  3653. var size = buffer$$1.write(value, index + 4, 'utf8'); // Write the size of the string to buffer
  3654. buffer$$1[index + 3] = size + 1 >> 24 & 0xff;
  3655. buffer$$1[index + 2] = size + 1 >> 16 & 0xff;
  3656. buffer$$1[index + 1] = size + 1 >> 8 & 0xff;
  3657. buffer$$1[index] = size + 1 & 0xff; // Update index
  3658. index = index + 4 + size; // Write zero
  3659. buffer$$1[index++] = 0;
  3660. return index;
  3661. }
  3662. function serializeNumber(buffer$$1, key, value, index, isArray) {
  3663. // We have an integer value
  3664. if (Math.floor(value) === value && value >= constants.JS_INT_MIN && value <= constants.JS_INT_MAX) {
  3665. // If the value fits in 32 bits encode as int, if it fits in a double
  3666. // encode it as a double, otherwise long
  3667. if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) {
  3668. // Set int type 32 bits or less
  3669. buffer$$1[index++] = constants.BSON_DATA_INT; // Number of written bytes
  3670. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3671. index = index + numberOfWrittenBytes;
  3672. buffer$$1[index++] = 0; // Write the int value
  3673. buffer$$1[index++] = value & 0xff;
  3674. buffer$$1[index++] = value >> 8 & 0xff;
  3675. buffer$$1[index++] = value >> 16 & 0xff;
  3676. buffer$$1[index++] = value >> 24 & 0xff;
  3677. } else if (value >= constants.JS_INT_MIN && value <= constants.JS_INT_MAX) {
  3678. // Encode as double
  3679. buffer$$1[index++] = constants.BSON_DATA_NUMBER; // Number of written bytes
  3680. var _numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3681. index = index + _numberOfWrittenBytes;
  3682. buffer$$1[index++] = 0; // Write float
  3683. writeIEEE754$1(buffer$$1, value, index, 'little', 52, 8); // Ajust index
  3684. index = index + 8;
  3685. } else {
  3686. // Set long type
  3687. buffer$$1[index++] = constants.BSON_DATA_LONG; // Number of written bytes
  3688. var _numberOfWrittenBytes2 = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3689. index = index + _numberOfWrittenBytes2;
  3690. buffer$$1[index++] = 0;
  3691. var longVal = long_1.fromNumber(value);
  3692. var lowBits = longVal.getLowBits();
  3693. var highBits = longVal.getHighBits(); // Encode low bits
  3694. buffer$$1[index++] = lowBits & 0xff;
  3695. buffer$$1[index++] = lowBits >> 8 & 0xff;
  3696. buffer$$1[index++] = lowBits >> 16 & 0xff;
  3697. buffer$$1[index++] = lowBits >> 24 & 0xff; // Encode high bits
  3698. buffer$$1[index++] = highBits & 0xff;
  3699. buffer$$1[index++] = highBits >> 8 & 0xff;
  3700. buffer$$1[index++] = highBits >> 16 & 0xff;
  3701. buffer$$1[index++] = highBits >> 24 & 0xff;
  3702. }
  3703. } else {
  3704. // Encode as double
  3705. buffer$$1[index++] = constants.BSON_DATA_NUMBER; // Number of written bytes
  3706. var _numberOfWrittenBytes3 = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3707. index = index + _numberOfWrittenBytes3;
  3708. buffer$$1[index++] = 0; // Write float
  3709. writeIEEE754$1(buffer$$1, value, index, 'little', 52, 8); // Ajust index
  3710. index = index + 8;
  3711. }
  3712. return index;
  3713. }
  3714. function serializeNull(buffer$$1, key, value, index, isArray) {
  3715. // Set long type
  3716. buffer$$1[index++] = constants.BSON_DATA_NULL; // Number of written bytes
  3717. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3718. index = index + numberOfWrittenBytes;
  3719. buffer$$1[index++] = 0;
  3720. return index;
  3721. }
  3722. function serializeBoolean(buffer$$1, key, value, index, isArray) {
  3723. // Write the type
  3724. buffer$$1[index++] = constants.BSON_DATA_BOOLEAN; // Number of written bytes
  3725. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3726. index = index + numberOfWrittenBytes;
  3727. buffer$$1[index++] = 0; // Encode the boolean value
  3728. buffer$$1[index++] = value ? 1 : 0;
  3729. return index;
  3730. }
  3731. function serializeDate(buffer$$1, key, value, index, isArray) {
  3732. // Write the type
  3733. buffer$$1[index++] = constants.BSON_DATA_DATE; // Number of written bytes
  3734. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3735. index = index + numberOfWrittenBytes;
  3736. buffer$$1[index++] = 0; // Write the date
  3737. var dateInMilis = long_1.fromNumber(value.getTime());
  3738. var lowBits = dateInMilis.getLowBits();
  3739. var highBits = dateInMilis.getHighBits(); // Encode low bits
  3740. buffer$$1[index++] = lowBits & 0xff;
  3741. buffer$$1[index++] = lowBits >> 8 & 0xff;
  3742. buffer$$1[index++] = lowBits >> 16 & 0xff;
  3743. buffer$$1[index++] = lowBits >> 24 & 0xff; // Encode high bits
  3744. buffer$$1[index++] = highBits & 0xff;
  3745. buffer$$1[index++] = highBits >> 8 & 0xff;
  3746. buffer$$1[index++] = highBits >> 16 & 0xff;
  3747. buffer$$1[index++] = highBits >> 24 & 0xff;
  3748. return index;
  3749. }
  3750. function serializeRegExp(buffer$$1, key, value, index, isArray) {
  3751. // Write the type
  3752. buffer$$1[index++] = constants.BSON_DATA_REGEXP; // Number of written bytes
  3753. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3754. index = index + numberOfWrittenBytes;
  3755. buffer$$1[index++] = 0;
  3756. if (value.source && value.source.match(regexp$1) != null) {
  3757. throw Error('value ' + value.source + ' must not contain null bytes');
  3758. } // Adjust the index
  3759. index = index + buffer$$1.write(value.source, index, 'utf8'); // Write zero
  3760. buffer$$1[index++] = 0x00; // Write the parameters
  3761. if (value.ignoreCase) buffer$$1[index++] = 0x69; // i
  3762. if (value.global) buffer$$1[index++] = 0x73; // s
  3763. if (value.multiline) buffer$$1[index++] = 0x6d; // m
  3764. // Add ending zero
  3765. buffer$$1[index++] = 0x00;
  3766. return index;
  3767. }
  3768. function serializeBSONRegExp(buffer$$1, key, value, index, isArray) {
  3769. // Write the type
  3770. buffer$$1[index++] = constants.BSON_DATA_REGEXP; // Number of written bytes
  3771. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3772. index = index + numberOfWrittenBytes;
  3773. buffer$$1[index++] = 0; // Check the pattern for 0 bytes
  3774. if (value.pattern.match(regexp$1) != null) {
  3775. // The BSON spec doesn't allow keys with null bytes because keys are
  3776. // null-terminated.
  3777. throw Error('pattern ' + value.pattern + ' must not contain null bytes');
  3778. } // Adjust the index
  3779. index = index + buffer$$1.write(value.pattern, index, 'utf8'); // Write zero
  3780. buffer$$1[index++] = 0x00; // Write the options
  3781. index = index + buffer$$1.write(value.options.split('').sort().join(''), index, 'utf8'); // Add ending zero
  3782. buffer$$1[index++] = 0x00;
  3783. return index;
  3784. }
  3785. function serializeMinMax(buffer$$1, key, value, index, isArray) {
  3786. console.log({
  3787. value: value,
  3788. MinKey: min_key,
  3789. isMinKey: value instanceof min_key
  3790. }); // Write the type of either min or max key
  3791. if (value === null) {
  3792. buffer$$1[index++] = constants.BSON_DATA_NULL;
  3793. } else if (value instanceof min_key) {
  3794. buffer$$1[index++] = constants.BSON_DATA_MIN_KEY;
  3795. } else {
  3796. buffer$$1[index++] = constants.BSON_DATA_MAX_KEY;
  3797. } // Number of written bytes
  3798. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3799. index = index + numberOfWrittenBytes;
  3800. buffer$$1[index++] = 0;
  3801. return index;
  3802. }
  3803. function serializeObjectId(buffer$$1, key, value, index, isArray) {
  3804. // Write the type
  3805. buffer$$1[index++] = constants.BSON_DATA_OID; // Number of written bytes
  3806. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3807. index = index + numberOfWrittenBytes;
  3808. buffer$$1[index++] = 0; // Write the objectId into the shared buffer
  3809. if (typeof value.id === 'string') {
  3810. buffer$$1.write(value.id, index, 'binary');
  3811. } else if (value.id && value.id.copy) {
  3812. value.id.copy(buffer$$1, index, 0, 12);
  3813. } else {
  3814. throw new TypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
  3815. } // Ajust index
  3816. return index + 12;
  3817. }
  3818. function serializeBuffer(buffer$$1, key, value, index, isArray) {
  3819. // Write the type
  3820. buffer$$1[index++] = constants.BSON_DATA_BINARY; // Number of written bytes
  3821. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3822. index = index + numberOfWrittenBytes;
  3823. buffer$$1[index++] = 0; // Get size of the buffer (current write point)
  3824. var size = value.length; // Write the size of the string to buffer
  3825. buffer$$1[index++] = size & 0xff;
  3826. buffer$$1[index++] = size >> 8 & 0xff;
  3827. buffer$$1[index++] = size >> 16 & 0xff;
  3828. buffer$$1[index++] = size >> 24 & 0xff; // Write the default subtype
  3829. buffer$$1[index++] = constants.BSON_BINARY_SUBTYPE_DEFAULT; // Copy the content form the binary field to the buffer
  3830. value.copy(buffer$$1, index, 0, size); // Adjust the index
  3831. index = index + size;
  3832. return index;
  3833. }
  3834. function serializeObject(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) {
  3835. for (var i = 0; i < path.length; i++) {
  3836. if (path[i] === value) throw new Error('cyclic dependency detected');
  3837. } // Push value to stack
  3838. path.push(value); // Write the type
  3839. buffer$$1[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; // Number of written bytes
  3840. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3841. index = index + numberOfWrittenBytes;
  3842. buffer$$1[index++] = 0;
  3843. var endIndex = serializeInto(buffer$$1, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); // Pop stack
  3844. path.pop();
  3845. return endIndex;
  3846. }
  3847. function serializeDecimal128(buffer$$1, key, value, index, isArray) {
  3848. buffer$$1[index++] = constants.BSON_DATA_DECIMAL128; // Number of written bytes
  3849. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3850. index = index + numberOfWrittenBytes;
  3851. buffer$$1[index++] = 0; // Write the data from the value
  3852. value.bytes.copy(buffer$$1, index, 0, 16);
  3853. return index + 16;
  3854. }
  3855. function serializeLong(buffer$$1, key, value, index, isArray) {
  3856. // Write the type
  3857. buffer$$1[index++] = value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; // Number of written bytes
  3858. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3859. index = index + numberOfWrittenBytes;
  3860. buffer$$1[index++] = 0; // Write the date
  3861. var lowBits = value.getLowBits();
  3862. var highBits = value.getHighBits(); // Encode low bits
  3863. buffer$$1[index++] = lowBits & 0xff;
  3864. buffer$$1[index++] = lowBits >> 8 & 0xff;
  3865. buffer$$1[index++] = lowBits >> 16 & 0xff;
  3866. buffer$$1[index++] = lowBits >> 24 & 0xff; // Encode high bits
  3867. buffer$$1[index++] = highBits & 0xff;
  3868. buffer$$1[index++] = highBits >> 8 & 0xff;
  3869. buffer$$1[index++] = highBits >> 16 & 0xff;
  3870. buffer$$1[index++] = highBits >> 24 & 0xff;
  3871. return index;
  3872. }
  3873. function serializeInt32(buffer$$1, key, value, index, isArray) {
  3874. // Set int type 32 bits or less
  3875. buffer$$1[index++] = constants.BSON_DATA_INT; // Number of written bytes
  3876. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3877. index = index + numberOfWrittenBytes;
  3878. buffer$$1[index++] = 0; // Write the int value
  3879. buffer$$1[index++] = value & 0xff;
  3880. buffer$$1[index++] = value >> 8 & 0xff;
  3881. buffer$$1[index++] = value >> 16 & 0xff;
  3882. buffer$$1[index++] = value >> 24 & 0xff;
  3883. return index;
  3884. }
  3885. function serializeDouble(buffer$$1, key, value, index, isArray) {
  3886. // Encode as double
  3887. buffer$$1[index++] = constants.BSON_DATA_NUMBER; // Number of written bytes
  3888. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3889. index = index + numberOfWrittenBytes;
  3890. buffer$$1[index++] = 0; // Write float
  3891. writeIEEE754$1(buffer$$1, value.value, index, 'little', 52, 8); // Adjust index
  3892. index = index + 8;
  3893. return index;
  3894. }
  3895. function serializeFunction(buffer$$1, key, value, index, checkKeys, depth, isArray) {
  3896. buffer$$1[index++] = constants.BSON_DATA_CODE; // Number of written bytes
  3897. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3898. index = index + numberOfWrittenBytes;
  3899. buffer$$1[index++] = 0; // Function string
  3900. var functionString = normalizedFunctionString$1(value); // Write the string
  3901. var size = buffer$$1.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer
  3902. buffer$$1[index] = size & 0xff;
  3903. buffer$$1[index + 1] = size >> 8 & 0xff;
  3904. buffer$$1[index + 2] = size >> 16 & 0xff;
  3905. buffer$$1[index + 3] = size >> 24 & 0xff; // Update index
  3906. index = index + 4 + size - 1; // Write zero
  3907. buffer$$1[index++] = 0;
  3908. return index;
  3909. }
  3910. function serializeCode(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) {
  3911. if (value.scope && _typeof(value.scope) === 'object') {
  3912. // Write the type
  3913. buffer$$1[index++] = constants.BSON_DATA_CODE_W_SCOPE; // Number of written bytes
  3914. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3915. index = index + numberOfWrittenBytes;
  3916. buffer$$1[index++] = 0; // Starting index
  3917. var startIndex = index; // Serialize the function
  3918. // Get the function string
  3919. var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); // Index adjustment
  3920. index = index + 4; // Write string into buffer
  3921. var codeSize = buffer$$1.write(functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer
  3922. buffer$$1[index] = codeSize & 0xff;
  3923. buffer$$1[index + 1] = codeSize >> 8 & 0xff;
  3924. buffer$$1[index + 2] = codeSize >> 16 & 0xff;
  3925. buffer$$1[index + 3] = codeSize >> 24 & 0xff; // Write end 0
  3926. buffer$$1[index + 4 + codeSize - 1] = 0; // Write the
  3927. index = index + codeSize + 4; //
  3928. // Serialize the scope value
  3929. var endIndex = serializeInto(buffer$$1, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined);
  3930. index = endIndex - 1; // Writ the total
  3931. var totalSize = endIndex - startIndex; // Write the total size of the object
  3932. buffer$$1[startIndex++] = totalSize & 0xff;
  3933. buffer$$1[startIndex++] = totalSize >> 8 & 0xff;
  3934. buffer$$1[startIndex++] = totalSize >> 16 & 0xff;
  3935. buffer$$1[startIndex++] = totalSize >> 24 & 0xff; // Write trailing zero
  3936. buffer$$1[index++] = 0;
  3937. } else {
  3938. buffer$$1[index++] = constants.BSON_DATA_CODE; // Number of written bytes
  3939. var _numberOfWrittenBytes4 = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3940. index = index + _numberOfWrittenBytes4;
  3941. buffer$$1[index++] = 0; // Function string
  3942. var _functionString = value.code.toString(); // Write the string
  3943. var size = buffer$$1.write(_functionString, index + 4, 'utf8') + 1; // Write the size of the string to buffer
  3944. buffer$$1[index] = size & 0xff;
  3945. buffer$$1[index + 1] = size >> 8 & 0xff;
  3946. buffer$$1[index + 2] = size >> 16 & 0xff;
  3947. buffer$$1[index + 3] = size >> 24 & 0xff; // Update index
  3948. index = index + 4 + size - 1; // Write zero
  3949. buffer$$1[index++] = 0;
  3950. }
  3951. return index;
  3952. }
  3953. function serializeBinary(buffer$$1, key, value, index, isArray) {
  3954. // Write the type
  3955. buffer$$1[index++] = constants.BSON_DATA_BINARY; // Number of written bytes
  3956. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3957. index = index + numberOfWrittenBytes;
  3958. buffer$$1[index++] = 0; // Extract the buffer
  3959. var data = value.value(true); // Calculate size
  3960. var size = value.position; // Add the deprecated 02 type 4 bytes of size to total
  3961. if (value.sub_type === binary.SUBTYPE_BYTE_ARRAY) size = size + 4; // Write the size of the string to buffer
  3962. buffer$$1[index++] = size & 0xff;
  3963. buffer$$1[index++] = size >> 8 & 0xff;
  3964. buffer$$1[index++] = size >> 16 & 0xff;
  3965. buffer$$1[index++] = size >> 24 & 0xff; // Write the subtype to the buffer
  3966. buffer$$1[index++] = value.sub_type; // If we have binary type 2 the 4 first bytes are the size
  3967. if (value.sub_type === binary.SUBTYPE_BYTE_ARRAY) {
  3968. size = size - 4;
  3969. buffer$$1[index++] = size & 0xff;
  3970. buffer$$1[index++] = size >> 8 & 0xff;
  3971. buffer$$1[index++] = size >> 16 & 0xff;
  3972. buffer$$1[index++] = size >> 24 & 0xff;
  3973. } // Write the data to the object
  3974. data.copy(buffer$$1, index, 0, value.position); // Adjust the index
  3975. index = index + value.position;
  3976. return index;
  3977. }
  3978. function serializeSymbol(buffer$$1, key, value, index, isArray) {
  3979. // Write the type
  3980. buffer$$1[index++] = constants.BSON_DATA_SYMBOL; // Number of written bytes
  3981. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3982. index = index + numberOfWrittenBytes;
  3983. buffer$$1[index++] = 0; // Write the string
  3984. var size = buffer$$1.write(value.value, index + 4, 'utf8') + 1; // Write the size of the string to buffer
  3985. buffer$$1[index] = size & 0xff;
  3986. buffer$$1[index + 1] = size >> 8 & 0xff;
  3987. buffer$$1[index + 2] = size >> 16 & 0xff;
  3988. buffer$$1[index + 3] = size >> 24 & 0xff; // Update index
  3989. index = index + 4 + size - 1; // Write zero
  3990. buffer$$1[index++] = 0x00;
  3991. return index;
  3992. }
  3993. function serializeDBRef(buffer$$1, key, value, index, depth, serializeFunctions, isArray) {
  3994. // Write the type
  3995. buffer$$1[index++] = constants.BSON_DATA_OBJECT; // Number of written bytes
  3996. var numberOfWrittenBytes = !isArray ? buffer$$1.write(key, index, 'utf8') : buffer$$1.write(key, index, 'ascii'); // Encode the name
  3997. index = index + numberOfWrittenBytes;
  3998. buffer$$1[index++] = 0;
  3999. var startIndex = index;
  4000. var endIndex;
  4001. var output = {
  4002. $ref: value.collection,
  4003. $id: value.oid
  4004. };
  4005. if (value.db != null) output.$db = value.db;
  4006. output = Object.assign(output, value.fields);
  4007. endIndex = serializeInto(buffer$$1, output, false, index, depth + 1, serializeFunctions); // Calculate object size
  4008. var size = endIndex - startIndex; // Write the size
  4009. buffer$$1[startIndex++] = size & 0xff;
  4010. buffer$$1[startIndex++] = size >> 8 & 0xff;
  4011. buffer$$1[startIndex++] = size >> 16 & 0xff;
  4012. buffer$$1[startIndex++] = size >> 24 & 0xff; // Set index
  4013. return endIndex;
  4014. }
  4015. function serializeInto(buffer$$1, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  4016. startingIndex = startingIndex || 0;
  4017. path = path || []; // Push the object to the path
  4018. path.push(object); // Start place to serialize into
  4019. var index = startingIndex + 4; // Special case isArray
  4020. if (Array.isArray(object)) {
  4021. // Get object keys
  4022. for (var i = 0; i < object.length; i++) {
  4023. var key = '' + i;
  4024. var value = object[i]; // Is there an override value
  4025. if (value && value.toBSON) {
  4026. if (typeof value.toBSON !== 'function') throw new TypeError('toBSON is not a function');
  4027. value = value.toBSON();
  4028. }
  4029. var type = _typeof(value);
  4030. if (type === 'string') {
  4031. index = serializeString(buffer$$1, key, value, index, true);
  4032. } else if (type === 'number') {
  4033. index = serializeNumber(buffer$$1, key, value, index, true);
  4034. } else if (type === 'boolean') {
  4035. index = serializeBoolean(buffer$$1, key, value, index, true);
  4036. } else if (value instanceof Date || isDate$1(value)) {
  4037. index = serializeDate(buffer$$1, key, value, index, true);
  4038. } else if (value === undefined) {
  4039. index = serializeNull(buffer$$1, key, value, index, true);
  4040. } else if (value === null) {
  4041. index = serializeNull(buffer$$1, key, value, index, true);
  4042. } else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  4043. index = serializeObjectId(buffer$$1, key, value, index, true);
  4044. } else if (Buffer$3.isBuffer(value)) {
  4045. index = serializeBuffer(buffer$$1, key, value, index, true);
  4046. } else if (value instanceof RegExp || isRegExp$1(value)) {
  4047. index = serializeRegExp(buffer$$1, key, value, index, true);
  4048. } else if (type === 'object' && value['_bsontype'] == null) {
  4049. index = serializeObject(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path);
  4050. } else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  4051. index = serializeDecimal128(buffer$$1, key, value, index, true);
  4052. } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  4053. index = serializeLong(buffer$$1, key, value, index, true);
  4054. } else if (value['_bsontype'] === 'Double') {
  4055. index = serializeDouble(buffer$$1, key, value, index, true);
  4056. } else if (typeof value === 'function' && serializeFunctions) {
  4057. index = serializeFunction(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, true);
  4058. } else if (value['_bsontype'] === 'Code') {
  4059. index = serializeCode(buffer$$1, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true);
  4060. } else if (value['_bsontype'] === 'Binary') {
  4061. index = serializeBinary(buffer$$1, key, value, index, true);
  4062. } else if (value['_bsontype'] === 'Symbol') {
  4063. index = serializeSymbol(buffer$$1, key, value, index, true);
  4064. } else if (value['_bsontype'] === 'DBRef') {
  4065. index = serializeDBRef(buffer$$1, key, value, index, depth, serializeFunctions, true);
  4066. } else if (value['_bsontype'] === 'BSONRegExp') {
  4067. index = serializeBSONRegExp(buffer$$1, key, value, index, true);
  4068. } else if (value['_bsontype'] === 'Int32') {
  4069. index = serializeInt32(buffer$$1, key, value, index, true);
  4070. } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  4071. index = serializeMinMax(buffer$$1, key, value, index, true);
  4072. }
  4073. }
  4074. } else if (object instanceof map) {
  4075. var iterator = object.entries();
  4076. var done = false;
  4077. while (!done) {
  4078. // Unpack the next entry
  4079. var entry = iterator.next();
  4080. done = entry.done; // Are we done, then skip and terminate
  4081. if (done) continue; // Get the entry values
  4082. var _key = entry.value[0];
  4083. var _value = entry.value[1]; // Check the type of the value
  4084. var _type = _typeof(_value); // Check the key and throw error if it's illegal
  4085. if (typeof _key === 'string' && !ignoreKeys.has(_key)) {
  4086. if (_key.match(regexp$1) != null) {
  4087. // The BSON spec doesn't allow keys with null bytes because keys are
  4088. // null-terminated.
  4089. throw Error('key ' + _key + ' must not contain null bytes');
  4090. }
  4091. if (checkKeys) {
  4092. if ('$' === _key[0]) {
  4093. throw Error('key ' + _key + " must not start with '$'");
  4094. } else if (~_key.indexOf('.')) {
  4095. throw Error('key ' + _key + " must not contain '.'");
  4096. }
  4097. }
  4098. }
  4099. if (_type === 'string') {
  4100. index = serializeString(buffer$$1, _key, _value, index);
  4101. } else if (_type === 'number') {
  4102. index = serializeNumber(buffer$$1, _key, _value, index);
  4103. } else if (_type === 'boolean') {
  4104. index = serializeBoolean(buffer$$1, _key, _value, index);
  4105. } else if (_value instanceof Date || isDate$1(_value)) {
  4106. index = serializeDate(buffer$$1, _key, _value, index);
  4107. } else if (_value === null || _value === undefined && ignoreUndefined === false) {
  4108. index = serializeNull(buffer$$1, _key, _value, index);
  4109. } else if (_value['_bsontype'] === 'ObjectId' || _value['_bsontype'] === 'ObjectID') {
  4110. index = serializeObjectId(buffer$$1, _key, _value, index);
  4111. } else if (Buffer$3.isBuffer(_value)) {
  4112. index = serializeBuffer(buffer$$1, _key, _value, index);
  4113. } else if (_value instanceof RegExp || isRegExp$1(_value)) {
  4114. index = serializeRegExp(buffer$$1, _key, _value, index);
  4115. } else if (_type === 'object' && _value['_bsontype'] == null) {
  4116. index = serializeObject(buffer$$1, _key, _value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  4117. } else if (_type === 'object' && _value['_bsontype'] === 'Decimal128') {
  4118. index = serializeDecimal128(buffer$$1, _key, _value, index);
  4119. } else if (_value['_bsontype'] === 'Long' || _value['_bsontype'] === 'Timestamp') {
  4120. index = serializeLong(buffer$$1, _key, _value, index);
  4121. } else if (_value['_bsontype'] === 'Double') {
  4122. index = serializeDouble(buffer$$1, _key, _value, index);
  4123. } else if (_value['_bsontype'] === 'Code') {
  4124. index = serializeCode(buffer$$1, _key, _value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  4125. } else if (typeof _value === 'function' && serializeFunctions) {
  4126. index = serializeFunction(buffer$$1, _key, _value, index, checkKeys, depth, serializeFunctions);
  4127. } else if (_value['_bsontype'] === 'Binary') {
  4128. index = serializeBinary(buffer$$1, _key, _value, index);
  4129. } else if (_value['_bsontype'] === 'Symbol') {
  4130. index = serializeSymbol(buffer$$1, _key, _value, index);
  4131. } else if (_value['_bsontype'] === 'DBRef') {
  4132. index = serializeDBRef(buffer$$1, _key, _value, index, depth, serializeFunctions);
  4133. } else if (_value['_bsontype'] === 'BSONRegExp') {
  4134. index = serializeBSONRegExp(buffer$$1, _key, _value, index);
  4135. } else if (_value['_bsontype'] === 'Int32') {
  4136. index = serializeInt32(buffer$$1, _key, _value, index);
  4137. } else if (_value['_bsontype'] === 'MinKey' || _value['_bsontype'] === 'MaxKey') {
  4138. index = serializeMinMax(buffer$$1, _key, _value, index);
  4139. }
  4140. }
  4141. } else {
  4142. // Did we provide a custom serialization method
  4143. if (object.toBSON) {
  4144. if (typeof object.toBSON !== 'function') throw new TypeError('toBSON is not a function');
  4145. object = object.toBSON();
  4146. if (object != null && _typeof(object) !== 'object') throw new TypeError('toBSON function did not return an object');
  4147. } // Iterate over all the keys
  4148. for (var _key2 in object) {
  4149. var _value2 = object[_key2]; // Is there an override value
  4150. if (_value2 && _value2.toBSON) {
  4151. if (typeof _value2.toBSON !== 'function') throw new TypeError('toBSON is not a function');
  4152. _value2 = _value2.toBSON();
  4153. } // Check the type of the value
  4154. var _type2 = _typeof(_value2); // Check the key and throw error if it's illegal
  4155. if (typeof _key2 === 'string' && !ignoreKeys.has(_key2)) {
  4156. if (_key2.match(regexp$1) != null) {
  4157. // The BSON spec doesn't allow keys with null bytes because keys are
  4158. // null-terminated.
  4159. throw Error('key ' + _key2 + ' must not contain null bytes');
  4160. }
  4161. if (checkKeys) {
  4162. if ('$' === _key2[0]) {
  4163. throw Error('key ' + _key2 + " must not start with '$'");
  4164. } else if (~_key2.indexOf('.')) {
  4165. throw Error('key ' + _key2 + " must not contain '.'");
  4166. }
  4167. }
  4168. }
  4169. if (_type2 === 'string') {
  4170. index = serializeString(buffer$$1, _key2, _value2, index);
  4171. } else if (_type2 === 'number') {
  4172. index = serializeNumber(buffer$$1, _key2, _value2, index);
  4173. } else if (_type2 === 'boolean') {
  4174. index = serializeBoolean(buffer$$1, _key2, _value2, index);
  4175. } else if (_value2 instanceof Date || isDate$1(_value2)) {
  4176. index = serializeDate(buffer$$1, _key2, _value2, index);
  4177. } else if (_value2 === undefined) {
  4178. if (ignoreUndefined === false) index = serializeNull(buffer$$1, _key2, _value2, index);
  4179. } else if (_value2 === null) {
  4180. index = serializeNull(buffer$$1, _key2, _value2, index);
  4181. } else if (_value2['_bsontype'] === 'ObjectId' || _value2['_bsontype'] === 'ObjectID') {
  4182. index = serializeObjectId(buffer$$1, _key2, _value2, index);
  4183. } else if (Buffer$3.isBuffer(_value2)) {
  4184. index = serializeBuffer(buffer$$1, _key2, _value2, index);
  4185. } else if (_value2 instanceof RegExp || isRegExp$1(_value2)) {
  4186. index = serializeRegExp(buffer$$1, _key2, _value2, index);
  4187. } else if (_type2 === 'object' && _value2['_bsontype'] == null) {
  4188. index = serializeObject(buffer$$1, _key2, _value2, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  4189. } else if (_type2 === 'object' && _value2['_bsontype'] === 'Decimal128') {
  4190. index = serializeDecimal128(buffer$$1, _key2, _value2, index);
  4191. } else if (_value2['_bsontype'] === 'Long' || _value2['_bsontype'] === 'Timestamp') {
  4192. index = serializeLong(buffer$$1, _key2, _value2, index);
  4193. } else if (_value2['_bsontype'] === 'Double') {
  4194. index = serializeDouble(buffer$$1, _key2, _value2, index);
  4195. } else if (_value2['_bsontype'] === 'Code') {
  4196. index = serializeCode(buffer$$1, _key2, _value2, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  4197. } else if (typeof _value2 === 'function' && serializeFunctions) {
  4198. index = serializeFunction(buffer$$1, _key2, _value2, index, checkKeys, depth, serializeFunctions);
  4199. } else if (_value2['_bsontype'] === 'Binary') {
  4200. index = serializeBinary(buffer$$1, _key2, _value2, index);
  4201. } else if (_value2['_bsontype'] === 'Symbol') {
  4202. index = serializeSymbol(buffer$$1, _key2, _value2, index);
  4203. } else if (_value2['_bsontype'] === 'DBRef') {
  4204. index = serializeDBRef(buffer$$1, _key2, _value2, index, depth, serializeFunctions);
  4205. } else if (_value2['_bsontype'] === 'BSONRegExp') {
  4206. index = serializeBSONRegExp(buffer$$1, _key2, _value2, index);
  4207. } else if (_value2['_bsontype'] === 'Int32') {
  4208. index = serializeInt32(buffer$$1, _key2, _value2, index);
  4209. } else if (_value2['_bsontype'] === 'MinKey' || _value2['_bsontype'] === 'MaxKey') {
  4210. index = serializeMinMax(buffer$$1, _key2, _value2, index);
  4211. }
  4212. }
  4213. } // Remove the path
  4214. path.pop(); // Final padding byte for object
  4215. buffer$$1[index++] = 0x00; // Final size
  4216. var size = index - startingIndex; // Write the size of the object
  4217. buffer$$1[startingIndex++] = size & 0xff;
  4218. buffer$$1[startingIndex++] = size >> 8 & 0xff;
  4219. buffer$$1[startingIndex++] = size >> 16 & 0xff;
  4220. buffer$$1[startingIndex++] = size >> 24 & 0xff;
  4221. return index;
  4222. }
  4223. var serializer = serializeInto;
  4224. var Buffer$4 = buffer.Buffer;
  4225. var normalizedFunctionString$2 = utils.normalizedFunctionString; // To ensure that 0.4 of node works correctly
  4226. function isDate$2(d) {
  4227. return _typeof(d) === 'object' && Object.prototype.toString.call(d) === '[object Date]';
  4228. }
  4229. function calculateObjectSize(object, serializeFunctions, ignoreUndefined) {
  4230. var totalLength = 4 + 1;
  4231. if (Array.isArray(object)) {
  4232. for (var i = 0; i < object.length; i++) {
  4233. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  4234. }
  4235. } else {
  4236. // If we have toBSON defined, override the current object
  4237. if (object.toBSON) {
  4238. object = object.toBSON();
  4239. } // Calculate size
  4240. for (var key in object) {
  4241. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  4242. }
  4243. }
  4244. return totalLength;
  4245. }
  4246. /**
  4247. * @ignore
  4248. * @api private
  4249. */
  4250. function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) {
  4251. // If we have toBSON defined, override the current object
  4252. if (value && value.toBSON) {
  4253. value = value.toBSON();
  4254. }
  4255. switch (_typeof(value)) {
  4256. case 'string':
  4257. return 1 + Buffer$4.byteLength(name, 'utf8') + 1 + 4 + Buffer$4.byteLength(value, 'utf8') + 1;
  4258. case 'number':
  4259. if (Math.floor(value) === value && value >= constants.JS_INT_MIN && value <= constants.JS_INT_MAX) {
  4260. if (value >= constants.BSON_INT32_MIN && value <= constants.BSON_INT32_MAX) {
  4261. // 32 bit
  4262. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (4 + 1);
  4263. } else {
  4264. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  4265. }
  4266. } else {
  4267. // 64 bit
  4268. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  4269. }
  4270. case 'undefined':
  4271. if (isArray || !ignoreUndefined) return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1;
  4272. return 0;
  4273. case 'boolean':
  4274. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (1 + 1);
  4275. case 'object':
  4276. if (value == null || value instanceof min_key || value instanceof max_key || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  4277. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1;
  4278. } else if (value instanceof objectid || value['_bsontype'] === 'ObjectId') {
  4279. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (12 + 1);
  4280. } else if (value instanceof Date || isDate$2(value)) {
  4281. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  4282. } else if (typeof Buffer$4 !== 'undefined' && Buffer$4.isBuffer(value)) {
  4283. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length;
  4284. } else if (value instanceof long_1 || value instanceof double_1 || value instanceof timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') {
  4285. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  4286. } else if (value instanceof decimal128 || value['_bsontype'] === 'Decimal128') {
  4287. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (16 + 1);
  4288. } else if (value instanceof code || value['_bsontype'] === 'Code') {
  4289. // Calculate size depending on the availability of a scope
  4290. if (value.scope != null && Object.keys(value.scope).length > 0) {
  4291. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer$4.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined);
  4292. } else {
  4293. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer$4.byteLength(value.code.toString(), 'utf8') + 1;
  4294. }
  4295. } else if (value instanceof binary || value['_bsontype'] === 'Binary') {
  4296. // Check what kind of subtype we have
  4297. if (value.sub_type === binary.SUBTYPE_BYTE_ARRAY) {
  4298. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4);
  4299. } else {
  4300. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1);
  4301. }
  4302. } else if (value instanceof symbol || value['_bsontype'] === 'Symbol') {
  4303. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + Buffer$4.byteLength(value.value, 'utf8') + 4 + 1 + 1;
  4304. } else if (value instanceof db_ref || value['_bsontype'] === 'DBRef') {
  4305. // Set up correct object for serialization
  4306. var ordered_values = Object.assign({
  4307. $ref: value.collection,
  4308. $id: value.oid
  4309. }, value.fields); // Add db reference if it exists
  4310. if (value.db != null) {
  4311. ordered_values['$db'] = value.db;
  4312. }
  4313. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined);
  4314. } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') {
  4315. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer$4.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1;
  4316. } else if (value instanceof regexp || value['_bsontype'] === 'BSONRegExp') {
  4317. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer$4.byteLength(value.pattern, 'utf8') + 1 + Buffer$4.byteLength(value.options, 'utf8') + 1;
  4318. } else {
  4319. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1;
  4320. }
  4321. case 'function':
  4322. // WTF for 0.4.X where typeof /someregexp/ === 'function'
  4323. if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') {
  4324. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer$4.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1;
  4325. } else {
  4326. if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
  4327. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer$4.byteLength(normalizedFunctionString$2(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined);
  4328. } else if (serializeFunctions) {
  4329. return (name != null ? Buffer$4.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer$4.byteLength(normalizedFunctionString$2(value), 'utf8') + 1;
  4330. }
  4331. }
  4332. }
  4333. return 0;
  4334. }
  4335. var calculate_size = calculateObjectSize;
  4336. var Buffer$5 = buffer.Buffer;
  4337. /**
  4338. * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
  4339. *
  4340. * @param {Buffer|Uint8Array} potentialBuffer The potential buffer
  4341. * @returns {Buffer} the input if potentialBuffer is a buffer, or a buffer that
  4342. * wraps a passed in Uint8Array
  4343. * @throws {TypeError} If anything other than a Buffer or Uint8Array is passed in
  4344. */
  4345. var ensure_buffer = function ensureBuffer(potentialBuffer) {
  4346. if (potentialBuffer instanceof Buffer$5) {
  4347. return potentialBuffer;
  4348. }
  4349. if (potentialBuffer instanceof Uint8Array) {
  4350. return Buffer$5.from(potentialBuffer.buffer);
  4351. }
  4352. throw new TypeError('Must use either Buffer or Uint8Array');
  4353. };
  4354. var Buffer$6 = buffer.Buffer; // Parts of the parser
  4355. /**
  4356. * @ignore
  4357. */
  4358. // Default Max Size
  4359. var MAXSIZE = 1024 * 1024 * 17; // Current Internal Temporary Serialization Buffer
  4360. var buffer$1 = Buffer$6.alloc(MAXSIZE);
  4361. /**
  4362. * Sets the size of the internal serialization buffer.
  4363. *
  4364. * @method
  4365. * @param {number} size The desired size for the internal serialization buffer
  4366. */
  4367. function setInternalBufferSize(size) {
  4368. // Resize the internal serialization buffer if needed
  4369. if (buffer$1.length < size) {
  4370. buffer$1 = Buffer$6.alloc(size);
  4371. }
  4372. }
  4373. /**
  4374. * Serialize a Javascript object.
  4375. *
  4376. * @param {Object} object the Javascript object to serialize.
  4377. * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid.
  4378. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.
  4379. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.
  4380. * @return {Buffer} returns the Buffer object containing the serialized object.
  4381. */
  4382. function serialize$1(object, options) {
  4383. options = options || {}; // Unpack the options
  4384. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4385. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4386. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4387. var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; // Resize the internal serialization buffer if needed
  4388. if (buffer$1.length < minInternalBufferSize) {
  4389. buffer$1 = Buffer$6.alloc(minInternalBufferSize);
  4390. } // Attempt to serialize
  4391. var serializationIndex = serializer(buffer$1, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); // Create the final buffer
  4392. var finishedBuffer = Buffer$6.alloc(serializationIndex); // Copy into the finished buffer
  4393. buffer$1.copy(finishedBuffer, 0, 0, finishedBuffer.length); // Return the buffer
  4394. return finishedBuffer;
  4395. }
  4396. /**
  4397. * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.
  4398. *
  4399. * @param {Object} object the Javascript object to serialize.
  4400. * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object.
  4401. * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid.
  4402. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.
  4403. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.
  4404. * @param {Number} [options.index] the index in the buffer where we wish to start serializing into.
  4405. * @return {Number} returns the index pointing to the last written byte in the buffer.
  4406. */
  4407. function serializeWithBufferAndIndex(object, finalBuffer, options) {
  4408. options = options || {}; // Unpack the options
  4409. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4410. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4411. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4412. var startIndex = typeof options.index === 'number' ? options.index : 0; // Attempt to serialize
  4413. var serializationIndex = serializer(buffer$1, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined);
  4414. buffer$1.copy(finalBuffer, startIndex, 0, serializationIndex); // Return the index
  4415. return startIndex + serializationIndex - 1;
  4416. }
  4417. /**
  4418. * Deserialize data as BSON.
  4419. *
  4420. * @param {Buffer} buffer the buffer containing the serialized set of BSON documents.
  4421. * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
  4422. * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
  4423. * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
  4424. * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
  4425. * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance.
  4426. * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
  4427. * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
  4428. * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
  4429. * @param {boolean} [options.allowObjectSmallerThanBufferSize=false] allows the buffer to be larger than the parsed BSON object
  4430. * @return {Object} returns the deserialized Javascript Object.
  4431. */
  4432. function deserialize$2(buffer$$1, options) {
  4433. buffer$$1 = ensure_buffer(buffer$$1);
  4434. return deserializer(buffer$$1, options);
  4435. }
  4436. /**
  4437. * Calculate the bson size for a passed in Javascript object.
  4438. *
  4439. * @param {Object} object the Javascript object to calculate the BSON byte size for.
  4440. * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**.
  4441. * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**.
  4442. * @return {Number} returns the number of bytes the BSON object will take up.
  4443. */
  4444. function calculateObjectSize$1(object, options) {
  4445. options = options || {};
  4446. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4447. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4448. return calculate_size(object, serializeFunctions, ignoreUndefined);
  4449. }
  4450. /**
  4451. * Deserialize stream data as BSON documents.
  4452. *
  4453. * @param {Buffer} data the buffer containing the serialized set of BSON documents.
  4454. * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start.
  4455. * @param {Number} numberOfDocuments number of documents to deserialize.
  4456. * @param {Array} documents an array where to store the deserialized documents.
  4457. * @param {Number} docStartIndex the index in the documents array from where to start inserting documents.
  4458. * @param {Object} [options] additional options used for the deserialization.
  4459. * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized.
  4460. * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse.
  4461. * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function.
  4462. * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits
  4463. * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance.
  4464. * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types.
  4465. * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer.
  4466. * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances.
  4467. * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents.
  4468. */
  4469. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  4470. options = Object.assign({
  4471. allowObjectSmallerThanBufferSize: true
  4472. }, options);
  4473. data = ensure_buffer(data);
  4474. var index = startIndex; // Loop over all documents
  4475. for (var i = 0; i < numberOfDocuments; i++) {
  4476. // Find size of the document
  4477. var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; // Update options with index
  4478. options.index = index; // Parse the document at this point
  4479. documents[docStartIndex + i] = deserializer(data, options); // Adjust index by the document size
  4480. index = index + size;
  4481. } // Return object containing end index of parsing and list of documents
  4482. return index;
  4483. }
  4484. var bson = {
  4485. // constants
  4486. // NOTE: this is done this way because rollup can't resolve an `Object.assign`ed export
  4487. BSON_INT32_MAX: constants.BSON_INT32_MAX,
  4488. BSON_INT32_MIN: constants.BSON_INT32_MIN,
  4489. BSON_INT64_MAX: constants.BSON_INT64_MAX,
  4490. BSON_INT64_MIN: constants.BSON_INT64_MIN,
  4491. JS_INT_MAX: constants.JS_INT_MAX,
  4492. JS_INT_MIN: constants.JS_INT_MIN,
  4493. BSON_DATA_NUMBER: constants.BSON_DATA_NUMBER,
  4494. BSON_DATA_STRING: constants.BSON_DATA_STRING,
  4495. BSON_DATA_OBJECT: constants.BSON_DATA_OBJECT,
  4496. BSON_DATA_ARRAY: constants.BSON_DATA_ARRAY,
  4497. BSON_DATA_BINARY: constants.BSON_DATA_BINARY,
  4498. BSON_DATA_UNDEFINED: constants.BSON_DATA_UNDEFINED,
  4499. BSON_DATA_OID: constants.BSON_DATA_OID,
  4500. BSON_DATA_BOOLEAN: constants.BSON_DATA_BOOLEAN,
  4501. BSON_DATA_DATE: constants.BSON_DATA_DATE,
  4502. BSON_DATA_NULL: constants.BSON_DATA_NULL,
  4503. BSON_DATA_REGEXP: constants.BSON_DATA_REGEXP,
  4504. BSON_DATA_DBPOINTER: constants.BSON_DATA_DBPOINTER,
  4505. BSON_DATA_CODE: constants.BSON_DATA_CODE,
  4506. BSON_DATA_SYMBOL: constants.BSON_DATA_SYMBOL,
  4507. BSON_DATA_CODE_W_SCOPE: constants.BSON_DATA_CODE_W_SCOPE,
  4508. BSON_DATA_INT: constants.BSON_DATA_INT,
  4509. BSON_DATA_TIMESTAMP: constants.BSON_DATA_TIMESTAMP,
  4510. BSON_DATA_LONG: constants.BSON_DATA_LONG,
  4511. BSON_DATA_DECIMAL128: constants.BSON_DATA_DECIMAL128,
  4512. BSON_DATA_MIN_KEY: constants.BSON_DATA_MIN_KEY,
  4513. BSON_DATA_MAX_KEY: constants.BSON_DATA_MAX_KEY,
  4514. BSON_BINARY_SUBTYPE_DEFAULT: constants.BSON_BINARY_SUBTYPE_DEFAULT,
  4515. BSON_BINARY_SUBTYPE_FUNCTION: constants.BSON_BINARY_SUBTYPE_FUNCTION,
  4516. BSON_BINARY_SUBTYPE_BYTE_ARRAY: constants.BSON_BINARY_SUBTYPE_BYTE_ARRAY,
  4517. BSON_BINARY_SUBTYPE_UUID: constants.BSON_BINARY_SUBTYPE_UUID,
  4518. BSON_BINARY_SUBTYPE_MD5: constants.BSON_BINARY_SUBTYPE_MD5,
  4519. BSON_BINARY_SUBTYPE_USER_DEFINED: constants.BSON_BINARY_SUBTYPE_USER_DEFINED,
  4520. // wrapped types
  4521. Code: code,
  4522. Map: map,
  4523. BSONSymbol: symbol,
  4524. DBRef: db_ref,
  4525. Binary: binary,
  4526. ObjectId: objectid,
  4527. Long: long_1,
  4528. Timestamp: timestamp,
  4529. Double: double_1,
  4530. Int32: int_32,
  4531. MinKey: min_key,
  4532. MaxKey: max_key,
  4533. BSONRegExp: regexp,
  4534. Decimal128: decimal128,
  4535. // methods
  4536. serialize: serialize$1,
  4537. serializeWithBufferAndIndex: serializeWithBufferAndIndex,
  4538. deserialize: deserialize$2,
  4539. calculateObjectSize: calculateObjectSize$1,
  4540. deserializeStream: deserializeStream,
  4541. setInternalBufferSize: setInternalBufferSize,
  4542. // legacy support
  4543. ObjectID: objectid,
  4544. // Extended JSON
  4545. EJSON: extended_json
  4546. };
  4547. var bson_1 = bson.BSON_INT32_MAX;
  4548. var bson_2 = bson.BSON_INT32_MIN;
  4549. var bson_3 = bson.BSON_INT64_MAX;
  4550. var bson_4 = bson.BSON_INT64_MIN;
  4551. var bson_5 = bson.JS_INT_MAX;
  4552. var bson_6 = bson.JS_INT_MIN;
  4553. var bson_7 = bson.BSON_DATA_NUMBER;
  4554. var bson_8 = bson.BSON_DATA_STRING;
  4555. var bson_9 = bson.BSON_DATA_OBJECT;
  4556. var bson_10 = bson.BSON_DATA_ARRAY;
  4557. var bson_11 = bson.BSON_DATA_BINARY;
  4558. var bson_12 = bson.BSON_DATA_UNDEFINED;
  4559. var bson_13 = bson.BSON_DATA_OID;
  4560. var bson_14 = bson.BSON_DATA_BOOLEAN;
  4561. var bson_15 = bson.BSON_DATA_DATE;
  4562. var bson_16 = bson.BSON_DATA_NULL;
  4563. var bson_17 = bson.BSON_DATA_REGEXP;
  4564. var bson_18 = bson.BSON_DATA_DBPOINTER;
  4565. var bson_19 = bson.BSON_DATA_CODE;
  4566. var bson_20 = bson.BSON_DATA_SYMBOL;
  4567. var bson_21 = bson.BSON_DATA_CODE_W_SCOPE;
  4568. var bson_22 = bson.BSON_DATA_INT;
  4569. var bson_23 = bson.BSON_DATA_TIMESTAMP;
  4570. var bson_24 = bson.BSON_DATA_LONG;
  4571. var bson_25 = bson.BSON_DATA_DECIMAL128;
  4572. var bson_26 = bson.BSON_DATA_MIN_KEY;
  4573. var bson_27 = bson.BSON_DATA_MAX_KEY;
  4574. var bson_28 = bson.BSON_BINARY_SUBTYPE_DEFAULT;
  4575. var bson_29 = bson.BSON_BINARY_SUBTYPE_FUNCTION;
  4576. var bson_30 = bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY;
  4577. var bson_31 = bson.BSON_BINARY_SUBTYPE_UUID;
  4578. var bson_32 = bson.BSON_BINARY_SUBTYPE_MD5;
  4579. var bson_33 = bson.BSON_BINARY_SUBTYPE_USER_DEFINED;
  4580. var bson_34 = bson.Code;
  4581. var bson_35 = bson.BSONSymbol;
  4582. var bson_36 = bson.DBRef;
  4583. var bson_37 = bson.Binary;
  4584. var bson_38 = bson.ObjectId;
  4585. var bson_39 = bson.Long;
  4586. var bson_40 = bson.Timestamp;
  4587. var bson_41 = bson.Double;
  4588. var bson_42 = bson.Int32;
  4589. var bson_43 = bson.MinKey;
  4590. var bson_44 = bson.MaxKey;
  4591. var bson_45 = bson.BSONRegExp;
  4592. var bson_46 = bson.Decimal128;
  4593. var bson_47 = bson.serialize;
  4594. var bson_48 = bson.serializeWithBufferAndIndex;
  4595. var bson_49 = bson.deserialize;
  4596. var bson_50 = bson.calculateObjectSize;
  4597. var bson_51 = bson.deserializeStream;
  4598. var bson_52 = bson.setInternalBufferSize;
  4599. var bson_53 = bson.ObjectID;
  4600. var bson_54 = bson.EJSON;
  4601. exports.default = bson;
  4602. exports.BSON_INT32_MAX = bson_1;
  4603. exports.BSON_INT32_MIN = bson_2;
  4604. exports.BSON_INT64_MAX = bson_3;
  4605. exports.BSON_INT64_MIN = bson_4;
  4606. exports.JS_INT_MAX = bson_5;
  4607. exports.JS_INT_MIN = bson_6;
  4608. exports.BSON_DATA_NUMBER = bson_7;
  4609. exports.BSON_DATA_STRING = bson_8;
  4610. exports.BSON_DATA_OBJECT = bson_9;
  4611. exports.BSON_DATA_ARRAY = bson_10;
  4612. exports.BSON_DATA_BINARY = bson_11;
  4613. exports.BSON_DATA_UNDEFINED = bson_12;
  4614. exports.BSON_DATA_OID = bson_13;
  4615. exports.BSON_DATA_BOOLEAN = bson_14;
  4616. exports.BSON_DATA_DATE = bson_15;
  4617. exports.BSON_DATA_NULL = bson_16;
  4618. exports.BSON_DATA_REGEXP = bson_17;
  4619. exports.BSON_DATA_DBPOINTER = bson_18;
  4620. exports.BSON_DATA_CODE = bson_19;
  4621. exports.BSON_DATA_SYMBOL = bson_20;
  4622. exports.BSON_DATA_CODE_W_SCOPE = bson_21;
  4623. exports.BSON_DATA_INT = bson_22;
  4624. exports.BSON_DATA_TIMESTAMP = bson_23;
  4625. exports.BSON_DATA_LONG = bson_24;
  4626. exports.BSON_DATA_DECIMAL128 = bson_25;
  4627. exports.BSON_DATA_MIN_KEY = bson_26;
  4628. exports.BSON_DATA_MAX_KEY = bson_27;
  4629. exports.BSON_BINARY_SUBTYPE_DEFAULT = bson_28;
  4630. exports.BSON_BINARY_SUBTYPE_FUNCTION = bson_29;
  4631. exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = bson_30;
  4632. exports.BSON_BINARY_SUBTYPE_UUID = bson_31;
  4633. exports.BSON_BINARY_SUBTYPE_MD5 = bson_32;
  4634. exports.BSON_BINARY_SUBTYPE_USER_DEFINED = bson_33;
  4635. exports.Code = bson_34;
  4636. exports.BSONSymbol = bson_35;
  4637. exports.DBRef = bson_36;
  4638. exports.Binary = bson_37;
  4639. exports.ObjectId = bson_38;
  4640. exports.Long = bson_39;
  4641. exports.Timestamp = bson_40;
  4642. exports.Double = bson_41;
  4643. exports.Int32 = bson_42;
  4644. exports.MinKey = bson_43;
  4645. exports.MaxKey = bson_44;
  4646. exports.BSONRegExp = bson_45;
  4647. exports.Decimal128 = bson_46;
  4648. exports.serialize = bson_47;
  4649. exports.serializeWithBufferAndIndex = bson_48;
  4650. exports.deserialize = bson_49;
  4651. exports.calculateObjectSize = bson_50;
  4652. exports.deserializeStream = bson_51;
  4653. exports.setInternalBufferSize = bson_52;
  4654. exports.ObjectID = bson_53;
  4655. exports.EJSON = bson_54;
  4656. Object.defineProperty(exports, '__esModule', { value: true });
  4657. })));