bson.esm.js 215 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488
  1. import { Buffer } from 'buffer';
  2. /*! *****************************************************************************
  3. Copyright (c) Microsoft Corporation.
  4. Permission to use, copy, modify, and/or distribute this software for any
  5. purpose with or without fee is hereby granted.
  6. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  7. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  8. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  9. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  10. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  11. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  12. PERFORMANCE OF THIS SOFTWARE.
  13. ***************************************************************************** */
  14. /* global Reflect, Promise */
  15. var _extendStatics = function extendStatics(d, b) {
  16. _extendStatics = Object.setPrototypeOf || {
  17. __proto__: []
  18. } instanceof Array && function (d, b) {
  19. d.__proto__ = b;
  20. } || function (d, b) {
  21. for (var p in b) {
  22. if (b.hasOwnProperty(p)) d[p] = b[p];
  23. }
  24. };
  25. return _extendStatics(d, b);
  26. };
  27. function __extends(d, b) {
  28. _extendStatics(d, b);
  29. function __() {
  30. this.constructor = d;
  31. }
  32. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  33. }
  34. var _assign = function __assign() {
  35. _assign = Object.assign || function __assign(t) {
  36. for (var s, i = 1, n = arguments.length; i < n; i++) {
  37. s = arguments[i];
  38. for (var p in s) {
  39. if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  40. }
  41. }
  42. return t;
  43. };
  44. return _assign.apply(this, arguments);
  45. };
  46. /** @public */
  47. var BSONError = /** @class */ (function (_super) {
  48. __extends(BSONError, _super);
  49. function BSONError(message) {
  50. var _this = _super.call(this, message) || this;
  51. Object.setPrototypeOf(_this, BSONError.prototype);
  52. return _this;
  53. }
  54. Object.defineProperty(BSONError.prototype, "name", {
  55. get: function () {
  56. return 'BSONError';
  57. },
  58. enumerable: false,
  59. configurable: true
  60. });
  61. return BSONError;
  62. }(Error));
  63. /** @public */
  64. var BSONTypeError = /** @class */ (function (_super) {
  65. __extends(BSONTypeError, _super);
  66. function BSONTypeError(message) {
  67. var _this = _super.call(this, message) || this;
  68. Object.setPrototypeOf(_this, BSONTypeError.prototype);
  69. return _this;
  70. }
  71. Object.defineProperty(BSONTypeError.prototype, "name", {
  72. get: function () {
  73. return 'BSONTypeError';
  74. },
  75. enumerable: false,
  76. configurable: true
  77. });
  78. return BSONTypeError;
  79. }(TypeError));
  80. function checkForMath(potentialGlobal) {
  81. // eslint-disable-next-line eqeqeq
  82. return potentialGlobal && potentialGlobal.Math == Math && potentialGlobal;
  83. }
  84. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  85. function getGlobal() {
  86. // eslint-disable-next-line no-undef
  87. return (checkForMath(typeof globalThis === 'object' && globalThis) ||
  88. checkForMath(typeof window === 'object' && window) ||
  89. checkForMath(typeof self === 'object' && self) ||
  90. checkForMath(typeof global === 'object' && global) ||
  91. Function('return this')());
  92. }
  93. /**
  94. * Normalizes our expected stringified form of a function across versions of node
  95. * @param fn - The function to stringify
  96. */
  97. function normalizedFunctionString(fn) {
  98. return fn.toString().replace('function(', 'function (');
  99. }
  100. function isReactNative() {
  101. var g = getGlobal();
  102. return typeof g.navigator === 'object' && g.navigator.product === 'ReactNative';
  103. }
  104. var insecureRandomBytes = function insecureRandomBytes(size) {
  105. var insecureWarning = isReactNative()
  106. ? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'
  107. : 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.';
  108. console.warn(insecureWarning);
  109. var result = Buffer.alloc(size);
  110. for (var i = 0; i < size; ++i)
  111. result[i] = Math.floor(Math.random() * 256);
  112. return result;
  113. };
  114. var detectRandomBytes = function () {
  115. if (typeof window !== 'undefined') {
  116. // browser crypto implementation(s)
  117. var target_1 = window.crypto || window.msCrypto; // allow for IE11
  118. if (target_1 && target_1.getRandomValues) {
  119. return function (size) { return target_1.getRandomValues(Buffer.alloc(size)); };
  120. }
  121. }
  122. if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) {
  123. // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global
  124. return function (size) { return global.crypto.getRandomValues(Buffer.alloc(size)); };
  125. }
  126. var requiredRandomBytes;
  127. try {
  128. // eslint-disable-next-line @typescript-eslint/no-var-requires
  129. requiredRandomBytes = require('crypto').randomBytes;
  130. }
  131. catch (e) {
  132. // keep the fallback
  133. }
  134. // NOTE: in transpiled cases the above require might return null/undefined
  135. return requiredRandomBytes || insecureRandomBytes;
  136. };
  137. var randomBytes = detectRandomBytes();
  138. function isAnyArrayBuffer(value) {
  139. return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value));
  140. }
  141. function isUint8Array(value) {
  142. return Object.prototype.toString.call(value) === '[object Uint8Array]';
  143. }
  144. function isBigInt64Array(value) {
  145. return Object.prototype.toString.call(value) === '[object BigInt64Array]';
  146. }
  147. function isBigUInt64Array(value) {
  148. return Object.prototype.toString.call(value) === '[object BigUint64Array]';
  149. }
  150. function isRegExp(d) {
  151. return Object.prototype.toString.call(d) === '[object RegExp]';
  152. }
  153. function isMap(d) {
  154. return Object.prototype.toString.call(d) === '[object Map]';
  155. }
  156. // To ensure that 0.4 of node works correctly
  157. function isDate(d) {
  158. return isObjectLike(d) && Object.prototype.toString.call(d) === '[object Date]';
  159. }
  160. /**
  161. * @internal
  162. * this is to solve the `'someKey' in x` problem where x is unknown.
  163. * https://github.com/typescript-eslint/typescript-eslint/issues/1071#issuecomment-541955753
  164. */
  165. function isObjectLike(candidate) {
  166. return typeof candidate === 'object' && candidate !== null;
  167. }
  168. function deprecate(fn, message) {
  169. var warned = false;
  170. function deprecated() {
  171. var args = [];
  172. for (var _i = 0; _i < arguments.length; _i++) {
  173. args[_i] = arguments[_i];
  174. }
  175. if (!warned) {
  176. console.warn(message);
  177. warned = true;
  178. }
  179. return fn.apply(this, args);
  180. }
  181. return deprecated;
  182. }
  183. /**
  184. * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
  185. *
  186. * @param potentialBuffer - The potential buffer
  187. * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
  188. * wraps a passed in Uint8Array
  189. * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in
  190. */
  191. function ensureBuffer(potentialBuffer) {
  192. if (ArrayBuffer.isView(potentialBuffer)) {
  193. return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
  194. }
  195. if (isAnyArrayBuffer(potentialBuffer)) {
  196. return Buffer.from(potentialBuffer);
  197. }
  198. throw new BSONTypeError('Must use either Buffer or TypedArray');
  199. }
  200. // Validation regex for v4 uuid (validates with or without dashes)
  201. var VALIDATION_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15})$/i;
  202. var uuidValidateString = function (str) {
  203. return typeof str === 'string' && VALIDATION_REGEX.test(str);
  204. };
  205. var uuidHexStringToBuffer = function (hexString) {
  206. if (!uuidValidateString(hexString)) {
  207. throw new BSONTypeError('UUID string representations must be a 32 or 36 character hex string (dashes excluded/included). Format: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" or "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".');
  208. }
  209. var sanitizedHexString = hexString.replace(/-/g, '');
  210. return Buffer.from(sanitizedHexString, 'hex');
  211. };
  212. var bufferToUuidHexString = function (buffer, includeDashes) {
  213. if (includeDashes === void 0) { includeDashes = true; }
  214. return includeDashes
  215. ? buffer.toString('hex', 0, 4) +
  216. '-' +
  217. buffer.toString('hex', 4, 6) +
  218. '-' +
  219. buffer.toString('hex', 6, 8) +
  220. '-' +
  221. buffer.toString('hex', 8, 10) +
  222. '-' +
  223. buffer.toString('hex', 10, 16)
  224. : buffer.toString('hex');
  225. };
  226. var BYTE_LENGTH = 16;
  227. var kId$1 = Symbol('id');
  228. /**
  229. * A class representation of the BSON UUID type.
  230. * @public
  231. */
  232. var UUID = /** @class */ (function () {
  233. /**
  234. * Create an UUID type
  235. *
  236. * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
  237. */
  238. function UUID(input) {
  239. if (typeof input === 'undefined') {
  240. // The most common use case (blank id, new UUID() instance)
  241. this.id = UUID.generate();
  242. }
  243. else if (input instanceof UUID) {
  244. this[kId$1] = Buffer.from(input.id);
  245. this.__id = input.__id;
  246. }
  247. else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) {
  248. this.id = ensureBuffer(input);
  249. }
  250. else if (typeof input === 'string') {
  251. this.id = uuidHexStringToBuffer(input);
  252. }
  253. else {
  254. throw new BSONTypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).');
  255. }
  256. }
  257. Object.defineProperty(UUID.prototype, "id", {
  258. /**
  259. * The UUID bytes
  260. * @readonly
  261. */
  262. get: function () {
  263. return this[kId$1];
  264. },
  265. set: function (value) {
  266. this[kId$1] = value;
  267. if (UUID.cacheHexString) {
  268. this.__id = bufferToUuidHexString(value);
  269. }
  270. },
  271. enumerable: false,
  272. configurable: true
  273. });
  274. /**
  275. * Generate a 16 byte uuid v4 buffer used in UUIDs
  276. */
  277. /**
  278. * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
  279. * @param includeDashes - should the string exclude dash-separators.
  280. * */
  281. UUID.prototype.toHexString = function (includeDashes) {
  282. if (includeDashes === void 0) { includeDashes = true; }
  283. if (UUID.cacheHexString && this.__id) {
  284. return this.__id;
  285. }
  286. var uuidHexString = bufferToUuidHexString(this.id, includeDashes);
  287. if (UUID.cacheHexString) {
  288. this.__id = uuidHexString;
  289. }
  290. return uuidHexString;
  291. };
  292. /**
  293. * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
  294. */
  295. UUID.prototype.toString = function (encoding) {
  296. return encoding ? this.id.toString(encoding) : this.toHexString();
  297. };
  298. /**
  299. * Converts the id into its JSON string representation.
  300. * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  301. */
  302. UUID.prototype.toJSON = function () {
  303. return this.toHexString();
  304. };
  305. /**
  306. * Compares the equality of this UUID with `otherID`.
  307. *
  308. * @param otherId - UUID instance to compare against.
  309. */
  310. UUID.prototype.equals = function (otherId) {
  311. if (!otherId) {
  312. return false;
  313. }
  314. if (otherId instanceof UUID) {
  315. return otherId.id.equals(this.id);
  316. }
  317. try {
  318. return new UUID(otherId).id.equals(this.id);
  319. }
  320. catch (_a) {
  321. return false;
  322. }
  323. };
  324. /**
  325. * Creates a Binary instance from the current UUID.
  326. */
  327. UUID.prototype.toBinary = function () {
  328. return new Binary(this.id, Binary.SUBTYPE_UUID);
  329. };
  330. /**
  331. * Generates a populated buffer containing a v4 uuid
  332. */
  333. UUID.generate = function () {
  334. var bytes = randomBytes(BYTE_LENGTH);
  335. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  336. // Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js
  337. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  338. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  339. return Buffer.from(bytes);
  340. };
  341. /**
  342. * Checks if a value is a valid bson UUID
  343. * @param input - UUID, string or Buffer to validate.
  344. */
  345. UUID.isValid = function (input) {
  346. if (!input) {
  347. return false;
  348. }
  349. if (input instanceof UUID) {
  350. return true;
  351. }
  352. if (typeof input === 'string') {
  353. return uuidValidateString(input);
  354. }
  355. if (isUint8Array(input)) {
  356. // check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3)
  357. if (input.length !== BYTE_LENGTH) {
  358. return false;
  359. }
  360. try {
  361. // get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx
  362. // check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx
  363. return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID;
  364. }
  365. catch (_a) {
  366. return false;
  367. }
  368. }
  369. return false;
  370. };
  371. /**
  372. * Creates an UUID from a hex string representation of an UUID.
  373. * @param hexString - 32 or 36 character hex string (dashes excluded/included).
  374. */
  375. UUID.createFromHexString = function (hexString) {
  376. var buffer = uuidHexStringToBuffer(hexString);
  377. return new UUID(buffer);
  378. };
  379. /**
  380. * Converts to a string representation of this Id.
  381. *
  382. * @returns return the 36 character hex string representation.
  383. * @internal
  384. */
  385. UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  386. return this.inspect();
  387. };
  388. UUID.prototype.inspect = function () {
  389. return "new UUID(\"" + this.toHexString() + "\")";
  390. };
  391. return UUID;
  392. }());
  393. Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' });
  394. /**
  395. * A class representation of the BSON Binary type.
  396. * @public
  397. * @category BSONType
  398. */
  399. var Binary = /** @class */ (function () {
  400. /**
  401. * @param buffer - a buffer object containing the binary data.
  402. * @param subType - the option binary type.
  403. */
  404. function Binary(buffer, subType) {
  405. if (!(this instanceof Binary))
  406. return new Binary(buffer, subType);
  407. if (!(buffer == null) &&
  408. !(typeof buffer === 'string') &&
  409. !ArrayBuffer.isView(buffer) &&
  410. !(buffer instanceof ArrayBuffer) &&
  411. !Array.isArray(buffer)) {
  412. throw new BSONTypeError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
  413. }
  414. this.sub_type = subType !== null && subType !== void 0 ? subType : Binary.BSON_BINARY_SUBTYPE_DEFAULT;
  415. if (buffer == null) {
  416. // create an empty binary buffer
  417. this.buffer = Buffer.alloc(Binary.BUFFER_SIZE);
  418. this.position = 0;
  419. }
  420. else {
  421. if (typeof buffer === 'string') {
  422. // string
  423. this.buffer = Buffer.from(buffer, 'binary');
  424. }
  425. else if (Array.isArray(buffer)) {
  426. // number[]
  427. this.buffer = Buffer.from(buffer);
  428. }
  429. else {
  430. // Buffer | TypedArray | ArrayBuffer
  431. this.buffer = ensureBuffer(buffer);
  432. }
  433. this.position = this.buffer.byteLength;
  434. }
  435. }
  436. /**
  437. * Updates this binary with byte_value.
  438. *
  439. * @param byteValue - a single byte we wish to write.
  440. */
  441. Binary.prototype.put = function (byteValue) {
  442. // If it's a string and a has more than one character throw an error
  443. if (typeof byteValue === 'string' && byteValue.length !== 1) {
  444. throw new BSONTypeError('only accepts single character String');
  445. }
  446. else if (typeof byteValue !== 'number' && byteValue.length !== 1)
  447. throw new BSONTypeError('only accepts single character Uint8Array or Array');
  448. // Decode the byte value once
  449. var decodedByte;
  450. if (typeof byteValue === 'string') {
  451. decodedByte = byteValue.charCodeAt(0);
  452. }
  453. else if (typeof byteValue === 'number') {
  454. decodedByte = byteValue;
  455. }
  456. else {
  457. decodedByte = byteValue[0];
  458. }
  459. if (decodedByte < 0 || decodedByte > 255) {
  460. throw new BSONTypeError('only accepts number in a valid unsigned byte range 0-255');
  461. }
  462. if (this.buffer.length > this.position) {
  463. this.buffer[this.position++] = decodedByte;
  464. }
  465. else {
  466. var buffer = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length);
  467. // Combine the two buffers together
  468. this.buffer.copy(buffer, 0, 0, this.buffer.length);
  469. this.buffer = buffer;
  470. this.buffer[this.position++] = decodedByte;
  471. }
  472. };
  473. /**
  474. * Writes a buffer or string to the binary.
  475. *
  476. * @param sequence - a string or buffer to be written to the Binary BSON object.
  477. * @param offset - specify the binary of where to write the content.
  478. */
  479. Binary.prototype.write = function (sequence, offset) {
  480. offset = typeof offset === 'number' ? offset : this.position;
  481. // If the buffer is to small let's extend the buffer
  482. if (this.buffer.length < offset + sequence.length) {
  483. var buffer = Buffer.alloc(this.buffer.length + sequence.length);
  484. this.buffer.copy(buffer, 0, 0, this.buffer.length);
  485. // Assign the new buffer
  486. this.buffer = buffer;
  487. }
  488. if (ArrayBuffer.isView(sequence)) {
  489. this.buffer.set(ensureBuffer(sequence), offset);
  490. this.position =
  491. offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
  492. }
  493. else if (typeof sequence === 'string') {
  494. this.buffer.write(sequence, offset, sequence.length, 'binary');
  495. this.position =
  496. offset + sequence.length > this.position ? offset + sequence.length : this.position;
  497. }
  498. };
  499. /**
  500. * Reads **length** bytes starting at **position**.
  501. *
  502. * @param position - read from the given position in the Binary.
  503. * @param length - the number of bytes to read.
  504. */
  505. Binary.prototype.read = function (position, length) {
  506. length = length && length > 0 ? length : this.position;
  507. // Let's return the data based on the type we have
  508. return this.buffer.slice(position, position + length);
  509. };
  510. /**
  511. * Returns the value of this binary as a string.
  512. * @param asRaw - Will skip converting to a string
  513. * @remarks
  514. * This is handy when calling this function conditionally for some key value pairs and not others
  515. */
  516. Binary.prototype.value = function (asRaw) {
  517. asRaw = !!asRaw;
  518. // Optimize to serialize for the situation where the data == size of buffer
  519. if (asRaw && this.buffer.length === this.position) {
  520. return this.buffer;
  521. }
  522. // If it's a node.js buffer object
  523. if (asRaw) {
  524. return this.buffer.slice(0, this.position);
  525. }
  526. return this.buffer.toString('binary', 0, this.position);
  527. };
  528. /** the length of the binary sequence */
  529. Binary.prototype.length = function () {
  530. return this.position;
  531. };
  532. Binary.prototype.toJSON = function () {
  533. return this.buffer.toString('base64');
  534. };
  535. Binary.prototype.toString = function (format) {
  536. return this.buffer.toString(format);
  537. };
  538. /** @internal */
  539. Binary.prototype.toExtendedJSON = function (options) {
  540. options = options || {};
  541. var base64String = this.buffer.toString('base64');
  542. var subType = Number(this.sub_type).toString(16);
  543. if (options.legacy) {
  544. return {
  545. $binary: base64String,
  546. $type: subType.length === 1 ? '0' + subType : subType
  547. };
  548. }
  549. return {
  550. $binary: {
  551. base64: base64String,
  552. subType: subType.length === 1 ? '0' + subType : subType
  553. }
  554. };
  555. };
  556. Binary.prototype.toUUID = function () {
  557. if (this.sub_type === Binary.SUBTYPE_UUID) {
  558. return new UUID(this.buffer.slice(0, this.position));
  559. }
  560. throw new BSONError("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
  561. };
  562. /** @internal */
  563. Binary.fromExtendedJSON = function (doc, options) {
  564. options = options || {};
  565. var data;
  566. var type;
  567. if ('$binary' in doc) {
  568. if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
  569. type = doc.$type ? parseInt(doc.$type, 16) : 0;
  570. data = Buffer.from(doc.$binary, 'base64');
  571. }
  572. else {
  573. if (typeof doc.$binary !== 'string') {
  574. type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  575. data = Buffer.from(doc.$binary.base64, 'base64');
  576. }
  577. }
  578. }
  579. else if ('$uuid' in doc) {
  580. type = 4;
  581. data = uuidHexStringToBuffer(doc.$uuid);
  582. }
  583. if (!data) {
  584. throw new BSONTypeError("Unexpected Binary Extended JSON format " + JSON.stringify(doc));
  585. }
  586. return new Binary(data, type);
  587. };
  588. /** @internal */
  589. Binary.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  590. return this.inspect();
  591. };
  592. Binary.prototype.inspect = function () {
  593. var asBuffer = this.value(true);
  594. return "new Binary(Buffer.from(\"" + asBuffer.toString('hex') + "\", \"hex\"), " + this.sub_type + ")";
  595. };
  596. /**
  597. * Binary default subtype
  598. * @internal
  599. */
  600. Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
  601. /** Initial buffer default size */
  602. Binary.BUFFER_SIZE = 256;
  603. /** Default BSON type */
  604. Binary.SUBTYPE_DEFAULT = 0;
  605. /** Function BSON type */
  606. Binary.SUBTYPE_FUNCTION = 1;
  607. /** Byte Array BSON type */
  608. Binary.SUBTYPE_BYTE_ARRAY = 2;
  609. /** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
  610. Binary.SUBTYPE_UUID_OLD = 3;
  611. /** UUID BSON type */
  612. Binary.SUBTYPE_UUID = 4;
  613. /** MD5 BSON type */
  614. Binary.SUBTYPE_MD5 = 5;
  615. /** Encrypted BSON type */
  616. Binary.SUBTYPE_ENCRYPTED = 6;
  617. /** Column BSON type */
  618. Binary.SUBTYPE_COLUMN = 7;
  619. /** User BSON type */
  620. Binary.SUBTYPE_USER_DEFINED = 128;
  621. return Binary;
  622. }());
  623. Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' });
  624. /**
  625. * A class representation of the BSON Code type.
  626. * @public
  627. * @category BSONType
  628. */
  629. var Code = /** @class */ (function () {
  630. /**
  631. * @param code - a string or function.
  632. * @param scope - an optional scope for the function.
  633. */
  634. function Code(code, scope) {
  635. if (!(this instanceof Code))
  636. return new Code(code, scope);
  637. this.code = code;
  638. this.scope = scope;
  639. }
  640. Code.prototype.toJSON = function () {
  641. return { code: this.code, scope: this.scope };
  642. };
  643. /** @internal */
  644. Code.prototype.toExtendedJSON = function () {
  645. if (this.scope) {
  646. return { $code: this.code, $scope: this.scope };
  647. }
  648. return { $code: this.code };
  649. };
  650. /** @internal */
  651. Code.fromExtendedJSON = function (doc) {
  652. return new Code(doc.$code, doc.$scope);
  653. };
  654. /** @internal */
  655. Code.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  656. return this.inspect();
  657. };
  658. Code.prototype.inspect = function () {
  659. var codeJson = this.toJSON();
  660. return "new Code(\"" + codeJson.code + "\"" + (codeJson.scope ? ", " + JSON.stringify(codeJson.scope) : '') + ")";
  661. };
  662. return Code;
  663. }());
  664. Object.defineProperty(Code.prototype, '_bsontype', { value: 'Code' });
  665. /** @internal */
  666. function isDBRefLike(value) {
  667. return (isObjectLike(value) &&
  668. value.$id != null &&
  669. typeof value.$ref === 'string' &&
  670. (value.$db == null || typeof value.$db === 'string'));
  671. }
  672. /**
  673. * A class representation of the BSON DBRef type.
  674. * @public
  675. * @category BSONType
  676. */
  677. var DBRef = /** @class */ (function () {
  678. /**
  679. * @param collection - the collection name.
  680. * @param oid - the reference ObjectId.
  681. * @param db - optional db name, if omitted the reference is local to the current db.
  682. */
  683. function DBRef(collection, oid, db, fields) {
  684. if (!(this instanceof DBRef))
  685. return new DBRef(collection, oid, db, fields);
  686. // check if namespace has been provided
  687. var parts = collection.split('.');
  688. if (parts.length === 2) {
  689. db = parts.shift();
  690. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  691. collection = parts.shift();
  692. }
  693. this.collection = collection;
  694. this.oid = oid;
  695. this.db = db;
  696. this.fields = fields || {};
  697. }
  698. Object.defineProperty(DBRef.prototype, "namespace", {
  699. // Property provided for compatibility with the 1.x parser
  700. // the 1.x parser used a "namespace" property, while 4.x uses "collection"
  701. /** @internal */
  702. get: function () {
  703. return this.collection;
  704. },
  705. set: function (value) {
  706. this.collection = value;
  707. },
  708. enumerable: false,
  709. configurable: true
  710. });
  711. DBRef.prototype.toJSON = function () {
  712. var o = Object.assign({
  713. $ref: this.collection,
  714. $id: this.oid
  715. }, this.fields);
  716. if (this.db != null)
  717. o.$db = this.db;
  718. return o;
  719. };
  720. /** @internal */
  721. DBRef.prototype.toExtendedJSON = function (options) {
  722. options = options || {};
  723. var o = {
  724. $ref: this.collection,
  725. $id: this.oid
  726. };
  727. if (options.legacy) {
  728. return o;
  729. }
  730. if (this.db)
  731. o.$db = this.db;
  732. o = Object.assign(o, this.fields);
  733. return o;
  734. };
  735. /** @internal */
  736. DBRef.fromExtendedJSON = function (doc) {
  737. var copy = Object.assign({}, doc);
  738. delete copy.$ref;
  739. delete copy.$id;
  740. delete copy.$db;
  741. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  742. };
  743. /** @internal */
  744. DBRef.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  745. return this.inspect();
  746. };
  747. DBRef.prototype.inspect = function () {
  748. // NOTE: if OID is an ObjectId class it will just print the oid string.
  749. var oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
  750. return "new DBRef(\"" + this.namespace + "\", new ObjectId(\"" + oid + "\")" + (this.db ? ", \"" + this.db + "\"" : '') + ")";
  751. };
  752. return DBRef;
  753. }());
  754. Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' });
  755. /**
  756. * wasm optimizations, to do native i64 multiplication and divide
  757. */
  758. var wasm = undefined;
  759. try {
  760. wasm = new WebAssembly.Instance(new WebAssembly.Module(
  761. // prettier-ignore
  762. new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
  763. }
  764. catch (_a) {
  765. // no wasm support
  766. }
  767. var TWO_PWR_16_DBL = 1 << 16;
  768. var TWO_PWR_24_DBL = 1 << 24;
  769. var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  770. var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  771. var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  772. /** A cache of the Long representations of small integer values. */
  773. var INT_CACHE = {};
  774. /** A cache of the Long representations of small unsigned integer values. */
  775. var UINT_CACHE = {};
  776. /**
  777. * A class representing a 64-bit integer
  778. * @public
  779. * @category BSONType
  780. * @remarks
  781. * The internal representation of a long is the two given signed, 32-bit values.
  782. * We use 32-bit pieces because these are the size of integers on which
  783. * Javascript performs bit-operations. For operations like addition and
  784. * multiplication, we split each number into 16 bit pieces, which can easily be
  785. * multiplied within Javascript's floating-point representation without overflow
  786. * or change in sign.
  787. * In the algorithms below, we frequently reduce the negative case to the
  788. * positive case by negating the input(s) and then post-processing the result.
  789. * Note that we must ALWAYS check specially whether those values are MIN_VALUE
  790. * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
  791. * a positive number, it overflows back into a negative). Not handling this
  792. * case would often result in infinite recursion.
  793. * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
  794. */
  795. var Long = /** @class */ (function () {
  796. /**
  797. * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
  798. * See the from* functions below for more convenient ways of constructing Longs.
  799. *
  800. * Acceptable signatures are:
  801. * - Long(low, high, unsigned?)
  802. * - Long(bigint, unsigned?)
  803. * - Long(string, unsigned?)
  804. *
  805. * @param low - The low (signed) 32 bits of the long
  806. * @param high - The high (signed) 32 bits of the long
  807. * @param unsigned - Whether unsigned or not, defaults to signed
  808. */
  809. function Long(low, high, unsigned) {
  810. if (low === void 0) { low = 0; }
  811. if (!(this instanceof Long))
  812. return new Long(low, high, unsigned);
  813. if (typeof low === 'bigint') {
  814. Object.assign(this, Long.fromBigInt(low, !!high));
  815. }
  816. else if (typeof low === 'string') {
  817. Object.assign(this, Long.fromString(low, !!high));
  818. }
  819. else {
  820. this.low = low | 0;
  821. this.high = high | 0;
  822. this.unsigned = !!unsigned;
  823. }
  824. Object.defineProperty(this, '__isLong__', {
  825. value: true,
  826. configurable: false,
  827. writable: false,
  828. enumerable: false
  829. });
  830. }
  831. /**
  832. * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.
  833. * Each is assumed to use 32 bits.
  834. * @param lowBits - The low 32 bits
  835. * @param highBits - The high 32 bits
  836. * @param unsigned - Whether unsigned or not, defaults to signed
  837. * @returns The corresponding Long value
  838. */
  839. Long.fromBits = function (lowBits, highBits, unsigned) {
  840. return new Long(lowBits, highBits, unsigned);
  841. };
  842. /**
  843. * Returns a Long representing the given 32 bit integer value.
  844. * @param value - The 32 bit integer in question
  845. * @param unsigned - Whether unsigned or not, defaults to signed
  846. * @returns The corresponding Long value
  847. */
  848. Long.fromInt = function (value, unsigned) {
  849. var obj, cachedObj, cache;
  850. if (unsigned) {
  851. value >>>= 0;
  852. if ((cache = 0 <= value && value < 256)) {
  853. cachedObj = UINT_CACHE[value];
  854. if (cachedObj)
  855. return cachedObj;
  856. }
  857. obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  858. if (cache)
  859. UINT_CACHE[value] = obj;
  860. return obj;
  861. }
  862. else {
  863. value |= 0;
  864. if ((cache = -128 <= value && value < 128)) {
  865. cachedObj = INT_CACHE[value];
  866. if (cachedObj)
  867. return cachedObj;
  868. }
  869. obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
  870. if (cache)
  871. INT_CACHE[value] = obj;
  872. return obj;
  873. }
  874. };
  875. /**
  876. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  877. * @param value - The number in question
  878. * @param unsigned - Whether unsigned or not, defaults to signed
  879. * @returns The corresponding Long value
  880. */
  881. Long.fromNumber = function (value, unsigned) {
  882. if (isNaN(value))
  883. return unsigned ? Long.UZERO : Long.ZERO;
  884. if (unsigned) {
  885. if (value < 0)
  886. return Long.UZERO;
  887. if (value >= TWO_PWR_64_DBL)
  888. return Long.MAX_UNSIGNED_VALUE;
  889. }
  890. else {
  891. if (value <= -TWO_PWR_63_DBL)
  892. return Long.MIN_VALUE;
  893. if (value + 1 >= TWO_PWR_63_DBL)
  894. return Long.MAX_VALUE;
  895. }
  896. if (value < 0)
  897. return Long.fromNumber(-value, unsigned).neg();
  898. return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  899. };
  900. /**
  901. * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
  902. * @param value - The number in question
  903. * @param unsigned - Whether unsigned or not, defaults to signed
  904. * @returns The corresponding Long value
  905. */
  906. Long.fromBigInt = function (value, unsigned) {
  907. return Long.fromString(value.toString(), unsigned);
  908. };
  909. /**
  910. * Returns a Long representation of the given string, written using the specified radix.
  911. * @param str - The textual representation of the Long
  912. * @param unsigned - Whether unsigned or not, defaults to signed
  913. * @param radix - The radix in which the text is written (2-36), defaults to 10
  914. * @returns The corresponding Long value
  915. */
  916. Long.fromString = function (str, unsigned, radix) {
  917. if (str.length === 0)
  918. throw Error('empty string');
  919. if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity')
  920. return Long.ZERO;
  921. if (typeof unsigned === 'number') {
  922. // For goog.math.long compatibility
  923. (radix = unsigned), (unsigned = false);
  924. }
  925. else {
  926. unsigned = !!unsigned;
  927. }
  928. radix = radix || 10;
  929. if (radix < 2 || 36 < radix)
  930. throw RangeError('radix');
  931. var p;
  932. if ((p = str.indexOf('-')) > 0)
  933. throw Error('interior hyphen');
  934. else if (p === 0) {
  935. return Long.fromString(str.substring(1), unsigned, radix).neg();
  936. }
  937. // Do several (8) digits each time through the loop, so as to
  938. // minimize the calls to the very expensive emulated div.
  939. var radixToPower = Long.fromNumber(Math.pow(radix, 8));
  940. var result = Long.ZERO;
  941. for (var i = 0; i < str.length; i += 8) {
  942. var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
  943. if (size < 8) {
  944. var power = Long.fromNumber(Math.pow(radix, size));
  945. result = result.mul(power).add(Long.fromNumber(value));
  946. }
  947. else {
  948. result = result.mul(radixToPower);
  949. result = result.add(Long.fromNumber(value));
  950. }
  951. }
  952. result.unsigned = unsigned;
  953. return result;
  954. };
  955. /**
  956. * Creates a Long from its byte representation.
  957. * @param bytes - Byte representation
  958. * @param unsigned - Whether unsigned or not, defaults to signed
  959. * @param le - Whether little or big endian, defaults to big endian
  960. * @returns The corresponding Long value
  961. */
  962. Long.fromBytes = function (bytes, unsigned, le) {
  963. return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
  964. };
  965. /**
  966. * Creates a Long from its little endian byte representation.
  967. * @param bytes - Little endian byte representation
  968. * @param unsigned - Whether unsigned or not, defaults to signed
  969. * @returns The corresponding Long value
  970. */
  971. Long.fromBytesLE = function (bytes, unsigned) {
  972. return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned);
  973. };
  974. /**
  975. * Creates a Long from its big endian byte representation.
  976. * @param bytes - Big endian byte representation
  977. * @param unsigned - Whether unsigned or not, defaults to signed
  978. * @returns The corresponding Long value
  979. */
  980. Long.fromBytesBE = function (bytes, unsigned) {
  981. return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned);
  982. };
  983. /**
  984. * Tests if the specified object is a Long.
  985. */
  986. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  987. Long.isLong = function (value) {
  988. return isObjectLike(value) && value['__isLong__'] === true;
  989. };
  990. /**
  991. * Converts the specified value to a Long.
  992. * @param unsigned - Whether unsigned or not, defaults to signed
  993. */
  994. Long.fromValue = function (val, unsigned) {
  995. if (typeof val === 'number')
  996. return Long.fromNumber(val, unsigned);
  997. if (typeof val === 'string')
  998. return Long.fromString(val, unsigned);
  999. // Throws for non-objects, converts non-instanceof Long:
  1000. return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
  1001. };
  1002. /** Returns the sum of this and the specified Long. */
  1003. Long.prototype.add = function (addend) {
  1004. if (!Long.isLong(addend))
  1005. addend = Long.fromValue(addend);
  1006. // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
  1007. var a48 = this.high >>> 16;
  1008. var a32 = this.high & 0xffff;
  1009. var a16 = this.low >>> 16;
  1010. var a00 = this.low & 0xffff;
  1011. var b48 = addend.high >>> 16;
  1012. var b32 = addend.high & 0xffff;
  1013. var b16 = addend.low >>> 16;
  1014. var b00 = addend.low & 0xffff;
  1015. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1016. c00 += a00 + b00;
  1017. c16 += c00 >>> 16;
  1018. c00 &= 0xffff;
  1019. c16 += a16 + b16;
  1020. c32 += c16 >>> 16;
  1021. c16 &= 0xffff;
  1022. c32 += a32 + b32;
  1023. c48 += c32 >>> 16;
  1024. c32 &= 0xffff;
  1025. c48 += a48 + b48;
  1026. c48 &= 0xffff;
  1027. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  1028. };
  1029. /**
  1030. * Returns the sum of this and the specified Long.
  1031. * @returns Sum
  1032. */
  1033. Long.prototype.and = function (other) {
  1034. if (!Long.isLong(other))
  1035. other = Long.fromValue(other);
  1036. return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  1037. };
  1038. /**
  1039. * Compares this Long's value with the specified's.
  1040. * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
  1041. */
  1042. Long.prototype.compare = function (other) {
  1043. if (!Long.isLong(other))
  1044. other = Long.fromValue(other);
  1045. if (this.eq(other))
  1046. return 0;
  1047. var thisNeg = this.isNegative(), otherNeg = other.isNegative();
  1048. if (thisNeg && !otherNeg)
  1049. return -1;
  1050. if (!thisNeg && otherNeg)
  1051. return 1;
  1052. // At this point the sign bits are the same
  1053. if (!this.unsigned)
  1054. return this.sub(other).isNegative() ? -1 : 1;
  1055. // Both are positive if at least one is unsigned
  1056. return other.high >>> 0 > this.high >>> 0 ||
  1057. (other.high === this.high && other.low >>> 0 > this.low >>> 0)
  1058. ? -1
  1059. : 1;
  1060. };
  1061. /** This is an alias of {@link Long.compare} */
  1062. Long.prototype.comp = function (other) {
  1063. return this.compare(other);
  1064. };
  1065. /**
  1066. * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.
  1067. * @returns Quotient
  1068. */
  1069. Long.prototype.divide = function (divisor) {
  1070. if (!Long.isLong(divisor))
  1071. divisor = Long.fromValue(divisor);
  1072. if (divisor.isZero())
  1073. throw Error('division by zero');
  1074. // use wasm support if present
  1075. if (wasm) {
  1076. // guard against signed division overflow: the largest
  1077. // negative number / -1 would be 1 larger than the largest
  1078. // positive number, due to two's complement.
  1079. if (!this.unsigned &&
  1080. this.high === -0x80000000 &&
  1081. divisor.low === -1 &&
  1082. divisor.high === -1) {
  1083. // be consistent with non-wasm code path
  1084. return this;
  1085. }
  1086. var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
  1087. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1088. }
  1089. if (this.isZero())
  1090. return this.unsigned ? Long.UZERO : Long.ZERO;
  1091. var approx, rem, res;
  1092. if (!this.unsigned) {
  1093. // This section is only relevant for signed longs and is derived from the
  1094. // closure library as a whole.
  1095. if (this.eq(Long.MIN_VALUE)) {
  1096. if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
  1097. return Long.MIN_VALUE;
  1098. // recall that -MIN_VALUE == MIN_VALUE
  1099. else if (divisor.eq(Long.MIN_VALUE))
  1100. return Long.ONE;
  1101. else {
  1102. // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
  1103. var halfThis = this.shr(1);
  1104. approx = halfThis.div(divisor).shl(1);
  1105. if (approx.eq(Long.ZERO)) {
  1106. return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
  1107. }
  1108. else {
  1109. rem = this.sub(divisor.mul(approx));
  1110. res = approx.add(rem.div(divisor));
  1111. return res;
  1112. }
  1113. }
  1114. }
  1115. else if (divisor.eq(Long.MIN_VALUE))
  1116. return this.unsigned ? Long.UZERO : Long.ZERO;
  1117. if (this.isNegative()) {
  1118. if (divisor.isNegative())
  1119. return this.neg().div(divisor.neg());
  1120. return this.neg().div(divisor).neg();
  1121. }
  1122. else if (divisor.isNegative())
  1123. return this.div(divisor.neg()).neg();
  1124. res = Long.ZERO;
  1125. }
  1126. else {
  1127. // The algorithm below has not been made for unsigned longs. It's therefore
  1128. // required to take special care of the MSB prior to running it.
  1129. if (!divisor.unsigned)
  1130. divisor = divisor.toUnsigned();
  1131. if (divisor.gt(this))
  1132. return Long.UZERO;
  1133. if (divisor.gt(this.shru(1)))
  1134. // 15 >>> 1 = 7 ; with divisor = 8 ; true
  1135. return Long.UONE;
  1136. res = Long.UZERO;
  1137. }
  1138. // Repeat the following until the remainder is less than other: find a
  1139. // floating-point that approximates remainder / other *from below*, add this
  1140. // into the result, and subtract it from the remainder. It is critical that
  1141. // the approximate value is less than or equal to the real value so that the
  1142. // remainder never becomes negative.
  1143. rem = this;
  1144. while (rem.gte(divisor)) {
  1145. // Approximate the result of division. This may be a little greater or
  1146. // smaller than the actual value.
  1147. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  1148. // We will tweak the approximate result by changing it in the 48-th digit or
  1149. // the smallest non-fractional digit, whichever is larger.
  1150. var log2 = Math.ceil(Math.log(approx) / Math.LN2);
  1151. var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
  1152. // Decrease the approximation until it is smaller than the remainder. Note
  1153. // that if it is too large, the product overflows and is negative.
  1154. var approxRes = Long.fromNumber(approx);
  1155. var approxRem = approxRes.mul(divisor);
  1156. while (approxRem.isNegative() || approxRem.gt(rem)) {
  1157. approx -= delta;
  1158. approxRes = Long.fromNumber(approx, this.unsigned);
  1159. approxRem = approxRes.mul(divisor);
  1160. }
  1161. // We know the answer can't be zero... and actually, zero would cause
  1162. // infinite recursion since we would make no progress.
  1163. if (approxRes.isZero())
  1164. approxRes = Long.ONE;
  1165. res = res.add(approxRes);
  1166. rem = rem.sub(approxRem);
  1167. }
  1168. return res;
  1169. };
  1170. /**This is an alias of {@link Long.divide} */
  1171. Long.prototype.div = function (divisor) {
  1172. return this.divide(divisor);
  1173. };
  1174. /**
  1175. * Tests if this Long's value equals the specified's.
  1176. * @param other - Other value
  1177. */
  1178. Long.prototype.equals = function (other) {
  1179. if (!Long.isLong(other))
  1180. other = Long.fromValue(other);
  1181. if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
  1182. return false;
  1183. return this.high === other.high && this.low === other.low;
  1184. };
  1185. /** This is an alias of {@link Long.equals} */
  1186. Long.prototype.eq = function (other) {
  1187. return this.equals(other);
  1188. };
  1189. /** Gets the high 32 bits as a signed integer. */
  1190. Long.prototype.getHighBits = function () {
  1191. return this.high;
  1192. };
  1193. /** Gets the high 32 bits as an unsigned integer. */
  1194. Long.prototype.getHighBitsUnsigned = function () {
  1195. return this.high >>> 0;
  1196. };
  1197. /** Gets the low 32 bits as a signed integer. */
  1198. Long.prototype.getLowBits = function () {
  1199. return this.low;
  1200. };
  1201. /** Gets the low 32 bits as an unsigned integer. */
  1202. Long.prototype.getLowBitsUnsigned = function () {
  1203. return this.low >>> 0;
  1204. };
  1205. /** Gets the number of bits needed to represent the absolute value of this Long. */
  1206. Long.prototype.getNumBitsAbs = function () {
  1207. if (this.isNegative()) {
  1208. // Unsigned Longs are never negative
  1209. return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  1210. }
  1211. var val = this.high !== 0 ? this.high : this.low;
  1212. var bit;
  1213. for (bit = 31; bit > 0; bit--)
  1214. if ((val & (1 << bit)) !== 0)
  1215. break;
  1216. return this.high !== 0 ? bit + 33 : bit + 1;
  1217. };
  1218. /** Tests if this Long's value is greater than the specified's. */
  1219. Long.prototype.greaterThan = function (other) {
  1220. return this.comp(other) > 0;
  1221. };
  1222. /** This is an alias of {@link Long.greaterThan} */
  1223. Long.prototype.gt = function (other) {
  1224. return this.greaterThan(other);
  1225. };
  1226. /** Tests if this Long's value is greater than or equal the specified's. */
  1227. Long.prototype.greaterThanOrEqual = function (other) {
  1228. return this.comp(other) >= 0;
  1229. };
  1230. /** This is an alias of {@link Long.greaterThanOrEqual} */
  1231. Long.prototype.gte = function (other) {
  1232. return this.greaterThanOrEqual(other);
  1233. };
  1234. /** This is an alias of {@link Long.greaterThanOrEqual} */
  1235. Long.prototype.ge = function (other) {
  1236. return this.greaterThanOrEqual(other);
  1237. };
  1238. /** Tests if this Long's value is even. */
  1239. Long.prototype.isEven = function () {
  1240. return (this.low & 1) === 0;
  1241. };
  1242. /** Tests if this Long's value is negative. */
  1243. Long.prototype.isNegative = function () {
  1244. return !this.unsigned && this.high < 0;
  1245. };
  1246. /** Tests if this Long's value is odd. */
  1247. Long.prototype.isOdd = function () {
  1248. return (this.low & 1) === 1;
  1249. };
  1250. /** Tests if this Long's value is positive. */
  1251. Long.prototype.isPositive = function () {
  1252. return this.unsigned || this.high >= 0;
  1253. };
  1254. /** Tests if this Long's value equals zero. */
  1255. Long.prototype.isZero = function () {
  1256. return this.high === 0 && this.low === 0;
  1257. };
  1258. /** Tests if this Long's value is less than the specified's. */
  1259. Long.prototype.lessThan = function (other) {
  1260. return this.comp(other) < 0;
  1261. };
  1262. /** This is an alias of {@link Long#lessThan}. */
  1263. Long.prototype.lt = function (other) {
  1264. return this.lessThan(other);
  1265. };
  1266. /** Tests if this Long's value is less than or equal the specified's. */
  1267. Long.prototype.lessThanOrEqual = function (other) {
  1268. return this.comp(other) <= 0;
  1269. };
  1270. /** This is an alias of {@link Long.lessThanOrEqual} */
  1271. Long.prototype.lte = function (other) {
  1272. return this.lessThanOrEqual(other);
  1273. };
  1274. /** Returns this Long modulo the specified. */
  1275. Long.prototype.modulo = function (divisor) {
  1276. if (!Long.isLong(divisor))
  1277. divisor = Long.fromValue(divisor);
  1278. // use wasm support if present
  1279. if (wasm) {
  1280. var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
  1281. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1282. }
  1283. return this.sub(this.div(divisor).mul(divisor));
  1284. };
  1285. /** This is an alias of {@link Long.modulo} */
  1286. Long.prototype.mod = function (divisor) {
  1287. return this.modulo(divisor);
  1288. };
  1289. /** This is an alias of {@link Long.modulo} */
  1290. Long.prototype.rem = function (divisor) {
  1291. return this.modulo(divisor);
  1292. };
  1293. /**
  1294. * Returns the product of this and the specified Long.
  1295. * @param multiplier - Multiplier
  1296. * @returns Product
  1297. */
  1298. Long.prototype.multiply = function (multiplier) {
  1299. if (this.isZero())
  1300. return Long.ZERO;
  1301. if (!Long.isLong(multiplier))
  1302. multiplier = Long.fromValue(multiplier);
  1303. // use wasm support if present
  1304. if (wasm) {
  1305. var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
  1306. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1307. }
  1308. if (multiplier.isZero())
  1309. return Long.ZERO;
  1310. if (this.eq(Long.MIN_VALUE))
  1311. return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  1312. if (multiplier.eq(Long.MIN_VALUE))
  1313. return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  1314. if (this.isNegative()) {
  1315. if (multiplier.isNegative())
  1316. return this.neg().mul(multiplier.neg());
  1317. else
  1318. return this.neg().mul(multiplier).neg();
  1319. }
  1320. else if (multiplier.isNegative())
  1321. return this.mul(multiplier.neg()).neg();
  1322. // If both longs are small, use float multiplication
  1323. if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
  1324. return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  1325. // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
  1326. // We can skip products that would overflow.
  1327. var a48 = this.high >>> 16;
  1328. var a32 = this.high & 0xffff;
  1329. var a16 = this.low >>> 16;
  1330. var a00 = this.low & 0xffff;
  1331. var b48 = multiplier.high >>> 16;
  1332. var b32 = multiplier.high & 0xffff;
  1333. var b16 = multiplier.low >>> 16;
  1334. var b00 = multiplier.low & 0xffff;
  1335. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1336. c00 += a00 * b00;
  1337. c16 += c00 >>> 16;
  1338. c00 &= 0xffff;
  1339. c16 += a16 * b00;
  1340. c32 += c16 >>> 16;
  1341. c16 &= 0xffff;
  1342. c16 += a00 * b16;
  1343. c32 += c16 >>> 16;
  1344. c16 &= 0xffff;
  1345. c32 += a32 * b00;
  1346. c48 += c32 >>> 16;
  1347. c32 &= 0xffff;
  1348. c32 += a16 * b16;
  1349. c48 += c32 >>> 16;
  1350. c32 &= 0xffff;
  1351. c32 += a00 * b32;
  1352. c48 += c32 >>> 16;
  1353. c32 &= 0xffff;
  1354. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  1355. c48 &= 0xffff;
  1356. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  1357. };
  1358. /** This is an alias of {@link Long.multiply} */
  1359. Long.prototype.mul = function (multiplier) {
  1360. return this.multiply(multiplier);
  1361. };
  1362. /** Returns the Negation of this Long's value. */
  1363. Long.prototype.negate = function () {
  1364. if (!this.unsigned && this.eq(Long.MIN_VALUE))
  1365. return Long.MIN_VALUE;
  1366. return this.not().add(Long.ONE);
  1367. };
  1368. /** This is an alias of {@link Long.negate} */
  1369. Long.prototype.neg = function () {
  1370. return this.negate();
  1371. };
  1372. /** Returns the bitwise NOT of this Long. */
  1373. Long.prototype.not = function () {
  1374. return Long.fromBits(~this.low, ~this.high, this.unsigned);
  1375. };
  1376. /** Tests if this Long's value differs from the specified's. */
  1377. Long.prototype.notEquals = function (other) {
  1378. return !this.equals(other);
  1379. };
  1380. /** This is an alias of {@link Long.notEquals} */
  1381. Long.prototype.neq = function (other) {
  1382. return this.notEquals(other);
  1383. };
  1384. /** This is an alias of {@link Long.notEquals} */
  1385. Long.prototype.ne = function (other) {
  1386. return this.notEquals(other);
  1387. };
  1388. /**
  1389. * Returns the bitwise OR of this Long and the specified.
  1390. */
  1391. Long.prototype.or = function (other) {
  1392. if (!Long.isLong(other))
  1393. other = Long.fromValue(other);
  1394. return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  1395. };
  1396. /**
  1397. * Returns this Long with bits shifted to the left by the given amount.
  1398. * @param numBits - Number of bits
  1399. * @returns Shifted Long
  1400. */
  1401. Long.prototype.shiftLeft = function (numBits) {
  1402. if (Long.isLong(numBits))
  1403. numBits = numBits.toInt();
  1404. if ((numBits &= 63) === 0)
  1405. return this;
  1406. else if (numBits < 32)
  1407. return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
  1408. else
  1409. return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
  1410. };
  1411. /** This is an alias of {@link Long.shiftLeft} */
  1412. Long.prototype.shl = function (numBits) {
  1413. return this.shiftLeft(numBits);
  1414. };
  1415. /**
  1416. * Returns this Long with bits arithmetically shifted to the right by the given amount.
  1417. * @param numBits - Number of bits
  1418. * @returns Shifted Long
  1419. */
  1420. Long.prototype.shiftRight = function (numBits) {
  1421. if (Long.isLong(numBits))
  1422. numBits = numBits.toInt();
  1423. if ((numBits &= 63) === 0)
  1424. return this;
  1425. else if (numBits < 32)
  1426. return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
  1427. else
  1428. return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  1429. };
  1430. /** This is an alias of {@link Long.shiftRight} */
  1431. Long.prototype.shr = function (numBits) {
  1432. return this.shiftRight(numBits);
  1433. };
  1434. /**
  1435. * Returns this Long with bits logically shifted to the right by the given amount.
  1436. * @param numBits - Number of bits
  1437. * @returns Shifted Long
  1438. */
  1439. Long.prototype.shiftRightUnsigned = function (numBits) {
  1440. if (Long.isLong(numBits))
  1441. numBits = numBits.toInt();
  1442. numBits &= 63;
  1443. if (numBits === 0)
  1444. return this;
  1445. else {
  1446. var high = this.high;
  1447. if (numBits < 32) {
  1448. var low = this.low;
  1449. return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
  1450. }
  1451. else if (numBits === 32)
  1452. return Long.fromBits(high, 0, this.unsigned);
  1453. else
  1454. return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
  1455. }
  1456. };
  1457. /** This is an alias of {@link Long.shiftRightUnsigned} */
  1458. Long.prototype.shr_u = function (numBits) {
  1459. return this.shiftRightUnsigned(numBits);
  1460. };
  1461. /** This is an alias of {@link Long.shiftRightUnsigned} */
  1462. Long.prototype.shru = function (numBits) {
  1463. return this.shiftRightUnsigned(numBits);
  1464. };
  1465. /**
  1466. * Returns the difference of this and the specified Long.
  1467. * @param subtrahend - Subtrahend
  1468. * @returns Difference
  1469. */
  1470. Long.prototype.subtract = function (subtrahend) {
  1471. if (!Long.isLong(subtrahend))
  1472. subtrahend = Long.fromValue(subtrahend);
  1473. return this.add(subtrahend.neg());
  1474. };
  1475. /** This is an alias of {@link Long.subtract} */
  1476. Long.prototype.sub = function (subtrahend) {
  1477. return this.subtract(subtrahend);
  1478. };
  1479. /** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */
  1480. Long.prototype.toInt = function () {
  1481. return this.unsigned ? this.low >>> 0 : this.low;
  1482. };
  1483. /** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */
  1484. Long.prototype.toNumber = function () {
  1485. if (this.unsigned)
  1486. return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
  1487. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  1488. };
  1489. /** Converts the Long to a BigInt (arbitrary precision). */
  1490. Long.prototype.toBigInt = function () {
  1491. return BigInt(this.toString());
  1492. };
  1493. /**
  1494. * Converts this Long to its byte representation.
  1495. * @param le - Whether little or big endian, defaults to big endian
  1496. * @returns Byte representation
  1497. */
  1498. Long.prototype.toBytes = function (le) {
  1499. return le ? this.toBytesLE() : this.toBytesBE();
  1500. };
  1501. /**
  1502. * Converts this Long to its little endian byte representation.
  1503. * @returns Little endian byte representation
  1504. */
  1505. Long.prototype.toBytesLE = function () {
  1506. var hi = this.high, lo = this.low;
  1507. return [
  1508. lo & 0xff,
  1509. (lo >>> 8) & 0xff,
  1510. (lo >>> 16) & 0xff,
  1511. lo >>> 24,
  1512. hi & 0xff,
  1513. (hi >>> 8) & 0xff,
  1514. (hi >>> 16) & 0xff,
  1515. hi >>> 24
  1516. ];
  1517. };
  1518. /**
  1519. * Converts this Long to its big endian byte representation.
  1520. * @returns Big endian byte representation
  1521. */
  1522. Long.prototype.toBytesBE = function () {
  1523. var hi = this.high, lo = this.low;
  1524. return [
  1525. hi >>> 24,
  1526. (hi >>> 16) & 0xff,
  1527. (hi >>> 8) & 0xff,
  1528. hi & 0xff,
  1529. lo >>> 24,
  1530. (lo >>> 16) & 0xff,
  1531. (lo >>> 8) & 0xff,
  1532. lo & 0xff
  1533. ];
  1534. };
  1535. /**
  1536. * Converts this Long to signed.
  1537. */
  1538. Long.prototype.toSigned = function () {
  1539. if (!this.unsigned)
  1540. return this;
  1541. return Long.fromBits(this.low, this.high, false);
  1542. };
  1543. /**
  1544. * Converts the Long to a string written in the specified radix.
  1545. * @param radix - Radix (2-36), defaults to 10
  1546. * @throws RangeError If `radix` is out of range
  1547. */
  1548. Long.prototype.toString = function (radix) {
  1549. radix = radix || 10;
  1550. if (radix < 2 || 36 < radix)
  1551. throw RangeError('radix');
  1552. if (this.isZero())
  1553. return '0';
  1554. if (this.isNegative()) {
  1555. // Unsigned Longs are never negative
  1556. if (this.eq(Long.MIN_VALUE)) {
  1557. // We need to change the Long value before it can be negated, so we remove
  1558. // the bottom-most digit in this base and then recurse to do the rest.
  1559. var radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
  1560. return div.toString(radix) + rem1.toInt().toString(radix);
  1561. }
  1562. else
  1563. return '-' + this.neg().toString(radix);
  1564. }
  1565. // Do several (6) digits each time through the loop, so as to
  1566. // minimize the calls to the very expensive emulated div.
  1567. var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
  1568. // eslint-disable-next-line @typescript-eslint/no-this-alias
  1569. var rem = this;
  1570. var result = '';
  1571. // eslint-disable-next-line no-constant-condition
  1572. while (true) {
  1573. var remDiv = rem.div(radixToPower);
  1574. var intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
  1575. var digits = intval.toString(radix);
  1576. rem = remDiv;
  1577. if (rem.isZero()) {
  1578. return digits + result;
  1579. }
  1580. else {
  1581. while (digits.length < 6)
  1582. digits = '0' + digits;
  1583. result = '' + digits + result;
  1584. }
  1585. }
  1586. };
  1587. /** Converts this Long to unsigned. */
  1588. Long.prototype.toUnsigned = function () {
  1589. if (this.unsigned)
  1590. return this;
  1591. return Long.fromBits(this.low, this.high, true);
  1592. };
  1593. /** Returns the bitwise XOR of this Long and the given one. */
  1594. Long.prototype.xor = function (other) {
  1595. if (!Long.isLong(other))
  1596. other = Long.fromValue(other);
  1597. return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  1598. };
  1599. /** This is an alias of {@link Long.isZero} */
  1600. Long.prototype.eqz = function () {
  1601. return this.isZero();
  1602. };
  1603. /** This is an alias of {@link Long.lessThanOrEqual} */
  1604. Long.prototype.le = function (other) {
  1605. return this.lessThanOrEqual(other);
  1606. };
  1607. /*
  1608. ****************************************************************
  1609. * BSON SPECIFIC ADDITIONS *
  1610. ****************************************************************
  1611. */
  1612. Long.prototype.toExtendedJSON = function (options) {
  1613. if (options && options.relaxed)
  1614. return this.toNumber();
  1615. return { $numberLong: this.toString() };
  1616. };
  1617. Long.fromExtendedJSON = function (doc, options) {
  1618. var result = Long.fromString(doc.$numberLong);
  1619. return options && options.relaxed ? result.toNumber() : result;
  1620. };
  1621. /** @internal */
  1622. Long.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  1623. return this.inspect();
  1624. };
  1625. Long.prototype.inspect = function () {
  1626. return "new Long(\"" + this.toString() + "\"" + (this.unsigned ? ', true' : '') + ")";
  1627. };
  1628. Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
  1629. /** Maximum unsigned value. */
  1630. Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
  1631. /** Signed zero */
  1632. Long.ZERO = Long.fromInt(0);
  1633. /** Unsigned zero. */
  1634. Long.UZERO = Long.fromInt(0, true);
  1635. /** Signed one. */
  1636. Long.ONE = Long.fromInt(1);
  1637. /** Unsigned one. */
  1638. Long.UONE = Long.fromInt(1, true);
  1639. /** Signed negative one. */
  1640. Long.NEG_ONE = Long.fromInt(-1);
  1641. /** Maximum signed value. */
  1642. Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
  1643. /** Minimum signed value. */
  1644. Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
  1645. return Long;
  1646. }());
  1647. Object.defineProperty(Long.prototype, '__isLong__', { value: true });
  1648. Object.defineProperty(Long.prototype, '_bsontype', { value: 'Long' });
  1649. var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  1650. var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  1651. var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  1652. var EXPONENT_MAX = 6111;
  1653. var EXPONENT_MIN = -6176;
  1654. var EXPONENT_BIAS = 6176;
  1655. var MAX_DIGITS = 34;
  1656. // Nan value bits as 32 bit values (due to lack of longs)
  1657. var NAN_BUFFER = [
  1658. 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1659. ].reverse();
  1660. // Infinity value bits 32 bit values (due to lack of longs)
  1661. var INF_NEGATIVE_BUFFER = [
  1662. 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1663. ].reverse();
  1664. var INF_POSITIVE_BUFFER = [
  1665. 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1666. ].reverse();
  1667. var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  1668. // Extract least significant 5 bits
  1669. var COMBINATION_MASK = 0x1f;
  1670. // Extract least significant 14 bits
  1671. var EXPONENT_MASK = 0x3fff;
  1672. // Value of combination field for Inf
  1673. var COMBINATION_INFINITY = 30;
  1674. // Value of combination field for NaN
  1675. var COMBINATION_NAN = 31;
  1676. // Detect if the value is a digit
  1677. function isDigit(value) {
  1678. return !isNaN(parseInt(value, 10));
  1679. }
  1680. // Divide two uint128 values
  1681. function divideu128(value) {
  1682. var DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
  1683. var _rem = Long.fromNumber(0);
  1684. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  1685. return { quotient: value, rem: _rem };
  1686. }
  1687. for (var i = 0; i <= 3; i++) {
  1688. // Adjust remainder to match value of next dividend
  1689. _rem = _rem.shiftLeft(32);
  1690. // Add the divided to _rem
  1691. _rem = _rem.add(new Long(value.parts[i], 0));
  1692. value.parts[i] = _rem.div(DIVISOR).low;
  1693. _rem = _rem.modulo(DIVISOR);
  1694. }
  1695. return { quotient: value, rem: _rem };
  1696. }
  1697. // Multiply two Long values and return the 128 bit value
  1698. function multiply64x2(left, right) {
  1699. if (!left && !right) {
  1700. return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
  1701. }
  1702. var leftHigh = left.shiftRightUnsigned(32);
  1703. var leftLow = new Long(left.getLowBits(), 0);
  1704. var rightHigh = right.shiftRightUnsigned(32);
  1705. var rightLow = new Long(right.getLowBits(), 0);
  1706. var productHigh = leftHigh.multiply(rightHigh);
  1707. var productMid = leftHigh.multiply(rightLow);
  1708. var productMid2 = leftLow.multiply(rightHigh);
  1709. var productLow = leftLow.multiply(rightLow);
  1710. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1711. productMid = new Long(productMid.getLowBits(), 0)
  1712. .add(productMid2)
  1713. .add(productLow.shiftRightUnsigned(32));
  1714. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1715. productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
  1716. // Return the 128 bit result
  1717. return { high: productHigh, low: productLow };
  1718. }
  1719. function lessThan(left, right) {
  1720. // Make values unsigned
  1721. var uhleft = left.high >>> 0;
  1722. var uhright = right.high >>> 0;
  1723. // Compare high bits first
  1724. if (uhleft < uhright) {
  1725. return true;
  1726. }
  1727. else if (uhleft === uhright) {
  1728. var ulleft = left.low >>> 0;
  1729. var ulright = right.low >>> 0;
  1730. if (ulleft < ulright)
  1731. return true;
  1732. }
  1733. return false;
  1734. }
  1735. function invalidErr(string, message) {
  1736. throw new BSONTypeError("\"" + string + "\" is not a valid Decimal128 string - " + message);
  1737. }
  1738. /**
  1739. * A class representation of the BSON Decimal128 type.
  1740. * @public
  1741. * @category BSONType
  1742. */
  1743. var Decimal128 = /** @class */ (function () {
  1744. /**
  1745. * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order,
  1746. * or a string representation as returned by .toString()
  1747. */
  1748. function Decimal128(bytes) {
  1749. if (!(this instanceof Decimal128))
  1750. return new Decimal128(bytes);
  1751. if (typeof bytes === 'string') {
  1752. this.bytes = Decimal128.fromString(bytes).bytes;
  1753. }
  1754. else if (isUint8Array(bytes)) {
  1755. if (bytes.byteLength !== 16) {
  1756. throw new BSONTypeError('Decimal128 must take a Buffer of 16 bytes');
  1757. }
  1758. this.bytes = bytes;
  1759. }
  1760. else {
  1761. throw new BSONTypeError('Decimal128 must take a Buffer or string');
  1762. }
  1763. }
  1764. /**
  1765. * Create a Decimal128 instance from a string representation
  1766. *
  1767. * @param representation - a numeric string representation.
  1768. */
  1769. Decimal128.fromString = function (representation) {
  1770. // Parse state tracking
  1771. var isNegative = false;
  1772. var sawRadix = false;
  1773. var foundNonZero = false;
  1774. // Total number of significant digits (no leading or trailing zero)
  1775. var significantDigits = 0;
  1776. // Total number of significand digits read
  1777. var nDigitsRead = 0;
  1778. // Total number of digits (no leading zeros)
  1779. var nDigits = 0;
  1780. // The number of the digits after radix
  1781. var radixPosition = 0;
  1782. // The index of the first non-zero in *str*
  1783. var firstNonZero = 0;
  1784. // Digits Array
  1785. var digits = [0];
  1786. // The number of digits in digits
  1787. var nDigitsStored = 0;
  1788. // Insertion pointer for digits
  1789. var digitsInsert = 0;
  1790. // The index of the first non-zero digit
  1791. var firstDigit = 0;
  1792. // The index of the last digit
  1793. var lastDigit = 0;
  1794. // Exponent
  1795. var exponent = 0;
  1796. // loop index over array
  1797. var i = 0;
  1798. // The high 17 digits of the significand
  1799. var significandHigh = new Long(0, 0);
  1800. // The low 17 digits of the significand
  1801. var significandLow = new Long(0, 0);
  1802. // The biased exponent
  1803. var biasedExponent = 0;
  1804. // Read index
  1805. var index = 0;
  1806. // Naively prevent against REDOS attacks.
  1807. // TODO: implementing a custom parsing for this, or refactoring the regex would yield
  1808. // further gains.
  1809. if (representation.length >= 7000) {
  1810. throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
  1811. }
  1812. // Results
  1813. var stringMatch = representation.match(PARSE_STRING_REGEXP);
  1814. var infMatch = representation.match(PARSE_INF_REGEXP);
  1815. var nanMatch = representation.match(PARSE_NAN_REGEXP);
  1816. // Validate the string
  1817. if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
  1818. throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
  1819. }
  1820. if (stringMatch) {
  1821. // full_match = stringMatch[0]
  1822. // sign = stringMatch[1]
  1823. var unsignedNumber = stringMatch[2];
  1824. // stringMatch[3] is undefined if a whole number (ex "1", 12")
  1825. // but defined if a number w/ decimal in it (ex "1.0, 12.2")
  1826. var e = stringMatch[4];
  1827. var expSign = stringMatch[5];
  1828. var expNumber = stringMatch[6];
  1829. // they provided e, but didn't give an exponent number. for ex "1e"
  1830. if (e && expNumber === undefined)
  1831. invalidErr(representation, 'missing exponent power');
  1832. // they provided e, but didn't give a number before it. for ex "e1"
  1833. if (e && unsignedNumber === undefined)
  1834. invalidErr(representation, 'missing exponent base');
  1835. if (e === undefined && (expSign || expNumber)) {
  1836. invalidErr(representation, 'missing e before exponent');
  1837. }
  1838. }
  1839. // Get the negative or positive sign
  1840. if (representation[index] === '+' || representation[index] === '-') {
  1841. isNegative = representation[index++] === '-';
  1842. }
  1843. // Check if user passed Infinity or NaN
  1844. if (!isDigit(representation[index]) && representation[index] !== '.') {
  1845. if (representation[index] === 'i' || representation[index] === 'I') {
  1846. return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  1847. }
  1848. else if (representation[index] === 'N') {
  1849. return new Decimal128(Buffer.from(NAN_BUFFER));
  1850. }
  1851. }
  1852. // Read all the digits
  1853. while (isDigit(representation[index]) || representation[index] === '.') {
  1854. if (representation[index] === '.') {
  1855. if (sawRadix)
  1856. invalidErr(representation, 'contains multiple periods');
  1857. sawRadix = true;
  1858. index = index + 1;
  1859. continue;
  1860. }
  1861. if (nDigitsStored < 34) {
  1862. if (representation[index] !== '0' || foundNonZero) {
  1863. if (!foundNonZero) {
  1864. firstNonZero = nDigitsRead;
  1865. }
  1866. foundNonZero = true;
  1867. // Only store 34 digits
  1868. digits[digitsInsert++] = parseInt(representation[index], 10);
  1869. nDigitsStored = nDigitsStored + 1;
  1870. }
  1871. }
  1872. if (foundNonZero)
  1873. nDigits = nDigits + 1;
  1874. if (sawRadix)
  1875. radixPosition = radixPosition + 1;
  1876. nDigitsRead = nDigitsRead + 1;
  1877. index = index + 1;
  1878. }
  1879. if (sawRadix && !nDigitsRead)
  1880. throw new BSONTypeError('' + representation + ' not a valid Decimal128 string');
  1881. // Read exponent if exists
  1882. if (representation[index] === 'e' || representation[index] === 'E') {
  1883. // Read exponent digits
  1884. var match = representation.substr(++index).match(EXPONENT_REGEX);
  1885. // No digits read
  1886. if (!match || !match[2])
  1887. return new Decimal128(Buffer.from(NAN_BUFFER));
  1888. // Get exponent
  1889. exponent = parseInt(match[0], 10);
  1890. // Adjust the index
  1891. index = index + match[0].length;
  1892. }
  1893. // Return not a number
  1894. if (representation[index])
  1895. return new Decimal128(Buffer.from(NAN_BUFFER));
  1896. // Done reading input
  1897. // Find first non-zero digit in digits
  1898. firstDigit = 0;
  1899. if (!nDigitsStored) {
  1900. firstDigit = 0;
  1901. lastDigit = 0;
  1902. digits[0] = 0;
  1903. nDigits = 1;
  1904. nDigitsStored = 1;
  1905. significantDigits = 0;
  1906. }
  1907. else {
  1908. lastDigit = nDigitsStored - 1;
  1909. significantDigits = nDigits;
  1910. if (significantDigits !== 1) {
  1911. while (digits[firstNonZero + significantDigits - 1] === 0) {
  1912. significantDigits = significantDigits - 1;
  1913. }
  1914. }
  1915. }
  1916. // Normalization of exponent
  1917. // Correct exponent based on radix position, and shift significand as needed
  1918. // to represent user input
  1919. // Overflow prevention
  1920. if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
  1921. exponent = EXPONENT_MIN;
  1922. }
  1923. else {
  1924. exponent = exponent - radixPosition;
  1925. }
  1926. // Attempt to normalize the exponent
  1927. while (exponent > EXPONENT_MAX) {
  1928. // Shift exponent to significand and decrease
  1929. lastDigit = lastDigit + 1;
  1930. if (lastDigit - firstDigit > MAX_DIGITS) {
  1931. // Check if we have a zero then just hard clamp, otherwise fail
  1932. var digitsString = digits.join('');
  1933. if (digitsString.match(/^0+$/)) {
  1934. exponent = EXPONENT_MAX;
  1935. break;
  1936. }
  1937. invalidErr(representation, 'overflow');
  1938. }
  1939. exponent = exponent - 1;
  1940. }
  1941. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  1942. // Shift last digit. can only do this if < significant digits than # stored.
  1943. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  1944. exponent = EXPONENT_MIN;
  1945. significantDigits = 0;
  1946. break;
  1947. }
  1948. if (nDigitsStored < nDigits) {
  1949. // adjust to match digits not stored
  1950. nDigits = nDigits - 1;
  1951. }
  1952. else {
  1953. // adjust to round
  1954. lastDigit = lastDigit - 1;
  1955. }
  1956. if (exponent < EXPONENT_MAX) {
  1957. exponent = exponent + 1;
  1958. }
  1959. else {
  1960. // Check if we have a zero then just hard clamp, otherwise fail
  1961. var digitsString = digits.join('');
  1962. if (digitsString.match(/^0+$/)) {
  1963. exponent = EXPONENT_MAX;
  1964. break;
  1965. }
  1966. invalidErr(representation, 'overflow');
  1967. }
  1968. }
  1969. // Round
  1970. // We've normalized the exponent, but might still need to round.
  1971. if (lastDigit - firstDigit + 1 < significantDigits) {
  1972. var endOfString = nDigitsRead;
  1973. // If we have seen a radix point, 'string' is 1 longer than we have
  1974. // documented with ndigits_read, so inc the position of the first nonzero
  1975. // digit and the position that digits are read to.
  1976. if (sawRadix) {
  1977. firstNonZero = firstNonZero + 1;
  1978. endOfString = endOfString + 1;
  1979. }
  1980. // if negative, we need to increment again to account for - sign at start.
  1981. if (isNegative) {
  1982. firstNonZero = firstNonZero + 1;
  1983. endOfString = endOfString + 1;
  1984. }
  1985. var roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  1986. var roundBit = 0;
  1987. if (roundDigit >= 5) {
  1988. roundBit = 1;
  1989. if (roundDigit === 5) {
  1990. roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
  1991. for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  1992. if (parseInt(representation[i], 10)) {
  1993. roundBit = 1;
  1994. break;
  1995. }
  1996. }
  1997. }
  1998. }
  1999. if (roundBit) {
  2000. var dIdx = lastDigit;
  2001. for (; dIdx >= 0; dIdx--) {
  2002. if (++digits[dIdx] > 9) {
  2003. digits[dIdx] = 0;
  2004. // overflowed most significant digit
  2005. if (dIdx === 0) {
  2006. if (exponent < EXPONENT_MAX) {
  2007. exponent = exponent + 1;
  2008. digits[dIdx] = 1;
  2009. }
  2010. else {
  2011. return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  2012. }
  2013. }
  2014. }
  2015. }
  2016. }
  2017. }
  2018. // Encode significand
  2019. // The high 17 digits of the significand
  2020. significandHigh = Long.fromNumber(0);
  2021. // The low 17 digits of the significand
  2022. significandLow = Long.fromNumber(0);
  2023. // read a zero
  2024. if (significantDigits === 0) {
  2025. significandHigh = Long.fromNumber(0);
  2026. significandLow = Long.fromNumber(0);
  2027. }
  2028. else if (lastDigit - firstDigit < 17) {
  2029. var dIdx = firstDigit;
  2030. significandLow = Long.fromNumber(digits[dIdx++]);
  2031. significandHigh = new Long(0, 0);
  2032. for (; dIdx <= lastDigit; dIdx++) {
  2033. significandLow = significandLow.multiply(Long.fromNumber(10));
  2034. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  2035. }
  2036. }
  2037. else {
  2038. var dIdx = firstDigit;
  2039. significandHigh = Long.fromNumber(digits[dIdx++]);
  2040. for (; dIdx <= lastDigit - 17; dIdx++) {
  2041. significandHigh = significandHigh.multiply(Long.fromNumber(10));
  2042. significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
  2043. }
  2044. significandLow = Long.fromNumber(digits[dIdx++]);
  2045. for (; dIdx <= lastDigit; dIdx++) {
  2046. significandLow = significandLow.multiply(Long.fromNumber(10));
  2047. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  2048. }
  2049. }
  2050. var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
  2051. significand.low = significand.low.add(significandLow);
  2052. if (lessThan(significand.low, significandLow)) {
  2053. significand.high = significand.high.add(Long.fromNumber(1));
  2054. }
  2055. // Biased exponent
  2056. biasedExponent = exponent + EXPONENT_BIAS;
  2057. var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
  2058. // Encode combination, exponent, and significand.
  2059. if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
  2060. // Encode '11' into bits 1 to 3
  2061. dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
  2062. dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
  2063. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
  2064. }
  2065. else {
  2066. dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  2067. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
  2068. }
  2069. dec.low = significand.low;
  2070. // Encode sign
  2071. if (isNegative) {
  2072. dec.high = dec.high.or(Long.fromString('9223372036854775808'));
  2073. }
  2074. // Encode into a buffer
  2075. var buffer = Buffer.alloc(16);
  2076. index = 0;
  2077. // Encode the low 64 bits of the decimal
  2078. // Encode low bits
  2079. buffer[index++] = dec.low.low & 0xff;
  2080. buffer[index++] = (dec.low.low >> 8) & 0xff;
  2081. buffer[index++] = (dec.low.low >> 16) & 0xff;
  2082. buffer[index++] = (dec.low.low >> 24) & 0xff;
  2083. // Encode high bits
  2084. buffer[index++] = dec.low.high & 0xff;
  2085. buffer[index++] = (dec.low.high >> 8) & 0xff;
  2086. buffer[index++] = (dec.low.high >> 16) & 0xff;
  2087. buffer[index++] = (dec.low.high >> 24) & 0xff;
  2088. // Encode the high 64 bits of the decimal
  2089. // Encode low bits
  2090. buffer[index++] = dec.high.low & 0xff;
  2091. buffer[index++] = (dec.high.low >> 8) & 0xff;
  2092. buffer[index++] = (dec.high.low >> 16) & 0xff;
  2093. buffer[index++] = (dec.high.low >> 24) & 0xff;
  2094. // Encode high bits
  2095. buffer[index++] = dec.high.high & 0xff;
  2096. buffer[index++] = (dec.high.high >> 8) & 0xff;
  2097. buffer[index++] = (dec.high.high >> 16) & 0xff;
  2098. buffer[index++] = (dec.high.high >> 24) & 0xff;
  2099. // Return the new Decimal128
  2100. return new Decimal128(buffer);
  2101. };
  2102. /** Create a string representation of the raw Decimal128 value */
  2103. Decimal128.prototype.toString = function () {
  2104. // Note: bits in this routine are referred to starting at 0,
  2105. // from the sign bit, towards the coefficient.
  2106. // decoded biased exponent (14 bits)
  2107. var biased_exponent;
  2108. // the number of significand digits
  2109. var significand_digits = 0;
  2110. // the base-10 digits in the significand
  2111. var significand = new Array(36);
  2112. for (var i = 0; i < significand.length; i++)
  2113. significand[i] = 0;
  2114. // read pointer into significand
  2115. var index = 0;
  2116. // true if the number is zero
  2117. var is_zero = false;
  2118. // the most significant significand bits (50-46)
  2119. var significand_msb;
  2120. // temporary storage for significand decoding
  2121. var significand128 = { parts: [0, 0, 0, 0] };
  2122. // indexing variables
  2123. var j, k;
  2124. // Output string
  2125. var string = [];
  2126. // Unpack index
  2127. index = 0;
  2128. // Buffer reference
  2129. var buffer = this.bytes;
  2130. // Unpack the low 64bits into a long
  2131. // bits 96 - 127
  2132. var low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2133. // bits 64 - 95
  2134. var midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2135. // Unpack the high 64bits into a long
  2136. // bits 32 - 63
  2137. var midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2138. // bits 0 - 31
  2139. var high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2140. // Unpack index
  2141. index = 0;
  2142. // Create the state of the decimal
  2143. var dec = {
  2144. low: new Long(low, midl),
  2145. high: new Long(midh, high)
  2146. };
  2147. if (dec.high.lessThan(Long.ZERO)) {
  2148. string.push('-');
  2149. }
  2150. // Decode combination field and exponent
  2151. // bits 1 - 5
  2152. var combination = (high >> 26) & COMBINATION_MASK;
  2153. if (combination >> 3 === 3) {
  2154. // Check for 'special' values
  2155. if (combination === COMBINATION_INFINITY) {
  2156. return string.join('') + 'Infinity';
  2157. }
  2158. else if (combination === COMBINATION_NAN) {
  2159. return 'NaN';
  2160. }
  2161. else {
  2162. biased_exponent = (high >> 15) & EXPONENT_MASK;
  2163. significand_msb = 0x08 + ((high >> 14) & 0x01);
  2164. }
  2165. }
  2166. else {
  2167. significand_msb = (high >> 14) & 0x07;
  2168. biased_exponent = (high >> 17) & EXPONENT_MASK;
  2169. }
  2170. // unbiased exponent
  2171. var exponent = biased_exponent - EXPONENT_BIAS;
  2172. // Create string of significand digits
  2173. // Convert the 114-bit binary number represented by
  2174. // (significand_high, significand_low) to at most 34 decimal
  2175. // digits through modulo and division.
  2176. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  2177. significand128.parts[1] = midh;
  2178. significand128.parts[2] = midl;
  2179. significand128.parts[3] = low;
  2180. if (significand128.parts[0] === 0 &&
  2181. significand128.parts[1] === 0 &&
  2182. significand128.parts[2] === 0 &&
  2183. significand128.parts[3] === 0) {
  2184. is_zero = true;
  2185. }
  2186. else {
  2187. for (k = 3; k >= 0; k--) {
  2188. var least_digits = 0;
  2189. // Perform the divide
  2190. var result = divideu128(significand128);
  2191. significand128 = result.quotient;
  2192. least_digits = result.rem.low;
  2193. // We now have the 9 least significant digits (in base 2).
  2194. // Convert and output to string.
  2195. if (!least_digits)
  2196. continue;
  2197. for (j = 8; j >= 0; j--) {
  2198. // significand[k * 9 + j] = Math.round(least_digits % 10);
  2199. significand[k * 9 + j] = least_digits % 10;
  2200. // least_digits = Math.round(least_digits / 10);
  2201. least_digits = Math.floor(least_digits / 10);
  2202. }
  2203. }
  2204. }
  2205. // Output format options:
  2206. // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
  2207. // Regular - ddd.ddd
  2208. if (is_zero) {
  2209. significand_digits = 1;
  2210. significand[index] = 0;
  2211. }
  2212. else {
  2213. significand_digits = 36;
  2214. while (!significand[index]) {
  2215. significand_digits = significand_digits - 1;
  2216. index = index + 1;
  2217. }
  2218. }
  2219. // the exponent if scientific notation is used
  2220. var scientific_exponent = significand_digits - 1 + exponent;
  2221. // The scientific exponent checks are dictated by the string conversion
  2222. // specification and are somewhat arbitrary cutoffs.
  2223. //
  2224. // We must check exponent > 0, because if this is the case, the number
  2225. // has trailing zeros. However, we *cannot* output these trailing zeros,
  2226. // because doing so would change the precision of the value, and would
  2227. // change stored data if the string converted number is round tripped.
  2228. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  2229. // Scientific format
  2230. // if there are too many significant digits, we should just be treating numbers
  2231. // as + or - 0 and using the non-scientific exponent (this is for the "invalid
  2232. // representation should be treated as 0/-0" spec cases in decimal128-1.json)
  2233. if (significand_digits > 34) {
  2234. string.push("" + 0);
  2235. if (exponent > 0)
  2236. string.push('E+' + exponent);
  2237. else if (exponent < 0)
  2238. string.push('E' + exponent);
  2239. return string.join('');
  2240. }
  2241. string.push("" + significand[index++]);
  2242. significand_digits = significand_digits - 1;
  2243. if (significand_digits) {
  2244. string.push('.');
  2245. }
  2246. for (var i = 0; i < significand_digits; i++) {
  2247. string.push("" + significand[index++]);
  2248. }
  2249. // Exponent
  2250. string.push('E');
  2251. if (scientific_exponent > 0) {
  2252. string.push('+' + scientific_exponent);
  2253. }
  2254. else {
  2255. string.push("" + scientific_exponent);
  2256. }
  2257. }
  2258. else {
  2259. // Regular format with no decimal place
  2260. if (exponent >= 0) {
  2261. for (var i = 0; i < significand_digits; i++) {
  2262. string.push("" + significand[index++]);
  2263. }
  2264. }
  2265. else {
  2266. var radix_position = significand_digits + exponent;
  2267. // non-zero digits before radix
  2268. if (radix_position > 0) {
  2269. for (var i = 0; i < radix_position; i++) {
  2270. string.push("" + significand[index++]);
  2271. }
  2272. }
  2273. else {
  2274. string.push('0');
  2275. }
  2276. string.push('.');
  2277. // add leading zeros after radix
  2278. while (radix_position++ < 0) {
  2279. string.push('0');
  2280. }
  2281. for (var i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  2282. string.push("" + significand[index++]);
  2283. }
  2284. }
  2285. }
  2286. return string.join('');
  2287. };
  2288. Decimal128.prototype.toJSON = function () {
  2289. return { $numberDecimal: this.toString() };
  2290. };
  2291. /** @internal */
  2292. Decimal128.prototype.toExtendedJSON = function () {
  2293. return { $numberDecimal: this.toString() };
  2294. };
  2295. /** @internal */
  2296. Decimal128.fromExtendedJSON = function (doc) {
  2297. return Decimal128.fromString(doc.$numberDecimal);
  2298. };
  2299. /** @internal */
  2300. Decimal128.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2301. return this.inspect();
  2302. };
  2303. Decimal128.prototype.inspect = function () {
  2304. return "new Decimal128(\"" + this.toString() + "\")";
  2305. };
  2306. return Decimal128;
  2307. }());
  2308. Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' });
  2309. /**
  2310. * A class representation of the BSON Double type.
  2311. * @public
  2312. * @category BSONType
  2313. */
  2314. var Double = /** @class */ (function () {
  2315. /**
  2316. * Create a Double type
  2317. *
  2318. * @param value - the number we want to represent as a double.
  2319. */
  2320. function Double(value) {
  2321. if (!(this instanceof Double))
  2322. return new Double(value);
  2323. if (value instanceof Number) {
  2324. value = value.valueOf();
  2325. }
  2326. this.value = +value;
  2327. }
  2328. /**
  2329. * Access the number value.
  2330. *
  2331. * @returns returns the wrapped double number.
  2332. */
  2333. Double.prototype.valueOf = function () {
  2334. return this.value;
  2335. };
  2336. Double.prototype.toJSON = function () {
  2337. return this.value;
  2338. };
  2339. Double.prototype.toString = function (radix) {
  2340. return this.value.toString(radix);
  2341. };
  2342. /** @internal */
  2343. Double.prototype.toExtendedJSON = function (options) {
  2344. if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
  2345. return this.value;
  2346. }
  2347. // NOTE: JavaScript has +0 and -0, apparently to model limit calculations. If a user
  2348. // explicitly provided `-0` then we need to ensure the sign makes it into the output
  2349. if (Object.is(Math.sign(this.value), -0)) {
  2350. return { $numberDouble: "-" + this.value.toFixed(1) };
  2351. }
  2352. var $numberDouble;
  2353. if (Number.isInteger(this.value)) {
  2354. $numberDouble = this.value.toFixed(1);
  2355. if ($numberDouble.length >= 13) {
  2356. $numberDouble = this.value.toExponential(13).toUpperCase();
  2357. }
  2358. }
  2359. else {
  2360. $numberDouble = this.value.toString();
  2361. }
  2362. return { $numberDouble: $numberDouble };
  2363. };
  2364. /** @internal */
  2365. Double.fromExtendedJSON = function (doc, options) {
  2366. var doubleValue = parseFloat(doc.$numberDouble);
  2367. return options && options.relaxed ? doubleValue : new Double(doubleValue);
  2368. };
  2369. /** @internal */
  2370. Double.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2371. return this.inspect();
  2372. };
  2373. Double.prototype.inspect = function () {
  2374. var eJSON = this.toExtendedJSON();
  2375. return "new Double(" + eJSON.$numberDouble + ")";
  2376. };
  2377. return Double;
  2378. }());
  2379. Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' });
  2380. /**
  2381. * A class representation of a BSON Int32 type.
  2382. * @public
  2383. * @category BSONType
  2384. */
  2385. var Int32 = /** @class */ (function () {
  2386. /**
  2387. * Create an Int32 type
  2388. *
  2389. * @param value - the number we want to represent as an int32.
  2390. */
  2391. function Int32(value) {
  2392. if (!(this instanceof Int32))
  2393. return new Int32(value);
  2394. if (value instanceof Number) {
  2395. value = value.valueOf();
  2396. }
  2397. this.value = +value | 0;
  2398. }
  2399. /**
  2400. * Access the number value.
  2401. *
  2402. * @returns returns the wrapped int32 number.
  2403. */
  2404. Int32.prototype.valueOf = function () {
  2405. return this.value;
  2406. };
  2407. Int32.prototype.toString = function (radix) {
  2408. return this.value.toString(radix);
  2409. };
  2410. Int32.prototype.toJSON = function () {
  2411. return this.value;
  2412. };
  2413. /** @internal */
  2414. Int32.prototype.toExtendedJSON = function (options) {
  2415. if (options && (options.relaxed || options.legacy))
  2416. return this.value;
  2417. return { $numberInt: this.value.toString() };
  2418. };
  2419. /** @internal */
  2420. Int32.fromExtendedJSON = function (doc, options) {
  2421. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  2422. };
  2423. /** @internal */
  2424. Int32.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2425. return this.inspect();
  2426. };
  2427. Int32.prototype.inspect = function () {
  2428. return "new Int32(" + this.valueOf() + ")";
  2429. };
  2430. return Int32;
  2431. }());
  2432. Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' });
  2433. /**
  2434. * A class representation of the BSON MaxKey type.
  2435. * @public
  2436. * @category BSONType
  2437. */
  2438. var MaxKey = /** @class */ (function () {
  2439. function MaxKey() {
  2440. if (!(this instanceof MaxKey))
  2441. return new MaxKey();
  2442. }
  2443. /** @internal */
  2444. MaxKey.prototype.toExtendedJSON = function () {
  2445. return { $maxKey: 1 };
  2446. };
  2447. /** @internal */
  2448. MaxKey.fromExtendedJSON = function () {
  2449. return new MaxKey();
  2450. };
  2451. /** @internal */
  2452. MaxKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2453. return this.inspect();
  2454. };
  2455. MaxKey.prototype.inspect = function () {
  2456. return 'new MaxKey()';
  2457. };
  2458. return MaxKey;
  2459. }());
  2460. Object.defineProperty(MaxKey.prototype, '_bsontype', { value: 'MaxKey' });
  2461. /**
  2462. * A class representation of the BSON MinKey type.
  2463. * @public
  2464. * @category BSONType
  2465. */
  2466. var MinKey = /** @class */ (function () {
  2467. function MinKey() {
  2468. if (!(this instanceof MinKey))
  2469. return new MinKey();
  2470. }
  2471. /** @internal */
  2472. MinKey.prototype.toExtendedJSON = function () {
  2473. return { $minKey: 1 };
  2474. };
  2475. /** @internal */
  2476. MinKey.fromExtendedJSON = function () {
  2477. return new MinKey();
  2478. };
  2479. /** @internal */
  2480. MinKey.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2481. return this.inspect();
  2482. };
  2483. MinKey.prototype.inspect = function () {
  2484. return 'new MinKey()';
  2485. };
  2486. return MinKey;
  2487. }());
  2488. Object.defineProperty(MinKey.prototype, '_bsontype', { value: 'MinKey' });
  2489. // Regular expression that checks for hex value
  2490. var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
  2491. // Unique sequence for the current process (initialized on first use)
  2492. var PROCESS_UNIQUE = null;
  2493. var kId = Symbol('id');
  2494. /**
  2495. * A class representation of the BSON ObjectId type.
  2496. * @public
  2497. * @category BSONType
  2498. */
  2499. var ObjectId = /** @class */ (function () {
  2500. /**
  2501. * Create an ObjectId type
  2502. *
  2503. * @param inputId - Can be a 24 character hex string, 12 byte binary Buffer, or a number.
  2504. */
  2505. function ObjectId(inputId) {
  2506. if (!(this instanceof ObjectId))
  2507. return new ObjectId(inputId);
  2508. // workingId is set based on type of input and whether valid id exists for the input
  2509. var workingId;
  2510. if (typeof inputId === 'object' && inputId && 'id' in inputId) {
  2511. if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
  2512. throw new BSONTypeError('Argument passed in must have an id that is of type string or Buffer');
  2513. }
  2514. if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
  2515. workingId = Buffer.from(inputId.toHexString(), 'hex');
  2516. }
  2517. else {
  2518. workingId = inputId.id;
  2519. }
  2520. }
  2521. else {
  2522. workingId = inputId;
  2523. }
  2524. // the following cases use workingId to construct an ObjectId
  2525. if (workingId == null || typeof workingId === 'number') {
  2526. // The most common use case (blank id, new objectId instance)
  2527. // Generate a new id
  2528. this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
  2529. }
  2530. else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
  2531. // If intstanceof matches we can escape calling ensure buffer in Node.js environments
  2532. this[kId] = workingId instanceof Buffer ? workingId : ensureBuffer(workingId);
  2533. }
  2534. else if (typeof workingId === 'string') {
  2535. if (workingId.length === 12) {
  2536. var bytes = Buffer.from(workingId);
  2537. if (bytes.byteLength === 12) {
  2538. this[kId] = bytes;
  2539. }
  2540. else {
  2541. throw new BSONTypeError('Argument passed in must be a string of 12 bytes');
  2542. }
  2543. }
  2544. else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
  2545. this[kId] = Buffer.from(workingId, 'hex');
  2546. }
  2547. else {
  2548. throw new BSONTypeError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer');
  2549. }
  2550. }
  2551. else {
  2552. throw new BSONTypeError('Argument passed in does not match the accepted types');
  2553. }
  2554. // If we are caching the hex string
  2555. if (ObjectId.cacheHexString) {
  2556. this.__id = this.id.toString('hex');
  2557. }
  2558. }
  2559. Object.defineProperty(ObjectId.prototype, "id", {
  2560. /**
  2561. * The ObjectId bytes
  2562. * @readonly
  2563. */
  2564. get: function () {
  2565. return this[kId];
  2566. },
  2567. set: function (value) {
  2568. this[kId] = value;
  2569. if (ObjectId.cacheHexString) {
  2570. this.__id = value.toString('hex');
  2571. }
  2572. },
  2573. enumerable: false,
  2574. configurable: true
  2575. });
  2576. Object.defineProperty(ObjectId.prototype, "generationTime", {
  2577. /**
  2578. * The generation time of this ObjectId instance
  2579. * @deprecated Please use getTimestamp / createFromTime which returns an int32 epoch
  2580. */
  2581. get: function () {
  2582. return this.id.readInt32BE(0);
  2583. },
  2584. set: function (value) {
  2585. // Encode time into first 4 bytes
  2586. this.id.writeUInt32BE(value, 0);
  2587. },
  2588. enumerable: false,
  2589. configurable: true
  2590. });
  2591. /** Returns the ObjectId id as a 24 character hex string representation */
  2592. ObjectId.prototype.toHexString = function () {
  2593. if (ObjectId.cacheHexString && this.__id) {
  2594. return this.__id;
  2595. }
  2596. var hexString = this.id.toString('hex');
  2597. if (ObjectId.cacheHexString && !this.__id) {
  2598. this.__id = hexString;
  2599. }
  2600. return hexString;
  2601. };
  2602. /**
  2603. * Update the ObjectId index
  2604. * @privateRemarks
  2605. * Used in generating new ObjectId's on the driver
  2606. * @internal
  2607. */
  2608. ObjectId.getInc = function () {
  2609. return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
  2610. };
  2611. /**
  2612. * Generate a 12 byte id buffer used in ObjectId's
  2613. *
  2614. * @param time - pass in a second based timestamp.
  2615. */
  2616. ObjectId.generate = function (time) {
  2617. if ('number' !== typeof time) {
  2618. time = Math.floor(Date.now() / 1000);
  2619. }
  2620. var inc = ObjectId.getInc();
  2621. var buffer = Buffer.alloc(12);
  2622. // 4-byte timestamp
  2623. buffer.writeUInt32BE(time, 0);
  2624. // set PROCESS_UNIQUE if yet not initialized
  2625. if (PROCESS_UNIQUE === null) {
  2626. PROCESS_UNIQUE = randomBytes(5);
  2627. }
  2628. // 5-byte process unique
  2629. buffer[4] = PROCESS_UNIQUE[0];
  2630. buffer[5] = PROCESS_UNIQUE[1];
  2631. buffer[6] = PROCESS_UNIQUE[2];
  2632. buffer[7] = PROCESS_UNIQUE[3];
  2633. buffer[8] = PROCESS_UNIQUE[4];
  2634. // 3-byte counter
  2635. buffer[11] = inc & 0xff;
  2636. buffer[10] = (inc >> 8) & 0xff;
  2637. buffer[9] = (inc >> 16) & 0xff;
  2638. return buffer;
  2639. };
  2640. /**
  2641. * Converts the id into a 24 character hex string for printing
  2642. *
  2643. * @param format - The Buffer toString format parameter.
  2644. */
  2645. ObjectId.prototype.toString = function (format) {
  2646. // Is the id a buffer then use the buffer toString method to return the format
  2647. if (format)
  2648. return this.id.toString(format);
  2649. return this.toHexString();
  2650. };
  2651. /** Converts to its JSON the 24 character hex string representation. */
  2652. ObjectId.prototype.toJSON = function () {
  2653. return this.toHexString();
  2654. };
  2655. /**
  2656. * Compares the equality of this ObjectId with `otherID`.
  2657. *
  2658. * @param otherId - ObjectId instance to compare against.
  2659. */
  2660. ObjectId.prototype.equals = function (otherId) {
  2661. if (otherId === undefined || otherId === null) {
  2662. return false;
  2663. }
  2664. if (otherId instanceof ObjectId) {
  2665. return this[kId][11] === otherId[kId][11] && this[kId].equals(otherId[kId]);
  2666. }
  2667. if (typeof otherId === 'string' &&
  2668. ObjectId.isValid(otherId) &&
  2669. otherId.length === 12 &&
  2670. isUint8Array(this.id)) {
  2671. return otherId === Buffer.prototype.toString.call(this.id, 'latin1');
  2672. }
  2673. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
  2674. return otherId.toLowerCase() === this.toHexString();
  2675. }
  2676. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
  2677. return Buffer.from(otherId).equals(this.id);
  2678. }
  2679. if (typeof otherId === 'object' &&
  2680. 'toHexString' in otherId &&
  2681. typeof otherId.toHexString === 'function') {
  2682. var otherIdString = otherId.toHexString();
  2683. var thisIdString = this.toHexString().toLowerCase();
  2684. return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
  2685. }
  2686. return false;
  2687. };
  2688. /** Returns the generation date (accurate up to the second) that this ID was generated. */
  2689. ObjectId.prototype.getTimestamp = function () {
  2690. var timestamp = new Date();
  2691. var time = this.id.readUInt32BE(0);
  2692. timestamp.setTime(Math.floor(time) * 1000);
  2693. return timestamp;
  2694. };
  2695. /** @internal */
  2696. ObjectId.createPk = function () {
  2697. return new ObjectId();
  2698. };
  2699. /**
  2700. * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
  2701. *
  2702. * @param time - an integer number representing a number of seconds.
  2703. */
  2704. ObjectId.createFromTime = function (time) {
  2705. var buffer = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  2706. // Encode time into first 4 bytes
  2707. buffer.writeUInt32BE(time, 0);
  2708. // Return the new objectId
  2709. return new ObjectId(buffer);
  2710. };
  2711. /**
  2712. * Creates an ObjectId from a hex string representation of an ObjectId.
  2713. *
  2714. * @param hexString - create a ObjectId from a passed in 24 character hexstring.
  2715. */
  2716. ObjectId.createFromHexString = function (hexString) {
  2717. // Throw an error if it's not a valid setup
  2718. if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) {
  2719. throw new BSONTypeError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters');
  2720. }
  2721. return new ObjectId(Buffer.from(hexString, 'hex'));
  2722. };
  2723. /**
  2724. * Checks if a value is a valid bson ObjectId
  2725. *
  2726. * @param id - ObjectId instance to validate.
  2727. */
  2728. ObjectId.isValid = function (id) {
  2729. if (id == null)
  2730. return false;
  2731. try {
  2732. new ObjectId(id);
  2733. return true;
  2734. }
  2735. catch (_a) {
  2736. return false;
  2737. }
  2738. };
  2739. /** @internal */
  2740. ObjectId.prototype.toExtendedJSON = function () {
  2741. if (this.toHexString)
  2742. return { $oid: this.toHexString() };
  2743. return { $oid: this.toString('hex') };
  2744. };
  2745. /** @internal */
  2746. ObjectId.fromExtendedJSON = function (doc) {
  2747. return new ObjectId(doc.$oid);
  2748. };
  2749. /**
  2750. * Converts to a string representation of this Id.
  2751. *
  2752. * @returns return the 24 character hex string representation.
  2753. * @internal
  2754. */
  2755. ObjectId.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2756. return this.inspect();
  2757. };
  2758. ObjectId.prototype.inspect = function () {
  2759. return "new ObjectId(\"" + this.toHexString() + "\")";
  2760. };
  2761. /** @internal */
  2762. ObjectId.index = Math.floor(Math.random() * 0xffffff);
  2763. return ObjectId;
  2764. }());
  2765. // Deprecated methods
  2766. Object.defineProperty(ObjectId.prototype, 'generate', {
  2767. value: deprecate(function (time) { return ObjectId.generate(time); }, 'Please use the static `ObjectId.generate(time)` instead')
  2768. });
  2769. Object.defineProperty(ObjectId.prototype, 'getInc', {
  2770. value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  2771. });
  2772. Object.defineProperty(ObjectId.prototype, 'get_inc', {
  2773. value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  2774. });
  2775. Object.defineProperty(ObjectId, 'get_inc', {
  2776. value: deprecate(function () { return ObjectId.getInc(); }, 'Please use the static `ObjectId.getInc()` instead')
  2777. });
  2778. Object.defineProperty(ObjectId.prototype, '_bsontype', { value: 'ObjectID' });
  2779. function alphabetize(str) {
  2780. return str.split('').sort().join('');
  2781. }
  2782. /**
  2783. * A class representation of the BSON RegExp type.
  2784. * @public
  2785. * @category BSONType
  2786. */
  2787. var BSONRegExp = /** @class */ (function () {
  2788. /**
  2789. * @param pattern - The regular expression pattern to match
  2790. * @param options - The regular expression options
  2791. */
  2792. function BSONRegExp(pattern, options) {
  2793. if (!(this instanceof BSONRegExp))
  2794. return new BSONRegExp(pattern, options);
  2795. this.pattern = pattern;
  2796. this.options = alphabetize(options !== null && options !== void 0 ? options : '');
  2797. if (this.pattern.indexOf('\x00') !== -1) {
  2798. throw new BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern));
  2799. }
  2800. if (this.options.indexOf('\x00') !== -1) {
  2801. throw new BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options));
  2802. }
  2803. // Validate options
  2804. for (var i = 0; i < this.options.length; i++) {
  2805. if (!(this.options[i] === 'i' ||
  2806. this.options[i] === 'm' ||
  2807. this.options[i] === 'x' ||
  2808. this.options[i] === 'l' ||
  2809. this.options[i] === 's' ||
  2810. this.options[i] === 'u')) {
  2811. throw new BSONError("The regular expression option [" + this.options[i] + "] is not supported");
  2812. }
  2813. }
  2814. }
  2815. BSONRegExp.parseOptions = function (options) {
  2816. return options ? options.split('').sort().join('') : '';
  2817. };
  2818. /** @internal */
  2819. BSONRegExp.prototype.toExtendedJSON = function (options) {
  2820. options = options || {};
  2821. if (options.legacy) {
  2822. return { $regex: this.pattern, $options: this.options };
  2823. }
  2824. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  2825. };
  2826. /** @internal */
  2827. BSONRegExp.fromExtendedJSON = function (doc) {
  2828. if ('$regex' in doc) {
  2829. if (typeof doc.$regex !== 'string') {
  2830. // This is for $regex query operators that have extended json values.
  2831. if (doc.$regex._bsontype === 'BSONRegExp') {
  2832. return doc;
  2833. }
  2834. }
  2835. else {
  2836. return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
  2837. }
  2838. }
  2839. if ('$regularExpression' in doc) {
  2840. return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
  2841. }
  2842. throw new BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc));
  2843. };
  2844. return BSONRegExp;
  2845. }());
  2846. Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' });
  2847. /**
  2848. * A class representation of the BSON Symbol type.
  2849. * @public
  2850. * @category BSONType
  2851. */
  2852. var BSONSymbol = /** @class */ (function () {
  2853. /**
  2854. * @param value - the string representing the symbol.
  2855. */
  2856. function BSONSymbol(value) {
  2857. if (!(this instanceof BSONSymbol))
  2858. return new BSONSymbol(value);
  2859. this.value = value;
  2860. }
  2861. /** Access the wrapped string value. */
  2862. BSONSymbol.prototype.valueOf = function () {
  2863. return this.value;
  2864. };
  2865. BSONSymbol.prototype.toString = function () {
  2866. return this.value;
  2867. };
  2868. /** @internal */
  2869. BSONSymbol.prototype.inspect = function () {
  2870. return "new BSONSymbol(\"" + this.value + "\")";
  2871. };
  2872. BSONSymbol.prototype.toJSON = function () {
  2873. return this.value;
  2874. };
  2875. /** @internal */
  2876. BSONSymbol.prototype.toExtendedJSON = function () {
  2877. return { $symbol: this.value };
  2878. };
  2879. /** @internal */
  2880. BSONSymbol.fromExtendedJSON = function (doc) {
  2881. return new BSONSymbol(doc.$symbol);
  2882. };
  2883. /** @internal */
  2884. BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2885. return this.inspect();
  2886. };
  2887. return BSONSymbol;
  2888. }());
  2889. Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' });
  2890. /** @public */
  2891. var LongWithoutOverridesClass = Long;
  2892. /**
  2893. * @public
  2894. * @category BSONType
  2895. * */
  2896. var Timestamp = /** @class */ (function (_super) {
  2897. __extends(Timestamp, _super);
  2898. function Timestamp(low, high) {
  2899. var _this = this;
  2900. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  2901. ///@ts-expect-error
  2902. if (!(_this instanceof Timestamp))
  2903. return new Timestamp(low, high);
  2904. if (Long.isLong(low)) {
  2905. _this = _super.call(this, low.low, low.high, true) || this;
  2906. }
  2907. else if (isObjectLike(low) && typeof low.t !== 'undefined' && typeof low.i !== 'undefined') {
  2908. _this = _super.call(this, low.i, low.t, true) || this;
  2909. }
  2910. else {
  2911. _this = _super.call(this, low, high, true) || this;
  2912. }
  2913. Object.defineProperty(_this, '_bsontype', {
  2914. value: 'Timestamp',
  2915. writable: false,
  2916. configurable: false,
  2917. enumerable: false
  2918. });
  2919. return _this;
  2920. }
  2921. Timestamp.prototype.toJSON = function () {
  2922. return {
  2923. $timestamp: this.toString()
  2924. };
  2925. };
  2926. /** Returns a Timestamp represented by the given (32-bit) integer value. */
  2927. Timestamp.fromInt = function (value) {
  2928. return new Timestamp(Long.fromInt(value, true));
  2929. };
  2930. /** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */
  2931. Timestamp.fromNumber = function (value) {
  2932. return new Timestamp(Long.fromNumber(value, true));
  2933. };
  2934. /**
  2935. * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
  2936. *
  2937. * @param lowBits - the low 32-bits.
  2938. * @param highBits - the high 32-bits.
  2939. */
  2940. Timestamp.fromBits = function (lowBits, highBits) {
  2941. return new Timestamp(lowBits, highBits);
  2942. };
  2943. /**
  2944. * Returns a Timestamp from the given string, optionally using the given radix.
  2945. *
  2946. * @param str - the textual representation of the Timestamp.
  2947. * @param optRadix - the radix in which the text is written.
  2948. */
  2949. Timestamp.fromString = function (str, optRadix) {
  2950. return new Timestamp(Long.fromString(str, true, optRadix));
  2951. };
  2952. /** @internal */
  2953. Timestamp.prototype.toExtendedJSON = function () {
  2954. return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } };
  2955. };
  2956. /** @internal */
  2957. Timestamp.fromExtendedJSON = function (doc) {
  2958. return new Timestamp(doc.$timestamp);
  2959. };
  2960. /** @internal */
  2961. Timestamp.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
  2962. return this.inspect();
  2963. };
  2964. Timestamp.prototype.inspect = function () {
  2965. return "new Timestamp({ t: " + this.getHighBits() + ", i: " + this.getLowBits() + " })";
  2966. };
  2967. Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
  2968. return Timestamp;
  2969. }(LongWithoutOverridesClass));
  2970. function isBSONType(value) {
  2971. return (isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string');
  2972. }
  2973. // INT32 boundaries
  2974. var BSON_INT32_MAX$1 = 0x7fffffff;
  2975. var BSON_INT32_MIN$1 = -0x80000000;
  2976. // INT64 boundaries
  2977. var BSON_INT64_MAX$1 = 0x7fffffffffffffff;
  2978. var BSON_INT64_MIN$1 = -0x8000000000000000;
  2979. // all the types where we don't need to do any special processing and can just pass the EJSON
  2980. //straight to type.fromExtendedJSON
  2981. var keysToCodecs = {
  2982. $oid: ObjectId,
  2983. $binary: Binary,
  2984. $uuid: Binary,
  2985. $symbol: BSONSymbol,
  2986. $numberInt: Int32,
  2987. $numberDecimal: Decimal128,
  2988. $numberDouble: Double,
  2989. $numberLong: Long,
  2990. $minKey: MinKey,
  2991. $maxKey: MaxKey,
  2992. $regex: BSONRegExp,
  2993. $regularExpression: BSONRegExp,
  2994. $timestamp: Timestamp
  2995. };
  2996. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2997. function deserializeValue(value, options) {
  2998. if (options === void 0) { options = {}; }
  2999. if (typeof value === 'number') {
  3000. if (options.relaxed || options.legacy) {
  3001. return value;
  3002. }
  3003. // if it's an integer, should interpret as smallest BSON integer
  3004. // that can represent it exactly. (if out of range, interpret as double.)
  3005. if (Math.floor(value) === value) {
  3006. if (value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1)
  3007. return new Int32(value);
  3008. if (value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1)
  3009. return Long.fromNumber(value);
  3010. }
  3011. // If the number is a non-integer or out of integer range, should interpret as BSON Double.
  3012. return new Double(value);
  3013. }
  3014. // from here on out we're looking for bson types, so bail if its not an object
  3015. if (value == null || typeof value !== 'object')
  3016. return value;
  3017. // upgrade deprecated undefined to null
  3018. if (value.$undefined)
  3019. return null;
  3020. var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; });
  3021. for (var i = 0; i < keys.length; i++) {
  3022. var c = keysToCodecs[keys[i]];
  3023. if (c)
  3024. return c.fromExtendedJSON(value, options);
  3025. }
  3026. if (value.$date != null) {
  3027. var d = value.$date;
  3028. var date = new Date();
  3029. if (options.legacy) {
  3030. if (typeof d === 'number')
  3031. date.setTime(d);
  3032. else if (typeof d === 'string')
  3033. date.setTime(Date.parse(d));
  3034. }
  3035. else {
  3036. if (typeof d === 'string')
  3037. date.setTime(Date.parse(d));
  3038. else if (Long.isLong(d))
  3039. date.setTime(d.toNumber());
  3040. else if (typeof d === 'number' && options.relaxed)
  3041. date.setTime(d);
  3042. }
  3043. return date;
  3044. }
  3045. if (value.$code != null) {
  3046. var copy = Object.assign({}, value);
  3047. if (value.$scope) {
  3048. copy.$scope = deserializeValue(value.$scope);
  3049. }
  3050. return Code.fromExtendedJSON(value);
  3051. }
  3052. if (isDBRefLike(value) || value.$dbPointer) {
  3053. var v = value.$ref ? value : value.$dbPointer;
  3054. // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
  3055. // because of the order JSON.parse goes through the document
  3056. if (v instanceof DBRef)
  3057. return v;
  3058. var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); });
  3059. var valid_1 = true;
  3060. dollarKeys.forEach(function (k) {
  3061. if (['$ref', '$id', '$db'].indexOf(k) === -1)
  3062. valid_1 = false;
  3063. });
  3064. // only make DBRef if $ keys are all valid
  3065. if (valid_1)
  3066. return DBRef.fromExtendedJSON(v);
  3067. }
  3068. return value;
  3069. }
  3070. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3071. function serializeArray(array, options) {
  3072. return array.map(function (v, index) {
  3073. options.seenObjects.push({ propertyName: "index " + index, obj: null });
  3074. try {
  3075. return serializeValue(v, options);
  3076. }
  3077. finally {
  3078. options.seenObjects.pop();
  3079. }
  3080. });
  3081. }
  3082. function getISOString(date) {
  3083. var isoStr = date.toISOString();
  3084. // we should only show milliseconds in timestamp if they're non-zero
  3085. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  3086. }
  3087. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3088. function serializeValue(value, options) {
  3089. if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
  3090. var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; });
  3091. if (index !== -1) {
  3092. var props = options.seenObjects.map(function (entry) { return entry.propertyName; });
  3093. var leadingPart = props
  3094. .slice(0, index)
  3095. .map(function (prop) { return prop + " -> "; })
  3096. .join('');
  3097. var alreadySeen = props[index];
  3098. var circularPart = ' -> ' +
  3099. props
  3100. .slice(index + 1, props.length - 1)
  3101. .map(function (prop) { return prop + " -> "; })
  3102. .join('');
  3103. var current = props[props.length - 1];
  3104. var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
  3105. var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
  3106. throw new BSONTypeError('Converting circular structure to EJSON:\n' +
  3107. (" " + leadingPart + alreadySeen + circularPart + current + "\n") +
  3108. (" " + leadingSpace + "\\" + dashes + "/"));
  3109. }
  3110. options.seenObjects[options.seenObjects.length - 1].obj = value;
  3111. }
  3112. if (Array.isArray(value))
  3113. return serializeArray(value, options);
  3114. if (value === undefined)
  3115. return null;
  3116. if (value instanceof Date || isDate(value)) {
  3117. var dateNum = value.getTime(),
  3118. // is it in year range 1970-9999?
  3119. inRange = dateNum > -1 && dateNum < 253402318800000;
  3120. if (options.legacy) {
  3121. return options.relaxed && inRange
  3122. ? { $date: value.getTime() }
  3123. : { $date: getISOString(value) };
  3124. }
  3125. return options.relaxed && inRange
  3126. ? { $date: getISOString(value) }
  3127. : { $date: { $numberLong: value.getTime().toString() } };
  3128. }
  3129. if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
  3130. // it's an integer
  3131. if (Math.floor(value) === value) {
  3132. var int32Range = value >= BSON_INT32_MIN$1 && value <= BSON_INT32_MAX$1, int64Range = value >= BSON_INT64_MIN$1 && value <= BSON_INT64_MAX$1;
  3133. // interpret as being of the smallest BSON integer type that can represent the number exactly
  3134. if (int32Range)
  3135. return { $numberInt: value.toString() };
  3136. if (int64Range)
  3137. return { $numberLong: value.toString() };
  3138. }
  3139. return { $numberDouble: value.toString() };
  3140. }
  3141. if (value instanceof RegExp || isRegExp(value)) {
  3142. var flags = value.flags;
  3143. if (flags === undefined) {
  3144. var match = value.toString().match(/[gimuy]*$/);
  3145. if (match) {
  3146. flags = match[0];
  3147. }
  3148. }
  3149. var rx = new BSONRegExp(value.source, flags);
  3150. return rx.toExtendedJSON(options);
  3151. }
  3152. if (value != null && typeof value === 'object')
  3153. return serializeDocument(value, options);
  3154. return value;
  3155. }
  3156. var BSON_TYPE_MAPPINGS = {
  3157. Binary: function (o) { return new Binary(o.value(), o.sub_type); },
  3158. Code: function (o) { return new Code(o.code, o.scope); },
  3159. DBRef: function (o) { return new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); },
  3160. Decimal128: function (o) { return new Decimal128(o.bytes); },
  3161. Double: function (o) { return new Double(o.value); },
  3162. Int32: function (o) { return new Int32(o.value); },
  3163. Long: function (o) {
  3164. return Long.fromBits(
  3165. // underscore variants for 1.x backwards compatibility
  3166. o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_);
  3167. },
  3168. MaxKey: function () { return new MaxKey(); },
  3169. MinKey: function () { return new MinKey(); },
  3170. ObjectID: function (o) { return new ObjectId(o); },
  3171. ObjectId: function (o) { return new ObjectId(o); },
  3172. BSONRegExp: function (o) { return new BSONRegExp(o.pattern, o.options); },
  3173. Symbol: function (o) { return new BSONSymbol(o.value); },
  3174. Timestamp: function (o) { return Timestamp.fromBits(o.low, o.high); }
  3175. };
  3176. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3177. function serializeDocument(doc, options) {
  3178. if (doc == null || typeof doc !== 'object')
  3179. throw new BSONError('not an object instance');
  3180. var bsontype = doc._bsontype;
  3181. if (typeof bsontype === 'undefined') {
  3182. // It's a regular object. Recursively serialize its property values.
  3183. var _doc = {};
  3184. for (var name in doc) {
  3185. options.seenObjects.push({ propertyName: name, obj: null });
  3186. try {
  3187. _doc[name] = serializeValue(doc[name], options);
  3188. }
  3189. finally {
  3190. options.seenObjects.pop();
  3191. }
  3192. }
  3193. return _doc;
  3194. }
  3195. else if (isBSONType(doc)) {
  3196. // the "document" is really just a BSON type object
  3197. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3198. var outDoc = doc;
  3199. if (typeof outDoc.toExtendedJSON !== 'function') {
  3200. // There's no EJSON serialization function on the object. It's probably an
  3201. // object created by a previous version of this library (or another library)
  3202. // that's duck-typing objects to look like they were generated by this library).
  3203. // Copy the object into this library's version of that type.
  3204. var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
  3205. if (!mapper) {
  3206. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
  3207. }
  3208. outDoc = mapper(outDoc);
  3209. }
  3210. // Two BSON types may have nested objects that may need to be serialized too
  3211. if (bsontype === 'Code' && outDoc.scope) {
  3212. outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
  3213. }
  3214. else if (bsontype === 'DBRef' && outDoc.oid) {
  3215. outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
  3216. }
  3217. return outDoc.toExtendedJSON(options);
  3218. }
  3219. else {
  3220. throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
  3221. }
  3222. }
  3223. /**
  3224. * EJSON parse / stringify API
  3225. * @public
  3226. */
  3227. // the namespace here is used to emulate `export * as EJSON from '...'`
  3228. // which as of now (sept 2020) api-extractor does not support
  3229. // eslint-disable-next-line @typescript-eslint/no-namespace
  3230. var EJSON;
  3231. (function (EJSON) {
  3232. /**
  3233. * Parse an Extended JSON string, constructing the JavaScript value or object described by that
  3234. * string.
  3235. *
  3236. * @example
  3237. * ```js
  3238. * const { EJSON } = require('bson');
  3239. * const text = '{ "int32": { "$numberInt": "10" } }';
  3240. *
  3241. * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
  3242. * console.log(EJSON.parse(text, { relaxed: false }));
  3243. *
  3244. * // prints { int32: 10 }
  3245. * console.log(EJSON.parse(text));
  3246. * ```
  3247. */
  3248. function parse(text, options) {
  3249. var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options);
  3250. // relaxed implies not strict
  3251. if (typeof finalOptions.relaxed === 'boolean')
  3252. finalOptions.strict = !finalOptions.relaxed;
  3253. if (typeof finalOptions.strict === 'boolean')
  3254. finalOptions.relaxed = !finalOptions.strict;
  3255. return JSON.parse(text, function (key, value) {
  3256. if (key.indexOf('\x00') !== -1) {
  3257. throw new BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key));
  3258. }
  3259. return deserializeValue(value, finalOptions);
  3260. });
  3261. }
  3262. EJSON.parse = parse;
  3263. /**
  3264. * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
  3265. * function is specified or optionally including only the specified properties if a replacer array
  3266. * is specified.
  3267. *
  3268. * @param value - The value to convert to extended JSON
  3269. * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
  3270. * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
  3271. * @param options - Optional settings
  3272. *
  3273. * @example
  3274. * ```js
  3275. * const { EJSON } = require('bson');
  3276. * const Int32 = require('mongodb').Int32;
  3277. * const doc = { int32: new Int32(10) };
  3278. *
  3279. * // prints '{"int32":{"$numberInt":"10"}}'
  3280. * console.log(EJSON.stringify(doc, { relaxed: false }));
  3281. *
  3282. * // prints '{"int32":10}'
  3283. * console.log(EJSON.stringify(doc));
  3284. * ```
  3285. */
  3286. function stringify(value,
  3287. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3288. replacer, space, options) {
  3289. if (space != null && typeof space === 'object') {
  3290. options = space;
  3291. space = 0;
  3292. }
  3293. if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
  3294. options = replacer;
  3295. replacer = undefined;
  3296. space = 0;
  3297. }
  3298. var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
  3299. seenObjects: [{ propertyName: '(root)', obj: null }]
  3300. });
  3301. var doc = serializeValue(value, serializeOptions);
  3302. return JSON.stringify(doc, replacer, space);
  3303. }
  3304. EJSON.stringify = stringify;
  3305. /**
  3306. * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
  3307. *
  3308. * @param value - The object to serialize
  3309. * @param options - Optional settings passed to the `stringify` function
  3310. */
  3311. function serialize(value, options) {
  3312. options = options || {};
  3313. return JSON.parse(stringify(value, options));
  3314. }
  3315. EJSON.serialize = serialize;
  3316. /**
  3317. * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
  3318. *
  3319. * @param ejson - The Extended JSON object to deserialize
  3320. * @param options - Optional settings passed to the parse method
  3321. */
  3322. function deserialize(ejson, options) {
  3323. options = options || {};
  3324. return parse(JSON.stringify(ejson), options);
  3325. }
  3326. EJSON.deserialize = deserialize;
  3327. })(EJSON || (EJSON = {}));
  3328. /* eslint-disable @typescript-eslint/no-explicit-any */
  3329. /** @public */
  3330. var bsonMap;
  3331. var bsonGlobal = getGlobal();
  3332. if (bsonGlobal.Map) {
  3333. bsonMap = bsonGlobal.Map;
  3334. }
  3335. else {
  3336. // We will return a polyfill
  3337. bsonMap = /** @class */ (function () {
  3338. function Map(array) {
  3339. if (array === void 0) { array = []; }
  3340. this._keys = [];
  3341. this._values = {};
  3342. for (var i = 0; i < array.length; i++) {
  3343. if (array[i] == null)
  3344. continue; // skip null and undefined
  3345. var entry = array[i];
  3346. var key = entry[0];
  3347. var value = entry[1];
  3348. // Add the key to the list of keys in order
  3349. this._keys.push(key);
  3350. // Add the key and value to the values dictionary with a point
  3351. // to the location in the ordered keys list
  3352. this._values[key] = { v: value, i: this._keys.length - 1 };
  3353. }
  3354. }
  3355. Map.prototype.clear = function () {
  3356. this._keys = [];
  3357. this._values = {};
  3358. };
  3359. Map.prototype.delete = function (key) {
  3360. var value = this._values[key];
  3361. if (value == null)
  3362. return false;
  3363. // Delete entry
  3364. delete this._values[key];
  3365. // Remove the key from the ordered keys list
  3366. this._keys.splice(value.i, 1);
  3367. return true;
  3368. };
  3369. Map.prototype.entries = function () {
  3370. var _this = this;
  3371. var index = 0;
  3372. return {
  3373. next: function () {
  3374. var key = _this._keys[index++];
  3375. return {
  3376. value: key !== undefined ? [key, _this._values[key].v] : undefined,
  3377. done: key !== undefined ? false : true
  3378. };
  3379. }
  3380. };
  3381. };
  3382. Map.prototype.forEach = function (callback, self) {
  3383. self = self || this;
  3384. for (var i = 0; i < this._keys.length; i++) {
  3385. var key = this._keys[i];
  3386. // Call the forEach callback
  3387. callback.call(self, this._values[key].v, key, self);
  3388. }
  3389. };
  3390. Map.prototype.get = function (key) {
  3391. return this._values[key] ? this._values[key].v : undefined;
  3392. };
  3393. Map.prototype.has = function (key) {
  3394. return this._values[key] != null;
  3395. };
  3396. Map.prototype.keys = function () {
  3397. var _this = this;
  3398. var index = 0;
  3399. return {
  3400. next: function () {
  3401. var key = _this._keys[index++];
  3402. return {
  3403. value: key !== undefined ? key : undefined,
  3404. done: key !== undefined ? false : true
  3405. };
  3406. }
  3407. };
  3408. };
  3409. Map.prototype.set = function (key, value) {
  3410. if (this._values[key]) {
  3411. this._values[key].v = value;
  3412. return this;
  3413. }
  3414. // Add the key to the list of keys in order
  3415. this._keys.push(key);
  3416. // Add the key and value to the values dictionary with a point
  3417. // to the location in the ordered keys list
  3418. this._values[key] = { v: value, i: this._keys.length - 1 };
  3419. return this;
  3420. };
  3421. Map.prototype.values = function () {
  3422. var _this = this;
  3423. var index = 0;
  3424. return {
  3425. next: function () {
  3426. var key = _this._keys[index++];
  3427. return {
  3428. value: key !== undefined ? _this._values[key].v : undefined,
  3429. done: key !== undefined ? false : true
  3430. };
  3431. }
  3432. };
  3433. };
  3434. Object.defineProperty(Map.prototype, "size", {
  3435. get: function () {
  3436. return this._keys.length;
  3437. },
  3438. enumerable: false,
  3439. configurable: true
  3440. });
  3441. return Map;
  3442. }());
  3443. }
  3444. /** @internal */
  3445. var BSON_INT32_MAX = 0x7fffffff;
  3446. /** @internal */
  3447. var BSON_INT32_MIN = -0x80000000;
  3448. /** @internal */
  3449. var BSON_INT64_MAX = Math.pow(2, 63) - 1;
  3450. /** @internal */
  3451. var BSON_INT64_MIN = -Math.pow(2, 63);
  3452. /**
  3453. * Any integer up to 2^53 can be precisely represented by a double.
  3454. * @internal
  3455. */
  3456. var JS_INT_MAX = Math.pow(2, 53);
  3457. /**
  3458. * Any integer down to -2^53 can be precisely represented by a double.
  3459. * @internal
  3460. */
  3461. var JS_INT_MIN = -Math.pow(2, 53);
  3462. /** Number BSON Type @internal */
  3463. var BSON_DATA_NUMBER = 1;
  3464. /** String BSON Type @internal */
  3465. var BSON_DATA_STRING = 2;
  3466. /** Object BSON Type @internal */
  3467. var BSON_DATA_OBJECT = 3;
  3468. /** Array BSON Type @internal */
  3469. var BSON_DATA_ARRAY = 4;
  3470. /** Binary BSON Type @internal */
  3471. var BSON_DATA_BINARY = 5;
  3472. /** Binary BSON Type @internal */
  3473. var BSON_DATA_UNDEFINED = 6;
  3474. /** ObjectId BSON Type @internal */
  3475. var BSON_DATA_OID = 7;
  3476. /** Boolean BSON Type @internal */
  3477. var BSON_DATA_BOOLEAN = 8;
  3478. /** Date BSON Type @internal */
  3479. var BSON_DATA_DATE = 9;
  3480. /** null BSON Type @internal */
  3481. var BSON_DATA_NULL = 10;
  3482. /** RegExp BSON Type @internal */
  3483. var BSON_DATA_REGEXP = 11;
  3484. /** Code BSON Type @internal */
  3485. var BSON_DATA_DBPOINTER = 12;
  3486. /** Code BSON Type @internal */
  3487. var BSON_DATA_CODE = 13;
  3488. /** Symbol BSON Type @internal */
  3489. var BSON_DATA_SYMBOL = 14;
  3490. /** Code with Scope BSON Type @internal */
  3491. var BSON_DATA_CODE_W_SCOPE = 15;
  3492. /** 32 bit Integer BSON Type @internal */
  3493. var BSON_DATA_INT = 16;
  3494. /** Timestamp BSON Type @internal */
  3495. var BSON_DATA_TIMESTAMP = 17;
  3496. /** Long BSON Type @internal */
  3497. var BSON_DATA_LONG = 18;
  3498. /** Decimal128 BSON Type @internal */
  3499. var BSON_DATA_DECIMAL128 = 19;
  3500. /** MinKey BSON Type @internal */
  3501. var BSON_DATA_MIN_KEY = 0xff;
  3502. /** MaxKey BSON Type @internal */
  3503. var BSON_DATA_MAX_KEY = 0x7f;
  3504. /** Binary Default Type @internal */
  3505. var BSON_BINARY_SUBTYPE_DEFAULT = 0;
  3506. /** Binary Function Type @internal */
  3507. var BSON_BINARY_SUBTYPE_FUNCTION = 1;
  3508. /** Binary Byte Array Type @internal */
  3509. var BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
  3510. /** Binary Deprecated UUID Type @deprecated Please use BSON_BINARY_SUBTYPE_UUID_NEW @internal */
  3511. var BSON_BINARY_SUBTYPE_UUID = 3;
  3512. /** Binary UUID Type @internal */
  3513. var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
  3514. /** Binary MD5 Type @internal */
  3515. var BSON_BINARY_SUBTYPE_MD5 = 5;
  3516. /** Encrypted BSON type @internal */
  3517. var BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
  3518. /** Column BSON type @internal */
  3519. var BSON_BINARY_SUBTYPE_COLUMN = 7;
  3520. /** Binary User Defined Type @internal */
  3521. var BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
  3522. function calculateObjectSize$1(object, serializeFunctions, ignoreUndefined) {
  3523. var totalLength = 4 + 1;
  3524. if (Array.isArray(object)) {
  3525. for (var i = 0; i < object.length; i++) {
  3526. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  3527. }
  3528. }
  3529. else {
  3530. // If we have toBSON defined, override the current object
  3531. if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
  3532. object = object.toBSON();
  3533. }
  3534. // Calculate size
  3535. for (var key in object) {
  3536. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  3537. }
  3538. }
  3539. return totalLength;
  3540. }
  3541. /** @internal */
  3542. function calculateElement(name,
  3543. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3544. value, serializeFunctions, isArray, ignoreUndefined) {
  3545. if (serializeFunctions === void 0) { serializeFunctions = false; }
  3546. if (isArray === void 0) { isArray = false; }
  3547. if (ignoreUndefined === void 0) { ignoreUndefined = false; }
  3548. // If we have toBSON defined, override the current object
  3549. if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
  3550. value = value.toBSON();
  3551. }
  3552. switch (typeof value) {
  3553. case 'string':
  3554. return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1;
  3555. case 'number':
  3556. if (Math.floor(value) === value &&
  3557. value >= JS_INT_MIN &&
  3558. value <= JS_INT_MAX) {
  3559. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  3560. // 32 bit
  3561. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1);
  3562. }
  3563. else {
  3564. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  3565. }
  3566. }
  3567. else {
  3568. // 64 bit
  3569. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  3570. }
  3571. case 'undefined':
  3572. if (isArray || !ignoreUndefined)
  3573. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;
  3574. return 0;
  3575. case 'boolean':
  3576. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1);
  3577. case 'object':
  3578. if (value == null || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  3579. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1;
  3580. }
  3581. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  3582. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1);
  3583. }
  3584. else if (value instanceof Date || isDate(value)) {
  3585. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  3586. }
  3587. else if (ArrayBuffer.isView(value) ||
  3588. value instanceof ArrayBuffer ||
  3589. isAnyArrayBuffer(value)) {
  3590. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.byteLength);
  3591. }
  3592. else if (value['_bsontype'] === 'Long' ||
  3593. value['_bsontype'] === 'Double' ||
  3594. value['_bsontype'] === 'Timestamp') {
  3595. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1);
  3596. }
  3597. else if (value['_bsontype'] === 'Decimal128') {
  3598. return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1);
  3599. }
  3600. else if (value['_bsontype'] === 'Code') {
  3601. // Calculate size depending on the availability of a scope
  3602. if (value.scope != null && Object.keys(value.scope).length > 0) {
  3603. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3604. 1 +
  3605. 4 +
  3606. 4 +
  3607. Buffer.byteLength(value.code.toString(), 'utf8') +
  3608. 1 +
  3609. calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined));
  3610. }
  3611. else {
  3612. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3613. 1 +
  3614. 4 +
  3615. Buffer.byteLength(value.code.toString(), 'utf8') +
  3616. 1);
  3617. }
  3618. }
  3619. else if (value['_bsontype'] === 'Binary') {
  3620. // Check what kind of subtype we have
  3621. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  3622. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3623. (value.position + 1 + 4 + 1 + 4));
  3624. }
  3625. else {
  3626. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1));
  3627. }
  3628. }
  3629. else if (value['_bsontype'] === 'Symbol') {
  3630. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3631. Buffer.byteLength(value.value, 'utf8') +
  3632. 4 +
  3633. 1 +
  3634. 1);
  3635. }
  3636. else if (value['_bsontype'] === 'DBRef') {
  3637. // Set up correct object for serialization
  3638. var ordered_values = Object.assign({
  3639. $ref: value.collection,
  3640. $id: value.oid
  3641. }, value.fields);
  3642. // Add db reference if it exists
  3643. if (value.db != null) {
  3644. ordered_values['$db'] = value.db;
  3645. }
  3646. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3647. 1 +
  3648. calculateObjectSize$1(ordered_values, serializeFunctions, ignoreUndefined));
  3649. }
  3650. else if (value instanceof RegExp || isRegExp(value)) {
  3651. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3652. 1 +
  3653. Buffer.byteLength(value.source, 'utf8') +
  3654. 1 +
  3655. (value.global ? 1 : 0) +
  3656. (value.ignoreCase ? 1 : 0) +
  3657. (value.multiline ? 1 : 0) +
  3658. 1);
  3659. }
  3660. else if (value['_bsontype'] === 'BSONRegExp') {
  3661. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3662. 1 +
  3663. Buffer.byteLength(value.pattern, 'utf8') +
  3664. 1 +
  3665. Buffer.byteLength(value.options, 'utf8') +
  3666. 1);
  3667. }
  3668. else {
  3669. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3670. calculateObjectSize$1(value, serializeFunctions, ignoreUndefined) +
  3671. 1);
  3672. }
  3673. case 'function':
  3674. // WTF for 0.4.X where typeof /someregexp/ === 'function'
  3675. if (value instanceof RegExp || isRegExp(value) || String.call(value) === '[object RegExp]') {
  3676. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3677. 1 +
  3678. Buffer.byteLength(value.source, 'utf8') +
  3679. 1 +
  3680. (value.global ? 1 : 0) +
  3681. (value.ignoreCase ? 1 : 0) +
  3682. (value.multiline ? 1 : 0) +
  3683. 1);
  3684. }
  3685. else {
  3686. if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) {
  3687. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3688. 1 +
  3689. 4 +
  3690. 4 +
  3691. Buffer.byteLength(normalizedFunctionString(value), 'utf8') +
  3692. 1 +
  3693. calculateObjectSize$1(value.scope, serializeFunctions, ignoreUndefined));
  3694. }
  3695. else if (serializeFunctions) {
  3696. return ((name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) +
  3697. 1 +
  3698. 4 +
  3699. Buffer.byteLength(normalizedFunctionString(value), 'utf8') +
  3700. 1);
  3701. }
  3702. }
  3703. }
  3704. return 0;
  3705. }
  3706. var FIRST_BIT = 0x80;
  3707. var FIRST_TWO_BITS = 0xc0;
  3708. var FIRST_THREE_BITS = 0xe0;
  3709. var FIRST_FOUR_BITS = 0xf0;
  3710. var FIRST_FIVE_BITS = 0xf8;
  3711. var TWO_BIT_CHAR = 0xc0;
  3712. var THREE_BIT_CHAR = 0xe0;
  3713. var FOUR_BIT_CHAR = 0xf0;
  3714. var CONTINUING_CHAR = 0x80;
  3715. /**
  3716. * Determines if the passed in bytes are valid utf8
  3717. * @param bytes - An array of 8-bit bytes. Must be indexable and have length property
  3718. * @param start - The index to start validating
  3719. * @param end - The index to end validating
  3720. */
  3721. function validateUtf8(bytes, start, end) {
  3722. var continuation = 0;
  3723. for (var i = start; i < end; i += 1) {
  3724. var byte = bytes[i];
  3725. if (continuation) {
  3726. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  3727. return false;
  3728. }
  3729. continuation -= 1;
  3730. }
  3731. else if (byte & FIRST_BIT) {
  3732. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  3733. continuation = 1;
  3734. }
  3735. else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  3736. continuation = 2;
  3737. }
  3738. else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  3739. continuation = 3;
  3740. }
  3741. else {
  3742. return false;
  3743. }
  3744. }
  3745. }
  3746. return !continuation;
  3747. }
  3748. // Internal long versions
  3749. var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
  3750. var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
  3751. var functionCache = {};
  3752. function deserialize$1(buffer, options, isArray) {
  3753. options = options == null ? {} : options;
  3754. var index = options && options.index ? options.index : 0;
  3755. // Read the document size
  3756. var size = buffer[index] |
  3757. (buffer[index + 1] << 8) |
  3758. (buffer[index + 2] << 16) |
  3759. (buffer[index + 3] << 24);
  3760. if (size < 5) {
  3761. throw new BSONError("bson size must be >= 5, is " + size);
  3762. }
  3763. if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
  3764. throw new BSONError("buffer length " + buffer.length + " must be >= bson size " + size);
  3765. }
  3766. if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
  3767. throw new BSONError("buffer length " + buffer.length + " must === bson size " + size);
  3768. }
  3769. if (size + index > buffer.byteLength) {
  3770. throw new BSONError("(bson size " + size + " + options.index " + index + " must be <= buffer length " + buffer.byteLength + ")");
  3771. }
  3772. // Illegal end value
  3773. if (buffer[index + size - 1] !== 0) {
  3774. throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  3775. }
  3776. // Start deserializtion
  3777. return deserializeObject(buffer, index, options, isArray);
  3778. }
  3779. var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
  3780. function deserializeObject(buffer, index, options, isArray) {
  3781. if (isArray === void 0) { isArray = false; }
  3782. var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions'];
  3783. var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions'];
  3784. var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
  3785. // Return raw bson buffer instead of parsing it
  3786. var raw = options['raw'] == null ? false : options['raw'];
  3787. // Return BSONRegExp objects instead of native regular expressions
  3788. var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
  3789. // Controls the promotion of values vs wrapper classes
  3790. var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
  3791. var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs'];
  3792. var promoteValues = options['promoteValues'] == null ? true : options['promoteValues'];
  3793. // Ensures default validation option if none given
  3794. var validation = options.validation == null ? { utf8: true } : options.validation;
  3795. // Shows if global utf-8 validation is enabled or disabled
  3796. var globalUTFValidation = true;
  3797. // Reflects utf-8 validation setting regardless of global or specific key validation
  3798. var validationSetting;
  3799. // Set of keys either to enable or disable validation on
  3800. var utf8KeysSet = new Set();
  3801. // Check for boolean uniformity and empty validation option
  3802. var utf8ValidatedKeys = validation.utf8;
  3803. if (typeof utf8ValidatedKeys === 'boolean') {
  3804. validationSetting = utf8ValidatedKeys;
  3805. }
  3806. else {
  3807. globalUTFValidation = false;
  3808. var utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
  3809. return utf8ValidatedKeys[key];
  3810. });
  3811. if (utf8ValidationValues.length === 0) {
  3812. throw new BSONError('UTF-8 validation setting cannot be empty');
  3813. }
  3814. if (typeof utf8ValidationValues[0] !== 'boolean') {
  3815. throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
  3816. }
  3817. validationSetting = utf8ValidationValues[0];
  3818. // Ensures boolean uniformity in utf-8 validation (all true or all false)
  3819. if (!utf8ValidationValues.every(function (item) { return item === validationSetting; })) {
  3820. throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
  3821. }
  3822. }
  3823. // Add keys to set that will either be validated or not based on validationSetting
  3824. if (!globalUTFValidation) {
  3825. for (var _i = 0, _a = Object.keys(utf8ValidatedKeys); _i < _a.length; _i++) {
  3826. var key = _a[_i];
  3827. utf8KeysSet.add(key);
  3828. }
  3829. }
  3830. // Set the start index
  3831. var startIndex = index;
  3832. // Validate that we have at least 4 bytes of buffer
  3833. if (buffer.length < 5)
  3834. throw new BSONError('corrupt bson message < 5 bytes long');
  3835. // Read the document size
  3836. var size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  3837. // Ensure buffer is valid size
  3838. if (size < 5 || size > buffer.length)
  3839. throw new BSONError('corrupt bson message');
  3840. // Create holding object
  3841. var object = isArray ? [] : {};
  3842. // Used for arrays to skip having to perform utf8 decoding
  3843. var arrayIndex = 0;
  3844. var done = false;
  3845. var isPossibleDBRef = isArray ? false : null;
  3846. // While we have more left data left keep parsing
  3847. while (!done) {
  3848. // Read the type
  3849. var elementType = buffer[index++];
  3850. // If we get a zero it's the last byte, exit
  3851. if (elementType === 0)
  3852. break;
  3853. // Get the start search index
  3854. var i = index;
  3855. // Locate the end of the c string
  3856. while (buffer[i] !== 0x00 && i < buffer.length) {
  3857. i++;
  3858. }
  3859. // If are at the end of the buffer there is a problem with the document
  3860. if (i >= buffer.byteLength)
  3861. throw new BSONError('Bad BSON Document: illegal CString');
  3862. // Represents the key
  3863. var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);
  3864. // shouldValidateKey is true if the key should be validated, false otherwise
  3865. var shouldValidateKey = true;
  3866. if (globalUTFValidation || utf8KeysSet.has(name)) {
  3867. shouldValidateKey = validationSetting;
  3868. }
  3869. else {
  3870. shouldValidateKey = !validationSetting;
  3871. }
  3872. if (isPossibleDBRef !== false && name[0] === '$') {
  3873. isPossibleDBRef = allowedDBRefKeys.test(name);
  3874. }
  3875. var value = void 0;
  3876. index = i + 1;
  3877. if (elementType === BSON_DATA_STRING) {
  3878. var stringSize = buffer[index++] |
  3879. (buffer[index++] << 8) |
  3880. (buffer[index++] << 16) |
  3881. (buffer[index++] << 24);
  3882. if (stringSize <= 0 ||
  3883. stringSize > buffer.length - index ||
  3884. buffer[index + stringSize - 1] !== 0) {
  3885. throw new BSONError('bad string length in bson');
  3886. }
  3887. value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  3888. index = index + stringSize;
  3889. }
  3890. else if (elementType === BSON_DATA_OID) {
  3891. var oid = Buffer.alloc(12);
  3892. buffer.copy(oid, 0, index, index + 12);
  3893. value = new ObjectId(oid);
  3894. index = index + 12;
  3895. }
  3896. else if (elementType === BSON_DATA_INT && promoteValues === false) {
  3897. value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24));
  3898. }
  3899. else if (elementType === BSON_DATA_INT) {
  3900. value =
  3901. buffer[index++] |
  3902. (buffer[index++] << 8) |
  3903. (buffer[index++] << 16) |
  3904. (buffer[index++] << 24);
  3905. }
  3906. else if (elementType === BSON_DATA_NUMBER && promoteValues === false) {
  3907. value = new Double(buffer.readDoubleLE(index));
  3908. index = index + 8;
  3909. }
  3910. else if (elementType === BSON_DATA_NUMBER) {
  3911. value = buffer.readDoubleLE(index);
  3912. index = index + 8;
  3913. }
  3914. else if (elementType === BSON_DATA_DATE) {
  3915. var lowBits = buffer[index++] |
  3916. (buffer[index++] << 8) |
  3917. (buffer[index++] << 16) |
  3918. (buffer[index++] << 24);
  3919. var highBits = buffer[index++] |
  3920. (buffer[index++] << 8) |
  3921. (buffer[index++] << 16) |
  3922. (buffer[index++] << 24);
  3923. value = new Date(new Long(lowBits, highBits).toNumber());
  3924. }
  3925. else if (elementType === BSON_DATA_BOOLEAN) {
  3926. if (buffer[index] !== 0 && buffer[index] !== 1)
  3927. throw new BSONError('illegal boolean type value');
  3928. value = buffer[index++] === 1;
  3929. }
  3930. else if (elementType === BSON_DATA_OBJECT) {
  3931. var _index = index;
  3932. var objectSize = buffer[index] |
  3933. (buffer[index + 1] << 8) |
  3934. (buffer[index + 2] << 16) |
  3935. (buffer[index + 3] << 24);
  3936. if (objectSize <= 0 || objectSize > buffer.length - index)
  3937. throw new BSONError('bad embedded document length in bson');
  3938. // We have a raw value
  3939. if (raw) {
  3940. value = buffer.slice(index, index + objectSize);
  3941. }
  3942. else {
  3943. var objectOptions = options;
  3944. if (!globalUTFValidation) {
  3945. objectOptions = _assign(_assign({}, options), { validation: { utf8: shouldValidateKey } });
  3946. }
  3947. value = deserializeObject(buffer, _index, objectOptions, false);
  3948. }
  3949. index = index + objectSize;
  3950. }
  3951. else if (elementType === BSON_DATA_ARRAY) {
  3952. var _index = index;
  3953. var objectSize = buffer[index] |
  3954. (buffer[index + 1] << 8) |
  3955. (buffer[index + 2] << 16) |
  3956. (buffer[index + 3] << 24);
  3957. var arrayOptions = options;
  3958. // Stop index
  3959. var stopIndex = index + objectSize;
  3960. // All elements of array to be returned as raw bson
  3961. if (fieldsAsRaw && fieldsAsRaw[name]) {
  3962. arrayOptions = {};
  3963. for (var n in options) {
  3964. arrayOptions[n] = options[n];
  3965. }
  3966. arrayOptions['raw'] = true;
  3967. }
  3968. if (!globalUTFValidation) {
  3969. arrayOptions = _assign(_assign({}, arrayOptions), { validation: { utf8: shouldValidateKey } });
  3970. }
  3971. value = deserializeObject(buffer, _index, arrayOptions, true);
  3972. index = index + objectSize;
  3973. if (buffer[index - 1] !== 0)
  3974. throw new BSONError('invalid array terminator byte');
  3975. if (index !== stopIndex)
  3976. throw new BSONError('corrupted array bson');
  3977. }
  3978. else if (elementType === BSON_DATA_UNDEFINED) {
  3979. value = undefined;
  3980. }
  3981. else if (elementType === BSON_DATA_NULL) {
  3982. value = null;
  3983. }
  3984. else if (elementType === BSON_DATA_LONG) {
  3985. // Unpack the low and high bits
  3986. var lowBits = buffer[index++] |
  3987. (buffer[index++] << 8) |
  3988. (buffer[index++] << 16) |
  3989. (buffer[index++] << 24);
  3990. var highBits = buffer[index++] |
  3991. (buffer[index++] << 8) |
  3992. (buffer[index++] << 16) |
  3993. (buffer[index++] << 24);
  3994. var long = new Long(lowBits, highBits);
  3995. // Promote the long if possible
  3996. if (promoteLongs && promoteValues === true) {
  3997. value =
  3998. long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
  3999. ? long.toNumber()
  4000. : long;
  4001. }
  4002. else {
  4003. value = long;
  4004. }
  4005. }
  4006. else if (elementType === BSON_DATA_DECIMAL128) {
  4007. // Buffer to contain the decimal bytes
  4008. var bytes = Buffer.alloc(16);
  4009. // Copy the next 16 bytes into the bytes buffer
  4010. buffer.copy(bytes, 0, index, index + 16);
  4011. // Update index
  4012. index = index + 16;
  4013. // Assign the new Decimal128 value
  4014. var decimal128 = new Decimal128(bytes);
  4015. // If we have an alternative mapper use that
  4016. if ('toObject' in decimal128 && typeof decimal128.toObject === 'function') {
  4017. value = decimal128.toObject();
  4018. }
  4019. else {
  4020. value = decimal128;
  4021. }
  4022. }
  4023. else if (elementType === BSON_DATA_BINARY) {
  4024. var binarySize = buffer[index++] |
  4025. (buffer[index++] << 8) |
  4026. (buffer[index++] << 16) |
  4027. (buffer[index++] << 24);
  4028. var totalBinarySize = binarySize;
  4029. var subType = buffer[index++];
  4030. // Did we have a negative binary size, throw
  4031. if (binarySize < 0)
  4032. throw new BSONError('Negative binary type element size found');
  4033. // Is the length longer than the document
  4034. if (binarySize > buffer.byteLength)
  4035. throw new BSONError('Binary type size larger than document size');
  4036. // Decode as raw Buffer object if options specifies it
  4037. if (buffer['slice'] != null) {
  4038. // If we have subtype 2 skip the 4 bytes for the size
  4039. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  4040. binarySize =
  4041. buffer[index++] |
  4042. (buffer[index++] << 8) |
  4043. (buffer[index++] << 16) |
  4044. (buffer[index++] << 24);
  4045. if (binarySize < 0)
  4046. throw new BSONError('Negative binary type element size found for subtype 0x02');
  4047. if (binarySize > totalBinarySize - 4)
  4048. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  4049. if (binarySize < totalBinarySize - 4)
  4050. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  4051. }
  4052. if (promoteBuffers && promoteValues) {
  4053. value = buffer.slice(index, index + binarySize);
  4054. }
  4055. else {
  4056. value = new Binary(buffer.slice(index, index + binarySize), subType);
  4057. }
  4058. }
  4059. else {
  4060. var _buffer = Buffer.alloc(binarySize);
  4061. // If we have subtype 2 skip the 4 bytes for the size
  4062. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  4063. binarySize =
  4064. buffer[index++] |
  4065. (buffer[index++] << 8) |
  4066. (buffer[index++] << 16) |
  4067. (buffer[index++] << 24);
  4068. if (binarySize < 0)
  4069. throw new BSONError('Negative binary type element size found for subtype 0x02');
  4070. if (binarySize > totalBinarySize - 4)
  4071. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  4072. if (binarySize < totalBinarySize - 4)
  4073. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  4074. }
  4075. // Copy the data
  4076. for (i = 0; i < binarySize; i++) {
  4077. _buffer[i] = buffer[index + i];
  4078. }
  4079. if (promoteBuffers && promoteValues) {
  4080. value = _buffer;
  4081. }
  4082. else {
  4083. value = new Binary(_buffer, subType);
  4084. }
  4085. }
  4086. // Update the index
  4087. index = index + binarySize;
  4088. }
  4089. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
  4090. // Get the start search index
  4091. i = index;
  4092. // Locate the end of the c string
  4093. while (buffer[i] !== 0x00 && i < buffer.length) {
  4094. i++;
  4095. }
  4096. // If are at the end of the buffer there is a problem with the document
  4097. if (i >= buffer.length)
  4098. throw new BSONError('Bad BSON Document: illegal CString');
  4099. // Return the C string
  4100. var source = buffer.toString('utf8', index, i);
  4101. // Create the regexp
  4102. index = i + 1;
  4103. // Get the start search index
  4104. i = index;
  4105. // Locate the end of the c string
  4106. while (buffer[i] !== 0x00 && i < buffer.length) {
  4107. i++;
  4108. }
  4109. // If are at the end of the buffer there is a problem with the document
  4110. if (i >= buffer.length)
  4111. throw new BSONError('Bad BSON Document: illegal CString');
  4112. // Return the C string
  4113. var regExpOptions = buffer.toString('utf8', index, i);
  4114. index = i + 1;
  4115. // For each option add the corresponding one for javascript
  4116. var optionsArray = new Array(regExpOptions.length);
  4117. // Parse options
  4118. for (i = 0; i < regExpOptions.length; i++) {
  4119. switch (regExpOptions[i]) {
  4120. case 'm':
  4121. optionsArray[i] = 'm';
  4122. break;
  4123. case 's':
  4124. optionsArray[i] = 'g';
  4125. break;
  4126. case 'i':
  4127. optionsArray[i] = 'i';
  4128. break;
  4129. }
  4130. }
  4131. value = new RegExp(source, optionsArray.join(''));
  4132. }
  4133. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
  4134. // Get the start search index
  4135. i = index;
  4136. // Locate the end of the c string
  4137. while (buffer[i] !== 0x00 && i < buffer.length) {
  4138. i++;
  4139. }
  4140. // If are at the end of the buffer there is a problem with the document
  4141. if (i >= buffer.length)
  4142. throw new BSONError('Bad BSON Document: illegal CString');
  4143. // Return the C string
  4144. var source = buffer.toString('utf8', index, i);
  4145. index = i + 1;
  4146. // Get the start search index
  4147. i = index;
  4148. // Locate the end of the c string
  4149. while (buffer[i] !== 0x00 && i < buffer.length) {
  4150. i++;
  4151. }
  4152. // If are at the end of the buffer there is a problem with the document
  4153. if (i >= buffer.length)
  4154. throw new BSONError('Bad BSON Document: illegal CString');
  4155. // Return the C string
  4156. var regExpOptions = buffer.toString('utf8', index, i);
  4157. index = i + 1;
  4158. // Set the object
  4159. value = new BSONRegExp(source, regExpOptions);
  4160. }
  4161. else if (elementType === BSON_DATA_SYMBOL) {
  4162. var stringSize = buffer[index++] |
  4163. (buffer[index++] << 8) |
  4164. (buffer[index++] << 16) |
  4165. (buffer[index++] << 24);
  4166. if (stringSize <= 0 ||
  4167. stringSize > buffer.length - index ||
  4168. buffer[index + stringSize - 1] !== 0) {
  4169. throw new BSONError('bad string length in bson');
  4170. }
  4171. var symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  4172. value = promoteValues ? symbol : new BSONSymbol(symbol);
  4173. index = index + stringSize;
  4174. }
  4175. else if (elementType === BSON_DATA_TIMESTAMP) {
  4176. var lowBits = buffer[index++] |
  4177. (buffer[index++] << 8) |
  4178. (buffer[index++] << 16) |
  4179. (buffer[index++] << 24);
  4180. var highBits = buffer[index++] |
  4181. (buffer[index++] << 8) |
  4182. (buffer[index++] << 16) |
  4183. (buffer[index++] << 24);
  4184. value = new Timestamp(lowBits, highBits);
  4185. }
  4186. else if (elementType === BSON_DATA_MIN_KEY) {
  4187. value = new MinKey();
  4188. }
  4189. else if (elementType === BSON_DATA_MAX_KEY) {
  4190. value = new MaxKey();
  4191. }
  4192. else if (elementType === BSON_DATA_CODE) {
  4193. var stringSize = buffer[index++] |
  4194. (buffer[index++] << 8) |
  4195. (buffer[index++] << 16) |
  4196. (buffer[index++] << 24);
  4197. if (stringSize <= 0 ||
  4198. stringSize > buffer.length - index ||
  4199. buffer[index + stringSize - 1] !== 0) {
  4200. throw new BSONError('bad string length in bson');
  4201. }
  4202. var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  4203. // If we are evaluating the functions
  4204. if (evalFunctions) {
  4205. // If we have cache enabled let's look for the md5 of the function in the cache
  4206. if (cacheFunctions) {
  4207. // Got to do this to avoid V8 deoptimizing the call due to finding eval
  4208. value = isolateEval(functionString, functionCache, object);
  4209. }
  4210. else {
  4211. value = isolateEval(functionString);
  4212. }
  4213. }
  4214. else {
  4215. value = new Code(functionString);
  4216. }
  4217. // Update parse index position
  4218. index = index + stringSize;
  4219. }
  4220. else if (elementType === BSON_DATA_CODE_W_SCOPE) {
  4221. var totalSize = buffer[index++] |
  4222. (buffer[index++] << 8) |
  4223. (buffer[index++] << 16) |
  4224. (buffer[index++] << 24);
  4225. // Element cannot be shorter than totalSize + stringSize + documentSize + terminator
  4226. if (totalSize < 4 + 4 + 4 + 1) {
  4227. throw new BSONError('code_w_scope total size shorter minimum expected length');
  4228. }
  4229. // Get the code string size
  4230. var stringSize = buffer[index++] |
  4231. (buffer[index++] << 8) |
  4232. (buffer[index++] << 16) |
  4233. (buffer[index++] << 24);
  4234. // Check if we have a valid string
  4235. if (stringSize <= 0 ||
  4236. stringSize > buffer.length - index ||
  4237. buffer[index + stringSize - 1] !== 0) {
  4238. throw new BSONError('bad string length in bson');
  4239. }
  4240. // Javascript function
  4241. var functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  4242. // Update parse index position
  4243. index = index + stringSize;
  4244. // Parse the element
  4245. var _index = index;
  4246. // Decode the size of the object document
  4247. var objectSize = buffer[index] |
  4248. (buffer[index + 1] << 8) |
  4249. (buffer[index + 2] << 16) |
  4250. (buffer[index + 3] << 24);
  4251. // Decode the scope object
  4252. var scopeObject = deserializeObject(buffer, _index, options, false);
  4253. // Adjust the index
  4254. index = index + objectSize;
  4255. // Check if field length is too short
  4256. if (totalSize < 4 + 4 + objectSize + stringSize) {
  4257. throw new BSONError('code_w_scope total size is too short, truncating scope');
  4258. }
  4259. // Check if totalSize field is too long
  4260. if (totalSize > 4 + 4 + objectSize + stringSize) {
  4261. throw new BSONError('code_w_scope total size is too long, clips outer document');
  4262. }
  4263. // If we are evaluating the functions
  4264. if (evalFunctions) {
  4265. // If we have cache enabled let's look for the md5 of the function in the cache
  4266. if (cacheFunctions) {
  4267. // Got to do this to avoid V8 deoptimizing the call due to finding eval
  4268. value = isolateEval(functionString, functionCache, object);
  4269. }
  4270. else {
  4271. value = isolateEval(functionString);
  4272. }
  4273. value.scope = scopeObject;
  4274. }
  4275. else {
  4276. value = new Code(functionString, scopeObject);
  4277. }
  4278. }
  4279. else if (elementType === BSON_DATA_DBPOINTER) {
  4280. // Get the code string size
  4281. var stringSize = buffer[index++] |
  4282. (buffer[index++] << 8) |
  4283. (buffer[index++] << 16) |
  4284. (buffer[index++] << 24);
  4285. // Check if we have a valid string
  4286. if (stringSize <= 0 ||
  4287. stringSize > buffer.length - index ||
  4288. buffer[index + stringSize - 1] !== 0)
  4289. throw new BSONError('bad string length in bson');
  4290. // Namespace
  4291. if (validation != null && validation.utf8) {
  4292. if (!validateUtf8(buffer, index, index + stringSize - 1)) {
  4293. throw new BSONError('Invalid UTF-8 string in BSON document');
  4294. }
  4295. }
  4296. var namespace = buffer.toString('utf8', index, index + stringSize - 1);
  4297. // Update parse index position
  4298. index = index + stringSize;
  4299. // Read the oid
  4300. var oidBuffer = Buffer.alloc(12);
  4301. buffer.copy(oidBuffer, 0, index, index + 12);
  4302. var oid = new ObjectId(oidBuffer);
  4303. // Update the index
  4304. index = index + 12;
  4305. // Upgrade to DBRef type
  4306. value = new DBRef(namespace, oid);
  4307. }
  4308. else {
  4309. throw new BSONError('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '"');
  4310. }
  4311. if (name === '__proto__') {
  4312. Object.defineProperty(object, name, {
  4313. value: value,
  4314. writable: true,
  4315. enumerable: true,
  4316. configurable: true
  4317. });
  4318. }
  4319. else {
  4320. object[name] = value;
  4321. }
  4322. }
  4323. // Check if the deserialization was against a valid array/object
  4324. if (size !== index - startIndex) {
  4325. if (isArray)
  4326. throw new BSONError('corrupt array bson');
  4327. throw new BSONError('corrupt object bson');
  4328. }
  4329. // if we did not find "$ref", "$id", "$db", or found an extraneous $key, don't make a DBRef
  4330. if (!isPossibleDBRef)
  4331. return object;
  4332. if (isDBRefLike(object)) {
  4333. var copy = Object.assign({}, object);
  4334. delete copy.$ref;
  4335. delete copy.$id;
  4336. delete copy.$db;
  4337. return new DBRef(object.$ref, object.$id, object.$db, copy);
  4338. }
  4339. return object;
  4340. }
  4341. /**
  4342. * Ensure eval is isolated, store the result in functionCache.
  4343. *
  4344. * @internal
  4345. */
  4346. function isolateEval(functionString, functionCache, object) {
  4347. if (!functionCache)
  4348. return new Function(functionString);
  4349. // Check for cache hit, eval if missing and return cached function
  4350. if (functionCache[functionString] == null) {
  4351. functionCache[functionString] = new Function(functionString);
  4352. }
  4353. // Set the object
  4354. return functionCache[functionString].bind(object);
  4355. }
  4356. function getValidatedString(buffer, start, end, shouldValidateUtf8) {
  4357. var value = buffer.toString('utf8', start, end);
  4358. // if utf8 validation is on, do the check
  4359. if (shouldValidateUtf8) {
  4360. for (var i = 0; i < value.length; i++) {
  4361. if (value.charCodeAt(i) === 0xfffd) {
  4362. if (!validateUtf8(buffer, start, end)) {
  4363. throw new BSONError('Invalid UTF-8 string in BSON document');
  4364. }
  4365. break;
  4366. }
  4367. }
  4368. }
  4369. return value;
  4370. }
  4371. // Copyright (c) 2008, Fair Oaks Labs, Inc.
  4372. function writeIEEE754(buffer, value, offset, endian, mLen, nBytes) {
  4373. var e;
  4374. var m;
  4375. var c;
  4376. var bBE = endian === 'big';
  4377. var eLen = nBytes * 8 - mLen - 1;
  4378. var eMax = (1 << eLen) - 1;
  4379. var eBias = eMax >> 1;
  4380. var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  4381. var i = bBE ? nBytes - 1 : 0;
  4382. var d = bBE ? -1 : 1;
  4383. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  4384. value = Math.abs(value);
  4385. if (isNaN(value) || value === Infinity) {
  4386. m = isNaN(value) ? 1 : 0;
  4387. e = eMax;
  4388. }
  4389. else {
  4390. e = Math.floor(Math.log(value) / Math.LN2);
  4391. if (value * (c = Math.pow(2, -e)) < 1) {
  4392. e--;
  4393. c *= 2;
  4394. }
  4395. if (e + eBias >= 1) {
  4396. value += rt / c;
  4397. }
  4398. else {
  4399. value += rt * Math.pow(2, 1 - eBias);
  4400. }
  4401. if (value * c >= 2) {
  4402. e++;
  4403. c /= 2;
  4404. }
  4405. if (e + eBias >= eMax) {
  4406. m = 0;
  4407. e = eMax;
  4408. }
  4409. else if (e + eBias >= 1) {
  4410. m = (value * c - 1) * Math.pow(2, mLen);
  4411. e = e + eBias;
  4412. }
  4413. else {
  4414. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  4415. e = 0;
  4416. }
  4417. }
  4418. if (isNaN(value))
  4419. m = 0;
  4420. while (mLen >= 8) {
  4421. buffer[offset + i] = m & 0xff;
  4422. i += d;
  4423. m /= 256;
  4424. mLen -= 8;
  4425. }
  4426. e = (e << mLen) | m;
  4427. if (isNaN(value))
  4428. e += 8;
  4429. eLen += mLen;
  4430. while (eLen > 0) {
  4431. buffer[offset + i] = e & 0xff;
  4432. i += d;
  4433. e /= 256;
  4434. eLen -= 8;
  4435. }
  4436. buffer[offset + i - d] |= s * 128;
  4437. }
  4438. var regexp = /\x00/; // eslint-disable-line no-control-regex
  4439. var ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
  4440. /*
  4441. * isArray indicates if we are writing to a BSON array (type 0x04)
  4442. * which forces the "key" which really an array index as a string to be written as ascii
  4443. * This will catch any errors in index as a string generation
  4444. */
  4445. function serializeString(buffer, key, value, index, isArray) {
  4446. // Encode String type
  4447. buffer[index++] = BSON_DATA_STRING;
  4448. // Number of written bytes
  4449. var numberOfWrittenBytes = !isArray
  4450. ? buffer.write(key, index, undefined, 'utf8')
  4451. : buffer.write(key, index, undefined, 'ascii');
  4452. // Encode the name
  4453. index = index + numberOfWrittenBytes + 1;
  4454. buffer[index - 1] = 0;
  4455. // Write the string
  4456. var size = buffer.write(value, index + 4, undefined, 'utf8');
  4457. // Write the size of the string to buffer
  4458. buffer[index + 3] = ((size + 1) >> 24) & 0xff;
  4459. buffer[index + 2] = ((size + 1) >> 16) & 0xff;
  4460. buffer[index + 1] = ((size + 1) >> 8) & 0xff;
  4461. buffer[index] = (size + 1) & 0xff;
  4462. // Update index
  4463. index = index + 4 + size;
  4464. // Write zero
  4465. buffer[index++] = 0;
  4466. return index;
  4467. }
  4468. function serializeNumber(buffer, key, value, index, isArray) {
  4469. // We have an integer value
  4470. // TODO(NODE-2529): Add support for big int
  4471. if (Number.isInteger(value) &&
  4472. value >= BSON_INT32_MIN &&
  4473. value <= BSON_INT32_MAX) {
  4474. // If the value fits in 32 bits encode as int32
  4475. // Set int type 32 bits or less
  4476. buffer[index++] = BSON_DATA_INT;
  4477. // Number of written bytes
  4478. var numberOfWrittenBytes = !isArray
  4479. ? buffer.write(key, index, undefined, 'utf8')
  4480. : buffer.write(key, index, undefined, 'ascii');
  4481. // Encode the name
  4482. index = index + numberOfWrittenBytes;
  4483. buffer[index++] = 0;
  4484. // Write the int value
  4485. buffer[index++] = value & 0xff;
  4486. buffer[index++] = (value >> 8) & 0xff;
  4487. buffer[index++] = (value >> 16) & 0xff;
  4488. buffer[index++] = (value >> 24) & 0xff;
  4489. }
  4490. else {
  4491. // Encode as double
  4492. buffer[index++] = BSON_DATA_NUMBER;
  4493. // Number of written bytes
  4494. var numberOfWrittenBytes = !isArray
  4495. ? buffer.write(key, index, undefined, 'utf8')
  4496. : buffer.write(key, index, undefined, 'ascii');
  4497. // Encode the name
  4498. index = index + numberOfWrittenBytes;
  4499. buffer[index++] = 0;
  4500. // Write float
  4501. writeIEEE754(buffer, value, index, 'little', 52, 8);
  4502. // Adjust index
  4503. index = index + 8;
  4504. }
  4505. return index;
  4506. }
  4507. function serializeNull(buffer, key, _, index, isArray) {
  4508. // Set long type
  4509. buffer[index++] = BSON_DATA_NULL;
  4510. // Number of written bytes
  4511. var numberOfWrittenBytes = !isArray
  4512. ? buffer.write(key, index, undefined, 'utf8')
  4513. : buffer.write(key, index, undefined, 'ascii');
  4514. // Encode the name
  4515. index = index + numberOfWrittenBytes;
  4516. buffer[index++] = 0;
  4517. return index;
  4518. }
  4519. function serializeBoolean(buffer, key, value, index, isArray) {
  4520. // Write the type
  4521. buffer[index++] = BSON_DATA_BOOLEAN;
  4522. // Number of written bytes
  4523. var numberOfWrittenBytes = !isArray
  4524. ? buffer.write(key, index, undefined, 'utf8')
  4525. : buffer.write(key, index, undefined, 'ascii');
  4526. // Encode the name
  4527. index = index + numberOfWrittenBytes;
  4528. buffer[index++] = 0;
  4529. // Encode the boolean value
  4530. buffer[index++] = value ? 1 : 0;
  4531. return index;
  4532. }
  4533. function serializeDate(buffer, key, value, index, isArray) {
  4534. // Write the type
  4535. buffer[index++] = BSON_DATA_DATE;
  4536. // Number of written bytes
  4537. var numberOfWrittenBytes = !isArray
  4538. ? buffer.write(key, index, undefined, 'utf8')
  4539. : buffer.write(key, index, undefined, 'ascii');
  4540. // Encode the name
  4541. index = index + numberOfWrittenBytes;
  4542. buffer[index++] = 0;
  4543. // Write the date
  4544. var dateInMilis = Long.fromNumber(value.getTime());
  4545. var lowBits = dateInMilis.getLowBits();
  4546. var highBits = dateInMilis.getHighBits();
  4547. // Encode low bits
  4548. buffer[index++] = lowBits & 0xff;
  4549. buffer[index++] = (lowBits >> 8) & 0xff;
  4550. buffer[index++] = (lowBits >> 16) & 0xff;
  4551. buffer[index++] = (lowBits >> 24) & 0xff;
  4552. // Encode high bits
  4553. buffer[index++] = highBits & 0xff;
  4554. buffer[index++] = (highBits >> 8) & 0xff;
  4555. buffer[index++] = (highBits >> 16) & 0xff;
  4556. buffer[index++] = (highBits >> 24) & 0xff;
  4557. return index;
  4558. }
  4559. function serializeRegExp(buffer, key, value, index, isArray) {
  4560. // Write the type
  4561. buffer[index++] = BSON_DATA_REGEXP;
  4562. // Number of written bytes
  4563. var numberOfWrittenBytes = !isArray
  4564. ? buffer.write(key, index, undefined, 'utf8')
  4565. : buffer.write(key, index, undefined, 'ascii');
  4566. // Encode the name
  4567. index = index + numberOfWrittenBytes;
  4568. buffer[index++] = 0;
  4569. if (value.source && value.source.match(regexp) != null) {
  4570. throw Error('value ' + value.source + ' must not contain null bytes');
  4571. }
  4572. // Adjust the index
  4573. index = index + buffer.write(value.source, index, undefined, 'utf8');
  4574. // Write zero
  4575. buffer[index++] = 0x00;
  4576. // Write the parameters
  4577. if (value.ignoreCase)
  4578. buffer[index++] = 0x69; // i
  4579. if (value.global)
  4580. buffer[index++] = 0x73; // s
  4581. if (value.multiline)
  4582. buffer[index++] = 0x6d; // m
  4583. // Add ending zero
  4584. buffer[index++] = 0x00;
  4585. return index;
  4586. }
  4587. function serializeBSONRegExp(buffer, key, value, index, isArray) {
  4588. // Write the type
  4589. buffer[index++] = BSON_DATA_REGEXP;
  4590. // Number of written bytes
  4591. var numberOfWrittenBytes = !isArray
  4592. ? buffer.write(key, index, undefined, 'utf8')
  4593. : buffer.write(key, index, undefined, 'ascii');
  4594. // Encode the name
  4595. index = index + numberOfWrittenBytes;
  4596. buffer[index++] = 0;
  4597. // Check the pattern for 0 bytes
  4598. if (value.pattern.match(regexp) != null) {
  4599. // The BSON spec doesn't allow keys with null bytes because keys are
  4600. // null-terminated.
  4601. throw Error('pattern ' + value.pattern + ' must not contain null bytes');
  4602. }
  4603. // Adjust the index
  4604. index = index + buffer.write(value.pattern, index, undefined, 'utf8');
  4605. // Write zero
  4606. buffer[index++] = 0x00;
  4607. // Write the options
  4608. index = index + buffer.write(value.options.split('').sort().join(''), index, undefined, 'utf8');
  4609. // Add ending zero
  4610. buffer[index++] = 0x00;
  4611. return index;
  4612. }
  4613. function serializeMinMax(buffer, key, value, index, isArray) {
  4614. // Write the type of either min or max key
  4615. if (value === null) {
  4616. buffer[index++] = BSON_DATA_NULL;
  4617. }
  4618. else if (value._bsontype === 'MinKey') {
  4619. buffer[index++] = BSON_DATA_MIN_KEY;
  4620. }
  4621. else {
  4622. buffer[index++] = BSON_DATA_MAX_KEY;
  4623. }
  4624. // Number of written bytes
  4625. var numberOfWrittenBytes = !isArray
  4626. ? buffer.write(key, index, undefined, 'utf8')
  4627. : buffer.write(key, index, undefined, 'ascii');
  4628. // Encode the name
  4629. index = index + numberOfWrittenBytes;
  4630. buffer[index++] = 0;
  4631. return index;
  4632. }
  4633. function serializeObjectId(buffer, key, value, index, isArray) {
  4634. // Write the type
  4635. buffer[index++] = BSON_DATA_OID;
  4636. // Number of written bytes
  4637. var numberOfWrittenBytes = !isArray
  4638. ? buffer.write(key, index, undefined, 'utf8')
  4639. : buffer.write(key, index, undefined, 'ascii');
  4640. // Encode the name
  4641. index = index + numberOfWrittenBytes;
  4642. buffer[index++] = 0;
  4643. // Write the objectId into the shared buffer
  4644. if (typeof value.id === 'string') {
  4645. buffer.write(value.id, index, undefined, 'binary');
  4646. }
  4647. else if (isUint8Array(value.id)) {
  4648. // Use the standard JS methods here because buffer.copy() is buggy with the
  4649. // browser polyfill
  4650. buffer.set(value.id.subarray(0, 12), index);
  4651. }
  4652. else {
  4653. throw new BSONTypeError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
  4654. }
  4655. // Adjust index
  4656. return index + 12;
  4657. }
  4658. function serializeBuffer(buffer, key, value, index, isArray) {
  4659. // Write the type
  4660. buffer[index++] = BSON_DATA_BINARY;
  4661. // Number of written bytes
  4662. var numberOfWrittenBytes = !isArray
  4663. ? buffer.write(key, index, undefined, 'utf8')
  4664. : buffer.write(key, index, undefined, 'ascii');
  4665. // Encode the name
  4666. index = index + numberOfWrittenBytes;
  4667. buffer[index++] = 0;
  4668. // Get size of the buffer (current write point)
  4669. var size = value.length;
  4670. // Write the size of the string to buffer
  4671. buffer[index++] = size & 0xff;
  4672. buffer[index++] = (size >> 8) & 0xff;
  4673. buffer[index++] = (size >> 16) & 0xff;
  4674. buffer[index++] = (size >> 24) & 0xff;
  4675. // Write the default subtype
  4676. buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
  4677. // Copy the content form the binary field to the buffer
  4678. buffer.set(ensureBuffer(value), index);
  4679. // Adjust the index
  4680. index = index + size;
  4681. return index;
  4682. }
  4683. function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) {
  4684. if (checkKeys === void 0) { checkKeys = false; }
  4685. if (depth === void 0) { depth = 0; }
  4686. if (serializeFunctions === void 0) { serializeFunctions = false; }
  4687. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  4688. if (isArray === void 0) { isArray = false; }
  4689. if (path === void 0) { path = []; }
  4690. for (var i = 0; i < path.length; i++) {
  4691. if (path[i] === value)
  4692. throw new BSONError('cyclic dependency detected');
  4693. }
  4694. // Push value to stack
  4695. path.push(value);
  4696. // Write the type
  4697. buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
  4698. // Number of written bytes
  4699. var numberOfWrittenBytes = !isArray
  4700. ? buffer.write(key, index, undefined, 'utf8')
  4701. : buffer.write(key, index, undefined, 'ascii');
  4702. // Encode the name
  4703. index = index + numberOfWrittenBytes;
  4704. buffer[index++] = 0;
  4705. var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  4706. // Pop stack
  4707. path.pop();
  4708. return endIndex;
  4709. }
  4710. function serializeDecimal128(buffer, key, value, index, isArray) {
  4711. buffer[index++] = BSON_DATA_DECIMAL128;
  4712. // Number of written bytes
  4713. var numberOfWrittenBytes = !isArray
  4714. ? buffer.write(key, index, undefined, 'utf8')
  4715. : buffer.write(key, index, undefined, 'ascii');
  4716. // Encode the name
  4717. index = index + numberOfWrittenBytes;
  4718. buffer[index++] = 0;
  4719. // Write the data from the value
  4720. // Prefer the standard JS methods because their typechecking is not buggy,
  4721. // unlike the `buffer` polyfill's.
  4722. buffer.set(value.bytes.subarray(0, 16), index);
  4723. return index + 16;
  4724. }
  4725. function serializeLong(buffer, key, value, index, isArray) {
  4726. // Write the type
  4727. buffer[index++] =
  4728. value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
  4729. // Number of written bytes
  4730. var numberOfWrittenBytes = !isArray
  4731. ? buffer.write(key, index, undefined, 'utf8')
  4732. : buffer.write(key, index, undefined, 'ascii');
  4733. // Encode the name
  4734. index = index + numberOfWrittenBytes;
  4735. buffer[index++] = 0;
  4736. // Write the date
  4737. var lowBits = value.getLowBits();
  4738. var highBits = value.getHighBits();
  4739. // Encode low bits
  4740. buffer[index++] = lowBits & 0xff;
  4741. buffer[index++] = (lowBits >> 8) & 0xff;
  4742. buffer[index++] = (lowBits >> 16) & 0xff;
  4743. buffer[index++] = (lowBits >> 24) & 0xff;
  4744. // Encode high bits
  4745. buffer[index++] = highBits & 0xff;
  4746. buffer[index++] = (highBits >> 8) & 0xff;
  4747. buffer[index++] = (highBits >> 16) & 0xff;
  4748. buffer[index++] = (highBits >> 24) & 0xff;
  4749. return index;
  4750. }
  4751. function serializeInt32(buffer, key, value, index, isArray) {
  4752. value = value.valueOf();
  4753. // Set int type 32 bits or less
  4754. buffer[index++] = BSON_DATA_INT;
  4755. // Number of written bytes
  4756. var numberOfWrittenBytes = !isArray
  4757. ? buffer.write(key, index, undefined, 'utf8')
  4758. : buffer.write(key, index, undefined, 'ascii');
  4759. // Encode the name
  4760. index = index + numberOfWrittenBytes;
  4761. buffer[index++] = 0;
  4762. // Write the int value
  4763. buffer[index++] = value & 0xff;
  4764. buffer[index++] = (value >> 8) & 0xff;
  4765. buffer[index++] = (value >> 16) & 0xff;
  4766. buffer[index++] = (value >> 24) & 0xff;
  4767. return index;
  4768. }
  4769. function serializeDouble(buffer, key, value, index, isArray) {
  4770. // Encode as double
  4771. buffer[index++] = BSON_DATA_NUMBER;
  4772. // Number of written bytes
  4773. var numberOfWrittenBytes = !isArray
  4774. ? buffer.write(key, index, undefined, 'utf8')
  4775. : buffer.write(key, index, undefined, 'ascii');
  4776. // Encode the name
  4777. index = index + numberOfWrittenBytes;
  4778. buffer[index++] = 0;
  4779. // Write float
  4780. writeIEEE754(buffer, value.value, index, 'little', 52, 8);
  4781. // Adjust index
  4782. index = index + 8;
  4783. return index;
  4784. }
  4785. function serializeFunction(buffer, key, value, index, _checkKeys, _depth, isArray) {
  4786. buffer[index++] = BSON_DATA_CODE;
  4787. // Number of written bytes
  4788. var numberOfWrittenBytes = !isArray
  4789. ? buffer.write(key, index, undefined, 'utf8')
  4790. : buffer.write(key, index, undefined, 'ascii');
  4791. // Encode the name
  4792. index = index + numberOfWrittenBytes;
  4793. buffer[index++] = 0;
  4794. // Function string
  4795. var functionString = normalizedFunctionString(value);
  4796. // Write the string
  4797. var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  4798. // Write the size of the string to buffer
  4799. buffer[index] = size & 0xff;
  4800. buffer[index + 1] = (size >> 8) & 0xff;
  4801. buffer[index + 2] = (size >> 16) & 0xff;
  4802. buffer[index + 3] = (size >> 24) & 0xff;
  4803. // Update index
  4804. index = index + 4 + size - 1;
  4805. // Write zero
  4806. buffer[index++] = 0;
  4807. return index;
  4808. }
  4809. function serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) {
  4810. if (checkKeys === void 0) { checkKeys = false; }
  4811. if (depth === void 0) { depth = 0; }
  4812. if (serializeFunctions === void 0) { serializeFunctions = false; }
  4813. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  4814. if (isArray === void 0) { isArray = false; }
  4815. if (value.scope && typeof value.scope === 'object') {
  4816. // Write the type
  4817. buffer[index++] = BSON_DATA_CODE_W_SCOPE;
  4818. // Number of written bytes
  4819. var numberOfWrittenBytes = !isArray
  4820. ? buffer.write(key, index, undefined, 'utf8')
  4821. : buffer.write(key, index, undefined, 'ascii');
  4822. // Encode the name
  4823. index = index + numberOfWrittenBytes;
  4824. buffer[index++] = 0;
  4825. // Starting index
  4826. var startIndex = index;
  4827. // Serialize the function
  4828. // Get the function string
  4829. var functionString = typeof value.code === 'string' ? value.code : value.code.toString();
  4830. // Index adjustment
  4831. index = index + 4;
  4832. // Write string into buffer
  4833. var codeSize = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  4834. // Write the size of the string to buffer
  4835. buffer[index] = codeSize & 0xff;
  4836. buffer[index + 1] = (codeSize >> 8) & 0xff;
  4837. buffer[index + 2] = (codeSize >> 16) & 0xff;
  4838. buffer[index + 3] = (codeSize >> 24) & 0xff;
  4839. // Write end 0
  4840. buffer[index + 4 + codeSize - 1] = 0;
  4841. // Write the
  4842. index = index + codeSize + 4;
  4843. //
  4844. // Serialize the scope value
  4845. var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined);
  4846. index = endIndex - 1;
  4847. // Writ the total
  4848. var totalSize = endIndex - startIndex;
  4849. // Write the total size of the object
  4850. buffer[startIndex++] = totalSize & 0xff;
  4851. buffer[startIndex++] = (totalSize >> 8) & 0xff;
  4852. buffer[startIndex++] = (totalSize >> 16) & 0xff;
  4853. buffer[startIndex++] = (totalSize >> 24) & 0xff;
  4854. // Write trailing zero
  4855. buffer[index++] = 0;
  4856. }
  4857. else {
  4858. buffer[index++] = BSON_DATA_CODE;
  4859. // Number of written bytes
  4860. var numberOfWrittenBytes = !isArray
  4861. ? buffer.write(key, index, undefined, 'utf8')
  4862. : buffer.write(key, index, undefined, 'ascii');
  4863. // Encode the name
  4864. index = index + numberOfWrittenBytes;
  4865. buffer[index++] = 0;
  4866. // Function string
  4867. var functionString = value.code.toString();
  4868. // Write the string
  4869. var size = buffer.write(functionString, index + 4, undefined, 'utf8') + 1;
  4870. // Write the size of the string to buffer
  4871. buffer[index] = size & 0xff;
  4872. buffer[index + 1] = (size >> 8) & 0xff;
  4873. buffer[index + 2] = (size >> 16) & 0xff;
  4874. buffer[index + 3] = (size >> 24) & 0xff;
  4875. // Update index
  4876. index = index + 4 + size - 1;
  4877. // Write zero
  4878. buffer[index++] = 0;
  4879. }
  4880. return index;
  4881. }
  4882. function serializeBinary(buffer, key, value, index, isArray) {
  4883. // Write the type
  4884. buffer[index++] = BSON_DATA_BINARY;
  4885. // Number of written bytes
  4886. var numberOfWrittenBytes = !isArray
  4887. ? buffer.write(key, index, undefined, 'utf8')
  4888. : buffer.write(key, index, undefined, 'ascii');
  4889. // Encode the name
  4890. index = index + numberOfWrittenBytes;
  4891. buffer[index++] = 0;
  4892. // Extract the buffer
  4893. var data = value.value(true);
  4894. // Calculate size
  4895. var size = value.position;
  4896. // Add the deprecated 02 type 4 bytes of size to total
  4897. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
  4898. size = size + 4;
  4899. // Write the size of the string to buffer
  4900. buffer[index++] = size & 0xff;
  4901. buffer[index++] = (size >> 8) & 0xff;
  4902. buffer[index++] = (size >> 16) & 0xff;
  4903. buffer[index++] = (size >> 24) & 0xff;
  4904. // Write the subtype to the buffer
  4905. buffer[index++] = value.sub_type;
  4906. // If we have binary type 2 the 4 first bytes are the size
  4907. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  4908. size = size - 4;
  4909. buffer[index++] = size & 0xff;
  4910. buffer[index++] = (size >> 8) & 0xff;
  4911. buffer[index++] = (size >> 16) & 0xff;
  4912. buffer[index++] = (size >> 24) & 0xff;
  4913. }
  4914. // Write the data to the object
  4915. buffer.set(data, index);
  4916. // Adjust the index
  4917. index = index + value.position;
  4918. return index;
  4919. }
  4920. function serializeSymbol(buffer, key, value, index, isArray) {
  4921. // Write the type
  4922. buffer[index++] = BSON_DATA_SYMBOL;
  4923. // Number of written bytes
  4924. var numberOfWrittenBytes = !isArray
  4925. ? buffer.write(key, index, undefined, 'utf8')
  4926. : buffer.write(key, index, undefined, 'ascii');
  4927. // Encode the name
  4928. index = index + numberOfWrittenBytes;
  4929. buffer[index++] = 0;
  4930. // Write the string
  4931. var size = buffer.write(value.value, index + 4, undefined, 'utf8') + 1;
  4932. // Write the size of the string to buffer
  4933. buffer[index] = size & 0xff;
  4934. buffer[index + 1] = (size >> 8) & 0xff;
  4935. buffer[index + 2] = (size >> 16) & 0xff;
  4936. buffer[index + 3] = (size >> 24) & 0xff;
  4937. // Update index
  4938. index = index + 4 + size - 1;
  4939. // Write zero
  4940. buffer[index++] = 0x00;
  4941. return index;
  4942. }
  4943. function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, isArray) {
  4944. // Write the type
  4945. buffer[index++] = BSON_DATA_OBJECT;
  4946. // Number of written bytes
  4947. var numberOfWrittenBytes = !isArray
  4948. ? buffer.write(key, index, undefined, 'utf8')
  4949. : buffer.write(key, index, undefined, 'ascii');
  4950. // Encode the name
  4951. index = index + numberOfWrittenBytes;
  4952. buffer[index++] = 0;
  4953. var startIndex = index;
  4954. var output = {
  4955. $ref: value.collection || value.namespace,
  4956. $id: value.oid
  4957. };
  4958. if (value.db != null) {
  4959. output.$db = value.db;
  4960. }
  4961. output = Object.assign(output, value.fields);
  4962. var endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions);
  4963. // Calculate object size
  4964. var size = endIndex - startIndex;
  4965. // Write the size
  4966. buffer[startIndex++] = size & 0xff;
  4967. buffer[startIndex++] = (size >> 8) & 0xff;
  4968. buffer[startIndex++] = (size >> 16) & 0xff;
  4969. buffer[startIndex++] = (size >> 24) & 0xff;
  4970. // Set index
  4971. return endIndex;
  4972. }
  4973. function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  4974. if (checkKeys === void 0) { checkKeys = false; }
  4975. if (startingIndex === void 0) { startingIndex = 0; }
  4976. if (depth === void 0) { depth = 0; }
  4977. if (serializeFunctions === void 0) { serializeFunctions = false; }
  4978. if (ignoreUndefined === void 0) { ignoreUndefined = true; }
  4979. if (path === void 0) { path = []; }
  4980. startingIndex = startingIndex || 0;
  4981. path = path || [];
  4982. // Push the object to the path
  4983. path.push(object);
  4984. // Start place to serialize into
  4985. var index = startingIndex + 4;
  4986. // Special case isArray
  4987. if (Array.isArray(object)) {
  4988. // Get object keys
  4989. for (var i = 0; i < object.length; i++) {
  4990. var key = '' + i;
  4991. var value = object[i];
  4992. // Is there an override value
  4993. if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
  4994. value = value.toBSON();
  4995. }
  4996. if (typeof value === 'string') {
  4997. index = serializeString(buffer, key, value, index, true);
  4998. }
  4999. else if (typeof value === 'number') {
  5000. index = serializeNumber(buffer, key, value, index, true);
  5001. }
  5002. else if (typeof value === 'bigint') {
  5003. throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
  5004. }
  5005. else if (typeof value === 'boolean') {
  5006. index = serializeBoolean(buffer, key, value, index, true);
  5007. }
  5008. else if (value instanceof Date || isDate(value)) {
  5009. index = serializeDate(buffer, key, value, index, true);
  5010. }
  5011. else if (value === undefined) {
  5012. index = serializeNull(buffer, key, value, index, true);
  5013. }
  5014. else if (value === null) {
  5015. index = serializeNull(buffer, key, value, index, true);
  5016. }
  5017. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  5018. index = serializeObjectId(buffer, key, value, index, true);
  5019. }
  5020. else if (isUint8Array(value)) {
  5021. index = serializeBuffer(buffer, key, value, index, true);
  5022. }
  5023. else if (value instanceof RegExp || isRegExp(value)) {
  5024. index = serializeRegExp(buffer, key, value, index, true);
  5025. }
  5026. else if (typeof value === 'object' && value['_bsontype'] == null) {
  5027. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path);
  5028. }
  5029. else if (typeof value === 'object' &&
  5030. isBSONType(value) &&
  5031. value._bsontype === 'Decimal128') {
  5032. index = serializeDecimal128(buffer, key, value, index, true);
  5033. }
  5034. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  5035. index = serializeLong(buffer, key, value, index, true);
  5036. }
  5037. else if (value['_bsontype'] === 'Double') {
  5038. index = serializeDouble(buffer, key, value, index, true);
  5039. }
  5040. else if (typeof value === 'function' && serializeFunctions) {
  5041. index = serializeFunction(buffer, key, value, index, checkKeys, depth, true);
  5042. }
  5043. else if (value['_bsontype'] === 'Code') {
  5044. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true);
  5045. }
  5046. else if (value['_bsontype'] === 'Binary') {
  5047. index = serializeBinary(buffer, key, value, index, true);
  5048. }
  5049. else if (value['_bsontype'] === 'Symbol') {
  5050. index = serializeSymbol(buffer, key, value, index, true);
  5051. }
  5052. else if (value['_bsontype'] === 'DBRef') {
  5053. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true);
  5054. }
  5055. else if (value['_bsontype'] === 'BSONRegExp') {
  5056. index = serializeBSONRegExp(buffer, key, value, index, true);
  5057. }
  5058. else if (value['_bsontype'] === 'Int32') {
  5059. index = serializeInt32(buffer, key, value, index, true);
  5060. }
  5061. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  5062. index = serializeMinMax(buffer, key, value, index, true);
  5063. }
  5064. else if (typeof value['_bsontype'] !== 'undefined') {
  5065. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  5066. }
  5067. }
  5068. }
  5069. else if (object instanceof bsonMap || isMap(object)) {
  5070. var iterator = object.entries();
  5071. var done = false;
  5072. while (!done) {
  5073. // Unpack the next entry
  5074. var entry = iterator.next();
  5075. done = !!entry.done;
  5076. // Are we done, then skip and terminate
  5077. if (done)
  5078. continue;
  5079. // Get the entry values
  5080. var key = entry.value[0];
  5081. var value = entry.value[1];
  5082. // Check the type of the value
  5083. var type = typeof value;
  5084. // Check the key and throw error if it's illegal
  5085. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  5086. if (key.match(regexp) != null) {
  5087. // The BSON spec doesn't allow keys with null bytes because keys are
  5088. // null-terminated.
  5089. throw Error('key ' + key + ' must not contain null bytes');
  5090. }
  5091. if (checkKeys) {
  5092. if ('$' === key[0]) {
  5093. throw Error('key ' + key + " must not start with '$'");
  5094. }
  5095. else if (~key.indexOf('.')) {
  5096. throw Error('key ' + key + " must not contain '.'");
  5097. }
  5098. }
  5099. }
  5100. if (type === 'string') {
  5101. index = serializeString(buffer, key, value, index);
  5102. }
  5103. else if (type === 'number') {
  5104. index = serializeNumber(buffer, key, value, index);
  5105. }
  5106. else if (type === 'bigint' || isBigInt64Array(value) || isBigUInt64Array(value)) {
  5107. throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
  5108. }
  5109. else if (type === 'boolean') {
  5110. index = serializeBoolean(buffer, key, value, index);
  5111. }
  5112. else if (value instanceof Date || isDate(value)) {
  5113. index = serializeDate(buffer, key, value, index);
  5114. }
  5115. else if (value === null || (value === undefined && ignoreUndefined === false)) {
  5116. index = serializeNull(buffer, key, value, index);
  5117. }
  5118. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  5119. index = serializeObjectId(buffer, key, value, index);
  5120. }
  5121. else if (isUint8Array(value)) {
  5122. index = serializeBuffer(buffer, key, value, index);
  5123. }
  5124. else if (value instanceof RegExp || isRegExp(value)) {
  5125. index = serializeRegExp(buffer, key, value, index);
  5126. }
  5127. else if (type === 'object' && value['_bsontype'] == null) {
  5128. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  5129. }
  5130. else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  5131. index = serializeDecimal128(buffer, key, value, index);
  5132. }
  5133. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  5134. index = serializeLong(buffer, key, value, index);
  5135. }
  5136. else if (value['_bsontype'] === 'Double') {
  5137. index = serializeDouble(buffer, key, value, index);
  5138. }
  5139. else if (value['_bsontype'] === 'Code') {
  5140. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  5141. }
  5142. else if (typeof value === 'function' && serializeFunctions) {
  5143. index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
  5144. }
  5145. else if (value['_bsontype'] === 'Binary') {
  5146. index = serializeBinary(buffer, key, value, index);
  5147. }
  5148. else if (value['_bsontype'] === 'Symbol') {
  5149. index = serializeSymbol(buffer, key, value, index);
  5150. }
  5151. else if (value['_bsontype'] === 'DBRef') {
  5152. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
  5153. }
  5154. else if (value['_bsontype'] === 'BSONRegExp') {
  5155. index = serializeBSONRegExp(buffer, key, value, index);
  5156. }
  5157. else if (value['_bsontype'] === 'Int32') {
  5158. index = serializeInt32(buffer, key, value, index);
  5159. }
  5160. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  5161. index = serializeMinMax(buffer, key, value, index);
  5162. }
  5163. else if (typeof value['_bsontype'] !== 'undefined') {
  5164. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  5165. }
  5166. }
  5167. }
  5168. else {
  5169. if (typeof (object === null || object === void 0 ? void 0 : object.toBSON) === 'function') {
  5170. // Provided a custom serialization method
  5171. object = object.toBSON();
  5172. if (object != null && typeof object !== 'object') {
  5173. throw new BSONTypeError('toBSON function did not return an object');
  5174. }
  5175. }
  5176. // Iterate over all the keys
  5177. for (var key in object) {
  5178. var value = object[key];
  5179. // Is there an override value
  5180. if (typeof (value === null || value === void 0 ? void 0 : value.toBSON) === 'function') {
  5181. value = value.toBSON();
  5182. }
  5183. // Check the type of the value
  5184. var type = typeof value;
  5185. // Check the key and throw error if it's illegal
  5186. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  5187. if (key.match(regexp) != null) {
  5188. // The BSON spec doesn't allow keys with null bytes because keys are
  5189. // null-terminated.
  5190. throw Error('key ' + key + ' must not contain null bytes');
  5191. }
  5192. if (checkKeys) {
  5193. if ('$' === key[0]) {
  5194. throw Error('key ' + key + " must not start with '$'");
  5195. }
  5196. else if (~key.indexOf('.')) {
  5197. throw Error('key ' + key + " must not contain '.'");
  5198. }
  5199. }
  5200. }
  5201. if (type === 'string') {
  5202. index = serializeString(buffer, key, value, index);
  5203. }
  5204. else if (type === 'number') {
  5205. index = serializeNumber(buffer, key, value, index);
  5206. }
  5207. else if (type === 'bigint') {
  5208. throw new BSONTypeError('Unsupported type BigInt, please use Decimal128');
  5209. }
  5210. else if (type === 'boolean') {
  5211. index = serializeBoolean(buffer, key, value, index);
  5212. }
  5213. else if (value instanceof Date || isDate(value)) {
  5214. index = serializeDate(buffer, key, value, index);
  5215. }
  5216. else if (value === undefined) {
  5217. if (ignoreUndefined === false)
  5218. index = serializeNull(buffer, key, value, index);
  5219. }
  5220. else if (value === null) {
  5221. index = serializeNull(buffer, key, value, index);
  5222. }
  5223. else if (value['_bsontype'] === 'ObjectId' || value['_bsontype'] === 'ObjectID') {
  5224. index = serializeObjectId(buffer, key, value, index);
  5225. }
  5226. else if (isUint8Array(value)) {
  5227. index = serializeBuffer(buffer, key, value, index);
  5228. }
  5229. else if (value instanceof RegExp || isRegExp(value)) {
  5230. index = serializeRegExp(buffer, key, value, index);
  5231. }
  5232. else if (type === 'object' && value['_bsontype'] == null) {
  5233. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path);
  5234. }
  5235. else if (type === 'object' && value['_bsontype'] === 'Decimal128') {
  5236. index = serializeDecimal128(buffer, key, value, index);
  5237. }
  5238. else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') {
  5239. index = serializeLong(buffer, key, value, index);
  5240. }
  5241. else if (value['_bsontype'] === 'Double') {
  5242. index = serializeDouble(buffer, key, value, index);
  5243. }
  5244. else if (value['_bsontype'] === 'Code') {
  5245. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
  5246. }
  5247. else if (typeof value === 'function' && serializeFunctions) {
  5248. index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
  5249. }
  5250. else if (value['_bsontype'] === 'Binary') {
  5251. index = serializeBinary(buffer, key, value, index);
  5252. }
  5253. else if (value['_bsontype'] === 'Symbol') {
  5254. index = serializeSymbol(buffer, key, value, index);
  5255. }
  5256. else if (value['_bsontype'] === 'DBRef') {
  5257. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions);
  5258. }
  5259. else if (value['_bsontype'] === 'BSONRegExp') {
  5260. index = serializeBSONRegExp(buffer, key, value, index);
  5261. }
  5262. else if (value['_bsontype'] === 'Int32') {
  5263. index = serializeInt32(buffer, key, value, index);
  5264. }
  5265. else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') {
  5266. index = serializeMinMax(buffer, key, value, index);
  5267. }
  5268. else if (typeof value['_bsontype'] !== 'undefined') {
  5269. throw new BSONTypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']);
  5270. }
  5271. }
  5272. }
  5273. // Remove the path
  5274. path.pop();
  5275. // Final padding byte for object
  5276. buffer[index++] = 0x00;
  5277. // Final size
  5278. var size = index - startingIndex;
  5279. // Write the size of the object
  5280. buffer[startingIndex++] = size & 0xff;
  5281. buffer[startingIndex++] = (size >> 8) & 0xff;
  5282. buffer[startingIndex++] = (size >> 16) & 0xff;
  5283. buffer[startingIndex++] = (size >> 24) & 0xff;
  5284. return index;
  5285. }
  5286. /** @internal */
  5287. // Default Max Size
  5288. var MAXSIZE = 1024 * 1024 * 17;
  5289. // Current Internal Temporary Serialization Buffer
  5290. var buffer = Buffer.alloc(MAXSIZE);
  5291. /**
  5292. * Sets the size of the internal serialization buffer.
  5293. *
  5294. * @param size - The desired size for the internal serialization buffer
  5295. * @public
  5296. */
  5297. function setInternalBufferSize(size) {
  5298. // Resize the internal serialization buffer if needed
  5299. if (buffer.length < size) {
  5300. buffer = Buffer.alloc(size);
  5301. }
  5302. }
  5303. /**
  5304. * Serialize a Javascript object.
  5305. *
  5306. * @param object - the Javascript object to serialize.
  5307. * @returns Buffer object containing the serialized object.
  5308. * @public
  5309. */
  5310. function serialize(object, options) {
  5311. if (options === void 0) { options = {}; }
  5312. // Unpack the options
  5313. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  5314. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  5315. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  5316. var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
  5317. // Resize the internal serialization buffer if needed
  5318. if (buffer.length < minInternalBufferSize) {
  5319. buffer = Buffer.alloc(minInternalBufferSize);
  5320. }
  5321. // Attempt to serialize
  5322. var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []);
  5323. // Create the final buffer
  5324. var finishedBuffer = Buffer.alloc(serializationIndex);
  5325. // Copy into the finished buffer
  5326. buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length);
  5327. // Return the buffer
  5328. return finishedBuffer;
  5329. }
  5330. /**
  5331. * Serialize a Javascript object using a predefined Buffer and index into the buffer,
  5332. * useful when pre-allocating the space for serialization.
  5333. *
  5334. * @param object - the Javascript object to serialize.
  5335. * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object.
  5336. * @returns the index pointing to the last written byte in the buffer.
  5337. * @public
  5338. */
  5339. function serializeWithBufferAndIndex(object, finalBuffer, options) {
  5340. if (options === void 0) { options = {}; }
  5341. // Unpack the options
  5342. var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  5343. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  5344. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  5345. var startIndex = typeof options.index === 'number' ? options.index : 0;
  5346. // Attempt to serialize
  5347. var serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined);
  5348. buffer.copy(finalBuffer, startIndex, 0, serializationIndex);
  5349. // Return the index
  5350. return startIndex + serializationIndex - 1;
  5351. }
  5352. /**
  5353. * Deserialize data as BSON.
  5354. *
  5355. * @param buffer - the buffer containing the serialized set of BSON documents.
  5356. * @returns returns the deserialized Javascript Object.
  5357. * @public
  5358. */
  5359. function deserialize(buffer, options) {
  5360. if (options === void 0) { options = {}; }
  5361. return deserialize$1(buffer instanceof Buffer ? buffer : ensureBuffer(buffer), options);
  5362. }
  5363. /**
  5364. * Calculate the bson size for a passed in Javascript object.
  5365. *
  5366. * @param object - the Javascript object to calculate the BSON byte size for
  5367. * @returns size of BSON object in bytes
  5368. * @public
  5369. */
  5370. function calculateObjectSize(object, options) {
  5371. if (options === void 0) { options = {}; }
  5372. options = options || {};
  5373. var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  5374. var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  5375. return calculateObjectSize$1(object, serializeFunctions, ignoreUndefined);
  5376. }
  5377. /**
  5378. * Deserialize stream data as BSON documents.
  5379. *
  5380. * @param data - the buffer containing the serialized set of BSON documents.
  5381. * @param startIndex - the start index in the data Buffer where the deserialization is to start.
  5382. * @param numberOfDocuments - number of documents to deserialize.
  5383. * @param documents - an array where to store the deserialized documents.
  5384. * @param docStartIndex - the index in the documents array from where to start inserting documents.
  5385. * @param options - additional options used for the deserialization.
  5386. * @returns next index in the buffer after deserialization **x** numbers of documents.
  5387. * @public
  5388. */
  5389. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  5390. var internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
  5391. var bufferData = ensureBuffer(data);
  5392. var index = startIndex;
  5393. // Loop over all documents
  5394. for (var i = 0; i < numberOfDocuments; i++) {
  5395. // Find size of the document
  5396. var size = bufferData[index] |
  5397. (bufferData[index + 1] << 8) |
  5398. (bufferData[index + 2] << 16) |
  5399. (bufferData[index + 3] << 24);
  5400. // Update options with index
  5401. internalOptions.index = index;
  5402. // Parse the document at this point
  5403. documents[docStartIndex + i] = deserialize$1(bufferData, internalOptions);
  5404. // Adjust index by the document size
  5405. index = index + size;
  5406. }
  5407. // Return object containing end index of parsing and list of documents
  5408. return index;
  5409. }
  5410. /**
  5411. * BSON default export
  5412. * @deprecated Please use named exports
  5413. * @privateRemarks
  5414. * We want to someday deprecate the default export,
  5415. * so none of the new TS types are being exported on the default
  5416. * @public
  5417. */
  5418. var BSON = {
  5419. Binary: Binary,
  5420. Code: Code,
  5421. DBRef: DBRef,
  5422. Decimal128: Decimal128,
  5423. Double: Double,
  5424. Int32: Int32,
  5425. Long: Long,
  5426. UUID: UUID,
  5427. Map: bsonMap,
  5428. MaxKey: MaxKey,
  5429. MinKey: MinKey,
  5430. ObjectId: ObjectId,
  5431. ObjectID: ObjectId,
  5432. BSONRegExp: BSONRegExp,
  5433. BSONSymbol: BSONSymbol,
  5434. Timestamp: Timestamp,
  5435. EJSON: EJSON,
  5436. setInternalBufferSize: setInternalBufferSize,
  5437. serialize: serialize,
  5438. serializeWithBufferAndIndex: serializeWithBufferAndIndex,
  5439. deserialize: deserialize,
  5440. calculateObjectSize: calculateObjectSize,
  5441. deserializeStream: deserializeStream,
  5442. BSONError: BSONError,
  5443. BSONTypeError: BSONTypeError
  5444. };
  5445. export default BSON;
  5446. export { BSONError, BSONRegExp, BSONSymbol, BSONTypeError, BSON_BINARY_SUBTYPE_BYTE_ARRAY, BSON_BINARY_SUBTYPE_COLUMN, BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_ENCRYPTED, BSON_BINARY_SUBTYPE_FUNCTION, BSON_BINARY_SUBTYPE_MD5, BSON_BINARY_SUBTYPE_USER_DEFINED, BSON_BINARY_SUBTYPE_UUID, BSON_BINARY_SUBTYPE_UUID_NEW, BSON_DATA_ARRAY, BSON_DATA_BINARY, BSON_DATA_BOOLEAN, BSON_DATA_CODE, BSON_DATA_CODE_W_SCOPE, BSON_DATA_DATE, BSON_DATA_DBPOINTER, BSON_DATA_DECIMAL128, BSON_DATA_INT, BSON_DATA_LONG, BSON_DATA_MAX_KEY, BSON_DATA_MIN_KEY, BSON_DATA_NULL, BSON_DATA_NUMBER, BSON_DATA_OBJECT, BSON_DATA_OID, BSON_DATA_REGEXP, BSON_DATA_STRING, BSON_DATA_SYMBOL, BSON_DATA_TIMESTAMP, BSON_DATA_UNDEFINED, BSON_INT32_MAX, BSON_INT32_MIN, BSON_INT64_MAX, BSON_INT64_MIN, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, LongWithoutOverridesClass, bsonMap as Map, MaxKey, MinKey, ObjectId as ObjectID, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize };
  5447. //# sourceMappingURL=bson.esm.js.map